@principles/host-runtime 4.9.4 → 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.
@@ -89,6 +89,6 @@ export declare function createProductionPainEvidenceHandler(options?: {
89
89
  hostKind?: GovernanceHostKind;
90
90
  projectDir?: string;
91
91
  events?: HostEventEmitter;
92
- environmentProvider?: () => Pick<NonNullable<Parameters<typeof recordEnvironmentSnapshot>[1]>, 'hostVersion' | 'runtimeVersion' | 'agentConfigDigest' | 'modelConfigDigest' | 'repoCommit' | 'workspaceStateDigest' | 'featureFlagsDigest'>;
92
+ environmentProvider?: (event: HostEvent) => Pick<NonNullable<Parameters<typeof recordEnvironmentSnapshot>[1]>, 'hostVersion' | 'runtimeVersion' | 'agentConfigDigest' | 'modelConfigDigest' | 'repoCommit' | 'workspaceStateDigest' | 'featureFlagsDigest'>;
93
93
  }): (event: HostEvent) => Promise<HostEventResult>;
94
94
  export { hasCanonicalSchema as hasProductionPainSchema };
@@ -442,6 +442,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
442
442
  const paramsJson = stable(sanitizedParams);
443
443
  const resultPreview = preview({ eventId, result: sanitizeValue(outcome.result, 0, event.context.workspaceDir) });
444
444
  let duplicate = false;
445
+ let identityConflict = false;
445
446
  try {
446
447
  db.transaction(() => {
447
448
  // CR-01: the host tool-call id is the stable join key for the
@@ -451,18 +452,48 @@ export function createProductionPainEvidenceHandler(options = {}) {
451
452
  // colliding row from ANOTHER host (or an unattributed legacy row) is
452
453
  // NOT this delivery's duplicate, so both hosts keep independent
453
454
  // records instead of the second being swallowed.
454
- if (event.context.toolCallId !== undefined
455
- && (options.hostKind !== undefined
456
- ? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?').get(event.context.sessionId, event.context.toolCallId, options.hostKind)
457
- : db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(event.context.sessionId, event.context.toolCallId)) !== undefined) {
458
- duplicate = true;
459
- return;
455
+ if (event.context.toolCallId !== undefined) {
456
+ const existingRow = options.hostKind !== undefined
457
+ ? db.prepare('SELECT tool_name, outcome, duration_ms, exit_code, error_message, params_json, result_preview, turn_id FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?').get(event.context.sessionId, event.context.toolCallId, options.hostKind)
458
+ : db.prepare('SELECT tool_name, outcome, duration_ms, exit_code, error_message, params_json, result_preview, turn_id FROM tool_calls WHERE session_id = ? AND tool_use_id = ?').get(event.context.sessionId, event.context.toolCallId);
459
+ const existing = isRecord(existingRow) ? existingRow : undefined;
460
+ if (existing !== undefined) {
461
+ duplicate = true;
462
+ // Same physical host-call identity is idempotent only when the
463
+ // evidence content agrees. A same-id/different-content delivery is
464
+ // a conflict: preserve the first evidence and surface the anomaly
465
+ // rather than splitting the call or overwriting history.
466
+ // CR-01 upgrades a live `unknown` row in place when verified
467
+ // transcript evidence arrives. Receiving that same original
468
+ // low-confidence live observation again must not be misclassified
469
+ // as a conflict merely because the durable row is now final. The
470
+ // schema has no separate first-delivery fingerprint, so this
471
+ // direction ignores mutable outcome/exit/preview finalization
472
+ // facts while still comparing immutable call facts below.
473
+ const verifiedUpgradeReplay = outcome.outcome === 'unknown' && existing.outcome !== 'unknown';
474
+ identityConflict = existing.tool_name !== toolName
475
+ || (existing.duration_ms ?? null) !== (outcome.durationMs ?? null)
476
+ || existing.params_json !== paramsJson
477
+ || (existing.turn_id ?? null) !== (event.context.turnId ?? null)
478
+ || (!verifiedUpgradeReplay && (existing.outcome !== outcome.outcome
479
+ || (existing.exit_code ?? null) !== (outcome.exitCode ?? null)
480
+ || (existing.error_message ?? null) !== (outcome.error ?? null)
481
+ || existing.result_preview !== resultPreview));
482
+ if (identityConflict) {
483
+ warnings.push('tool_call_identity_conflict:same host toolCallId delivered with different evidence content; original row preserved');
484
+ }
485
+ return;
486
+ }
460
487
  }
461
488
  // Review R3/P2: the content-shape fallback dedup is host-scoped the
462
- // same way — identical content from two hosts is two records.
463
- if ((options.hostKind !== undefined
464
- ? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ? AND host_kind = ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview, options.hostKind)
465
- : db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview)) !== undefined) {
489
+ // same way — identical content from two hosts is two records. It is
490
+ // only a fallback for hosts WITHOUT a physical call id: once the host
491
+ // supplies toolCallId, a different id is a different physical call even
492
+ // when the bounded content fingerprint happens to match.
493
+ if (event.context.toolCallId === undefined
494
+ && (options.hostKind !== undefined
495
+ ? db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ? AND host_kind = ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview, options.hostKind)
496
+ : db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?').get(event.context.sessionId, toolName, paramsJson, outcome.outcome, outcome.exitCode, outcome.error ?? null, resultPreview)) !== undefined) {
466
497
  duplicate = true;
467
498
  return;
468
499
  }
@@ -476,9 +507,8 @@ export function createProductionPainEvidenceHandler(options = {}) {
476
507
  // Capture failure degrades to a warning and never blocks the tool
477
508
  // evidence write (rc-9).
478
509
  if (!envCapturedSessions.has(event.context.sessionId)) {
479
- envCapturedSessions.add(event.context.sessionId);
480
510
  try {
481
- const env = options.environmentProvider?.();
511
+ const env = options.environmentProvider?.(event);
482
512
  recordEnvironmentSnapshot(db, {
483
513
  sessionId: event.context.sessionId,
484
514
  captureKind: 'after_tool_call',
@@ -494,12 +524,17 @@ export function createProductionPainEvidenceHandler(options = {}) {
494
524
  capturedAt: createdAt,
495
525
  payload: {},
496
526
  });
527
+ envCapturedSessions.add(event.context.sessionId);
497
528
  }
498
529
  catch (envError) {
499
530
  warnings.push(`environment_snapshot_failed:${envError instanceof Error ? envError.message.slice(0, 200) : String(envError).slice(0, 200)}`);
500
531
  }
501
532
  }
502
- })();
533
+ // The dedupe probes above must hold the write lock before reading:
534
+ // otherwise two processes can both observe no row and both insert the
535
+ // same physical redelivery. `.immediate()` serializes that check-write
536
+ // critical section without introducing a second writer mechanism.
537
+ }).immediate();
503
538
  }
504
539
  catch (error) {
505
540
  return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), `trajectory_write_failed:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`], metadata: { outcome: outcome.outcome, duplicate: false, nextAction: 'inspect the workspace trajectory database and retry' } };
@@ -515,7 +550,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
515
550
  source: event.source,
516
551
  ...(emissionWarning || warnings.length > 0 ? { warnings: [...(emissionWarning ? [emissionWarning] : []), ...warnings] } : {}),
517
552
  metadata: {
518
- eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate,
553
+ eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate, ...(identityConflict ? { identityConflict: true } : {}),
519
554
  }
520
555
  };
521
556
  };
@@ -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;