@smthrs/gateway 1.0.0-rc.3 → 1.0.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/EngineTrace.d.ts.map +1 -1
  3. package/dist/cjs/EngineTrace.js +10 -2
  4. package/dist/cjs/EngineTrace.js.map +2 -2
  5. package/dist/cjs/GatewayProjection.d.ts.map +1 -1
  6. package/dist/cjs/GatewayProjection.js +10 -1
  7. package/dist/cjs/GatewayProjection.js.map +2 -2
  8. package/dist/cjs/HostBranchPresence.d.ts +7 -0
  9. package/dist/cjs/HostBranchPresence.d.ts.map +1 -1
  10. package/dist/cjs/HostBranchPresence.js.map +2 -2
  11. package/dist/cjs/RunTrace.d.ts.map +1 -1
  12. package/dist/cjs/RunTrace.js +3 -1
  13. package/dist/cjs/RunTrace.js.map +2 -2
  14. package/dist/cjs/internal/actionRenderings.d.ts +10 -0
  15. package/dist/cjs/internal/actionRenderings.d.ts.map +1 -1
  16. package/dist/cjs/internal/actionRenderings.js.map +2 -2
  17. package/dist/cjs/internal/inspectLabels.d.ts +5 -0
  18. package/dist/cjs/internal/inspectLabels.d.ts.map +1 -1
  19. package/dist/cjs/internal/inspectLabels.js.map +2 -2
  20. package/dist/esm/EngineTrace.d.ts.map +1 -1
  21. package/dist/esm/EngineTrace.js +19 -10
  22. package/dist/esm/EngineTrace.js.map +1 -1
  23. package/dist/esm/GatewayProjection.d.ts.map +1 -1
  24. package/dist/esm/GatewayProjection.js +7 -0
  25. package/dist/esm/GatewayProjection.js.map +1 -1
  26. package/dist/esm/HostBranchPresence.d.ts +7 -0
  27. package/dist/esm/HostBranchPresence.d.ts.map +1 -1
  28. package/dist/esm/HostBranchPresence.js +4 -1
  29. package/dist/esm/HostBranchPresence.js.map +1 -1
  30. package/dist/esm/RunTrace.d.ts.map +1 -1
  31. package/dist/esm/RunTrace.js +4 -3
  32. package/dist/esm/RunTrace.js.map +1 -1
  33. package/dist/esm/internal/actionRenderings.d.ts +10 -0
  34. package/dist/esm/internal/actionRenderings.d.ts.map +1 -1
  35. package/dist/esm/internal/actionRenderings.js +10 -0
  36. package/dist/esm/internal/actionRenderings.js.map +1 -1
  37. package/dist/esm/internal/inspectLabels.d.ts +5 -0
  38. package/dist/esm/internal/inspectLabels.d.ts.map +1 -1
  39. package/dist/esm/internal/inspectLabels.js +5 -0
  40. package/dist/esm/internal/inspectLabels.js.map +1 -1
  41. package/package.json +13 -13
  42. package/src/EngineTrace.ts +34 -12
  43. package/src/GatewayProjection.ts +17 -6
  44. package/src/HostBranchPresence.ts +5 -1
  45. package/src/RunTrace.ts +9 -6
  46. package/src/internal/actionRenderings.ts +11 -0
  47. package/src/internal/inspectLabels.ts +6 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/RunTrace.ts"],
