@principles/host-runtime 4.10.0 → 4.11.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.
@@ -19,6 +19,8 @@ export interface Stage2CorrectionCycleReport {
19
19
  readonly classifier: 'used' | 'unavailable' | 'disabled';
20
20
  readonly claimed: number;
21
21
  readonly admitted: number;
22
+ readonly inboxCandidates?: number;
23
+ readonly stallInboxCandidates?: number;
22
24
  readonly resolvedNone: number;
23
25
  readonly abandoned: number;
24
26
  readonly stillPending: number;
@@ -1,3 +1,5 @@
1
+ import { hydrateStage2ContextForCandidate } from './stage2-context-hydrator.js';
2
+ import { scanWorkspaceTrajectoryStalls } from './trajectory-stall-detector.js';
1
3
  import { claimPendingCorrectionCandidates, recordPendingCorrectionReview, releasePendingCorrectionClaim, settlePendingCorrection, verifyPendingClaimForClassification, } from './governance-signal-admission.js';
2
4
  const DEFAULT_MAX_CANDIDATES = 2;
3
5
  const DEFAULT_AGGREGATE_BUDGET_MS = 60_000;
@@ -50,6 +52,7 @@ export async function runStage2CorrectionCycle(input) {
50
52
  };
51
53
  }
52
54
  let admitted = 0;
55
+ let inboxCandidates = 0;
53
56
  let resolvedNone = 0;
54
57
  let abandoned = 0;
55
58
  let stillPending = 0;
