@crewhaus/runtime-core 0.1.8 → 0.2.0

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.
@@ -0,0 +1,88 @@
1
+ import type { TraceEventBus } from "@crewhaus/trace-event-bus";
2
+ /**
3
+ * Structural subset of `@crewhaus/durable-state`'s `BudgetStore` — declared
4
+ * here (mirroring `JustificationAuditSink`) so runtime-core does not take a
5
+ * dependency on durable-state. Only target-managed wires a real store.
6
+ */
7
+ export type JanitorReservationStore = {
8
+ clearReservations(): Promise<void>;
9
+ };
10
+ export type JanitorStepName = "reservation_cleanup" | "session_ttl_eviction" | "orphan_tool_use_sweep";
11
+ export type JanitorStepStatus = "ok" | "skipped" | "error";
12
+ export type JanitorStepResult = {
13
+ readonly step: JanitorStepName;
14
+ readonly status: JanitorStepStatus;
15
+ /** Step tally: sessions evicted / orphaned tool_use ids found. */
16
+ readonly count?: number;
17
+ /** Skip reason, error message, or sweep stats. */
18
+ readonly detail?: string;
19
+ };
20
+ export type JanitorRunResult = {
21
+ readonly startedAt: string;
22
+ readonly durationMs: number;
23
+ readonly steps: ReadonlyArray<JanitorStepResult>;
24
+ };
25
+ export type CreateJanitorOptions = {
26
+ /**
27
+ * Durable-state budget store whose crash-leaked reservations are cleared
28
+ * on the first successful run. Omitted (the default for channel/batch
29
+ * daemons, which carry no budget store) the step reports `skipped`.
30
+ */
31
+ readonly budgetStore?: JanitorReservationStore;
32
+ /**
33
+ * Session directories to sweep — TTL eviction and the orphan scan both
34
+ * walk every listed root. Default: the single root `runChatLoop` itself
35
+ * would use outside a tenant scope (`CREWHAUS_SESSION_DIR` or
36
+ * `.crewhaus/sessions`), unless `tenantsRootDir` is set (then only the
37
+ * discovered tenant roots are swept). The managed target passes its
38
+ * per-tenant `sessionRoot`s here AND `tenantsRootDir` below.
39
+ */
40
+ readonly sessionRootDirs?: ReadonlyArray<string>;
41
+ /**
42
+ * Parent directory whose immediate subdirectories are per-tenant roots
43
+ * (`<tenantsRootDir>/<tenantId>/sessions` — the layout tenancy's
44
+ * `buildTenant` produces). Re-enumerated on EVERY run, so tenants that
45
+ * only appear AFTER boot — gateway-server serves any authenticated tenant
46
+ * id via its `buildTenant` fallback, not just spec-declared overrides —
47
+ * are swept too. Discovered roots are merged (deduplicated) with
48
+ * `sessionRootDirs`.
49
+ */
50
+ readonly tenantsRootDir?: string;
51
+ /**
52
+ * TTL for session eviction. Default: session-store's own (30 days).
53
+ * Daemons should pass the harness's `.crewhaus/retention.json`
54
+ * `sessions.maxAgeDays` (see `@crewhaus/data-retention-engine`'s
55
+ * `loadRetentionConfig`) so the janitor and the `crewhaus retention` CLI
56
+ * enforce one policy.
57
+ */
58
+ readonly sessionTtlDays?: number;
59
+ /**
60
+ * Session ids never evicted, however old — `.crewhaus/retention.json`'s
61
+ * `pins`, threaded into session-store's `evictExpiredSessions`.
62
+ */
63
+ readonly pinnedSessionIds?: ReadonlyArray<string>;
64
+ /**
65
+ * Most recent N session logs scanned per root for orphaned tool_use
66
+ * entries. Bounds the sweep on long-lived hosts. Default 20; 0 disables
67
+ * the orphan step entirely.
68
+ */
69
+ readonly orphanScanLimit?: number;
70
+ /**
71
+ * Logs modified within this window are presumed live (a mid-turn session
72
+ * transiently looks orphaned) and are skipped. Default 5 minutes.
73
+ */
74
+ readonly orphanQuietPeriodMs?: number;
75
+ /** Optional trace bus — one `janitor_action` event per step per run. */
76
+ readonly bus?: TraceEventBus;
77
+ /** Test seam: clock. */
78
+ readonly now?: () => Date;
79
+ };
80
+ export type Janitor = {
81
+ /** Run all steps once. Never rejects — failures land in the result. */
82
+ runOnce(): Promise<JanitorRunResult>;
83
+ /** Re-run `runOnce` every `intervalMs` (unref'd). `<= 0` is a no-op. */
84
+ start(intervalMs: number): void;
85
+ /** Cancel the interval started by `start`. Idempotent. */
86
+ stop(): void;
87
+ };
88
+ export declare function createJanitor(opts?: CreateJanitorOptions): Janitor;
@@ -0,0 +1,287 @@
1
+ import { readdir, stat } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { openEventLog } from "@crewhaus/event-log";
4
+ import { DEFAULT_ROOT_DIR, evictExpiredSessions } from "@crewhaus/session-store";
5
+ const SESSION_LOG_REGEX = /^(sess_[0-9a-f]{16})\.jsonl$/;
6
+ const DEFAULT_ORPHAN_SCAN_LIMIT = 20;
7
+ const DEFAULT_ORPHAN_QUIET_PERIOD_MS = 5 * 60_000;
8
+ /** Scan one session's `.jsonl` for assistant `tool_use` ids with no answering `tool_result`. */
9
+ async function countOrphanToolUses(sessionId, rootDir) {
10
+ const log = await openEventLog(sessionId, { rootDir });
11
+ const toolUseIds = [];
12
+ const answered = new Set();
13
+ // Mirror `replayMessageHistory`: events nested inside a2a_turn_start/
14
+ // sub_agent_start brackets belong to a peer/sub-agent transcript, not the
15
+ // outer history — only depth-0 messages count. Orphan detection then
16
+ // mirrors `sanitizeOrphanToolUses`: an assistant tool_use is orphaned when
17
+ // no message anywhere carries a tool_result with its id.
18
+ let depth = 0;
19
+ try {
20
+ for await (const ev of log.read()) {
21
+ if (ev.kind === "a2a_turn_start" || ev.kind === "sub_agent_start") {
22
+ depth += 1;
23
+ continue;
24
+ }
25
+ if (ev.kind === "a2a_turn_end" || ev.kind === "sub_agent_end") {
26
+ depth = Math.max(0, depth - 1);
27
+ continue;
28
+ }
29
+ if (depth > 0)
30
+ continue;
31
+ if (ev.kind !== "user_message" && ev.kind !== "assistant_message")
32
+ continue;
33
+ const content = ev.payload?.content;
34
+ if (!Array.isArray(content))
35
+ continue;
36
+ for (const block of content) {
37
+ const b = block;
38
+ if (ev.kind === "assistant_message" && b.type === "tool_use" && typeof b.id === "string") {
39
+ toolUseIds.push(b.id);
40
+ }
41
+ if (b.type === "tool_result" && typeof b.tool_use_id === "string") {
42
+ answered.add(b.tool_use_id);
43
+ }
44
+ }
45
+ }
46
+ }
47
+ finally {
48
+ await log.close();
49
+ }
50
+ return toolUseIds.filter((id) => !answered.has(id)).length;
51
+ }
52
+ export function createJanitor(opts = {}) {
53
+ const now = opts.now ?? (() => new Date());
54
+ // Same non-tenant fallback chain as `resolveSessionRootDir` (the janitor
55
+ // runs at boot, outside any tenant scope; a cycle-free inline keeps this
56
+ // module import-independent of index.ts). With a `tenantsRootDir` the
57
+ // single-root fallback is skipped — a tenant-scoped daemon has no
58
+ // non-tenant session root to sweep.
59
+ const staticRootDirs = opts.sessionRootDirs !== undefined && opts.sessionRootDirs.length > 0
60
+ ? opts.sessionRootDirs
61
+ : opts.tenantsRootDir !== undefined
62
+ ? []
63
+ : [process.env["CREWHAUS_SESSION_DIR"] ?? DEFAULT_ROOT_DIR];
64
+ const orphanScanLimit = opts.orphanScanLimit ?? DEFAULT_ORPHAN_SCAN_LIMIT;
65
+ const orphanQuietPeriodMs = opts.orphanQuietPeriodMs ?? DEFAULT_ORPHAN_QUIET_PERIOD_MS;
66
+ /**
67
+ * The roots to sweep THIS run: the static list plus — when a
68
+ * `tenantsRootDir` is configured — `<tenantsRootDir>/<subdir>/sessions`
69
+ * for every subdirectory, re-enumerated each run so fallback tenants that
70
+ * first authenticated after boot are covered (ops-review F6).
71
+ */
72
+ async function resolveRootDirs() {
73
+ if (opts.tenantsRootDir === undefined)
74
+ return staticRootDirs;
75
+ const merged = new Map();
76
+ for (const dir of staticRootDirs)
77
+ merged.set(resolve(dir), dir);
78
+ let entries;
79
+ try {
80
+ entries = await readdir(opts.tenantsRootDir, { withFileTypes: true });
81
+ }
82
+ catch (err) {
83
+ if (err.code === "ENOENT")
84
+ return [...merged.values()];
85
+ throw err;
86
+ }
87
+ for (const entry of entries) {
88
+ if (!entry.isDirectory())
89
+ continue;
90
+ const sessionRoot = resolve(opts.tenantsRootDir, entry.name, "sessions");
91
+ if (!merged.has(sessionRoot))
92
+ merged.set(sessionRoot, sessionRoot);
93
+ }
94
+ return [...merged.values()];
95
+ }
96
+ // Boot-only latch, set on the ATTEMPT (not on success): after the first
97
+ // call — succeeded or not — clearReservations() is never invoked again by
98
+ // this janitor. See the module header for why a retry is a hazard.
99
+ let reservationsClearAttempted = false;
100
+ let reservationsClearSucceeded = false;
101
+ let timer;
102
+ let tickInFlight = false;
103
+ function report(result) {
104
+ if (opts.bus !== undefined) {
105
+ opts.bus.publish({
106
+ ...opts.bus.envelope(now()),
107
+ kind: "janitor_action",
108
+ step: result.step,
109
+ status: result.status,
110
+ ...(result.count !== undefined ? { count: result.count } : {}),
111
+ ...(result.detail !== undefined ? { detail: result.detail } : {}),
112
+ });
113
+ }
114
+ return result;
115
+ }
116
+ async function reservationCleanup() {
117
+ const step = "reservation_cleanup";
118
+ if (opts.budgetStore === undefined) {
119
+ return { step, status: "skipped", detail: "no budget store provided" };
120
+ }
121
+ if (reservationsClearAttempted) {
122
+ // Boot-only by design: after boot there is no way to tell a leaked
123
+ // reservation from a live in-flight one, and clearing would zero live
124
+ // reservations (see module header). This holds for a FAILED boot
125
+ // attempt too — by the next hourly tick traffic is flowing, so the
126
+ // attempt is never retried.
127
+ return {
128
+ step,
129
+ status: "skipped",
130
+ detail: reservationsClearSucceeded
131
+ ? "already cleared at boot"
132
+ : "skipped (boot-only, earlier attempt failed)",
133
+ };
134
+ }
135
+ // Latch BEFORE the call: a throw must count as the one-and-only attempt.
136
+ reservationsClearAttempted = true;
137
+ await opts.budgetStore.clearReservations();
138
+ reservationsClearSucceeded = true;
139
+ return { step, status: "ok", detail: "cleared crash-leaked reservations" };
140
+ }
141
+ async function sessionTtlEviction(rootDirs) {
142
+ const step = "session_ttl_eviction";
143
+ let evicted = 0;
144
+ for (const rootDir of rootDirs) {
145
+ const result = await evictExpiredSessions({
146
+ rootDir,
147
+ ...(opts.sessionTtlDays !== undefined ? { ttlDays: opts.sessionTtlDays } : {}),
148
+ ...(opts.pinnedSessionIds !== undefined ? { pinnedIds: opts.pinnedSessionIds } : {}),
149
+ now,
150
+ });
151
+ evicted += result.evictedIds.length;
152
+ }
153
+ return {
154
+ step,
155
+ status: "ok",
156
+ count: evicted,
157
+ detail: `evicted ${evicted} expired session(s) across ${rootDirs.length} root(s)`,
158
+ };
159
+ }
160
+ async function orphanToolUseSweep(rootDirs) {
161
+ const step = "orphan_tool_use_sweep";
162
+ if (orphanScanLimit <= 0) {
163
+ return { step, status: "skipped", detail: "orphanScanLimit is 0" };
164
+ }
165
+ const cutoff = now().getTime() - orphanQuietPeriodMs;
166
+ let scanned = 0;
167
+ let skippedActive = 0;
168
+ let unreadable = 0;
169
+ let orphans = 0;
170
+ const affected = [];
171
+ for (const rootDir of rootDirs) {
172
+ let entries;
173
+ try {
174
+ entries = await readdir(rootDir);
175
+ }
176
+ catch (err) {
177
+ if (err.code === "ENOENT")
178
+ continue;
179
+ throw err;
180
+ }
181
+ const candidates = [];
182
+ for (const entry of entries) {
183
+ const match = entry.match(SESSION_LOG_REGEX);
184
+ const id = match?.[1];
185
+ if (id === undefined)
186
+ continue;
187
+ let mtimeMs;
188
+ try {
189
+ const st = await stat(join(rootDir, entry));
190
+ mtimeMs = st.mtimeMs;
191
+ }
192
+ catch {
193
+ continue;
194
+ }
195
+ if (mtimeMs > cutoff) {
196
+ // Presumed live — a mid-turn session transiently has an
197
+ // unanswered tool_use between the assistant append and the
198
+ // tool_result append.
199
+ skippedActive += 1;
200
+ continue;
201
+ }
202
+ candidates.push({ id, mtimeMs });
203
+ }
204
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
205
+ for (const { id } of candidates.slice(0, orphanScanLimit)) {
206
+ try {
207
+ const found = await countOrphanToolUses(id, rootDir);
208
+ scanned += 1;
209
+ if (found > 0) {
210
+ orphans += found;
211
+ affected.push(id);
212
+ }
213
+ }
214
+ catch {
215
+ // Malformed log — report-only sweep must not fail on it.
216
+ unreadable += 1;
217
+ }
218
+ }
219
+ }
220
+ const detailParts = [
221
+ `${orphans} orphaned tool_use id(s) in ${affected.length}/${scanned} scanned log(s)`,
222
+ ];
223
+ if (affected.length > 0)
224
+ detailParts.push(`sessions: ${affected.slice(0, 5).join(", ")}`);
225
+ if (skippedActive > 0)
226
+ detailParts.push(`${skippedActive} recently-active log(s) skipped`);
227
+ if (unreadable > 0)
228
+ detailParts.push(`${unreadable} unreadable log(s) skipped`);
229
+ detailParts.push("report-only: resume self-heals via sanitizeOrphanToolUses");
230
+ return { step, status: "ok", count: orphans, detail: detailParts.join("; ") };
231
+ }
232
+ async function runStep(step, fn) {
233
+ try {
234
+ return report(await fn());
235
+ }
236
+ catch (err) {
237
+ const message = err instanceof Error ? err.message : String(err);
238
+ return report({ step, status: "error", detail: message });
239
+ }
240
+ }
241
+ async function runOnce() {
242
+ const startedAt = now().toISOString();
243
+ const t0 = performance.now();
244
+ // Resolve the sweep roots per run — with a tenantsRootDir this discovers
245
+ // tenants that first appeared after boot. A throwing resolution falls
246
+ // back to the static roots so the run still proceeds.
247
+ let rootDirs;
248
+ try {
249
+ rootDirs = await resolveRootDirs();
250
+ }
251
+ catch {
252
+ rootDirs = staticRootDirs;
253
+ }
254
+ const steps = [
255
+ await runStep("reservation_cleanup", reservationCleanup),
256
+ await runStep("session_ttl_eviction", () => sessionTtlEviction(rootDirs)),
257
+ await runStep("orphan_tool_use_sweep", () => orphanToolUseSweep(rootDirs)),
258
+ ];
259
+ return { startedAt, durationMs: performance.now() - t0, steps };
260
+ }
261
+ return {
262
+ runOnce,
263
+ start(intervalMs) {
264
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0)
265
+ return;
266
+ if (timer !== undefined)
267
+ return;
268
+ timer = setInterval(() => {
269
+ if (tickInFlight)
270
+ return;
271
+ tickInFlight = true;
272
+ void runOnce().finally(() => {
273
+ tickInFlight = false;
274
+ });
275
+ }, intervalMs);
276
+ // Never keep a finished process alive — the batch worker's idle-exit
277
+ // path returns from main() with the janitor still scheduled.
278
+ timer.unref?.();
279
+ },
280
+ stop() {
281
+ if (timer === undefined)
282
+ return;
283
+ clearInterval(timer);
284
+ timer = undefined;
285
+ },
286
+ };
287
+ }
@@ -1,4 +1,5 @@
1
1
  import { type CostTracker } from "@crewhaus/cost-tracker";