4
- "sourcesContent": ["/**\n * The run trace model (factory spec 06, \"the run trace\": one card shows every\n * run).\n *\n * A run is a recursive program: the agent writes REPL cells in a code\n * container, every `ctx.call` is a durable span, and each turn is a frame. The\n * control journal already records exactly that (`@smthrs/agent` AgentSession\n * journals turn-opened, model-settled, cell-produced, cell-call-started,\n * cell-call-settled, cell-printed, cell-settled, resolved), and the gateway\n * serves it as the `run-events` projection the run card already reads. This\n * module folds those records into a span tree, run \u2192 frame \u2192 cell \u2192 call, and\n * the geometry of one bar per span on a shared time axis. No second data\n * source: what the journal does not carry (realm variables, child runs' own\n * frames) the model does not invent.\n *\n * Pure: the card renders the model, the tests read it from a fixture.\n * @since 1.0.0\n */\n\nimport { CallFact } from \"@smthrs/journal\"\nimport { CallPresentation, FlowActivity, type FlowDescriptor } from \"@smthrs/registry/Descriptor\"\nimport { Schema } from \"effect\"\nimport { callScope, openCallIndex } from \"./Diagnosis.ts\"\nimport { engineExecutionEvidence, engineTraceFromJournal } from \"./EngineTrace.ts\"\nimport { ACTION_RENDERINGS } from \"./internal/actionRenderings.ts\"\nimport { type CallEventFilter, callEventFilter, nativeStepEvent, uniqueCallEvents } from \"./internal/callEvents.ts\"\nimport { inspectLabel } from \"./internal/inspectLabels.ts\"\n\nexport { inspectLabel } from \"./internal/inspectLabels.ts\"\n\n/** One control journal record, as the run card stores it (the run-events projection's row shape).\n *\n * @category models\n * @since 1.0.0\n */\nexport interface JournalRecord {\n readonly runId?: string | undefined\n readonly sequence?: number | undefined\n readonly kind?: string | undefined\n readonly occurredAt?: number | undefined\n readonly payload?: unknown | undefined\n}\n\n/**\n * What kind of node a span is in the tree. `fork` is the row 0 of a forked run\n * (spec 06 \u00A71); no journal record folds into it yet, so no fold produces one.\n *\n * @category models\n * @since 1.0.0\n */\nexport type SpanKind =\n | \"run\"\n | \"frame\"\n | \"model\"\n | \"cell\"\n | \"call\"\n | \"approval\"\n | \"resolved\"\n | \"event\"\n | \"fork\"\n | \"execution\"\n | \"attempt\"\n\n/** What the journal said about the span; the run root wears the run's own status word.\n *\n * @category models\n * @since 1.0.0\n */\nexport type SpanStatus = \"running\" | \"completed\" | \"failed\" | \"waiting\" | \"approved\" | \"denied\" | string\n\n/** The facts the details pane shows for one span: only what its journal records carry.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface SpanDetail {\n /** The journal sequence that opened the span. */\n readonly sequence?: number | undefined\n /** The journal kind that opened the span. */\n readonly event?: string | undefined\n readonly seat?: string | undefined\n /** A cell's source text. */\n readonly source?: string | undefined\n /** What a cell printed for the next model turn. */\n readonly printed?: string | undefined\n /**\n * A call's flow name exactly as journaled. The span's `label` is its\n * display form; read call semantics from this field, never from the label.\n *\n * @since 1.0.0\n */\n readonly flowName?: string | undefined\n /** A call's input, as journaled. */\n readonly input?: unknown | undefined\n /** A call's settled value, a model's text, or a resolved text. */\n readonly output?: string | undefined\n /** A detached child's recorded execution id; only the agent/spawn result establishes this edge. */\n readonly childRunId?: string | undefined\n /** A failure's message. */\n readonly message?: string | undefined\n readonly usage?: { readonly inputTokens?: number | undefined; readonly outputTokens?: number | undefined } | undefined\n /** Every other payload field the opening record carried, as the journal bound it. */\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n}\n\n/**\n * One nested execution span with its original journal evidence.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceSpan {\n readonly id: string\n readonly kind: SpanKind\n readonly label: string\n readonly status: SpanStatus\n readonly startedAt: number\n /** Absent while the span is open. */\n readonly endedAt?: number | undefined\n readonly depth: number\n readonly children: ReadonlyArray<TraceSpan>\n readonly detail: SpanDetail\n}\n\n/** The run the trace belongs to, as the run card knows it.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceRun {\n readonly runId: string\n readonly flowId: string\n /** The run card's phase word (running, completed, failed, cancelled, waiting-approval, ...). */\n readonly status: string\n readonly kind?: string | undefined\n}\n\n/**\n * The recorded start and end of a trace in milliseconds.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceExtent {\n readonly start: number\n readonly end: number\n}\n\n/**\n * What a frame was doing, derived from what it did \u2014 never declared.\n *\n * `unrecorded` is the honest reading of a frame whose journal carries nothing\n * this fold can name: every other word here is a claim about the frame's work,\n * and a claim needs a record behind it.\n *\n * @category models\n * @since 1.0.0\n */\nexport type PhaseId = \"researching\" | \"implementing\" | \"testing\" | \"stuck\" | \"blocked\" | \"unrecorded\"\n\n/** One contiguous run of frames in one phase.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface PhaseBand {\n readonly phase: PhaseId\n readonly startedAt: number\n readonly endedAt: number\n /** Span ids of the frames in this band, in order. */\n readonly frames: ReadonlyArray<string>\n /** Journal sequence to scrub to when this band is clicked. */\n readonly seq: number\n}\n\n/** A moment a person would scrub to.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface Milestone {\n readonly seq: number\n readonly at: number\n readonly label: string\n /** `muted` is a person's stop: neither a success nor a failure. */\n readonly tone: \"warn\" | \"bad\" | \"good\" | \"brand\" | \"muted\"\n /**\n * The frame this moment was recorded under, carried through the scoped\n * merge. Two steps run at once in one journal, so the frame a milestone\n * belongs to is the one its OWN step had open, never whichever frame opened\n * last.\n */\n readonly spanId: string\n}\n\n/**\n * The frame one journal record was recorded under.\n *\n * The strip scrubs to sequences no milestone names, so the ownership rule has\n * to hold for every record, not only for the ones that mint a pin.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceOwner {\n readonly seq: number\n readonly spanId: string\n}\n\n/** What one frame did, in plain English, derived from its calls.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface FrameLine {\n readonly spanId: string\n /** Frame ordinal as shown to a person, 1-based. */\n readonly frame: number\n readonly verb: string\n /** Empty when the call's input named nothing this fold reads as a subject; the card then prints the verb alone. */\n readonly subject: string\n readonly result: string\n readonly failed: boolean\n readonly wrote: boolean\n /** Frame ordinal this repeats, set ONLY inside a stall streak. */\n readonly repeatOf?: number | undefined\n}\n\n/** A discipline event, rendered where it happened.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceNote {\n readonly seq: number\n /** Span id of the frame it attaches under. */\n readonly spanId: string\n readonly tone: \"warn\" | \"bad\" | \"good\"\n readonly title: string\n readonly body: string\n /** Quoted evidence lines, already clipped. */\n readonly evidence?: ReadonlyArray<string> | undefined\n}\n\n/** Extra options the fold takes; every field optional, absent = today's behaviour.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceOptions {\n /** Plan targets are coverage requirements, never evidence that a call ran tests. */\n readonly checkTargets?: ReadonlyArray<string> | undefined\n}\n\n/**\n * The shared projection rendered by app and terminal monitors.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceModel {\n /** Source records for status and check receipts, including their settlement sequences. */\n readonly journal: ReadonlyArray<JournalRecord>\n readonly root: TraceSpan\n /** Every span in tree order, with its depth: the tree's rows and the waterfall's rows. */\n readonly rows: ReadonlyArray<TraceSpan>\n readonly extent: TraceExtent\n readonly counts: { readonly spans: number; readonly running: number; readonly failed: number }\n /** The run's frames merged into what they were doing; empty when the journal opened no frame. */\n readonly bands: ReadonlyArray<PhaseBand>\n /** The moments a person scrubs to, in journal order; empty when the journal recorded none. */\n readonly milestones: ReadonlyArray<Milestone>\n /** One line per frame that called something; a frame that called nothing has none. */\n readonly lines: ReadonlyArray<FrameLine>\n /** The discipline records that carry fields, attached where they happened. */\n readonly notes: ReadonlyArray<TraceNote>\n /** Every recorded sequence with the frame it was recorded under, in journal order. */\n readonly owners: ReadonlyArray<TraceOwner>\n}\n\n/** Mutable draft shared by the control and native journal folds; never persisted.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceBuilder {\n readonly id: string\n readonly kind: SpanKind\n label: string\n status: SpanStatus\n startedAt: number\n endedAt?: number | undefined\n readonly children: Array<TraceBuilder>\n detail: SpanDetail\n}\ntype Builder = TraceBuilder\n\nconst TERMINAL_RUN: ReadonlySet<string> = new Set([\"completed\", \"failed\", \"cancelled\", \"no-capacity\"])\n\nconst asRecord = (value: unknown): Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {}\nconst asString = (value: unknown): string | undefined => typeof value === \"string\" ? value : undefined\nconst asNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n\n/** The record's time: the agent's own `at` stamp when it carries one, the journal's otherwise (the gateway's rule). */\nconst timeOf = (record: JournalRecord, payload: Record<string, unknown>): number =>\n asNumber(payload.at) ?? asNumber(record.occurredAt) ?? 0\n\n/** One line of text for a value the journal traced, or nothing. */\nconst textOf = (value: unknown): string | undefined => {\n if (value === undefined || value === null) return undefined\n if (typeof value === \"string\") return value\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\n/** The payload fields the pane does not already show by name. */\nconst restOf = (\n payload: Record<string, unknown>,\n shown: ReadonlyArray<string>\n): Record<string, unknown> | undefined => {\n const rest: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(payload)) {\n if (shown.includes(key) || key === \"at\" || key === \"journalVersion\") continue\n rest[key] = value\n }\n return Object.keys(rest).length === 0 ? undefined : rest\n}\n\nconst builder = (\n id: string,\n kind: SpanKind,\n label: string,\n status: SpanStatus,\n startedAt: number,\n detail: SpanDetail\n): Builder => ({ id, kind, label, status, startedAt, children: [], detail })\n\n/*\n * What the frame was DOING.\n *\n * Same discipline as the tree above, held one level closer to the reader:\n * every word below is read off a journal record, never off what the model said\n * it would do. A frame's line comes from the calls it made; its phase comes\n * from those calls and from the controller's own observations of the tree; a\n * note is a discipline record's own fields, quoted. Nothing here counts what\n * the journal may be missing, and a frame the journal says nothing about gets\n * nothing said about it.\n */\n\n/**\n * What a recorded call means: what it did, and how it reads.\n *\n * The rows, the phase bands and the run header all read a call through this\n * one answer, so they cannot tell three different stories about one record.\n *\n * @category models\n * @since 1.0.0\n */\nexport type CallMetadata = Pick<FlowDescriptor, \"activity\" | \"presentation\">\n\n/** Compatibility for journals whose descriptors predate presentation metadata. */\nconst legacy = (\n activity: FlowActivity | undefined,\n pending: string,\n success: string,\n failure: string,\n subject: CallPresentation[\"subject\"],\n result: CallPresentation[\"result\"]\n): CallMetadata => ({\n ...(activity === undefined ? {} : { activity }),\n presentation: { verb: { pending, success, failure }, subject, result }\n})\n\nconst LEGACY_PRESENTATION: ReadonlyMap<string, CallMetadata> = new Map([\n // `bash` has no compatibility activity for the same reason `@smthrs/std`\n // declares none: what a shell call does is in the command, which the rule\n // below reads off the record.\n [\"bash\", legacy(undefined, \"running\", \"ran\", \"failed to run\", \"command\", \"command\")],\n [\"test\", legacy(\"tests\", \"running\", \"ran\", \"failed to run\", \"selection\", \"tests\")],\n [\"edit\", legacy(\"writes\", \"editing\", \"edited\", \"failed to edit\", \"path\", \"edit\")],\n [\"write\", legacy(\"writes\", \"writing\", \"wrote\", \"failed to write\", \"path\", \"write\")],\n [\"apply_patch\", legacy(\"writes\", \"patching\", \"patched\", \"failed to patch\", \"patch\", \"patch\")],\n [\"read\", legacy(\"reads\", \"reading\", \"read\", \"failed to read\", \"path\", \"read\")],\n [\"grep\", legacy(\"reads\", \"searching\", \"searched\", \"failed to search\", \"pattern\", \"matches\")],\n [\"glob\", legacy(\"reads\", \"listing\", \"listed\", \"failed to list\", \"pattern\", \"paths\")],\n [\"ls\", legacy(\"reads\", \"listing\", \"listed\", \"failed to list\", \"path\", \"entries\")]\n])\n\n/** Read only the descriptor's validated display fields; a call input is never metadata. */\nconst recordedMetadata = (value: unknown, flowName: string): CallMetadata | undefined => {\n const descriptor = asRecord(value)\n if (descriptor.name !== flowName) return undefined\n if (descriptor.activity === undefined && descriptor.presentation === undefined) return undefined\n const activity = Schema.is(FlowActivity)(descriptor.activity) ? descriptor.activity : undefined\n const presentation = Schema.is(CallPresentation)(descriptor.presentation) ? descriptor.presentation : undefined\n return { activity, presentation }\n}\n\n/**\n * The name a queued checkpoint mint carries (`QuickJSSandbox` `checkpointFlow`).\n * A mint journals `control.agent.checkpoint-minted` and never a call, so no\n * call in a journal wears this name today; the dominant-call rule skips it\n * anyway, so a host that binds a flow by that name cannot make a frame's\n * headline read as bookkeeping.\n */\nconst CHECKPOINT_FLOW = \"checkpoint\"\n\n/** The command line a call ran, for the flows that run one. */\nconst commandOf = (input: unknown): string | undefined => {\n const fields = asRecord(input)\n return asString(fields.command) ?? asString(fields.script)\n}\n\n/** The last segment of a path: the name a person calls the file. */\nconst basename = (path: string): string => path.split(\"/\").filter((part) => part !== \"\").pop() ?? path\n\n/**\n * The files a V4A patch names (`@smthrs/std` ApplyPatch's `*** Add File: `,\n * `*** Delete File: ` and `*** Update File: ` markers).\n *\n * `apply_patch` carries its entire patch in one `input` string, and the patch\n * is not the subject: what it patches is. A string that is not a patch names no\n * files and yields none, so a flow that happens to call its field `input` is\n * not mistaken for one.\n */\nconst patchedPaths = (patch: string): ReadonlyArray<string> => {\n const paths: Array<string> = []\n for (const line of patch.split(\"\\n\")) {\n const named = /^\\*\\*\\* (?:Add|Delete|Update) File:\\s*(\\S.*)$/.exec(line.trim())?.[1]\n if (named !== undefined) paths.push(named.trim())\n }\n return paths\n}\n\n/**\n * Several files in the room one name has: the first named, the rest counted.\n *\n * A multi-file patch's line and a frame's write pin both say it through here,\n * so `views.py +1` means one thing wherever the card prints it. The count is a\n * fact the journal carried, never an estimate. No file, no words.\n */\nconst filesLabel = (paths: ReadonlyArray<string>): string => {\n const first = paths[0]\n if (first === undefined) return \"\"\n return paths.length === 1 ? basename(first) : `${basename(first)} +${paths.length - 1}`\n}\n\n/** The files an edit-like call names: its `path`, or every file its patch names. */\nconst writtenPaths = (input: unknown): ReadonlyArray<string> => {\n const fields = asRecord(input)\n const path = asString(fields.path)\n if (path !== undefined) return [path]\n const patch = asString(fields.input)\n return patch === undefined ? [] : patchedPaths(patch)\n}\n\n/**\n * What one recorded call was about, in the shape its declaration chose.\n *\n * Exported because the run header names the same subject as the row beneath\n * it: two readings of one input is two answers to one question.\n *\n * @param input the call input, as journaled\n * @param format the declared subject field, when the declaration named one\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const callSubject = (input: unknown, format?: CallPresentation[\"subject\"]): string => {\n const fields = asRecord(input)\n if (format === \"none\") return \"\"\n if (format === \"path\") return asString(fields.path) === undefined ? \"\" : basename(fields.path as string)\n if (format === \"command\") return commandOf(input) ?? \"\"\n if (format === \"patch\") return filesLabel(patchedPaths(asString(fields.input) ?? \"\"))\n if (format === \"pattern\") return asString(fields.pattern) ?? \"\"\n if (format === \"selection\") return stringList(fields.selection)?.join(\" \") ?? \"\"\n const path = asString(fields.path)\n if (path !== undefined) return basename(path)\n const command = commandOf(input)\n if (command !== undefined) return command\n const patch = asString(fields.input)\n if (patch !== undefined) {\n // The patch is not the subject; the files it patches are.\n const files = filesLabel(patchedPaths(patch))\n if (files !== \"\") return files\n }\n // `test` names what it selected (`@smthrs/std` TestRun `Input.selection`).\n // An omitted selection means the record named nothing; that the flow would\n // then run everything is the flow's default, not a fact this record carries.\n const selection = Array.isArray(fields.selection)\n ? fields.selection.filter((one): one is string => typeof one === \"string\")\n : undefined\n if (selection !== undefined && selection.length > 0) return selection.join(\" \")\n return asString(fields.pattern) ?? \"\"\n}\n\n/**\n * Legacy shell journals have no structured activity. Recognize only direct\n * invocations of known runners. Shell composition, expansion and quoted\n * programs remain unknown. Arguments can narrow a check without changing\n * its activity; no command here establishes a plan's required coverage.\n */\nconst shellActivity = (command: string): FlowActivity => {\n if (/[;&|<>`$\\n\\r]/.test(command)) return \"other\"\n const words = command.trim().split(/\\s+/)\n const first = words[0]!\n if ([\"pytest\", \"vitest\", \"jest\"].includes(first)) return \"tests\"\n if (/^python[23]?$/.test(first) && words[1] === \"-m\" && [\"pytest\", \"unittest\"].includes(words[2] ?? \"\")) {\n return \"tests\"\n }\n if (first === \"bun\" && words[1] === \"test\") return \"tests\"\n if ([\"pnpm\", \"npm\", \"bun\"].includes(first)) {\n if (words[1] === \"test\" || (words[1] === \"run\" && words[2] === \"test\")) return \"tests\"\n if (words[1] === \"exec\" && [\"vitest\", \"jest\"].includes(words[2] ?? \"\")) return \"tests\"\n if (words[1] === \"run\" && [\"check\", \"typecheck\", \"lint\"].includes(words[2] ?? \"\")) return \"checks\"\n }\n if (first === \"go\" && words[1] === \"test\") return \"tests\"\n if (first === \"cargo\" && words[1] === \"test\") return \"tests\"\n if (first === \"tsc\") return \"checks\"\n return \"other\"\n}\n\n/**\n * The one reading of a recorded call's semantics, shared by the rows, the\n * phase bands and the run header.\n *\n * Precedence, and why: the record's own `descriptor` wins, because it is what\n * the declaration said when the call was made, and only a record that carries\n * none falls back to {@link LEGACY_PRESENTATION}, which is a guess about the\n * flows that were journaled before a declaration could say anything. A flow the\n * table does not know stays unknown, and unknown is said as unknown.\n *\n * `bash` is the one activity read off the call rather than the declaration.\n * `@smthrs/std` declares none for it on purpose \u2014 the same flow runs a test\n * suite, a type check and `cat` \u2014 so a recognised runner in the recorded\n * command is the only thing that names the activity, and an explicit\n * declaration still outranks it.\n *\n * @param flowName the flow the record names\n * @param payload the `cell-call-started` payload, as journaled\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const callSemantics = (\n flowName: string,\n payload: Record<string, unknown>\n): CallMetadata => {\n const recorded = recordedMetadata(payload.descriptor, flowName)\n const metadata = recorded ?? LEGACY_PRESENTATION.get(flowName)\n const activity = metadata?.activity\n ?? (flowName === \"bash\" ? shellActivity(commandOf(payload.input) ?? \"\") : undefined)\n return {\n ...(activity === undefined ? {} : { activity }),\n ...(metadata?.presentation === undefined ? {} : { presentation: metadata.presentation })\n }\n}\n\nconst stringList = (value: unknown): ReadonlyArray<string> | undefined =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\") ? value : undefined\n\nconst countOf = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n\nconst counted = (value: number, noun: string, plural = `${noun}s`): string => `${value} ${value === 1 ? noun : plural}`\n\n/** Known output fields only. Unknown objects remain in the call's raw output. */\nconst resultOf = (value: unknown, format?: CallPresentation[\"result\"]): string => {\n if (format === \"none\") return \"\"\n if (typeof value === \"string\") return clip(value) ?? \"\"\n const fields = asRecord(value)\n if (fields.truncated === true && typeof fields.digest === \"string\") return \"\"\n switch (format) {\n case \"read\": {\n const start = countOf(fields.startLine)\n const end = countOf(fields.endLine)\n return start !== undefined && start > 0 && end !== undefined && end >= start - 1\n ? counted(end - start + 1, \"line\") :\n \"\"\n }\n case \"write\":\n return countOf(fields.bytesWritten) === undefined ? \"\" : counted(fields.bytesWritten as number, \"byte\")\n case \"edit\":\n return countOf(fields.replacements) === undefined ? \"\" : counted(fields.replacements as number, \"replacement\")\n case \"patch\": {\n const groups = [stringList(fields.added), stringList(fields.modified), stringList(fields.deleted)]\n return groups.every((group) => group !== undefined) ? counted(new Set(groups.flat()).size, \"file\") : \"\"\n }\n case \"tests\": {\n const passed = countOf(fields.passed)\n const failed = stringList(fields.failed)\n if (fields.parsed === true && passed !== undefined && failed !== undefined && fields.invalidProbe === undefined) {\n const exit = countOf(fields.exitCode)\n return `${passed} passed${\n failed.length > 0 ? ` \u00B7 ${failed.length} failed` : exit !== undefined && exit !== 0 ? ` \u00B7 exit ${exit}` : \"\"\n }`\n }\n return countOf(fields.exitCode) === undefined ? \"\" : `exit ${fields.exitCode}`\n }\n case \"command\":\n return countOf(fields.exitCode) === undefined ? \"\" : `exit ${fields.exitCode}`\n case \"matches\":\n return Array.isArray(fields.matches) ? counted(fields.matches.length, \"match\", \"matches\") : \"\"\n case \"paths\":\n return stringList(fields.paths) === undefined\n ? \"\"\n : counted((fields.paths as ReadonlyArray<string>).length, \"file\")\n case \"entries\":\n return Array.isArray(fields.entries) ? counted(fields.entries.length, \"entry\", \"entries\") : \"\"\n default:\n return \"\"\n }\n}\n\n/** A note body from the sentences the payload carried; a field the record omitted contributes nothing. */\nconst bodyOf = (...sentences: ReadonlyArray<string | undefined>): string =>\n sentences.filter((sentence) => sentence !== undefined).join(\" \")\n\n/** One quoted line of evidence, bounded the way the turn list bounds prose. */\nconst clip = (value: unknown): string | undefined => {\n const line = asString(value)\n if (line === undefined || line === \"\") return undefined\n return line.length <= 160 ? line : `${line.slice(0, 159).trimEnd()}\u2026`\n}\n\n/** One call a frame made, as the journal opened and settled it. */\ninterface CallFacts {\n readonly flowName: string\n readonly callId?: string | undefined\n readonly input: unknown\n readonly activity?: FlowActivity | undefined\n readonly presentation?: CallPresentation | undefined\n /**\n * What a repeat is judged by: the flow and the input exactly as journaled. A\n * field the trail truncated still canonicalizes to its own digest, so a\n * repeat of a huge input is still recognised as one.\n */\n readonly signature: string\n settled?:\n | { readonly failed: boolean; readonly result: string; readonly denied: boolean; readonly value: unknown }\n | undefined\n /** What a repeat is matched on: the signature and the settlement. */\n reading?: string | undefined\n}\n\n/** What one frame did, as its own records said it. */\ninterface FrameFacts {\n readonly id: string\n readonly frame: number\n readonly seq: number\n readonly startedAt: number\n endedAt: number\n blocked: boolean\n /** `control.agent.mutation-observed`'s answer; absent when the frame closed on none. */\n mutated?: boolean | undefined\n /** A measured tree comparison outranks declared writes and successful no-op calls. */\n observedMutation?: boolean | undefined\n /** The write pin this frame minted: where it sits in the milestones, and every file it counts. */\n wrote?: { readonly milestone: number; readonly paths: Array<string> } | undefined\n readonly calls: Array<CallFacts>\n}\n\n/** Whether the frame made an edit-like call the journal recorded settling successfully. */\nconst madeAWrite = (entry: FrameFacts): boolean =>\n entry.calls.some((call) => call.activity === \"writes\" && call.settled?.failed === false && !call.settled.denied)\n\n/**\n * The call a frame's line is about: a change it made, else the check it ran,\n * else the first thing it asked for.\n *\n * The phase rules and the lines read the same answer, so the two can never\n * disagree about whether the journal said anything about a frame at all.\n */\nconst dominantCall = (entry: FrameFacts): CallFacts | undefined =>\n entry.calls.find((one) => one.activity === \"writes\")\n ?? entry.calls.find((one) => one.activity === \"checks\" || one.activity === \"tests\")\n ?? entry.calls.find((one) => one.flowName !== CHECKPOINT_FLOW)\n\n/**\n * Folds the journal a second time, into what a person would say the run was\n * doing: its phase bands, its milestones, one line per frame, and the\n * discipline notes.\n *\n * Read off the RECORDS rather than off the spans the fold above builds, for\n * three reasons. The spans keep a settled value as text (`textOf`), so an\n * `ask` denial would have to be parsed back out of JSON. An unrecognised\n * kind's span hangs off `cell ?? frame ?? root`, so the frame a note belongs\n * to would have to be recovered from tree position. And that span shape is the\n * fold's `default` arm: the day a kind gains a case of its own, notes read off\n * `detail.fields` would vanish without a word, while notes read off the\n * records keep working.\n *\n * @param runId the run, for the notes that land before any frame opened\n * @param ordered the journal, in sequence order, call events already deduplicated\n */\ninterface DisciplineState {\n readonly runId: string\n readonly frames: Array<FrameFacts>\n readonly notes: Array<TraceNote>\n readonly milestones: Array<Milestone>\n readonly owners: Array<TraceOwner>\n readonly open: Array<CallFacts>\n frame: FrameFacts | undefined\n lastAt: number\n /** Each frame's line as last built, reused while its inputs are the same objects. */\n readonly lineOf: WeakMap<FrameFacts, {\n readonly call: CallFacts\n readonly settled: CallFacts[\"settled\"]\n readonly repeatOf: number | undefined\n readonly line: FrameLine\n }>\n}\n\nconst disciplineInit = (runId: string): DisciplineState => ({\n runId,\n frames: [],\n notes: [],\n milestones: [],\n owners: [],\n open: [],\n frame: undefined,\n lastAt: 0,\n lineOf: new WeakMap()\n})\n\n/** One record of the discipline fold; the state is advanced in place. */\nconst disciplineStep = (state: DisciplineState, record: JournalRecord): void => {\n const { runId, frames, notes, milestones, owners, open } = state\n let frame = state.frame\n /** Where a discipline record attaches: the open frame, else the run itself. */\n const here = (): string => frame?.id ?? `run:${runId}`\n const note = (\n seq: number,\n tone: TraceNote[\"tone\"],\n title: string,\n body: string,\n evidence: ReadonlyArray<string | undefined>\n ): void => {\n const quoted = evidence.filter((line): line is string => line !== undefined)\n notes.push({ seq, spanId: here(), tone, title, body, ...(quoted.length === 0 ? {} : { evidence: quoted }) })\n }\n /** A moment, owned by the frame that recorded it, exactly the way a note is. */\n const pin = (seq: number, at: number, label: string, tone: Milestone[\"tone\"]): void => {\n milestones.push({ seq, at, label, tone, spanId: here() })\n }\n\n {\n const kind = record.kind ?? \"\"\n const payload = asRecord(record.payload)\n const at = timeOf(record, payload)\n const seq = record.sequence ?? 0\n state.lastAt = Math.max(state.lastAt, at)\n if (frame !== undefined) frame.endedAt = Math.max(frame.endedAt, at)\n switch (kind) {\n case \"control.agent.turn-opened\": {\n frame = {\n id: `frame-${frames.length + 1}`,\n frame: frames.length + 1,\n seq,\n startedAt: at,\n endedAt: at,\n blocked: false,\n calls: []\n }\n frames.push(frame)\n break\n }\n case \"control.agent.cell-call-started\": {\n const flowName = asString(payload.flowName) ?? \"\"\n const metadata = callSemantics(flowName, payload)\n const call: CallFacts = {\n flowName,\n callId: asString(payload.callId),\n input: payload.input,\n activity: metadata.activity,\n presentation: metadata.presentation,\n signature: `${flowName} ${textOf(payload.input) ?? \"\"}`\n }\n open.push(call)\n // A call journaled outside a frame belongs to no frame, and the tree\n // above puts it on the run. It is still open work, so it still pairs.\n frame?.calls.push(call)\n break\n }\n case \"control.agent.cell-call-settled\": {\n if (payload.outcome !== \"success\" && payload.outcome !== \"failure\") break\n const index = openCallIndex(open, asString(payload.callId), asString(payload.flowName))\n const call = index < 0 ? undefined : open.splice(index, 1)[0]\n if (call === undefined) break\n const failed = asString(payload.outcome) === \"failure\"\n // `ask` settles SUCCESSFULLY with the person's answer (`AgentSession`\n // answers `{ answer, approved }`), so a refusal is a denial and not a\n // failure. That is the call that settles with a denial.\n const denied = !failed && asRecord(payload.value).approved === false\n call.settled = {\n failed,\n result: (failed ? textOf(payload.message) : textOf(payload.value)) ?? \"\",\n denied,\n value: payload.value\n }\n if (denied && frame !== undefined) frame.blocked = true\n // A write is the fastest thing a run does, so its band is always too\n // narrow to carry a label, and its own marker is the only way to reach\n // the moment that matters most.\n if (!failed && !denied && call.activity === \"writes\") {\n // A pin is its label, so a pin with none is a marker nobody can read\n // and nobody can tell from the next one. The journal gave this call\n // no file; no file, no pin.\n const paths = [...new Set(writtenPaths(call.input))]\n const minted = frame?.wrote\n if (minted !== undefined) {\n // A frame's writes are ONE moment. A frame that edits fifteen files\n // does it inside a second, so a pin per file is fifteen names\n // stacked over a point on the axis nobody can aim between. The pin\n // stays where the frame started writing, on the file it names, and\n // counts the rest; a file written twice is still one file.\n for (const path of paths) if (!minted.paths.includes(path)) minted.paths.push(path)\n milestones[minted.milestone] = { ...milestones[minted.milestone]!, label: filesLabel(minted.paths) }\n } else if (paths.length > 0) {\n // A write journaled outside a frame has no frame to be counted\n // into, so it stays a moment of its own.\n if (frame !== undefined) frame.wrote = { milestone: milestones.length, paths }\n pin(seq, at, filesLabel(paths), \"brand\")\n }\n }\n break\n }\n case \"control.agent.mutation-observed\": {\n const mutated = payload.mutated === true\n if (frame !== undefined) frame.mutated = mutated\n if (frame !== undefined && payload.basis === \"observed\" && typeof payload.mutated === \"boolean\") {\n frame.observedMutation = payload.mutated\n }\n // Written for every frame, so only a frame that changed something is\n // worth a note. `basis` is the body because a `declared` answer is\n // paperwork and an `observed` one is a fact about the tree, and a\n // reader must not have to guess which one they are holding. `paths` is\n // a COUNT of what the measurement covered, not the paths themselves,\n // so it is not quotable evidence and is not quoted.\n if (mutated) {\n note(\n seq,\n asString(payload.basis) === \"observed\" ? \"good\" : \"warn\",\n \"changed\",\n asString(payload.basis) ?? \"\",\n []\n )\n }\n break\n }\n case \"control.agent.permission-required\": {\n if (frame !== undefined) frame.blocked = true\n pin(seq, at, \"permission\", \"warn\")\n break\n }\n case \"control.agent.suspended\": {\n if (frame !== undefined) frame.blocked = true\n break\n }\n case \"control.agent.checkpoint-minted\": {\n note(seq, \"good\", \"checkpoint\", asString(payload.ref) ?? \"\", [])\n break\n }\n case \"control.agent.read-only-demanded\": {\n // The caps are this run's own armed numbers, read off the payload: a\n // host overrides any of them, so a constant here would print a number\n // the run never used.\n const streak = asNumber(payload.streak)\n const cap = asNumber(payload.cap)\n const nextFrame = asNumber(payload.nextFrame)\n const nextAction = asString(payload.nextAction)\n note(\n seq,\n \"warn\",\n \"read-only\",\n bodyOf(\n streak === undefined || cap === undefined ? undefined : `${streak} of ${cap} frames changed nothing.`,\n nextFrame === undefined || nextAction === undefined ? undefined : `Frame ${nextFrame}: ${nextAction}.`\n ),\n []\n )\n pin(seq, at, \"read-only\", \"warn\")\n break\n }\n case \"control.agent.repeat-demanded\": {\n const spent = asNumber(payload.frames)\n const cap = asNumber(payload.cap)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"warn\",\n \"repeat\",\n bodyOf(\n spent === undefined || cap === undefined ? undefined : `${spent} of ${cap} frames repeated calls.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n []\n )\n pin(seq, at, \"repeat\", \"warn\")\n break\n }\n case \"control.agent.narrowed-demanded\": {\n const flow = asString(payload.flow)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"bad\",\n \"narrowed\",\n bodyOf(\n flow === undefined ? undefined : `${flow} ran narrower than the reading it stands in for.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n [clip(payload.broader), clip(payload.narrower)]\n )\n pin(seq, at, \"narrowed\", \"bad\")\n break\n }\n case \"control.agent.unmoved-demanded\": {\n const nextFrame = asNumber(payload.nextFrame)\n // Both digests or neither: one alone cannot tell an unmoved tree from a\n // measurement that never happened, and either may be the empty string.\n const opened = clip(payload.openedDigest)\n const current = clip(payload.currentDigest)\n note(\n seq,\n \"bad\",\n \"unmoved\",\n bodyOf(\n \"The tree the run opened on is the tree it closed on.\",\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n opened === undefined || current === undefined ? [] : [opened, current]\n )\n pin(seq, at, \"unmoved\", \"bad\")\n break\n }\n case \"control.agent.unresolved-demanded\": {\n const flow = asString(payload.flow)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"bad\",\n \"unresolved\",\n bodyOf(\n flow === undefined ? undefined : `${flow} failed and was not answered.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n [clip(payload.failed), clip(payload.instead)]\n )\n pin(seq, at, \"unresolved\", \"bad\")\n break\n }\n case \"control.agent.claim-demanded\": {\n // Written on EVERY evaluation, and a reading that neither handed the\n // completion back nor refused it cost the run nothing and changed\n // nothing, so only those two are moments anyone would scrub to. A\n // refusal is the larger of them: it ends the run and takes its answer.\n if (payload.demanded !== true && payload.refused !== true) break\n const complete = asNumber(payload.complete)\n const overclaims = asNumber(payload.overclaims)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"bad\",\n payload.refused === true ? \"claim refused\" : \"claim\",\n bodyOf(\n complete === undefined || overclaims === undefined\n ? undefined\n : `complete ${complete}, overclaims ${overclaims}.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n []\n )\n pin(seq, at, payload.refused === true ? \"claim refused\" : \"claim\", \"bad\")\n break\n }\n /*\n * The five kinds `AgentSession`'s `default` arm once journaled with\n * `payload: {}`, however rich their `AgentEvent` schema was:\n * cell-rejected-in-frame, read-only-demand-issued,\n * narrow-only-demanded, steering-drained and sufficiency-observed.\n * Their whole payload is late (`AgentSession` `lateFields`), so one\n * record carries every field or none, and each arm below reads what its\n * record has: a legacy record still folds, and still says nothing the\n * record does not carry. A note with no body and no evidence is a title\n * on its own, so a fieldless record writes none.\n */\n case \"control.agent.cell-rejected-in-frame\": {\n // A refused reply is a model call the frame paid for. The code is why\n // the parse refused it; the message is what the frame said back.\n const attempt = asNumber(payload.attempt)\n const code = asString(payload.code)\n const body = bodyOf(\n code === undefined ? undefined : `${code}.`,\n attempt === undefined ? undefined : `Attempt ${attempt}.`\n )\n if (body !== \"\") note(seq, \"warn\", \"rejected\", body, [clip(payload.message)])\n break\n }\n case \"control.agent.read-only-demand-issued\": {\n // The issuance's own numbers. `read-only-demanded` above carries the\n // same demand's later answer, and a run that crashes between the two\n // boundaries still has this one.\n const streak = asNumber(payload.streak)\n const cap = asNumber(payload.cap)\n const nextFrame = asNumber(payload.nextFrame)\n const body = bodyOf(\n streak === undefined || cap === undefined ? undefined : `${streak} of ${cap} frames changed nothing.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n )\n if (body !== \"\") note(seq, \"warn\", \"read-only\", body, [])\n pin(seq, at, \"read-only\", \"warn\")\n break\n }\n case \"control.agent.narrow-only-demanded\": {\n // The sibling of `narrowed-demanded`: that one fires when a broader\n // reading exists and was not re-run, this one when none was ever\n // taken. There is no broader input to quote, so the subjects the\n // demand is about stand in its place.\n const flow = asString(payload.flow)\n const targets = Array.isArray(payload.targets)\n ? payload.targets.filter((one): one is string => typeof one === \"string\")\n : []\n const nextFrame = asNumber(payload.nextFrame)\n const body = bodyOf(\n flow === undefined || targets.length === 0\n ? undefined\n : `${flow} ran on ${targets.join(\", \")} and nothing broader.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n )\n if (body !== \"\") note(seq, \"warn\", \"narrow-only\", body, [clip(payload.check)])\n pin(seq, at, \"narrow-only\", \"warn\")\n break\n }\n case \"control.agent.steering-drained\": {\n // A drain is written at every frame boundary, and the queue is empty\n // at almost all of them. Only messages ON the record establish that a\n // person reached the run, so an empty drain is not a moment and a\n // legacy record \u2014 which carries no messages either way \u2014 cannot be\n // read as one. A steer too large to trace was still delivered; the\n // record says so even where its words are gone.\n const messages = Array.isArray(payload.messages) ? payload.messages : []\n if (messages.length === 0) break\n note(\n seq,\n \"warn\",\n \"steering\",\n messages.length === 1 ? \"1 steer.\" : `${messages.length} steers.`,\n messages.map((message) => clip(asRecord(message).text))\n )\n pin(seq, at, \"steering\", \"warn\")\n break\n }\n case \"control.agent.sufficiency-observed\": {\n // The one observation that rewards a run rather than braking it: a\n // failing check answered by a passing one. The two inputs are the\n // whole of it, so they are quoted.\n const flow = asString(payload.flow)\n const nextFrame = asNumber(payload.nextFrame)\n const body = bodyOf(\n flow === undefined ? undefined : `${flow} failed before the change and passed after it.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n )\n if (body !== \"\") note(seq, \"good\", \"sufficiency\", body, [clip(payload.failed), clip(payload.passed)])\n pin(seq, at, \"sufficiency\", \"good\")\n break\n }\n case \"control.run.completed\":\n case \"control.run.failed\":\n case \"control.run.cancelled\": {\n const verdict = kind.slice(\"control.run.\".length)\n // A person's stop reads as the product word every surface uses, and\n // is never drawn as a failure.\n if (verdict === \"cancelled\") pin(seq, at, \"stopped\", \"muted\")\n else pin(seq, at, verdict, verdict === \"completed\" ? \"good\" : \"bad\")\n break\n }\n default:\n break\n }\n // After the record's own arm, so a turn-opened belongs to the frame it\n // opened: the rule `here()` already gives a note and a pin.\n owners.push({ seq, spanId: here() })\n }\n state.frame = frame\n}\n\n/**\n * What {@link disciplineStep} has read so far, as the model's arrays.\n *\n * The derived rows are rebuilt from the frames; the recorded ones are copied,\n * so a model taken now never sees a record stepped after it.\n */\nconst disciplineModel = (\n state: DisciplineState\n): Pick<TraceModel, \"bands\" | \"milestones\" | \"lines\" | \"notes\" | \"owners\"> => {\n const { frames, lastAt } = state\n const notes = state.notes.slice()\n const milestones = state.milestones.slice()\n const owners = state.owners.slice()\n\n // A measured unchanged tree is authoritative even when a write succeeded.\n const changed = frames.map((entry) => entry.observedMutation ?? (entry.mutated === true || madeAWrite(entry)))\n\n // A repeated call is only evidence of a stall inside a STREAK, and only\n // across a span the workspace never moved in.\n //\n // Re-running one check after an edit is the OPPOSITE of a stall: it is the\n // answer `control.agent.sufficiency-observed` rewards. A rule that flagged\n // any second occurrence of a call would mark that good frame and a looping\n // one identically, and a rule that only checked THIS frame for a change\n // would still flag it, because the edit it answers happened in the frame\n // before. So a change resets what a first occurrence is: a call is judged\n // against the last time it ran on THIS tree, never against a run from before\n // an edit landed. On top of that a repeat counts only where the frames beside\n // it repeat too \u2014 each of them recording no change of its own \u2014 and\n // `repeatOf` is set only inside a streak of two or more such frames. Every\n // substantive call must repeat a settled reading; a fresh call, new result,\n // or pending result means this frame has not been shown to be redundant.\n const firstSeen = new Map<string, number>()\n const repeatedFrom = new Map<CallFacts, number>()\n const redundant: Array<boolean> = []\n frames.forEach((entry, index) => {\n const calls = entry.calls.filter((call) => call.flowName !== CHECKPOINT_FLOW)\n for (const call of calls) {\n if (call.settled === undefined) continue\n // A call settles once, so its reading is built once, not per model taken.\n call.reading ??= `${call.signature} ${JSON.stringify(call.settled)}`\n const reading = call.reading\n const seen = firstSeen.get(reading)\n if (seen === undefined) firstSeen.set(reading, entry.frame)\n else if (seen < entry.frame) repeatedFrom.set(call, seen)\n }\n redundant.push(calls.length > 0 && calls.every((call) => repeatedFrom.has(call)))\n // The tree moved in this frame, so every call recorded before it ran\n // against a tree that no longer exists and none of them can be repeated.\n if (changed[index] === true) firstSeen.clear()\n })\n const stalling = frames.map((_frame, index) => redundant[index] === true && changed[index] !== true)\n const stuck = stalling.map((flag, index) => flag && (stalling[index - 1] === true || stalling[index + 1] === true))\n\n // Phase, most specific rule first. The last rule is the honesty one: every\n // other word is a claim about what the frame was doing, and `researching` is\n // as much of a claim as the rest. A frame this fold cannot name one call for\n // is a frame it declines to write a line about, so it declines to name a\n // phase for it too.\n const phases = frames.map((entry, index): PhaseId =>\n entry.blocked\n ? \"blocked\"\n : stuck[index] === true\n ? \"stuck\"\n : changed[index] === true || entry.calls.some((call) => call.activity === \"writes\")\n ? \"implementing\"\n : entry.calls.some((call) => call.activity === \"checks\" || call.activity === \"tests\")\n ? \"testing\"\n : entry.calls.some((call) => call.activity === \"reads\")\n ? \"researching\"\n : \"unrecorded\"\n )\n\n const bands: Array<PhaseBand> = []\n frames.forEach((entry, index) => {\n const phase = phases[index]!\n // A frame's band ends where the next frame opens, and the last one ends\n // where the journal does: the rule the tree's own frames close by.\n const endedAt = frames[index + 1]?.startedAt ?? Math.max(entry.endedAt, lastAt)\n const last = bands[bands.length - 1]\n if (last !== undefined && last.phase === phase) {\n bands[bands.length - 1] = { ...last, endedAt, frames: [...last.frames, entry.id] }\n return\n }\n bands.push({ phase, startedAt: entry.startedAt, endedAt, frames: [entry.id], seq: entry.seq })\n })\n\n const lines = frames.flatMap((entry, index): ReadonlyArray<FrameLine> => {\n const call = dominantCall(entry)\n // A frame that called nothing has no line. Absence is absence.\n if (call === undefined) return []\n const repeatOf = stuck[index] === true ? repeatedFrom.get(call) : undefined\n const held = state.lineOf.get(entry)\n if (held !== undefined && held.call === call && held.settled === call.settled && held.repeatOf === repeatOf) {\n return [held.line]\n }\n const outcome = call.settled === undefined\n ? \"pending\"\n : call.settled.failed || call.settled.denied\n ? \"failure\"\n : \"success\"\n const line: FrameLine = {\n spanId: entry.id,\n frame: entry.frame,\n verb: call.presentation?.verb[outcome] ??\n `${call.flowName}${outcome === \"pending\" ? \" pending\" : outcome === \"failure\" ? \" failed\" : \"\"}`,\n subject: callSubject(call.input, call.presentation?.subject),\n // Read supported output fields through the descriptor's presentation.\n // The selected call retains the raw value, including unsupported shapes.\n result: call.settled?.failed === true\n ? clip(call.settled.result) ?? \"\"\n : resultOf(call.settled?.value, call.presentation?.result),\n failed: call.settled?.failed === true,\n wrote: call.activity === \"writes\" && call.settled?.failed === false && !call.settled.denied,\n ...(repeatOf === undefined ? {} : { repeatOf })\n }\n state.lineOf.set(entry, { call, settled: call.settled, repeatOf, line })\n return [line]\n })\n\n return { bands, milestones, lines, notes, owners }\n}\n\n/** The run a fold belongs to; its status is read when a model is taken. */\ntype TraceIdentity = Omit<TraceRun, \"status\">\n\n/**\n * One dispatch's span fold, advanced one record at a time.\n *\n * Every field is what {@link foldStep} has read so far. The builders are live:\n * a model is taken by freezing them, never by handing them out.\n */\ninterface FoldState {\n readonly run: TraceIdentity\n readonly root: Builder\n frame: Builder | undefined\n cell: Builder | undefined\n frames: number\n calls: number\n seat: string | undefined\n lastAt: number\n /** Records stepped after deduplication: `ordered.length`. */\n count: number\n /** The journal's own verdict, from a `control.run.*` record. */\n verdict: string | undefined\n readonly openCalls: Array<{ readonly flowName: string; readonly callId?: string | undefined; readonly span: Builder }>\n readonly approvals: Map<string, Builder>\n readonly discipline: DisciplineState\n /** The native rows of this fold's own input, in order. */\n readonly engine: Array<JournalRecord>\n /** {@link engineTraceFromJournal} of `engine`, until another row arrives. */\n engineTrace: ReadonlyArray<Builder> | undefined\n /** The span each builder last froze to. */\n readonly frozen: WeakMap<Builder, TraceSpan>\n /**\n * The run's direct children a step may have changed since the last model.\n * Every other child is a closed subtree, and its frozen span is reused as is.\n */\n readonly dirty: Set<Builder>\n /** The run's direct child a call or approval span sits under, for {@link dirty}. */\n readonly topOf: WeakMap<Builder, Builder>\n}\n\nconst isEngineRow = (record: JournalRecord): boolean =>\n record.kind === \"control.engine.event\" || record.kind === \"control.engine.projection-gap\"\n\nconst foldInit = (run: TraceIdentity): FoldState => ({\n run,\n root: builder(`run:${run.runId}`, \"run\", `run ${run.runId} \u00B7 ${run.flowId}`, \"running\", 0, {\n ...(run.kind === undefined ? {} : { fields: { kind: run.kind } })\n }),\n frame: undefined,\n cell: undefined,\n frames: 0,\n calls: 0,\n seat: undefined,\n lastAt: 0,\n count: 0,\n verdict: undefined,\n openCalls: [],\n approvals: new Map(),\n discipline: disciplineInit(run.runId),\n engine: [],\n engineTrace: undefined,\n frozen: new WeakMap(),\n dirty: new Set(),\n topOf: new WeakMap()\n})\n\n/**\n * Folds one record, in sequence order, into a dispatch's trace.\n *\n * Frames open on `turn-opened` and close when the next opens or the run ends;\n * cells open on `cell-produced` and close on `cell-settled`; calls open on\n * `cell-call-started` under the open cell (or the frame, when a call is\n * journaled outside a cell) and settle by stable call identity the way the gateway's own\n * `run-tree` pairs them, so a call's `call-N` id is the node id the\n * `node-output` projection knows it by. A journal with no records yields the\n * run root alone, wearing the run's status: the honest empty trace.\n *\n * The same records fold a second time, into what a person would say the run\n * was doing: see {@link disciplineStep}.\n */\nconst foldStep = (state: FoldState, record: JournalRecord): void => {\n if (isEngineRow(record)) {\n state.engine.push(record)\n state.engineTrace = undefined\n }\n // route receives only the records kept by the shared call-event filter.\n const { root, openCalls, approvals, dirty, topOf } = state\n let { frame, cell, frames, calls, seat } = state\n const top = frame ?? cell\n if (top !== undefined) dirty.add(top)\n /** Marks the run's child that `span` sits under as changed. */\n const touch = (span: Builder): void => {\n // Both callers retrieve spans registered in topOf when they were opened.\n dirty.add(topOf.get(span)!)\n }\n /** Where a new span attaches: the open cell, else the open frame, else the run. */\n const parent = (): Builder => cell ?? frame ?? root\n const closeCell = (at: number, status: SpanStatus): void => {\n if (cell === undefined) return\n cell.endedAt = at\n cell.status = status\n cell = undefined\n }\n const closeFrame = (at: number): void => {\n if (frame === undefined) return\n closeCell(at, cell?.children.some((child) => child.status === \"failed\") === true ? \"failed\" : \"completed\")\n frame.endedAt = at\n frame.status = frame.children.some((child) => child.status === \"failed\") ? \"failed\" : \"completed\"\n frame = undefined\n }\n\n {\n const kind = record.kind ?? \"\"\n const payload = asRecord(record.payload)\n const at = timeOf(record, payload)\n if (state.count === 0) {\n root.startedAt = at\n state.lastAt = at\n } else state.lastAt = Math.max(state.lastAt, at)\n state.count += 1\n const opened = { sequence: record.sequence, event: kind }\n switch (kind) {\n case \"control.engine.event\":\n case \"control.engine.projection-gap\":\n case \"control.engine.projection-started\":\n case \"control.engine.projection-settled\":\n // Native records have their own identities and lifecycle. Never put\n // them under whichever agent frame happened to be open at ingestion.\n break\n case \"control.agent.turn-opened\": {\n closeFrame(at)\n frames += 1\n seat = asString(payload.seat) ?? seat\n frame = builder(\n `frame-${frames}`,\n \"frame\",\n `frame ${frames}${seat === undefined ? \"\" : ` \u00B7 ${seat}`}`,\n \"running\",\n at,\n {\n ...opened,\n ...(seat === undefined ? {} : { seat }),\n fields: restOf(payload, [\"seat\"])\n }\n )\n root.children.push(frame)\n break\n }\n case \"control.agent.model-settled\": {\n const usage = asRecord(payload.usage)\n const duration = asNumber(payload.durationMillis)\n const span = builder(\n `model-${record.sequence ?? at}`,\n \"model\",\n \"model\",\n \"completed\",\n duration === undefined ? at : at - duration,\n {\n ...opened,\n ...(seat === undefined ? {} : { seat }),\n output: textOf(payload.text),\n usage: { inputTokens: asNumber(usage.inputTokens), outputTokens: asNumber(usage.outputTokens) },\n fields: restOf(payload, [\"text\", \"usage\", \"durationMillis\"])\n }\n )\n span.endedAt = at\n ;(frame ?? root).children.push(span)\n break\n }\n case \"control.agent.cell-produced\": {\n closeCell(at, \"completed\")\n const language = asString(payload.language)\n cell = builder(\n `cell-${record.sequence ?? at}`,\n \"cell\",\n `cell${language === undefined ? \"\" : ` \u00B7 ${language}`}`,\n \"running\",\n at,\n {\n ...opened,\n source: asString(payload.text),\n fields: restOf(payload, [\"text\", \"language\"])\n }\n )\n ;(frame ?? root).children.push(cell)\n break\n }\n case \"control.agent.cell-call-started\": {\n calls += 1\n const recordedName = asString(payload.flowName)\n const flowName = recordedName ?? `call-${calls}`\n const span = builder(`call-${calls}`, \"call\", inspectLabel(flowName), \"running\", at, {\n ...opened,\n ...(recordedName === undefined ? {} : { flowName: recordedName }),\n input: payload.input,\n fields: restOf(payload, [\"flowName\", \"input\"])\n })\n openCalls.push({ flowName, callId: asString(payload.callId), span })\n topOf.set(span, frame ?? cell ?? span)\n parent().children.push(span)\n break\n }\n case \"control.agent.cell-call-settled\": {\n const index = openCallIndex(openCalls, asString(payload.callId), asString(payload.flowName))\n const settled = index < 0 ? undefined : openCalls.splice(index, 1)[0]\n if (settled === undefined) break\n const failed = asString(payload.outcome) === \"failure\"\n touch(settled.span)\n settled.span.endedAt = at\n settled.span.status = failed ? \"failed\" : \"completed\"\n settled.span.detail = {\n ...settled.span.detail,\n ...(failed ? { message: textOf(payload.message) } : { output: textOf(payload.value) }),\n ...(!failed && settled.flowName === \"agent/spawn\" && asString(asRecord(payload.value).child) !== undefined\n ? { childRunId: asString(asRecord(payload.value).child) }\n : {})\n }\n break\n }\n case \"control.agent.cell-printed\": {\n if (cell === undefined) {\n parent().children.push(\n builder(`printed-${record.sequence ?? at}`, \"event\", \"printed\", \"completed\", at, {\n ...opened,\n printed: textOf(payload.text)\n })\n )\n break\n }\n cell.detail = {\n ...cell.detail,\n printed: [cell.detail.printed, textOf(payload.text)].filter((text) => text !== undefined).join(\"\\n\")\n }\n break\n }\n case \"control.agent.cell-settled\": {\n closeCell(at, asString(payload.outcome) === \"failure\" ? \"failed\" : \"completed\")\n break\n }\n case \"control.agent.resolved\": {\n const span = builder(`resolved-${record.sequence ?? at}`, \"resolved\", \"resolved\", \"completed\", at, {\n ...opened,\n output: textOf(payload.text)\n })\n span.endedAt = at\n ;(frame ?? root).children.push(span)\n break\n }\n case \"control.approval.requested\": {\n const requestId = asString(payload.requestId) ?? `approval-${record.sequence ?? at}`\n const question = asString(payload.question)\n const span = builder(\n `approval-${requestId}`,\n \"approval\",\n `approval${question === undefined ? \"\" : ` \u00B7 ${question}`}`,\n \"waiting\",\n at,\n {\n ...opened,\n fields: restOf(payload, [\"question\", \"requestId\", \"payload\", \"runId\"])\n }\n )\n approvals.set(requestId, span)\n topOf.set(span, frame ?? span)\n ;(frame ?? root).children.push(span)\n break\n }\n case \"control.approval.approved\":\n case \"control.approval.denied\": {\n const decided = kind === \"control.approval.approved\" ? \"approved\" : \"denied\"\n const key = asString(payload.tokenId) ?? asString(payload.requestId)\n const span = key === undefined\n ? [...approvals.values()].find((entry) => entry.status === \"waiting\")\n : approvals.get(key)\n if (span === undefined) break\n touch(span)\n span.status = decided\n span.endedAt = at\n break\n }\n case \"control.run.completed\":\n case \"control.run.failed\":\n case \"control.run.cancelled\": {\n closeFrame(at)\n root.endedAt = at\n // The journal's own verdict outranks the card's phase word: a scrub to this record shows the run settled.\n state.verdict = kind.slice(\"control.run.\".length)\n break\n }\n default: {\n if (!kind.startsWith(\"control.\")) break\n const span = builder(\n `event-${record.sequence ?? at}`,\n \"event\",\n kind.slice(\"control.\".length),\n \"completed\",\n at,\n {\n ...opened,\n fields: restOf(payload, [])\n }\n )\n span.endedAt = at\n parent().children.push(span)\n if (kind === \"control.agent.turn-closed\" && payload.step !== undefined) {\n const closed = frame\n closeFrame(at)\n if (closed !== undefined && payload.outcome === \"suspended\") closed.status = \"waiting\"\n if (closed !== undefined && payload.outcome === \"aborted\") closed.status = \"cancelled\"\n }\n }\n }\n }\n Object.assign(state, { frame, cell, frames, calls, seat })\n const after = frame ?? cell\n if (after !== undefined) dirty.add(after)\n disciplineStep(state.discipline, record)\n}\n\n/**\n * The trace {@link foldStep} has read so far, as the run with `status` would\n * show it.\n *\n * Nothing live is mutated. A settled run closes its open frame where the\n * journal ends, so that close is applied to the frozen copy only.\n */\nconst foldModel = (\n state: FoldState,\n status: string,\n journal: ReadonlyArray<JournalRecord>,\n engine?: ReadonlyArray<Builder>\n): TraceModel => {\n const { root, frame, cell, lastAt } = state\n const closed = new Map<Builder, { readonly status: SpanStatus; readonly endedAt: number }>()\n const statusOf = (node: Builder): SpanStatus => closed.get(node)?.status ?? node.status\n // A settled run leaves no frame open: the last frame ends where the journal does.\n const terminal = TERMINAL_RUN.has(status)\n if (terminal && frame !== undefined) {\n if (cell !== undefined) {\n closed.set(cell, {\n status: cell.children.some((child) => child.status === \"failed\") ? \"failed\" : \"completed\",\n endedAt: lastAt\n })\n }\n closed.set(frame, {\n status: frame.children.some((child) => statusOf(child) === \"failed\") ? \"failed\" : \"completed\",\n endedAt: lastAt\n })\n }\n if (engine === undefined && state.engineTrace === undefined) state.engineTrace = engineTraceFromJournal(state.engine)\n const children = [...root.children, ...(engine ?? state.engineTrace!)]\n closed.set(root, {\n status: state.verdict ?? status,\n endedAt: root.endedAt ?? (terminal && state.count > 0 ? lastAt : Number.NaN)\n })\n\n const freeze = (node: Builder, depth: number, members: ReadonlyArray<Builder>): TraceSpan =>\n freezeWith(node, depth, members.map((child) => freeze(child, depth + 1, child.children)))\n const freezeWith = (node: Builder, depth: number, frozenChildren: ReadonlyArray<TraceSpan>): TraceSpan => {\n const override = closed.get(node)\n const nodeStatus = override?.status ?? node.status\n const endedAt = override === undefined || Number.isNaN(override.endedAt) ? node.endedAt : override.endedAt\n const held = state.frozen.get(node)\n if (\n held !== undefined && held.depth === depth && held.label === node.label && held.status === nodeStatus &&\n held.startedAt === node.startedAt && held.endedAt === endedAt && held.detail === node.detail &&\n held.children.length === frozenChildren.length &&\n held.children.every((child, index) => child === frozenChildren[index])\n ) return held\n const span: TraceSpan = {\n id: node.id,\n kind: node.kind,\n label: node.label,\n status: nodeStatus,\n startedAt: node.startedAt,\n ...(endedAt === undefined ? {} : { endedAt }),\n depth,\n children: frozenChildren,\n detail: node.detail\n }\n state.frozen.set(node, span)\n return span\n }\n // A child no step touched since the last model is a closed subtree: its\n // frozen span stands, and nothing under it is walked again.\n const settledChild = (child: Builder): TraceSpan | undefined => {\n if (state.dirty.has(child) || closed.has(child)) return undefined\n const held = state.frozen.get(child)\n return held?.depth === 1 ? held : undefined\n }\n const frozenChildren = children.map((child) => settledChild(child) ?? freeze(child, 1, child.children))\n state.dirty.clear()\n const frozenRoot = freezeWith(root, 0, frozenChildren)\n const rows: Array<TraceSpan> = []\n const walk = (span: TraceSpan): void => {\n rows.push(span)\n for (const child of span.children) walk(child)\n }\n walk(frozenRoot)\n let start = Number.POSITIVE_INFINITY\n let end = 0\n let running = 0\n let failed = 0\n for (const span of rows) {\n start = Math.min(start, span.startedAt)\n end = Math.max(end, span.endedAt ?? span.startedAt)\n if (span.kind !== \"run\" && span.status === \"running\") running += 1\n if (span.kind !== \"run\" && span.status === \"failed\") failed += 1\n }\n const extent = state.count === 0 || !Number.isFinite(start)\n ? { start: 0, end: 0 }\n : { start, end: Math.max(end, start) }\n return {\n journal,\n root: frozenRoot,\n rows,\n extent,\n counts: { spans: rows.length - 1, running, failed },\n ...disciplineModel(state.discipline)\n }\n}\n\n/**\n * A run's trace fold, advanced one record at a time.\n *\n * {@link traceFromJournal} is {@link traceFold} over the whole journal and then\n * {@link traceFoldModel}; a live reader keeps the fold and hands it each new\n * record with {@link traceFoldStep}, so a record costs its own work rather than\n * a refold of the journal before it. The fold is mutable: stepping it consumes\n * the value it was, and a reader that needs an older trace takes a model first.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceFold {\n readonly run: Omit<TraceRun, \"status\">\n /** Every record stepped, in sequence order: the model's `journal`. */\n readonly journal: ReadonlyArray<JournalRecord>\n}\n\ninterface FoldTop extends TraceFold {\n /** Records as they arrived, so a refold sorts exactly what the batch sorts. */\n arrived: Array<JournalRecord>\n journal: Array<JournalRecord>\n filter: CallEventFilter<JournalRecord>\n base: FoldState\n groups: Map<string, FoldState>\n /** The native rows of the raw journal, read while no record names a step. */\n engine: Array<JournalRecord>\n engineTrace: ReadonlyArray<Builder> | undefined\n firstAt: number\n terminal: JournalRecord | undefined\n /**\n * The records {@link traceFoldSync} last consumed, copied so a caller that\n * grows or rewrites its own array in place is still compared to what was read.\n */\n source: ReadonlyArray<JournalRecord> | undefined\n memo: { readonly status: string; readonly model: TraceModel } | undefined\n}\n\nconst sequenceOf = (record: JournalRecord): number => record.sequence ?? 0\n\nconst TERMINAL_KINDS: ReadonlySet<string> = new Set([\n \"control.run.completed\",\n \"control.run.failed\",\n \"control.run.cancelled\"\n])\n\n/** One deduplicated record to the fold of the dispatch it was recorded under. */\nconst route = (state: FoldTop, record: JournalRecord): void => {\n // A run verdict stamped with another run's id (a child's, riding in this\n // journal) must not settle this run's trace or pin its milestone.\n if (\n record.kind?.startsWith(\"control.run.\") === true && record.runId !== undefined && record.runId !== state.run.runId\n ) {\n return\n }\n state.firstAt = Math.min(state.firstAt, timeOf(record, asRecord(record.payload)))\n if (TERMINAL_KINDS.has(record.kind ?? \"\")) state.terminal = record\n const scope = callScope(record)\n if (scope === undefined) return foldStep(state.base, record)\n let group = state.groups.get(scope)\n if (group === undefined) {\n group = foldInit(state.run)\n state.groups.set(scope, group)\n }\n foldStep(group, record)\n}\n\n/** Refolds `arrived` from nothing: the batch rules, exactly. */\nconst reseed = (state: FoldTop, arrived: Array<JournalRecord>): void => {\n const journal = [...arrived].sort((left, right) => sequenceOf(left) - sequenceOf(right))\n const filter = callEventFilter<JournalRecord>()\n for (const record of journal) filter.push(record)\n Object.assign(state, {\n arrived,\n journal,\n filter,\n base: foldInit(state.run),\n groups: new Map(),\n engine: journal.filter(isEngineRow),\n engineTrace: undefined,\n firstAt: Number.POSITIVE_INFINITY,\n terminal: undefined,\n memo: undefined\n })\n for (const record of uniqueCallEvents(journal)) route(state, record)\n}\n\n/**\n * Folds `records` into a fold that later records can be stepped onto.\n *\n * @param run the run the journal belongs to\n * @param records its journal so far, in any order\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const traceFold = (run: Omit<TraceRun, \"status\">, records: ReadonlyArray<JournalRecord> = []): TraceFold => {\n const state = {\n run: { runId: run.runId, flowId: run.flowId, ...(run.kind === undefined ? {} : { kind: run.kind }) }\n } as FoldTop\n state.source = undefined\n reseed(state, [...records])\n return state\n}\n\n/**\n * Folds one more record onto `fold`, which it returns.\n *\n * A record in sequence order costs its own work. One that arrives before a\n * sequence already stepped, or a native fact that supersedes telemetry the\n * fold already placed, refolds the journal, because the batch rules move an\n * earlier record for both.\n *\n * @param fold the fold; consumed\n * @param record the next journal record\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const traceFoldStep = (fold: TraceFold, record: JournalRecord): TraceFold => {\n const state = fold as FoldTop\n state.memo = undefined\n state.arrived.push(record)\n const last = state.journal.at(-1)\n if (last !== undefined && !(sequenceOf(record) >= sequenceOf(last))) {\n reseed(state, state.arrived)\n return fold\n }\n state.journal.push(record)\n if (isEngineRow(record)) {\n state.engine.push(record)\n state.engineTrace = undefined\n }\n const verdict = state.filter.push(record)\n if (verdict._tag === \"rewrite\") reseed(state, state.arrived)\n else if (verdict._tag === \"keep\") route(state, verdict.event)\n return fold\n}\n\n/**\n * Brings `fold` up to `records`, stepping only what it has not read.\n *\n * `records` extends the array the fold last read when every earlier element is\n * the same object; anything else, or a different run, starts a new fold. The\n * comparison is against the records the fold consumed, not the caller's array,\n * so growing or rewriting that same array in place is seen. A reader that\n * re-renders one growing journal therefore pays per new record.\n *\n * @param fold the fold the reader holds, if any; consumed\n * @param run the run the journal belongs to\n * @param records the whole journal as the reader now holds it\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const traceFoldSync = (\n fold: TraceFold | undefined,\n run: Omit<TraceRun, \"status\">,\n records: ReadonlyArray<JournalRecord>\n): TraceFold => {\n const held = fold as FoldTop | undefined\n const source = held?.source\n const extends_ = held !== undefined && source !== undefined && held.run.runId === run.runId &&\n held.run.flowId === run.flowId && held.run.kind === run.kind && records.length >= source.length &&\n source.every((record, index) => records[index] === record)\n const next = extends_ ? held : traceFold(run) as FoldTop\n for (let index = extends_ ? source.length : 0; index < records.length; index++) traceFoldStep(next, records[index]!)\n next.source = records.slice()\n return next\n}\n\n/**\n * The trace a fold has read, as the run with `status` shows it.\n *\n * Taken again without a step between, it is the same object.\n *\n * @param fold the fold\n * @param status the run card's phase word\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const traceFoldModel = (fold: TraceFold, status: string): TraceModel => {\n const state = fold as FoldTop\n if (state.memo?.status === status) return state.memo.model\n const model = mergeModel(state, status)\n state.memo = { status, model }\n return model\n}\n\nconst mergeModel = (state: FoldTop, status: string): TraceModel => {\n const journal = state.journal.slice()\n if (state.groups.size === 0) {\n if (state.engineTrace === undefined) state.engineTrace = engineTraceFromJournal(state.engine)\n return foldModel(state.base, status, journal, state.engineTrace)\n }\n const base = foldModel(state.base, status, journal)\n const children = [...base.root.children]\n const bands = [...base.bands]\n const milestones = [...base.milestones]\n const lines = [...base.lines]\n const notes = [...base.notes]\n const owners = [...base.owners]\n const terminal = state.terminal\n const terminalAt = terminal === undefined ? undefined : timeOf(terminal, asRecord(terminal.payload))\n for (const [scope, group] of state.groups) {\n const prefix = `step:${encodeURIComponent(scope)}/`\n const scoped = foldModel(group, \"running\", journal)\n const rename = (span: TraceSpan): TraceSpan => ({\n ...span,\n id: `${prefix}${span.id}`,\n children: span.children.map(rename),\n ...(span.status === \"running\" && TERMINAL_RUN.has(base.root.status) ?\n {\n // A terminal run proves work stopped. It does not prove which open\n // step succeeded or caused the run to fail.\n status: \"stopped\",\n ...(terminalAt === undefined ? {} : { endedAt: terminalAt })\n } :\n {})\n })\n children.push(...scoped.root.children.map(rename))\n bands.push(...scoped.bands.map((band) => ({ ...band, frames: band.frames.map((id) => `${prefix}${id}`) })))\n // A moment, a line, a note and a position all name the frame they were\n // recorded under, so the merge renames each of them the same way: the\n // step's own frame, or this run's root for what the step recorded outside\n // any frame.\n const owned = (spanId: string): string => spanId === scoped.root.id ? base.root.id : `${prefix}${spanId}`\n milestones.push(...scoped.milestones.map((one) => ({ ...one, spanId: owned(one.spanId) })))\n lines.push(...scoped.lines.map((line) => ({ ...line, spanId: `${prefix}${line.spanId}` })))\n notes.push(...scoped.notes.map((note) => ({ ...note, spanId: owned(note.spanId) })))\n owners.push(...scoped.owners.map((one) => ({ ...one, spanId: owned(one.spanId) })))\n }\n children.sort((left, right) =>\n left.startedAt - right.startedAt || (left.detail.sequence ?? 0) - (right.detail.sequence ?? 0)\n )\n const root = { ...base.root, startedAt: state.firstAt, children }\n const rows: Array<TraceSpan> = []\n const walk = (span: TraceSpan): void => {\n rows.push(span)\n span.children.forEach(walk)\n }\n walk(root)\n const positions = new Map(rows.map((span, index) => [span.id, index]))\n // Each step folds its own frames from 1, so a merged run would print two\n // rows numbered 1 and a `same as 1` that names either. The merged list\n // numbers the rows a person reads, and a repeat names the renumbered row of\n // the step that recorded it.\n const merged = lines.sort((left, right) => positions.get(left.spanId)! - positions.get(right.spanId)!)\n const stepOf = (spanId: string): string => spanId.slice(0, spanId.lastIndexOf(\"/\") + 1)\n const renumbered = new Map(merged.map((line, index) => [`${stepOf(line.spanId)}${line.frame}`, index + 1]))\n let start = Number.POSITIVE_INFINITY\n let end = Number.NEGATIVE_INFINITY\n for (const span of rows) {\n start = Math.min(start, span.startedAt)\n end = Math.max(end, span.endedAt ?? span.startedAt)\n }\n return {\n journal,\n root,\n rows,\n extent: { start, end },\n counts: {\n spans: rows.length - 1,\n running: rows.filter((span) => span.kind !== \"run\" && span.status === \"running\").length,\n failed: rows.filter((span) => span.kind !== \"run\" && span.status === \"failed\").length\n },\n bands: bands.sort((left, right) => left.startedAt - right.startedAt || left.seq - right.seq),\n milestones: milestones.sort((left, right) => left.seq - right.seq),\n lines: merged.map((line, index) => ({\n ...line,\n frame: index + 1,\n ...(line.repeatOf === undefined\n ? {}\n : { repeatOf: renumbered.get(`${stepOf(line.spanId)}${line.repeatOf}`)! })\n })),\n notes: notes.sort((left, right) => left.seq - right.seq),\n owners: owners.sort((left, right) => left.seq - right.seq)\n }\n}\n\n/**\n * Fold each recorded dispatch independently, keeping prompt-run addresses unchanged.\n *\n * The same fold a live reader advances with {@link traceFoldStep}, taken over\n * the whole journal at once.\n *\n * The options the card carries are accepted and read by nothing: a plan's\n * check targets are a coverage requirement, and a requirement is not evidence\n * that any call ran it. Every word this fold says is read off a record.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const traceFromJournal = (\n run: TraceRun,\n records: ReadonlyArray<JournalRecord>,\n _options: TraceOptions = {}\n): TraceModel => traceFoldModel(traceFold(run, records), run.status)\n\n/**\n * One span's bar on the shared axis, as percentages. An open span runs to the\n * axis end; an instant span is zero width and renders as a marker.\n *\n * @param span the span\n * @param extent the axis\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const waterfallGeometry = (\n span: TraceSpan,\n extent: TraceExtent\n): { readonly left: number; readonly width: number } => {\n const width = Math.max(extent.end - extent.start, 1)\n const from = span.startedAt\n const to = span.endedAt ?? extent.end\n const left = ((from - extent.start) / width) * 100\n const bar = Math.max(((to - from) / width) * 100, 0)\n return { left: Math.round(left * 100) / 100, width: Math.round(bar * 100) / 100 }\n}\n\n/**\n * The axis the phase strip measures on: the bands' own span when the journal\n * opened frames, the run's whole extent when it opened none.\n *\n * A milestone is a journal record, and the records that write one do not need a\n * frame: a journal of `read-only-demanded` and `sufficiency-observed` with no\n * `turn-opened` carries two moments and opens no band. Milestones therefore\n * survive without bands, and the axis that places them cannot be read off the\n * bands alone. The other choice \u2014 dropping a moment because no band was drawn\n * beside it \u2014 would be this fold deciding a record the journal made did not\n * happen, which is the one thing it may never do.\n *\n * @param model the trace\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const phaseExtent = (model: TraceModel): TraceExtent => {\n return model.bands.length === 0 ? model.extent : {\n start: Math.min(...model.bands.map((band) => band.startedAt)),\n end: Math.max(...model.bands.map((band) => band.endedAt))\n }\n}\n\n/**\n * One band's share of that axis, as percentages, the way the waterfall measures\n * a span.\n *\n * A run whose frames all land in one millisecond recorded no elapsed time. Read\n * against a floored axis every such band is zero wide at left 0, so the whole\n * strip collapses onto the left edge and says nothing at all. The bands' ORDER\n * is a journal fact even where their durations are not, so with no duration to\n * measure the ordinal IS the axis: equal slices, left to right.\n *\n * @param band the band\n * @param extent the axis, from {@link phaseExtent}\n * @param index the band's place in the strip\n * @param count how many bands the strip holds\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const phaseBandGeometry = (\n band: PhaseBand,\n extent: TraceExtent,\n index: number,\n count: number\n): { readonly left: number; readonly width: number } => {\n const round = (value: number): number => Math.round(value * 100) / 100\n const axis = extent.end - extent.start\n if (axis <= 0) {\n const share = 100 / Math.max(count, 1)\n return { left: round(index * share), width: round(share) }\n }\n return {\n left: round(((band.startedAt - extent.start) / axis) * 100),\n width: round((Math.max(band.endedAt - band.startedAt, 0) / axis) * 100)\n }\n}\n\n/** The flows whose spans are messages between a coordinator and its workers (spec 06 \u00A73). */\nconst MESSAGE_FLOWS: ReadonlySet<string> = new Set([\"agent/send\", \"agent/await\"])\n\n/** Whether a span, or any span under it, passes the filter.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const spanMatches = (span: TraceSpan, filter: TraceFilter): boolean => {\n const own = filter === \"all\"\n ? true\n : filter === \"running\"\n ? span.status === \"running\" || span.status === \"waiting\"\n : filter === \"failed\"\n ? span.status === \"failed\"\n : filter === \"model\"\n ? span.kind === \"model\"\n : filter === \"flow\"\n ? span.kind === \"call\" || span.kind === \"execution\" || span.kind === \"attempt\"\n : span.kind === \"call\" && MESSAGE_FLOWS.has(span.label)\n return own || span.children.some((child) => spanMatches(child, filter))\n}\n\n/** The tree's filters, in the slash grammar's words (spec 06 \u00A76: `runs.trace.filter <runId> <filter>`).\n *\n * @category models\n * @since 1.0.0\n */\nexport type TraceFilter = \"all\" | \"running\" | \"failed\" | \"model\" | \"flow\" | \"messages\"\n\n/**\n * Stable filter identifiers accepted by run trace commands.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const TRACE_FILTER_IDS: ReadonlyArray<TraceFilter> = [\n \"all\",\n \"running\",\n \"failed\",\n \"model\",\n \"flow\",\n \"messages\"\n]\n\nconst FILTER_LABELS: Readonly<Record<TraceFilter, string>> = {\n all: \"all\",\n running: \"running\",\n failed: \"failed\",\n model: \"model calls\",\n flow: \"flow calls\",\n messages: \"messages\"\n}\n\n/**\n * The filter chips a run of this kind shows (spec 06 \u00A72 and \u00A73): a prototype\n * has `all | messages | failed` and nothing else; every other run has the\n * shared set. `messages` is a prototype's conversation across workers, so it\n * is not offered elsewhere.\n *\n * @param kind the run's kind\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const traceFiltersFor = (kind: string | undefined): ReadonlyArray<readonly [TraceFilter, string]> =>\n (kind === \"prototype\"\n ? ([\"all\", \"messages\", \"failed\"] as const)\n : ([\"all\", \"running\", \"failed\", \"model\", \"flow\"] as const)).map((id) => [id, FILTER_LABELS[id]] as const)\n\n/** Whether a filter word is one the trace knows.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const isTraceFilter = (value: string): value is TraceFilter =>\n (TRACE_FILTER_IDS as ReadonlyArray<string>).includes(value)\n\n/** The two presentations of the same persisted run card.\n *\n * @category models\n * @since 1.0.0\n */\nexport type TraceView = \"turns\" | \"timeline\"\n\n/** A concise projection of one recorded turn, never a generated claim about intent or correctness.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TurnNarrative {\n readonly frame: TraceSpan\n readonly number: number\n readonly text: string\n readonly source: \"model\" | \"calls\" | \"journal\"\n}\n\n/** The first prose line outside fenced code, bounded for the cheap turn list. Full text stays in the model span. */\nconst proseLine = (text: string | undefined): string | undefined => {\n if (text === undefined) return undefined\n let fence: string | undefined\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim()\n const marker = /^(?:`{3,}|~{3,})/.exec(trimmed)?.[0]\n if (marker !== undefined) {\n if (fence === undefined) fence = marker\n else if (marker[0] === fence[0] && marker.length >= fence.length) fence = undefined\n continue\n }\n if (fence !== undefined || trimmed === \"\") continue\n // A code-only response or the journal's truncated-field object is not explanatory prose.\n if (/^(?:[[{]|(?:const|let|var|await|import|export|function|return)\\b)/.test(trimmed)) return undefined\n const words = trimmed.replace(/^#{1,6}\\s+|^[-*+]\\s+|^>\\s+/, \"\").replace(/\\s+/g, \" \")\n const sentence = words.match(/^.*?[.!?](?=\\s|$)/)?.[0] ?? `${words}.`\n return sentence.length <= 180 ? sentence : `${sentence.slice(0, 179).trimEnd()}\u2026`\n }\n return undefined\n}\n\n/** One cheap line per turn; falls back to actual call names when the model recorded only code.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const turnNarratives = (model: TraceModel): ReadonlyArray<TurnNarrative> =>\n model.root.children.filter((span) => span.kind === \"frame\").map((frame, index) => {\n const text = frame.children.filter((span) => span.kind === \"model\").map((span) => proseLine(span.detail.output))\n .find((value) => value !== undefined)\n if (text !== undefined) return { frame, number: index + 1, text, source: \"model\" }\n const names: Array<string> = []\n const walk = (span: TraceSpan): void => {\n if (span.kind === \"call\" && !names.includes(span.label)) names.push(span.label)\n for (const child of span.children) walk(child)\n }\n walk(frame)\n return names.length > 0\n ? {\n frame,\n number: index + 1,\n text: `The agent called ${names.slice(0, 3).join(\", \")}${\n names.length > 3 ? ` and ${names.length - 3} other flows` : \"\"\n }.`,\n source: \"calls\"\n }\n : {\n frame,\n number: index + 1,\n text: frame.children.some((span) => span.kind === \"cell\")\n ? \"The agent produced a script; no flow calls were recorded in this turn.\"\n : frame.children.some((span) => span.kind === \"model\")\n ? \"The model responded; no script or flow calls were recorded in this turn.\"\n : \"The turn started; no model response or flow calls have been recorded.\",\n source: \"journal\"\n }\n })\n\n/** The recorded ancestry of a selection, for breadcrumbs and the selected turn's scoped call tree.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const spanPath = (model: TraceModel, id: string): ReadonlyArray<TraceSpan> => {\n const visit = (span: TraceSpan): ReadonlyArray<TraceSpan> | undefined => {\n if (span.id === id) return [span]\n for (const child of span.children) {\n const path = visit(child)\n if (path !== undefined) return [span, ...path]\n }\n return undefined\n }\n return visit(model.root) ?? [model.root]\n}\n\n/** A duration in the trace's units: milliseconds under a second, seconds under a minute, minutes and seconds under an hour, hours and minutes after.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const durationWords = (ms: number): string => {\n if (ms < 1000) return `${Math.round(ms)}ms`\n // Round before splitting, so 59.96s reads 1m00s rather than 60.0s, and 51m59.6s reads 52m00s rather than 51m60s.\n if (ms < 59_950) return `${(ms / 1000).toFixed(1)}s`\n const total = Math.round(ms / 1000)\n if (total < 3600) {\n const minutes = Math.floor(total / 60)\n return `${minutes}m${String(total - minutes * 60).padStart(2, \"0\")}s`\n }\n const minutes = Math.round(ms / 60_000)\n const hours = Math.floor(minutes / 60)\n return `${hours}h${String(minutes - hours * 60).padStart(2, \"0\")}m`\n}\n\n/** One memory item a run's relevance readings weighed.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface MemoryItem {\n readonly id: string\n readonly kind: string\n /** How likely the item is needed: 1 \u2212 Jev's probability that it is not. */\n readonly relevance: number\n}\n\n/** The memory a run was shown and the memory Jev withheld from it.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface RunMemory {\n readonly kept: ReadonlyArray<MemoryItem>\n readonly withheld: ReadonlyArray<MemoryItem>\n}\n\nconst memoryItems = (value: unknown): ReadonlyArray<MemoryItem> =>\n Array.isArray(value) ?\n value.flatMap((raw: unknown) => {\n const item = typeof raw === \"object\" && raw !== null ? raw as Record<string, unknown> : undefined\n return item?.kind === \"memory\" && typeof item.id === \"string\" && typeof item.p === \"number\"\n ? [{ id: item.id, kind: \"memory\", relevance: 1 - item.p }]\n : []\n }) :\n []\n\n/**\n * What memory a run was brought, from the `control.agent.relevance-settled`\n * rows of its `run-events` projection: ids and probabilities, never text. A\n * reading also weighs flows, skills and instructions; only memory counts here.\n * An item any reading kept is in; one only ever withheld is withheld; both\n * most relevant first. A row whose verdicts were not retained is no reading.\n * Undefined when Jev never read for the run.\n *\n * @category folds\n * @since 1.0.0\n */\nexport const runMemoryOf = (records: ReadonlyArray<JournalRecord>): RunMemory | undefined => {\n const kept = new Map<string, MemoryItem>()\n const withheld = new Map<string, MemoryItem>()\n let read = false\n for (const record of records) {\n if (record.kind !== \"control.agent.relevance-settled\") continue\n const payload = typeof record.payload === \"object\" && record.payload !== null\n ? record.payload as Record<string, unknown>\n : {}\n if (!Array.isArray(payload.kept) && !Array.isArray(payload.withheld)) continue\n read = true\n for (const item of memoryItems(payload.kept)) kept.set(item.id, item)\n for (const item of memoryItems(payload.withheld)) withheld.set(item.id, item)\n }\n if (!read) return undefined\n const byRelevance = (left: MemoryItem, right: MemoryItem) =>\n right.relevance - left.relevance || left.id.localeCompare(right.id)\n return {\n kept: [...kept.values()].sort(byRelevance),\n withheld: [...withheld.values()].filter((item) => !kept.has(item.id)).sort(byRelevance)\n }\n}\n\n/** One recorded agent action inside an engine step, as an Inspect cell.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TranscriptCell {\n readonly id: string\n readonly kind: \"read\" | \"edit\" | \"run\" | \"think\" | \"ask\"\n label: string\n code?: string\n output?: string\n quote?: string\n tokens?: number\n took_s?: number\n tone?: \"ok\" | \"fail\" | \"live\"\n}\n\n/** What the agent did inside one engine dispatch, keyed `<execution id>:<step id>`. */\ninterface StepTranscript {\n readonly cells: Array<TranscriptCell>\n tokens: number\n models: number\n /** The task the agent was given: its first request's task system part. */\n input?: unknown\n}\n\n/** The system part an agent step's task travels in (`Agent.ts`). */\nconst TASK_PREFIX = \"The task for this run:\\n\\n\"\n\n/** The agent's task from a traced request: its own `task` field, or the task\n * part of its system text when that fit the journal. Parsed when it is JSON. */\nconst taskOf = (request: Record<string, unknown>): unknown => {\n const parts = Array.isArray(request.system) ? request.system : []\n const part = parts.find((text): text is string => typeof text === \"string\" && text.startsWith(TASK_PREFIX))\n const task = typeof request.task === \"string\" ? request.task : part?.slice(TASK_PREFIX.length)\n if (task === undefined) return undefined\n try {\n return JSON.parse(task)\n } catch {\n return task\n }\n}\n\nconst hexDigest = /^[0-9a-f]{64}$/\n\n/** A transcript cell shows an excerpt; the journal keeps the full record. */\nconst cellText = (value: unknown): string | undefined => {\n const text = textOf(value)\n return text === undefined || text.length <= 2000 ? text : `${text.slice(0, 2000)}\u2026`\n}\n\n/** The recorded presentation of a tool call: \"Read t5.md\", \"Failed to write t5.md\". */\nconst callCellLabel = (started: Extract<CallFact.Fact, { phase: \"invoked\" }>, failed: boolean): string => {\n const descriptor = asRecord(started.descriptor)\n const presentation = asRecord(descriptor.presentation)\n const verbs = asRecord(presentation.verb)\n const name = started.flowName\n const verb = asString(failed ? verbs.failure : verbs.success) ?? (failed ? `failed ${name}` : name)\n const subjectKey = asString(presentation.subject)\n const subject = subjectKey === undefined ? undefined : asString(asRecord(started.input)[subjectKey])\n const text = subject === undefined ? verb : `${verb} ${subject}`\n return text.charAt(0).toUpperCase() + text.slice(1)\n}\n\nconst callCellKind = (started: Extract<CallFact.Fact, { phase: \"invoked\" }>): TranscriptCell[\"kind\"] => {\n const activity = asString(asRecord(started.descriptor).activity)\n const name = started.flowName\n return name === \"ask\" ? \"ask\" : activity === \"reads\" ? \"read\" : activity === \"writes\" ? \"edit\" : \"run\"\n}\n\nconst decodeCallFact = Schema.decodeUnknownOption(CallFact.Fact)\n\n/** A native tool-call fact and the dispatch digest its scope names. */\nconst callFactOf = (record: JournalRecord) => {\n if (record.kind !== \"control.engine.event\") return undefined\n const envelope = asRecord(record.payload)\n if (envelope.version !== 1 || envelope.eventType !== CallFact.eventType || envelope.sourceSequence !== 0) {\n return undefined\n }\n const fact = decodeCallFact(envelope.payload)\n if (fact._tag === \"None\" || envelope.sourceId !== `call-fact-v1:${fact.value.callId}:${fact.value.phase}`) {\n return undefined\n }\n const stepId = /@([0-9a-f]{64}):\\d+#\\d+$/.exec(fact.value.identity.runId)?.[1]\n return stepId === undefined ? undefined : { stepId, fact: fact.value }\n}\n\n/**\n * The agent transcript of every native dispatch in `journal`: model replies,\n * cells with what they printed, and tool calls, in journal order. Keyed by the\n * dispatch's step key digest, which the engine's node settlement names in\n * `stepKeyDigests`. Pure over the records; no model call.\n */\nconst stepTranscripts = (journal: ReadonlyArray<JournalRecord>): ReadonlyMap<string, StepTranscript> => {\n const transcripts = new Map<string, StepTranscript>()\n const entry = (key: string) => {\n let found = transcripts.get(key)\n if (found === undefined) transcripts.set(key, found = { cells: [], tokens: 0, models: 0 })\n return found\n }\n const lastCell = new Map<string, TranscriptCell>()\n const calls = new Map<\n string,\n { readonly cell: TranscriptCell; readonly started: Extract<CallFact.Fact, { phase: \"invoked\" }> }\n >()\n for (const record of journal) {\n const sequence = record.sequence ?? 0\n const step = nativeStepEvent(record)\n if (step !== undefined) {\n const payload = asRecord(step.payload)\n // nativeStepEvent has decoded StepFact.Scope, whose stepId is a 64-digit hex string.\n const stepId = asString(asRecord(payload.step).stepId)!\n const transcript = entry(stepId)\n if (step.kind === \"control.agent.model-requested\" && transcript.input === undefined) {\n const task = taskOf(payload)\n if (task !== undefined) transcript.input = task\n } else if (step.kind === \"control.agent.model-settled\") {\n const usage = asRecord(payload.usage)\n const tokens = (asNumber(usage.inputTokens) ?? 0) + (asNumber(usage.outputTokens) ?? 0)\n const duration = asNumber(payload.durationMillis)\n const text = cellText(payload.text)\n transcript.tokens += tokens\n transcript.models += 1\n transcript.cells.push({\n id: `cell:${sequence}`,\n kind: \"think\",\n label: \"Model reply\",\n ...(text === undefined ? {} : { quote: text }),\n tokens,\n ...(duration === undefined ? {} : { took_s: Math.max(0, duration) / 1000 })\n })\n } else if (step.kind === \"control.agent.cell-produced\") {\n const code = cellText(payload.text)\n const cell: TranscriptCell = {\n id: `cell:${sequence}`,\n kind: \"run\",\n label: \"Ran a cell\",\n ...(code === undefined ? {} : { code })\n }\n transcript.cells.push(cell)\n lastCell.set(stepId, cell)\n } else if (step.kind === \"control.agent.cell-printed\") {\n const cell = lastCell.get(stepId)\n const printed = cellText(payload.text)\n if (cell !== undefined && printed !== undefined && printed !== \"\") {\n cell.output = cell.output === undefined ? printed : `${cell.output}\\n${printed}`\n }\n } else if (step.kind === \"control.agent.cell-settled\") {\n const cell = lastCell.get(stepId)\n if (cell !== undefined) cell.tone = asString(payload.outcome) === \"failure\" ? \"fail\" : \"ok\"\n }\n continue\n }\n const call = callFactOf(record)\n if (call === undefined) continue\n const handle = `${call.stepId}:${call.fact.callId}`\n if (call.fact.phase === \"invoked\") {\n const input = cellText(call.fact.input)\n const cell: TranscriptCell = {\n id: `cell:${sequence}`,\n kind: callCellKind(call.fact),\n label: callCellLabel(call.fact, false),\n ...(input === undefined ? {} : { code: input }),\n tone: \"live\"\n }\n entry(call.stepId).cells.push(cell)\n calls.set(handle, { cell, started: call.fact })\n continue\n }\n const open = calls.get(handle)\n if (open === undefined) continue\n const failed = call.fact.outcome === \"failure\"\n open.cell.label = callCellLabel(open.started, failed)\n open.cell.tone = failed ? \"fail\" : \"ok\"\n const result = failed ? cellText(call.fact.message) : cellText(call.fact.value)\n if (result !== undefined) open.cell.output = result\n }\n return transcripts\n}\n\n/** The dispatches a settled engine node drove, as `<execution id>:<step key digest>`. */\nconst nodeDispatches = (row: TraceSpan): ReadonlyArray<string> => {\n if (!row.id.startsWith(\"engine-node:\")) return []\n const fields = asRecord(row.detail.fields)\n const execution = asString(fields.executionId)\n const digests = asRecord(fields.payload).stepKeyDigests\n if (execution === undefined || !Array.isArray(digests)) return []\n return [\n ...new Set(digests.filter((digest): digest is string => typeof digest === \"string\" && hexDigest.test(digest)))\n ]\n .map((digest) => `${execution}:${digest}`)\n}\n\n/** Plan node kinds that only shape the plan (@smthrs/plan); a child flow's own nodes are its steps. */\nconst PLAN_STRUCTURE: ReadonlySet<string> = new Set([\n \"Succeed\",\n \"Fail\",\n \"All\",\n \"Race\",\n \"Map\",\n \"AndThen\",\n \"Branch\",\n \"Catch\",\n \"FlowCall\",\n \"FunctionIdentity\",\n \"PlannedReference\"\n])\n\n/** A check receipt's leading scalar fields, read from a preview the engine\n * may have cut short (its evidence comes last): `{\"checkId\":\u2026,\"status\":\u2026`. */\nconst RECEIPT_HEAD = /^\\{\"checkId\":\"[^\"\\\\]*\"(?:,\"[A-Za-z]+\":(?:\"[^\"\\\\]*\"|-?\\d+))*,\"status\":\"(passed|failed|superseded)\"/\n\n/** How many checks a step's recorded output reports failed: a check receipt\n * (`{checkId, status, \u2026}`, possibly a cut-short preview) or a list of them;\n * zero for any other output. */\nconst checkFailures = (output: string | undefined): number => {\n if (output === undefined) return 0\n const head = RECEIPT_HEAD.exec(output)\n if (head !== null) return head[1] === \"failed\" ? 1 : 0\n let value: unknown\n try {\n value = JSON.parse(output)\n } catch {\n return 0\n }\n return (Array.isArray(value) ? value : []).filter((receipt) => {\n const record = asRecord(receipt)\n return typeof record.checkId === \"string\" && record.status === \"failed\"\n }).length\n}\n\n/** Each recorded engine node's kind and action, by its trace span id (without instance). */\nconst engineNodeShapes = (journal: ReadonlyArray<JournalRecord>) => {\n const shapes = new Map<string, { kind?: string | undefined; action?: string | undefined }>()\n for (const record of journal) {\n if (record.kind !== \"control.engine.event\") continue\n const envelope = asRecord(record.payload)\n const executionId = asString(envelope.executionId)\n const generation = asNumber(envelope.generation)\n const payload = asRecord(envelope.payload)\n if (executionId === undefined || generation === undefined) continue\n const prefix = `engine-node:${encodeURIComponent(`${encodeURIComponent(executionId)}:${generation}`)}:`\n if (\n envelope.eventType === \"flows.engine.plan-recorded\" || envelope.eventType === \"flows.engine.subgraph-appended\"\n ) {\n const nodes = asRecord(payload.graph).nodes\n for (const node of Array.isArray(nodes) ? nodes : []) {\n const shape = asRecord(node)\n const id = asString(shape.id)\n if (id !== undefined) {\n shapes.set(prefix + encodeURIComponent(id), { kind: asString(shape.kind), action: asString(shape.action) })\n }\n }\n } else if (envelope.eventType === \"flows.engine.node-scheduled\") {\n const id = asString(payload.nodeId)\n if (id === undefined) continue\n const known = shapes.get(prefix + encodeURIComponent(id))\n shapes.set(prefix + encodeURIComponent(id), {\n kind: asString(payload.kind) ?? known?.kind,\n action: asString(payload.action) ?? known?.action\n })\n }\n }\n return shapes\n}\n\n/** Adapt the canonical trace to the install monitor. IDs and timestamps come\n * from recorded spans; inspection never evaluates flow bodies or presentations.\n * @since 1.0.0\n * @category constructors\n */\nexport const monitorFromJournal = (run: TraceRun, records: ReadonlyArray<JournalRecord>, at?: number) => {\n const last = records.reduce((last, row) => Math.max(last, row.sequence ?? 0), 0)\n const journal = at === undefined ? records : records.filter((row) => (row.sequence ?? 0) <= at)\n // A historical frame must not inherit the current run's terminal status.\n const lifecycleRow = [...journal].reverse().find((row) =>\n /^control\\.run\\.(running|waiting-approval|paused|suspended|held|completed|failed|cancelled|interrupted)$/.test(\n row.kind ?? \"\"\n ) &&\n (row.runId === undefined || row.runId === run.runId)\n )\n const status = at === undefined ? run.status : lifecycleRow?.kind?.split(\".\").at(-1) ?? \"running\"\n const state = (value: string): \"running\" | \"waiting\" | \"held\" | \"failed\" | \"done\" | \"interrupted\" =>\n value === \"completed\" || value === \"done\" ? \"done\" : value === \"failed\" ?\n \"failed\"\n : value === \"cancelled\" || value === \"interrupted\" ?\n \"interrupted\" :\n value === \"held\" ?\n \"held\"\n : value === \"waiting\" || value === \"waiting-approval\" || value === \"paused\" || value === \"suspended\"\n ? \"waiting\"\n : \"running\"\n const trace = traceFromJournal({ ...run, status }, journal)\n const engineLabel = (label: string) =>\n ACTION_RENDERINGS[label] === null || /^<(?:boundary:|quota-park>|structured-output-count>)/.test(label)\n const bookkeeping = (row: TraceSpan) => engineLabel(row.label)\n const transcripts = stepTranscripts(journal)\n // Every call below is a member of trace.rows, so both lookups are total.\n const dispatchesOf = new Map(trace.rows.map((row) => [row.id, nodeDispatches(row)] as const))\n // A step is a node that dispatched an action. Plan structure (sequences,\n // branches, maps) and child-flow calls, whose own nodes are the steps, are\n // never steps of their own.\n const structural = (kind: string | undefined) => kind !== undefined && PLAN_STRUCTURE.has(kind)\n const nodeShapes = engineNodeShapes(journal)\n const calls = trace.rows.filter((row) => {\n // A tool call an agent made inside a step is a cell of that step's\n // transcript (step:<scope>/\u2026), never a step of its own.\n if (row.kind !== \"call\" || bookkeeping(row) || row.id.startsWith(\"step:\")) return false\n const shape = nodeShapes.get(row.id.replace(/#\\d+$/, \"\"))\n return shape === undefined || !structural(shape.kind)\n })\n const transcriptOf = (row: TraceSpan) => {\n const parts = dispatchesOf.get(row.id)!.flatMap((dispatch) => {\n const found = transcripts.get(dispatch.slice(dispatch.lastIndexOf(\":\") + 1))\n return found === undefined ? [] : [found]\n })\n return {\n cells: parts.flatMap((part) => part.cells).sort((left, right) =>\n Number(left.id.slice(5)) - Number(right.id.slice(5))\n ),\n tokens: parts.reduce((total, part) => total + part.tokens, 0),\n models: parts.reduce((total, part) => total + part.models, 0),\n input: parts.find((part) => part.input !== undefined)?.input\n }\n }\n const steps = calls.map((row) => {\n const meter = dispatchesOf.get(row.id)!\n const transcript = transcriptOf(row)\n return {\n ...(() => {\n const matched = /^(engine-node:.*)#(\\d+)$/.exec(row.id)\n const id = matched?.[1] ?? row.id\n const k = Number(matched?.[2] ?? 1)\n return { key: `${id}#${k}`, id, k }\n })(),\n label: row.label,\n state: row.status,\n started_at: new Date(row.startedAt).toISOString(),\n ...(row.endedAt === undefined\n ? {}\n : { ended_at: new Date(row.endedAt).toISOString(), took_s: Math.max(0, row.endedAt - row.startedAt) / 1000 }),\n ...(row.detail.input !== undefined\n ? { input: row.detail.input }\n : transcript.input !== undefined\n ? { input: transcript.input }\n : {}),\n ...(row.detail.output === undefined ? {} : { output: row.detail.output }),\n // The install prices these dispatches from its metered proxy rows and\n // replaces them with `usage`; the journal's own token count rides along.\n ...(meter.length === 0 ? {} : { meter }),\n ...(transcript.models === 0 ? {} : { model_calls: transcript.models, tokens: transcript.tokens })\n }\n })\n const tone = (value: string): \"live\" | \"ok\" | \"fail\" | \"wait\" =>\n value === \"failed\" ?\n \"fail\"\n : value === \"completed\"\n ? \"ok\"\n : value === \"waiting\"\n ? \"wait\"\n : \"live\"\n const phases = calls.map((row, index) => {\n const transcript = transcriptOf(row).cells\n const failedChecks = checkFailures(row.detail.output)\n const cells: Array<Omit<TranscriptCell, \"tone\"> & { tone?: ReturnType<typeof tone> }> = transcript.length > 0\n ? transcript\n : [{\n id: `cell:${row.id}`,\n kind: /Edited/.test(row.label) ? \"edit\" : /Read/.test(row.label) ? \"read\" : \"run\",\n label: row.label,\n ...(row.detail.output === undefined ? {} : { output: row.detail.output }),\n tone: tone(row.status)\n }]\n return {\n id: `phase:${row.id}`,\n step: steps[index]!.key,\n // The title is the Appendix C label plus the outcome its recorded\n // output reports: \"Ran checks \u00B7 1 failed\".\n title: failedChecks === 0 ? row.label : `${row.label} \u00B7 ${failedChecks} failed`,\n took_s: Math.max(0, (row.endedAt ?? row.startedAt) - row.startedAt) / 1000,\n tone: failedChecks === 0 ? tone(row.status) : \"fail\" as const,\n cells\n }\n })\n const declaredGraph = engineExecutionEvidence(journal).filter((execution) => execution.coherent).flatMap(\n (execution) => {\n const prefix = `engine-node:${\n encodeURIComponent(`${encodeURIComponent(execution.executionId)}:${execution.generation}`)\n }:`\n const nodes = execution.graph?.nodes ?? []\n const hidden = new Map(\n nodes.filter((node) => engineLabel(node.action ?? node.id) || structural(node.kind))\n .map((node) => [node.id, node])\n )\n // Engine bookkeeping stays in the Engine row. Its dependency edges still\n // order the visible steps, including across several hidden boundaries.\n const visibleDeps = (id: string, seen: ReadonlySet<string>): string[] => {\n const node = hidden.get(id)\n if (node === undefined) return [prefix + encodeURIComponent(id)]\n if (seen.has(id)) return []\n return node.dependsOn.flatMap((dependency) => visibleDeps(dependency, new Set([...seen, id])))\n }\n return nodes.filter((node) => !hidden.has(node.id)).map((node) => {\n const id = prefix + encodeURIComponent(node.id)\n const instances = calls.filter((row) => row.id.startsWith(`${id}#`))\n const current = instances.at(-1)\n return {\n id,\n label: inspectLabel(node.action ?? node.id),\n // A branch not taken never ran: it stays next, even in a finished run.\n state: current === undefined || current.status === \"skipped\" ?\n \"next\" as const :\n current.status === \"completed\" ?\n \"done\" as const\n : current.status === \"failed\"\n ? \"failed\" as const\n : current.status === \"waiting\"\n ? \"waiting\" as const\n : \"current\" as const,\n deps: [...new Set(node.dependsOn.flatMap((dependency) => visibleDeps(dependency, new Set([node.id]))))]\n }\n })\n }\n )\n const usageOf = (row: TraceSpan) => (row.detail.usage?.inputTokens ?? 0) + (row.detail.usage?.outputTokens ?? 0)\n const tokens = trace.rows.reduce((total, row) => total + usageOf(row), 0)\n // Model calls no native dispatch recorded (a legacy agent journal) can\n // never be joined to metered rows; the install refuses to price them.\n const unmetered = trace.rows.filter((row) => row.kind === \"model\" && asRecord(row.detail.fields).step === undefined)\n .reduce((total, row) => total + usageOf(row), 0)\n const approvalWaits = trace.rows.filter((row) => row.kind === \"approval\").map((row) => ({\n id: row.id,\n kind: \"approval\" as const,\n label: row.label,\n since: new Date(row.startedAt).toISOString(),\n ...(row.endedAt === undefined\n ? {}\n : {\n settled: { by: { kind: \"system\" as const, color_index: 7 as const }, at: new Date(row.endedAt).toISOString() }\n })\n }))\n // The machine records its declared custom view as data. Only the shipped\n // text renderer is supported; module paths, HTML and executable data never\n // cross this seam. Replay selects the last declaration in its own prefix.\n const custom = [...journal].reverse().find(row => (row.runId === undefined || row.runId === run.runId) &&\n row.kind === \"control.engine.event\" && asRecord(row.payload).eventType === \"flows.run.presentation\")\n const presentation = asRecord(asRecord(custom?.payload).payload)\n const text = asString(presentation.text)\n const customView = presentation.kind === \"text\" && text !== undefined && text.length <= 65536 &&\n Object.keys(presentation).every(key => key === \"kind\" || key === \"text\")\n ? { presentation: { kind: \"text\" as const, text } } : {}\n return {\n ...customView,\n id: run.runId,\n flow: run.flowId,\n version: \"\",\n title: run.flowId,\n state: state(status),\n attempts: [{\n n: 1,\n run_id: run.runId,\n state: state(status),\n steps,\n phases,\n graph: declaredGraph.length > 0 ?\n declaredGraph :\n calls.map((row) => ({\n id: row.id,\n label: row.label,\n state: row.status === \"skipped\" ? \"next\" as const : row.status === \"completed\" ?\n \"done\" as const\n : row.status === \"failed\"\n ? \"failed\" as const\n : row.status === \"waiting\"\n ? \"waiting\" as const\n : \"current\" as const,\n deps: [] as string[]\n }))\n }],\n waits: [\n ...approvalWaits,\n ...engineExecutionEvidence(journal).filter((execution) => execution.coherent).flatMap((execution) =>\n execution.waits.map((wait) => ({\n id: wait.id,\n kind: wait.kind,\n label: inspectLabel(\"wait\"),\n since: new Date(wait.since).toISOString(),\n ...(wait.settledAt === undefined\n ? {}\n : {\n settled: {\n by: { kind: \"system\" as const, color_index: 7 as const },\n at: new Date(wait.settledAt).toISOString()\n }\n })\n }))\n )\n ],\n tokens,\n // Spend is priced where model calls are metered. The host never publishes\n // an unknown total as zero: a run with model tokens leaves cost to the install.\n time_s: Math.max(0, trace.extent.end - trace.extent.start) / 1000,\n ...(tokens === 0 ? { cost_usd: 0 } : {}),\n ...(unmetered === 0 ? {} : { unmetered_tokens: unmetered }),\n engine: trace.rows.filter((row) =>\n row.kind === \"event\" || row.kind === \"execution\" || row.kind === \"attempt\" || bookkeeping(row)\n ).map((row) => ({ label: row.label, detail: row.detail.output ?? row.detail.message ?? \"\" })),\n journal: journal.map((row) => ({\n seq: row.sequence ?? 0,\n at: new Date(row.occurredAt ?? 0).toISOString(),\n type: row.kind ?? \"event\",\n text: JSON.stringify(row.payload) ?? \"null\"\n })),\n ...(at === undefined ? {} : { replay: { at: Math.min(at, last), last } })\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,qBAAyB;AACzB,wBAAoE;AACpE,oBAAuB;AACvB,uBAAyC;AACzC,yBAAgE;AAChE,8BAAkC;AAClC,wBAAyF;AACzF,2BAA6B;AAE7B,IAAAA,wBAA6B;AA6Q7B,MAAM,eAAoC,oBAAI,IAAI,CAAC,aAAa,UAAU,aAAa,aAAa,CAAC;AAErG,MAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAmC,CAAC;AAC7G,MAAM,WAAW,CAAC,UAAuC,OAAO,UAAU,WAAW,QAAQ;AAC7F,MAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AAGhE,MAAM,SAAS,CAAC,QAAuB,YACrC,SAAS,QAAQ,EAAE,KAAK,SAAS,OAAO,UAAU,KAAK;AAGzD,MAAM,SAAS,CAAC,UAAuC;AACrD,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI;AACF,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO,OAA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U;AAAA,IACzD,QAAQ,MAAM,KAAK;AAAA,MAAO,CAAC,QACzB,IAAI,SAAS,WAAW,IAAI,SAAS,eAAe,IAAI,SAAS,aAAa,YAAY,GAAG;AAAA,IAC/F,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,IAAI,OAAO,QAAQ,IAAI,OAAO,UAAU,IAAI,OAAO,WAAW,GAAG,EAAE;AAAA,IAC5F,SAAS,QAAQ,IAAI,CAAC,SAAS;AAAA,MAC7B,KAAK,IAAI,YAAY;AAAA,MACrB,IAAI,IAAI,KAAK,IAAI,cAAc,CAAC,EAAE,YAAY;AAAA,MAC9C,MAAM,IAAI,QAAQ;AAAA,MAClB,MAAM,KAAK,UAAU,IAAI,OAAO,KAAK;AAAA,IACvC,EAAE;AAAA,IACF,GAAI,OAAO,SAAY,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,KAAK,IAAI,IAAI,IAAI,GAAG,KAAK,EAAE;AAAA,EACzE;AACF;",
4
+ "sourcesContent": ["/**\n * The run trace model (factory spec 06, \"the run trace\": one card shows every\n * run).\n *\n * A run is a recursive program: the agent writes REPL cells in a code\n * container, every `ctx.call` is a durable span, and each turn is a frame. The\n * control journal already records exactly that (`@smthrs/agent` AgentSession\n * journals turn-opened, model-settled, cell-produced, cell-call-started,\n * cell-call-settled, cell-printed, cell-settled, resolved), and the gateway\n * serves it as the `run-events` projection the run card already reads. This\n * module folds those records into a span tree, run \u2192 frame \u2192 cell \u2192 call, and\n * the geometry of one bar per span on a shared time axis. No second data\n * source: what the journal does not carry (realm variables, child runs' own\n * frames) the model does not invent.\n *\n * Pure: the card renders the model, the tests read it from a fixture.\n * @since 1.0.0\n */\n\nimport { CallFact } from \"@smthrs/journal\"\nimport { CallPresentation, FlowActivity, type FlowDescriptor } from \"@smthrs/registry/Descriptor\"\nimport { Schema } from \"effect\"\nimport { callScope, openCallIndex } from \"./Diagnosis.ts\"\nimport { engineExecutionEvidence, engineTraceFromJournal } from \"./EngineTrace.ts\"\nimport { ACTION_RENDERINGS } from \"./internal/actionRenderings.ts\"\nimport { type CallEventFilter, callEventFilter, nativeStepEvent, uniqueCallEvents } from \"./internal/callEvents.ts\"\nimport { inspectLabel } from \"./internal/inspectLabels.ts\"\n\nexport { inspectLabel } from \"./internal/inspectLabels.ts\"\n\n/** One control journal record, as the run card stores it (the run-events projection's row shape).\n *\n * @category models\n * @since 1.0.0\n */\nexport interface JournalRecord {\n readonly runId?: string | undefined\n readonly sequence?: number | undefined\n readonly kind?: string | undefined\n readonly occurredAt?: number | undefined\n readonly payload?: unknown | undefined\n}\n\n/**\n * What kind of node a span is in the tree. `fork` is the row 0 of a forked run\n * (spec 06 \u00A71); no journal record folds into it yet, so no fold produces one.\n *\n * @category models\n * @since 1.0.0\n */\nexport type SpanKind =\n | \"run\"\n | \"frame\"\n | \"model\"\n | \"cell\"\n | \"call\"\n | \"approval\"\n | \"resolved\"\n | \"event\"\n | \"fork\"\n | \"execution\"\n | \"attempt\"\n\n/** What the journal said about the span; the run root wears the run's own status word.\n *\n * @category models\n * @since 1.0.0\n */\nexport type SpanStatus = \"running\" | \"completed\" | \"failed\" | \"waiting\" | \"approved\" | \"denied\" | string\n\n/** The facts the details pane shows for one span: only what its journal records carry.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface SpanDetail {\n /** The journal sequence that opened the span. */\n readonly sequence?: number | undefined\n /** The journal kind that opened the span. */\n readonly event?: string | undefined\n readonly seat?: string | undefined\n /** A cell's source text. */\n readonly source?: string | undefined\n /** What a cell printed for the next model turn. */\n readonly printed?: string | undefined\n /**\n * A call's flow name exactly as journaled. The span's `label` is its\n * display form; read call semantics from this field, never from the label.\n *\n * @since 1.0.0\n */\n readonly flowName?: string | undefined\n /** A call's input, as journaled. */\n readonly input?: unknown | undefined\n /** A call's settled value, a model's text, or a resolved text. */\n readonly output?: string | undefined\n /** A detached child's recorded execution id; only the agent/spawn result establishes this edge. */\n readonly childRunId?: string | undefined\n /** A failure's message. */\n readonly message?: string | undefined\n readonly usage?: { readonly inputTokens?: number | undefined; readonly outputTokens?: number | undefined } | undefined\n /** Every other payload field the opening record carried, as the journal bound it. */\n readonly fields?: Readonly<Record<string, unknown>> | undefined\n}\n\n/**\n * One nested execution span with its original journal evidence.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceSpan {\n readonly id: string\n readonly kind: SpanKind\n readonly label: string\n readonly status: SpanStatus\n readonly startedAt: number\n /** Absent while the span is open. */\n readonly endedAt?: number | undefined\n readonly depth: number\n readonly children: ReadonlyArray<TraceSpan>\n readonly detail: SpanDetail\n}\n\n/** The run the trace belongs to, as the run card knows it.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceRun {\n readonly runId: string\n readonly flowId: string\n /** The run card's phase word (running, completed, failed, cancelled, waiting-approval, ...). */\n readonly status: string\n readonly kind?: string | undefined\n}\n\n/**\n * The recorded start and end of a trace in milliseconds.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceExtent {\n readonly start: number\n readonly end: number\n}\n\n/**\n * What a frame was doing, derived from what it did \u2014 never declared.\n *\n * `unrecorded` is the honest reading of a frame whose journal carries nothing\n * this fold can name: every other word here is a claim about the frame's work,\n * and a claim needs a record behind it.\n *\n * @category models\n * @since 1.0.0\n */\nexport type PhaseId = \"researching\" | \"implementing\" | \"testing\" | \"stuck\" | \"blocked\" | \"unrecorded\"\n\n/** One contiguous run of frames in one phase.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface PhaseBand {\n readonly phase: PhaseId\n readonly startedAt: number\n readonly endedAt: number\n /** Span ids of the frames in this band, in order. */\n readonly frames: ReadonlyArray<string>\n /** Journal sequence to scrub to when this band is clicked. */\n readonly seq: number\n}\n\n/** A moment a person would scrub to.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface Milestone {\n readonly seq: number\n readonly at: number\n readonly label: string\n /** `muted` is a person's stop: neither a success nor a failure. */\n readonly tone: \"warn\" | \"bad\" | \"good\" | \"brand\" | \"muted\"\n /**\n * The frame this moment was recorded under, carried through the scoped\n * merge. Two steps run at once in one journal, so the frame a milestone\n * belongs to is the one its OWN step had open, never whichever frame opened\n * last.\n */\n readonly spanId: string\n}\n\n/**\n * The frame one journal record was recorded under.\n *\n * The strip scrubs to sequences no milestone names, so the ownership rule has\n * to hold for every record, not only for the ones that mint a pin.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceOwner {\n readonly seq: number\n readonly spanId: string\n}\n\n/** What one frame did, in plain English, derived from its calls.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface FrameLine {\n readonly spanId: string\n /** Frame ordinal as shown to a person, 1-based. */\n readonly frame: number\n readonly verb: string\n /** Empty when the call's input named nothing this fold reads as a subject; the card then prints the verb alone. */\n readonly subject: string\n readonly result: string\n readonly failed: boolean\n readonly wrote: boolean\n /** Frame ordinal this repeats, set ONLY inside a stall streak. */\n readonly repeatOf?: number | undefined\n}\n\n/** A discipline event, rendered where it happened.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceNote {\n readonly seq: number\n /** Span id of the frame it attaches under. */\n readonly spanId: string\n readonly tone: \"warn\" | \"bad\" | \"good\"\n readonly title: string\n readonly body: string\n /** Quoted evidence lines, already clipped. */\n readonly evidence?: ReadonlyArray<string> | undefined\n}\n\n/** Extra options the fold takes; every field optional, absent = today's behaviour.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceOptions {\n /** Plan targets are coverage requirements, never evidence that a call ran tests. */\n readonly checkTargets?: ReadonlyArray<string> | undefined\n}\n\n/**\n * The shared projection rendered by app and terminal monitors.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceModel {\n /** Source records for status and check receipts, including their settlement sequences. */\n readonly journal: ReadonlyArray<JournalRecord>\n readonly root: TraceSpan\n /** Every span in tree order, with its depth: the tree's rows and the waterfall's rows. */\n readonly rows: ReadonlyArray<TraceSpan>\n readonly extent: TraceExtent\n readonly counts: { readonly spans: number; readonly running: number; readonly failed: number }\n /** The run's frames merged into what they were doing; empty when the journal opened no frame. */\n readonly bands: ReadonlyArray<PhaseBand>\n /** The moments a person scrubs to, in journal order; empty when the journal recorded none. */\n readonly milestones: ReadonlyArray<Milestone>\n /** One line per frame that called something; a frame that called nothing has none. */\n readonly lines: ReadonlyArray<FrameLine>\n /** The discipline records that carry fields, attached where they happened. */\n readonly notes: ReadonlyArray<TraceNote>\n /** Every recorded sequence with the frame it was recorded under, in journal order. */\n readonly owners: ReadonlyArray<TraceOwner>\n}\n\n/** Mutable draft shared by the control and native journal folds; never persisted.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceBuilder {\n readonly id: string\n readonly kind: SpanKind\n label: string\n status: SpanStatus\n startedAt: number\n endedAt?: number | undefined\n readonly children: Array<TraceBuilder>\n detail: SpanDetail\n}\ntype Builder = TraceBuilder\n\nconst TERMINAL_RUN: ReadonlySet<string> = new Set([\"completed\", \"failed\", \"cancelled\", \"no-capacity\"])\n\nconst asRecord = (value: unknown): Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {}\nconst asString = (value: unknown): string | undefined => typeof value === \"string\" ? value : undefined\nconst asNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n\n/** The record's time: the agent's own `at` stamp when it carries one, the journal's otherwise (the gateway's rule). */\nconst timeOf = (record: JournalRecord, payload: Record<string, unknown>): number =>\n asNumber(payload.at) ?? asNumber(record.occurredAt) ?? 0\n\n/** One line of text for a value the journal traced, or nothing. */\nconst textOf = (value: unknown): string | undefined => {\n if (value === undefined || value === null) return undefined\n if (typeof value === \"string\") return value\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\n/** The payload fields the pane does not already show by name. */\nconst restOf = (\n payload: Record<string, unknown>,\n shown: ReadonlyArray<string>\n): Record<string, unknown> | undefined => {\n const rest: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(payload)) {\n if (shown.includes(key) || key === \"at\" || key === \"journalVersion\") continue\n rest[key] = value\n }\n return Object.keys(rest).length === 0 ? undefined : rest\n}\n\nconst builder = (\n id: string,\n kind: SpanKind,\n label: string,\n status: SpanStatus,\n startedAt: number,\n detail: SpanDetail\n): Builder => ({ id, kind, label, status, startedAt, children: [], detail })\n\n/*\n * What the frame was DOING.\n *\n * Same discipline as the tree above, held one level closer to the reader:\n * every word below is read off a journal record, never off what the model said\n * it would do. A frame's line comes from the calls it made; its phase comes\n * from those calls and from the controller's own observations of the tree; a\n * note is a discipline record's own fields, quoted. Nothing here counts what\n * the journal may be missing, and a frame the journal says nothing about gets\n * nothing said about it.\n */\n\n/**\n * What a recorded call means: what it did, and how it reads.\n *\n * The rows, the phase bands and the run header all read a call through this\n * one answer, so they cannot tell three different stories about one record.\n *\n * @category models\n * @since 1.0.0\n */\nexport type CallMetadata = Pick<FlowDescriptor, \"activity\" | \"presentation\">\n\n/** Compatibility for journals whose descriptors predate presentation metadata. */\nconst legacy = (\n activity: FlowActivity | undefined,\n pending: string,\n success: string,\n failure: string,\n subject: CallPresentation[\"subject\"],\n result: CallPresentation[\"result\"]\n): CallMetadata => ({\n ...(activity === undefined ? {} : { activity }),\n presentation: { verb: { pending, success, failure }, subject, result }\n})\n\nconst LEGACY_PRESENTATION: ReadonlyMap<string, CallMetadata> = new Map([\n // `bash` has no compatibility activity for the same reason `@smthrs/std`\n // declares none: what a shell call does is in the command, which the rule\n // below reads off the record.\n [\"bash\", legacy(undefined, \"running\", \"ran\", \"failed to run\", \"command\", \"command\")],\n [\"test\", legacy(\"tests\", \"running\", \"ran\", \"failed to run\", \"selection\", \"tests\")],\n [\"edit\", legacy(\"writes\", \"editing\", \"edited\", \"failed to edit\", \"path\", \"edit\")],\n [\"write\", legacy(\"writes\", \"writing\", \"wrote\", \"failed to write\", \"path\", \"write\")],\n [\"apply_patch\", legacy(\"writes\", \"patching\", \"patched\", \"failed to patch\", \"patch\", \"patch\")],\n [\"read\", legacy(\"reads\", \"reading\", \"read\", \"failed to read\", \"path\", \"read\")],\n [\"grep\", legacy(\"reads\", \"searching\", \"searched\", \"failed to search\", \"pattern\", \"matches\")],\n [\"glob\", legacy(\"reads\", \"listing\", \"listed\", \"failed to list\", \"pattern\", \"paths\")],\n [\"ls\", legacy(\"reads\", \"listing\", \"listed\", \"failed to list\", \"path\", \"entries\")]\n])\n\n/** Read only the descriptor's validated display fields; a call input is never metadata. */\nconst recordedMetadata = (value: unknown, flowName: string): CallMetadata | undefined => {\n const descriptor = asRecord(value)\n if (descriptor.name !== flowName) return undefined\n if (descriptor.activity === undefined && descriptor.presentation === undefined) return undefined\n const activity = Schema.is(FlowActivity)(descriptor.activity) ? descriptor.activity : undefined\n const presentation = Schema.is(CallPresentation)(descriptor.presentation) ? descriptor.presentation : undefined\n return { activity, presentation }\n}\n\n/**\n * The name a queued checkpoint mint carries (`QuickJSSandbox` `checkpointFlow`).\n * A mint journals `control.agent.checkpoint-minted` and never a call, so no\n * call in a journal wears this name today; the dominant-call rule skips it\n * anyway, so a host that binds a flow by that name cannot make a frame's\n * headline read as bookkeeping.\n */\nconst CHECKPOINT_FLOW = \"checkpoint\"\n\n/** The command line a call ran, for the flows that run one. */\nconst commandOf = (input: unknown): string | undefined => {\n const fields = asRecord(input)\n return asString(fields.command) ?? asString(fields.script)\n}\n\n/** The last segment of a path: the name a person calls the file. */\nconst basename = (path: string): string => path.split(\"/\").filter((part) => part !== \"\").pop() ?? path\n\n/**\n * The files a V4A patch names (`@smthrs/std` ApplyPatch's `*** Add File: `,\n * `*** Delete File: ` and `*** Update File: ` markers).\n *\n * `apply_patch` carries its entire patch in one `input` string, and the patch\n * is not the subject: what it patches is. A string that is not a patch names no\n * files and yields none, so a flow that happens to call its field `input` is\n * not mistaken for one.\n */\nconst patchedPaths = (patch: string): ReadonlyArray<string> => {\n const paths: Array<string> = []\n for (const line of patch.split(\"\\n\")) {\n const named = /^\\*\\*\\* (?:Add|Delete|Update) File:\\s*(\\S.*)$/.exec(line.trim())?.[1]\n if (named !== undefined) paths.push(named.trim())\n }\n return paths\n}\n\n/**\n * Several files in the room one name has: the first named, the rest counted.\n *\n * A multi-file patch's line and a frame's write pin both say it through here,\n * so `views.py +1` means one thing wherever the card prints it. The count is a\n * fact the journal carried, never an estimate. No file, no words.\n */\nconst filesLabel = (paths: ReadonlyArray<string>): string => {\n const first = paths[0]\n if (first === undefined) return \"\"\n return paths.length === 1 ? basename(first) : `${basename(first)} +${paths.length - 1}`\n}\n\n/** The files an edit-like call names: its `path`, or every file its patch names. */\nconst writtenPaths = (input: unknown): ReadonlyArray<string> => {\n const fields = asRecord(input)\n const path = asString(fields.path)\n if (path !== undefined) return [path]\n const patch = asString(fields.input)\n return patch === undefined ? [] : patchedPaths(patch)\n}\n\n/**\n * What one recorded call was about, in the shape its declaration chose.\n *\n * Exported because the run header names the same subject as the row beneath\n * it: two readings of one input is two answers to one question.\n *\n * @param input the call input, as journaled\n * @param format the declared subject field, when the declaration named one\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const callSubject = (input: unknown, format?: CallPresentation[\"subject\"]): string => {\n const fields = asRecord(input)\n if (format === \"none\") return \"\"\n if (format === \"path\") return asString(fields.path) === undefined ? \"\" : basename(fields.path as string)\n if (format === \"command\") return commandOf(input) ?? \"\"\n if (format === \"patch\") return filesLabel(patchedPaths(asString(fields.input) ?? \"\"))\n if (format === \"pattern\") return asString(fields.pattern) ?? \"\"\n if (format === \"selection\") return stringList(fields.selection)?.join(\" \") ?? \"\"\n const path = asString(fields.path)\n if (path !== undefined) return basename(path)\n const command = commandOf(input)\n if (command !== undefined) return command\n const patch = asString(fields.input)\n if (patch !== undefined) {\n // The patch is not the subject; the files it patches are.\n const files = filesLabel(patchedPaths(patch))\n if (files !== \"\") return files\n }\n // `test` names what it selected (`@smthrs/std` TestRun `Input.selection`).\n // An omitted selection means the record named nothing; that the flow would\n // then run everything is the flow's default, not a fact this record carries.\n const selection = Array.isArray(fields.selection)\n ? fields.selection.filter((one): one is string => typeof one === \"string\")\n : undefined\n if (selection !== undefined && selection.length > 0) return selection.join(\" \")\n return asString(fields.pattern) ?? \"\"\n}\n\n/**\n * Legacy shell journals have no structured activity. Recognize only direct\n * invocations of known runners. Shell composition, expansion and quoted\n * programs remain unknown. Arguments can narrow a check without changing\n * its activity; no command here establishes a plan's required coverage.\n */\nconst shellActivity = (command: string): FlowActivity => {\n if (/[;&|<>`$\\n\\r]/.test(command)) return \"other\"\n const words = command.trim().split(/\\s+/)\n const first = words[0]!\n if ([\"pytest\", \"vitest\", \"jest\"].includes(first)) return \"tests\"\n if (/^python[23]?$/.test(first) && words[1] === \"-m\" && [\"pytest\", \"unittest\"].includes(words[2] ?? \"\")) {\n return \"tests\"\n }\n if (first === \"bun\" && words[1] === \"test\") return \"tests\"\n if ([\"pnpm\", \"npm\", \"bun\"].includes(first)) {\n if (words[1] === \"test\" || (words[1] === \"run\" && words[2] === \"test\")) return \"tests\"\n if (words[1] === \"exec\" && [\"vitest\", \"jest\"].includes(words[2] ?? \"\")) return \"tests\"\n if (words[1] === \"run\" && [\"check\", \"typecheck\", \"lint\"].includes(words[2] ?? \"\")) return \"checks\"\n }\n if (first === \"go\" && words[1] === \"test\") return \"tests\"\n if (first === \"cargo\" && words[1] === \"test\") return \"tests\"\n if (first === \"tsc\") return \"checks\"\n return \"other\"\n}\n\n/**\n * The one reading of a recorded call's semantics, shared by the rows, the\n * phase bands and the run header.\n *\n * Precedence, and why: the record's own `descriptor` wins, because it is what\n * the declaration said when the call was made, and only a record that carries\n * none falls back to {@link LEGACY_PRESENTATION}, which is a guess about the\n * flows that were journaled before a declaration could say anything. A flow the\n * table does not know stays unknown, and unknown is said as unknown.\n *\n * `bash` is the one activity read off the call rather than the declaration.\n * `@smthrs/std` declares none for it on purpose \u2014 the same flow runs a test\n * suite, a type check and `cat` \u2014 so a recognised runner in the recorded\n * command is the only thing that names the activity, and an explicit\n * declaration still outranks it.\n *\n * @param flowName the flow the record names\n * @param payload the `cell-call-started` payload, as journaled\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const callSemantics = (\n flowName: string,\n payload: Record<string, unknown>\n): CallMetadata => {\n const recorded = recordedMetadata(payload.descriptor, flowName)\n const metadata = recorded ?? LEGACY_PRESENTATION.get(flowName)\n const activity = metadata?.activity\n ?? (flowName === \"bash\" ? shellActivity(commandOf(payload.input) ?? \"\") : undefined)\n return {\n ...(activity === undefined ? {} : { activity }),\n ...(metadata?.presentation === undefined ? {} : { presentation: metadata.presentation })\n }\n}\n\nconst stringList = (value: unknown): ReadonlyArray<string> | undefined =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\") ? value : undefined\n\nconst countOf = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n\nconst counted = (value: number, noun: string, plural = `${noun}s`): string => `${value} ${value === 1 ? noun : plural}`\n\n/** Known output fields only. Unknown objects remain in the call's raw output. */\nconst resultOf = (value: unknown, format?: CallPresentation[\"result\"]): string => {\n if (format === \"none\") return \"\"\n if (typeof value === \"string\") return clip(value) ?? \"\"\n const fields = asRecord(value)\n if (fields.truncated === true && typeof fields.digest === \"string\") return \"\"\n switch (format) {\n case \"read\": {\n const start = countOf(fields.startLine)\n const end = countOf(fields.endLine)\n return start !== undefined && start > 0 && end !== undefined && end >= start - 1\n ? counted(end - start + 1, \"line\") :\n \"\"\n }\n case \"write\":\n return countOf(fields.bytesWritten) === undefined ? \"\" : counted(fields.bytesWritten as number, \"byte\")\n case \"edit\":\n return countOf(fields.replacements) === undefined ? \"\" : counted(fields.replacements as number, \"replacement\")\n case \"patch\": {\n const groups = [stringList(fields.added), stringList(fields.modified), stringList(fields.deleted)]\n return groups.every((group) => group !== undefined) ? counted(new Set(groups.flat()).size, \"file\") : \"\"\n }\n case \"tests\": {\n const passed = countOf(fields.passed)\n const failed = stringList(fields.failed)\n if (fields.parsed === true && passed !== undefined && failed !== undefined && fields.invalidProbe === undefined) {\n const exit = countOf(fields.exitCode)\n return `${passed} passed${\n failed.length > 0 ? ` \u00B7 ${failed.length} failed` : exit !== undefined && exit !== 0 ? ` \u00B7 exit ${exit}` : \"\"\n }`\n }\n return countOf(fields.exitCode) === undefined ? \"\" : `exit ${fields.exitCode}`\n }\n case \"command\":\n return countOf(fields.exitCode) === undefined ? \"\" : `exit ${fields.exitCode}`\n case \"matches\":\n return Array.isArray(fields.matches) ? counted(fields.matches.length, \"match\", \"matches\") : \"\"\n case \"paths\":\n return stringList(fields.paths) === undefined\n ? \"\"\n : counted((fields.paths as ReadonlyArray<string>).length, \"file\")\n case \"entries\":\n return Array.isArray(fields.entries) ? counted(fields.entries.length, \"entry\", \"entries\") : \"\"\n default:\n return \"\"\n }\n}\n\n/** A note body from the sentences the payload carried; a field the record omitted contributes nothing. */\nconst bodyOf = (...sentences: ReadonlyArray<string | undefined>): string =>\n sentences.filter((sentence) => sentence !== undefined).join(\" \")\n\n/** One quoted line of evidence, bounded the way the turn list bounds prose. */\nconst clip = (value: unknown): string | undefined => {\n const line = asString(value)\n if (line === undefined || line === \"\") return undefined\n return line.length <= 160 ? line : `${line.slice(0, 159).trimEnd()}\u2026`\n}\n\n/** One call a frame made, as the journal opened and settled it. */\ninterface CallFacts {\n readonly flowName: string\n readonly callId?: string | undefined\n readonly input: unknown\n readonly activity?: FlowActivity | undefined\n readonly presentation?: CallPresentation | undefined\n /**\n * What a repeat is judged by: the flow and the input exactly as journaled. A\n * field the trail truncated still canonicalizes to its own digest, so a\n * repeat of a huge input is still recognised as one.\n */\n readonly signature: string\n settled?:\n | { readonly failed: boolean; readonly result: string; readonly denied: boolean; readonly value: unknown }\n | undefined\n /** What a repeat is matched on: the signature and the settlement. */\n reading?: string | undefined\n}\n\n/** What one frame did, as its own records said it. */\ninterface FrameFacts {\n readonly id: string\n readonly frame: number\n readonly seq: number\n readonly startedAt: number\n endedAt: number\n blocked: boolean\n /** `control.agent.mutation-observed`'s answer; absent when the frame closed on none. */\n mutated?: boolean | undefined\n /** A measured tree comparison outranks declared writes and successful no-op calls. */\n observedMutation?: boolean | undefined\n /** The write pin this frame minted: where it sits in the milestones, and every file it counts. */\n wrote?: { readonly milestone: number; readonly paths: Array<string> } | undefined\n readonly calls: Array<CallFacts>\n}\n\n/** Whether the frame made an edit-like call the journal recorded settling successfully. */\nconst madeAWrite = (entry: FrameFacts): boolean =>\n entry.calls.some((call) => call.activity === \"writes\" && call.settled?.failed === false && !call.settled.denied)\n\n/**\n * The call a frame's line is about: a change it made, else the check it ran,\n * else the first thing it asked for.\n *\n * The phase rules and the lines read the same answer, so the two can never\n * disagree about whether the journal said anything about a frame at all.\n */\nconst dominantCall = (entry: FrameFacts): CallFacts | undefined =>\n entry.calls.find((one) => one.activity === \"writes\")\n ?? entry.calls.find((one) => one.activity === \"checks\" || one.activity === \"tests\")\n ?? entry.calls.find((one) => one.flowName !== CHECKPOINT_FLOW)\n\n/**\n * Folds the journal a second time, into what a person would say the run was\n * doing: its phase bands, its milestones, one line per frame, and the\n * discipline notes.\n *\n * Read off the RECORDS rather than off the spans the fold above builds, for\n * three reasons. The spans keep a settled value as text (`textOf`), so an\n * `ask` denial would have to be parsed back out of JSON. An unrecognised\n * kind's span hangs off `cell ?? frame ?? root`, so the frame a note belongs\n * to would have to be recovered from tree position. And that span shape is the\n * fold's `default` arm: the day a kind gains a case of its own, notes read off\n * `detail.fields` would vanish without a word, while notes read off the\n * records keep working.\n *\n * @param runId the run, for the notes that land before any frame opened\n * @param ordered the journal, in sequence order, call events already deduplicated\n */\ninterface DisciplineState {\n readonly runId: string\n readonly frames: Array<FrameFacts>\n readonly notes: Array<TraceNote>\n readonly milestones: Array<Milestone>\n readonly owners: Array<TraceOwner>\n readonly open: Array<CallFacts>\n frame: FrameFacts | undefined\n lastAt: number\n /** Each frame's line as last built, reused while its inputs are the same objects. */\n readonly lineOf: WeakMap<FrameFacts, {\n readonly call: CallFacts\n readonly settled: CallFacts[\"settled\"]\n readonly repeatOf: number | undefined\n readonly line: FrameLine\n }>\n}\n\nconst disciplineInit = (runId: string): DisciplineState => ({\n runId,\n frames: [],\n notes: [],\n milestones: [],\n owners: [],\n open: [],\n frame: undefined,\n lastAt: 0,\n lineOf: new WeakMap()\n})\n\n/** One record of the discipline fold; the state is advanced in place. */\nconst disciplineStep = (state: DisciplineState, record: JournalRecord): void => {\n const { runId, frames, notes, milestones, owners, open } = state\n let frame = state.frame\n /** Where a discipline record attaches: the open frame, else the run itself. */\n const here = (): string => frame?.id ?? `run:${runId}`\n const note = (\n seq: number,\n tone: TraceNote[\"tone\"],\n title: string,\n body: string,\n evidence: ReadonlyArray<string | undefined>\n ): void => {\n const quoted = evidence.filter((line): line is string => line !== undefined)\n notes.push({ seq, spanId: here(), tone, title, body, ...(quoted.length === 0 ? {} : { evidence: quoted }) })\n }\n /** A moment, owned by the frame that recorded it, exactly the way a note is. */\n const pin = (seq: number, at: number, label: string, tone: Milestone[\"tone\"]): void => {\n milestones.push({ seq, at, label, tone, spanId: here() })\n }\n\n {\n const kind = record.kind ?? \"\"\n const payload = asRecord(record.payload)\n const at = timeOf(record, payload)\n const seq = record.sequence ?? 0\n state.lastAt = Math.max(state.lastAt, at)\n if (frame !== undefined) frame.endedAt = Math.max(frame.endedAt, at)\n switch (kind) {\n case \"control.agent.turn-opened\": {\n frame = {\n id: `frame-${frames.length + 1}`,\n frame: frames.length + 1,\n seq,\n startedAt: at,\n endedAt: at,\n blocked: false,\n calls: []\n }\n frames.push(frame)\n break\n }\n case \"control.agent.cell-call-started\": {\n const flowName = asString(payload.flowName) ?? \"\"\n const metadata = callSemantics(flowName, payload)\n const call: CallFacts = {\n flowName,\n callId: asString(payload.callId),\n input: payload.input,\n activity: metadata.activity,\n presentation: metadata.presentation,\n signature: `${flowName} ${textOf(payload.input) ?? \"\"}`\n }\n open.push(call)\n // A call journaled outside a frame belongs to no frame, and the tree\n // above puts it on the run. It is still open work, so it still pairs.\n frame?.calls.push(call)\n break\n }\n case \"control.agent.cell-call-settled\": {\n if (payload.outcome !== \"success\" && payload.outcome !== \"failure\") break\n const index = openCallIndex(open, asString(payload.callId), asString(payload.flowName))\n const call = index < 0 ? undefined : open.splice(index, 1)[0]\n if (call === undefined) break\n const failed = asString(payload.outcome) === \"failure\"\n // `ask` settles SUCCESSFULLY with the person's answer (`AgentSession`\n // answers `{ answer, approved }`), so a refusal is a denial and not a\n // failure. That is the call that settles with a denial.\n const denied = !failed && asRecord(payload.value).approved === false\n call.settled = {\n failed,\n result: (failed ? textOf(payload.message) : textOf(payload.value)) ?? \"\",\n denied,\n value: payload.value\n }\n if (denied && frame !== undefined) frame.blocked = true\n // A write is the fastest thing a run does, so its band is always too\n // narrow to carry a label, and its own marker is the only way to reach\n // the moment that matters most.\n if (!failed && !denied && call.activity === \"writes\") {\n // A pin is its label, so a pin with none is a marker nobody can read\n // and nobody can tell from the next one. The journal gave this call\n // no file; no file, no pin.\n const paths = [...new Set(writtenPaths(call.input))]\n const minted = frame?.wrote\n if (minted !== undefined) {\n // A frame's writes are ONE moment. A frame that edits fifteen files\n // does it inside a second, so a pin per file is fifteen names\n // stacked over a point on the axis nobody can aim between. The pin\n // stays where the frame started writing, on the file it names, and\n // counts the rest; a file written twice is still one file.\n for (const path of paths) if (!minted.paths.includes(path)) minted.paths.push(path)\n milestones[minted.milestone] = { ...milestones[minted.milestone]!, label: filesLabel(minted.paths) }\n } else if (paths.length > 0) {\n // A write journaled outside a frame has no frame to be counted\n // into, so it stays a moment of its own.\n if (frame !== undefined) frame.wrote = { milestone: milestones.length, paths }\n pin(seq, at, filesLabel(paths), \"brand\")\n }\n }\n break\n }\n case \"control.agent.mutation-observed\": {\n const mutated = payload.mutated === true\n if (frame !== undefined) frame.mutated = mutated\n if (frame !== undefined && payload.basis === \"observed\" && typeof payload.mutated === \"boolean\") {\n frame.observedMutation = payload.mutated\n }\n // Written for every frame, so only a frame that changed something is\n // worth a note. `basis` is the body because a `declared` answer is\n // paperwork and an `observed` one is a fact about the tree, and a\n // reader must not have to guess which one they are holding. `paths` is\n // a COUNT of what the measurement covered, not the paths themselves,\n // so it is not quotable evidence and is not quoted.\n if (mutated) {\n note(\n seq,\n asString(payload.basis) === \"observed\" ? \"good\" : \"warn\",\n \"changed\",\n asString(payload.basis) ?? \"\",\n []\n )\n }\n break\n }\n case \"control.agent.permission-required\": {\n if (frame !== undefined) frame.blocked = true\n pin(seq, at, \"permission\", \"warn\")\n break\n }\n case \"control.agent.suspended\": {\n if (frame !== undefined) frame.blocked = true\n break\n }\n case \"control.agent.checkpoint-minted\": {\n note(seq, \"good\", \"checkpoint\", asString(payload.ref) ?? \"\", [])\n break\n }\n case \"control.agent.read-only-demanded\": {\n // The caps are this run's own armed numbers, read off the payload: a\n // host overrides any of them, so a constant here would print a number\n // the run never used.\n const streak = asNumber(payload.streak)\n const cap = asNumber(payload.cap)\n const nextFrame = asNumber(payload.nextFrame)\n const nextAction = asString(payload.nextAction)\n note(\n seq,\n \"warn\",\n \"read-only\",\n bodyOf(\n streak === undefined || cap === undefined ? undefined : `${streak} of ${cap} frames changed nothing.`,\n nextFrame === undefined || nextAction === undefined ? undefined : `Frame ${nextFrame}: ${nextAction}.`\n ),\n []\n )\n pin(seq, at, \"read-only\", \"warn\")\n break\n }\n case \"control.agent.repeat-demanded\": {\n const spent = asNumber(payload.frames)\n const cap = asNumber(payload.cap)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"warn\",\n \"repeat\",\n bodyOf(\n spent === undefined || cap === undefined ? undefined : `${spent} of ${cap} frames repeated calls.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n []\n )\n pin(seq, at, \"repeat\", \"warn\")\n break\n }\n case \"control.agent.narrowed-demanded\": {\n const flow = asString(payload.flow)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"bad\",\n \"narrowed\",\n bodyOf(\n flow === undefined ? undefined : `${flow} ran narrower than the reading it stands in for.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n [clip(payload.broader), clip(payload.narrower)]\n )\n pin(seq, at, \"narrowed\", \"bad\")\n break\n }\n case \"control.agent.unmoved-demanded\": {\n const nextFrame = asNumber(payload.nextFrame)\n // Both digests or neither: one alone cannot tell an unmoved tree from a\n // measurement that never happened, and either may be the empty string.\n const opened = clip(payload.openedDigest)\n const current = clip(payload.currentDigest)\n note(\n seq,\n \"bad\",\n \"unmoved\",\n bodyOf(\n \"The tree the run opened on is the tree it closed on.\",\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n opened === undefined || current === undefined ? [] : [opened, current]\n )\n pin(seq, at, \"unmoved\", \"bad\")\n break\n }\n case \"control.agent.unresolved-demanded\": {\n const flow = asString(payload.flow)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"bad\",\n \"unresolved\",\n bodyOf(\n flow === undefined ? undefined : `${flow} failed and was not answered.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n [clip(payload.failed), clip(payload.instead)]\n )\n pin(seq, at, \"unresolved\", \"bad\")\n break\n }\n case \"control.agent.claim-demanded\": {\n // Written on EVERY evaluation, and a reading that neither handed the\n // completion back nor refused it cost the run nothing and changed\n // nothing, so only those two are moments anyone would scrub to. A\n // refusal is the larger of them: it ends the run and takes its answer.\n if (payload.demanded !== true && payload.refused !== true) break\n const complete = asNumber(payload.complete)\n const overclaims = asNumber(payload.overclaims)\n const nextFrame = asNumber(payload.nextFrame)\n note(\n seq,\n \"bad\",\n payload.refused === true ? \"claim refused\" : \"claim\",\n bodyOf(\n complete === undefined || overclaims === undefined\n ? undefined\n : `complete ${complete}, overclaims ${overclaims}.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n ),\n []\n )\n pin(seq, at, payload.refused === true ? \"claim refused\" : \"claim\", \"bad\")\n break\n }\n /*\n * The five kinds `AgentSession`'s `default` arm once journaled with\n * `payload: {}`, however rich their `AgentEvent` schema was:\n * cell-rejected-in-frame, read-only-demand-issued,\n * narrow-only-demanded, steering-drained and sufficiency-observed.\n * Their whole payload is late (`AgentSession` `lateFields`), so one\n * record carries every field or none, and each arm below reads what its\n * record has: a legacy record still folds, and still says nothing the\n * record does not carry. A note with no body and no evidence is a title\n * on its own, so a fieldless record writes none.\n */\n case \"control.agent.cell-rejected-in-frame\": {\n // A refused reply is a model call the frame paid for. The code is why\n // the parse refused it; the message is what the frame said back.\n const attempt = asNumber(payload.attempt)\n const code = asString(payload.code)\n const body = bodyOf(\n code === undefined ? undefined : `${code}.`,\n attempt === undefined ? undefined : `Attempt ${attempt}.`\n )\n if (body !== \"\") note(seq, \"warn\", \"rejected\", body, [clip(payload.message)])\n break\n }\n case \"control.agent.read-only-demand-issued\": {\n // The issuance's own numbers. `read-only-demanded` above carries the\n // same demand's later answer, and a run that crashes between the two\n // boundaries still has this one.\n const streak = asNumber(payload.streak)\n const cap = asNumber(payload.cap)\n const nextFrame = asNumber(payload.nextFrame)\n const body = bodyOf(\n streak === undefined || cap === undefined ? undefined : `${streak} of ${cap} frames changed nothing.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n )\n if (body !== \"\") note(seq, \"warn\", \"read-only\", body, [])\n pin(seq, at, \"read-only\", \"warn\")\n break\n }\n case \"control.agent.narrow-only-demanded\": {\n // The sibling of `narrowed-demanded`: that one fires when a broader\n // reading exists and was not re-run, this one when none was ever\n // taken. There is no broader input to quote, so the subjects the\n // demand is about stand in its place.\n const flow = asString(payload.flow)\n const targets = Array.isArray(payload.targets)\n ? payload.targets.filter((one): one is string => typeof one === \"string\")\n : []\n const nextFrame = asNumber(payload.nextFrame)\n const body = bodyOf(\n flow === undefined || targets.length === 0\n ? undefined\n : `${flow} ran on ${targets.join(\", \")} and nothing broader.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n )\n if (body !== \"\") note(seq, \"warn\", \"narrow-only\", body, [clip(payload.check)])\n pin(seq, at, \"narrow-only\", \"warn\")\n break\n }\n case \"control.agent.steering-drained\": {\n // A drain is written at every frame boundary, and the queue is empty\n // at almost all of them. Only messages ON the record establish that a\n // person reached the run, so an empty drain is not a moment and a\n // legacy record \u2014 which carries no messages either way \u2014 cannot be\n // read as one. A steer too large to trace was still delivered; the\n // record says so even where its words are gone.\n const messages = Array.isArray(payload.messages) ? payload.messages : []\n if (messages.length === 0) break\n note(\n seq,\n \"warn\",\n \"steering\",\n messages.length === 1 ? \"1 steer.\" : `${messages.length} steers.`,\n messages.map((message) => clip(asRecord(message).text))\n )\n pin(seq, at, \"steering\", \"warn\")\n break\n }\n case \"control.agent.sufficiency-observed\": {\n // The one observation that rewards a run rather than braking it: a\n // failing check answered by a passing one. The two inputs are the\n // whole of it, so they are quoted.\n const flow = asString(payload.flow)\n const nextFrame = asNumber(payload.nextFrame)\n const body = bodyOf(\n flow === undefined ? undefined : `${flow} failed before the change and passed after it.`,\n nextFrame === undefined ? undefined : `Frame ${nextFrame}.`\n )\n if (body !== \"\") note(seq, \"good\", \"sufficiency\", body, [clip(payload.failed), clip(payload.passed)])\n pin(seq, at, \"sufficiency\", \"good\")\n break\n }\n case \"control.run.completed\":\n case \"control.run.failed\":\n case \"control.run.cancelled\": {\n const verdict = kind.slice(\"control.run.\".length)\n // A person's stop reads as the product word every surface uses, and\n // is never drawn as a failure.\n if (verdict === \"cancelled\") pin(seq, at, \"stopped\", \"muted\")\n else pin(seq, at, verdict, verdict === \"completed\" ? \"good\" : \"bad\")\n break\n }\n default:\n break\n }\n // After the record's own arm, so a turn-opened belongs to the frame it\n // opened: the rule `here()` already gives a note and a pin.\n owners.push({ seq, spanId: here() })\n }\n state.frame = frame\n}\n\n/**\n * What {@link disciplineStep} has read so far, as the model's arrays.\n *\n * The derived rows are rebuilt from the frames; the recorded ones are copied,\n * so a model taken now never sees a record stepped after it.\n */\nconst disciplineModel = (\n state: DisciplineState\n): Pick<TraceModel, \"bands\" | \"milestones\" | \"lines\" | \"notes\" | \"owners\"> => {\n const { frames, lastAt } = state\n const notes = state.notes.slice()\n const milestones = state.milestones.slice()\n const owners = state.owners.slice()\n\n // A measured unchanged tree is authoritative even when a write succeeded.\n const changed = frames.map((entry) => entry.observedMutation ?? (entry.mutated === true || madeAWrite(entry)))\n\n // A repeated call is only evidence of a stall inside a STREAK, and only\n // across a span the workspace never moved in.\n //\n // Re-running one check after an edit is the OPPOSITE of a stall: it is the\n // answer `control.agent.sufficiency-observed` rewards. A rule that flagged\n // any second occurrence of a call would mark that good frame and a looping\n // one identically, and a rule that only checked THIS frame for a change\n // would still flag it, because the edit it answers happened in the frame\n // before. So a change resets what a first occurrence is: a call is judged\n // against the last time it ran on THIS tree, never against a run from before\n // an edit landed. On top of that a repeat counts only where the frames beside\n // it repeat too \u2014 each of them recording no change of its own \u2014 and\n // `repeatOf` is set only inside a streak of two or more such frames. Every\n // substantive call must repeat a settled reading; a fresh call, new result,\n // or pending result means this frame has not been shown to be redundant.\n const firstSeen = new Map<string, number>()\n const repeatedFrom = new Map<CallFacts, number>()\n const redundant: Array<boolean> = []\n frames.forEach((entry, index) => {\n const calls = entry.calls.filter((call) => call.flowName !== CHECKPOINT_FLOW)\n for (const call of calls) {\n if (call.settled === undefined) continue\n // A call settles once, so its reading is built once, not per model taken.\n call.reading ??= `${call.signature} ${JSON.stringify(call.settled)}`\n const reading = call.reading\n const seen = firstSeen.get(reading)\n if (seen === undefined) firstSeen.set(reading, entry.frame)\n else if (seen < entry.frame) repeatedFrom.set(call, seen)\n }\n redundant.push(calls.length > 0 && calls.every((call) => repeatedFrom.has(call)))\n // The tree moved in this frame, so every call recorded before it ran\n // against a tree that no longer exists and none of them can be repeated.\n if (changed[index] === true) firstSeen.clear()\n })\n const stalling = frames.map((_frame, index) => redundant[index] === true && changed[index] !== true)\n const stuck = stalling.map((flag, index) => flag && (stalling[index - 1] === true || stalling[index + 1] === true))\n\n // Phase, most specific rule first. The last rule is the honesty one: every\n // other word is a claim about what the frame was doing, and `researching` is\n // as much of a claim as the rest. A frame this fold cannot name one call for\n // is a frame it declines to write a line about, so it declines to name a\n // phase for it too.\n const phases = frames.map((entry, index): PhaseId =>\n entry.blocked\n ? \"blocked\"\n : stuck[index] === true\n ? \"stuck\"\n : changed[index] === true || entry.calls.some((call) => call.activity === \"writes\")\n ? \"implementing\"\n : entry.calls.some((call) => call.activity === \"checks\" || call.activity === \"tests\")\n ? \"testing\"\n : entry.calls.some((call) => call.activity === \"reads\")\n ? \"researching\"\n : \"unrecorded\"\n )\n\n const bands: Array<PhaseBand> = []\n frames.forEach((entry, index) => {\n const phase = phases[index]!\n // A frame's band ends where the next frame opens, and the last one ends\n // where the journal does: the rule the tree's own frames close by.\n const endedAt = frames[index + 1]?.startedAt ?? Math.max(entry.endedAt, lastAt)\n const last = bands[bands.length - 1]\n if (last !== undefined && last.phase === phase) {\n bands[bands.length - 1] = { ...last, endedAt, frames: [...last.frames, entry.id] }\n return\n }\n bands.push({ phase, startedAt: entry.startedAt, endedAt, frames: [entry.id], seq: entry.seq })\n })\n\n const lines = frames.flatMap((entry, index): ReadonlyArray<FrameLine> => {\n const call = dominantCall(entry)\n // A frame that called nothing has no line. Absence is absence.\n if (call === undefined) return []\n const repeatOf = stuck[index] === true ? repeatedFrom.get(call) : undefined\n const held = state.lineOf.get(entry)\n if (held !== undefined && held.call === call && held.settled === call.settled && held.repeatOf === repeatOf) {\n return [held.line]\n }\n const outcome = call.settled === undefined\n ? \"pending\"\n : call.settled.failed || call.settled.denied\n ? \"failure\"\n : \"success\"\n const line: FrameLine = {\n spanId: entry.id,\n frame: entry.frame,\n verb: call.presentation?.verb[outcome] ??\n `${call.flowName}${outcome === \"pending\" ? \" pending\" : outcome === \"failure\" ? \" failed\" : \"\"}`,\n subject: callSubject(call.input, call.presentation?.subject),\n // Read supported output fields through the descriptor's presentation.\n // The selected call retains the raw value, including unsupported shapes.\n result: call.settled?.failed === true\n ? clip(call.settled.result) ?? \"\"\n : resultOf(call.settled?.value, call.presentation?.result),\n failed: call.settled?.failed === true,\n wrote: call.activity === \"writes\" && call.settled?.failed === false && !call.settled.denied,\n ...(repeatOf === undefined ? {} : { repeatOf })\n }\n state.lineOf.set(entry, { call, settled: call.settled, repeatOf, line })\n return [line]\n })\n\n return { bands, milestones, lines, notes, owners }\n}\n\n/** The run a fold belongs to; its status is read when a model is taken. */\ntype TraceIdentity = Omit<TraceRun, \"status\">\n\n/**\n * One dispatch's span fold, advanced one record at a time.\n *\n * Every field is what {@link foldStep} has read so far. The builders are live:\n * a model is taken by freezing them, never by handing them out.\n */\ninterface FoldState {\n readonly run: TraceIdentity\n readonly root: Builder\n frame: Builder | undefined\n cell: Builder | undefined\n frames: number\n calls: number\n seat: string | undefined\n lastAt: number\n /** Records stepped after deduplication: `ordered.length`. */\n count: number\n /** The journal's own verdict, from a `control.run.*` record. */\n verdict: string | undefined\n readonly openCalls: Array<{ readonly flowName: string; readonly callId?: string | undefined; readonly span: Builder }>\n readonly approvals: Map<string, Builder>\n readonly discipline: DisciplineState\n /** The native rows of this fold's own input, in order. */\n readonly engine: Array<JournalRecord>\n /** {@link engineTraceFromJournal} of `engine`, until another row arrives. */\n engineTrace: ReadonlyArray<Builder> | undefined\n /** The span each builder last froze to. */\n readonly frozen: WeakMap<Builder, TraceSpan>\n /**\n * The run's direct children a step may have changed since the last model.\n * Every other child is a closed subtree, and its frozen span is reused as is.\n */\n readonly dirty: Set<Builder>\n /** The run's direct child a call or approval span sits under, for {@link dirty}. */\n readonly topOf: WeakMap<Builder, Builder>\n}\n\nconst isEngineRow = (record: JournalRecord): boolean =>\n record.kind === \"control.engine.event\" || record.kind === \"control.engine.projection-gap\"\n\nconst foldInit = (run: TraceIdentity): FoldState => ({\n run,\n root: builder(`run:${run.runId}`, \"run\", `run ${run.runId} \u00B7 ${run.flowId}`, \"running\", 0, {\n ...(run.kind === undefined ? {} : { fields: { kind: run.kind } })\n }),\n frame: undefined,\n cell: undefined,\n frames: 0,\n calls: 0,\n seat: undefined,\n lastAt: 0,\n count: 0,\n verdict: undefined,\n openCalls: [],\n approvals: new Map(),\n discipline: disciplineInit(run.runId),\n engine: [],\n engineTrace: undefined,\n frozen: new WeakMap(),\n dirty: new Set(),\n topOf: new WeakMap()\n})\n\n/**\n * Folds one record, in sequence order, into a dispatch's trace.\n *\n * Frames open on `turn-opened` and close when the next opens or the run ends;\n * cells open on `cell-produced` and close on `cell-settled`; calls open on\n * `cell-call-started` under the open cell (or the frame, when a call is\n * journaled outside a cell) and settle by stable call identity the way the gateway's own\n * `run-tree` pairs them, so a call's `call-N` id is the node id the\n * `node-output` projection knows it by. A journal with no records yields the\n * run root alone, wearing the run's status: the honest empty trace.\n *\n * The same records fold a second time, into what a person would say the run\n * was doing: see {@link disciplineStep}.\n */\nconst foldStep = (state: FoldState, record: JournalRecord): void => {\n if (isEngineRow(record)) {\n state.engine.push(record)\n state.engineTrace = undefined\n }\n // route receives only the records kept by the shared call-event filter.\n const { root, openCalls, approvals, dirty, topOf } = state\n let { frame, cell, frames, calls, seat } = state\n const top = frame ?? cell\n if (top !== undefined) dirty.add(top)\n /** Marks the run's child that `span` sits under as changed. */\n const touch = (span: Builder): void => {\n // Both callers retrieve spans registered in topOf when they were opened.\n dirty.add(topOf.get(span)!)\n }\n /** Where a new span attaches: the open cell, else the open frame, else the run. */\n const parent = (): Builder => cell ?? frame ?? root\n const closeCell = (at: number, status: SpanStatus): void => {\n if (cell === undefined) return\n cell.endedAt = at\n cell.status = status\n cell = undefined\n }\n const closeFrame = (at: number): void => {\n if (frame === undefined) return\n closeCell(at, cell?.children.some((child) => child.status === \"failed\") === true ? \"failed\" : \"completed\")\n frame.endedAt = at\n frame.status = frame.children.some((child) => child.status === \"failed\") ? \"failed\" : \"completed\"\n frame = undefined\n }\n\n {\n const kind = record.kind ?? \"\"\n const payload = asRecord(record.payload)\n const at = timeOf(record, payload)\n if (state.count === 0) {\n root.startedAt = at\n state.lastAt = at\n } else state.lastAt = Math.max(state.lastAt, at)\n state.count += 1\n const opened = { sequence: record.sequence, event: kind }\n switch (kind) {\n case \"control.engine.event\":\n case \"control.engine.projection-gap\":\n case \"control.engine.projection-started\":\n case \"control.engine.projection-settled\":\n // Native records have their own identities and lifecycle. Never put\n // them under whichever agent frame happened to be open at ingestion.\n break\n case \"control.agent.turn-opened\": {\n closeFrame(at)\n frames += 1\n seat = asString(payload.seat) ?? seat\n frame = builder(\n `frame-${frames}`,\n \"frame\",\n `frame ${frames}${seat === undefined ? \"\" : ` \u00B7 ${seat}`}`,\n \"running\",\n at,\n {\n ...opened,\n ...(seat === undefined ? {} : { seat }),\n fields: restOf(payload, [\"seat\"])\n }\n )\n root.children.push(frame)\n break\n }\n case \"control.agent.model-settled\": {\n const usage = asRecord(payload.usage)\n const duration = asNumber(payload.durationMillis)\n const span = builder(\n `model-${record.sequence ?? at}`,\n \"model\",\n \"model\",\n \"completed\",\n duration === undefined ? at : at - duration,\n {\n ...opened,\n ...(seat === undefined ? {} : { seat }),\n output: textOf(payload.text),\n usage: { inputTokens: asNumber(usage.inputTokens), outputTokens: asNumber(usage.outputTokens) },\n fields: restOf(payload, [\"text\", \"usage\", \"durationMillis\"])\n }\n )\n span.endedAt = at\n ;(frame ?? root).children.push(span)\n break\n }\n case \"control.agent.cell-produced\": {\n closeCell(at, \"completed\")\n const language = asString(payload.language)\n cell = builder(\n `cell-${record.sequence ?? at}`,\n \"cell\",\n `cell${language === undefined ? \"\" : ` \u00B7 ${language}`}`,\n \"running\",\n at,\n {\n ...opened,\n source: asString(payload.text),\n fields: restOf(payload, [\"text\", \"language\"])\n }\n )\n ;(frame ?? root).children.push(cell)\n break\n }\n case \"control.agent.cell-call-started\": {\n calls += 1\n const recordedName = asString(payload.flowName)\n const flowName = recordedName ?? `call-${calls}`\n const span = builder(`call-${calls}`, \"call\", inspectLabel(flowName), \"running\", at, {\n ...opened,\n ...(recordedName === undefined ? {} : { flowName: recordedName }),\n input: payload.input,\n fields: restOf(payload, [\"flowName\", \"input\"])\n })\n openCalls.push({ flowName, callId: asString(payload.callId), span })\n topOf.set(span, frame ?? cell ?? span)\n parent().children.push(span)\n break\n }\n case \"control.agent.cell-call-settled\": {\n const index = openCallIndex(openCalls, asString(payload.callId), asString(payload.flowName))\n const settled = index < 0 ? undefined : openCalls.splice(index, 1)[0]\n if (settled === undefined) break\n const failed = asString(payload.outcome) === \"failure\"\n touch(settled.span)\n settled.span.endedAt = at\n settled.span.status = failed ? \"failed\" : \"completed\"\n settled.span.detail = {\n ...settled.span.detail,\n ...(failed ? { message: textOf(payload.message) } : { output: textOf(payload.value) }),\n ...(!failed && settled.flowName === \"agent/spawn\" && asString(asRecord(payload.value).child) !== undefined\n ? { childRunId: asString(asRecord(payload.value).child) }\n : {})\n }\n break\n }\n case \"control.agent.cell-printed\": {\n if (cell === undefined) {\n parent().children.push(\n builder(`printed-${record.sequence ?? at}`, \"event\", \"printed\", \"completed\", at, {\n ...opened,\n printed: textOf(payload.text)\n })\n )\n break\n }\n cell.detail = {\n ...cell.detail,\n printed: [cell.detail.printed, textOf(payload.text)].filter((text) => text !== undefined).join(\"\\n\")\n }\n break\n }\n case \"control.agent.cell-settled\": {\n closeCell(at, asString(payload.outcome) === \"failure\" ? \"failed\" : \"completed\")\n break\n }\n case \"control.agent.resolved\": {\n const span = builder(`resolved-${record.sequence ?? at}`, \"resolved\", \"resolved\", \"completed\", at, {\n ...opened,\n output: textOf(payload.text)\n })\n span.endedAt = at\n ;(frame ?? root).children.push(span)\n break\n }\n case \"control.approval.requested\": {\n const requestId = asString(payload.requestId) ?? `approval-${record.sequence ?? at}`\n const question = asString(payload.question)\n const span = builder(\n `approval-${requestId}`,\n \"approval\",\n `approval${question === undefined ? \"\" : ` \u00B7 ${question}`}`,\n \"waiting\",\n at,\n {\n ...opened,\n fields: restOf(payload, [\"question\", \"requestId\", \"payload\", \"runId\"])\n }\n )\n approvals.set(requestId, span)\n topOf.set(span, frame ?? span)\n ;(frame ?? root).children.push(span)\n break\n }\n case \"control.approval.approved\":\n case \"control.approval.denied\": {\n const decided = kind === \"control.approval.approved\" ? \"approved\" : \"denied\"\n const key = asString(payload.tokenId) ?? asString(payload.requestId)\n const span = key === undefined\n ? [...approvals.values()].find((entry) => entry.status === \"waiting\")\n : approvals.get(key)\n if (span === undefined) break\n touch(span)\n span.status = decided\n span.endedAt = at\n break\n }\n case \"control.run.completed\":\n case \"control.run.failed\":\n case \"control.run.cancelled\": {\n closeFrame(at)\n root.endedAt = at\n // The journal's own verdict outranks the card's phase word: a scrub to this record shows the run settled.\n state.verdict = kind.slice(\"control.run.\".length)\n break\n }\n default: {\n if (!kind.startsWith(\"control.\")) break\n const span = builder(\n `event-${record.sequence ?? at}`,\n \"event\",\n kind.slice(\"control.\".length),\n \"completed\",\n at,\n {\n ...opened,\n fields: restOf(payload, [])\n }\n )\n span.endedAt = at\n parent().children.push(span)\n if (kind === \"control.agent.turn-closed\" && payload.step !== undefined) {\n const closed = frame\n closeFrame(at)\n if (closed !== undefined && payload.outcome === \"suspended\") closed.status = \"waiting\"\n if (closed !== undefined && payload.outcome === \"aborted\") closed.status = \"cancelled\"\n }\n }\n }\n }\n Object.assign(state, { frame, cell, frames, calls, seat })\n const after = frame ?? cell\n if (after !== undefined) dirty.add(after)\n disciplineStep(state.discipline, record)\n}\n\n/**\n * The trace {@link foldStep} has read so far, as the run with `status` would\n * show it.\n *\n * Nothing live is mutated. A settled run closes its open frame where the\n * journal ends, so that close is applied to the frozen copy only.\n */\nconst foldModel = (\n state: FoldState,\n status: string,\n journal: ReadonlyArray<JournalRecord>,\n engine?: ReadonlyArray<Builder>\n): TraceModel => {\n const { root, frame, cell, lastAt } = state\n const closed = new Map<Builder, { readonly status: SpanStatus; readonly endedAt: number }>()\n const statusOf = (node: Builder): SpanStatus => closed.get(node)?.status ?? node.status\n // A settled run leaves no frame open: the last frame ends where the journal does.\n const terminal = TERMINAL_RUN.has(status)\n if (terminal && frame !== undefined) {\n if (cell !== undefined) {\n closed.set(cell, {\n status: cell.children.some((child) => child.status === \"failed\") ? \"failed\" : \"completed\",\n endedAt: lastAt\n })\n }\n closed.set(frame, {\n status: frame.children.some((child) => statusOf(child) === \"failed\") ? \"failed\" : \"completed\",\n endedAt: lastAt\n })\n }\n if (engine === undefined && state.engineTrace === undefined) state.engineTrace = engineTraceFromJournal(state.engine)\n const children = [...root.children, ...(engine ?? state.engineTrace!)]\n closed.set(root, {\n status: state.verdict ?? status,\n endedAt: root.endedAt ?? (terminal && state.count > 0 ? lastAt : Number.NaN)\n })\n\n const freeze = (node: Builder, depth: number, members: ReadonlyArray<Builder>): TraceSpan =>\n freezeWith(node, depth, members.map((child) => freeze(child, depth + 1, child.children)))\n const freezeWith = (node: Builder, depth: number, frozenChildren: ReadonlyArray<TraceSpan>): TraceSpan => {\n const override = closed.get(node)\n const nodeStatus = override?.status ?? node.status\n const endedAt = override === undefined || Number.isNaN(override.endedAt) ? node.endedAt : override.endedAt\n const held = state.frozen.get(node)\n if (\n held !== undefined && held.depth === depth && held.label === node.label && held.status === nodeStatus &&\n held.startedAt === node.startedAt && held.endedAt === endedAt && held.detail === node.detail &&\n held.children.length === frozenChildren.length &&\n held.children.every((child, index) => child === frozenChildren[index])\n ) return held\n const span: TraceSpan = {\n id: node.id,\n kind: node.kind,\n label: node.label,\n status: nodeStatus,\n startedAt: node.startedAt,\n ...(endedAt === undefined ? {} : { endedAt }),\n depth,\n children: frozenChildren,\n detail: node.detail\n }\n state.frozen.set(node, span)\n return span\n }\n // A child no step touched since the last model is a closed subtree: its\n // frozen span stands, and nothing under it is walked again.\n const settledChild = (child: Builder): TraceSpan | undefined => {\n if (state.dirty.has(child) || closed.has(child)) return undefined\n const held = state.frozen.get(child)\n return held?.depth === 1 ? held : undefined\n }\n const frozenChildren = children.map((child) => settledChild(child) ?? freeze(child, 1, child.children))\n state.dirty.clear()\n const frozenRoot = freezeWith(root, 0, frozenChildren)\n const rows: Array<TraceSpan> = []\n const walk = (span: TraceSpan): void => {\n rows.push(span)\n for (const child of span.children) walk(child)\n }\n walk(frozenRoot)\n let start = Number.POSITIVE_INFINITY\n let end = 0\n let running = 0\n let failed = 0\n for (const span of rows) {\n start = Math.min(start, span.startedAt)\n end = Math.max(end, span.endedAt ?? span.startedAt)\n if (span.kind !== \"run\" && span.status === \"running\") running += 1\n if (span.kind !== \"run\" && span.status === \"failed\") failed += 1\n }\n const extent = state.count === 0 || !Number.isFinite(start)\n ? { start: 0, end: 0 }\n : { start, end: Math.max(end, start) }\n return {\n journal,\n root: frozenRoot,\n rows,\n extent,\n counts: { spans: rows.length - 1, running, failed },\n ...disciplineModel(state.discipline)\n }\n}\n\n/**\n * A run's trace fold, advanced one record at a time.\n *\n * {@link traceFromJournal} is {@link traceFold} over the whole journal and then\n * {@link traceFoldModel}; a live reader keeps the fold and hands it each new\n * record with {@link traceFoldStep}, so a record costs its own work rather than\n * a refold of the journal before it. The fold is mutable: stepping it consumes\n * the value it was, and a reader that needs an older trace takes a model first.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TraceFold {\n readonly run: Omit<TraceRun, \"status\">\n /** Every record stepped, in sequence order: the model's `journal`. */\n readonly journal: ReadonlyArray<JournalRecord>\n}\n\ninterface FoldTop extends TraceFold {\n /** Records as they arrived, so a refold sorts exactly what the batch sorts. */\n arrived: Array<JournalRecord>\n journal: Array<JournalRecord>\n filter: CallEventFilter<JournalRecord>\n base: FoldState\n groups: Map<string, FoldState>\n /** The native rows of the raw journal, read while no record names a step. */\n engine: Array<JournalRecord>\n engineTrace: ReadonlyArray<Builder> | undefined\n firstAt: number\n terminal: JournalRecord | undefined\n /**\n * The records {@link traceFoldSync} last consumed, copied so a caller that\n * grows or rewrites its own array in place is still compared to what was read.\n */\n source: ReadonlyArray<JournalRecord> | undefined\n memo: { readonly status: string; readonly model: TraceModel } | undefined\n}\n\nconst sequenceOf = (record: JournalRecord): number => record.sequence ?? 0\n\nconst TERMINAL_KINDS: ReadonlySet<string> = new Set([\n \"control.run.completed\",\n \"control.run.failed\",\n \"control.run.cancelled\"\n])\n\n/** One deduplicated record to the fold of the dispatch it was recorded under. */\nconst route = (state: FoldTop, record: JournalRecord): void => {\n // A run verdict stamped with another run's id (a child's, riding in this\n // journal) must not settle this run's trace or pin its milestone.\n if (\n record.kind?.startsWith(\"control.run.\") === true && record.runId !== undefined && record.runId !== state.run.runId\n ) {\n return\n }\n state.firstAt = Math.min(state.firstAt, timeOf(record, asRecord(record.payload)))\n if (TERMINAL_KINDS.has(record.kind ?? \"\")) state.terminal = record\n const scope = callScope(record)\n if (scope === undefined) return foldStep(state.base, record)\n let group = state.groups.get(scope)\n if (group === undefined) {\n group = foldInit(state.run)\n state.groups.set(scope, group)\n }\n foldStep(group, record)\n}\n\n/** Refolds `arrived` from nothing: the batch rules, exactly. */\nconst reseed = (state: FoldTop, arrived: Array<JournalRecord>): void => {\n const journal = [...arrived].sort((left, right) => sequenceOf(left) - sequenceOf(right))\n const filter = callEventFilter<JournalRecord>()\n for (const record of journal) filter.push(record)\n Object.assign(state, {\n arrived,\n journal,\n filter,\n base: foldInit(state.run),\n groups: new Map(),\n engine: journal.filter(isEngineRow),\n engineTrace: undefined,\n firstAt: Number.POSITIVE_INFINITY,\n terminal: undefined,\n memo: undefined\n })\n for (const record of uniqueCallEvents(journal)) route(state, record)\n}\n\n/**\n * Folds `records` into a fold that later records can be stepped onto.\n *\n * @param run the run the journal belongs to\n * @param records its journal so far, in any order\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const traceFold = (run: Omit<TraceRun, \"status\">, records: ReadonlyArray<JournalRecord> = []): TraceFold => {\n const state = {\n run: { runId: run.runId, flowId: run.flowId, ...(run.kind === undefined ? {} : { kind: run.kind }) }\n } as FoldTop\n state.source = undefined\n reseed(state, [...records])\n return state\n}\n\n/**\n * Folds one more record onto `fold`, which it returns.\n *\n * A record in sequence order costs its own work. One that arrives before a\n * sequence already stepped, or a native fact that supersedes telemetry the\n * fold already placed, refolds the journal, because the batch rules move an\n * earlier record for both.\n *\n * @param fold the fold; consumed\n * @param record the next journal record\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const traceFoldStep = (fold: TraceFold, record: JournalRecord): TraceFold => {\n const state = fold as FoldTop\n state.memo = undefined\n state.arrived.push(record)\n const last = state.journal.at(-1)\n if (last !== undefined && !(sequenceOf(record) >= sequenceOf(last))) {\n reseed(state, state.arrived)\n return fold\n }\n state.journal.push(record)\n if (isEngineRow(record)) {\n state.engine.push(record)\n state.engineTrace = undefined\n }\n const verdict = state.filter.push(record)\n if (verdict._tag === \"rewrite\") reseed(state, state.arrived)\n else if (verdict._tag === \"keep\") route(state, verdict.event)\n return fold\n}\n\n/**\n * Brings `fold` up to `records`, stepping only what it has not read.\n *\n * `records` extends the array the fold last read when every earlier element is\n * the same object; anything else, or a different run, starts a new fold. The\n * comparison is against the records the fold consumed, not the caller's array,\n * so growing or rewriting that same array in place is seen. A reader that\n * re-renders one growing journal therefore pays per new record.\n *\n * @param fold the fold the reader holds, if any; consumed\n * @param run the run the journal belongs to\n * @param records the whole journal as the reader now holds it\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const traceFoldSync = (\n fold: TraceFold | undefined,\n run: Omit<TraceRun, \"status\">,\n records: ReadonlyArray<JournalRecord>\n): TraceFold => {\n const held = fold as FoldTop | undefined\n const source = held?.source\n const extends_ = held !== undefined && source !== undefined && held.run.runId === run.runId &&\n held.run.flowId === run.flowId && held.run.kind === run.kind && records.length >= source.length &&\n source.every((record, index) => records[index] === record)\n const next = extends_ ? held : traceFold(run) as FoldTop\n for (let index = extends_ ? source.length : 0; index < records.length; index++) traceFoldStep(next, records[index]!)\n next.source = records.slice()\n return next\n}\n\n/**\n * The trace a fold has read, as the run with `status` shows it.\n *\n * Taken again without a step between, it is the same object.\n *\n * @param fold the fold\n * @param status the run card's phase word\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const traceFoldModel = (fold: TraceFold, status: string): TraceModel => {\n const state = fold as FoldTop\n if (state.memo?.status === status) return state.memo.model\n const model = mergeModel(state, status)\n state.memo = { status, model }\n return model\n}\n\nconst mergeModel = (state: FoldTop, status: string): TraceModel => {\n const journal = state.journal.slice()\n if (state.groups.size === 0) {\n if (state.engineTrace === undefined) state.engineTrace = engineTraceFromJournal(state.engine)\n return foldModel(state.base, status, journal, state.engineTrace)\n }\n const base = foldModel(state.base, status, journal)\n const children = [...base.root.children]\n const bands = [...base.bands]\n const milestones = [...base.milestones]\n const lines = [...base.lines]\n const notes = [...base.notes]\n const owners = [...base.owners]\n const terminal = state.terminal\n const terminalAt = terminal === undefined ? undefined : timeOf(terminal, asRecord(terminal.payload))\n for (const [scope, group] of state.groups) {\n const prefix = `step:${encodeURIComponent(scope)}/`\n const scoped = foldModel(group, \"running\", journal)\n const rename = (span: TraceSpan): TraceSpan => ({\n ...span,\n id: `${prefix}${span.id}`,\n children: span.children.map(rename),\n ...(span.status === \"running\" && TERMINAL_RUN.has(base.root.status) ?\n {\n // A terminal run proves work stopped. It does not prove which open\n // step succeeded or caused the run to fail.\n status: \"stopped\",\n ...(terminalAt === undefined ? {} : { endedAt: terminalAt })\n } :\n {})\n })\n children.push(...scoped.root.children.map(rename))\n bands.push(...scoped.bands.map((band) => ({ ...band, frames: band.frames.map((id) => `${prefix}${id}`) })))\n // A moment, a line, a note and a position all name the frame they were\n // recorded under, so the merge renames each of them the same way: the\n // step's own frame, or this run's root for what the step recorded outside\n // any frame.\n const owned = (spanId: string): string => spanId === scoped.root.id ? base.root.id : `${prefix}${spanId}`\n milestones.push(...scoped.milestones.map((one) => ({ ...one, spanId: owned(one.spanId) })))\n lines.push(...scoped.lines.map((line) => ({ ...line, spanId: `${prefix}${line.spanId}` })))\n notes.push(...scoped.notes.map((note) => ({ ...note, spanId: owned(note.spanId) })))\n owners.push(...scoped.owners.map((one) => ({ ...one, spanId: owned(one.spanId) })))\n }\n children.sort((left, right) =>\n left.startedAt - right.startedAt || (left.detail.sequence ?? 0) - (right.detail.sequence ?? 0)\n )\n const root = { ...base.root, startedAt: state.firstAt, children }\n const rows: Array<TraceSpan> = []\n const walk = (span: TraceSpan): void => {\n rows.push(span)\n span.children.forEach(walk)\n }\n walk(root)\n const positions = new Map(rows.map((span, index) => [span.id, index]))\n // Each step folds its own frames from 1, so a merged run would print two\n // rows numbered 1 and a `same as 1` that names either. The merged list\n // numbers the rows a person reads, and a repeat names the renumbered row of\n // the step that recorded it.\n const merged = lines.sort((left, right) => positions.get(left.spanId)! - positions.get(right.spanId)!)\n const stepOf = (spanId: string): string => spanId.slice(0, spanId.lastIndexOf(\"/\") + 1)\n const renumbered = new Map(merged.map((line, index) => [`${stepOf(line.spanId)}${line.frame}`, index + 1]))\n let start = Number.POSITIVE_INFINITY\n let end = Number.NEGATIVE_INFINITY\n for (const span of rows) {\n start = Math.min(start, span.startedAt)\n end = Math.max(end, span.endedAt ?? span.startedAt)\n }\n return {\n journal,\n root,\n rows,\n extent: { start, end },\n counts: {\n spans: rows.length - 1,\n running: rows.filter((span) => span.kind !== \"run\" && span.status === \"running\").length,\n failed: rows.filter((span) => span.kind !== \"run\" && span.status === \"failed\").length\n },\n bands: bands.sort((left, right) => left.startedAt - right.startedAt || left.seq - right.seq),\n milestones: milestones.sort((left, right) => left.seq - right.seq),\n lines: merged.map((line, index) => ({\n ...line,\n frame: index + 1,\n ...(line.repeatOf === undefined\n ? {}\n : { repeatOf: renumbered.get(`${stepOf(line.spanId)}${line.repeatOf}`)! })\n })),\n notes: notes.sort((left, right) => left.seq - right.seq),\n owners: owners.sort((left, right) => left.seq - right.seq)\n }\n}\n\n/**\n * Fold each recorded dispatch independently, keeping prompt-run addresses unchanged.\n *\n * The same fold a live reader advances with {@link traceFoldStep}, taken over\n * the whole journal at once.\n *\n * The options the card carries are accepted and read by nothing: a plan's\n * check targets are a coverage requirement, and a requirement is not evidence\n * that any call ran it. Every word this fold says is read off a record.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const traceFromJournal = (\n run: TraceRun,\n records: ReadonlyArray<JournalRecord>,\n _options: TraceOptions = {}\n): TraceModel => traceFoldModel(traceFold(run, records), run.status)\n\n/**\n * One span's bar on the shared axis, as percentages. An open span runs to the\n * axis end; an instant span is zero width and renders as a marker.\n *\n * @param span the span\n * @param extent the axis\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const waterfallGeometry = (\n span: TraceSpan,\n extent: TraceExtent\n): { readonly left: number; readonly width: number } => {\n const width = Math.max(extent.end - extent.start, 1)\n const from = span.startedAt\n const to = span.endedAt ?? extent.end\n const left = ((from - extent.start) / width) * 100\n const bar = Math.max(((to - from) / width) * 100, 0)\n return { left: Math.round(left * 100) / 100, width: Math.round(bar * 100) / 100 }\n}\n\n/**\n * The axis the phase strip measures on: the bands' own span when the journal\n * opened frames, the run's whole extent when it opened none.\n *\n * A milestone is a journal record, and the records that write one do not need a\n * frame: a journal of `read-only-demanded` and `sufficiency-observed` with no\n * `turn-opened` carries two moments and opens no band. Milestones therefore\n * survive without bands, and the axis that places them cannot be read off the\n * bands alone. The other choice \u2014 dropping a moment because no band was drawn\n * beside it \u2014 would be this fold deciding a record the journal made did not\n * happen, which is the one thing it may never do.\n *\n * @param model the trace\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const phaseExtent = (model: TraceModel): TraceExtent => {\n return model.bands.length === 0 ? model.extent : {\n start: Math.min(...model.bands.map((band) => band.startedAt)),\n end: Math.max(...model.bands.map((band) => band.endedAt))\n }\n}\n\n/**\n * One band's share of that axis, as percentages, the way the waterfall measures\n * a span.\n *\n * A run whose frames all land in one millisecond recorded no elapsed time. Read\n * against a floored axis every such band is zero wide at left 0, so the whole\n * strip collapses onto the left edge and says nothing at all. The bands' ORDER\n * is a journal fact even where their durations are not, so with no duration to\n * measure the ordinal IS the axis: equal slices, left to right.\n *\n * @param band the band\n * @param extent the axis, from {@link phaseExtent}\n * @param index the band's place in the strip\n * @param count how many bands the strip holds\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const phaseBandGeometry = (\n band: PhaseBand,\n extent: TraceExtent,\n index: number,\n count: number\n): { readonly left: number; readonly width: number } => {\n const round = (value: number): number => Math.round(value * 100) / 100\n const axis = extent.end - extent.start\n if (axis <= 0) {\n const share = 100 / Math.max(count, 1)\n return { left: round(index * share), width: round(share) }\n }\n return {\n left: round(((band.startedAt - extent.start) / axis) * 100),\n width: round((Math.max(band.endedAt - band.startedAt, 0) / axis) * 100)\n }\n}\n\n/** The flows whose spans are messages between a coordinator and its workers (spec 06 \u00A73). */\nconst MESSAGE_FLOWS: ReadonlySet<string> = new Set([\"agent/send\", \"agent/await\"])\n\n/** Whether a span, or any span under it, passes the filter.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const spanMatches = (span: TraceSpan, filter: TraceFilter): boolean => {\n const own = filter === \"all\"\n ? true\n : filter === \"running\"\n ? span.status === \"running\" || span.status === \"waiting\"\n : filter === \"failed\"\n ? span.status === \"failed\"\n : filter === \"model\"\n ? span.kind === \"model\"\n : filter === \"flow\"\n ? span.kind === \"call\" || span.kind === \"execution\" || span.kind === \"attempt\"\n : span.kind === \"call\" && MESSAGE_FLOWS.has(span.label)\n return own || span.children.some((child) => spanMatches(child, filter))\n}\n\n/** The tree's filters, in the slash grammar's words (spec 06 \u00A76: `runs.trace.filter <runId> <filter>`).\n *\n * @category models\n * @since 1.0.0\n */\nexport type TraceFilter = \"all\" | \"running\" | \"failed\" | \"model\" | \"flow\" | \"messages\"\n\n/**\n * Stable filter identifiers accepted by run trace commands.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const TRACE_FILTER_IDS: ReadonlyArray<TraceFilter> = [\n \"all\",\n \"running\",\n \"failed\",\n \"model\",\n \"flow\",\n \"messages\"\n]\n\nconst FILTER_LABELS: Readonly<Record<TraceFilter, string>> = {\n all: \"all\",\n running: \"running\",\n failed: \"failed\",\n model: \"model calls\",\n flow: \"flow calls\",\n messages: \"messages\"\n}\n\n/**\n * The filter chips a run of this kind shows (spec 06 \u00A72 and \u00A73): a prototype\n * has `all | messages | failed` and nothing else; every other run has the\n * shared set. `messages` is a prototype's conversation across workers, so it\n * is not offered elsewhere.\n *\n * @param kind the run's kind\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const traceFiltersFor = (kind: string | undefined): ReadonlyArray<readonly [TraceFilter, string]> =>\n (kind === \"prototype\"\n ? ([\"all\", \"messages\", \"failed\"] as const)\n : ([\"all\", \"running\", \"failed\", \"model\", \"flow\"] as const)).map((id) => [id, FILTER_LABELS[id]] as const)\n\n/** Whether a filter word is one the trace knows.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const isTraceFilter = (value: string): value is TraceFilter =>\n (TRACE_FILTER_IDS as ReadonlyArray<string>).includes(value)\n\n/** The two presentations of the same persisted run card.\n *\n * @category models\n * @since 1.0.0\n */\nexport type TraceView = \"turns\" | \"timeline\"\n\n/** A concise projection of one recorded turn, never a generated claim about intent or correctness.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TurnNarrative {\n readonly frame: TraceSpan\n readonly number: number\n readonly text: string\n readonly source: \"model\" | \"calls\" | \"journal\"\n}\n\n/** The first prose line outside fenced code, bounded for the cheap turn list. Full text stays in the model span. */\nconst proseLine = (text: string | undefined): string | undefined => {\n if (text === undefined) return undefined\n let fence: string | undefined\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim()\n const marker = /^(?:`{3,}|~{3,})/.exec(trimmed)?.[0]\n if (marker !== undefined) {\n if (fence === undefined) fence = marker\n else if (marker[0] === fence[0] && marker.length >= fence.length) fence = undefined\n continue\n }\n if (fence !== undefined || trimmed === \"\") continue\n // A code-only response or the journal's truncated-field object is not explanatory prose.\n if (/^(?:[[{]|(?:const|let|var|await|import|export|function|return)\\b)/.test(trimmed)) return undefined\n const words = trimmed.replace(/^#{1,6}\\s+|^[-*+]\\s+|^>\\s+/, \"\").replace(/\\s+/g, \" \")\n const sentence = words.match(/^.*?[.!?](?=\\s|$)/)?.[0] ?? `${words}.`\n return sentence.length <= 180 ? sentence : `${sentence.slice(0, 179).trimEnd()}\u2026`\n }\n return undefined\n}\n\n/** One cheap line per turn; falls back to actual call names when the model recorded only code.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const turnNarratives = (model: TraceModel): ReadonlyArray<TurnNarrative> =>\n model.root.children.filter((span) => span.kind === \"frame\").map((frame, index) => {\n const text = frame.children.filter((span) => span.kind === \"model\").map((span) => proseLine(span.detail.output))\n .find((value) => value !== undefined)\n if (text !== undefined) return { frame, number: index + 1, text, source: \"model\" }\n const names: Array<string> = []\n const walk = (span: TraceSpan): void => {\n if (span.kind === \"call\" && !names.includes(span.label)) names.push(span.label)\n for (const child of span.children) walk(child)\n }\n walk(frame)\n return names.length > 0\n ? {\n frame,\n number: index + 1,\n text: `The agent called ${names.slice(0, 3).join(\", \")}${\n names.length > 3 ? ` and ${names.length - 3} other flows` : \"\"\n }.`,\n source: \"calls\"\n }\n : {\n frame,\n number: index + 1,\n text: frame.children.some((span) => span.kind === \"cell\")\n ? \"The agent produced a script; no flow calls were recorded in this turn.\"\n : frame.children.some((span) => span.kind === \"model\")\n ? \"The model responded; no script or flow calls were recorded in this turn.\"\n : \"The turn started; no model response or flow calls have been recorded.\",\n source: \"journal\"\n }\n })\n\n/** The recorded ancestry of a selection, for breadcrumbs and the selected turn's scoped call tree.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const spanPath = (model: TraceModel, id: string): ReadonlyArray<TraceSpan> => {\n const visit = (span: TraceSpan): ReadonlyArray<TraceSpan> | undefined => {\n if (span.id === id) return [span]\n for (const child of span.children) {\n const path = visit(child)\n if (path !== undefined) return [span, ...path]\n }\n return undefined\n }\n return visit(model.root) ?? [model.root]\n}\n\n/** A duration in the trace's units: milliseconds under a second, seconds under a minute, minutes and seconds under an hour, hours and minutes after.\n *\n * @category utilities\n * @since 1.0.0\n */\nexport const durationWords = (ms: number): string => {\n if (ms < 1000) return `${Math.round(ms)}ms`\n // Round before splitting, so 59.96s reads 1m00s rather than 60.0s, and 51m59.6s reads 52m00s rather than 51m60s.\n if (ms < 59_950) return `${(ms / 1000).toFixed(1)}s`\n const total = Math.round(ms / 1000)\n if (total < 3600) {\n const minutes = Math.floor(total / 60)\n return `${minutes}m${String(total - minutes * 60).padStart(2, \"0\")}s`\n }\n const minutes = Math.round(ms / 60_000)\n const hours = Math.floor(minutes / 60)\n return `${hours}h${String(minutes - hours * 60).padStart(2, \"0\")}m`\n}\n\n/** One memory item a run's relevance readings weighed.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface MemoryItem {\n readonly id: string\n readonly kind: string\n /** How likely the item is needed: 1 \u2212 Jev's probability that it is not. */\n readonly relevance: number\n}\n\n/** The memory a run was shown and the memory Jev withheld from it.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface RunMemory {\n readonly kept: ReadonlyArray<MemoryItem>\n readonly withheld: ReadonlyArray<MemoryItem>\n}\n\nconst memoryItems = (value: unknown): ReadonlyArray<MemoryItem> =>\n Array.isArray(value) ?\n value.flatMap((raw: unknown) => {\n const item = typeof raw === \"object\" && raw !== null ? raw as Record<string, unknown> : undefined\n return item?.kind === \"memory\" && typeof item.id === \"string\" && typeof item.p === \"number\"\n ? [{ id: item.id, kind: \"memory\", relevance: 1 - item.p }]\n : []\n }) :\n []\n\n/**\n * What memory a run was brought, from the `control.agent.relevance-settled`\n * rows of its `run-events` projection: ids and probabilities, never text. A\n * reading also weighs flows, skills and instructions; only memory counts here.\n * An item any reading kept is in; one only ever withheld is withheld; both\n * most relevant first. A row whose verdicts were not retained is no reading.\n * Undefined when Jev never read for the run.\n *\n * @category folds\n * @since 1.0.0\n */\nexport const runMemoryOf = (records: ReadonlyArray<JournalRecord>): RunMemory | undefined => {\n const kept = new Map<string, MemoryItem>()\n const withheld = new Map<string, MemoryItem>()\n let read = false\n for (const record of records) {\n if (record.kind !== \"control.agent.relevance-settled\") continue\n const payload = typeof record.payload === \"object\" && record.payload !== null\n ? record.payload as Record<string, unknown>\n : {}\n if (!Array.isArray(payload.kept) && !Array.isArray(payload.withheld)) continue\n read = true\n for (const item of memoryItems(payload.kept)) kept.set(item.id, item)\n for (const item of memoryItems(payload.withheld)) withheld.set(item.id, item)\n }\n if (!read) return undefined\n const byRelevance = (left: MemoryItem, right: MemoryItem) =>\n right.relevance - left.relevance || left.id.localeCompare(right.id)\n return {\n kept: [...kept.values()].sort(byRelevance),\n withheld: [...withheld.values()].filter((item) => !kept.has(item.id)).sort(byRelevance)\n }\n}\n\n/** One recorded agent action inside an engine step, as an Inspect cell.\n *\n * @category models\n * @since 1.0.0\n */\nexport interface TranscriptCell {\n readonly id: string\n readonly kind: \"read\" | \"edit\" | \"run\" | \"think\" | \"ask\"\n label: string\n code?: string\n output?: string\n quote?: string\n tokens?: number\n took_s?: number\n tone?: \"ok\" | \"fail\" | \"live\"\n}\n\n/** What the agent did inside one engine dispatch, keyed `<execution id>:<step id>`. */\ninterface StepTranscript {\n readonly cells: Array<TranscriptCell>\n tokens: number\n models: number\n /** The task the agent was given: its first request's task system part. */\n input?: unknown\n}\n\n/** The system part an agent step's task travels in (`Agent.ts`). */\nconst TASK_PREFIX = \"The task for this run:\\n\\n\"\n\n/** The agent's task from a traced request: its own `task` field, or the task\n * part of its system text when that fit the journal. Parsed when it is JSON. */\nconst taskOf = (request: Record<string, unknown>): unknown => {\n const parts = Array.isArray(request.system) ? request.system : []\n const part = parts.find((text): text is string => typeof text === \"string\" && text.startsWith(TASK_PREFIX))\n const task = typeof request.task === \"string\" ? request.task : part?.slice(TASK_PREFIX.length)\n if (task === undefined) return undefined\n try {\n return JSON.parse(task)\n } catch {\n return task\n }\n}\n\nconst hexDigest = /^[0-9a-f]{64}$/\n\n/** A transcript cell shows an excerpt; the journal keeps the full record. */\nconst cellText = (value: unknown): string | undefined => {\n const text = textOf(value)\n return text === undefined || text.length <= 2000 ? text : `${text.slice(0, 2000)}\u2026`\n}\n\n/** The recorded presentation of a tool call: \"Read t5.md\", \"Failed to write t5.md\". */\nconst callCellLabel = (started: Extract<CallFact.Fact, { phase: \"invoked\" }>, failed: boolean): string => {\n const descriptor = asRecord(started.descriptor)\n const presentation = asRecord(descriptor.presentation)\n const verbs = asRecord(presentation.verb)\n const name = started.flowName\n const verb = asString(failed ? verbs.failure : verbs.success) ?? (failed ? `failed ${name}` : name)\n const subjectKey = asString(presentation.subject)\n const subject = subjectKey === undefined ? undefined : asString(asRecord(started.input)[subjectKey])\n const text = subject === undefined ? verb : `${verb} ${subject}`\n return text.charAt(0).toUpperCase() + text.slice(1)\n}\n\nconst callCellKind = (started: Extract<CallFact.Fact, { phase: \"invoked\" }>): TranscriptCell[\"kind\"] => {\n const activity = asString(asRecord(started.descriptor).activity)\n const name = started.flowName\n return name === \"ask\" ? \"ask\" : activity === \"reads\" ? \"read\" : activity === \"writes\" ? \"edit\" : \"run\"\n}\n\nconst decodeCallFact = Schema.decodeUnknownOption(CallFact.Fact)\n\n/** A native tool-call fact and the dispatch digest its scope names. */\nconst callFactOf = (record: JournalRecord) => {\n if (record.kind !== \"control.engine.event\") return undefined\n const envelope = asRecord(record.payload)\n if (envelope.version !== 1 || envelope.eventType !== CallFact.eventType || envelope.sourceSequence !== 0) {\n return undefined\n }\n const fact = decodeCallFact(envelope.payload)\n if (fact._tag === \"None\" || envelope.sourceId !== `call-fact-v1:${fact.value.callId}:${fact.value.phase}`) {\n return undefined\n }\n const stepId = /@([0-9a-f]{64}):\\d+#\\d+$/.exec(fact.value.identity.runId)?.[1]\n return stepId === undefined ? undefined : { stepId, fact: fact.value }\n}\n\n/**\n * The agent transcript of every native dispatch in `journal`: model replies,\n * cells with what they printed, and tool calls, in journal order. Keyed by the\n * dispatch's step key digest, which the engine's node settlement names in\n * `stepKeyDigests`. Pure over the records; no model call.\n */\nconst stepTranscripts = (journal: ReadonlyArray<JournalRecord>): ReadonlyMap<string, StepTranscript> => {\n const transcripts = new Map<string, StepTranscript>()\n const entry = (key: string) => {\n let found = transcripts.get(key)\n if (found === undefined) transcripts.set(key, found = { cells: [], tokens: 0, models: 0 })\n return found\n }\n const lastCell = new Map<string, TranscriptCell>()\n const calls = new Map<\n string,\n { readonly cell: TranscriptCell; readonly started: Extract<CallFact.Fact, { phase: \"invoked\" }> }\n >()\n for (const record of journal) {\n const sequence = record.sequence ?? 0\n const step = nativeStepEvent(record)\n if (step !== undefined) {\n const payload = asRecord(step.payload)\n // nativeStepEvent has decoded StepFact.Scope, whose stepId is a 64-digit hex string.\n const stepId = asString(asRecord(payload.step).stepId)!\n const transcript = entry(stepId)\n if (step.kind === \"control.agent.model-requested\" && transcript.input === undefined) {\n const task = taskOf(payload)\n if (task !== undefined) transcript.input = task\n } else if (step.kind === \"control.agent.model-settled\") {\n const usage = asRecord(payload.usage)\n const tokens = (asNumber(usage.inputTokens) ?? 0) + (asNumber(usage.outputTokens) ?? 0)\n const duration = asNumber(payload.durationMillis)\n const text = cellText(payload.text)\n transcript.tokens += tokens\n transcript.models += 1\n transcript.cells.push({\n id: `cell:${sequence}`,\n kind: \"think\",\n label: \"Model reply\",\n ...(text === undefined ? {} : { quote: text }),\n tokens,\n ...(duration === undefined ? {} : { took_s: Math.max(0, duration) / 1000 })\n })\n } else if (step.kind === \"control.agent.cell-produced\") {\n const code = cellText(payload.text)\n const cell: TranscriptCell = {\n id: `cell:${sequence}`,\n kind: \"run\",\n label: \"Ran a cell\",\n ...(code === undefined ? {} : { code })\n }\n transcript.cells.push(cell)\n lastCell.set(stepId, cell)\n } else if (step.kind === \"control.agent.cell-printed\") {\n const cell = lastCell.get(stepId)\n const printed = cellText(payload.text)\n if (cell !== undefined && printed !== undefined && printed !== \"\") {\n cell.output = cell.output === undefined ? printed : `${cell.output}\\n${printed}`\n }\n } else if (step.kind === \"control.agent.cell-settled\") {\n const cell = lastCell.get(stepId)\n if (cell !== undefined) cell.tone = asString(payload.outcome) === \"failure\" ? \"fail\" : \"ok\"\n }\n continue\n }\n const call = callFactOf(record)\n if (call === undefined) continue\n const handle = `${call.stepId}:${call.fact.callId}`\n if (call.fact.phase === \"invoked\") {\n const input = cellText(call.fact.input)\n const cell: TranscriptCell = {\n id: `cell:${sequence}`,\n kind: callCellKind(call.fact),\n label: callCellLabel(call.fact, false),\n ...(input === undefined ? {} : { code: input }),\n tone: \"live\"\n }\n entry(call.stepId).cells.push(cell)\n calls.set(handle, { cell, started: call.fact })\n continue\n }\n const open = calls.get(handle)\n if (open === undefined) continue\n const failed = call.fact.outcome === \"failure\"\n open.cell.label = callCellLabel(open.started, failed)\n open.cell.tone = failed ? \"fail\" : \"ok\"\n const result = failed ? cellText(call.fact.message) : cellText(call.fact.value)\n if (result !== undefined) open.cell.output = result\n }\n return transcripts\n}\n\n/** The dispatches a settled engine node drove, as `<execution id>:<step key digest>`. */\nconst nodeDispatches = (row: TraceSpan): ReadonlyArray<string> => {\n if (!row.id.startsWith(\"engine-node:\")) return []\n const fields = asRecord(row.detail.fields)\n const execution = asString(fields.executionId)\n const digests = asRecord(fields.payload).stepKeyDigests\n if (execution === undefined || !Array.isArray(digests)) return []\n return [\n ...new Set(digests.filter((digest): digest is string => typeof digest === \"string\" && hexDigest.test(digest)))\n ]\n .map((digest) => `${execution}:${digest}`)\n}\n\n/** Plan node kinds that only shape the plan (@smthrs/plan); a child flow's own nodes are its steps. */\nconst PLAN_STRUCTURE: ReadonlySet<string> = new Set([\n \"Succeed\",\n \"Fail\",\n \"All\",\n \"Race\",\n \"Map\",\n \"AndThen\",\n \"Branch\",\n \"Catch\",\n \"FlowCall\",\n \"FunctionIdentity\",\n \"PlannedReference\"\n])\n\n/** A check receipt's leading scalar fields, read from a preview the engine\n * may have cut short (its evidence comes last): `{\"checkId\":\u2026,\"status\":\u2026`. */\nconst RECEIPT_HEAD = /^\\{\"checkId\":\"[^\"\\\\]*\"(?:,\"[A-Za-z]+\":(?:\"[^\"\\\\]*\"|-?\\d+))*,\"status\":\"(passed|failed|superseded)\"/\n\n/** How many checks a step's recorded output reports failed: a check receipt\n * (`{checkId, status, \u2026}`, possibly a cut-short preview) or a list of them;\n * zero for any other output. */\nconst checkFailures = (output: string | undefined): number => {\n if (output === undefined) return 0\n const head = RECEIPT_HEAD.exec(output)\n if (head !== null) return head[1] === \"failed\" ? 1 : 0\n let value: unknown\n try {\n value = JSON.parse(output)\n } catch {\n return 0\n }\n return (Array.isArray(value) ? value : []).filter((receipt) => {\n const record = asRecord(receipt)\n return typeof record.checkId === \"string\" && record.status === \"failed\"\n }).length\n}\n\n/** Each recorded engine node's kind and action, by its trace span id (without instance). */\nconst engineNodeShapes = (journal: ReadonlyArray<JournalRecord>) => {\n const shapes = new Map<string, { kind?: string | undefined; action?: string | undefined }>()\n for (const record of journal) {\n if (record.kind !== \"control.engine.event\") continue\n const envelope = asRecord(record.payload)\n const executionId = asString(envelope.executionId)\n const generation = asNumber(envelope.generation)\n const payload = asRecord(envelope.payload)\n if (executionId === undefined || generation === undefined) continue\n const prefix = `engine-node:${encodeURIComponent(`${encodeURIComponent(executionId)}:${generation}`)}:`\n if (\n envelope.eventType === \"flows.engine.plan-recorded\" || envelope.eventType === \"flows.engine.subgraph-appended\"\n ) {\n const nodes = asRecord(payload.graph).nodes\n for (const node of Array.isArray(nodes) ? nodes : []) {\n const shape = asRecord(node)\n const id = asString(shape.id)\n if (id !== undefined) {\n shapes.set(prefix + encodeURIComponent(id), { kind: asString(shape.kind), action: asString(shape.action) })\n }\n }\n } else if (envelope.eventType === \"flows.engine.node-scheduled\") {\n const id = asString(payload.nodeId)\n if (id === undefined) continue\n const known = shapes.get(prefix + encodeURIComponent(id))\n shapes.set(prefix + encodeURIComponent(id), {\n kind: asString(payload.kind) ?? known?.kind,\n action: asString(payload.action) ?? known?.action\n })\n }\n }\n return shapes\n}\n\n/** Adapt the canonical trace to the install monitor. IDs and timestamps come\n * from recorded spans; inspection never evaluates flow bodies or presentations.\n * @since 1.0.0\n * @category constructors\n */\nexport const monitorFromJournal = (run: TraceRun, records: ReadonlyArray<JournalRecord>, at?: number) => {\n const last = records.reduce((last, row) => Math.max(last, row.sequence ?? 0), 0)\n const journal = at === undefined ? records : records.filter((row) => (row.sequence ?? 0) <= at)\n // A historical frame must not inherit the current run's terminal status.\n const lifecycleRow = [...journal].reverse().find((row) =>\n /^control\\.run\\.(running|waiting-approval|paused|suspended|held|completed|failed|cancelled|interrupted)$/.test(\n row.kind ?? \"\"\n ) &&\n (row.runId === undefined || row.runId === run.runId)\n )\n const status = at === undefined ? run.status : lifecycleRow?.kind?.split(\".\").at(-1) ?? \"running\"\n const state = (value: string): \"running\" | \"waiting\" | \"held\" | \"failed\" | \"done\" | \"interrupted\" =>\n value === \"completed\" || value === \"done\" ? \"done\" : value === \"failed\" ?\n \"failed\"\n : value === \"cancelled\" || value === \"interrupted\" ?\n \"interrupted\" :\n value === \"held\" ?\n \"held\"\n : value === \"waiting\" || value === \"waiting-approval\" || value === \"paused\" || value === \"suspended\"\n ? \"waiting\"\n : \"running\"\n const trace = traceFromJournal({ ...run, status }, journal)\n const engineLabel = (label: string) =>\n ACTION_RENDERINGS[label] === null || /^<(?:boundary:|quota-park>|structured-output-count>)/.test(label)\n const bookkeeping = (row: TraceSpan) => engineLabel(row.label)\n const transcripts = stepTranscripts(journal)\n // Every call below is a member of trace.rows, so both lookups are total.\n const dispatchesOf = new Map(trace.rows.map((row) => [row.id, nodeDispatches(row)] as const))\n // A step is a node that dispatched an action. Plan structure (sequences,\n // branches, maps) and child-flow calls, whose own nodes are the steps, are\n // never steps of their own.\n const structural = (kind: string | undefined) => kind !== undefined && PLAN_STRUCTURE.has(kind)\n const nodeShapes = engineNodeShapes(journal)\n const calls = trace.rows.filter((row) => {\n // A tool call an agent made inside a step is a cell of that step's\n // transcript (step:<scope>/\u2026), never a step of its own.\n if (row.kind !== \"call\" || bookkeeping(row) || row.id.startsWith(\"step:\")) return false\n const shape = nodeShapes.get(row.id.replace(/#\\d+$/, \"\"))\n return shape === undefined || !structural(shape.kind)\n })\n const transcriptOf = (row: TraceSpan) => {\n const parts = dispatchesOf.get(row.id)!.flatMap((dispatch) => {\n const found = transcripts.get(dispatch.slice(dispatch.lastIndexOf(\":\") + 1))\n return found === undefined ? [] : [found]\n })\n return {\n cells: parts.flatMap((part) => part.cells).sort((left, right) =>\n Number(left.id.slice(5)) - Number(right.id.slice(5))\n ),\n tokens: parts.reduce((total, part) => total + part.tokens, 0),\n models: parts.reduce((total, part) => total + part.models, 0),\n input: parts.find((part) => part.input !== undefined)?.input\n }\n }\n const steps = calls.map((row) => {\n const meter = dispatchesOf.get(row.id)!\n const transcript = transcriptOf(row)\n return {\n ...(() => {\n const matched = /^(engine-node:.*)#(\\d+)$/.exec(row.id)\n const id = matched?.[1] ?? row.id\n const k = Number(matched?.[2] ?? 1)\n return { key: `${id}#${k}`, id, k }\n })(),\n label: row.label,\n state: row.status,\n started_at: new Date(row.startedAt).toISOString(),\n ...(row.endedAt === undefined\n ? {}\n : { ended_at: new Date(row.endedAt).toISOString(), took_s: Math.max(0, row.endedAt - row.startedAt) / 1000 }),\n ...(row.detail.input !== undefined\n ? { input: row.detail.input }\n : transcript.input !== undefined\n ? { input: transcript.input }\n : {}),\n ...(row.detail.output === undefined ? {} : { output: row.detail.output }),\n // The install prices these dispatches from its metered proxy rows and\n // replaces them with `usage`; the journal's own token count rides along.\n ...(meter.length === 0 ? {} : { meter }),\n ...(transcript.models === 0 ? {} : { model_calls: transcript.models, tokens: transcript.tokens })\n }\n })\n const tone = (value: string): \"live\" | \"ok\" | \"fail\" | \"wait\" =>\n value === \"failed\" ?\n \"fail\"\n : value === \"completed\"\n ? \"ok\"\n : value === \"waiting\"\n ? \"wait\"\n : \"live\"\n const phases = calls.map((row, index) => {\n const transcript = transcriptOf(row).cells\n const failedChecks = checkFailures(row.detail.output)\n const cells: Array<Omit<TranscriptCell, \"tone\"> & { tone?: ReturnType<typeof tone> }> = transcript.length > 0\n ? transcript\n : [{\n id: `cell:${row.id}`,\n kind: /Edited/.test(row.label) ? \"edit\" : /Read/.test(row.label) ? \"read\" : \"run\",\n label: row.label,\n ...(row.detail.output === undefined ? {} : { output: row.detail.output }),\n tone: tone(row.status)\n }]\n return {\n id: `phase:${row.id}`,\n step: steps[index]!.key,\n // The title is the Appendix C label plus the outcome its recorded\n // output reports: \"Ran checks \u00B7 1 failed\".\n title: failedChecks === 0 ? row.label : `${row.label} \u00B7 ${failedChecks} failed`,\n took_s: Math.max(0, (row.endedAt ?? row.startedAt) - row.startedAt) / 1000,\n tone: failedChecks === 0 ? tone(row.status) : \"fail\" as const,\n cells\n }\n })\n const declaredGraph = engineExecutionEvidence(journal).filter((execution) => execution.coherent).flatMap(\n (execution) => {\n const prefix = `engine-node:${\n encodeURIComponent(`${encodeURIComponent(execution.executionId)}:${execution.generation}`)\n }:`\n const nodes = execution.graph?.nodes ?? []\n const hidden = new Map(\n nodes.filter((node) => engineLabel(node.action ?? node.id) || structural(node.kind))\n .map((node) => [node.id, node])\n )\n // Engine bookkeeping stays in the Engine row. Its dependency edges still\n // order the visible steps, including across several hidden boundaries.\n const visibleDeps = (id: string, seen: ReadonlySet<string>): Array<string> => {\n const node = hidden.get(id)\n if (node === undefined) return [prefix + encodeURIComponent(id)]\n if (seen.has(id)) return []\n return node.dependsOn.flatMap((dependency) => visibleDeps(dependency, new Set([...seen, id])))\n }\n return nodes.filter((node) => !hidden.has(node.id)).map((node) => {\n const id = prefix + encodeURIComponent(node.id)\n const instances = calls.filter((row) => row.id.startsWith(`${id}#`))\n const current = instances.at(-1)\n return {\n id,\n label: inspectLabel(node.action ?? node.id),\n // A branch not taken never ran: it stays next, even in a finished run.\n state: current === undefined || current.status === \"skipped\" ?\n \"next\" as const :\n current.status === \"completed\" ?\n \"done\" as const\n : current.status === \"failed\"\n ? \"failed\" as const\n : current.status === \"waiting\"\n ? \"waiting\" as const\n : \"current\" as const,\n deps: [...new Set(node.dependsOn.flatMap((dependency) => visibleDeps(dependency, new Set([node.id]))))]\n }\n })\n }\n )\n const usageOf = (row: TraceSpan) => (row.detail.usage?.inputTokens ?? 0) + (row.detail.usage?.outputTokens ?? 0)\n const tokens = trace.rows.reduce((total, row) => total + usageOf(row), 0)\n // Model calls no native dispatch recorded (a legacy agent journal) can\n // never be joined to metered rows; the install refuses to price them.\n const unmetered = trace.rows.filter((row) => row.kind === \"model\" && asRecord(row.detail.fields).step === undefined)\n .reduce((total, row) => total + usageOf(row), 0)\n const approvalWaits = trace.rows.filter((row) => row.kind === \"approval\").map((row) => ({\n id: row.id,\n kind: \"approval\" as const,\n label: row.label,\n since: new Date(row.startedAt).toISOString(),\n ...(row.endedAt === undefined\n ? {}\n : {\n settled: { by: { kind: \"system\" as const, color_index: 7 as const }, at: new Date(row.endedAt).toISOString() }\n })\n }))\n // The machine records its declared custom view as data. Only the shipped\n // text renderer is supported; module paths, HTML and executable data never\n // cross this seam. Replay selects the last declaration in its own prefix.\n const custom = [...journal].reverse().find((row) =>\n (row.runId === undefined || row.runId === run.runId) &&\n row.kind === \"control.engine.event\" && asRecord(row.payload).eventType === \"flows.run.presentation\"\n )\n const presentation = asRecord(asRecord(custom?.payload).payload)\n const text = asString(presentation.text)\n const customView = presentation.kind === \"text\" && text !== undefined && text.length <= 65536 &&\n Object.keys(presentation).every((key) => key === \"kind\" || key === \"text\")\n ? { presentation: { kind: \"text\" as const, text } } :\n {}\n return {\n ...customView,\n id: run.runId,\n flow: run.flowId,\n version: \"\",\n title: run.flowId,\n state: state(status),\n attempts: [{\n n: 1,\n run_id: run.runId,\n state: state(status),\n steps,\n phases,\n graph: declaredGraph.length > 0 ?\n declaredGraph :\n calls.map((row) => ({\n id: row.id,\n label: row.label,\n state: row.status === \"skipped\" ? \"next\" as const : row.status === \"completed\" ?\n \"done\" as const\n : row.status === \"failed\"\n ? \"failed\" as const\n : row.status === \"waiting\"\n ? \"waiting\" as const\n : \"current\" as const,\n deps: [] as Array<string>\n }))\n }],\n waits: [\n ...approvalWaits,\n ...engineExecutionEvidence(journal).filter((execution) => execution.coherent).flatMap((execution) =>\n execution.waits.map((wait) => ({\n id: wait.id,\n kind: wait.kind,\n label: inspectLabel(\"wait\"),\n since: new Date(wait.since).toISOString(),\n ...(wait.settledAt === undefined\n ? {}\n : {\n settled: {\n by: { kind: \"system\" as const, color_index: 7 as const },\n at: new Date(wait.settledAt).toISOString()\n }\n })\n }))\n )\n ],\n tokens,\n // Spend is priced where model calls are metered. The host never publishes\n // an unknown total as zero: a run with model tokens leaves cost to the install.\n time_s: Math.max(0, trace.extent.end - trace.extent.start) / 1000,\n ...(tokens === 0 ? { cost_usd: 0 } : {}),\n ...(unmetered === 0 ? {} : { unmetered_tokens: unmetered }),\n engine: trace.rows.filter((row) =>\n row.kind === \"event\" || row.kind === \"execution\" || row.kind === \"attempt\" || bookkeeping(row)\n ).map((row) => ({ label: row.label, detail: row.detail.output ?? row.detail.message ?? \"\" })),\n journal: journal.map((row) => ({\n seq: row.sequence ?? 0,\n at: new Date(row.occurredAt ?? 0).toISOString(),\n type: row.kind ?? \"event\",\n text: JSON.stringify(row.payload) ?? \"null\"\n })),\n ...(at === undefined ? {} : { replay: { at: Math.min(at, last), last } })\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,qBAAyB;AACzB,wBAAoE;AACpE,oBAAuB;AACvB,uBAAyC;AACzC,yBAAgE;AAChE,8BAAkC;AAClC,wBAAyF;AACzF,2BAA6B;AAE7B,IAAAA,wBAA6B;AA6Q7B,MAAM,eAAoC,oBAAI,IAAI,CAAC,aAAa,UAAU,aAAa,aAAa,CAAC;AAErG,MAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAmC,CAAC;AAC7G,MAAM,WAAW,CAAC,UAAuC,OAAO,UAAU,WAAW,QAAQ;AAC7F,MAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AAGhE,MAAM,SAAS,CAAC,QAAuB,YACrC,SAAS,QAAQ,EAAE,KAAK,SAAS,OAAO,UAAU,KAAK;AAGzD,MAAM,SAAS,CAAC,UAAuC;AACrD,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI;AACF,WA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