@@ -75,6 +78,8 @@ export async function runStage2CorrectionCycle(input) {
75
78
  const tally = (outcome) => {
76
79
  if (outcome.disposition === 'admitted')
77
80
  admitted += 1;
81
+ else if (outcome.disposition === 'inbox_candidate')
82
+ inboxCandidates += 1;
78
83
  else if (outcome.disposition === 'resolved_none')
79
84
  resolvedNone += 1;
80
85
  else if (outcome.disposition === 'abandoned')
@@ -140,7 +145,12 @@ export async function runStage2CorrectionCycle(input) {
140
145
  // The remaining budget goes INTO the adapter request as well as the
141
146
  // outer race (v0.3.1 §2.2); an outer timeout does not cancel a
142
147
  // provider request that the adapter does not support cancelling.
143
- const llm = await withTimeout(input.classifier(candidate.text, { timeoutMs }), timeoutMs);
148
+ const stage2Context = hydrateStage2ContextForCandidate({
149
+ workspaceDir: input.workspaceDir,
150
+ candidate,
151
+ now,
152
+ });
153
+ const llm = await withTimeout(input.classifier(candidate.text, { timeoutMs, context: stage2Context }), timeoutMs);
144
154
  const { claimToken } = candidate;
145
155
  if (claimToken === null) {
146
156
  // A freshly claimed candidate always carries a token; its absence
@@ -154,6 +164,7 @@ export async function runStage2CorrectionCycle(input) {
154
164
  logicalObservationKey: candidate.logicalObservationKey,
155
165
  claimToken,
156
166
  llmResult: llm,
167
+ priorAssistantTurnCount: stage2Context.priorAssistantTurnCount,
157
168
  now,
158
169
  });
159
170
  if (!recorded.ok) {
@@ -199,11 +210,29 @@ export async function runStage2CorrectionCycle(input) {
199
210
  skipped += 1;
200
211
  }
201
212
  }
213
+ // SPEC-PD-PAIN-DETECTION-UPGRADE-001 R4 (W5): bounded trajectory stall scan
214
+ // inside the existing worker cycle (zero new background services).
215
+ let stallInboxCandidates = 0;
216
+ try {
217
+ const stallReport = scanWorkspaceTrajectoryStalls({
218
+ workspaceDir: input.workspaceDir,
219
+ now,
220
+ });
221
+ stallInboxCandidates = stallReport.admittedInboxCandidates;
222
+ if (stallReport.scanError !== undefined) {
223
+ degradations.push(`trajectory_stall_scan:${stallReport.scanError}`);
224
+ }
225
+ }
226
+ catch (error) {
227
+ degradations.push(`trajectory_stall_scan:${error instanceof Error ? error.message.slice(0, 160) : String(error).slice(0, 160)}`);
228
+ }
202
229
  return {
203
230
  ok: degradations.length === 0,
204
231
  classifier: classifierState,
205
232
  claimed: claimedResult.candidates.length,
206
233
  admitted,
234
+ inboxCandidates,
235
+ ...(stallInboxCandidates > 0 ? { stallInboxCandidates } : {}),
207
236
  resolvedNone,
208
237
  abandoned,
209
238
  stillPending,
@@ -345,6 +345,25 @@ function sweepTrajectoryDb(args) {
345
345
  // - sanitized_text uses '' (the column is NOT NULL — the previous NULL
346
346
  // form violated the schema and rolled the whole purge back, F1);
347
347
  // - every ref is containment-checked before it can address a path (F4).
348
+ // W4 (SPEC-PD-PAIN-DETECTION-UPGRADE-001): when revoking OpenClaw,
349
+ // ALWAYS terminate OpenClaw inbox_candidate/inbox_approving rows in
350
+ // signal_confirmations to explicit terminal resolution='source_revoked'
351
+ // even when sibling hosts hold granted consent, so re-granting can NEVER
352
+ // resurrect old Inbox candidates.
353
+ if (hostKind === 'openclaw' && tableExists('signal_confirmations') && otherGrantedHosts.length > 0) {
354
+ if (apply) {
355
+ counts.trajectorySignalConfirmationRows += db.prepare(`UPDATE signal_confirmations
356
+ SET excerpt = '', recent_assistant_turns_json = NULL,
357
+ status = 'abandoned',
358
+ resolution = 'source_revoked',
359
+ resolved_at = ?
360
+ WHERE status = 'pending' AND resolution IN ('inbox_candidate', 'inbox_approving')`).run(nowIso).changes;
361
+ }
362
+ else {
363
+ counts.trajectorySignalConfirmationRows += db.prepare(`SELECT COUNT(*) AS c FROM signal_confirmations
364
+ WHERE status = 'pending' AND resolution IN ('inbox_candidate', 'inbox_approving')`).get().c;
365
+ }
366
+ }
348
367
  if (otherGrantedHosts.length > 0) {
349
368
  skipped.push(`trajectory_turns: shared workspace, other granted hosts present (${otherGrantedHosts.join(', ')}) — turn purge skipped`);
350
369
  skipped.push(`signal_confirmations: shared workspace, other granted hosts present (${otherGrantedHosts.join(', ')}) — excerpt purge skipped`);
@@ -453,6 +472,25 @@ function sweepTrajectoryDb(args) {
453
472
  else {
454
473
  const markers = db.prepare('SELECT id, decision, reason, task_payload_json, canonical_pain_id, host_kind FROM governance_signal_admissions WHERE host_kind = ?').all(hostKind);
455
474
  for (const marker of markers) {
475
+ // W4 (SPEC-PD-PAIN-DETECTION-UPGRADE-001): explicitly terminate
476
+ // Pain Inbox candidates (inbox_candidate / inbox_approving) to terminal
477
+ // decision='source_revoked' with redacted payload so re-granting never
478
+ // resurrects revoked candidates.
479
+ if (marker.decision === 'inbox_candidate' || marker.decision === 'inbox_approving') {
480
+ if (apply) {
481
+ const { changes } = db.prepare(`UPDATE governance_signal_admissions
482
+ SET decision = 'source_revoked', reason = 'source_revoked', task_payload_json = ?, updated_at = ?
483
+ WHERE id = ? AND decision IN ('inbox_candidate', 'inbox_approving')`).run(JSON.stringify({ decision: 'source_revoked', revokedAt: nowIso }), nowIso, marker.id);
484
+ if (changes === 1)
485
+ counts.pendingReviewsTerminated += 1;
486
+ else
487
+ failures.push(`admission_${marker.id}: inbox source_revoked lost a race — skipped (rerun the sweep)`);
488
+ }
489
+ else {
490
+ counts.pendingReviewsTerminated += 1;
491
+ }
492
+ continue;
493
+ }
456
494
  const classification = classifyAdmissionMarker(marker);
457
495
  if (classification.kind === 'owner_explicit') {
458
496
  // Directive B: an explicit Owner submission is an Owner act, not
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Stage-2 Conversation Context Hydrator — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R1-2.
3
+ *
4
+ * Hydrates bounded, host-owned `Stage2ConversationContext` for Codex and
5
+ * WorkBuddy pending correction candidates before Stage-2 LLM classification
6
+ * and Gate 3 confidence gating.
7
+ *
8
+ * Architectural invariants (TD-PD-PAIN-DETECTION-UPGRADE-001 §2.2):
9
+ * - Consent fail-closed: checks `readSourceMaterialAuthorization` before
10
+ * reading any observation row. Unauthorized hosts receive
11
+ * `priorAssistantTurnCount: null` (unknown), never fabricated `0`.
12
+ * - Anchor resolution by `(host_kind, rollout_identity, logical_key)` on
13
+ * `governance_observations` — never GSA `created_at`.
14
+ * - Ordering strictly uses `source_order` (byte offset within the rollout).
15
+ * If `source_order` is missing on the anchor or mixed (some rows NULL, some
16
+ * non-NULL) within the same rollout, returns `priorAssistantTurnCount: null`
17
+ * honestly rather than fabricating `0` or guessing insertion order.
18
+ * - Filters strictly to `kind IN ('assistant_turn', 'tool_call')` and
19
+ * `retention_class IN ('operational', 'promoted')` within the same
20
+ * `rollout_row_id`.
21
+ */
22
+ import type { Stage2ConversationContext } from '@principles/core/runtime';
23
+ import type { ObservationDatabaseFactory } from './governance-observation-store.js';
24
+ export interface Stage2HydrationCandidate {
25
+ readonly logicalObservationKey: string;
26
+ readonly hostKind: 'codex' | 'workbuddy';
27
+ readonly rolloutIdentity: string;
28
+ readonly rootSessionId: string;
29
+ readonly hostTurnId: string;
30
+ }
31
+ export interface HydrateStage2ContextInput {
32
+ readonly workspaceDir: string;
33
+ readonly candidate: Stage2HydrationCandidate;
34
+ readonly maxRecentAssistantTurns?: number;
35
+ readonly maxSummaryChars?: number;
36
+ readonly now?: Date;
37
+ readonly databaseFactory?: ObservationDatabaseFactory;
38
+ }
39
+ /**
40
+ * Hydrate bounded conversation facts (`Stage2ConversationContext`) from
41
+ * `governance_observations` for a Codex or WorkBuddy pending correction
42
+ * candidate. Never throws; degrades honestly to `priorAssistantTurnCount: null`
43
+ * when consent is missing/revoked, the trajectory DB or anchor row is absent,
44
+ * or `source_order` is missing/mixed.
45
+ */
46
+ export declare function hydrateStage2ContextForCandidate(input: HydrateStage2ContextInput): Stage2ConversationContext;
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Stage-2 Conversation Context Hydrator — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R1-2.
3
+ *
4
+ * Hydrates bounded, host-owned `Stage2ConversationContext` for Codex and
5
+ * WorkBuddy pending correction candidates before Stage-2 LLM classification
6
+ * and Gate 3 confidence gating.
7
+ *
8
+ * Architectural invariants (TD-PD-PAIN-DETECTION-UPGRADE-001 §2.2):
9
+ * - Consent fail-closed: checks `readSourceMaterialAuthorization` before
10
+ * reading any observation row. Unauthorized hosts receive
11
+ * `priorAssistantTurnCount: null` (unknown), never fabricated `0`.
12
+ * - Anchor resolution by `(host_kind, rollout_identity, logical_key)` on
13
+ * `governance_observations` — never GSA `created_at`.
14
+ * - Ordering strictly uses `source_order` (byte offset within the rollout).
15
+ * If `source_order` is missing on the anchor or mixed (some rows NULL, some
16
+ * non-NULL) within the same rollout, returns `priorAssistantTurnCount: null`
17
+ * honestly rather than fabricating `0` or guessing insertion order.
18
+ * - Filters strictly to `kind IN ('assistant_turn', 'tool_call')` and
19
+ * `retention_class IN ('operational', 'promoted')` within the same
20
+ * `rollout_row_id`.
21
+ */
22
+ import fs from 'node:fs';
23
+ import Database from 'better-sqlite3';
24
+ import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
25
+ import { readSourceMaterialAuthorization } from './source-material-authorization.js';
26
+ const DEFAULT_MAX_RECENT_ASSISTANT_TURNS = 4;
27
+ const DEFAULT_MAX_SUMMARY_CHARS = 240;
28
+ function isRecord(value) {
29
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
30
+ }
31
+ function isAnchorRow(value) {
32
+ if (!isRecord(value))
33
+ return false;
34
+ return (typeof value.id === 'number' &&
35
+ typeof value.rollout_row_id === 'number' &&
36
+ (value.source_order === null || typeof value.source_order === 'number') &&
37
+ typeof value.observed_at === 'string');
38
+ }
39
+ function isPriorObservationRow(value) {
40
+ if (!isRecord(value))
41
+ return false;
42
+ return (typeof value.id === 'number' &&
43
+ typeof value.kind === 'string' &&
44
+ (value.visible_text === null || typeof value.visible_text === 'string') &&
45
+ (value.sanitized_tool_facts_json === null || typeof value.sanitized_tool_facts_json === 'string') &&
46
+ (value.source_order === null || typeof value.source_order === 'number'));
47
+ }
48
+ function unknownContext(snapshotCapturedAt) {
49
+ return {
50
+ priorAssistantTurnCount: null,
51
+ recentAssistantTurns: [],
52
+ snapshotCapturedAt,
53
+ };
54
+ }
55
+ function truncateText(text, maxChars) {
56
+ const collapsed = text.replace(/\s+/g, ' ').trim();
57
+ if (collapsed.length <= maxChars)
58
+ return collapsed;
59
+ return `${collapsed.slice(0, Math.max(1, maxChars - 1))}…`;
60
+ }
61
+ function formatToolFactsSummary(rawJson, maxChars) {
62
+ if (!rawJson)
63
+ return '[tool_call]';
64
+ try {
65
+ const parsed = JSON.parse(rawJson);
66
+ if (isRecord(parsed)) {
67
+ const obj = isRecord(parsed.facts) ? parsed.facts : parsed;
68
+ const toolName = typeof obj.toolName === 'string'
69
+ ? obj.toolName
70
+ : typeof obj.tool === 'string'
71
+ ? obj.tool
72
+ : typeof obj.name === 'string'
73
+ ? obj.name
74
+ : 'tool';
75
+ const outcome = typeof obj.outcome === 'string'
76
+ ? obj.outcome
77
+ : typeof obj.status === 'string'
78
+ ? obj.status
79
+ : undefined;
80
+ const detail = typeof obj.error === 'string'
81
+ ? obj.error
82
+ : typeof obj.summary === 'string'
83
+ ? obj.summary
84
+ : undefined;
85
+ const parts = [`[tool:${toolName}]`];
86
+ if (outcome)
87
+ parts.push(`outcome=${outcome}`);
88
+ if (detail)
89
+ parts.push(detail);
90
+ return truncateText(parts.join(' '), maxChars);
91
+ }
92
+ }
93
+ catch {
94
+ // Fall back to bounded raw string preview if JSON is malformed.
95
+ }
96
+ return truncateText(`[tool_call] ${rawJson}`, maxChars);
97
+ }
98
+ function summarizeObservationRow(row, maxChars) {
99
+ if (row.kind === 'assistant_turn') {
100
+ const text = row.visible_text?.trim();
101
+ if (!text)
102
+ return null;
103
+ return { summary: truncateText(text, maxChars), referenced: false };
104
+ }
105
+ if (row.kind === 'tool_call') {
106
+ const summary = row.visible_text?.trim()
107
+ ? truncateText(`[tool_call] ${row.visible_text}`, maxChars)
108
+ : formatToolFactsSummary(row.sanitized_tool_facts_json, maxChars);
109
+ return { summary, referenced: false };
110
+ }
111
+ return null;
112
+ }
113
+ /**
114
+ * Hydrate bounded conversation facts (`Stage2ConversationContext`) from
115
+ * `governance_observations` for a Codex or WorkBuddy pending correction
116
+ * candidate. Never throws; degrades honestly to `priorAssistantTurnCount: null`
117
+ * when consent is missing/revoked, the trajectory DB or anchor row is absent,
118
+ * or `source_order` is missing/mixed.
119
+ */
120
+ export function hydrateStage2ContextForCandidate(input) {
121
+ const snapshotCapturedAt = (input.now ?? new Date()).toISOString();
122
+ const maxRecent = Math.max(1, input.maxRecentAssistantTurns ?? DEFAULT_MAX_RECENT_ASSISTANT_TURNS);
123
+ const maxChars = Math.max(32, input.maxSummaryChars ?? DEFAULT_MAX_SUMMARY_CHARS);
124
+ // Fail-closed consent gate: never read observations from an unauthorized host.
125
+ const authz = readSourceMaterialAuthorization({
126
+ workspaceDir: input.workspaceDir,
127
+ hostKind: input.candidate.hostKind,
128
+ });
129
+ if (authz.status !== 'authorized') {
130
+ return unknownContext(snapshotCapturedAt);
131
+ }
132
+ const dbPath = resolveTrajectoryDbPath(input.workspaceDir);
133
+ if (!input.databaseFactory && !fs.existsSync(dbPath)) {
134
+ return unknownContext(snapshotCapturedAt);
135
+ }
136
+ let db = null;
137
+ try {
138
+ db = input.databaseFactory
139
+ ? input.databaseFactory(dbPath)
140
+ : new Database(dbPath, { readonly: true, fileMustExist: true });
141
+ const tableExists = db
142
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'governance_observations' LIMIT 1")
143
+ .get();
144
+ if (!tableExists) {
145
+ return unknownContext(snapshotCapturedAt);
146
+ }
147
+ const rawAnchor = db
148
+ .prepare(`SELECT id, rollout_row_id, source_order, observed_at
149
+ FROM governance_observations
150
+ WHERE host_kind = ? AND rollout_identity = ? AND logical_key = ?
151
+ LIMIT 1`)
152
+ .get(input.candidate.hostKind, input.candidate.rolloutIdentity, input.candidate.logicalObservationKey);
153
+ if (!isAnchorRow(rawAnchor)) {
154
+ return unknownContext(snapshotCapturedAt);
155
+ }
156
+ // Ordering safety: if the anchor lacks `source_order` (e.g., live-hook row
157
+ // before transcript convergence), we cannot prove whether earlier backfilled
158
+ // rows preceded it without risking a fabricated 0. Degrade honestly to null.
159
+ if (rawAnchor.source_order === null) {
160
+ return unknownContext(snapshotCapturedAt);
161
+ }
162
+ // Check for mixed ordering within the same rollout: if any active
163
+ // assistant_turn/tool_call row lacks `source_order`, total order is
164
+ // unprovable — degrade honestly to null rather than fabricating 0.
165
+ const rawUnordered = db
166
+ .prepare(`SELECT COUNT(*) AS n
167
+ FROM governance_observations
168
+ WHERE rollout_row_id = ?
169
+ AND kind IN ('assistant_turn', 'tool_call')
170
+ AND retention_class IN ('operational', 'promoted')
171
+ AND source_order IS NULL`)
172
+ .get(rawAnchor.rollout_row_id);
173
+ const unorderedCount = isRecord(rawUnordered) && typeof rawUnordered.n === 'number' ? rawUnordered.n : 0;
174
+ if (unorderedCount > 0) {
175
+ return unknownContext(snapshotCapturedAt);
176
+ }
177
+ const rawPriorRows = db
178
+ .prepare(`SELECT id, kind, visible_text, sanitized_tool_facts_json, source_order
179
+ FROM governance_observations
180
+ WHERE rollout_row_id = ?
181
+ AND kind IN ('assistant_turn', 'tool_call')
182
+ AND retention_class IN ('operational', 'promoted')
183
+ AND (source_order < ? OR (source_order = ? AND id < ?))
184
+ ORDER BY source_order ASC, id ASC`)
185
+ .all(rawAnchor.rollout_row_id, rawAnchor.source_order, rawAnchor.source_order, rawAnchor.id);
186
+ const priorRows = Array.isArray(rawPriorRows)
187
+ ? rawPriorRows.filter(isPriorObservationRow)
188
+ : [];
189
+ let priorAssistantTurnCount = 0;
190
+ const summaries = [];
191
+ for (const row of priorRows) {
192
+ if (row.kind === 'assistant_turn') {
193
+ priorAssistantTurnCount += 1;
194
+ }
195
+ const summary = summarizeObservationRow(row, maxChars);
196
+ if (summary !== null) {
197
+ summaries.push(summary);
198
+ }
199
+ }
200
+ // Keep the most recent bounded window in chronological (old -> new) order.
201
+ const recentAssistantTurns = summaries.length > maxRecent ? summaries.slice(summaries.length - maxRecent) : summaries;
202
+ return {
203
+ priorAssistantTurnCount,
204
+ recentAssistantTurns,
205
+ snapshotCapturedAt,
206
+ };
207
+ }
208
+ catch {
209
+ return unknownContext(snapshotCapturedAt);
210
+ }
211
+ finally {
212
+ if (db !== null) {
213
+ try {
214
+ db.close();
215
+ }
216
+ catch {
217
+ // Ignore close errors on readonly handle.
218
+ }
219
+ }
220
+ }
221
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Trajectory Stall Detector — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R4 (W5).
3
+ *
4
+ * Detects repeated tool-failure loops ("spinning in place") and routes them
5
+ * strictly to the Owner-confirmable Pain Inbox (`governance_signal_admissions`
6
+ * with `signal_kind = 'trajectory_stall'`, `decision = 'inbox_candidate'`).
7
+ * Never writes directly to `pain_events`.
8
+ *
9
+ * Architectural invariants (TD-PD-PAIN-DETECTION-UPGRADE-001 §2.5 / W5):
10
+ * 1. Cross-table deterministic ordering for Codex & WorkBuddy:
11
+ * `tool_calls` is joined to `governance_observations` via
12
+ * `(host_kind, root_session_id = session_id, tool_use_id)` with
13
+ * `kind = 'tool_call'` and `retention_class IN ('operational', 'promoted')`.
14
+ * If ANY tool call in the candidate window matches 0 or >1 observation rows,
15
+ * lacks `tool_use_id`, or has `source_order IS NULL`, returns
16
+ * `status: 'unknown_incomplete'` and skips — NEVER falls back to
17
+ * `tool_calls.created_at`.
18
+ * OpenClaw real-time in-process detection may use `orderMode: 'openclaw_realtime'`
19
+ * which orders directly by monotonic `tc.id DESC` (+ `tc.turn_id`).
20
+ * 2. Structured infrastructure failure classification & null-error degradation:
21
+ * `classifyToolFailureOrigin()` distinguishes `'infrastructure'`,
22
+ * `'actionable_failure'`, and `'unknown'`. Backfilled rows whose
23
+ * `error_type` and `error_message` are both NULL and whose structured
24
+ * facts / preview do not prove a non-infrastructure failure degrade to
25
+ * `'unknown'` and break the streak.
26
+ * 3. Isolation & target path requirement:
27
+ * Strictly isolated by `(host_kind, session_id)`. Both `'success'` and
28
+ * `'unknown'` outcomes, `'infrastructure'` / `'unknown'` failure origins,
29
+ * and missing `normalizedTargetPath` break the consecutive streak.
30
+ * Requires `>= 3` consecutive actionable failures with the same
31
+ * `(toolName, normalizedTargetPath)` fingerprint.
32
+ */
33
+ import type { ObservationDatabaseFactory } from './governance-observation-store.js';
34
+ export declare const DEFAULT_STALL_WINDOW_SIZE = 8;
35
+ export declare const DEFAULT_STALL_MIN_CONSECUTIVE = 3;
36
+ export declare const MAX_STALL_INBOX_PER_SESSION = 2;
37
+ export type StallHostKind = 'codex' | 'workbuddy' | 'openclaw';
38
+ export type ToolFailureOrigin = 'infrastructure' | 'actionable_failure' | 'unknown';
39
+ export interface ClassifyToolFailureOriginInput {
40
+ readonly outcome?: string | null;
41
+ readonly errorType?: string | null;
42
+ readonly errorMessage?: string | null;
43
+ readonly resultPreview?: string | null;
44
+ readonly sanitizedToolFactsJson?: string | null;
45
+ }
46
+ export interface DetectTrajectoryStallInput {
47
+ readonly workspaceDir: string;
48
+ readonly hostKind: StallHostKind;
49
+ readonly sessionId: string;
50
+ /**
51
+ * 'cross_table' (default for Codex/WorkBuddy): requires unique join to
52
+ * `governance_observations` with non-null `source_order`.
53
+ * 'openclaw_realtime': uses monotonic `tool_calls.id DESC` for OpenClaw.
54
+ */
55
+ readonly orderMode?: 'cross_table' | 'openclaw_realtime';
56
+ readonly minConsecutive?: number;
57
+ readonly windowSize?: number;
58
+ readonly now?: Date;
59
+ readonly databaseFactory?: ObservationDatabaseFactory;
60
+ }
61
+ export type DetectTrajectoryStallResult = {
62
+ readonly status: 'stall_detected';
63
+ readonly hostKind: StallHostKind;
64
+ readonly sessionId: string;
65
+ readonly fingerprint: string;
66
+ readonly toolName: string;
67
+ readonly targetPath: string;
68
+ readonly consecutiveFailures: number;
69
+ readonly toolCallIds: readonly number[];
70
+ readonly latestToolCallId: number;
71
+ readonly rolloutIdentity: string;
72
+ } | {
73
+ readonly status: 'no_stall';
74
+ readonly reason: string;
75
+ } | {
76
+ readonly status: 'unknown_incomplete';
77
+ readonly reason: string;
78
+ };
79
+ export interface AdmitTrajectoryStallResult {
80
+ readonly ok: boolean;
81
+ readonly disposition: 'inbox_candidate' | 'already_exists' | 'session_cap_reached' | 'no_stall' | 'unknown_incomplete' | 'unauthorized' | 'db_unavailable';
82
+ readonly logicalObservationKey?: string;
83
+ readonly reason?: string;
84
+ }
85
+ export interface ScanWorkspaceStallsInput {
86
+ readonly workspaceDir: string;
87
+ readonly maxSessionsPerHost?: number;
88
+ readonly now?: Date;
89
+ readonly databaseFactory?: ObservationDatabaseFactory;
90
+ }
91
+ export interface ScanWorkspaceStallsReport {
92
+ readonly scannedSessions: number;
93
+ readonly admittedInboxCandidates: number;
94
+ readonly skippedUnknownIncomplete: number;
95
+ readonly skippedUnauthorized: number;
96
+ readonly scanError?: string;
97
+ }
98
+ /**
99
+ * Pure failure origin classifier (TD §2.5 / W5).
100
+ *
101
+ * - Infrastructure/network/provider/rate-limit/auth errors -> 'infrastructure'
102
+ * - Backfilled rows with NULL errorType & errorMessage and no concrete failure
103
+ * evidence in sanitizedToolFactsJson or resultPreview -> 'unknown'
104
+ * - Concrete non-infrastructure failure evidence -> 'actionable_failure'
105
+ */
106
+ export declare function classifyToolFailureOrigin(input: ClassifyToolFailureOriginInput): ToolFailureOrigin;
107
+ export declare function extractNormalizedTargetPath(paramsJson: string): string | null;
108
+ /**
109
+ * Evaluate whether `(hostKind, sessionId)` is currently in a repeated-failure
110
+ * trajectory stall. Pure read; never mutates the DB.
111
+ */
112
+ export declare function detectTrajectoryStallForSession(input: DetectTrajectoryStallInput): DetectTrajectoryStallResult;
113
+ /**
114
+ * Detect a trajectory stall for `(hostKind, sessionId)` and, if confirmed and
115
+ * authorized, write an Inbox-only candidate (`decision = 'inbox_candidate'`)
116
+ * into `governance_signal_admissions`.
117
+ */
118
+ export declare function detectAndAdmitTrajectoryStall(input: DetectTrajectoryStallInput): AdmitTrajectoryStallResult;
119
+ /**
120
+ * Bounded workspace-wide scan intended to run inside the existing worker cycle
121
+ * (zero new background services). Scans recent `(host_kind, session_id)` pairs
122
+ * with failures in `tool_calls` and admits confirmed stalls into Pain Inbox.
123
+ */
124
+ export declare function scanWorkspaceTrajectoryStalls(input: ScanWorkspaceStallsInput): ScanWorkspaceStallsReport;