import { RunAbortReason, Rationale, ContentPartSummary, LlmCallPurpose, StructuredAttemptReport, StructuredOutputReport, AgentEvent } from '@reactive-agents/core'; /** Discriminated union of every observable reactive event. */ type TraceEvent = RunStartedEvent | RunCompletedEvent | RunAbortedEvent | PhaseBoundaryEvent | IterationBoundaryEvent | EntropyScoredEvent | DecisionEvaluatedEvent | InterventionDispatchedEvent | InterventionSuppressedEvent | StatePatchAppliedEvent | ToolCallEvent | MessageAppendedEvent | StrategySwitchedEvent | KernelStateSnapshotEvent | VerifierVerdictEvent | GuardFiredEvent | LLMExchangeEvent | ContentPartDegradedEvent | HarnessSignalInjectedEvent | SignalRenderedEvent | SignalEffectEvent | AssumptionRecordedEvent | CuratorDecisionEvent | ToolSurfaceResolvedEvent | ContractCompiledEvent | AssessmentEvent | ProjectionRenderedEvent | ControlResolutionEvent | LedgerEntryTraceEvent | ChecklistInferredTraceEvent | EnvironmentUpdatedTraceEvent | EvalGradedEvent | StructuredOutputReportedTraceEvent | RunCostFinalizedEvent; interface TraceEventBase { readonly runId: string; readonly timestamp: number; readonly iter: number; readonly seq: number; /** Top-most run in this delegation tree. Absent ⇒ treat as `runId` (root). */ readonly rootRunId?: string; /** The run that spawned this one. Absent at the root. */ readonly parentRunId?: string; /** Delegation depth. Absent ⇒ 0 (root). */ readonly depth?: number; } interface RunStartedEvent extends TraceEventBase { readonly kind: "run-started"; readonly task: string; readonly model: string; readonly provider: string; readonly seed?: number; /** True iff `task` was clipped to the 64KB publisher cap (GH #237). */ readonly taskTruncated?: boolean; /** * Resolved harness configuration, shaped `{ mechanisms, builder, env }` * (secret-free, size-bounded). `{}` on traces recorded before it existed. */ readonly config: Record; /** * Who started the run: `"user" | "gateway" | "cortex-chat" | "cortex-utility" * | "subagent" | "scheduled" | "eval"`. Additive optional * (REQUIRED_FIELDS_BY_KIND unchanged): absent on traces recorded before it * existed; readers treat absent as `"user"`. */ readonly origin?: string; } /** * Terminal sentinel for a run that ended abnormally (failure, defect or * interrupt) without a `run-completed`. A trace with neither is a lost run. */ interface RunAbortedEvent extends TraceEventBase { readonly kind: "run-aborted"; /** `"failure"` (typed error) | `"defect"` (crash) | `"interrupt"` (fiber interrupted). */ readonly causeClass: "failure" | "defect" | "interrupt"; /** Why the runtime knows the run ended: timeout | user-stop | terminate | abort. Additive optional. */ readonly reason?: RunAbortReason; /** Short error description (tag/message), never a stack or payload. */ readonly error?: string; readonly durationMs: number; } interface RunCompletedEvent extends TraceEventBase { readonly kind: "run-completed"; readonly status: "success" | "failure" | "cancelled"; /** Final deliverable output (capped at 64KB by the publisher; see `outputTruncated`). */ readonly output?: string; /** True iff `output` was clipped to the publisher's 64KB cap. */ readonly outputTruncated?: boolean; readonly error?: string; /** Raw termination reason (AgentCompleted.terminationReason) — e.g. "abstained", "max-iterations:5". */ readonly terminatedBy?: string; readonly totalTokens: number; /** * Spend known when the result was built (`AgentCompleted.totalCostUsd`). It * excludes the background debrief call: the billed run total is on the * run's `run-cost-finalized` event when one was recorded. A lower bound when * `costComplete` is `false`; `0` with `costComplete: false` means the * publisher reported no cost at all (unknown, not free). */ readonly totalCostUsd: number; /** * `false` when `totalCostUsd` understates the spend (an LLM call had an * unknown price, or no cost was reported). Additive optional * (REQUIRED_FIELDS_BY_KIND unchanged): absent on traces recorded before it * existed, where completeness is not known. */ readonly costComplete?: boolean; readonly durationMs: number; /** Per-signal consumption tally (see `RunSignalTally`). Absent on runs without a signal ledger. */ readonly signals?: RunSignalTally; /** * The ONE reconciled terminal outcome (Plan 8 K1): status, terminatedBy, * deliverable provenance, gate verdict, answer-satisfied and the * kernel-supported success claim, derived once so they cannot disagree. * Additive optional (REQUIRED_FIELDS_BY_KIND unchanged): absent on traces * recorded before it existed and on publishers that do not forward it. */ readonly outcome?: RunOutcome; } /** * The run's final billed cost (core `RunCostFinalized`), recorded once per run. * It can arrive AFTER `run-completed` (the background debrief call settles * first), so the recorder appends it to the run's trace late. Readers take the * run total from here when present, not from `run-completed.totalCostUsd` * (which excludes the debrief call). Conventionally `iter: -1`. */ interface RunCostFinalizedEvent extends TraceEventBase { readonly kind: "run-cost-finalized"; /** Total billed USD, debrief included. A lower bound when `costComplete` is `false`. */ readonly totalCostUsd: number; /** `true` when every LLM call in the run had a known price. */ readonly costComplete: boolean; } /** Shape of the kernel's `TerminalOutcome` (structural twin; trace stays dependency-free of reasoning). */ interface RunOutcome { readonly status: "completed" | "partial" | "abstained" | "failed"; readonly terminatedBy: string | null; readonly provenance: "model-final" | "synthesized" | "tool-artifact" | "sentinel" | "none"; readonly verdict: { readonly accepted: boolean; readonly summary: string; } | null; readonly answerSatisfied: boolean | null; readonly success: boolean; /** The ONE authority owning the final status (kernel's, or `runtime-verifier-gate` / `runtime-success-veto:`). */ readonly authority?: string; /** The kernel's own authority, present only when a runtime authority replaced it. */ readonly kernelAuthority?: string; /** * The terminal gate's DECISION on the deliverable, separate from the verifier * verdict: `accepted:true` beside a failing verifier reads as "overridden by * the deliverable decision: ". Additive optional. */ readonly deliverable?: { readonly outcome: "pass" | "block"; readonly reason: string; readonly accepted: boolean; } | null; /** The verifier's own verdict (`verified` + failed check names). Additive optional. */ readonly verifierVerdict?: { readonly verified: boolean; readonly failedChecks: readonly string[]; } | null; /** Requirement/check ids that kept the status from `completed`. Additive optional. */ readonly outstanding?: readonly string[]; /** Class of the provider error that ended the run (authority `error`). Additive optional. */ readonly errorClass?: string; /** Deterministic reason the runtime shipped its final status. Additive optional. */ readonly statusReason?: string; /** True exactly when the runtime tolerance lane shipped success over a kernel `partial` (explained exception, not a contradiction). Additive optional. */ readonly tolerated?: boolean; /** Which tolerance lane fired (e.g. `partial-substantive-output`); present iff `tolerated`. Additive optional. */ readonly toleratedBy?: string; } interface PhaseBoundaryEvent extends TraceEventBase { readonly kind: "phase-enter" | "phase-exit"; readonly phase: string; readonly durationMs?: number; } /** * `iteration-exit` is the trace record of core `ReasoningIterationProgress`: * one loop finished (a kernel iteration, or a plan-execute step). `iter` is the * event's 1-based `iteration`. It is the canonical loop count * (`traceStats.iterations`), the same events Cortex's replay counts. The * optional fields are absent on `iteration-enter` and on hand-built events. */ interface IterationBoundaryEvent extends TraceEventBase { readonly kind: "iteration-enter" | "iteration-exit"; /** Strategy that ran the loop (e.g. `reactive`, `plan-execute-reflect`). */ readonly strategy?: string; /** The loop limit the emitter reported. */ readonly maxIterations?: number; /** Tools called in this loop (duplicates kept). */ readonly toolsThisStep?: readonly string[]; } /** * One structured-output extraction finished (core `StructuredOutputReported`): * how the value was obtained (native, prompt, repaired, coerced, retried) or * why extraction failed. The event carries no iteration, so `iter` is -1. */ interface StructuredOutputReportedTraceEvent extends TraceEventBase { readonly kind: "structured-output-reported"; /** Strategy that requested the extraction; absent when the caller is not a strategy. */ readonly strategy?: string; /** The extraction's provenance report, as core emitted it. */ readonly report: StructuredOutputReport; } interface EntropyScoredEvent extends TraceEventBase { readonly kind: "entropy-scored"; readonly composite: number; readonly sources: { /** null = source structurally unavailable (e.g. no logprobs on Ollama), not a measured zero. */ readonly token: number | null; readonly structural: number; /** null = no embedding available or no prior thought to compare against. */ readonly semantic: number | null; readonly behavioral: number; readonly contextPressure: number; }; /** * Count of non-null sources, 2-4 (excludes contextPressure, which is * structurally never null — matches the sensor's own confidence-driving * count in composite.ts). Below 4 means the composite is a partial signal. */ readonly sourcesPresent: number; /** Sensor's own self-assessment. "low" on short runs and degraded-source runs. */ readonly confidence: "high" | "medium" | "low"; /** EntropyTrajectory.shape, or "unknown" when no trajectory was supplied. */ readonly trajectoryShape: string; readonly modelTier: "frontier" | "local" | "unknown"; } interface DecisionEvaluatedEvent extends TraceEventBase { readonly kind: "decision-evaluated"; readonly decisionType: string; readonly confidence: number; readonly reason: string; /** Optional structured rationale (v0.11.x); free-text `reason` remains source of truth. */ readonly rationale?: Rationale; } interface InterventionDispatchedEvent extends TraceEventBase { readonly kind: "intervention-dispatched"; readonly decisionType: string; readonly patchKind: string; readonly cost: { readonly tokensEstimated: number; readonly latencyMsEstimated: number; }; readonly telemetry: Record; } interface InterventionSuppressedEvent extends TraceEventBase { readonly kind: "intervention-suppressed"; readonly decisionType: string; readonly reason: "below-entropy-threshold" | "below-iteration-threshold" | "over-budget" | "max-fires-exceeded" | "mode-advisory" | "mode-off" | "no-handler"; } interface StatePatchAppliedEvent extends TraceEventBase { readonly kind: "state-patch-applied"; readonly patchKind: string; readonly diff: Record; } interface ToolCallEvent extends TraceEventBase { readonly kind: "tool-call-start" | "tool-call-end"; readonly toolName: string; readonly args?: unknown; /** Tool result payload (only on "tool-call-end"; may be truncated for size). */ readonly result?: unknown; /** True iff `result` was clipped or replaced with an unserializable marker. */ readonly resultTruncated?: boolean; readonly durationMs?: number; readonly ok?: boolean; readonly error?: string; /** Optional rationale (v0.11.x). Only set on "tool-call-start". */ readonly rationale?: Rationale; } interface MessageAppendedEvent extends TraceEventBase { readonly kind: "message-appended"; readonly role: "user" | "assistant" | "tool" | "system"; readonly tokenCount: number; } interface StrategySwitchedEvent extends TraceEventBase { readonly kind: "strategy-switched"; readonly from: string; readonly to: string; readonly reason: string; /** Optional structured rationale (v0.11.x); free-text `reason` remains source of truth. */ readonly rationale?: Rationale; } /** * Snapshot of kernel state at an iteration boundary. Captures enough to * reconstruct what the agent saw without re-running. Sized to be replayable * but bounded — message and scratchpad payloads are previewed, not full. */ interface KernelStateSnapshotEvent extends TraceEventBase { readonly kind: "kernel-state-snapshot"; readonly status: "thinking" | "acting" | "observing" | "done" | "failed" | "evaluating" | "paused"; readonly toolsUsed: readonly string[]; readonly scratchpadKeys: readonly string[]; readonly stepsCount: number; readonly stepsByType: Readonly>; readonly outputPreview: string | null; readonly outputLen: number; readonly messagesCount: number; readonly tokens: number; readonly cost: number; readonly llmCalls: number; readonly terminatedBy: string | undefined; readonly pendingGuidance: Record | undefined; /** Set iff terminatedBy is set; structured rationale for the termination. */ readonly terminationRationale?: Rationale; } /** * Verifier verdict on a single action's outcome. Mirrors the * VerificationResult type from the reasoning package without coupling to it. * The `checks` array preserves order so consumers can find the first failed * check (the "lead" reason for rejection). */ interface VerifierVerdictEvent extends TraceEventBase { readonly kind: "verifier-verdict"; readonly action: string; readonly terminal: boolean; /** `kernel` (in-loop, default when absent) or `runtime` (result-boundary pass). */ readonly source?: "kernel" | "runtime"; readonly verified: boolean; readonly summary: string; readonly checks: readonly { readonly name: string; readonly passed: boolean; readonly reason?: string; }[]; } /** * A guard or phase decision in the reasoning loop. Captures which control-flow * branch fired and why, so trace consumers can answer "why did this run take * path A instead of path B" without reading kernel source. * * Examples: * - guard="guardPrematureFinalAnswer", outcome="redirect", reason="missing tools: get-hn-posts" * - guard="completion-guard", outcome="pass", reason="all required tools satisfied" * - guard="loop-detector", outcome="terminate", reason="3 consecutive identical thoughts" */ interface GuardFiredEvent extends TraceEventBase { readonly kind: "guard-fired"; readonly guard: string; readonly outcome: "pass" | "redirect" | "terminate" | "block" | "warn"; readonly reason: string; readonly metadata?: Record; } /** * One LLM round-trip: prompt sent and response received. Enables answering * "what did the model actually see" and "why did it produce that output" * without re-running. * * Payloads are token-budgeted to keep traces small: * - systemPrompt and messages may be truncated (with `truncated: true`) * - rawResponse is sampled (full text up to a soft cap; otherwise prefix) * * Tool schemas sent are recorded by name only; full schemas live in * KernelStateSnapshot when needed. */ interface LLMExchangeEvent extends TraceEventBase { readonly kind: "llm-exchange"; readonly provider: string; readonly model: string; readonly requestKind: "complete" | "stream" | "completeStructured"; readonly systemPrompt: string | undefined; readonly systemPromptTruncated?: boolean; readonly messages: readonly { readonly role: "system" | "user" | "assistant" | "tool"; readonly content: string; readonly truncated?: boolean; /** * Summaries of the message's non-text parts (`type`, `media_type`, * `bytes`, `sha256`), never raw bytes (Plan 9 Phase 4 stage F). Optional: * absent on text-only messages and on every trace recorded before it. */ readonly parts?: readonly ContentPartSummary[]; }[]; readonly toolSchemaNames: readonly string[]; /** * What this call was for. Absent on un-mediated calls (and on every trace * recorded before 2026-07-28) — treat absence as "unknown", never as a tier. * This is the field that turns "the harness costs 640%" into a per-subsystem * breakdown. */ readonly purpose?: LlmCallPurpose; readonly temperature?: number; readonly maxTokens?: number; readonly response: { readonly content: string; readonly truncated?: boolean; readonly toolCalls?: readonly { readonly name: string; readonly arguments?: unknown; }[]; readonly stopReason?: string; readonly tokensIn?: number; readonly tokensOut?: number; /** Anthropic prompt-caching: tokens that wrote new cache entries (Lever 1 evidence). */ readonly cacheCreationTokensIn?: number; /** Anthropic prompt-caching: tokens served from cache hits (90% input discount). */ readonly cacheReadTokensIn?: number; readonly costUsd?: number; readonly durationMs?: number; /** * Set only when the LLM call FAILED: the provider error's own class * (`_tag`/`kind`/`name`, else "unknown") and message. A failed exchange also * carries `stopReason:"error"`. Additive optional: absent on every success * and on traces recorded before it existed. */ readonly error?: { readonly class: string; readonly message: string; }; /** * W1.4 forensics (Local-Tier Reliability): FULL character length of the * provider's internal reasoning for this exchange — 0/absent when the * model emitted no thinking. Pair with `thinkingPreview` so `rax diagnose * replay` can show that a starved visible channel was outcompeted by * reasoning tokens (the S2 baseline: 4-char content vs 1.8-2.6K thinking * tokens per run). Additive optional — traces recorded before this field * load unchanged (REQUIRED_FIELDS_BY_KIND did not grow). */ readonly thinkingChars?: number; /** * Prefix of the thinking text, capped at the existing trace-budgeting * constant PREVIEW_MAX (see reasoning/src/kernel/utils/diagnostics.ts — * the same cap every other exchange preview uses). Never carries the full * reasoning: trace payload growth is bounded by construction. */ readonly thinkingPreview?: string; /** * `completeStructured` only: one entry per native provider attempt inside * the call (count, per-attempt input/output tokens, stop reason, thinking * size). One exchange can hold several attempts; this split is what tells a * thinking runaway from a parse retry. Additive optional: absent when the * provider reported no attempt detail and on traces recorded before it. */ readonly attempts?: readonly StructuredAttemptReport[]; }; } /** * A non-text part replaced by a text stub before it reached the model (Plan 9 * Phase 4 stage F). Emitted by the kernel's provider-boundary conversion * (`toLLMMessages`): audio and file parts, unsupported image types, media in * tool results. Carries the part summary, never raw bytes. */ interface ContentPartDegradedEvent extends TraceEventBase { readonly kind: "content-part-degraded"; readonly part: ContentPartSummary; readonly role: "user" | "assistant" | "tool"; readonly reason: string; } /** * A harness-injected step (recovery nudge, dispatcher message, guard redirect). * Distinguishes harness-authored content from model-produced content in the * trace. Origin captures the source site (e.g. "think-guards.ts:213") so * trace consumers can navigate from the event to the code that emitted it. */ interface HarnessSignalInjectedEvent extends TraceEventBase { readonly kind: "harness-signal-injected"; readonly signalKind: "redirect" | "nudge" | "block" | "completion-gap" | "rule-violation" | "dispatcher-status" | "loop-graceful" | "other"; readonly origin: string; readonly contentPreview: string; readonly contentLen: number; readonly metadata?: Record; /** * Ledger id for this signal (`sig--`, per-signal; Task 2's * signal-ledger owns the format). Join key against `signal-rendered` and * `signal-effect` events. Absent / `""` on pre-instrumentation events. */ readonly signalId?: string; /** Tool the signal steered toward or away from, when the signal named one. */ readonly targetTool?: string; /** Why the signal targeted that tool (the classifier family), when known. */ readonly targetPolicy?: SignalTargetPolicy; } /** * Why a harness signal targets a tool — the "family" the effect classifier * (`classifySignalEffect`) dispatches on. Open by widening: add members when * a new target family appears, never re-purpose an existing one. */ type SignalTargetPolicy = "denied-tool-retry" | "alternate-tool" | "synthesize" | "required-tool" | "other"; /** * The Projector actually rendered a signal into the model's window * (signal consumption edge, 2026-10-25; emitted alongside the * `harness-signal-injected` event that opened the signal and keyed by the * same `signalId`). Together with `SignalEffectEvent` this closes the * opened → rendered → effect chain per signal, so trace consumers can * distinguish "signal never reached the model" (blind spot) from "signal * reached the model and the model ignored it" (effect), which the * 2026-10-24 introspective probes could only approximate by message parsing. */ interface SignalRenderedEvent extends TraceEventBase { readonly kind: "signal-rendered"; /** Same ledger id as the originating `harness-signal-injected` event. */ readonly signalId: string; /** The kernel iteration whose window the signal was composed into. */ readonly renderedInIter: number; /** Prompt section the signal was rendered into. */ readonly renderedSection: SignalRenderSection; } /** * Prompt section a signal was rendered into. Single value today (the system * prompt's `Guidance:` section); the union stays open: add members when a * second render target appears, never re-purpose this one. */ type SignalRenderSection = "guidance"; /** * The model's OBSERVABLE behavior after a signal was rendered (signal * consumption edge, 2026-10-25). Emitted once per (signal, pass) when the * effect classifier (Task 4) closes the signal. * * IMPORTANT SEMANTICS (locked by the plan): `response` says whether the * model OBEYED the steer, NOT whether the steer's advice was GOOD. A wrong * steer that the model followed is still `remediated`; the steer's quality * is a separate I5 concern and lives elsewhere (the ledger entry content). */ interface SignalEffectEvent extends TraceEventBase { readonly kind: "signal-effect"; /** Same ledger id as the originating `harness-signal-injected` event. */ readonly signalId: string; /** * What the model observably did after render: * - `remediated` : the model acted per the signal's target * - `ignored` : the model acted, but on something else * - `contradicted` : the model repeated the exact behavior the steer * redirected it away from * - `ambiguous` : no act this pass, or evidence inconclusive */ readonly response: "remediated" | "ignored" | "contradicted" | "ambiguous"; /** Tool the post-render act actually called, when an act happened. */ readonly observedTool?: string; /** Convenience echo of the subject the effect classifies against (e.g. target tool name). */ readonly observedSubject?: string; /** Why this label was chosen (e.g. "args textually differ from denied payload"). */ readonly detail?: string; } /** * Per-run consumption tally of the signal chain (signal consumption edge, * 2026-10-25; Task 6 builds it from the kernel signal ledger at run end). * Counts are number of SIGNALS in each state/effect class; `rendered` * counts signals ever stamped, `unobserved` counts signals still open at * terminal with no effect classified. `opened >= rendered + unobserved` and * `rendered >= remediated + ignored + contradicted + ambiguous`. */ interface RunSignalTally { readonly opened: number; readonly rendered: number; readonly remediated: number; readonly ignored: number; readonly contradicted: number; readonly ambiguous: number; readonly unobserved: number; } /** * Assumption the model made during reasoning (e.g. "user means USD because no * currency given"). Emitted by the think-phase assumption detector. Surfaced * by `rax diagnose debrief` so reviewers see what the model filled in. */ interface AssumptionRecordedEvent extends TraceEventBase { readonly kind: "assumption-recorded"; readonly assumption: string; readonly rationale: Rationale; } /** * Context curator action — what was kept, dropped, compressed, or flagged as * untrusted, and why. Pairs the curator's existing trustLevel/justification * with a structured rationale. */ interface CuratorDecisionEvent extends TraceEventBase { readonly kind: "curator-decision"; readonly action: "kept" | "dropped" | "compressed" | "marked-untrusted"; readonly targetRef: string; readonly rationale: Rationale; } /** * Per-iteration tool-surface resolution (Overhaul Phase 2, 2026-07-07): what * the model could see (`visible`) and call (`callable`) this turn, plus WHY * each tool in the augmented set landed where it did. Replaces the debug-tap * workflow the rw-9 visibility regression required. */ interface ToolSurfaceResolvedEvent extends TraceEventBase { readonly kind: "tool-surface-resolved"; readonly visible: readonly string[]; readonly callable: readonly string[]; readonly reasons: readonly { readonly tool: string; readonly reason: string; }[]; } /** * RunContract compiled at run start (meta-loop Phase 4a, 2026-07-08): the typed * "what does DONE mean" object — its requirement + deliverable refs and the run * horizon. The goal-compiler node of the meta-loop DAG, made replayable the way * `tool-surface-resolved` made tool resolution replayable. */ interface ContractCompiledEvent extends TraceEventBase { readonly kind: "contract-compiled"; readonly requirements: readonly ContractRef[]; readonly deliverables: readonly ContractRef[]; readonly horizon: string; /** Which task slice the contract compiled from; `historyStripped` ⇒ chat history excluded. */ readonly currentTurn?: { readonly offset: number; readonly historyStripped: boolean; }; } /** A requirement/deliverable ref on `contract-compiled`, with typed provenance. */ interface ContractRef { readonly id: string; readonly kind: string; readonly provenance?: { readonly source: "task-text" | "required-tools" | "task-contract" | "floor"; /** Half-open `[start, end)` offset into the ORIGINAL task string (task-text only). */ readonly span?: { readonly start: number; readonly end: number; }; }; } /** * RunAssessment recomputed at an iteration (meta-loop Phase 5a, 2026-07-08): the * perception node of the meta-loop DAG. Carries the run phase, pace band, the one * evidenceDelta progress currency, and the requirement/deliverable tallies — * making the contract → assessment → action chain replayable, the way * `contract-compiled` made the goal compiler replayable. */ interface AssessmentEvent extends TraceEventBase { readonly kind: "assessment"; readonly phase: string; readonly band: string; readonly evidenceDelta: number; readonly requirementsSatisfied: number; readonly requirementsOutstanding: number; readonly deliverablesProduced: number; readonly deliverablesMissing: number; readonly burnRatio: number; } /** * The Projector rendered the LLM window (meta-loop Phase 4c, 2026-07-08): the * LAST node of the meta-loop DAG. Carries the rendered section names, the refs * reachable from the window, the refs compaction dropped, and the total rendered * size — making the contract → assessment → projection chain replayable, the way * `assessment` made perception replayable. */ interface ProjectionRenderedEvent extends TraceEventBase { readonly kind: "projection-rendered"; readonly sections: readonly string[]; readonly refs: readonly string[]; readonly droppedRefs: readonly string[]; readonly chars: number; /** R4 (2026-07-30): the resolved capability window the per-result budgets came * from (the budget/wire divergence signal), and each result the projector * replaced with a preview+ref. Optional — absent on pre-R4 replays. */ readonly window?: number; readonly tier?: string; readonly compressions?: readonly { readonly tool: string; readonly rawChars: number; readonly shownChars: number; readonly budget: number; }[]; } /** * Control plane resolved competing proposals into ONE action (meta-loop Phase 5b, * 2026-07-08, task F1): the action-selection node of the meta-loop DAG. Carries * the proposals considered (source→action), the ONE action chosen, and why — * making the contract → assessment → CONTROL → action chain replayable, the way * `assessment` made perception replayable. */ interface ControlResolutionEvent extends TraceEventBase { readonly kind: "control-resolution"; readonly action: string; readonly reason: string; readonly proposals: readonly { readonly source: string; readonly action: string; }[]; } /** * A batch of run-ledger entries appended at a kernel iteration boundary * (Wave C.1 live tap → C.2 run-scoped ledger). Projects the `LedgerEntryAppended` * bus event onto the trace stream so the ledger — the run's append-only record of * tool invocations, results, artifacts, requirements, claims and verdicts — is no * longer siloed from the trace JSONL. * * Each element of `entries` carries its OWN ledger `seq` (dense/monotonic within * the run ledger) and `kind` (`tool-invocation` | `tool-result` | `artifact` | * `requirement` | `claim` | `verdict` | …), distinct from this trace event's own * `seq`/`iter`. A merged sub-agent entry additionally carries `pass: * "sub-agent:"` (Wave C.2). The batch is stamped `Record` * at the core package boundary (core cannot depend on reasoning's LedgerEntry * union) and reaches the trace layer unchanged. */ interface LedgerEntryTraceEvent extends TraceEventBase { readonly kind: "ledger-entry"; readonly entries: ReadonlyArray>; } /** * An advisory checklist item was inferred done from deterministic ledger * evidence (core `ChecklistInferred`). Display-side only: never model-visible. * `evidence.seq` is the LEDGER seq of the matched entry (join key against * `ledger-entry.entries[].seq`), distinct from this event's own trace `seq`. */ interface ChecklistInferredTraceEvent extends TraceEventBase { readonly kind: "checklist-inferred"; readonly itemId: string; /** Checklist group key (`"root"` or a sub-agent path). */ readonly groupKey: string; readonly evidence: { readonly seq: number; readonly kind: "tool-result" | "artifact" | "requirement"; readonly detail: string; }; } /** * The chat environment changed between two turns (core `EnvironmentChanged`). * Conversation-scoped, not run-scoped: `runId` carries the chat `sessionId` * and `iter` is -1. Emitted only on a turn whose diff is non-empty. */ interface EnvironmentUpdatedTraceEvent extends TraceEventBase { readonly kind: "environment-updated"; readonly changes: ReadonlyArray<{ readonly kind: string; readonly summary: string; }>; } /** One named check of a deterministic grader (e.g. a hidden-check assertion). */ interface EvalGradedCheck { readonly name: string; readonly passed: boolean; readonly detail?: string; } /** * A deterministic grader's verdict on this run's answer, appended to the trace * AFTER the run completed (by the bench runner, or by a re-grade over a stored * trace). It is the only trace signal that says whether the answer was RIGHT: * every other event says how the run ended. `analyzeCause` reads it only to * label a clean-ending run whose answer failed the grader (`wrong-answer`); * a passing grade never changes a label. * * Emitted only for deterministic graders (regex / expected / verifiable / * abstention). LLM-judge scores and inconclusive accuracy never produce one. * Conventionally `iter: -1` and `seq` one past the trace's last event. */ interface EvalGradedEvent extends TraceEventBase { readonly kind: "eval-graded"; /** Accuracy in [0, 1]. */ readonly score: number; /** `score >= threshold` (the bench's solve bar). */ readonly passed: boolean; /** Solve bar the grade was compared against (1 for deterministic graders). */ readonly threshold?: number; /** Per-check results; empty when the grader exposes no named checks. */ readonly checks: ReadonlyArray; /** Which grader produced the score (e.g. `regex`, `verifiable:bun hidden-check.ts`). */ readonly grader: string; /** Bench task id that was graded. */ readonly taskId: string; /** Fingerprint of the frozen task suite the grader belongs to, when known. */ readonly suiteHash?: string; /** `bench` = graded live by the runner; `trace-regrade` = re-graded from a stored trace. */ readonly source?: "bench" | "trace-regrade"; } declare function toTraceEvent(raw: AgentEvent, seq: number): TraceEvent | null; export { toTraceEvent };