2
+ import type { EventLog } from "@crewhaus/event-log";
2
3
  import { type AttachedMetrics } from "@crewhaus/metrics-collector";
3
4
  import { type AttachedOtelExporter } from "@crewhaus/otel-exporter";
4
5
  /**
@@ -11,19 +12,23 @@ import { type AttachedOtelExporter } from "@crewhaus/otel-exporter";
11
12
  * OTEL_EXPORTER_OTLP_ENDPOINT → otel-exporter (OTLP/HTTP, gen_ai/* attributes)
12
13
  * CREWHAUS_COST_TRACKING=1 → cost-tracker (Section 27 — emits cost_accrual events)
13
14
  * CREWHAUS_COST_INLINE=1 → CLI inline cost line per turn (requires CREWHAUS_COST_TRACKING)
15
+ * CREWHAUS_SECURITY_DIGEST=1 → per-run security tally, one stderr line at end of run (item 48)
14
16
  *
15
17
  * All are opt-in. With no env vars set this function returns a no-op
16
18
  * `flushAll` so observability adds zero output and zero overhead.
17
19
  */
18
20
  import type { RunContext } from "@crewhaus/run-context";
19
21
  import { type AttachedPrinter } from "@crewhaus/structured-event-printer";
20
- import type { CostAccrualEvent, TraceEventBus, Unsubscribe } from "@crewhaus/trace-event-bus";
22
+ import type { CostAccrualEvent, TraceEvent, TraceEventBus, Unsubscribe } from "@crewhaus/trace-event-bus";
23
+ import { type SloMitigationSink, type SloTargets } from "./slo-monitor";
21
24
  export type AttachedSubscribers = {
22
25
  printer: AttachedPrinter | undefined;
23
26
  metrics: AttachedMetrics | undefined;
24
27
  otel: AttachedOtelExporter | undefined;
25
28
  costTracker: CostTracker | undefined;
26
29
  costInlineUnsubscribe: Unsubscribe | undefined;
30
+ /** Item 48 — per-run security tally (undefined unless CREWHAUS_SECURITY_DIGEST is set). */
31
+ securityTally: SecurityTally | undefined;
27
32
  flushAll(): Promise<void>;
28
33
  shutdownAll(): Promise<void>;
29
34
  };
