Editable analysis prompts on the admin page
CI / test (push) Successful in 44s
CI / build (push) Successful in 4m13s
CI / deploy (push) Skipped

The system prompts of the free summary and the paid detailed analysis can be
edited per language under /admin/promptok. Every save is a new row in
prompt_revisions (NULL = built-in text); new analyses record the revision in
prompt_version (v2-r<id>) and the worker uses exactly that text. Existing
analyses stay; the cross-user cache only copies results of the same revision.

The prompt code moves to the shared analysis-prompt crate so the backend can
show the built-in text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-17 14:25:08 +00:00
co-authored by Claude Opus 5.5
parent 0ba80abb47
commit 86d5dc5503
25 changed files with 1051 additions and 347 deletions
+11 -3
View File
@@ -145,8 +145,14 @@ async fn queue(
Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None),
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)),
};
let prompt_version = &state.config.prompt_version;
let cache_key = sha256_hex(&format!("{kind}|{hash}|{prompt_version}|{model}|{language}"));
// The cache key leaves out the admin-edited prompt revision, so a chart keeps
// its analysis when the prompt changes; copying from another chart needs the same revision.
let base_version = &state.config.prompt_version;
let cache_key = sha256_hex(&format!("{kind}|{hash}|{base_version}|{model}|{language}"));
let prompt_version = &match super::prompts::current_revision(&state.db, kind, language).await? {
Some(id) => format!("{base_version}-r{id}"),
None => base_version.clone(),
};
// Already requested for this chart/synastry: return it.
let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
@@ -172,9 +178,11 @@ async fn queue(
// The same chart elsewhere (another user, same birth data) was already analysed: copy it.
let cached: Option<(Value, Option<i32>, Option<i32>)> = sqlx::query_as(
"SELECT content, input_tokens, output_tokens FROM analyses WHERE cache_key = $1 AND status = 'done' LIMIT 1",
"SELECT content, input_tokens, output_tokens FROM analyses \
WHERE cache_key = $1 AND prompt_version = $2 AND status = 'done' LIMIT 1",
)
.bind(&cache_key)
.bind(prompt_version)
.fetch_optional(&state.db)
.await?;
if let Some((content, input_tokens, output_tokens)) = cached {
+3
View File
@@ -11,6 +11,7 @@ mod analyses;
mod auth;
mod charts;
mod payments;
mod prompts;
mod shares;
mod synastries;
@@ -89,6 +90,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/admin/users", get(admin::list_users))
.route("/v1/admin/users/{id}", patch(admin::update_user))
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
.route("/v1/admin/prompts", get(prompts::list))
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
.layer(cors(&state.config.cors_allowed_origins))
.layer(
TraceLayer::new_for_http()
+138
View File
@@ -0,0 +1,138 @@
//! Editable system prompts of the analyses (admin only).
//!
//! Every save adds a row to `prompt_revisions`; the newest row of a
//! (kind, language) is in force, `system` NULL meaning the built-in text.
//! New analyses record the revision in `prompt_version`, so analyses that
//! are already written or queued keep the text they were started with.
use analysis_prompt::{Kind, default_system, user_template};
use axum::Json;
use axum::extract::{Path, State};
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use super::{Body, St};
use crate::AppState;
use crate::auth::AdminUser;
use crate::error::{ApiError, ApiResult};
use crate::views::rfc3339;
/// The kinds whose prompt the admin page edits.
const EDITABLE: [Kind; 2] = [Kind::Summary, Kind::Natal];
const MAX_CHARS: usize = 50_000;
const HISTORY: i64 = 20;
/// The revision id of an admin-edited prompt in force, `None` for the built-in one.
pub async fn current_revision(db: &PgPool, kind: &str, language: &str) -> Result<Option<i64>, sqlx::Error> {
let row: Option<(i64, bool)> = sqlx::query_as(
"SELECT id, system IS NOT NULL FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1",
)
.bind(kind)
.bind(language)
.fetch_optional(db)
.await?;
Ok(row.filter(|(_, custom)| *custom).map(|(id, _)| id))
}
type RevisionRow = (i64, Option<String>, OffsetDateTime, Option<String>);
async fn entry(db: &PgPool, kind: Kind, language: &str) -> Result<Value, sqlx::Error> {
let rows: Vec<RevisionRow> = sqlx::query_as(
"SELECT r.id, r.system, r.created_at, u.email FROM prompt_revisions r \
LEFT JOIN users u ON u.id = r.created_by \
WHERE r.kind = $1 AND r.language = $2 ORDER BY r.id DESC LIMIT $3",
)
.bind(kind.as_str())
.bind(language)
.bind(HISTORY)
.fetch_all(db)
.await?;
let default = default_system(kind, language);
let current = rows.first();
let history: Vec<Value> = rows
.iter()
.map(|(id, system, at, by)| {
json!({"id": id, "custom": system.is_some(), "system": system, "created_at": rfc3339(*at), "created_by": by})
})
.collect();
Ok(json!({
"kind": kind.as_str(),
"language": language,
"system": current.and_then(|r| r.1.clone()).unwrap_or_else(|| default.clone()),
"custom": current.is_some_and(|r| r.1.is_some()),
"updated_at": current.map(|r| rfc3339(r.2)),
"updated_by": current.and_then(|r| r.3.clone()),
"default": default,
"user_template": user_template(kind),
"history": history,
}))
}
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
let mut prompts = Vec::new();
for kind in EDITABLE {
for language in &state.config.supported_locales {
prompts.push(entry(&state.db, kind, language).await?);
}
}
Ok(Json(json!({ "prompts": prompts })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SavePrompt {
/// The new system prompt; `null` restores the built-in one.
system: Option<String>,
}
fn parse_target(state: &AppState, kind: &str, language: &str) -> Result<Kind, ApiError> {
let kind = Kind::parse(kind).filter(|k| EDITABLE.contains(k)).ok_or(ApiError::NotFound("prompt"))?;
if !state.config.supported_locales.iter().any(|l| l == language) {
return Err(ApiError::NotFound("prompt"));
}
Ok(kind)
}
pub async fn save(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path((kind, language)), _): WithRejection<Path<(String, String)>, ApiError>,
WithRejection(Json(req), _): Body<SavePrompt>,
) -> ApiResult<Json<Value>> {
let kind = parse_target(&state, &kind, &language)?;
let default = default_system(kind, &language);
// The built-in text is stored as NULL, so later code changes reach it.
let system = match req.system.map(|s| s.trim().replace("\r\n", "\n")) {
Some(s) if s.is_empty() => return Err(ApiError::BadRequest("the prompt must not be empty".into())),
Some(s) if s.chars().count() > MAX_CHARS => {
return Err(ApiError::BadRequest(format!("the prompt is longer than {MAX_CHARS} characters")));
}
Some(s) if s == default.trim() => None,
other => other,
};
let current: Option<(Option<String>,)> = sqlx::query_as(
"SELECT system FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1",
)
.bind(kind.as_str())
.bind(&language)
.fetch_optional(&state.db)
.await?;
let unchanged = match &current {
Some((text,)) => *text == system,
None => system.is_none(),
};
if !unchanged {
sqlx::query("INSERT INTO prompt_revisions (kind, language, system, created_by) VALUES ($1, $2, $3, $4)")
.bind(kind.as_str())
.bind(&language)
.bind(&system)
.bind(admin.id())
.execute(&state.db)
.await?;
tracing::info!(admin = %admin.id(), kind = kind.as_str(), %language, custom = system.is_some(), "prompt changed");
}
Ok(Json(entry(&state.db, kind, &language).await?))
}
+67
View File
@@ -827,3 +827,70 @@ async fn persons_use_package_slots(pool: PgPool) {
let r = app.call("PATCH", &format!("/v1/charts/{pid}"), Some(&admin), Some(corrected)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn admins_edit_analysis_prompts(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let admin = app.register("admin@example.com", "Admin").await;
let anna = app.register("anna@example.com", "Anna").await;
assert_eq!(app.get("/v1/admin/prompts", Some(&anna)).await.status, StatusCode::FORBIDDEN);
let r = app.get("/v1/admin/prompts", Some(&admin)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let prompts = r.body["prompts"].as_array().unwrap();
let keys: Vec<String> =
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en"]);
let natal = &prompts[2];
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
let default = natal["default"].as_str().unwrap().to_string();
let put = |body: Value, uri: &'static str| app.call("PUT", uri, Some(&admin), Some(body));
assert_eq!(put(json!({"system": " "}), "/v1/admin/prompts/natal/hu").await.status, StatusCode::BAD_REQUEST);
assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/synastry/hu").await.status, StatusCode::NOT_FOUND);
assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/natal/de").await.status, StatusCode::NOT_FOUND);
// saving the built-in text keeps the built-in prompt
let r = put(json!({"system": default}), "/v1/admin/prompts/natal/hu").await;
assert_eq!(
(r.status, &r.body["custom"], r.body["history"].as_array().unwrap().len()),
(StatusCode::OK, &json!(false), 0)
);
// an analysis written with the built-in prompt
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let uri = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
grant_units(&app, &anna, "natal", 1).await;
let r = app.call("POST", &uri, Some(&anna), None).await;
assert_eq!((r.status, r.body["prompt_version"].as_str()), (StatusCode::ACCEPTED, Some("v1")));
let first = r.body["id"].as_str().unwrap().to_string();
sqlx::query("UPDATE analyses SET status = 'done', content = '{}', completed_at = now() WHERE id = $1::uuid")
.bind(&first)
.execute(&pool)
.await
.unwrap();
let r = put(json!({"system": "Saját szabályok.\r\n"}), "/v1/admin/prompts/natal/hu").await;
assert_eq!(
(&r.body["custom"], r.body["system"].as_str(), r.body["updated_by"].as_str()),
(&json!(true), Some("Saját szabályok."), Some("admin@example.com"))
);
let revision = r.body["history"][0]["id"].as_i64().unwrap();
let r = put(json!({"system": "Saját szabályok."}), "/v1/admin/prompts/natal/hu").await;
assert_eq!(r.body["history"].as_array().unwrap().len(), 1); // unchanged: no new revision
// the chart keeps its analysis; the same birth data elsewhere is written anew with the edited prompt
let r = app.call("POST", &uri, Some(&anna), None).await;
assert_eq!((r.status, r.body["id"].as_str()), (StatusCode::OK, Some(first.as_str())));
let bela = app.register("bela@example.com", "Béla").await;
let same = app.chart(&bela, "Saját", true, "1990-03-15").await;
grant_units(&app, &bela, "natal", 1).await;
let r = app.call("POST", &format!("/v1/charts/{}/analyses", same["id"].as_str().unwrap()), Some(&bela), None).await;
let expected = format!("v1-r{revision}");
assert_eq!((r.status, r.body["prompt_version"].as_str()), (StatusCode::ACCEPTED, Some(expected.as_str())));
// back to the built-in prompt
let r = put(json!({"system": null}), "/v1/admin/prompts/natal/hu").await;
assert_eq!((&r.body["custom"], r.body["system"].as_str()), (&json!(false), Some(default.as_str())));
assert_eq!(r.body["history"].as_array().unwrap().len(), 2);
}