chain-rdeveloper portal
build

Scenario runs

A scenario run is a scripted set of agent chats, run on the real chat path and exported whole for review. A developer writes (or is given) a scenario file — the agents to make, the knowledge to grant them, the conversations to have, and what each turn should do — uploads it, and downloads one JSON file holding everything each turn did: what triage chose, each knowledge lane's funnel, what was retrieved and what was cited, the quality check, the cost, the decision record, and whether each was what the file expected.

It exists so a change can be tested by running it and reading what happened, instead of asking an agent questions by hand and pasting answers back: most of what explains an answer (the mix, the lanes, the passages not cited) never reaches the chat window.

Code: modules/svc-core/app/services/scenarios/, routes modules/svc-core/app/router/app/scenario_runs/router.py.

Turning it on

Scenario runs are a developer tool, gated twice:

  1. The deployment: SCENARIO_RUNS_ENABLED (svc-core, default false). The deployed dev host runs as APP_ENV=prod, so this setting, not the environment's name, is what turns it on there: SSM /chainr/dev/features/SCENARIO_RUNS_ENABLED=true, which the deploy writes to dotenv/prod/features.env (read as optional). Locally, put the line in modules/dotenv/dev/features.env. Off, every /app/scenario-runs route is a 404.

    ``bash aws ssm put-parameter --profile chainr-dev --overwrite \ --name /chainr/dev/features/SCENARIO_RUNS_ENABLED --value true --type String ``

    then deploy (or restart svc-core).

  2. The person: the developer platform role, assigned in Auth0 (auth-flow.md). Without it every route is a 403 naming the role. A superuser holds it too; it changes no access check, so a developer's run sees only what they could see by hand.

The page

fe-core → Settings → Developer → Scenario runs (apps/user/pages/settings/ScenarioRuns.tsx). The Developer group of settings tabs shows only for the developer role (hasPlatformRole; a superuser holds it too); the page itself says so plainly when the deployment has runs off (404) or the person lacks the role (403).

  • Run a scenario: choose a file. The page reads it first (scenarioFile.readScenario: JSON, one object, then counts its agents, conversations and turns) and shows what is about to run; Start the run sends it, and a file svc-core refuses shows svc-core's reason. One run at a time: Start is held while another is going.

  • Your runs, newest first, read again every five seconds while one is going: each with its status (RUN_STATUS), when it started and where it is (runLine: turns done and the one running, or turns, checks passed and cost), a progress bar, its error, up to five failed checks with where they are, and Export, Open project (its agents, in the project's workspace), Cancel while it runs and Delete once it has finished (asked first: it deletes the project).

The review loop

  1. Write or pick a scenario (samples/scenarios/).

  2. Run it from the page (or the CLI).

  3. Export, and put the file in /workspace/.scenario-runs/ (gitignored).

  4. Ask Claude to review it: the export holds what it needs — triage's choice, each lane's funnel, what was retrieved beside what was cited, the quality check, the decision record and every expectation checked.

  5. Change the code, deploy, and run the same file again: the run's scenario_sha256 and svc-ai's code fingerprint say whether the file and the code are the ones you think.

What a run does

POST /app/scenario-runs validates the file (a 422 says what is wrong) and starts the run in the background (202); one run at a time a person (409). The run:

  1. Makes a project of its own — a personal project named Scenario · <name> · <date time> · <id> — with the file's agents in it, each created and granted its repositories the way the pages do (an agent version per grant). Memory, recommendations and figures start empty, so two runs of one file can be compared. The project shows in the workspace menu like any other: its agents and chats can be opened in the app.

  2. Waits for the knowledge it granted (readiness.wait, 28 October 2026). A built-in website repository is crawled only while an agent holds it, so on a deployment where nobody had granted it, it held nothing: the first run's compliance agent answered all eight of its turns from knowledge bases with nothing indexed. The grants now start the first crawls (knowledge/built_in_crawls), and the first turn waits until every granted source has settled — a website source holding indexed pages, or whose crawl finished; a written source stored and indexed — for at most 20 minutes (KNOWLEDGE_WAIT_S), checking every 10 s. The page's progress line says "indexing: 5 of 9 sources ready" meanwhile. Cancel stops the wait.

  3. Reads each agent's context panel (agent_context): what it holds of each kind of knowledge, and which built-ins it suggests for a missing one.

  4. Runs every turn through the chat route, conversation by conversation, one turn at a time (driver.run_turn). The turn is the websocket route itself (agent_prompt_ws), handed a stand-in socket (ScenarioSocket) that keeps every frame it is sent — tokens counted, not kept — and ai_client.tap_stream keeps svc-ai's terminal frame, which no socket sees (every passage retrieved, not only those cited). So a turn is governed, ledgered, stored and recorded exactly as a person's chat is: rules, budgets, the usage ledger, the stored messages, the citations and retrieval records, the decision record. A turn running past 10 minutes is stopped as Stop stops a chat. A pause to ask the person is answered from the turn's answers (once). Any other pause is left unanswered, so the turn ends there, unless the file sets "pauses": "answer": then it is answered as a person with no preference would answer it (driver.default_answers, 28 October 2026). That means the option the agent recommends (every recommended one for a question of several choices), else the first; "No preference — use your judgement" for a typed answer; nothing for a number or a date. It is checked as the route checks an answer (hitl.validate_response), and when the route would refuse it (a required number or date) nothing is answered, which the route takes as a deliberate skip. An approval gate is approved. The turn records answered (default), skipped (default) or approved (default) in its pauses. Run 5's b-bakery asked "Which regions?" after fifteen tool calls and, left unanswered, had no quality check and no citations to measure. A turn's command_inputs go in its opening frame as fe-core's command form sends them, so /execute skill research-brief runs with its form filled.

  5. Exports each turn as it finishes, appending it to the run's record, so a run cut off by a restart keeps what it did (and reads as failed once it has been silent for 15 minutes).

  6. Closes with each agent's context panel again, the recommendations offered for it and for the project, and a summary.

Cancel (POST /{id}/cancel) stops the turn running and starts no more; Delete (DELETE /{id}, once finished) removes the run and its project, its agents and what they remembered.

Each turn is an ordinary chat turn: it costs what that chat would, counts against the workspace's budgets (a personal project counts to its owner's Personal allowance) and the platform's spending ceiling, and is in the usage ledger. There is no new model path.