@@ -35,4 +40,175 @@ export type AttachedSubscribers = {
35
40
  * without re-implementing it.
36
41
  */
37
42
  export declare function formatCostInlineLine(ev: CostAccrualEvent): string;
38
- export declare function attachDefaultSubscribers(bus: TraceEventBus, runContext: RunContext, env?: NodeJS.ProcessEnv): Promise<AttachedSubscribers>;
43
+ /**
44
+ * Item 48 — the live half of `crewhaus security digest`: a per-run tally of
45
+ * security-relevant TraceEvents, gated behind CREWHAUS_SECURITY_DIGEST=1.
46
+ * The durable audit-log rollup (the CLI command) answers "what happened this
47
+ * week?"; this answers "what did THIS run trip?" without waiting for the
48
+ * offline walk. When anything was tallied, one summary line lands on STDERR
49
+ * at end of run — stderr so it never contaminates piped agent output.
50
+ */
51
+ export type SecurityTally = {
52
+ /** Justification-gate denials (permission_decision with judgeModel + deny). */
53
+ justificationDenials: number;
54
+ /** Plain permission-policy denials (no judge identity, no outcome). */
55
+ permissionDenials: number;
56
+ /** Egress classifier warn-tier verdicts (outcome: "egress-warned"). */
57
+ egressWarned: number;
58
+ /** Egress classifier block-tier verdicts (outcome: "egress-blocked"). */
59
+ egressBlocked: number;
60
+ /** Injection classifier redactions (outcome: "redacted"). */
61
+ injectionRedactions: number;
62
+ /** Injection classifier suspicious-but-kept warns (outcome: "warned"). */
63
+ injectionWarnings: number;
64
+ /** Detector rule-id → hit count, from redacted/warned events' `rules`. */
65
+ injectionRuleHits: Record<string, number>;
66
+ /** pre/post-tool hooks that denied (hook_fired with allowed: false). */
67
+ hookDenials: number;
68
+ /** Circuit-breaker transitions INTO "open" (a provider went degraded). */
69
+ circuitOpens: number;
70
+ /** Circuit-breaker recoveries (non-closed → "closed"). */
71
+ circuitRecoveries: number;
72
+ };
73
+ export declare function createSecurityTally(): SecurityTally;
74
+ /**
75
+ * Fold one TraceEvent into the tally. Returns true when the event counted.
76
+ * Classification rules (kept mutually exclusive so nothing double-counts):
77
+ * - a `permission_decision` carrying an outcome (egress-warned,
78
+ * egress-blocked, redacted, warned) is an egress/injection verdict,
79
+ * NEVER also a plain permission denial (the egress-blocked event
80
+ * carries decision "deny" too);
81
+ * - a `judgeModel` marks the justification gate — deny → justification
82
+ * denial;
83
+ * - remaining decision "deny" events are plain policy denials. "ask" is
84
+ * not tallied — a prompt is not an incident.
85
+ */
86
+ export declare function tallySecurityEvent(tally: SecurityTally, event: TraceEvent): boolean;
87
+ /** Sum of every tallied counter — 0 means "print nothing at end of run". */
88
+ export declare function securityTallyTotal(tally: SecurityTally): number;
89
+ /**
90
+ * Format the end-of-run summary line. Only non-zero segments render, e.g.
91
+ * `[security] 2 justification denial(s) · 1 egress block(s) · 1 injection
92
+ * redaction(s) [rules: exfil-url ×2] — run crewhaus security digest …`
93
+ * Exported so target bundles (and tests) can render the identical format,
94
+ * mirroring `formatCostInlineLine`.
95
+ */
96
+ export declare function formatSecurityTallyLine(tally: SecurityTally): string;
97
+ /**
98
+ * Ops item 31 — how the alert watchdog delivers a breach beyond the
99
+ * `alert_raised` trace event. Both callbacks are OPTIONAL and injected by the
100
+ * caller (the CLI/codegen), so runtime-core stays free of audit-log/hook I/O:
101
+ * - `appendAudit` writes a tamper-evident record (the CLI passes an
102
+ * `openAuditLog(...)`-backed sink);
103
+ * - `fireAlertHook` invokes the settings.json `alert` hook and/or POSTs the
104
+ * configured webhook.
105
+ * Absent → the watchdog still persists the snapshot + publishes the trace
106
+ * event, it just has no durable/off-box delivery.
107
+ */
108
+ export type AlertSink = {
109
+ appendAudit?: (breach: AlertBreachPayload) => Promise<void>;
110
+ fireAlertHook?: (breach: AlertBreachPayload) => Promise<void>;
111
+ };
112
+ /** The payload handed to the audit sink / settings.json alert hook / webhook. */
113
+ export type AlertBreachPayload = {
114
+ readonly sessionId: string;
115
+ readonly metric: string;
116
+ readonly observed: number;
117
+ readonly threshold: number;
118
+ readonly baselineSessions: number;
119
+ readonly detail: string;
120
+ };
121
+ export type AttachDefaultSubscribersOptions = {
122
+ /** Item 31 — where the alert watchdog persists its per-session snapshot history. */
123
+ readonly metricsDir?: string;
124
+ /** Item 31 — durable + off-box alert delivery (see {@link AlertSink}). */
125
+ readonly alertSink?: AlertSink;
126
+ /** Item 37 — lowered `observability.slo` targets. The SLO monitor is a no-op
127
+ * without both this AND CREWHAUS_SLO set. */
128
+ readonly sloTargets?: SloTargets;
129
+ /** Item 37 — injected SLO mitigation ladder delivery (see {@link SloMitigationSink}). */
130
+ readonly sloSink?: SloMitigationSink;
131
+ };
132
+ export declare function attachDefaultSubscribers(bus: TraceEventBus, runContext: RunContext, env?: NodeJS.ProcessEnv, options?: AttachDefaultSubscribersOptions): Promise<AttachedSubscribers>;
133
+ export type AttachedAlertWatchdog = {
134
+ /** Compute the snapshot, persist it, derive baselines, raise alerts. Idempotent. */
135
+ finalize(): Promise<void>;
136
+ unsubscribe: Unsubscribe;
137
+ };
138
+ /**
139
+ * Ops item 31 — attach the alert watchdog when CREWHAUS_ALERTS is set. Folds
140
+ * events into a per-session {@link SessionMetricsAccumulator}; `finalize()`
141
+ * (called from flush/shutdown) persists the snapshot, derives baseline
142
+ * thresholds from the accrued history, and — per breach — publishes an
143
+ * `alert_raised` trace event, appends an audit record, and fires the alert
144
+ * hook/webhook via the injected {@link AlertSink}. Returns undefined (a no-op)
145
+ * when the env gate is off, so it adds zero overhead by default.
146
+ *
147
+ * NOTE (spec gate): the primary gate is the CREWHAUS_ALERTS env var, matching
148
+ * every other subscriber in this file (attachDefaultSubscribers only receives
149
+ * env). A spec-level `observability.alerts` block would be lowered by the
150
+ * compiler into an env stamp / options flag on the emitted bundle; that
151
+ * lowering is the follow-up — the runtime seam here already honours it.
152
+ */
153
+ export declare function attachAlertWatchdog(bus: TraceEventBus, runContext: RunContext, env: NodeJS.ProcessEnv, options?: AttachDefaultSubscribersOptions): AttachedAlertWatchdog | undefined;
154
+ export type AttachedAdvisorPersistence = {
155
+ unsubscribe: Unsubscribe;
156
+ /**
157
+ * Item 14 in-run digest — the one-line stderr summary the runtime prints
158
+ * at session end when any cheap advisory threshold tripped, or undefined
159
+ * when the session looks healthy. Counters only: no LLM, no file reads,
160
+ * nothing heavier than a Map bump per event in the hot path — the real
161
+ * analysis is `crewhaus advise`'s job, offline.
162
+ */
163
+ digestLine(): string | undefined;
164
+ };
165
+ /**
166
+ * Advisor groundwork (items 14/15/17) — mirror the runtime signals that were
167
+ * previously trace-bus-only into the session JSONL, through the SAME
168
+ * `event-log` append path the run already writes its transcript with:
169
+ *
170
+ * error_recovered → `recovery` { errorName, action, depth }
171
+ * tool_call_end → `tool_stats` { toolName, durationMs, isError }
172
+ * permission_decision → `permission` { toolName, decision, askOutcome }
173
+ * model_response → `model_meta` { stopReason, model }
174
+ *
175
+ * Unlike the other `attach*IfEnvSet` subscribers this one is DEFAULT-ON:
176
+ * the lines are tiny (see the granularity note on the `tool_stats` kind in
177
+ * `@crewhaus/event-log`) and they are the food `crewhaus advise` mines, so
178
+ * opting in would starve the advisor on exactly the runs that need it.
179
+ * Disable with `CREWHAUS_ADVISOR_EVENTS=0` (or `false`).
180
+ *
181
+ * Permission mapping detail: a `decision: "ask"` event WITHOUT `askOutcome`
182
+ * is the pre-prompt publish — skipped here so each ask persists exactly once,
183
+ * as its resolution (`askOutcome: "approved" | "denied"`). Allow/deny
184
+ * decisions (including the justification-gate and egress verdicts, which
185
+ * publish additional `permission_decision` events per call) persist with
186
+ * `askOutcome: null`.
187
+ *
188
+ * `append()` failures must never abort a turn, so — like the cost_accrual
189
+ * persistence path — the promise result is logged rather than thrown.
190
+ */
191
+ export declare function attachAdvisorPersistence(bus: TraceEventBus, eventLog: EventLog, runContext: RunContext, env?: NodeJS.ProcessEnv): AttachedAdvisorPersistence | undefined;
192
+ export type AttachedMcpStatsPersistence = {
193
+ unsubscribe: Unsubscribe;
194
+ };
195
+ /**
196
+ * Ops item 38 — mirror the trace-bus-only `mcp_call_end` events into the same
197
+ * session JSONL the transcript already writes to, as the durable `mcp_stats`
198
+ * kind, so `crewhaus mcp doctor` can score per-server MCP health OFFLINE across
199
+ * sessions. `mcp_call_start`/`mcp_call_end` are trace-bus-only today — nothing
200
+ * durably records per-server error-rate / latency — so this subscriber is the
201
+ * durable history the report reads.
202
+ *
203
+ * Payload per line: `{ server, toolName, durationMs, isError }` — the same
204
+ * granularity decision the advisor's `tool_stats` made: per-call, not a per-turn
205
+ * aggregate, so the report keeps the full latency/error distribution. Whole
206
+ * milliseconds only (performance.now() floats add bytes without adding signal).
207
+ *
208
+ * Shares the DEFAULT-ON gate with the advisor events (disable with
209
+ * CREWHAUS_ADVISOR_EVENTS=0): the lines are tiny and they are exactly what the
210
+ * MCP-health report mines, so opting in would starve the doctor on the runs
211
+ * that used MCP servers. `append()` failures are logged, never thrown — a
212
+ * persistence hiccup must not abort a turn.
213
+ */
214
+ export declare function attachMcpStatsPersistence(bus: TraceEventBus, eventLog: EventLog, runContext: RunContext, env?: NodeJS.ProcessEnv): AttachedMcpStatsPersistence | undefined;