"""B4 draft persistence, concurrency, scope, confirmation and migration regression.""" from __future__ import annotations import asyncio import json import sqlite3 from calliope.agent.deliverables import complete_task from calliope.agent.harness.runner import runner from calliope.config import settings from calliope.db import get_db, migrate_db TEXT = ( "第一场,清晨海岸,女孩将纸船推向海面,等待父亲归来。" "第二场,纸船带回树叶,女孩沿着灯塔的光继续前行。" ) def setup(client, stage="script"): project = client.post("/api/projects", json={"title": "B4 isolated"}).json() session = client.post( "/api/agent/sessions", json={ "project_id": project["id"], "agent_key": stage, }, ).json() runner._persist_message(session["id"], role="assistant", content=TEXT) complete_task(session["id"], TEXT) draft = client.get("/api/results/deliverables", params={"session_id": session["id"]}).json()[0] return project["id"], session["id"], draft def store(client, pid, draft, stage="script"): return client.post( "/api/results/store", json={ "project_id": pid, "stage_key": stage, "deliverable_id": draft["id"], "revision": draft["revision"], }, ) def test_draft_save_refresh_conflict_and_scope(client): pid, sid, draft = setup(client) body = {"revision": 1, "content": TEXT + "新结尾。", "project_id": pid, "stage_key": "script"} saved = client.patch(f"/api/results/deliverables/{draft['id']}", json=body) assert saved.status_code == 200 assert saved.json()["revision"] == 2 versions = client.get(f"/api/results/deliverables/{draft['id']}/versions").json() assert len(versions) == 1 and versions[0]["content"] == TEXT assert ( client.get("/api/results/deliverables", params={"session_id": sid}).json()[0] == saved.json() ) assert client.patch(f"/api/results/deliverables/{draft['id']}", json=body).status_code == 409 assert store(client, pid, draft).status_code == 409 other = client.post("/api/projects", json={"title": "Other"}).json()["id"] assert store(client, other, saved.json()).status_code == 409 body.update(revision=2, project_id=other) assert client.patch(f"/api/results/deliverables/{draft['id']}", json=body).status_code == 409 assert client.get(f"/api/agent/sessions/{sid}").json()["task_status"] == "awaiting_confirm" def test_store_idempotency_confirm_restore_and_preserve_snapshot(client): pid, sid, draft = setup(client) url = f"/api/workbench/projects/{pid}/stages/script" old = {"text": TEXT + "已确认的旧版。"} assert client.patch(url, json={"content": old}).status_code == 200 snapshot = client.post(url + "/confirm", json={}).json()["stage"]["confirmed_content"] res = store(client, pid, draft) assert res.status_code == 200, res.text stage = res.json()["stage"] assert stage["status"] == "awaiting_confirm" assert stage["confirmed_content"] == snapshot assert stage["content"]["text"] == TEXT assert len(stage["incoming_results"]) == 1 assert store(client, pid, draft).json()["already_attached"] is True assert len(store(client, pid, draft).json()["stage"]["incoming_results"]) == 1 assert client.get(f"/api/agent/sessions/{sid}").json()["task_status"] == "returned" assert client.post(url + "/restore", json={}).json()["stage"]["content"] == snapshot # A newer source revision is a new explicit handoff, never an automatic update. draft = client.patch( f"/api/results/deliverables/{draft['id']}", json={ "revision": 1, "content": TEXT + "新版本。", "project_id": pid, "stage_key": "script", }, ).json() assert store(client, pid, draft).status_code == 200 confirmed = client.post(url + "/confirm", json={}).json()["stage"]["confirmed_content"] assert confirmed["text"].endswith("新版本。") assert len(confirmed["incoming_results"]) == 1 stages = client.get(f"/api/workbench/projects/{pid}").json()["stages"] assert all(s["status"] == "todo" for s in stages if s["stage_key"] != "script") def test_capture_idempotency_and_no_error_artifact(client): _, sid, _ = setup(client) complete_task(sid, TEXT) assert len(client.get("/api/results/deliverables", params={"session_id": sid}).json()) == 1 runner._persist_message(sid, role="assistant", content="error", status="error") complete_task(sid, "error") assert len(client.get("/api/results/deliverables", params={"session_id": sid}).json()) == 1 def test_sandbox_assignment_and_running_stage(client): pid, _, draft = setup(client) conn = get_db(settings.db_path) conn.execute("UPDATE project_stages SET status='running' WHERE project_id=?", (pid,)) conn.commit() conn.close() # Stage rows are created lazily; ensure they exist first. client.get(f"/api/workbench/projects/{pid}") conn = get_db(settings.db_path) conn.execute("UPDATE project_stages SET status='running' WHERE project_id=?", (pid,)) conn.commit() conn.close() assert store(client, pid, draft).status_code == 409 assert client.get("/api/results/deliverables", params={"session_id": 99999}).json() == [] def test_media_paths_scope_and_empty_errors(client): pid, _, _ = setup(client) other = client.post("/api/projects", json={"title": "other"}).json()["id"] path = settings.assets_dir / "b4.txt" path.parent.mkdir(parents=True, exist_ok=True) path.write_text("isolated") conn = get_db(settings.db_path) job = conn.execute( "INSERT INTO jobs(project_id,kind,status,output_paths_json) VALUES (?,'image','done',?)", (pid, json.dumps([str(path)])), ).lastrowid conn.commit() conn.close() body = {"job_id": job, "project_id": other, "stage_key": "assets"} assert client.post("/api/results/store", json=body).status_code == 409 body["project_id"] = pid result = client.post("/api/results/store", json=body) assert result.status_code == 200, result.text assert result.json()["stage"]["incoming_results"][0]["paths"] == [str(path)] assert client.post("/api/results/store", json=body).json()["already_attached"] assert ( client.post( "/api/results/store", json={"project_id": pid, "stage_key": "bogus", "job_id": job} ).status_code == 422 ) assert ( client.post( "/api/results/store", json={"project_id": pid, "stage_key": "assets"} ).status_code == 422 ) path.unlink() assert client.post("/api/results/store", json=body).status_code == 404 def test_migration_twice_and_sqlite_backup_rollback(client, tmp_path): pid, sid, draft = setup(client) conn = sqlite3.connect(settings.db_path) backup = sqlite3.connect(tmp_path / "before-b4.db") conn.backup(backup) backup.close() conn.close() asyncio.run(migrate_db(settings.db_path)) asyncio.run(migrate_db(settings.db_path)) assert client.get("/api/results/deliverables").json()[0]["content"] == draft["content"] conn = get_db(settings.db_path) # Old-code SQL continues reading the original schema and rows. assert ( conn.execute( "SELECT title,status,project_id FROM agent_sessions WHERE id=?", (sid,) ).fetchone()["project_id"] == pid ) assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok" conn.close()