From 1ec5348f424f0d2767938963de52031c07aa9c98 Mon Sep 17 00:00:00 2001 From: Justo Stoll Date: Tue, 25 Aug 2026 08:44:58 +0200 Subject: [PATCH] Gate generate-story/script append mode; add beat CRUD tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The destructive guard only gated replace=true — an unconfirmed generate_story(replace=false) on a non-empty project silently APPENDED a duplicate 25-beat set (25 -> 50, observed live 2026-08-25), and the guard's own message recommended exactly that escape. Both modes are now gated on a non-empty project with mode-specific messages that point at the granular tools; 'append' joins the confirmation cues. And the granular tools now exist for beats: add_beat (insert-with-shift, or append when order_index omitted), update_beat (project-scoped id check), delete_beat (destructive-flagged; later beats renumber to close the gap) — before this, bulk regeneration was the only way to change a beat, which is what boxed the story sub-agent into the append in the first place. The story role's allowlist gains all three. (cherry picked from commit 14ca52f5c02d1e8dd52e0f58e5fd0b8593816c9b) --- .../src/calliope/agent/harness/__init__.py | 31 ++- .../calliope/agent/harness/orchestrator.py | 10 +- .../calliope/agent/harness/plugins/story.py | 176 ++++++++++++++++++ .../src/calliope/agent/harness/policy.py | 2 +- .../tests/test_agent_event_log.py | 12 +- calliope-backend/tests/test_agent_security.py | 98 ++++++++++ 6 files changed, 315 insertions(+), 14 deletions(-) diff --git a/calliope-backend/src/calliope/agent/harness/__init__.py b/calliope-backend/src/calliope/agent/harness/__init__.py index c9559b23..7ceab027 100644 --- a/calliope-backend/src/calliope/agent/harness/__init__.py +++ b/calliope-backend/src/calliope/agent/harness/__init__.py @@ -85,10 +85,11 @@ def _destructive_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreEx if not has_replace_param: return allow() replace = bool(args.get("replace", True)) - if not replace: - return allow() - # Destructive path: only allow when the project is effectively empty, or - # the user explicitly confirmed. + # BOTH modes are gated on a non-empty project: replace=true deletes the + # existing content, and replace=false APPENDS a second full set alongside + # it (observed live 2026-08-25: an unconfirmed replace=false generate_story + # silently doubled a project's beats, 25 -> 50). Only allow when the + # project is effectively empty, or the user explicitly confirmed. from calliope.agent.harness.registry import _db if ctx.project_id is None: @@ -117,11 +118,25 @@ def _destructive_guard(ctx: ToolContext, t: ToolDefinition, args: dict) -> PreEx return allow() if _user_confirmed_replacement(ctx): return allow() - return deny( + counts = ( f"Project #{ctx.project_id} already has content ({scenes} scenes, {beats} beats, " - f"{chars} characters, {locs} locations, {items} items). Ask the user to confirm before replacing; " - "once they confirm (e.g. 'yes, replace'), call this tool again. " - "To append instead, pass replace=false." + f"{chars} characters, {locs} locations, {items} items)." + ) + if replace: + return deny( + counts + " replace=true DELETES all of it first. Ask the user to " + "confirm before replacing; once they confirm (e.g. 'yes, replace'), " + "call this tool again. For targeted changes use the granular tools " + "instead (add/update/delete for beats, characters, locations, " + "items, scenes)." + ) + return deny( + counts + " replace=false would APPEND a second full set alongside the " + "existing content (e.g. doubling the beat list) — usually wrong. Ask " + "the user to confirm before appending; once they confirm (e.g. 'yes, " + "append'), call this tool again. For targeted changes use the granular " + "tools instead (add/update/delete for beats, characters, locations, " + "items, scenes)." ) diff --git a/calliope-backend/src/calliope/agent/harness/orchestrator.py b/calliope-backend/src/calliope/agent/harness/orchestrator.py index 4c9fdf44..16812cbc 100644 --- a/calliope-backend/src/calliope/agent/harness/orchestrator.py +++ b/calliope-backend/src/calliope/agent/harness/orchestrator.py @@ -32,7 +32,15 @@ MAX_HISTORY_USER_TURNS = 40 # Tool subsets per sub-agent role. Scoped tighter than the full registry so a # sub-agent cannot wander into another role's tools. ROLE_TOOLS: dict[str, list[str]] = { - "story": ["get_workspace", "get_story", "generate_story", "list_workflows"], + "story": [ + "get_workspace", + "get_story", + "generate_story", + "add_beat", + "update_beat", + "delete_beat", + "list_workflows", + ], "script": [ "get_workspace", "list_scenes", diff --git a/calliope-backend/src/calliope/agent/harness/plugins/story.py b/calliope-backend/src/calliope/agent/harness/plugins/story.py index b696812d..dafba6ee 100644 --- a/calliope-backend/src/calliope/agent/harness/plugins/story.py +++ b/calliope-backend/src/calliope/agent/harness/plugins/story.py @@ -52,6 +52,182 @@ def register(registry: ToolRegistry) -> None: ) ) _register_asset_crud(registry) + _register_beat_crud(registry) + + +def _register_beat_crud(registry: ToolRegistry) -> None: + """Register add/update/delete tools for story beats. + + Before these existed, beats could ONLY be changed via generate_story — + a bulk regenerate — so "align the beats to this story" left an agent no + non-destructive path (observed live 2026-08-25: a story sub-agent, boxed + in, appended a duplicate 25-beat set and then hit the destructive guard). + """ + registry.register( + ToolDefinition( + name="add_beat", + description=( + "Insert one story beat. title is required. order_index is the " + "1-based timeline position — later beats shift down to make " + "room; omit it to append at the end." + ), + parameters={ + "type": "object", + "properties": { + "title": {"type": "string"}, + "description": {"type": "string"}, + "order_index": { + "type": "integer", + "description": "1-based position; omit to append at the end", + }, + }, + "required": ["title"], + }, + executor=t_add_beat, + category="story", + ) + ) + registry.register( + ToolDefinition( + name="update_beat", + description=( + "Update one existing story beat. beat_id must come from " + "get_story/get_workspace — never guess it. Pass only the fields " + "to change (title, description, order_index)." + ), + parameters={ + "type": "object", + "properties": { + "beat_id": {"type": "integer"}, + "title": {"type": "string"}, + "description": {"type": "string"}, + "order_index": {"type": "integer"}, + }, + "required": ["beat_id"], + }, + executor=t_update_beat, + category="story", + ) + ) + registry.register( + ToolDefinition( + name="delete_beat", + description=( + "Delete one story beat permanently; later beats renumber to " + "close the gap. beat_id must come from get_story/get_workspace. " + "Prefer update_beat for content changes." + ), + parameters={ + "type": "object", + "properties": {"beat_id": {"type": "integer"}}, + "required": ["beat_id"], + }, + executor=t_delete_beat, + category="story", + destructive=True, + ) + ) + + +async def t_add_beat(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + title = args.get("title") + if not isinstance(title, str) or not title.strip(): + return {"ok": False, "error": "title is required (non-empty string)"} + conn = _db() + try: + max_idx = conn.execute( + "SELECT COALESCE(MAX(order_index), 0) AS m FROM story_beats WHERE project_id = ?", + (ctx.project_id,), + ).fetchone()["m"] + idx = args.get("order_index") + idx = int(idx) if idx is not None else max_idx + 1 + idx = max(1, min(idx, max_idx + 1)) + conn.execute( + "UPDATE story_beats SET order_index = order_index + 1 " + "WHERE project_id = ? AND order_index >= ?", + (ctx.project_id, idx), + ) + cur = conn.execute( + "INSERT INTO story_beats (project_id, order_index, title, description) " + "VALUES (?, ?, ?, ?)", + (ctx.project_id, idx, title.strip(), args.get("description")), + ) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + beat = conn.execute( + "SELECT * FROM story_beats WHERE id = ?", (cur.lastrowid,) + ).fetchone() + return {"ok": True, "beat": row_to_dict(beat)} + finally: + conn.close() + + +async def t_update_beat(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + bid = int(args["beat_id"]) + data = { + k: v + for k, v in args.items() + if k in ("title", "description", "order_index") and v is not None + } + if "title" in data and not str(data["title"]).strip(): + data.pop("title") + conn = _db() + try: + existing = conn.execute( + "SELECT id FROM story_beats WHERE id = ? AND project_id = ?", + (bid, ctx.project_id), + ).fetchone() + if not existing: + return {"ok": False, "error": f"Beat {bid} not found in this project"} + if data: + fields = ", ".join(f"{k} = :{k}" for k in data) + conn.execute( + f"UPDATE story_beats SET {fields} WHERE id = :id AND project_id = :project_id", + {**data, "id": bid, "project_id": ctx.project_id}, + ) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + beat = conn.execute( + "SELECT * FROM story_beats WHERE id = ?", (bid,) + ).fetchone() + return {"ok": True, "beat": row_to_dict(beat)} + finally: + conn.close() + + +async def t_delete_beat(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]: + bid = int(args["beat_id"]) + conn = _db() + try: + row = conn.execute( + "SELECT order_index FROM story_beats WHERE id = ? AND project_id = ?", + (bid, ctx.project_id), + ).fetchone() + if not row: + return {"ok": False, "error": f"Beat {bid} not found in this project"} + conn.execute( + "DELETE FROM story_beats WHERE id = ? AND project_id = ?", + (bid, ctx.project_id), + ) + conn.execute( + "UPDATE story_beats SET order_index = order_index - 1 " + "WHERE project_id = ? AND order_index > ?", + (ctx.project_id, row["order_index"]), + ) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + return {"ok": True, "deleted_beat_id": bid} + finally: + conn.close() def _register_asset_crud(registry: ToolRegistry) -> None: diff --git a/calliope-backend/src/calliope/agent/harness/policy.py b/calliope-backend/src/calliope/agent/harness/policy.py index f4c99223..a737aaf3 100644 --- a/calliope-backend/src/calliope/agent/harness/policy.py +++ b/calliope-backend/src/calliope/agent/harness/policy.py @@ -14,7 +14,7 @@ from calliope.agent.harness.registry import ToolContext # (or "replace it" / "start over") for the destructive guard. _CONFIRM_RE = re.compile( r"\b(yes|yeah|yep|yup|sure|ok|okay|k|confirm(?:ed)?|proceed|" - r"go\s+ahead|do\s+it|please\s+do|overwrite|replace|regenerate|" + r"go\s+ahead|do\s+it|please\s+do|overwrite|replace|append|regenerate|" r"redo|re-?do|start\s+over|restart|delete|wipe|reset|from\s+scratch|" r"go\s+for\s+it|fine|sounds\s+good|that'?s\s+fine)\b", re.IGNORECASE, diff --git a/calliope-backend/tests/test_agent_event_log.py b/calliope-backend/tests/test_agent_event_log.py index 5f4b4109..385cda3f 100644 --- a/calliope-backend/tests/test_agent_event_log.py +++ b/calliope-backend/tests/test_agent_event_log.py @@ -298,12 +298,16 @@ def test_destructive_guard_blocks_replace_on_nonempty_project(client): ) assert out["ok"] is False assert "blocked:" in out["error"] - assert "replace=false" in out["error"] + # The old message suggested "pass replace=false" as the escape — that + # advice caused a silent beat-doubling (2026-08-25), so append is now + # gated too and the message points at the granular tools instead. + assert "granular tools" in out["error"] - # replace=false passes the guard (then may fail later for other reasons — - # but NOT with a "blocked:" error). + # replace=false on a NON-EMPTY project is also blocked now (it would + # append a duplicate full set), with its own explanatory message. out2 = asyncio.run(registry.execute(ctx, "generate_story", {"replace": False})) - assert "blocked:" not in str(out2.get("error", "")) + assert out2["ok"] is False + assert "APPEND" in out2["error"] def test_destructive_guard_allows_empty_project(client): diff --git a/calliope-backend/tests/test_agent_security.py b/calliope-backend/tests/test_agent_security.py index ee405e1e..0f235544 100644 --- a/calliope-backend/tests/test_agent_security.py +++ b/calliope-backend/tests/test_agent_security.py @@ -1860,3 +1860,101 @@ def test_assets_role_has_editors_and_they_resolve(): ctx = ToolContext(session_id=9_999_003, project_id=99) names = {t["function"]["name"] for t in _scoped_payload(ctx, ROLE_TOOLS["assets"])} assert {"update_character", "update_location", "update_item", "get_workspace"} <= names + + +# ───────────────────────────────────────────────────────────────────────── +# Append gating + beat CRUD +# (Observed live 2026-08-25: an unconfirmed generate_story replace=false +# silently APPENDED a duplicate 25-beat set — 25 -> 50 beats — because the +# guard only gated replace=true; and with no beat editors, bulk regeneration +# was the sub-agent's only lever for "align the beats to this story".) +# ───────────────────────────────────────────────────────────────────────── + + +def test_guard_blocks_append_on_nonempty_project(client): + registry, _ = build_harness() + pid = _mk_project(client, "Append Film") + client.post(f"/api/projects/{pid}/scenes", json={"heading": "S1", "order_index": 1}) + ctx = ToolContext(session_id=_mk_session(), project_id=pid) + + out = asyncio.run(registry.execute(ctx, "generate_story", {"replace": False})) + assert out["ok"] is False + assert "APPEND" in out["error"] + assert "granular tools" in out["error"] + + +def test_guard_allows_append_after_user_confirms(client): + pid = _mk_project(client, "Append OK Film") + client.post(f"/api/projects/{pid}/scenes", json={"heading": "S1", "order_index": 1}) + sid = _mk_session(pid) + session_log.append_event( + sid, session_log.USER_MESSAGE, {"content": "yes, append the new beats"} + ) + reg = _guard_registry() + out = asyncio.run( + reg.execute(ToolContext(session_id=sid, project_id=pid), "bulk_replace", {"replace": False}) + ) + assert "blocked:" not in str(out.get("error", "")) + + +def test_beat_crud_round_trip(client): + from calliope.agent.harness.tools import execute_tool + + registry, _ = build_harness() + pid = _mk_project(client, "Beat Film") + sid = _mk_session(project_id=pid) + ctx = ToolContext(session_id=sid, project_id=pid) + + # Append two, then insert one at position 2 — later beats shift down. + a = asyncio.run(execute_tool(ctx, "add_beat", {"title": "Open", "description": "a"})) + b = asyncio.run(execute_tool(ctx, "add_beat", {"title": "End", "description": "c"})) + assert (a["beat"]["order_index"], b["beat"]["order_index"]) == (1, 2) + m = asyncio.run( + execute_tool(ctx, "add_beat", {"title": "Turn", "description": "b", "order_index": 2}) + ) + assert m["beat"]["order_index"] == 2 + + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT order_index, title FROM story_beats WHERE project_id = ? ORDER BY order_index", + (pid,), + ).fetchall() + finally: + conn.close() + assert [(r["order_index"], r["title"]) for r in rows] == [ + (1, "Open"), (2, "Turn"), (3, "End"), + ] + + # Update content + reject foreign/unknown ids. + out = asyncio.run( + execute_tool(ctx, "update_beat", {"beat_id": m["beat"]["id"], "description": "the turn"}) + ) + assert out["beat"]["description"] == "the turn" + out = asyncio.run(execute_tool(ctx, "update_beat", {"beat_id": 999999})) + assert out["ok"] is False + + # Delete the middle beat — the gap closes. + out = asyncio.run(execute_tool(ctx, "delete_beat", {"beat_id": m["beat"]["id"]})) + assert out["ok"] is True + conn = get_db(settings.db_path) + try: + rows = conn.execute( + "SELECT order_index, title FROM story_beats WHERE project_id = ? ORDER BY order_index", + (pid,), + ).fetchall() + finally: + conn.close() + assert [(r["order_index"], r["title"]) for r in rows] == [(1, "Open"), (2, "End")] + + +def test_story_role_has_beat_editors(): + from calliope.agent.harness.orchestrator import ROLE_TOOLS, _scoped_payload + + for tool in ("add_beat", "update_beat", "delete_beat"): + assert tool in ROLE_TOOLS["story"] + ctx = ToolContext(session_id=9_999_004, project_id=99) + names = {t["function"]["name"] for t in _scoped_payload(ctx, ROLE_TOOLS["story"])} + assert {"add_beat", "update_beat"} <= names + # delete_beat is destructive but not approval-gated; it should resolve too + assert "delete_beat" in names