The file

JSON, schema: 1, validated whole (schema.py, every object extra="forbid"). samples/scenarios/ holds the ones in the repo, each loaded by tests/test_scenario_runs.py as an upload would be.

{
  "schema": 1,
  "name": "builtin-knowledge",
  "description": "What the built-in knowledge does in each kind.",
  "pauses": "answer",
  "agents": [
    {
      "key": "A",
      "name": "Compliance advisor",
      "description": "Advises a UK company on AI and data protection.",
      "instructions": "Answer as a compliance adviser.",
      "model": null,
      "cost_profile": "thorough",
      "clarify_scope": false,
      "repositories": ["AI & data protection law", "Risk & assurance"],
      "expect": {
        "suggests_first": {"temporal": "Regulation & security updates"},
        "recommends": ["no_dated_knowledge"]
      }
    }
  ],
  "conversations": [
    {
      "key": "a-dpia",
      "agent": "A",
      "turns": [
        {
          "prompt": "Do we need a DPIA to fine-tune on support transcripts?",
          "answers": null,
          "expect": {
            "profile": "analysis",
            "searched": ["domain", "reasoning"],
            "not_searched": ["temporal"],
            "cites": ["AI & data protection law"],
            "not_cites": [],
            "quality": ["passed", "revised"]
          }
        }
      ]
    }
  ]
}
  • Agents (at most 10): key (how conversations name it), name, optional description and instructions (its system prompt), model (a catalogue model's model_name; null for the deployment's default), cost_profile, clarify_scope (off by default: a scripted run has nobody to ask), repositories (built-ins by their exact names; a name that is no built-in a user may grant here is refused, listing the ones that are).

  • pauses (optional): leave (the default) leaves a pause the file wrote no answers for unanswered; answer answers it by default (see step 4). builtin-knowledge.json answers: its agents ask, and a turn that ends at a question measures nothing.

  • Conversations: key, agent, turns. A conversation's turns share one chat, so a follow-up has its history.

  • Turns (at most 60 in all): prompt, answers for a pause (field id → value; the ids are the model's, so a scripted answer is often refused and the pause given up, which still counts as asking; a pause it does not answer is handled as pauses says), command_inputs for a chat command's form (field id → value; Research brief needs topic), expect.

  • Expectations are optional, and each is checked after the run and recorded, passed or not; none fails the run (checks.py, one class each):

    Tools are svc-ai's (its built-ins, the knowledge tools and the attachment tools) and kinds are its fences (chart, plot, mermaid, graph, map, document), both pinned to its source by the tests. ask_user is refused under tools: asking pauses the turn rather than returning, so it is asks: true.

    ExpectationRead fromPasses when
    searchedthe lane nodes that ranevery kind named ran
    not_searchedthe samenone of them ran
    citesthe answer's citations record, by built-inevery repository named was cited
    not_citesthe samenone was
    qualitythe stored meta.eval_outcomethe outcome is one of those named
    toolsthe turn's tool_call framesevery tool named was called and did its work (not an error, and not its own [<tool>] … refusal, which the frame reads as a success)
    not_toolsthe samenone of them was called
    artifactsthe answer's fences (artifacts)a fence of each kind named is well-formed and was made by its render tool; the actual says missing, invalid: … or written by hand, not by its tool
    not_artifactsthe samethe answer holds none of the kinds named
    documentthe answer's first document (documents)pdf (default true): it renders; min_pages; min_images: images embedded; all_images: every image it links was embedded; visuals: kinds of visual its body holds, each drawn in its PDF
    asksthe turn's pausestrue: it paused to ask; false: it did not
    commandthe person's message's meta.commandthe command target's slug is the one named
    suggests_first (agent)the context panel before any turneach kind's first suggestion is the one named
    recommends (agent)the recommendations after its turnseach kind named was offered

Swarms in a file

A file may also make swarms of its agents and send them on tasks (swarms: up to 4 swarms, 8 runs in all, follow-ups included; a file needs a conversation or a swarm). Each swarm names a shape, its settings and a roster of the file's agents by key (each with a role, an optional note and spawn), is made in the run's project as the Swarms page makes one (engine.check_swarm, a created version), and runs each of its tasks unattended after the conversations — one run at a time, each coordinated to its end (runner._swarm_runs, engine.Origin.scenario: listed in the project, no inbox notice). A run's expect (SwarmRunExpect): status (any of), answered, approach, min_pieces / max_pieces, kinds (task kinds it must hold), max_cost_usd, and cites_pages (its answer cites a page or a document a piece read, not only the team's own pieces).

