@crewhaus/runtime-core 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,7 +32,7 @@ export type SessionMetricsSnapshot = {
32
32
  readonly turns: number;
33
33
  /** Total model calls (model_response events). */
34
34
  readonly modelCalls: number;
35
- /** Errors that were NOT recovered (error_recovered action "fail"). */
35
+ /** Errors that were NOT recovered (error_recovered action "fail" or "halt"). */
36
36
  readonly unrecoveredErrors: number;
37
37
  /** unrecoveredErrors / max(modelCalls,1) — the rate we alert on. */
38
38
  readonly errorRate: number;
@@ -104,9 +104,12 @@ export class SessionMetricsAccumulator {
104
104
  this.ttftSeen.delete(ev.traceId);
105
105
  return;
106
106
  case "error_recovered":
107
- // Only a terminal "fail" is an unrecovered error; retry/compact/etc.
108
- // are the recovery engine doing its job.
109
- if (ev.action === "fail")
107
+ // Only a terminal stop is an unrecovered error; retry/compact/etc.
108
+ // are the recovery engine doing its job. "fail" is the generic
109
+ // terminal action; "halt" (v0.3.0 Goal 6) is the CLASSIFIED
110
+ // terminal action (billing/auth/rate-limit) — count both so the
111
+ // error-rate baseline is unchanged by the taxonomy upgrade.
112
+ if (ev.action === "fail" || ev.action === "halt")
110
113
  this.unrecoveredErrors += 1;
111
114
  return;
112
115
  case "cost_accrual": {
@@ -1,6 +1,6 @@
1
1
  import type { RunContext } from "@crewhaus/run-context";
2
2
  import type { TraceEvent, TraceEventBus, Unsubscribe } from "@crewhaus/trace-event-bus";
3
- export type IncidentTriggerKind = "circuit_open" | "egress_blocked" | "justification_deny_storm";
3
+ export type IncidentTriggerKind = "circuit_open" | "egress_blocked" | "justification_deny_storm" | "run_failed";
4
4
  /** How many judge-backed denials in the ring buffer constitute a "storm". */
5
5
  export declare const DENY_STORM_THRESHOLD = 3;
6
6
  export type IncidentCapture = {
@@ -36,6 +36,15 @@ export function classifyIncidentTrigger(event, ringDenials) {
36
36
  };
37
37
  }
38
38
  return undefined;
39
+ case "run_failed":
40
+ // v0.3.0 Goal 6 — a terminal run failure (classified or generic)
41
+ // captures an incident bundle unconditionally: it is published
42
+ // exactly once, immediately before the run-ending throw.
43
+ return {
44
+ kind: "run_failed",
45
+ reason: `run failed (${event.class}, exit ${event.exitCode}): ${event.message}`,
46
+ triggeredBy: "run_failed",
47
+ };
39
48
  case "permission_decision":
40
49
  if (event.outcome === "egress-blocked") {
41
50
  return {
package/dist/index.d.ts CHANGED
@@ -14,6 +14,93 @@ import { type SlashCommand } from "@crewhaus/slash-commands";
14
14
  import type { RegisteredTool } from "@crewhaus/tool-catalog";
15
15
  import { type AlertSink } from "./observability";
16
16
  import type { SloMitigationSink, SloTargets } from "./slo-monitor";
17
+ /**
18
+ * Hard cap (chars) on the RENDERED mutable tail — the `<current_plan>` +
19
+ * `<requirements_ledger>` blocks appended after the cache-marked frozen
20
+ * prefix on every model call. The spec's `continuity.focusMaxChars` lowers
21
+ * onto this in PR 11; until then the default applies. Enforced in
22
+ * `renderContinuityTail`: the ledger has priority (it is the
23
+ * motivating-failure fix), truncating oldest-first with a marker; the plan
24
+ * yields whatever budget remains.
25
+ */
26
+ export declare const DEFAULT_CONTINUITY_TAIL_MAX_CHARS = 4096;
27
+ /**
28
+ * Cap (chars, ~16KB) on the in-run requirements ledger's total entry text.
29
+ * Oldest entries are evicted first and the rendered block gains a
30
+ * `[ledger truncated]` marker — user messages are small, so hitting this
31
+ * means hundreds of evicted requirements.
32
+ */
33
+ export declare const CONTINUITY_LEDGER_MAX_CHARS: number;
34
+ /**
35
+ * Key in the per-run `runState` state-store that plan-mutating tools
36
+ * (PlanUpdate/FocusWrite, PR 7) set to `true` after a write. The loop
37
+ * re-reads it before each model call and re-renders the `<current_plan>`
38
+ * tail block via `continuity.onPlanDirty` when set — the state-store's
39
+ * first consumer.
40
+ */
41
+ export declare const PLAN_DIRTY_STATE_KEY = "plan.dirty";
42
+ /** Role attribution on an evicted-content record (§2.3): `"user"` for user
43
+ * text, `"assistant"` for assistant text, `"tool"` for tool_result content
44
+ * (which the API carries inside user-role messages). */
45
+ export type ContextEvictedRole = "user" | "assistant" | "tool";
46
+ /** One verbatim evicted-content record — the `context_evicted` event payload
47
+ * and the requirements-ledger entry shape. */
48
+ export type ContinuityLedgerEntry = {
49
+ readonly role: ContextEvictedRole;
50
+ readonly text: string;
51
+ readonly turnNumber?: number;
52
+ };
53
+ /**
54
+ * §2.5 — the deterministic teardown handoff payload. Built with ZERO model
55
+ * calls from state the run already holds: the last rendered plan snapshot,
56
+ * the in-run ledger entries verbatim, the session id, and why the run
57
+ * stopped (the same reason the `stop` hook receives).
58
+ */
59
+ export type HandoffInput = {
60
+ /** Last `<current_plan>` content from `loadPlan`/`onPlanDirty`; null when
61
+ * the plan store is empty or the seam never produced one. */
62
+ readonly plan: string | null;
63
+ /** The in-run requirements ledger, oldest-first, verbatim. */
64
+ readonly ledger: ReadonlyArray<ContinuityLedgerEntry>;
65
+ readonly sessionId: string;
66
+ readonly stopReason: "complete" | "exit" | "abort";
67
+ };
68
+ /**
69
+ * §2.3 — decompose one message that compaction is about to drop into
70
+ * verbatim `context_evicted` records. Text-bearing content only: user/
71
+ * assistant text becomes one entry per message (blocks joined with `\n` so
72
+ * the record IS the message, not fragments), each `tool_result`'s text
73
+ * becomes a `"tool"` entry. `tool_use` inputs are skipped — they already
74
+ * persist verbatim as `tool_use` event-log lines. The snip marker is
75
+ * dropped. Exported for tests.
76
+ */
77
+ export declare function extractEvictedEntries(message: Anthropic.MessageParam): ContinuityLedgerEntry[];
78
+ /**
79
+ * §2.5 — render the mutable tail region: the `<current_plan>` block and the
80
+ * `<requirements_ledger>` block, hard-capped at `maxChars` (default
81
+ * {@link DEFAULT_CONTINUITY_TAIL_MAX_CHARS}). Pure and deterministic;
82
+ * exported for tests.
83
+ *
84
+ * Cap enforcement, in priority order:
85
+ * 1. The ledger block drops its OLDEST entries first (they are the
86
+ * time-ordered content) until it fits, gaining the
87
+ * `[ledger truncated]` marker — the newest requirements always survive.
88
+ * 2. The plan gets whatever budget remains; an over-budget plan keeps its
89
+ * HEAD (focus/next-steps render first in plan documents) and gains a
90
+ * trailing truncation marker. A remainder too small for any plan
91
+ * content drops the plan block entirely — the ledger is the
92
+ * motivating-failure fix and always wins.
93
+ *
94
+ * Closing delimiters inside plan/ledger content are neutralized so
95
+ * embedded `</current_plan>` / `</requirements_ledger>` text cannot
96
+ * terminate its wrapper block early (same defense as `<recalled_memory>`).
97
+ */
98
+ export declare function renderContinuityTail(input: {
99
+ readonly plan: string | null;
100
+ readonly ledger: ReadonlyArray<ContinuityLedgerEntry>;
101
+ readonly ledgerTruncated?: boolean;
102
+ readonly maxChars?: number;
103
+ }): string[];
17
104
  /**
18
105
  * Run `items` through `fn` with at most `limit` in flight at once,
19
106
  * preserving input order in the returned results. A pool of `limit`
@@ -26,7 +113,8 @@ export declare function mapWithConcurrency<T, R>(items: ReadonlyArray<T>, limit:
26
113
  export { CLAUDE_CODE_HEADERS, CLAUDE_CODE_SYSTEM_PREFIX, OAUTH_BETAS, createAnthropicClient, resolveAuth, } from "@crewhaus/adapter-anthropic";
27
114
  export type { ResolvedAuth } from "@crewhaus/adapter-anthropic";
28
115
  export { createJanitor } from "./janitor";
29
- export type { CreateJanitorOptions, Janitor, JanitorReservationStore, JanitorRunResult, JanitorStepName, JanitorStepResult, JanitorStepStatus, } from "./janitor";
116
+ export { JANITOR_BUILTIN_STEPS } from "./janitor";
117
+ export type { CreateJanitorOptions, Janitor, JanitorBuiltinStepName, JanitorReservationStore, JanitorRunResult, JanitorStep, JanitorStepName, JanitorStepOutcome, JanitorStepResult, JanitorStepStatus, } from "./janitor";
30
118
  export { type AlertBreachPayload, type AlertSink, type AttachDefaultSubscribersOptions, attachDefaultSubscribers, } from "./observability";
31
119
  export { type AttachedSloMonitor, type AttachSloMonitorOptions, type SloBreach, type SloMitigationEvent, type SloMitigationRung, type SloMitigationSink, type SloTargets, type SloWindowMetrics, DEFAULT_SLO_WINDOW_MS, MIN_SLO_SAMPLES, SloWindow, attachSloMonitor, detectSloBreaches, } from "./slo-monitor";
32
120
  export { type AttachIncidentCollectorOptions, type IncidentCapture, type IncidentTriggerKind, attachIncidentCollector, classifyIncidentTrigger, } from "./incident-collector";
@@ -287,6 +375,53 @@ export type RunChatLoopOptions = {
287
375
  * run's session id (so the callback can read the transcript to summarize). */
288
376
  readonly onCapture?: (completedTurns: number, sessionId: string) => Promise<void>;
289
377
  };
378
+ /**
379
+ * v0.3.0 Goal 1 — the continuity seam (§2.3 requirements ledger, §2.5
380
+ * mutable tail region, §2.8 handoff). Injected closures exactly like
381
+ * `memory` above: the composition root (memory-service) constructs them
382
+ * over the continuity store; runtime-core never touches a store.
383
+ *
384
+ * When present:
385
+ * - A VOLATILE TAIL of system blocks (`<current_plan>` +
386
+ * `<requirements_ledger>`) is rebuilt on every model call and appended
387
+ * AFTER the cache-marked frozen prefix, so tail edits re-tokenize only
388
+ * the tail (see prompt-cache-manager's `volatile` flag). The rendered
389
+ * tail is hard-capped at {@link DEFAULT_CONTINUITY_TAIL_MAX_CHARS}.
390
+ * - `loadPlan` renders the initial `<current_plan>` content at boot;
391
+ * `onPlanDirty` re-renders it when a tool has set
392
+ * `"plan.dirty": true` in the per-run state-store (reachable via the
393
+ * RuntimeBridge's `runState`); absent `onPlanDirty` falls back to
394
+ * `loadPlan`.
395
+ * - `ledger !== false` (the default) turns on the requirements ledger —
396
+ * the deterministic fix for the release's motivating failure: every
397
+ * USER message compaction is about to drop is appended VERBATIM to the
398
+ * session event log as a `context_evicted` event and folded into the
399
+ * in-run ledger ({@link CONTINUITY_LEDGER_MAX_CHARS} cap, oldest-first
400
+ * eviction), which re-injects on every model call — the user's answer
401
+ * survives any number of compactions regardless of summary quality.
402
+ * Evicted assistant text and tool findings are also persisted as
403
+ * `context_evicted` events (episodic externalization for a later
404
+ * recall integration). `--resume` rebuilds the ledger from the logged
405
+ * events. The autocompact summarizer's prompt receives the ledger text
406
+ * as an anchor, but nothing depends on the summary being right.
407
+ * - `onHandoff` fires ONCE at teardown (the same finally slot as
408
+ * `memory.onCapture`) with a deterministic {@link HandoffInput} — no
409
+ * model calls.
410
+ *
411
+ * ABSENT → byte-identical behavior to a pre-0.3.0 runtime: no tail
412
+ * blocks, no `context_evicted` events, no ledger anchor in the compaction
413
+ * prompt, no handoff (regression-pinned in continuity.test.ts).
414
+ */
415
+ continuity?: {
416
+ /** Rendered `<current_plan>` tail content, or null when no plan exists. */
417
+ readonly loadPlan: () => Promise<string | null>;
418
+ /** Re-render after a Plan/Goal mutation (the `plan.dirty` flag). */
419
+ readonly onPlanDirty?: () => Promise<string | null>;
420
+ /** `context_evicted` externalization + reinjection. Default: true. */
421
+ readonly ledger?: boolean;
422
+ /** Deterministic teardown handoff write. */
423
+ readonly onHandoff?: (input: HandoffInput) => Promise<void>;
424
+ };
290
425
  /**
291
426
  * Item #56 — absolute paths to per-user preference files injected at run
292
427
  * start via the project-memory auto-load path (alongside LESSONS.md, which
@@ -578,11 +713,26 @@ export type RunChatLoopOptions = {
578
713
  }>;
579
714
  /**
580
715
  * Section 27 — when set, the system block array goes through
581
- * `prompt-cache-manager.manage()` once at run start; if a fresh marker is
582
- * injected the new `lastRotatedAt` is exposed via the returned bus event.
583
- * Pass `0` (or omit) to force a refresh on the first turn.
716
+ * `prompt-cache-manager.manage()` once at run start; a valid recent
717
+ * timestamp makes `manage()` skip, so the run REUSES the existing cached
718
+ * prefix instead of force-rotating (and cold-starting the cache) at every
719
+ * boot. Pass `0` (or omit) to force a refresh on the first turn.
720
+ *
721
+ * v0.3.0 Goal 1 (§2.5) — the cross-run bookkeeping is live now: a
722
+ * rotation publishes a `cache_rotation` trace event and invokes
723
+ * `onPromptCacheRotated` with the fresh timestamp so the caller can
724
+ * persist it and thread it back here on the next run (store wiring lands
725
+ * with memory-service/threading, PR 10/11).
584
726
  */
585
727
  promptCacheLastRotatedAt?: number;
728
+ /**
729
+ * v0.3.0 Goal 1 (§2.5) — invoked once at boot IF `manage()` injected a
730
+ * fresh cache marker, with the `rotatedAt` timestamp to persist. The
731
+ * caller threads the persisted value back as `promptCacheLastRotatedAt`
732
+ * on the next run, which stops the boot-time force-rotation. Best-effort:
733
+ * a persist failure is logged and never aborts the run.
734
+ */
735
+ onPromptCacheRotated?: (rotatedAt: number) => void | Promise<void>;
586
736
  /**
587
737
  * Item 27 — run-level spend cap with a degradation ladder. Generalizes
588
738
  * the optimizer's `BudgetMeter` to normal runs (`crewhaus run
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { autoCompact } from "@crewhaus/compaction-autocompact";
8
8
  import { snip } from "@crewhaus/compaction-snip";
9
9
  import { DEFAULT_PRICING, computeCostMicros, createCostTracker, resolvePricing, } from "@crewhaus/cost-tracker";
10
10
  import { classifyEgress, summarizeEgress, } from "@crewhaus/egress-classifier";
11
- import { ConfigError, RuntimeError } from "@crewhaus/errors";
11
+ import { ConfigError, EXIT_CODES, RunFailedError, RuntimeError, isRunFailedError, } from "@crewhaus/errors";
12
12
  import { openEventLog } from "@crewhaus/event-log";
13
13
  import { aggregateDecisions, runHooks } from "@crewhaus/hooks-engine";
14
14
  import { createFailoverChain, createPolicyRouter, createTierRouter, parseModelString, resolveModel, } from "@crewhaus/model-router";
@@ -118,6 +118,214 @@ const DEFAULT_MAX_CONCURRENT_TOOLS = 4;
118
118
  const DEFAULT_COMPACTION_THRESHOLD = 0.85;
119
119
  const DEFAULT_SNIP_KEEP_HEAD = 4;
120
120
  const DEFAULT_SNIP_KEEP_TAIL = 20;
121
+ // Convert a registered tool to the Anthropic `input_schema` shape. Anthropic
122
+ // requires a JSON-Schema OBJECT at the top level: it rejects a `type`-less
123
+ // schema (`input_schema.type: Field required`) AND a top-level `anyOf`/`oneOf`/
124
+ // `allOf` (`input_schema does not support oneOf, allOf, or anyOf at the top
125
+ // level`). zod-to-json-schema renders a union / discriminatedUnion as exactly
126
+ // that top-level `anyOf` — e.g. tool-plan's `PlanUpdate` (an action-discriminated
127
+ // union) and tool-evm — so we FLATTEN a top-level union of object branches into
128
+ // one object schema (see `flattenUnionToObject`). A schema that is already a
129
+ // clean object passes through by reference untouched.
130
+ function toAnthropicInputSchema(t) {
131
+ const converted = (t.jsonSchema ??
132
+ zodToJsonSchema(t.inputSchema, { $refStrategy: "none" }));
133
+ const union = converted.anyOf ?? converted.oneOf ?? converted.allOf;
134
+ // Already a clean top-level object schema (incl. an empty `z.object({})`).
135
+ if (converted.type === "object" && union === undefined) {
136
+ return converted;
137
+ }
138
+ if (Array.isArray(union)) {
139
+ return flattenUnionToObject(union, converted.properties);
140
+ }
141
+ // Degenerate (no object type, no union): coerce to an empty object schema.
142
+ return { type: "object", properties: converted.properties ?? {} };
143
+ }
144
+ // Merge a top-level union of object branches into a single object schema.
145
+ // Anthropic forbids a top-level `anyOf`, but a nested `anyOf` on an individual
146
+ // property is fine — so each property becomes the union of its per-branch
147
+ // shapes, and `required` is the intersection across branches (in practice the
148
+ // shared discriminator). The tool's own zod schema still validates the real
149
+ // input at execute time, so the looser model-facing schema loses no safety.
150
+ function flattenUnionToObject(branches, baseProps) {
151
+ const perKey = new Map();
152
+ const requiredSets = [];
153
+ for (const b of branches) {
154
+ for (const [k, v] of Object.entries(b.properties ?? {})) {
155
+ const seen = perKey.get(k) ?? [];
156
+ if (!seen.some((e) => JSON.stringify(e) === JSON.stringify(v)))
157
+ seen.push(v);
158
+ perKey.set(k, seen);
159
+ }
160
+ requiredSets.push(Array.isArray(b.required) ? b.required : []);
161
+ }
162
+ const properties = { ...(baseProps ?? {}) };
163
+ for (const [k, variants] of perKey) {
164
+ properties[k] = variants.length === 1 ? variants[0] : { anyOf: variants };
165
+ }
166
+ const required = requiredSets.length > 0
167
+ ? requiredSets.reduce((acc, r) => acc.filter((x) => r.includes(x)))
168
+ : [];
169
+ return {
170
+ type: "object",
171
+ properties,
172
+ ...(required.length > 0 ? { required } : {}),
173
+ };
174
+ }
175
+ // ---------------------------------------------------------------------------
176
+ // v0.3.0 Goal 1 — the continuity seam (§2.3 requirements ledger, §2.5 mutable
177
+ // tail region). All injected closures: runtime-core stays store-free; the
178
+ // composition root (memory-service, PR 10) constructs them over the
179
+ // continuity store and target emitters thread them (PR 11).
180
+ // ---------------------------------------------------------------------------
181
+ /**
182
+ * Hard cap (chars) on the RENDERED mutable tail — the `<current_plan>` +
183
+ * `<requirements_ledger>` blocks appended after the cache-marked frozen
184
+ * prefix on every model call. The spec's `continuity.focusMaxChars` lowers
185
+ * onto this in PR 11; until then the default applies. Enforced in
186
+ * `renderContinuityTail`: the ledger has priority (it is the
187
+ * motivating-failure fix), truncating oldest-first with a marker; the plan
188
+ * yields whatever budget remains.
189
+ */
190
+ export const DEFAULT_CONTINUITY_TAIL_MAX_CHARS = 4096;
191
+ /**
192
+ * Cap (chars, ~16KB) on the in-run requirements ledger's total entry text.
193
+ * Oldest entries are evicted first and the rendered block gains a
194
+ * `[ledger truncated]` marker — user messages are small, so hitting this
195
+ * means hundreds of evicted requirements.
196
+ */
197
+ export const CONTINUITY_LEDGER_MAX_CHARS = 16 * 1024;
198
+ /**
199
+ * Key in the per-run `runState` state-store that plan-mutating tools
200
+ * (PlanUpdate/FocusWrite, PR 7) set to `true` after a write. The loop
201
+ * re-reads it before each model call and re-renders the `<current_plan>`
202
+ * tail block via `continuity.onPlanDirty` when set — the state-store's
203
+ * first consumer.
204
+ */
205
+ export const PLAN_DIRTY_STATE_KEY = "plan.dirty";
206
+ /** compaction-snip's marker message — filtered out of eviction records (it
207
+ * is runtime scaffolding, not conversation content). */
208
+ const SNIP_MARKER_RE = /^\[Context compacted: \d+ messages removed\]$/;
209
+ /**
210
+ * §2.3 — decompose one message that compaction is about to drop into
211
+ * verbatim `context_evicted` records. Text-bearing content only: user/
212
+ * assistant text becomes one entry per message (blocks joined with `\n` so
213
+ * the record IS the message, not fragments), each `tool_result`'s text
214
+ * becomes a `"tool"` entry. `tool_use` inputs are skipped — they already
215
+ * persist verbatim as `tool_use` event-log lines. The snip marker is
216
+ * dropped. Exported for tests.
217
+ */
218
+ export function extractEvictedEntries(message) {
219
+ const textRole = message.role === "user" ? "user" : "assistant";
220
+ if (typeof message.content === "string") {
221
+ if (message.content.length === 0 || SNIP_MARKER_RE.test(message.content))
222
+ return [];
223
+ return [{ role: textRole, text: message.content }];
224
+ }
225
+ const entries = [];
226
+ const texts = [];
227
+ for (const block of message.content) {
228
+ const b = block;
229
+ if (b.type === "text" && typeof b.text === "string" && b.text.length > 0) {
230
+ texts.push(b.text);
231
+ }
232
+ else if (b.type === "tool_result") {
233
+ const c = b.content;
234
+ const text = typeof c === "string"
235
+ ? c
236
+ : Array.isArray(c)
237
+ ? c
238
+ .map((inner) => {
239
+ const i = inner;
240
+ return i.type === "text" && typeof i.text === "string" ? i.text : "";
241
+ })
242
+ .filter((t) => t.length > 0)
243
+ .join("\n")
244
+ : "";
245
+ if (text.length > 0)
246
+ entries.push({ role: "tool", text });
247
+ }
248
+ }
249
+ if (texts.length > 0) {
250
+ const joined = texts.join("\n");
251
+ if (!SNIP_MARKER_RE.test(joined))
252
+ entries.push({ role: textRole, text: joined });
253
+ }
254
+ return entries;
255
+ }
256
+ const LEDGER_TRUNCATED_MARKER = "[ledger truncated]";
257
+ const PLAN_TRUNCATED_MARKER = "[plan truncated to fit the tail cap]";
258
+ /**
259
+ * §2.5 — render the mutable tail region: the `<current_plan>` block and the
260
+ * `<requirements_ledger>` block, hard-capped at `maxChars` (default
261
+ * {@link DEFAULT_CONTINUITY_TAIL_MAX_CHARS}). Pure and deterministic;
262
+ * exported for tests.
263
+ *
264
+ * Cap enforcement, in priority order:
265
+ * 1. The ledger block drops its OLDEST entries first (they are the
266
+ * time-ordered content) until it fits, gaining the
267
+ * `[ledger truncated]` marker — the newest requirements always survive.
268
+ * 2. The plan gets whatever budget remains; an over-budget plan keeps its
269
+ * HEAD (focus/next-steps render first in plan documents) and gains a
270
+ * trailing truncation marker. A remainder too small for any plan
271
+ * content drops the plan block entirely — the ledger is the
272
+ * motivating-failure fix and always wins.
273
+ *
274
+ * Closing delimiters inside plan/ledger content are neutralized so
275
+ * embedded `</current_plan>` / `</requirements_ledger>` text cannot
276
+ * terminate its wrapper block early (same defense as `<recalled_memory>`).
277
+ */
278
+ export function renderContinuityTail(input) {
279
+ const maxChars = input.maxChars ?? DEFAULT_CONTINUITY_TAIL_MAX_CHARS;
280
+ const renderLedger = (entries, truncated) => {
281
+ const lines = entries.map((e) => {
282
+ const attribution = e.turnNumber !== undefined ? `(user, turn ${e.turnNumber})` : "(user)";
283
+ return `- ${attribution} ${escapeBoundaryDelimiter(e.text, "requirements_ledger")}`;
284
+ });
285
+ const body = [...(truncated ? [LEDGER_TRUNCATED_MARKER] : []), ...lines].join("\n");
286
+ return `<requirements_ledger>\nUser requirements preserved verbatim before context compaction — they remain binding even though the original messages were evicted:\n${body}\n</requirements_ledger>`;
287
+ };
288
+ // 1. Ledger block, oldest-first eviction until it fits the cap alone.
289
+ let ledgerBlock;
290
+ if (input.ledger.length > 0) {
291
+ let entries = [...input.ledger];
292
+ let truncated = input.ledgerTruncated === true;
293
+ ledgerBlock = renderLedger(entries, truncated);
294
+ while (ledgerBlock.length > maxChars && entries.length > 1) {
295
+ entries = entries.slice(1);
296
+ truncated = true;
297
+ ledgerBlock = renderLedger(entries, truncated);
298
+ }
299
+ if (ledgerBlock.length > maxChars) {
300
+ // A single entry alone exceeds the cap — keep its NEWEST chars.
301
+ const last = entries[0];
302
+ const clipped = last.text.slice(Math.max(0, last.text.length - maxChars));
303
+ ledgerBlock = renderLedger([{ ...last, text: clipped }], true).slice(0, maxChars);
304
+ }
305
+ }
306
+ // 2. Plan block within the remaining budget.
307
+ let planBlock;
308
+ const planText = input.plan;
309
+ if (planText !== null && planText.trim().length > 0) {
310
+ const remaining = maxChars - (ledgerBlock !== undefined ? ledgerBlock.length : 0);
311
+ const escaped = escapeBoundaryDelimiter(planText, "current_plan");
312
+ const wrap = (body) => `<current_plan>\n${body}\n</current_plan>`;
313
+ const overhead = wrap("").length + PLAN_TRUNCATED_MARKER.length + 1;
314
+ if (remaining > overhead) {
315
+ const full = wrap(escaped);
316
+ planBlock =
317
+ full.length <= remaining
318
+ ? full
319
+ : wrap(`${escaped.slice(0, remaining - overhead)}\n${PLAN_TRUNCATED_MARKER}`);
320
+ }
321
+ }
322
+ const blocks = [];
323
+ if (planBlock !== undefined)
324
+ blocks.push(planBlock);
325
+ if (ledgerBlock !== undefined)
326
+ blocks.push(ledgerBlock);
327
+ return blocks;
328
+ }
121
329
  /**
122
330
  * Run `items` through `fn` with at most `limit` in flight at once,
123
331
  * preserving input order in the returned results. A pool of `limit`
@@ -151,6 +359,7 @@ export { CLAUDE_CODE_HEADERS, CLAUDE_CODE_SYSTEM_PREFIX, OAUTH_BETAS, createAnth
151
359
  // own module (`./janitor`) but is re-exported here because emitted bundles
152
360
  // only import the package root.
153
361
  export { createJanitor } from "./janitor";
362
+ export { JANITOR_BUILTIN_STEPS } from "./janitor";
154
363
  // Ops item 31 — alert watchdog seams re-exported so the CLI/codegen can build
155
364
  // the durable + off-box alert sink (audit append + settings.json alert hook /
156
365
  // webhook) it passes as `RunChatLoopOptions.alertSink`.
@@ -645,6 +854,11 @@ export async function runChatLoop(opts) {
645
854
  };
646
855
  let sessionId;
647
856
  let resumedMessages;
857
+ // §2.3 — on resume, the requirements ledger rebuilds DETERMINISTICALLY
858
+ // from the `context_evicted` events already on disk (dedup against
859
+ // re-evictions happens at fold time): a resumed session recovers every
860
+ // externalized user requirement without trusting any summary.
861
+ const resumedLedgerSeed = [];
648
862
  if (opts.resume) {
649
863
  const existing = await sessionStore.get(opts.resume.sessionId);
650
864
  if (existing === null) {
@@ -653,6 +867,20 @@ export async function runChatLoop(opts) {
653
867
  sessionId = existing.id;
654
868
  const replayLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
655
869
  resumedMessages = await replayMessageHistory(replayLog);
870
+ if (opts.continuity !== undefined && opts.continuity.ledger !== false) {
871
+ for await (const ev of replayLog.read()) {
872
+ if (ev.kind !== "context_evicted")
873
+ continue;
874
+ const p = ev.payload;
875
+ if (p.role === "user" && typeof p.text === "string") {
876
+ resumedLedgerSeed.push({
877
+ role: "user",
878
+ text: p.text,
879
+ ...(typeof p.turnNumber === "number" ? { turnNumber: p.turnNumber } : {}),
880
+ });
881
+ }
882
+ }
883
+ }
656
884
  await replayLog.close();
657
885
  }
658
886
  else {
@@ -884,11 +1112,12 @@ export async function runChatLoop(opts) {
884
1112
  // score per-server MCP health offline. Shares the advisor's DEFAULT-ON gate
885
1113
  // (CREWHAUS_ADVISOR_EVENTS=0 disables both). See observability.ts.
886
1114
  const mcpStatsPersist = attachMcpStatsPersistence(bus, eventLog, runContext);
887
- // Per-run state container — coordination surface for hooks/skills/tools
888
- // landing in Section 11+. Section 10 only ships the plumbing; the
889
- // underscore prefix marks the intentional non-consumer.
890
- const _runState = createStore({});
891
- void _runState;
1115
+ // Per-run state container — coordination surface for hooks/skills/tools.
1116
+ // Shipped as plumbing in Section 10; v0.3.0 Goal 1 (§2.5) lands its first
1117
+ // consumer: plan-mutating tools set `PLAN_DIRTY_STATE_KEY` here (via the
1118
+ // RuntimeBridge's `runState`) and `buildContinuityTail` below re-reads it
1119
+ // before each model call to re-render the `<current_plan>` tail block.
1120
+ const runState = createStore({});
892
1121
  // Section 13 — RuntimeBridge. Built once per run, handed to every
893
1122
  // tool execution through the executor's ExecutionContext. Framework-
894
1123
  // aware tools (only `Task` today) cast `ctx.bridge` to RuntimeBridge.
@@ -940,6 +1169,139 @@ export async function runChatLoop(opts) {
940
1169
  runContext.logger.warn("memory auto-capture failed", { error: err.message });
941
1170
  }
942
1171
  };
1172
+ // -------------------------------------------------------------------------
1173
+ // v0.3.0 Goal 1 — continuity wiring (§2.3 ledger, §2.5 tail, §2.8 handoff).
1174
+ // Everything below is inert when `opts.continuity` is absent: no tail
1175
+ // blocks, no `context_evicted` events, no ledger anchor, no handoff —
1176
+ // byte-identical request payloads to a pre-0.3.0 runtime.
1177
+ // -------------------------------------------------------------------------
1178
+ const continuity = opts.continuity;
1179
+ const continuityLedgerEnabled = continuity !== undefined && continuity.ledger !== false;
1180
+ // The in-run requirements ledger: evicted USER messages, oldest-first,
1181
+ // verbatim. `ledgerTruncated` flags that oldest entries were dropped at
1182
+ // the CONTINUITY_LEDGER_MAX_CHARS cap so the rendered block says so.
1183
+ const ledgerEntries = [];
1184
+ let ledgerTruncated = false;
1185
+ // The last rendered plan snapshot (loadPlan at boot, onPlanDirty on a
1186
+ // `plan.dirty` refresh) — also the deterministic handoff's plan field.
1187
+ let lastPlanText = null;
1188
+ let handoffFired = false;
1189
+ /** Fold one evicted user message into the ledger. Dedupe (role, text) —
1190
+ * a resume seed followed by a live re-eviction of the same replayed
1191
+ * message must not double an entry — then evict oldest-first past the
1192
+ * cap. A single over-cap entry is clipped to its newest chars. */
1193
+ const foldLedgerEntry = (entry) => {
1194
+ if (ledgerEntries.some((e) => e.role === entry.role && e.text === entry.text))
1195
+ return;
1196
+ ledgerEntries.push(entry);
1197
+ let total = ledgerEntries.reduce((n, e) => n + e.text.length, 0);
1198
+ while (total > CONTINUITY_LEDGER_MAX_CHARS && ledgerEntries.length > 1) {
1199
+ const dropped = ledgerEntries.shift();
1200
+ total -= dropped.text.length;
1201
+ ledgerTruncated = true;
1202
+ }
1203
+ const sole = ledgerEntries[0];
1204
+ if (total > CONTINUITY_LEDGER_MAX_CHARS && ledgerEntries.length === 1 && sole !== undefined) {
1205
+ ledgerEntries[0] = {
1206
+ ...sole,
1207
+ text: sole.text.slice(sole.text.length - CONTINUITY_LEDGER_MAX_CHARS),
1208
+ };
1209
+ ledgerTruncated = true;
1210
+ }
1211
+ };
1212
+ for (const seeded of resumedLedgerSeed)
1213
+ foldLedgerEntry(seeded);
1214
+ /**
1215
+ * §2.3 — the eviction chokepoint, called by the compaction ladder with
1216
+ * the messages a step is ABOUT to drop, before the drop commits. Every
1217
+ * text-bearing record is appended verbatim to the session event log as
1218
+ * `context_evicted` (zero model trust — the recall integration comes in a
1219
+ * later PR); user records additionally fold into the in-run ledger for
1220
+ * per-call reinjection.
1221
+ */
1222
+ const externalizeEvicted = async (evicted) => {
1223
+ if (!continuityLedgerEnabled)
1224
+ return;
1225
+ for (const message of evicted) {
1226
+ for (const entry of extractEvictedEntries(message)) {
1227
+ await logEvent("context_evicted", {
1228
+ role: entry.role,
1229
+ text: entry.text,
1230
+ ...(entry.turnNumber !== undefined ? { turnNumber: entry.turnNumber } : {}),
1231
+ });
1232
+ if (entry.role === "user")
1233
+ foldLedgerEntry(entry);
1234
+ }
1235
+ }
1236
+ };
1237
+ /** §2.3 — the ledger text handed to the autocompact summarizer as an
1238
+ * anchor. Evaluated lazily AFTER the current step's evictions folded, so
1239
+ * the requirements at risk in THIS compaction anchor THIS summary. */
1240
+ const ledgerAnchorText = () => {
1241
+ if (!continuityLedgerEnabled || ledgerEntries.length === 0)
1242
+ return undefined;
1243
+ return ledgerEntries.map((e) => `- ${e.text}`).join("\n");
1244
+ };
1245
+ /**
1246
+ * §2.5 — build the volatile tail for one model call. Re-reads the
1247
+ * `plan.dirty` flag from the per-run state-store (set by plan-mutating
1248
+ * tools through the RuntimeBridge) and re-renders the plan via
1249
+ * `onPlanDirty` (falling back to `loadPlan`) when set. The returned
1250
+ * blocks carry NO cache_control — they sit AFTER the cache-marked frozen
1251
+ * prefix, so per-call edits re-tokenize only the tail (the
1252
+ * prompt-cache-manager `volatile` contract).
1253
+ */
1254
+ const buildContinuityTail = async () => {
1255
+ if (continuity === undefined)
1256
+ return [];
1257
+ if (runState.get()[PLAN_DIRTY_STATE_KEY] === true) {
1258
+ try {
1259
+ lastPlanText = await (continuity.onPlanDirty ?? continuity.loadPlan)();
1260
+ }
1261
+ catch (err) {
1262
+ runContext.logger.warn("continuity plan refresh failed", {
1263
+ error: err.message,
1264
+ });
1265
+ }
1266
+ runState.set({ [PLAN_DIRTY_STATE_KEY]: false });
1267
+ }
1268
+ return renderContinuityTail({
1269
+ plan: lastPlanText,
1270
+ ledger: ledgerEntries,
1271
+ ledgerTruncated,
1272
+ }).map((text) => ({ type: "text", text }));
1273
+ };
1274
+ /** §2.8 — the deterministic teardown handoff: fired exactly once, in the
1275
+ * same finally slot as `memory.onCapture`, with no model calls.
1276
+ * Best-effort — a handoff failure never turns a clean exit into an
1277
+ * error. */
1278
+ const maybeHandoff = async (stopReason) => {
1279
+ if (continuity?.onHandoff === undefined || handoffFired)
1280
+ return;
1281
+ handoffFired = true;
1282
+ try {
1283
+ await continuity.onHandoff({
1284
+ plan: lastPlanText,
1285
+ ledger: [...ledgerEntries],
1286
+ sessionId,
1287
+ stopReason,
1288
+ });
1289
+ }
1290
+ catch (err) {
1291
+ runContext.logger.warn("continuity handoff failed", { error: err.message });
1292
+ }
1293
+ };
1294
+ // Boot-time plan snapshot. Best-effort: a store failure degrades to no
1295
+ // plan block rather than aborting the run (memory-backend failures
1296
+ // degrade; provider failures halt).
1297
+ if (continuity !== undefined) {
1298
+ try {
1299
+ lastPlanText = await continuity.loadPlan();
1300
+ }
1301
+ catch (err) {
1302
+ runContext.logger.warn("continuity loadPlan failed", { error: err.message });
1303
+ }
1304
+ }
943
1305
  // Section 11 — `session-start` fires once after the persistence + run
944
1306
  // context boot is complete. Observational only (no deny/block effect).
945
1307
  await fireHook("session-start", {
@@ -971,6 +1333,25 @@ export async function runChatLoop(opts) {
971
1333
  const skillsBlock = skillsText.length > 0
972
1334
  ? [{ type: "text", text: skillsText, cache_control: { type: "ephemeral" } }]
973
1335
  : [];
1336
+ // v0.3.0 §7.1 — child-seam projections for the RuntimeBridge, computed once
1337
+ // per run. The spawner threads these into child loops via the Task tool:
1338
+ // - memory: RECALL-ONLY. `autoCapture`/`onCapture` are dropped at the
1339
+ // projection so no write closure can reach a child (parents own memory
1340
+ // writes; child findings arrive through the capture pass walking the
1341
+ // sub_agent_start/end brackets). Projected only when a recall closure
1342
+ // exists — a capture-only seam gives children nothing.
1343
+ // - continuity: READ-ONLY. Only `loadPlan` crosses; `onPlanDirty` /
1344
+ // `onHandoff` / the ledger stay parent-side so a child cannot mutate
1345
+ // the parent's plan-store state through the seam.
1346
+ const bridgeMemorySeam = opts.memory?.recall !== undefined
1347
+ ? {
1348
+ ...(opts.memory.autoRecall !== undefined ? { autoRecall: opts.memory.autoRecall } : {}),
1349
+ ...(opts.memory.recallK !== undefined ? { recallK: opts.memory.recallK } : {}),
1350
+ ...(opts.memory.recallSeed !== undefined ? { recallSeed: opts.memory.recallSeed } : {}),
1351
+ recall: opts.memory.recall,
1352
+ }
1353
+ : undefined;
1354
+ const bridgeContinuitySeam = opts.continuity !== undefined ? { loadPlan: opts.continuity.loadPlan } : undefined;
974
1355
  // M3.1 — auto-load project memory files (AGENTS.md / CLAUDE.md /
975
1356
  // CODE-COMPANION.md / AGENT.md) from cwd at session start. Follows the
976
1357
  // vendor-neutral agents.md convention; compatible with Claude Code's
@@ -1044,7 +1425,9 @@ export async function runChatLoop(opts) {
1044
1425
  // last refresh is older than the rotation interval. Skips automatically
1045
1426
  // when the adapter doesn't support explicit caching (OpenAI / Bedrock
1046
1427
  // Llama / Mistral). This keeps long-running CHN/MGD/RES daemons under
1047
- // Anthropic's 30-day TTL.
1428
+ // Anthropic's 30-day TTL. A caller-supplied `promptCacheLastRotatedAt`
1429
+ // that is still fresh makes `manage()` skip — the run reuses the cached
1430
+ // prefix instead of force-rotating at every boot (§2.5 bookkeeping fix).
1048
1431
  if (adapter.features.caching === "explicit") {
1049
1432
  const cacheManaged = manageCacheMarkers(systemBlocks.map((b) => ({
1050
1433
  type: "text",
@@ -1062,6 +1445,25 @@ export async function runChatLoop(opts) {
1062
1445
  text: b.text,
1063
1446
  ...(b.cache_control !== undefined ? { cache_control: b.cache_control } : {}),
1064
1447
  }));
1448
+ // v0.3.0 §2.5 — surface the rotation so the caller can persist
1449
+ // `rotatedAt` and thread it back next run. The trace event is the
1450
+ // observable half; `onPromptCacheRotated` is the persistence seam
1451
+ // (best-effort — a persist failure never aborts the run).
1452
+ bus.publish({
1453
+ ...bus.envelope(),
1454
+ kind: "cache_rotation",
1455
+ rotatedAt: cacheManaged.rotatedAt,
1456
+ });
1457
+ if (opts.onPromptCacheRotated !== undefined) {
1458
+ try {
1459
+ await opts.onPromptCacheRotated(cacheManaged.rotatedAt);
1460
+ }
1461
+ catch (err) {
1462
+ runContext.logger.warn("prompt-cache rotatedAt persist failed", {
1463
+ error: err.message,
1464
+ });
1465
+ }
1466
+ }
1065
1467
  }
1066
1468
  }
1067
1469
  const tools = opts.tools ?? [];
@@ -1069,10 +1471,7 @@ export async function runChatLoop(opts) {
1069
1471
  ? tools.map((t) => ({
1070
1472
  name: t.name,
1071
1473
  description: t.description,
1072
- input_schema: (t.jsonSchema ??
1073
- zodToJsonSchema(t.inputSchema, {
1074
- $refStrategy: "none",
1075
- })),
1474
+ input_schema: toAnthropicInputSchema(t),
1076
1475
  }))
1077
1476
  : undefined;
1078
1477
  const toolByName = new Map(tools.map((t) => [t.name, t]));
@@ -1451,9 +1850,21 @@ export async function runChatLoop(opts) {
1451
1850
  maxTokens,
1452
1851
  ...(sessionRootDir !== undefined ? { sessionRootDir } : {}),
1453
1852
  hooks,
1853
+ // v0.3.0 §2.5 — the per-run state-store, so plan-mutating tools can
1854
+ // set PLAN_DIRTY_STATE_KEY and the loop re-renders the plan tail
1855
+ // before the next model call.
1856
+ runState,
1454
1857
  ...(opts.subAgents !== undefined ? { subAgents: opts.subAgents } : {}),
1455
1858
  ...(opts.spawnSubAgent !== undefined ? { spawnSubAgent: opts.spawnSubAgent } : {}),
1456
1859
  ...(opts.crewMailbox !== undefined ? { crewMailbox: opts.crewMailbox } : {}),
1860
+ // v0.3.0 §7.1 — the four child seams (projected above: recall-only
1861
+ // memory, skills list, failure taxonomy, read-only continuity) so the
1862
+ // Task tool can hand them to the spawner. All conditional: a run
1863
+ // without them builds the exact pre-0.3.0 bridge shape.
1864
+ ...(bridgeMemorySeam !== undefined ? { memory: bridgeMemorySeam } : {}),
1865
+ ...(skills.length > 0 ? { skills } : {}),
1866
+ ...(opts.failureTaxonomy !== undefined ? { failureTaxonomy: opts.failureTaxonomy } : {}),
1867
+ ...(bridgeContinuitySeam !== undefined ? { continuity: bridgeContinuitySeam } : {}),
1457
1868
  };
1458
1869
  // Spin "running <tool>…" for exactly the execution window — started after
1459
1870
  // every gate (permission/justification/egress) so it never overlaps the
@@ -1728,6 +2139,29 @@ export async function runChatLoop(opts) {
1728
2139
  // strongest candidate for the rest of the run (misroute recovery, mirroring
1729
2140
  // the tier router's fast→default escalation latch).
1730
2141
  let escalatePool = false;
2142
+ // v0.3.0 Goal 6 — one structured report on every terminal path,
2143
+ // published to the bus AND appended to the session event log BEFORE the
2144
+ // throw (a throw is invisible to structured consumers; the event is what
2145
+ // the UI host, printers, exporters, and incident capture render). Used
2146
+ // by the recovery `halt`/`fail` arms below and by the §7.1 sub-agent
2147
+ // escalation path in `NeedTools`.
2148
+ const publishRunFailed = async (report) => {
2149
+ const failureMessage = `${report.title}: ${report.detail}`;
2150
+ bus.publish({
2151
+ ...bus.envelope(),
2152
+ kind: "run_failed",
2153
+ class: report.class,
2154
+ message: failureMessage,
2155
+ ...(report.remediation !== undefined ? { remediation: report.remediation } : {}),
2156
+ exitCode: report.exitCode,
2157
+ });
2158
+ await logEvent("run_failed", {
2159
+ class: report.class,
2160
+ message: failureMessage,
2161
+ ...(report.remediation !== undefined ? { remediation: report.remediation } : {}),
2162
+ exitCode: report.exitCode,
2163
+ });
2164
+ };
1731
2165
  while (state.kind !== "Done") {
1732
2166
  if (turnAbort.signal.aborted) {
1733
2167
  state = transition(state, { kind: "Aborted" });
@@ -1920,13 +2354,22 @@ export async function runChatLoop(opts) {
1920
2354
  // Item 22 — the failover chain rewrites `model` per serving
1921
2355
  // candidate internally; the planned id here is the single-adapter
1922
2356
  // value and the chain's best-effort prediction otherwise.
2357
+ // v0.3.0 §2.5 — the volatile continuity tail is rebuilt for
2358
+ // EVERY model call and appended AFTER the frozen cache-marked
2359
+ // prefix, so a plan/ledger edit re-tokenizes only the tail.
2360
+ // `[]` when the seam is absent — the request payload is then
2361
+ // byte-identical to a pre-0.3.0 runtime.
2362
+ const continuityTail = await buildContinuityTail();
1923
2363
  const reqStream = turnAdapter.stream({
1924
2364
  model: reqWireModelId,
1925
- system: systemBlocks.map((b) => ({
1926
- type: "text",
1927
- text: b.text,
1928
- ...(b.cache_control !== undefined ? { cache_control: b.cache_control } : {}),
1929
- })),
2365
+ system: [
2366
+ ...systemBlocks.map((b) => ({
2367
+ type: "text",
2368
+ text: b.text,
2369
+ ...(b.cache_control !== undefined ? { cache_control: b.cache_control } : {}),
2370
+ })),
2371
+ ...continuityTail.map((b) => ({ type: "text", text: b.text })),
2372
+ ],
1930
2373
  messages: messages,
1931
2374
  tools: anthropicTools !== undefined
1932
2375
  ? anthropicTools.map((t) => ({
@@ -2228,7 +2671,25 @@ export async function runChatLoop(opts) {
2228
2671
  // Item 26 — accrue this turn's tool_use count (a next-turn tier
2229
2672
  // signal): a dense tool turn marks an active multi-step task.
2230
2673
  thisTurnToolUseCount += state.toolUses.length;
2231
- const toolResults = await runToolBatch(state.toolUses);
2674
+ let toolResults;
2675
+ try {
2676
+ toolResults = await runToolBatch(state.toolUses);
2677
+ }
2678
+ catch (err) {
2679
+ // v0.3.0 §7.1 — a RunFailedError escaping the tool batch is a
2680
+ // sub-agent's terminal report escalated through the spawner
2681
+ // (tool-executor deliberately lets it pass). Publish the same
2682
+ // structured run_failed surface as the recovery halt path, then
2683
+ // rethrow: both the singleTurn and REPL paths propagate non-abort
2684
+ // errors to the caller's catch-wrapper, which renders the
2685
+ // child's report and exits with its coded status. (The streaming
2686
+ // path reaches the identical halt through recovery — the
2687
+ // streaming executor rethrows after its drain and `recover()`
2688
+ // passes an already-classified report through verbatim.)
2689
+ if (isRunFailedError(err))
2690
+ await publishRunFailed(err.report);
2691
+ throw err;
2692
+ }
2232
2693
  messages.push({ role: "user", content: toolResults });
2233
2694
  await logEvent("user_message", { content: toolResults });
2234
2695
  const warning = maybeBuildLoopWarning();
@@ -2261,10 +2722,19 @@ export async function runChatLoop(opts) {
2261
2722
  bus.publish({
2262
2723
  ...bus.envelope(),
2263
2724
  kind: "error_recovered",
2725
+ // v0.3.0 Goal 6 — `halt` is published first-class now that the
2726
+ // action union carries it (PR 1 mapped it to "fail" as a
2727
+ // stopgap). alert-watchdog and the SLO monitor count BOTH
2728
+ // `fail` and `halt` as unrecovered, so terminal-failure
2729
+ // accounting is unchanged.
2264
2730
  action: action.kind,
2265
2731
  errorName: state.error.name,
2266
2732
  depth: recovery.retryCount + recovery.compactCount + recovery.continueCount,
2267
2733
  });
2734
+ // Non-terminal actions publish no run_failed report here — only
2735
+ // the terminal `fail`/`halt` arms below call `publishRunFailed`
2736
+ // (hoisted to runOneTurn scope; also used by the §7.1 sub-agent
2737
+ // escalation path in `NeedTools`).
2268
2738
  switch (action.kind) {
2269
2739
  case "compact": {
2270
2740
  const before = messages.length;
@@ -2278,13 +2748,21 @@ export async function runChatLoop(opts) {
2278
2748
  snipKeepHead,
2279
2749
  snipKeepTail,
2280
2750
  logger: runContext.logger,
2751
+ onEvict: externalizeEvicted,
2752
+ getLedgerText: ledgerAnchorText,
2281
2753
  }).finally(() => out.spinner.stop());
2754
+ // §2.3 — persist the summary text alongside the counts (the
2755
+ // reactive path always ends in autocompact's [marker, summary]).
2756
+ const reactiveSummary = compacted.length === 2 && typeof compacted[1]?.content === "string"
2757
+ ? compacted[1].content
2758
+ : undefined;
2282
2759
  messages.length = 0;
2283
2760
  messages.push(...compacted);
2284
2761
  await logEvent("compaction", {
2285
2762
  kind: "reactive",
2286
2763
  before,
2287
2764
  after: messages.length,
2765
+ ...(reactiveSummary !== undefined ? { summary: reactiveSummary } : {}),
2288
2766
  });
2289
2767
  bus.publish({
2290
2768
  ...bus.envelope(),
@@ -2376,8 +2854,31 @@ export async function runChatLoop(opts) {
2376
2854
  state = transition(state, { kind: "RecoveryDone" });
2377
2855
  break;
2378
2856
  }
2379
- case "fail":
2857
+ case "fail": {
2858
+ // Generic terminal fail — synthesize a best-effort report
2859
+ // (class "unknown", exit 1) so even the unclassified path
2860
+ // leaves a structured `run_failed` behind, then throw the
2861
+ // byte-identical pre-0.3.0 RuntimeError (die()'s one-liner
2862
+ // for non-RunFailedError CrewhausErrors is unchanged).
2863
+ await publishRunFailed({
2864
+ class: "unknown",
2865
+ title: "recovery failed",
2866
+ detail: action.reason,
2867
+ exitCode: EXIT_CODES.generic,
2868
+ });
2380
2869
  throw new RuntimeError(`recovery failed: ${action.reason}`);
2870
+ }
2871
+ case "halt":
2872
+ // v0.3.0 Goal 6 — classified terminal stop (billing / auth /
2873
+ // rate-limit exhaustion / hinted taxonomy entries). The report
2874
+ // carries title, raw provider text, remediation, and the coded
2875
+ // exit status; RunFailedError extends RuntimeError so existing
2876
+ // CrewhausError catch sites (e.g. `crewhaus run`'s die())
2877
+ // still work. Every terminal surface renders the SAME report:
2878
+ // die() and the bundle catch-wrappers print formatRunFailure()
2879
+ // and exit with report.exitCode.
2880
+ await publishRunFailed(action.report);
2881
+ throw new RunFailedError(action.report, lastErrorForRecovery);
2381
2882
  }
2382
2883
  break;
2383
2884
  }
@@ -2435,6 +2936,8 @@ export async function runChatLoop(opts) {
2435
2936
  snipKeepHead,
2436
2937
  snipKeepTail,
2437
2938
  logger: runContext.logger,
2939
+ onEvict: externalizeEvicted,
2940
+ getLedgerText: ledgerAnchorText,
2438
2941
  }, async (info) => {
2439
2942
  await logEvent("compaction", info);
2440
2943
  bus.publish({
@@ -2473,6 +2976,8 @@ export async function runChatLoop(opts) {
2473
2976
  reason: "complete",
2474
2977
  });
2475
2978
  await maybeAutoCapture();
2979
+ // §2.8 — deterministic handoff, same teardown slot as onCapture.
2980
+ await maybeHandoff("complete");
2476
2981
  await subscribers.flushAll();
2477
2982
  await subscribers.shutdownAll();
2478
2983
  costPersistUnsubscribe?.();
@@ -2652,6 +3157,8 @@ export async function runChatLoop(opts) {
2652
3157
  snipKeepHead,
2653
3158
  snipKeepTail,
2654
3159
  logger: runContext.logger,
3160
+ onEvict: externalizeEvicted,
3161
+ getLedgerText: ledgerAnchorText,
2655
3162
  }, async (info) => {
2656
3163
  await logEvent("compaction", info);
2657
3164
  bus.publish({
@@ -2698,6 +3205,8 @@ export async function runChatLoop(opts) {
2698
3205
  reason: runAbort.signal.aborted ? "abort" : "exit",
2699
3206
  });
2700
3207
  await maybeAutoCapture();
3208
+ // §2.8 — deterministic handoff, same teardown slot as onCapture.
3209
+ await maybeHandoff(runAbort.signal.aborted ? "abort" : "exit");
2701
3210
  await subscribers.flushAll();
2702
3211
  await subscribers.shutdownAll();
2703
3212
  costPersistUnsubscribe?.();
@@ -2741,6 +3250,18 @@ function isAbortError(err) {
2741
3250
  const name = err.name;
2742
3251
  return typeof name === "string" && (name === "AbortError" || name === "APIUserAbortError");
2743
3252
  }
3253
+ /** The messages `snip` dropped: input entries absent (by reference — snip
3254
+ * copies references) from the output. The inserted marker is a fresh
3255
+ * object, so it never shows up as "kept". */
3256
+ function snippedAway(before, after) {
3257
+ const kept = new Set(after);
3258
+ return before.filter((m) => !kept.has(m));
3259
+ }
3260
+ /** Extract the summary text out of autoCompact's `[marker, summary]` tuple. */
3261
+ function summaryTextOf(tuple) {
3262
+ const summary = tuple[1];
3263
+ return summary !== undefined && typeof summary.content === "string" ? summary.content : undefined;
3264
+ }
2744
3265
  /**
2745
3266
  * Pre-turn compaction ladder: estimate → snip → re-estimate → autocompact.
2746
3267
  * Returns the (possibly replaced) messages array. Pure with respect to
@@ -2749,13 +3270,19 @@ function isAbortError(err) {
2749
3270
  * event to the session log without duplicating the cost-estimation logic.
2750
3271
  */
2751
3272
  async function maybeCompact(args, onCompaction) {
2752
- const { messages, adapter, model, contextLimit, compactionThreshold, snipKeepHead, snipKeepTail, logger, } = args;
3273
+ const { messages, adapter, model, contextLimit, compactionThreshold, snipKeepHead, snipKeepTail, logger, onEvict, getLedgerText, } = args;
2753
3274
  const initialBudget = new TokenBudget(contextLimit);
2754
3275
  initialBudget.add(estimateTokens(messages), 0);
2755
3276
  if (!initialBudget.isApproachingLimit(compactionThreshold)) {
2756
3277
  return messages;
2757
3278
  }
2758
3279
  const snipped = snip(messages, snipKeepHead, snipKeepTail);
3280
+ // §2.3 — externalize what snip is about to drop BEFORE the drop commits.
3281
+ if (onEvict !== undefined) {
3282
+ const evicted = snippedAway(messages, snipped);
3283
+ if (evicted.length > 0)
3284
+ await onEvict(evicted);
3285
+ }
2759
3286
  logger.info("snip applied", { before: messages.length, after: snipped.length });
2760
3287
  if (onCompaction !== undefined) {
2761
3288
  await onCompaction({ kind: "snip", before: messages.length, after: snipped.length });
@@ -2766,9 +3293,22 @@ async function maybeCompact(args, onCompaction) {
2766
3293
  return snipped;
2767
3294
  }
2768
3295
  logger.info("autocompact triggered", { tokensAfterSnip: postSnipBudget.used });
2769
- const after = await autoCompact(snipped, adapter, model);
3296
+ // §2.3 — autocompact replaces the ENTIRE history; externalize all of it
3297
+ // before the summarizer model call so the records survive even a
3298
+ // summarizer failure. The ledger anchor is read afterwards so this
3299
+ // step's evictions are part of it.
3300
+ if (onEvict !== undefined && snipped.length > 0)
3301
+ await onEvict(snipped);
3302
+ const ledgerText = getLedgerText?.();
3303
+ const after = await autoCompact(snipped, adapter, model, ledgerText !== undefined ? { ledgerText } : {});
2770
3304
  if (onCompaction !== undefined) {
2771
- await onCompaction({ kind: "autocompact", before: snipped.length, after: after.length });
3305
+ const summary = summaryTextOf(after);
3306
+ await onCompaction({
3307
+ kind: "autocompact",
3308
+ before: snipped.length,
3309
+ after: after.length,
3310
+ ...(summary !== undefined ? { summary } : {}),
3311
+ });
2772
3312
  }
2773
3313
  return after;
2774
3314
  }
@@ -2779,8 +3319,19 @@ async function maybeCompact(args, onCompaction) {
2779
3319
  * largest blob).
2780
3320
  */
2781
3321
  async function forceCompact(args) {
2782
- const { messages, adapter, model, snipKeepHead, snipKeepTail, logger } = args;
3322
+ const { messages, adapter, model, snipKeepHead, snipKeepTail, logger, onEvict, getLedgerText } = args;
2783
3323
  const snipped = snip(messages, snipKeepHead, snipKeepTail);
3324
+ // §2.3 — same externalize-before-drop contract as the pre-turn ladder:
3325
+ // the snip diff first, then the full remaining history autocompact is
3326
+ // about to replace (disjoint sets, so no record is written twice).
3327
+ if (onEvict !== undefined) {
3328
+ const evicted = snippedAway(messages, snipped);
3329
+ if (evicted.length > 0)
3330
+ await onEvict(evicted);
3331
+ }
2784
3332
  logger.info("reactive snip applied", { before: messages.length, after: snipped.length });
2785
- return await autoCompact(snipped, adapter, model);
3333
+ if (onEvict !== undefined && snipped.length > 0)
3334
+ await onEvict(snipped);
3335
+ const ledgerText = getLedgerText?.();
3336
+ return await autoCompact(snipped, adapter, model, ledgerText !== undefined ? { ledgerText } : {});
2786
3337
  }
package/dist/janitor.d.ts CHANGED
@@ -7,16 +7,46 @@ import type { TraceEventBus } from "@crewhaus/trace-event-bus";
7
7
  export type JanitorReservationStore = {
8
8
  clearReservations(): Promise<void>;
9
9
  };
10
- export type JanitorStepName = "reservation_cleanup" | "session_ttl_eviction" | "orphan_tool_use_sweep";
10
+ /** The built-in steps every janitor runs. Registered steps (v0.3.0 PR 14 —
11
+ * `CreateJanitorOptions.steps`) carry their own names beyond this union. */
12
+ export declare const JANITOR_BUILTIN_STEPS: readonly ["reservation_cleanup", "session_ttl_eviction", "orphan_tool_use_sweep"];
13
+ export type JanitorBuiltinStepName = (typeof JANITOR_BUILTIN_STEPS)[number];
14
+ /** @deprecated the union closed over the built-ins only; kept as an alias for
15
+ * source compat. Step names are open since the v0.3.0 step registry. */
16
+ export type JanitorStepName = JanitorBuiltinStepName;
11
17
  export type JanitorStepStatus = "ok" | "skipped" | "error";
12
18
  export type JanitorStepResult = {
13
- readonly step: JanitorStepName;
19
+ /** Built-in step name or a registered step's own name. */
20
+ readonly step: string;
14
21
  readonly status: JanitorStepStatus;
15
22
  /** Step tally: sessions evicted / orphaned tool_use ids found. */
16
23
  readonly count?: number;
17
24
  /** Skip reason, error message, or sweep stats. */
18
25
  readonly detail?: string;
19
26
  };
27
+ /** What a registered step's `run()` reports — the janitor stamps the step
28
+ * name and publishes the `janitor_action` trace event around it. */
29
+ export type JanitorStepOutcome = {
30
+ readonly status: JanitorStepStatus;
31
+ readonly count?: number;
32
+ readonly detail?: string;
33
+ };
34
+ /**
35
+ * v0.3.0 PR 14 — a pluggable maintenance step. Registered steps run AFTER
36
+ * the built-ins on every `runOnce()` (boot run + interval ticks alike), each
37
+ * individually try/caught exactly like the built-ins, and each reported as a
38
+ * `janitor_action` trace event when a bus is wired. The overlap guard in
39
+ * `start()` covers them for free — a tick that is still consolidating is
40
+ * never re-entered. The memory release's dream step registers through this
41
+ * seam so daemon shapes get scheduled consolidation without runtime-core
42
+ * ever importing a store package.
43
+ */
44
+ export type JanitorStep = {
45
+ /** Step name in results + `janitor_action` events. Must not collide with
46
+ * a built-in name. */
47
+ readonly name: string;
48
+ run(): Promise<JanitorStepOutcome>;
49
+ };
20
50
  export type JanitorRunResult = {
21
51
  readonly startedAt: string;
22
52
  readonly durationMs: number;
@@ -72,6 +102,14 @@ export type CreateJanitorOptions = {
72
102
  * transiently looks orphaned) and are skipped. Default 5 minutes.
73
103
  */
74
104
  readonly orphanQuietPeriodMs?: number;
105
+ /**
106
+ * v0.3.0 PR 14 — registered steps, run after the built-ins on every
107
+ * `runOnce()`. Each is individually try/caught and reported exactly like
108
+ * a built-in (`janitor_action` trace event included). A registered name
109
+ * colliding with a built-in throws at construction — a shadowed built-in
110
+ * would make trace events ambiguous.
111
+ */
112
+ readonly steps?: ReadonlyArray<JanitorStep>;
75
113
  /** Optional trace bus — one `janitor_action` event per step per run. */
76
114
  readonly bus?: TraceEventBus;
77
115
  /** Test seam: clock. */
package/dist/janitor.js CHANGED
@@ -5,6 +5,13 @@ import { DEFAULT_ROOT_DIR, evictExpiredSessions } from "@crewhaus/session-store"
5
5
  const SESSION_LOG_REGEX = /^(sess_[0-9a-f]{16})\.jsonl$/;
6
6
  const DEFAULT_ORPHAN_SCAN_LIMIT = 20;
7
7
  const DEFAULT_ORPHAN_QUIET_PERIOD_MS = 5 * 60_000;
8
+ /** The built-in steps every janitor runs. Registered steps (v0.3.0 PR 14 —
9
+ * `CreateJanitorOptions.steps`) carry their own names beyond this union. */
10
+ export const JANITOR_BUILTIN_STEPS = [
11
+ "reservation_cleanup",
12
+ "session_ttl_eviction",
13
+ "orphan_tool_use_sweep",
14
+ ];
8
15
  /** Scan one session's `.jsonl` for assistant `tool_use` ids with no answering `tool_result`. */
9
16
  async function countOrphanToolUses(sessionId, rootDir) {
10
17
  const log = await openEventLog(sessionId, { rootDir });
@@ -51,6 +58,18 @@ async function countOrphanToolUses(sessionId, rootDir) {
51
58
  }
52
59
  export function createJanitor(opts = {}) {
53
60
  const now = opts.now ?? (() => new Date());
61
+ const registeredSteps = opts.steps ?? [];
62
+ const builtinNames = new Set(JANITOR_BUILTIN_STEPS);
63
+ const seenNames = new Set();
64
+ for (const step of registeredSteps) {
65
+ if (builtinNames.has(step.name)) {
66
+ throw new Error(`createJanitor: registered step "${step.name}" shadows a built-in step — pick a distinct name`);
67
+ }
68
+ if (seenNames.has(step.name)) {
69
+ throw new Error(`createJanitor: duplicate registered step name "${step.name}"`);
70
+ }
71
+ seenNames.add(step.name);
72
+ }
54
73
  // Same non-tenant fallback chain as `resolveSessionRootDir` (the janitor
55
74
  // runs at boot, outside any tenant scope; a cycle-free inline keeps this
56
75
  // module import-independent of index.ts). With a `tenantsRootDir` the
@@ -256,6 +275,16 @@ export function createJanitor(opts = {}) {
256
275
  await runStep("session_ttl_eviction", () => sessionTtlEviction(rootDirs)),
257
276
  await runStep("orphan_tool_use_sweep", () => orphanToolUseSweep(rootDirs)),
258
277
  ];
278
+ // v0.3.0 PR 14 — registered steps, after the built-ins: same per-step
279
+ // isolation, same trace-event reporting, and the start() overlap guard
280
+ // already covers a long-running registered step (a still-consolidating
281
+ // tick is never re-entered).
282
+ for (const registered of registeredSteps) {
283
+ steps.push(await runStep(registered.name, async () => ({
284
+ step: registered.name,
285
+ ...(await registered.run()),
286
+ })));
287
+ }
259
288
  return { startedAt, durationMs: performance.now() - t0, steps };
260
289
  }
261
290
  return {
@@ -59,8 +59,11 @@ export class SloWindow {
59
59
  this.ttftSeen.delete(ev.traceId);
60
60
  return;
61
61
  case "error_recovered":
62
- if (ev.action === "fail")
62
+ // "fail" (generic) and "halt" (v0.3.0 classified terminal stop) are
63
+ // both unrecovered — mirror alert-watchdog's accounting.
64
+ if (ev.action === "fail" || ev.action === "halt") {
63
65
  this.unrecoveredErrors.push({ ts: t, value: 1 });
66
+ }
64
67
  return;
65
68
  case "cost_accrual":
66
69
  // Skip the FR-003 terminal aggregate (summary:true) — it double-counts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/runtime-core",
3
- "version": "0.2.4",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "description": "Minimal runtime imported by generated harness bundles",
6
6
  "main": "dist/index.js",
@@ -16,48 +16,49 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@anthropic-ai/sdk": "^0.96.0",
19
- "@crewhaus/abort-controller": "0.2.4",
20
- "@crewhaus/adapter-anthropic": "0.2.4",
21
- "@crewhaus/agent-context-isolation": "0.2.4",
22
- "@crewhaus/boundary-classifier": "0.2.4",
23
- "@crewhaus/circuit-breaker": "0.2.4",
24
- "@crewhaus/compaction-autocompact": "0.2.4",
25
- "@crewhaus/compaction-snip": "0.2.4",
26
- "@crewhaus/cost-tracker": "0.2.4",
27
- "@crewhaus/egress-classifier": "0.2.4",
28
- "@crewhaus/errors": "0.2.4",
29
- "@crewhaus/event-log": "0.2.4",
30
- "@crewhaus/hooks-engine": "0.2.4",
31
- "@crewhaus/model-router": "0.2.4",
32
- "@crewhaus/permission-engine": "0.2.4",
33
- "@crewhaus/prompt-cache-manager": "0.2.4",
34
- "@crewhaus/prompt-injection-detector": "0.2.4",
35
- "@crewhaus/rate-limiter": "0.2.4",
36
- "@crewhaus/recovery-engine": "0.2.4",
37
- "@crewhaus/routing-store": "0.2.4",
38
- "@crewhaus/run-context": "0.2.4",
39
- "@crewhaus/session-store": "0.2.4",
40
- "@crewhaus/skills-registry": "0.2.4",
41
- "@crewhaus/slash-commands": "0.2.4",
42
- "@crewhaus/state-store": "0.2.4",
43
- "@crewhaus/tenancy": "0.2.4",
44
- "@crewhaus/token-budget": "0.2.4",
45
- "@crewhaus/tool-catalog": "0.2.4",
46
- "@crewhaus/tool-executor": "0.2.4",
47
- "@crewhaus/tool-loop-detection": "0.2.4",
48
- "@crewhaus/tool-orchestrator": "0.2.4",
49
- "@crewhaus/tool-result-store": "0.2.4",
50
- "@crewhaus/streaming-tool-executor": "0.2.4",
51
- "@crewhaus/turn-state-machine": "0.2.4",
52
- "@crewhaus/trace-event-bus": "0.2.4",
53
- "@crewhaus/structured-event-printer": "0.2.4",
54
- "@crewhaus/metrics-collector": "0.2.4",
55
- "@crewhaus/otel-exporter": "0.2.4",
19
+ "@crewhaus/abort-controller": "0.3.1",
20
+ "@crewhaus/adapter-anthropic": "0.3.1",
21
+ "@crewhaus/agent-context-isolation": "0.3.1",
22
+ "@crewhaus/boundary-classifier": "0.3.1",
23
+ "@crewhaus/circuit-breaker": "0.3.1",
24
+ "@crewhaus/compaction-autocompact": "0.3.1",
25
+ "@crewhaus/compaction-snip": "0.3.1",
26
+ "@crewhaus/cost-tracker": "0.3.1",
27
+ "@crewhaus/egress-classifier": "0.3.1",
28
+ "@crewhaus/errors": "0.3.1",
29
+ "@crewhaus/event-log": "0.3.1",
30
+ "@crewhaus/hooks-engine": "0.3.1",
31
+ "@crewhaus/model-router": "0.3.1",
32
+ "@crewhaus/permission-engine": "0.3.1",
33
+ "@crewhaus/prompt-cache-manager": "0.3.1",
34
+ "@crewhaus/prompt-injection-detector": "0.3.1",
35
+ "@crewhaus/rate-limiter": "0.3.1",
36
+ "@crewhaus/recovery-engine": "0.3.1",
37
+ "@crewhaus/routing-store": "0.3.1",
38
+ "@crewhaus/run-context": "0.3.1",
39
+ "@crewhaus/session-store": "0.3.1",
40
+ "@crewhaus/skills-registry": "0.3.1",
41
+ "@crewhaus/slash-commands": "0.3.1",
42
+ "@crewhaus/state-store": "0.3.1",
43
+ "@crewhaus/tenancy": "0.3.1",
44
+ "@crewhaus/token-budget": "0.3.1",
45
+ "@crewhaus/tool-catalog": "0.3.1",
46
+ "@crewhaus/tool-executor": "0.3.1",
47
+ "@crewhaus/tool-loop-detection": "0.3.1",
48
+ "@crewhaus/tool-orchestrator": "0.3.1",
49
+ "@crewhaus/tool-result-store": "0.3.1",
50
+ "@crewhaus/streaming-tool-executor": "0.3.1",
51
+ "@crewhaus/turn-state-machine": "0.3.1",
52
+ "@crewhaus/trace-event-bus": "0.3.1",
53
+ "@crewhaus/structured-event-printer": "0.3.1",
54
+ "@crewhaus/metrics-collector": "0.3.1",
55
+ "@crewhaus/otel-exporter": "0.3.1",
56
56
  "zod-to-json-schema": "^3.23.5"
57
57
  },
58
58
  "devDependencies": {
59
- "@crewhaus/logging": "0.2.4",
60
- "@crewhaus/tool-builder": "0.2.4",
59
+ "@crewhaus/logging": "0.3.1",
60
+ "@crewhaus/tool-builder": "0.3.1",
61
+ "@crewhaus/tool-plan": "0.3.1",
61
62
  "zod": "^3.23.8"
62
63
  },
63
64
  "license": "Apache-2.0",