import { Rationale, ContentPartSummary, LlmCallPurpose, StructuredAttemptReport, RunAbortReason, StructuredOutputReport, RunContext, EventBus, AgentEvent } from '@reactive-agents/core'; export { Rationale } from '@reactive-agents/core'; import { Context, Effect, Layer } from 'effect'; import * as effect_Cause from 'effect/Cause'; import * as effect_Types from 'effect/Types'; /** * Decision rationale — structured "why" capture for any agent decision. * * The type lives in `@reactive-agents/core/src/types/rationale.ts` so trace, * tools, reasoning, and runtime can share the shape without cross-package * coupling. This module owns the validators. * * Attached as an optional field to: * - ToolCallEvent (on tool-call-start) * - AssumptionRecordedEvent * - CuratorDecisionEvent * - KernelStateSnapshotEvent (when terminatedBy set) * - StrategySwitchedEvent / DecisionEvaluatedEvent (alongside free-text reason) * * v1 keeps this OPTIONAL everywhere it appears; models that don't emit it still * produce valid traces. */ /** * Validate a candidate Rationale shape, throwing a {@link RationaleValidationError} * if invalid (message text identical to the pre-tagging string errors; * discriminate via `_tag`, not `instanceof`). * Returns the value (narrowed) when valid. */ declare const validateRationale: (value: unknown) => Rationale; /** Type guard — returns true when value matches Rationale shape. */ declare const isRationale: (value: unknown) => value is Rationale; /** 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; } /** * Single constructor for the correlated base of every trace event. * * Threading `RunContext` here is what makes "show me this run and everything * it spawned" a single JSONL filter: a sub-agent's events carry a different * `runId` than the parent's (correct), but share `rootRunId` and record * `parentRunId`/`depth` so the tree is reconstructable. */ declare const traceBaseFrom: (ctx: RunContext, iter: number, seq: number) => TraceEventBase; 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"; } /** Type-narrowing helper. Validates the base fields, that `kind` is a known * trace-event kind, and that the fields that kind's payload requires are * present — see `REQUIRED_FIELDS_BY_KIND`. */ declare function isTraceEvent(x: unknown): x is TraceEvent; interface TraceRecorder { readonly emit: (ev: TraceEvent) => Effect.Effect; readonly snapshot: (runId: string) => Effect.Effect; readonly flush: (runId: string) => Effect.Effect; readonly flushAll: () => Effect.Effect; readonly close: (runId: string) => Effect.Effect; } declare const TraceRecorderService_base: Context.TagClass; declare class TraceRecorderService extends TraceRecorderService_base { } interface TraceRecorderOptions { /** Directory to write JSONL files. null = memory only. */ readonly dir: string | null; } declare function TraceRecorderServiceLive(rawOpts: TraceRecorderOptions): Layer.Layer; /** Canonical default trace directory: `~/.reactive-agents/traces`. */ declare function defaultTraceDir(): string; /** * Single canonical trace-directory resolver. * * `REACTIVE_AGENTS_TRACE_DIR` (when non-empty) wins; otherwise the home-dir * default. The test preload (`scripts/test-preload.ts`) points the env var at * a per-process temp dir so unit tests never write into the real corpus. */ declare function resolveTraceDir(env?: NodeJS.ProcessEnv): string; /** * Boundary redirect applied by the recorder: a caller that hard-codes the * default home dir (e.g. `.withTracing()` with no dir) still honors the env * override (and, under a test runner, a per-process temp dir). Explicit non-default dirs are never redirected. */ declare function effectiveTraceDir(dir: string, env?: NodeJS.ProcessEnv): string; type TraceProvenance = "real" | "synthetic"; /** Resolved retention bounds. */ interface RetentionPolicy { readonly syntheticMaxAgeMs: number; readonly syntheticMaxFiles: number; readonly realMinRuns: number; readonly realMaxAgeMs: number; readonly realMaxBytes: number; } /** A run file as seen by the planner. */ interface TraceFileInfo { readonly name: string; readonly mtime: number; readonly size: number; readonly provenance: TraceProvenance; } /** Read the policy from `RA_TRACE_*` env vars (see file header for defaults). */ declare function retentionPolicyFromEnv(env?: NodeJS.ProcessEnv): RetentionPolicy; /** Classify a trace from its first line. Test provider/model => synthetic; unknown => real. */ declare function classifyProvenance(firstLine: string): TraceProvenance; /** * Pure planner: names of run files to delete. Newest-first ordering by mtime. */ declare function planRunPrune(files: readonly TraceFileInfo[], policy: RetentionPolicy, now: number): string[]; /** Apply the retention policy to `dir`. Safe to run concurrently; never throws per-file. */ declare function pruneTraceDir(dir: string, policy?: RetentionPolicy): Promise; interface Trace { readonly runId: string; readonly events: readonly TraceEvent[]; } /** * Load a JSONL trace and parse it into a Trace object: from a file path, or * from JSONL text already in hand (`{ text }`, e.g. a trace a server read or * received). Parsing is {@link parseTrace}. * * @param source A `.jsonl` file path, or `{ text }` holding the JSONL itself. */ declare function loadTrace(source: string | { readonly text: string; }): Promise; /** * Parse JSONL trace text into a Trace object. Synchronous and pure. * Each line must be valid JSON representing a TraceEvent; other lines are skipped. * * `isTraceEvent` checks the base fields, that `kind` is a known trace-event * kind, and that the fields that kind's payload requires are present (see * `REQUIRED_FIELDS_BY_KIND` in `events.ts`) — it does not validate nested * shapes or field types. * * @param text JSONL, one TraceEvent per line. */ declare function parseTrace(text: string): Trace; interface TraceStats { readonly totalEvents: number; readonly iterations: number; readonly interventionsDispatched: number; readonly interventionsSuppressed: number; readonly maxEntropy: number; readonly avgEntropy: number; readonly toolCalls: number; readonly durationMs: number; readonly totalTokens: number; readonly llmExchanges: number; readonly verifierVerdicts: number; readonly verifierRejections: number; readonly guardsFired: number; readonly harnessSignalsInjected: number; readonly stateSnapshots: number; } /** * Compute summary statistics from a trace. * Aggregates entropy, interventions, tool calls, and completion metrics. */ declare function traceStats(trace: Trace): TraceStats; /** A run's recorded cost and how far to trust it. */ interface RunCost { /** * Known USD spend. A lower bound unless `complete` is `true`. `undefined` * when the trace records no cost at all (no `run-completed`, no * `run-cost-finalized`). */ readonly totalCostUsd: number | undefined; /** * `true`: every LLM call was priced. `false`: at least one call had an * unknown price, so `totalCostUsd` understates the spend. `undefined`: the * trace predates the completeness flag and does not say. */ readonly complete: boolean | undefined; /** * Which record the total came from. `run-cost-finalized` is the billed run * total; `run-completed` excludes the background debrief call. */ readonly source: "run-cost-finalized" | "run-completed" | "none"; } /** * Read a run's cost from its trace events: the last `run-cost-finalized` when * present, else the last `run-completed`. Pass one run's events (see * `runSegments` for a file that holds several runs under one runId). * * @param events One run's trace events, in recorded order. * @returns The total, its completeness and its source record. */ declare function runCost(events: readonly TraceEvent[]): RunCost; /** * Render a run cost for a report line: `$0.0123`, `≥$0.0123 (partial: unpriced * calls)` when incomplete, `$0.0123 (completeness unknown)` on a pre-flag * trace, `unknown` when no cost was recorded. * * @param cost A {@link RunCost} from {@link runCost}. */ declare function renderRunCost(cost: RunCost): string; /** Closed set of failure causes (plus `none` for healthy runs and `undetermined`). */ type FailureCause = "direct-chat" | "timeout" | "user-stop" | "aborted" | "incomplete-trace" | "provider-error" | "strategy-error" | "satisfiability-abstain" | "terminal-mislabel" | "plan-posture-veto" | "never-engaged" | "tool-protocol" | "tool-failure" | "wrong-tool-arg" | "stall-after-work" | "stall-no-progress" | "loop-after-work" | "bookkeeping-loop" | "verifier-reject" | "budget-cap" | "unexplained" | "wrong-answer" | "success-with-warning" | "none" | "undetermined"; /** How much the trace supports the verdict. */ type CauseConfidence = "decisive" | "probable" | "insufficient-trace"; /** One trace event that supports the verdict. */ interface CauseEvidence { readonly eventKind: string; readonly seq: number; readonly detail: string; } /** Position of one run among the runs that share a runId in one trace file. */ interface RunSegmentRef { /** 1-based position in recorded order. */ readonly index: number; /** Runs in the file. */ readonly count: number; } /** Output of {@link analyzeCause}. */ interface CauseAnalysis { readonly runId: string; readonly cause: FailureCause; /** Finer, still-deterministic qualifier (e.g. provider `quota`, `cap-cutoff`). */ readonly subCause?: string; readonly confidence: CauseConfidence; readonly evidence: readonly CauseEvidence[]; /** Trace signals that would have made the verdict decisive but were absent. */ readonly missing: readonly string[]; /** The authority that owned the final status (`run-completed.outcome.authority`, else `terminal_decision`). */ readonly authority?: string; /** The kernel's own authority, when a runtime authority replaced it. */ readonly kernelAuthority?: string; /** `run-completed.status`, or `aborted` / `unknown` when no run-completed exists. */ readonly outcomeStatus: string; /** * Which run this is when several share the runId in one trace file (a * reused runId, e.g. Cortex "Continue"); absent when the file holds one run. * `analyzeCause` covers the last run (`index === count`, 1-based); classify * another with `runSegments` (segments.ts) and {@link withRunSegment}. */ readonly runSegment?: RunSegmentRef; } /** * Classify why a run ended the way it did, from trace events only. * * Pure and deterministic: ordered predicates, first match wins. Returns * `confidence: "insufficient-trace"` (cause `undetermined`) instead of * guessing when a trace lacks the terminal signals. Reads model text only for * the warning-level tool-claim check (see the honesty rules above). * * @param trace A loaded trace. When several runs share its runId, the last * run is classified (see {@link CauseAnalysis.runSegment}). * @returns The cause, confidence, supporting evidence and the signals whose * absence kept the verdict from being decisive. */ declare function analyzeCause(trace: Trace): CauseAnalysis; /** One-line human rendering of a {@link CauseAnalysis}. */ declare function renderCause(c: CauseAnalysis): string; /** * One line naming which of the runs that share a runId a report covers. * * @param s The run's position (`CauseAnalysis.runSegment`). */ declare function runSegmentNote(s: RunSegmentRef): string; /** * Classify one run of a multi-run trace file and record its position. * * @param segment One element of `runSegments(trace)`. * @param ref Its 1-based position and the file's run count. */ declare function withRunSegment(segment: Trace, ref: RunSegmentRef): CauseAnalysis; /** Cohort tally of causes across many runs (audit rule 13 cohort mode). */ interface CauseTally { /** Runs tallied. Direct-chat traces are not runs and are excluded (see `notRuns`). */ readonly total: number; readonly byCause: Readonly>; readonly byConfidence: Readonly>; /** `cause|outcomeStatus` → count, so a cause on successful runs is distinguishable. */ readonly byCauseAndStatus: Readonly>; /** `direct-chat` traces skipped (no run lifecycle by design). */ readonly notRuns: number; } /** * Tally {@link CauseAnalysis} results across a cohort. `direct-chat` results * are counted in `notRuns` only. * * @param analyses One analysis per run. * @returns Counts by cause, by confidence, and by cause x outcome status. */ declare function tallyCauses(analyses: readonly CauseAnalysis[]): CauseTally; interface GuardStat { readonly guard: string; readonly count: number; /** outcome → count, e.g. { warn: 2, terminate: 1 }. */ readonly outcomes: Readonly>; /** iterations at which this guard fired (with duplicates for repeat-in-iter). */ readonly iters: readonly number[]; } /** An iteration where ≥2 DISTINCT guards fired — the redundancy fingerprint. */ interface OverlapStorm { readonly iter: number; readonly guards: readonly string[]; } interface FailureMode { readonly mode: string; readonly evidence: string; } interface InterventionAnalysis { readonly runId: string; readonly status?: RunCompletedEvent["status"]; readonly iterations: number; readonly guardsFired: number; /** Per-guard stats, sorted by count desc. */ readonly byGuard: readonly GuardStat[]; /** Iterations with ≥2 distinct guards firing. */ readonly overlapStorms: readonly OverlapStorm[]; /** The decider that actually ended the run, if recoverable from the trace. */ readonly terminalDecision?: { guard: string; outcome: string; reason: string; }; /** terminatedBy from the last snapshot, if present. */ readonly terminatedBy?: string; /** tool name → number of tool-call-start events. */ readonly toolCallCounts: Readonly>; /** Largest single-iteration token increase across snapshots. */ readonly maxIterTokenDelta: number; readonly totalTokens: number; /** Trace-detectable failure modes (see SCOPE). */ readonly failureModes: readonly FailureMode[]; /** Honest gaps — modes that require non-trace inspection. */ readonly notDetectable: readonly string[]; } interface AnalyzeOptions { /** A single-iteration token jump ≥ this flags a runaway. Default 30000. */ readonly runawayTokenDelta?: number; /** Same guard firing redirect/warn ≥ this flags a nudge-loop. Default 3. */ readonly nudgeLoopThreshold?: number; /** ≥ this many recall tool-calls flags a recall-loop. Default 3. */ readonly recallLoopThreshold?: number; } declare function analyzeInterventions(trace: Trace, opts?: AnalyzeOptions): InterventionAnalysis; /** Human-readable per-run report — the debug view for a single trace. */ declare function renderInterventionReport(a: InterventionAnalysis): string; interface HonestyCheck { /** True when the run reported done/success. */ readonly claimedSuccess: boolean; /** A deliverable-producing tool call succeeded (file written). */ readonly deliverableProduced: boolean; /** Any substantive (non-introspection) tool call succeeded. */ readonly substantiveWorkDone: boolean; /** * The trust-labeled verdict. NEVER bare "success" — `status` is self-reported. * - honest-failure : claimed failure (trustworthy negative) * - claimed-success (unverified): claimed success + did real work; content * correctness NOT checkable from trace (task * text absent) — treat as UNVERIFIED. * - dishonest-success-suspected: claimed success but did NO substantive tool * work — the prose-lie class. * - aborted : the run never reached a terminal event * (`run-aborted` sentinel, or no `run-completed`); * NOT an honest failure — nothing was claimed. */ readonly label: "aborted" | "honest-failure" | "claimed-success (unverified)" | "dishonest-success-suspected"; readonly evidence: string; } interface CostSignal { readonly totalTokens: number; /** Cumulative token reading at each snapshot. */ readonly tokenTrajectory: readonly number[]; readonly maxIterTokenDelta: number; /** LLM call count — proxy for harness sub-call overhead (synthesis, classify). */ readonly llmCalls: number; /** Sum of intervention-dispatched cost.tokensEstimated — harness intervention spend. */ readonly interventionEstimatedTokens: number; /** * Whether per-exchange input/output + cache token split is available. * llm-exchange fires on the live kernel path via observable-llm.ts (verified * 2026-07-05); response payloads complete as of Arc 1 Task 1. Currently FALSE * because no provider populates tokensIn/tokensOut/cacheRead yet (coverage gap). */ readonly inOutSplitAvailable: boolean; /** * The run's USD spend (see `runCost`): the late `run-cost-finalized` total * when recorded, else `run-completed`'s. Check `spend.complete` before * reading the number as the full spend. */ readonly spend: RunCost; } interface EntropyDegradation { /** * Lowest sourcesPresent (2-4; excludes contextPressure, which is never * null — see EntropyScoredEvent.sourcesPresent) seen across all * entropy-scored events; 0 when none fired. */ readonly minSourcesPresent: number; /** * Highest sourcesPresent (2-4; excludes contextPressure, which is never * null) seen across all entropy-scored events; 0 when none fired. */ readonly maxSourcesPresent: number; /** Iterations where the composite was a partial signal (sourcesPresent < 4). */ readonly degradedIterations: number; /** Iterations where the sensor self-reported low confidence. */ readonly lowConfidenceIterations: number; } interface ReasoningTrajectory { readonly entropyFirst?: number; readonly entropyLast?: number; readonly entropyShape: "converging" | "flat" | "diverging" | "unknown"; /** decisionType → count, from decision-evaluated events. */ readonly decisionTypes: Readonly>; /** Final step composition, from the last snapshot. */ readonly stepsByTypeFinal: Readonly>; /** Surfaces partial-source composites (RC-1/RC-2) without hand-grepping JSONL. */ readonly entropyDegradation: EntropyDegradation; } interface ToolOutcome { readonly tool: string; readonly calls: number; readonly ok: number; readonly errors: number; readonly truncated: number; } interface InterventionPressure { /** Reactive interventions that fired (intervention-dispatched). */ readonly dispatched: number; /** Interventions evaluated but NOT fired, by suppression reason. */ readonly suppressedByReason: Readonly>; /** Harness-authored steps injected into the model stream, by kind. */ readonly signalsInjectedByKind: Readonly>; } interface CoverageReport { /** event kind → count present in this trace. */ readonly present: Readonly>; /** Emitters known to have ZERO callers (signal is structurally blind). */ readonly knownDeadEmitters: readonly string[]; /** * Metrics that cannot be computed because their source events are missing — * with WHY. The anti-misleading guarantee: a blind metric is never reported * as a real zero. */ readonly blindSpots: readonly { readonly metric: string; readonly reason: string; }[]; } /** * What actually crossed the provider boundary, summarized per run — the * closed-loop replacement for hand-rolled logging proxies. * * Born 2026-07-10: three wire-level defects (empty assistant prose, a 67% * meta-tool schema share, a hidden memory-extraction call) were invisible to * every existing report even though `llm-exchange` RECORDED the evidence — * nobody asked the questions. This section asks them on every run. */ interface WireVisibility { /** Provider requests this run sent (mirror of llmExchangeCount). */ readonly exchanges: number; /** Assistant turns replayed across all requests. */ readonly assistantTurns: number; /** * Chars of the model's OWN PROSE re-shown to it across assistant turns * (placeholders like `[tool_use:x]` excluded). 0 with multiple turns means * the model never re-reads a word of its reasoning (thought continuity OFF). */ readonly assistantProseChars: number; /** Distinct tool schemas the model was offered, across the run. */ readonly toolSchemaNames: readonly string[]; /** Mean schemas per request — the per-turn schema tax. */ readonly avgToolSchemasPerRequest: number; /** Wire-level anomalies worth a human look. */ readonly flags: readonly string[]; } interface RunAnalysis { readonly runId: string; readonly status?: RunCompletedEvent["status"]; readonly iterations: number; /** KEYSTONE — trust-labeled outcome (never bare "success"). */ readonly honesty: HonestyCheck; readonly interventions: InterventionAnalysis; readonly pressure: InterventionPressure; readonly cost: CostSignal; readonly reasoning: ReasoningTrajectory; readonly tools: readonly ToolOutcome[]; readonly failureModes: readonly FailureMode[]; /** * WHY the run ended the way it did — deterministic, trace-only, additive * next to `failureModes` (see `cause.ts`). `confidence: "insufficient-trace"` * means the trace could not support a verdict, never a guess. */ readonly cause: CauseAnalysis; /** CENTERPIECE — what the trace could and could NOT see. */ readonly coverage: CoverageReport; /** Count of llm-exchange events in this run — proxy for model round-trips. */ readonly llmExchangeCount: number; /** What crossed the provider boundary (undefined when no exchanges recorded). */ readonly wire?: WireVisibility; } declare function analyzeRun(trace: Trace, opts?: AnalyzeOptions): RunAnalysis; /** Full per-run forensic report — the human debug view. */ declare function renderRunReport(a: RunAnalysis): string; /** * Split a trace into one {@link Trace} per run that shares its runId. * * @param trace A loaded trace (one file). * @returns The runs in recorded order; `[trace]` when the file holds one run. */ declare function runSegments(trace: Trace): readonly Trace[]; /** * The last run in a trace file (see {@link runSegments}): the run a reader of * "how did this runId end" means. * * @param trace A loaded trace (one file). * @returns The last segment, and how many runs the file holds. */ declare function lastRunSegment(trace: Trace): { readonly trace: Trace; readonly count: number; }; /** One-sentence plain-language description of each {@link FailureCause}. */ declare const CAUSE_DESCRIPTIONS: Readonly>; /** * Plain-language description of a failure cause, sharpened by its `subCause` * when the cause-level sentence would blur it (pass the analysis' `subCause`). * * @param cause A cause from {@link CauseAnalysis.cause}. * @param subCause Optional {@link CauseAnalysis.subCause}. * @returns One sentence, no trailing period. */ declare function causeDescription(cause: FailureCause, subCause?: string): string; /** * Next steps the diagnosis can justify, from the cause and its `subCause`. * Empty when nothing in the trace points to an action (a user stop, a healthy run). * * @param analysis The cause and sub-cause from {@link analyzeCause}. * @returns Short imperative sentences, most useful first. */ declare function causeNextActions(analysis: Pick): readonly string[]; /** The minimal event shape this reader needs (typed trace events and raw JSONL records both fit). */ interface GuardEventLike { readonly kind?: unknown; readonly guard?: unknown; readonly outcome?: unknown; readonly iter?: unknown; readonly metadata?: unknown; } /** * The exit gate's decision for the guard event at `index`: the first `exit_gate` * event after it in the same iteration whose `proposedBy` is that guard. * Undefined when none exists. */ declare function gateDecisionFor(events: readonly GuardEventLike[], index: number): string | undefined; /** * True when the guard-fired event at `index` ended the run: the paired exit gate * accepted or handed off its proposal. Without a paired gate event, the event's * own outcome decides (`terminate` = ended) — this covers guards that never * propose and the `exit_gate` event itself (its handoff reads `terminate`). */ declare function guardEndedRun(events: readonly GuardEventLike[], index: number): boolean; /** * Guard-fired events that ended the run, optionally limited to `guards`. * * @param events - The trace's events in order (any shape with `kind`/`guard`/`outcome`/`iter`/`metadata`). * @param guards - Guard names to keep; omit for every guard. * @returns The run-ending guard events, in trace order. */ declare function runEndingGuardEvents(events: readonly E[], guards?: readonly string[]): E[]; /** Who the trace says is at fault for a failed run. */ type AttributionVerdict = "harness" | "model" | "environment" | "unattributed" | "not-failed"; /** * Reasons the turn-level rules (attribution.ts, attribution-rules.ts, * attribution-guidance.ts, attribution-forcing.ts, attribution-refusal.ts, * attribution-literal-newlines.ts) return, listed in rule order * (first match wins; `harness:refusal-counted-as-repeat` also runs last, in its * probable mode). The runtime list the {@link AttributionReason} type is derived * from, so the docs Reasons table (`reference/cli.md`) is pinned against it. */ declare const TURN_LEVEL_REASONS: readonly ["harness:false-veto", "harness:honest-decline-mislabeled", "model:fabrication-vetoed", "harness:tool-surface", "harness:tool-not-offered", "harness:contradictory-guidance", "harness:subpass-abstained", "harness:tool-call-dropped", "harness:refusal-counted-as-repeat", "harness:refused-repairable", "harness:misleading-refusal", "model:invalid-content", "harness:unrepaired-content", "harness:tool-call-corrupted", "harness:plan-fanout-blob", "harness:premature-stop", "harness:completeness-blind", "harness:offer-accepted-as-done", "harness:evidence-withheld", "harness:evidence-truncated", "harness:evidence-missing", "harness:misleading-guidance", "harness:forcing-unused", "model:ignored-guidance", "model:evidence-not-gathered", "model:had-evidence-wrong-output"]; /** A reason a turn-level attribution rule returns. */ type TurnLevelReason = (typeof TURN_LEVEL_REASONS)[number]; /** Closed set of attribution reasons. The prefix names the {@link AttributionVerdict}. */ type AttributionReason = TurnLevelReason | "harness:terminal-mislabel" | "harness:plan-posture-veto" | "harness:stall-after-work" | "harness:loop-after-work" | "harness:strategy-error" | "model:never-engaged" | "model:tool-protocol" | "model:wrong-tool-arg" | "model:stall-no-progress" | "model:bookkeeping-loop" | "environment:run-aborted" | "environment:provider-error" | "environment:budget-cap" | "environment:tool-failure" | "unattributed" | "not-failed"; /** * Owner of each failure cause, as an attribution reason. Causes whose owner * the trace cannot settle without a grader map to `unattributed`: * a satisfiability abstain may be right, a verifier reject may be a correct * veto, and `unexplained` / `undetermined` are residuals by definition. */ declare const CAUSE_ATTRIBUTION: Readonly>; /** The owner a reason names. */ declare const verdictOf: (r: AttributionReason) => AttributionVerdict; /** The turn whose output produced the failing artifact or answer. */ interface DivergenceTurn { readonly iter: number; /** `seq` of the `llm-exchange` event of that turn. */ readonly seq: number; } /** What the attribution judged: a file the run had to write, or its answer. */ interface AttributionTarget { readonly kind: "file" | "answer"; /** File name (or template, e.g. `out-N.txt`) for `file`; `answer` for `answer`. */ readonly ref: string; /** Where the target came from: a grader check name, the contract, the outcome, or the run's writes. */ readonly source: "grader-check" | "contract" | "outcome-outstanding" | "run-writes" | "final-output"; } /** Output of {@link attributeFailure}. */ interface Attribution { readonly runId: string; readonly verdict: AttributionVerdict; readonly reason: AttributionReason; readonly confidence: CauseConfidence; /** Absent when the failing artifact was never produced (or the run did not fail). */ readonly divergenceTurn?: DivergenceTurn; /** The artifact or answer the attribution judged. Absent on `not-failed`. */ readonly target?: AttributionTarget; /** Trace events that support the verdict. */ readonly evidence: readonly CauseEvidence[]; /** Trace signals that would have made the verdict decisive (or possible) but were absent. */ readonly missing: readonly string[]; /** Other reasons whose rule also matched, in rule order (contributing factors). */ readonly alsoMatched: readonly AttributionReason[]; /** Which failure signals fired (`run-completed.status=failure`, `eval-graded.passed=false`, ...). */ readonly failureSignals: readonly string[]; /** Present when the reason came from the failure cause (no turn-level rule fired): `cause[/subCause]`. */ readonly cause?: string; } /** * Attribute a failed run to the harness or the model, from trace events only. * * Pure and deterministic, zero tokens. A run counts as failed when * `run-completed.status` is not `success`, `run-completed.outcome.success` is * false, or the last `eval-graded` event failed. A grader pass on an abstained * run is a correct abstention (`not-failed`). * * Works on any trace recorded by the trace recorder (`.withObservability({ tracing })`), * with or without an `eval-graded` event. Without a grader, only rules that do * not need to know the answer was wrong can fire; the rest report * `unattributed` and name `eval-graded` in `missing`. * * @param full A loaded trace, e.g. from {@link loadTrace}. When several runs * share its runId, the last run is attributed (segments.ts `runSegments`). * @returns The verdict, the reason, the divergence turn, supporting evidence, * the signals whose absence limited the verdict, and other matching reasons. */ declare function attributeFailure(full: Trace): Attribution; /** Human rendering of an {@link Attribution}. */ declare function renderAttribution(a: Attribution): string; /** Cohort tally of {@link Attribution} results. */ interface AttributionTally { readonly total: number; readonly byVerdict: Readonly>; readonly byReason: Readonly>; readonly byConfidence: Readonly>; } /** * Tally attributions across a cohort (e.g. a directory of bench traces). * * @param attributions One attribution per run. * @returns Counts by verdict, by reason and by confidence. */ declare function tallyAttributions(attributions: readonly Attribution[]): AttributionTally; /** Outcomes of a run's real (non-meta) tool calls: the provenance an honest decline rests on. */ interface ToolProvenance { /** Real tool calls that succeeded. */ readonly toolOk: number; /** Real tool calls that failed. */ readonly toolFailed: number; /** The failing calls' error text, to tell a quoted number from an invented one. */ readonly failedErrors: readonly string[]; } /** * Whether `output` is an honest decline: it admits inability, names why (the data * or tool is unreachable), and reports no number the failing tools did not print. * Deterministic, zero tokens. * * @param output The run's final text. * @param provenance Tool outcomes; when given, the decline only counts if tools ran and none succeeded. * @returns True for an honest decline. */ declare function isHonestDecline(output: string, provenance?: ToolProvenance): boolean; /** * The real (non-meta) tool-call outcomes of a recorded run, for callers that * grade a decline against its trace (the benchmark rescore). * * @param trace A loaded trace (one run). */ declare const toolProvenanceOf: (trace: Trace) => ToolProvenance; /** The set of activity keys for one run. */ type MechanismActivity = ReadonlySet; /** * Activity keys for one run (see the file header for the key families). * * @param trace A loaded trace (one run). * @returns The distinct mechanism keys that acted in the run. */ declare function mechanismActivity(trace: Trace): MechanismActivity; /** How often one activity key occurred in each cohort. */ interface ActivityDelta { readonly key: string; /** Runs (of `beforeRuns`) in which the key occurred. */ readonly before: number; /** Runs (of `afterRuns`) in which the key occurred. */ readonly after: number; } /** Output of {@link compareActivity}. */ interface ActivityComparison { readonly beforeRuns: number; readonly afterRuns: number; /** Keys whose run count changed, largest change first. */ readonly changed: readonly ActivityDelta[]; } /** * Compare mechanism activity between two cohorts of runs. * * @param before Activity of each run in the baseline cohort. * @param after Activity of each run in the changed cohort. * @returns Every key whose run count differs, ordered by the size of the change. */ declare function compareActivity(before: readonly MechanismActivity[], after: readonly MechanismActivity[]): ActivityComparison; /** * Runs in which a mechanism fired: those with at least one key that contains * `mechanism` (e.g. `exit_gate`, `requirement:artifact-produced@task-text`). * * @param runs Activity of each run. * @param mechanism A key or key fragment. * @returns How many runs carry a matching key. */ declare function runsWithMechanism(runs: readonly MechanismActivity[], mechanism: string): number; interface CohortStats { readonly label: string; readonly n: number; /** Fraction claiming success (pass@1 estimate — NOT verified). */ readonly claimedSuccessRate: number; /** Strict pass^n: every run in the cohort claimed success. */ readonly allClaimedSuccess: boolean; /** Honesty guard — fraction flagged dishonest-success-suspected. Lower is better. */ readonly dishonestSuspectedRate: number; /** Honesty guard — fraction that produced a deliverable file. Higher is better. */ readonly deliverableProducedRate: number; /** honesty label → count. */ readonly honestyDistribution: Readonly>; readonly tokensP50: number; readonly tokensP95: number; readonly avgLlmCalls: number; readonly avgGuardsFired: number; /** Fraction of runs with ≥1 overlap storm. */ readonly overlapStormRate: number; /** guard name → total fires across the cohort. */ readonly guardFrequency: Readonly>; /** failure mode → fraction of runs exhibiting it. */ readonly failureModeRates: Readonly>; /** A metric blind in ANY run of the cohort — comparisons on these are inconclusive. */ readonly blindMetrics: readonly string[]; } declare function aggregateCohort(label: string, traces: readonly Trace[], opts?: AnalyzeOptions): CohortStats; interface CohortDelta { readonly a: CohortStats; readonly b: CohortStats; /** * Trust-gated verdict on B-vs-A: * - "B regresses" : honesty loosened (dishonest↑ or deliverable↓) OR success dropped. * - "B improves" : honesty held AND (success↑ or tokens↓ at flat success). * - "B neutral" : honesty held, no material outcome/cost delta. * - "inconclusive (blind)": a decisive metric is blind in a cohort — can't call it. */ readonly verdict: "B improves" | "B regresses" | "B neutral" | "inconclusive (blind)"; readonly reasons: readonly string[]; readonly deltas: { readonly claimedSuccessRate: number; readonly dishonestSuspectedRate: number; readonly deliverableProducedRate: number; readonly tokensP50: number; readonly avgGuardsFired: number; readonly overlapStormRate: number; }; } declare function compareCohorts(a: CohortStats, b: CohortStats): CohortDelta; declare function renderCohortDelta(d: CohortDelta): string; /** * TraceBridgeLayer — subscribes to the EventBus and converts reactive events * into TraceEvents recorded by the TraceRecorderService. * * Requires: EventBus, TraceRecorderService * * Lifecycle: subscription is registered when the layer scope opens and * automatically unregistered when the scope closes. */ declare const TraceBridgeLayer: Layer.Layer; declare function toTraceEvent(raw: AgentEvent, seq: number): TraceEvent | null; declare const RationaleValidationError_base: new = {}>(args: effect_Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => effect_Cause.YieldableError & { readonly _tag: "RationaleValidationError"; } & Readonly; /** * Raised by `validateRationale` when a candidate Rationale fails a shape rule. * * Thrown (not an Effect error channel) to keep the validator's existing sync * calling contract — `isRationale` and the test suite catch it as a plain * throw site, mirroring the sanctioned validator pattern in * `@reactive-agents/memory` (`throw new MemoryError({ message })`). * `message` carries the exact, byte-identical validator text (prefixed * `Rationale: `) so message-based consumers stay green; `_tag` gives * consumers a stable discriminator without relying on `instanceof`. */ declare class RationaleValidationError extends RationaleValidationError_base<{ readonly message: string; }> { } declare const TraceStorageError_base: new = {}>(args: effect_Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => effect_Cause.YieldableError & { readonly _tag: "TraceStorageError"; } & Readonly; /** * Raised inside the trace recorder when a disk-store operation fails * (retention prune, directory creation, JSONL append). * * The value never escapes the recorder: each construction site is a * `Effect.tryPromise` catch whose failure is immediately consumed by * `errorTag(err)` in an `Effect.catchAll` that publishes an * `ErrorSwallowed` telemetry event. `errorTag` resolves tagged errors via * their `_tag` (the class-name identity fallback is never reached), so the * emitted discriminator is now `"TraceStorageError"` instead of `"Error"`. * `cause` keeps the original IO error for debugging; `message` keeps the * previous `String(e)` rendering byte-identical. */ declare class TraceStorageError extends TraceStorageError_base<{ readonly message: string; readonly cause?: unknown; }> { } export { type ActivityComparison, type ActivityDelta, type AnalyzeOptions, type AssessmentEvent, type AssumptionRecordedEvent, type Attribution, type AttributionReason, type AttributionTally, type AttributionTarget, type AttributionVerdict, CAUSE_ATTRIBUTION, CAUSE_DESCRIPTIONS, type CauseAnalysis, type CauseConfidence, type CauseEvidence, type CauseTally, type ChecklistInferredTraceEvent, type CohortDelta, type CohortStats, type ContentPartDegradedEvent, type ContractCompiledEvent, type ContractRef, type ControlResolutionEvent, type CostSignal, type CoverageReport, type CuratorDecisionEvent, type DecisionEvaluatedEvent, type DivergenceTurn, type EntropyScoredEvent, type EnvironmentUpdatedTraceEvent, type EvalGradedCheck, type EvalGradedEvent, type FailureCause, type FailureMode, type GuardEventLike, type GuardFiredEvent, type GuardStat, type HarnessSignalInjectedEvent, type HonestyCheck, type InterventionAnalysis, type InterventionDispatchedEvent, type InterventionPressure, type InterventionSuppressedEvent, type IterationBoundaryEvent, type KernelStateSnapshotEvent, type LLMExchangeEvent, type LedgerEntryTraceEvent, type MechanismActivity, type MessageAppendedEvent, type OverlapStorm, type PhaseBoundaryEvent, type ProjectionRenderedEvent, RationaleValidationError, type ReasoningTrajectory, type RetentionPolicy, type RunAbortedEvent, type RunAnalysis, type RunCompletedEvent, type RunCost, type RunCostFinalizedEvent, type RunOutcome, type RunSegmentRef, type RunSignalTally, type RunStartedEvent, type SignalEffectEvent, type SignalRenderSection, type SignalRenderedEvent, type SignalTargetPolicy, type StatePatchAppliedEvent, type StrategySwitchedEvent, type StructuredOutputReportedTraceEvent, type ToolCallEvent, type ToolOutcome, type ToolProvenance, type ToolSurfaceResolvedEvent, type Trace, TraceBridgeLayer, type TraceEvent, type TraceEventBase, type TraceFileInfo, type TraceProvenance, type TraceRecorder, type TraceRecorderOptions, TraceRecorderService, TraceRecorderServiceLive, type TraceStats, TraceStorageError, type VerifierVerdictEvent, aggregateCohort, analyzeCause, analyzeInterventions, analyzeRun, attributeFailure, causeDescription, causeNextActions, classifyProvenance, compareActivity, compareCohorts, defaultTraceDir, effectiveTraceDir, gateDecisionFor, guardEndedRun, isHonestDecline, isRationale, isTraceEvent, lastRunSegment, loadTrace, mechanismActivity, parseTrace, planRunPrune, pruneTraceDir, renderAttribution, renderCause, renderCohortDelta, renderInterventionReport, renderRunCost, renderRunReport, resolveTraceDir, retentionPolicyFromEnv, runCost, runEndingGuardEvents, runSegmentNote, runSegments, runsWithMechanism, tallyAttributions, tallyCauses, toTraceEvent, toolProvenanceOf, traceBaseFrom, traceStats, validateRationale, verdictOf, withRunSegment };