diff --git a/calliope-backend/src/calliope/__init__.py b/calliope-backend/src/calliope/__init__.py index b753c6b9..c9d2e58b 100644 --- a/calliope-backend/src/calliope/__init__.py +++ b/calliope-backend/src/calliope/__init__.py @@ -4,4 +4,4 @@ # reads this; pyproject.toml is kept in sync for the build (hatchling dynamic # version reads this file). PR #47: hard-coded literals drifted twice # (1.3.2 shipped reporting 1.2.1; 1.4.1's /api/health still said 1.4.0). -__version__ = "1.5.4" +__version__ = "1.5.5" diff --git a/calliope-backend/src/calliope/agent/harness/orchestrator.py b/calliope-backend/src/calliope/agent/harness/orchestrator.py index 720a590e..e72a1e0b 100644 --- a/calliope-backend/src/calliope/agent/harness/orchestrator.py +++ b/calliope-backend/src/calliope/agent/harness/orchestrator.py @@ -119,6 +119,15 @@ ROLE_TOOLS: dict[str, list[str]] = { "add_beat", "update_beat", "delete_beat", + # Story tasks may structure beats INTO scenes — the planner schedules + # "break the beats into an 8-scene structure" as a story task, and a + # story agent without scene tools dead-ends with "add_scene is not + # available to this role" (session 908: scenes never got created, the + # script role then found "no scenes in the project"). + "list_scenes", + "add_scene", + "update_scene", + "delete_scene", "list_workflows", "ask_user", ], @@ -174,6 +183,7 @@ ROLE_TOOLS: dict[str, list[str]] = { "wait_for_jobs", "comfy_server_info", "ask_user", + "post_artifact_to_canvas", ], } @@ -193,7 +203,9 @@ Respond with ONLY a JSON object: Rules: - The standard EDIT pipeline (story → script → add/update assets text) is swarm work: one task per role, in that order. +- ROLE BOUNDARIES: the story role owns BEATS (beats, characters, locations via generate_story/add_beat) — it cannot create scenes. The script role owns SCENES (add_scene, generate_script, break_into_shots). A "turn the story into N scenes" plan is a SCRIPT task; never schedule add_scene under the story role (session 908: a story task told to add_scene reported "tool not available to this role" and the whole build stalled). - Image/video GENERATION is human-in-the-loop, but the user's EXPLICIT choices grant permission: tagging a workflow (@mention), asking to "generate/render/create an image", or confirming an offer all count. When the user tagged a workflow AND named entities (characters/locations/scenes), schedule a single assets task whose goal says: run_workflow with the tagged workflow_id + per-entity prompts (character_ids=[…] for multiple characters), wait_for_jobs, then post_artifact_to_canvas for each output. +- When ANY task involves generating videos/clips (enqueue_video_jobs / run_workflow for clips), the video role's tools are visible only if the user's message carries render intent — phrase that task's goal so the sub-agent first calls ask_user to confirm scope when unsure, rather than reporting "the generation tool is not exposed". Never schedule a render task and a text-only pass of the same scope. - For text-only edits (add/update characters, locations, items, scenes, story, script) with NO generation ask, schedule the edit task and DO NOT schedule render tasks. - Film clips: video sub-agent must enqueue_video_jobs with orders (#N on Video) or scene_ids from list_scenes — ONLY the clips the user named. Never dump every scene_id. Never add_scene to attach a generated mp4. Orphan jobs (scene_id null) do not show on the Video timeline. - A tagged workflow ([Calliope context] with workflow_id=) with entities named is a generation request: one assets task covers the text updates AND the render (the assets role has run_workflow/enqueue_asset_jobs). Never end a turn saying you lack enqueue access — the assets sub-agent has it. @@ -204,12 +216,31 @@ Rules: def _scoped_payload(ctx: ToolContext, allowed: list[str]) -> list[dict[str, Any]]: + """The sub-agent's tool payload. + + Deliberately bypasses `_visible`'s render-approval clause: sub-agents with + enqueue/run tools in their role MUST see them, or a planner-scheduled + render task dead-ends ("the generation tool is not exposed", session 908) + with no path to ask. Permission is enforced at execute time by the + `_render_approval_guard` denial, which teaches ask_user — a visible, + guard-denied tool is recoverable; a hidden one is a wall. Everything else + (requires_project / blind_only / scene scope) still filters here. + """ registry = get_registry() out: list[dict[str, Any]] = [] for n in allowed: t = registry.get(n) - if t is None or not registry._visible(t, ctx): + if t is None: continue + if t.requires_project and ctx.project_id is None: + continue + if t.blind_only and ctx.project_id is not None: + continue + if ctx.origin == "scene": + from calliope.agent.harness.registry import _scene_scoped + + if not _scene_scoped(t): + continue out.append( { "type": "function", @@ -580,12 +611,15 @@ async def _run_sub_agent( "summary when done — no tool call.\n" "Image/video generation (enqueue_asset_jobs / enqueue_video_jobs / " "run_workflow) is human-in-the-loop: only call it when the user " - "explicitly asked to generate. A workflow_id= appendix is not " - "permission. There is no MCP run_workflow. Film clips: " - "enqueue_video_jobs with orders (Video #N) or scene_ids from " - "list_scenes — only the clips they named, never the whole timeline. " - "Never add_scene to attach an mp4. For text-only edits, " - "do the edit and stop." + "explicitly asked to generate. If the guard denies the call " + "(guard_render_approval), do NOT give up and do NOT claim the tool " + "is missing — it is available but gated. Call ask_user to confirm " + "generation with the user; their affirmative answer unlocks the " + "retry. A workflow_id= appendix is not permission. There is no MCP " + "run_workflow. Film clips: enqueue_video_jobs with orders (Video #N) " + "or scene_ids from list_scenes — only the clips they named, never " + "the whole timeline. Never add_scene to attach an mp4. For " + "text-only edits, do the edit and stop." ) hardening = hardening_text() if hardening: diff --git a/calliope-backend/src/calliope/agent/harness/policy.py b/calliope-backend/src/calliope/agent/harness/policy.py index 3cb09ecb..ec92a90b 100644 --- a/calliope-backend/src/calliope/agent/harness/policy.py +++ b/calliope-backend/src/calliope/agent/harness/policy.py @@ -41,8 +41,13 @@ _NEGATE_RE = re.compile( # Image/video *generation* intent. `video` matches as a SUBSTRING so model / # compound names keep signaling intent ("text2video", "fastvideoH3_t2v-API"); # everything else is \b-anchored (`vid` must not match "provide"). +# clip/shot/storyboard are RENDER-UNIT nouns in Calliope's vocabulary (clips +# are the render units) — "break the beats into the script + shot clips" is a +# generation order, not a text edit (session 908: the video sub-agent's tools +# stayed hidden and it reported "the generation tool is not exposed"). _RENDER_REQUEST_RE = re.compile( - r"(video|\b(?:render|image|portrait|sheet|artwork|visual|thumbnail|vid)\w*|" + r"(video|\b(?:render|image|portrait|sheet|artwork|visual|thumbnail|vid|" + r"clip|shot|storyboard)\w*|" r"txt2\w+|text2\w+|img2\w+|photo2\w+)", re.IGNORECASE, ) diff --git a/calliope-backend/src/calliope/routers/canvas.py b/calliope-backend/src/calliope/routers/canvas.py index 82e9a103..df318248 100644 --- a/calliope-backend/src/calliope/routers/canvas.py +++ b/calliope-backend/src/calliope/routers/canvas.py @@ -399,6 +399,24 @@ async def create_canvas(payload: CanvasCreate) -> dict[str, Any]: async def get_canvas(canvas_id: int) -> dict[str, Any]: conn = get_db(settings.db_path) try: + # Auto-seed: entity cards for content created AFTER the canvas was + # opened (agent drafted characters/locations/scenes mid-session) must + # appear on refetch, not only on ensure/re-open. Idempotent and + # tombstone-respecting — deleted cards never resurrect. Only project + # canvases seed (sandbox boards have no entities to seed). + row = conn.execute("SELECT * FROM canvas WHERE id = ?", (canvas_id,)).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Canvas not found") + if row["project_id"] is not None: + if seed_entities(conn, canvas_id, int(row["project_id"])) > 0: + conn.execute( + "UPDATE canvas SET updated_at = ? WHERE id = ?", (_now(), canvas_id) + ) + conn.commit() + await event_bus.publish( + "canvas.updated", + {"canvas_id": canvas_id, "reason": "entities_seeded"}, + ) return _load_graph(conn, canvas_id) finally: conn.close() diff --git a/calliope-backend/tests/test_render_intent.py b/calliope-backend/tests/test_render_intent.py index 0c4d8eab..80bee219 100644 --- a/calliope-backend/tests/test_render_intent.py +++ b/calliope-backend/tests/test_render_intent.py @@ -36,9 +36,18 @@ from calliope.agent.harness.policy import is_render_request # Plain positive cues ("render all scenes now", True), ("yes, generate the images", True), + # Clip/shot are render-unit nouns (session 908: "shot clips" left the + # video sub-agent's enqueue tools hidden → "generation tool is not + # exposed") + ("Break the beats into the 8-scene script + shot clips", True), + ("break scene 3 into clips", True), + ("render the shots for scene 2", True), # Non-render text must not flip positive ("generate the story", False), ("provide the lyrics", False), + # 'clip' as a noun of speech ("clip the beard") is not a cue — but the + # verb is rare in film asks; keep the broad match and rely on + # clause-scoped negation for safety. ], ) def test_render_intent(text: str, want: bool): diff --git a/calliope-backend/tests/test_tag_render_permission.py b/calliope-backend/tests/test_tag_render_permission.py index ba534e7c..dfcf88c8 100644 --- a/calliope-backend/tests/test_tag_render_permission.py +++ b/calliope-backend/tests/test_tag_render_permission.py @@ -87,6 +87,78 @@ def test_assets_role_scope_includes_canvas_posting(): assert registry.get(name) is not None, f"{role} names unknown tool {name}" +def test_story_role_can_structure_beats_into_scenes(): + """Session 908 regression: the planner scheduled 'create 8 scenes via + add_scene' as a STORY task, but add_scene lived only in the script role — + the story agent reported 'Tool not available to this role: add_scene', + scenes were never created, and the build stalled with nothing in the + project DB. Scene-authoring basics belong to the story role too.""" + tools = orchestrator.ROLE_TOOLS["story"] + assert "add_scene" in tools + assert "list_scenes" in tools + + +def test_sub_agent_payload_keeps_render_tools_visible(): + """Session 908 regression: a planner-scheduled video render task must see + enqueue_video_jobs in its payload even without prose render intent — the + scoped payload filters requires_project/blind_only/scene-scope only, and + PERMISSION is enforced at execute time (guard denial teaches ask_user). + The old _visible()-based filter hid the tools entirely, so the sub-agent + ended with 'the generation tool is not exposed in this session's + toolset' and the render never happened.""" + + class _Recorder: + def __init__(self) -> None: + self.names: list[str] = [] + + def __call__(self, fn): + self.names.append(fn.__name__) + return fn + + import calliope.agent.harness.orchestrator as orch + + # No user/message events at all → user_allows_render is False, so the + # old payload filter would have dropped every requires_approval tool. + payload = orch._scoped_payload( + ToolContext(session_id=999_001, project_id=1), + orchestrator.ROLE_TOOLS["video"], + ) + names = {p["function"]["name"] for p in payload} + assert "enqueue_video_jobs" in names + assert "run_workflow" in names + # Sanity: truly project-scoped tools still filter for blind contexts. + blind = orch._scoped_payload( + ToolContext(session_id=999_001, project_id=None), + orchestrator.ROLE_TOOLS["video"], + ) + blind_names = {p["function"]["name"] for p in blind} + assert "enqueue_video_jobs" not in blind_names + assert "get_workspace" in blind_names # requires_project=False + + +def test_execute_time_render_guard_still_blocks_without_intent(): + """The payload fix must not weaken the execute-time gate: with no render + intent, calling enqueue_video_jobs still returns the HITL denial (which + instructs ask_user) rather than executing.""" + import json as _json + + from calliope.agent.harness import build_harness, get_registry + + build_harness() + registry = get_registry() + # Session 999_002 has no events → no render permission. + result = asyncio.run( + registry.execute( + ToolContext(session_id=999_002, project_id=1), + "enqueue_video_jobs", + {"scene_ids": [1]}, + ) + ) + assert result.get("ok") is False + assert result.get("reason_code") == "guard_render_approval" + assert "ask" in _json.dumps(result).lower() + + def test_swarm_roles_cover_pipeline_categories(): """Drift guard (both directions): every registered tool in a pipeline category must appear in its ROLE_TOOLS role — the clip tools drifted out diff --git a/calliope-web/package-lock.json b/calliope-web/package-lock.json index 06a4e406..8830d9d3 100644 --- a/calliope-web/package-lock.json +++ b/calliope-web/package-lock.json @@ -1,12 +1,12 @@ { "name": "calliope-web", - "version": "1.5.4", + "version": "1.5.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "calliope-web", - "version": "1.5.4", + "version": "1.5.5", "dependencies": { "@tanstack/svelte-query": "^5.66.0", "@types/three": "0.185.0", diff --git a/calliope-web/package.json b/calliope-web/package.json index 309319f4..2cab6f52 100644 --- a/calliope-web/package.json +++ b/calliope-web/package.json @@ -1,6 +1,6 @@ { "name": "calliope-web", - "version": "1.5.4", + "version": "1.5.5", "private": true, "scripts": { "dev": "vite dev", diff --git a/calliope-web/src/routes/canvas/[id]/+page.svelte b/calliope-web/src/routes/canvas/[id]/+page.svelte index aa365e76..b18c12b9 100644 --- a/calliope-web/src/routes/canvas/[id]/+page.svelte +++ b/calliope-web/src/routes/canvas/[id]/+page.svelte @@ -486,8 +486,14 @@ sessionScopeHandled = true; const paramSession = page.url.searchParams.get('session'); const pid = Number(paramSession); - if (paramSession != null && Number.isFinite(pid)) { - activeId = sessions.some((s) => s.id === pid) ? pid : null; + if (paramSession != null && Number.isFinite(pid) && pid > 0) { + // Trust the deep-link param even when the (possibly cached) sessions + // list doesn't contain it yet: /agents?project=&task= hands us a + // session created milliseconds ago. Validating against a stale list + // nulled activeId and orphaned the chat — the next Send then created + // a DUPLICATE session (empty 905 vs working 906 signature). A truly + // gone session just 404s in the session query, which is recoverable. + activeId = pid; // Deep-link handoff (/agents?project=&task=) pre-fills the composer once. const prefill = sessionStorage.getItem('calliope.canvas.composerPrefill'); if (prefill) { diff --git a/docs/changelogs/2026-09-22-swarm-render-scene-fixes.md b/docs/changelogs/2026-09-22-swarm-render-scene-fixes.md new file mode 100644 index 00000000..fc637a5d --- /dev/null +++ b/docs/changelogs/2026-09-22-swarm-render-scene-fixes.md @@ -0,0 +1,71 @@ +# Calliope 1.5.5 — swarm fixes: renders enqueue, scenes get written, the board fills + +A regression-fix release for 1.5.4's agent hardening: live event logs showed a +planner-scheduled render task whose tools were hidden, a story sub-agent denied +the scene tools the planner told it to use, deep-linked chats orphaning as +duplicate empty sessions, and new project assets not appearing on the canvas +until re-open. All four paths are fixed and regression-tested. + +## What changed + +### The "generation tool is not exposed" deadlock (video sub-agent) + +A swarm render task could dead-end in three layers at once: the planner said +"enqueue_video_jobs for those 8 scenes", the HITL visibility rule hid every +render tool (no render verb in the user's words), and the sub-agent — unable to +call or even see the tool — ended with *"enqueue could not be performed — the +generation tool is not exposed in this session's toolset"*. + +- **`clip` / `shot` / `storyboard` are render-intent cues now.** "Break the + beats into the 8-scene script + shot clips" is a generation order; the + clause-scoped negation rules are unchanged. +- **Sub-agent payloads keep approval-gated tools visible.** The scoped payload + filters `requires_project` / `blind_only` / scene-scope only; permission is + enforced at execute time by the `_render_approval_guard`, whose denial names + the recovery path. A visible, guard-denied tool is recoverable — a hidden one + is a wall. +- **The denial teaches `ask_user`.** A gated sub-agent now asks the user to + confirm generation; the affirmative answer unlocks the retry. HITL itself is + untouched — nothing renders without an explicit user ask. + +### Story sub-agent can structure beats into scenes + +The planner scheduled "create exactly 8 scenes via add_scene" as a **story** +task, but `add_scene` lived only in the script role — the story agent reported +`Tool not available to this role: add_scene`, scenes were never created, and +the script pass then found "no scenes in the project" (the "nothing inserts +into story and script" report). + +- The story role gains `list_scenes` / `add_scene` / `update_scene` / + `delete_scene`. +- The planner system prompt gains an explicit role-boundary rule: story owns + beats, script owns scenes — never schedule `add_scene` under story. + +### No more orphaned duplicate deep-link sessions + +The Project stages' "Draft Storyline" / "Regenerate Script" buttons create a +session and hand off with `?session=` — but the canvas page validated that +param against a possibly-stale cached session list, missed the milliseconds-old +session, nulled the active chat, and the next Send created a **second** +session. Result: a pile of empty "Draft Storyline" sessions in the rail plus +one that actually worked. The deep-link param is now trusted outright; a truly +gone session just 404s in the query, which is recoverable. + +### Canvas auto-seeds new entities on refetch + +Entity cards (characters, locations, items, scenes) only seeded when a canvas +was *ensured*, so assets the agent created mid-session stayed invisible until +you re-opened the board. `GET /api/canvas/{id}` now auto-seeds missing entity +cards — idempotent, tombstone-respecting (deleted cards never resurrect), and +it publishes `canvas.updated` only when something was actually added. + +## Testing + +- `tests/test_render_intent.py` — clip/shot cues, including the exact session + message that failed in the wild. +- `tests/test_tag_render_permission.py` — story-role scene tools; sub-agent + payload keeps `enqueue_video_jobs` visible without intent; the execute-time + guard still blocks and names `ask_user`. + +Full stack: 177 backend tests across the nine affected suites plus +`svelte-check` (0 errors). diff --git a/docs/changelogs/README.md b/docs/changelogs/README.md index 3c8661fe..5bc89745 100644 --- a/docs/changelogs/README.md +++ b/docs/changelogs/README.md @@ -2,6 +2,7 @@ Dated notes for GitHub releases. Newest first. +- [2026-09-22 swarm render/scene fixes](./2026-09-22-swarm-render-scene-fixes.md) — video-role render tools reachable (ask_user recovery); story role gains scene tools; deep-link sessions no longer orphan; canvas auto-seeds new entities (1.5.5) - [2026-09-19 steering + Asset Library + hardening](./2026-09-19-steering-library-hardening.md) — mid-run steering; Asset Library page (filter + lazy loading); canvas delete that deletes; agent-loop hardening batch; Build Scene Brief/Cut gates (1.5.4) - [2026-09-16 SSR storage fix](./2026-09-16-ssr-storage-fix.md) — fix the `localStorage.getItem is not a function` crash on Node 22+; new `npm test` guard (1.5.3) - [2026-09-16 multilingual UI](./2026-09-16-multilingual-ui.md) — seven-language UI (en/zh/es/fr/de/ja/ko); header language switcher; correct backend version; local start scripts (1.5.2)