A run may have up to three follow-ups (follow_ups: task, budget, time cap, expect; 30 October 2026), each sent once the run before it has finished through engine.follow_up of that run, so the thread and the scenario's origin carry on (see docs/guides/swarms.md#follow-ups-a-thread-of-requests). Each is a swarm run of the file's count. A follow-up's expect takes the same fields and two more: min_builds_on (how many of its plan's pieces build on pieces of the request before) and cites_carried (its answer cites a source an earlier request of the thread cited — carried through, not lost or found again).

"swarms": [{
  "key": "team", "name": "Lead and analysts", "topology": "supervisor",
  "params": {"span": 3},
  "roster": [{"role": "lead", "agent": "lead"},
             {"role": "worker", "agent": "uk", "note": "Takes anything about the UK"}],
  "runs": [{"task": "Compare …", "budget_usd": 1.5,
            "expect": {"answered": true, "approach": "team", "min_pieces": 2},
            "follow_ups": [{"task": "Now turn that into a CFO's brief …",
                            "expect": {"min_builds_on": 1, "cites_carried": true}}]}]
}]

The export

GET /app/scenario-runs/{id}/export downloads scenario-run-<name>-<yyyymmdd-hhmm>.json (schema EXPORT_SCHEMA, 1), as far as the run has got:

  • run: the scenario's name and digest, start and finish, status and error, the project and its workspace key, DEPLOY_ID, and svc-ai's code fingerprint (/health), so two runs say whether the same code answered. run.knowledge is what the granted knowledge held when the turns began: waited_ms, timed_out, and per repository each source's newest crawl, its documents by indexing state, its chunks, whether it had settled and when, and its documents (document_list, at most 200: title, address, index state, chunks, page state). So a page never crawled is told apart from one never retrieved.

  • agents: each with its settings and grants, context_before / context_after (the context panel's eight kinds, with suggestions), recommendations_after, and its checks.

  • turns, each with:

    • prompt, status (completed / blocked / error / stopped / crashed), error and error_code, started_at, duration_ms, tokens_streamed, pauses;

    • conversation_id, message_id, invocation_id;

    • answer, model, quality (outcome, score, critique, gaps), cost;

    • triage (the gate's result), profile, knowledge_plan, lanes (each lane's frame: kind, role, queries, found, judged, ruled out, out of the window, handed on), searched, join;

    • cited_sources (as stored), citations (the citations record, with the built-in each belongs to), cited_repositories, retrieved (every passage retrieved, snippets cut to 300 characters), web_search, tools, terminal (svc-ai's terminal frames, less the answer and the passages);

    • what the answer delivered (scenarios/artifacts.py):

      • artifacts: each chart, plot, mermaid, graph, map or document fence in the answer, with its kind, valid and problems (checked against the shape its tool writes: a chart or plot's type and data, a graph's node ids and edges, a map's GeoJSON type, a document's title; mermaid only for opening with a diagram type, its syntax unchecked, and the entry says so), from_tool (its render_<kind> call returned that fence) and chars;

      • documents: each document's title, its images (linked by its text, embedded as stored copies, the links missing), its visuals (a row a kind of visual fence in its body: count, valid, drawn in its PDF and problems; since 29 October 2026), and pdf (bytes, pages, error), rendered by svc-ai as the conversation's PDF route renders it, footer included; pages are read from the page tree, a refusal is rejected: …, and svc-ai's own error text is never kept. What the PDF drew is svc-ai's word (the X-Document-Visuals header of /documents/pdf: each visual, drawn or a note in its place), since a PDF's subset-encoded text cannot be read for it; drawn is null when the PDF did not render;

      • hitl: each pause the answer records (meta.hitl): kind, source, outcome, how many questions, how long it waited;

      • command: the person's message's chat command (line, action, kind, target name, inputs, request) and its target's slug;

    • knowledge_record (the turn's retrieval record and each source's counts), decision (the decision record, read as its owner);

    • trace (every frame but tokens, strings cut to 2,000 characters);

    • checks.

  • recommendations: what the project's knowledge recommendations offer at the end.

  • summary: turns by status, checks passed, each failed check with where it is, the cost, unpriced turns, the time.

The export is the runner's account of what happened, not a copy of the database: a stored answer's text is its message's, everything else as the turn sent it, cut where it says so.

From a shell

cd modules/svc-core
uv run python -m app.services.scenarios run ../../samples/scenarios/<file>.json \
  --email you@example.com --out ../../.scenario-runs

The same provisioning, turns and export, run in the foreground as the person named (who must exist), with the export written to --out and a summary printed; exit code 0 when it completed. It needs svc-core's database and an svc-ai that can call a model, so on a local stack only once that stack has working model access. A shell is already an administrator's, so neither the switch nor the role is asked.

Each swarm run is exported in swarm_runs (export.swarm_run_export): its status, wrap-up reason and error, the lead's approach and how many pieces the plan held, the kinds of task it held, every task (handle, kind, role, agent, status, what it waited for, spend, error), the ledger, warnings, the answer (20,000 characters), cost and duration, and its checks. It also carries its answer's sources (citations: marker, title, URL, tool, kind) and cites (pages: those a piece read, not the team's own pieces; carried: those an earlier request of its thread cited, matched by address or document, export.source_key). A follow-up adds follow_up (its number after the run it follows), thread (seq, parent_run_id), builds_on (each new piece's earlier pieces, as its brief keeps them) and given (the earlier documents each task read, by name, export.thread_documents: what thread.documents_for gave it). The summary counts swarm runs, their checks and their cost, and names a follow-up's failed check as swarm team run 1 follow-up 1.

Limits

  • One worker on the process: runs queue behind one another, one turn at a time, so a 60-turn run takes as long as 60 chats.

  • A restart ends a run where it was (what it did is kept); nothing resumes it.

  • Built-in repositories only: the run's project is new, so a person's own repositories are not visible in it.

  • Agent chat and swarm runs only: no model chat, skill runs or tiles.

  • A default answer is the agent's own choice ("pauses": "answer"): a turn answered by default measures what the agent does with the option it recommended, never with what a person would have picked. Whether it should have asked at all is the asks check's to say.

  • What is checked of an artifact is its shape, not how it draws: a mermaid diagram is not parsed, a chart's numbers are not compared with the prompt's, and a PDF's pages are counted, never read.

Which sample to run

  • samples/scenarios/builtin-knowledge.json (3 agents, 19 turns) after a change to triage, the knowledge mix, the lanes, retrieval or the built-in knowledge.

  • samples/scenarios/capabilities.json (2 agents, 13 turns) after a change to the render tools, documents and their images and visuals, chat commands, or asking before working. pdf-visuals asks for a PDF holding a chart and a flowchart, and expects both drawn in it (document.visuals). It fetches images (Wikimedia) and runs the Research brief skill, so a turn costs more than a knowledge turn.

  • samples/scenarios/swarms.json (4 agents, 5 swarm runs) after a change to the swarm engine, a shape, follow-ups or the sources carried through: one task of separable parts sent to a lead and analysts, a council and a pipeline; the lead and analysts' answer followed up as a CFO's brief, which should build pieces on the earlier ones and cite a page the first request's pieces read; and a one-line task the lead should plan as one piece. Each run is a whole swarm run: up to $6.