@principles/host-runtime 4.10.0 → 4.12.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.
- package/dist/auto-pain-authorization.js +6 -1
- package/dist/conversation-ingestion/consent.d.ts +33 -7
- package/dist/conversation-ingestion/consent.js +240 -42
- package/dist/conversation-ingestion/disclosure.d.ts +21 -0
- package/dist/conversation-ingestion/disclosure.js +74 -0
- package/dist/conversation-ingestion/index.d.ts +1 -0
- package/dist/conversation-ingestion/index.js +1 -0
- package/dist/forward-observation.d.ts +29 -0
- package/dist/forward-observation.js +279 -0
- package/dist/governance-signal-admission.d.ts +6 -1
- package/dist/governance-signal-admission.js +77 -11
- package/dist/idle-turn-audit.d.ts +155 -0
- package/dist/idle-turn-audit.js +786 -0
- package/dist/idle-turn-auditor.d.ts +20 -0
- package/dist/idle-turn-auditor.js +249 -0
- package/dist/index.d.ts +11 -5
- package/dist/index.js +38 -8
- package/dist/pain-inbox.d.ts +137 -0
- package/dist/pain-inbox.js +1020 -0
- package/dist/production-pain-evidence.d.ts +2 -2
- package/dist/production-pain-evidence.js +301 -55
- package/dist/signal-stage2-cycle.d.ts +2 -0
- package/dist/signal-stage2-cycle.js +30 -1
- package/dist/source-revocation-sweep.js +38 -0
- package/dist/stage2-context-hydrator.d.ts +46 -0
- package/dist/stage2-context-hydrator.js +221 -0
- package/dist/trajectory-stall-detector.d.ts +124 -0
- package/dist/trajectory-stall-detector.js +583 -0
- package/package.json +3 -3
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import Database from 'better-sqlite3';
|
|
2
|
-
import { recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
|
|
3
2
|
import type { GovernanceHostKind } from '@principles/core/runtime';
|
|
4
3
|
import type { HostEvent, HostEventEmitter, HostEventResult } from '@principles/core/host';
|
|
5
4
|
export interface ProductionPainEnrichment {
|
|
@@ -35,6 +34,8 @@ declare function hasCanonicalSchema(db: Database.Database): boolean;
|
|
|
35
34
|
export interface VerifiedToolOutcomeInput {
|
|
36
35
|
/** Host tool-call id — the join key written by the live PostToolUse path. */
|
|
37
36
|
readonly toolUseId: string;
|
|
37
|
+
/** Host turn/run identity required for exact v4 correlation; absent stays unlinked. */
|
|
38
|
+
readonly hostTurnId?: string;
|
|
38
39
|
readonly toolName: string;
|
|
39
40
|
readonly params?: unknown;
|
|
40
41
|
/** Verified process exit code from the host's authoritative tool-fact record. */
|
|
@@ -89,6 +90,5 @@ export declare function createProductionPainEvidenceHandler(options?: {
|
|
|
89
90
|
hostKind?: GovernanceHostKind;
|
|
90
91
|
projectDir?: string;
|
|
91
92
|
events?: HostEventEmitter;
|
|
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 };
|
|
@@ -3,10 +3,11 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import Database from 'better-sqlite3';
|
|
5
5
|
import { applyTrajectorySchemaBase, sanitizeToolParams, sanitizeValue, } from '@principles/core/runtime';
|
|
6
|
+
import { claimFirstWriterProvenance, jsonEvidenceTextEquivalent, linkToolCallToOpportunity, recordCoverageDiagnostic } from '@principles/core/runtime/forward-evidence';
|
|
7
|
+
import { forwardObservationScopeAuthorized } from '@principles/core/runtime/forward-observation-scope';
|
|
6
8
|
// PRI-1135: the canonical column declaration lives with the DDL owner. Import
|
|
7
9
|
// the subpath directly so the public runtime barrel surface stays unchanged.
|
|
8
10
|
import { TRAJECTORY_REQUIRED_COLUMNS, convergeTrajectorySchemaVersion } from '@principles/core/runtime/trajectory-schema';
|
|
9
|
-
import { recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
|
|
10
11
|
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
11
12
|
const MAX_PREVIEW = 500;
|
|
12
13
|
function isRecord(value) {
|
|
@@ -276,49 +277,160 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
276
277
|
// Callers without a hostKind keep the historical match-any semantics
|
|
277
278
|
// (explicit compat contract, asserted by tests).
|
|
278
279
|
const findByToolUseId = args.hostKind !== undefined
|
|
279
|
-
? db.prepare('SELECT id, outcome FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ? ORDER BY id LIMIT 1')
|
|
280
|
-
: db.prepare('SELECT id, outcome FROM tool_calls WHERE session_id = ? AND tool_use_id = ? ORDER BY id LIMIT 1');
|
|
281
|
-
const
|
|
282
|
-
|
|
280
|
+
? db.prepare('SELECT id, outcome, turn_id, tool_name, params_json FROM tool_calls WHERE session_id = ? AND tool_use_id = ? AND host_kind = ? ORDER BY id LIMIT 1')
|
|
281
|
+
: db.prepare('SELECT id, outcome, turn_id, tool_name, params_json FROM tool_calls WHERE session_id = ? AND tool_use_id = ? ORDER BY id LIMIT 1');
|
|
282
|
+
const findFullKeyCandidates = args.hostKind !== undefined
|
|
283
|
+
? db.prepare(`SELECT id, outcome, turn_id, tool_name, params_json FROM tool_calls
|
|
284
|
+
WHERE session_id = ? AND tool_use_id = ? AND host_kind = ?
|
|
285
|
+
ORDER BY CASE WHEN turn_id = ? THEN 0 WHEN turn_id IS NULL THEN 1 ELSE 2 END, id LIMIT 4`)
|
|
286
|
+
: null;
|
|
287
|
+
const upgradeUnknown = db.prepare("UPDATE tool_calls SET outcome = ?, exit_code = ?, result_preview = COALESCE(?, result_preview), turn_id = COALESCE(turn_id, ?) WHERE id = ? AND outcome = 'unknown'");
|
|
288
|
+
const insertVerified = db.prepare('INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, host_kind, turn_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
283
289
|
const upsertSession = db.prepare('INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at');
|
|
284
290
|
const createdAt = new Date().toISOString();
|
|
285
|
-
|
|
291
|
+
const database = db;
|
|
292
|
+
database.transaction(() => {
|
|
293
|
+
// Authorization is part of the durable write boundary. Checking it only
|
|
294
|
+
// before schema convergence would leave a revocation/expiry window while
|
|
295
|
+
// the database is opened and migrated.
|
|
296
|
+
const forwardAuthorizedAtWrite = forwardObservationScopeAuthorized(args.workspaceDir);
|
|
286
297
|
for (const input of args.outcomes) {
|
|
287
298
|
if (typeof input.exitCode !== 'number' || !Number.isInteger(input.exitCode))
|
|
288
299
|
continue;
|
|
289
300
|
const finalOutcome = input.exitCode === 0 ? 'success' : 'failure';
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
301
|
+
const sanitizedParams = sanitizeToolParams(input.params ?? {}, args.workspaceDir);
|
|
302
|
+
const inputParamsJson = stable(sanitizedParams);
|
|
303
|
+
let candidate;
|
|
304
|
+
if (args.hostKind !== undefined && input.hostTurnId !== undefined && findFullKeyCandidates !== null) {
|
|
305
|
+
const candidates = findFullKeyCandidates.all(args.sessionId, input.toolUseId, args.hostKind, input.hostTurnId);
|
|
306
|
+
const exactRow = candidates.find((row) => row.turn_id === input.hostTurnId);
|
|
307
|
+
// The host-native exact tuple (session+turn+call id) is the
|
|
308
|
+
// identity authority. Params are evidence content and may serialize
|
|
309
|
+
// differently between live hooks and transcript replay; canonical
|
|
310
|
+
// JSON equivalence therefore decides compatibility. When content is
|
|
311
|
+
// actually contradictory and a forward opportunity can consume the row,
|
|
312
|
+
// verified evidence is preserved separately so the linker quarantines
|
|
313
|
+
// the ambiguity instead of borrowing either projection. Tool-name mismatch remains
|
|
314
|
+
// incompatible.
|
|
315
|
+
const forwardOpportunityAtRisk = forwardAuthorizedAtWrite
|
|
316
|
+
? database.prepare('SELECT 1 AS ok FROM observation_opportunities WHERE host_kind = ? AND host_session_id = ? AND turn_id = ? AND native_tool_call_id = ? LIMIT 1').get(args.hostKind, args.sessionId, input.hostTurnId, input.toolUseId) !== undefined
|
|
317
|
+
: false;
|
|
318
|
+
const evidenceParamsCompatible = (storedParams) => {
|
|
319
|
+
// Outside a forward opportunity this preserves the legacy verified-outcome
|
|
320
|
+
// reconciliation contract. Once an exact forward opportunity can consume
|
|
321
|
+
// the row, contradictory partial evidence must not be silently merged.
|
|
322
|
+
if (!forwardOpportunityAtRisk)
|
|
323
|
+
return true;
|
|
324
|
+
if (storedParams === null || storedParams === undefined)
|
|
325
|
+
return true;
|
|
326
|
+
return typeof storedParams === 'string' && jsonEvidenceTextEquivalent(storedParams, inputParamsJson);
|
|
327
|
+
};
|
|
328
|
+
const exact = exactRow !== undefined && exactRow.tool_name === input.toolName && evidenceParamsCompatible(exactRow.params_json) ? exactRow : undefined;
|
|
329
|
+
const hasDifferentKnownTurn = candidates.some((row) => row.turn_id !== null && row.turn_id !== input.hostTurnId);
|
|
330
|
+
const nullTurnCandidates = candidates.filter((row) => row.turn_id === null);
|
|
331
|
+
// Exact full identity wins. A SINGLE NULL-turn partial may be
|
|
332
|
+
// upgraded only when no same-call-id reuse evidence exists in another
|
|
333
|
+
// known turn; otherwise the partial row is ambiguous and the verified
|
|
334
|
+
// full key must remain a separate write.
|
|
335
|
+
const solePartial = !hasDifferentKnownTurn && nullTurnCandidates.length === 1 && candidates.length === 1 ? nullTurnCandidates[0] : undefined;
|
|
336
|
+
candidate = exact ?? (solePartial !== undefined && solePartial.tool_name === input.toolName && evidenceParamsCompatible(solePartial.params_json) ? solePartial : undefined);
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
candidate = (args.hostKind !== undefined
|
|
340
|
+
? findByToolUseId.get(args.sessionId, input.toolUseId, args.hostKind)
|
|
341
|
+
: findByToolUseId.get(args.sessionId, input.toolUseId));
|
|
342
|
+
}
|
|
343
|
+
// A verified full key must not consume a row from a reused call id in
|
|
344
|
+
// another known turn. Such rows stay unlinked evidence.
|
|
345
|
+
const existing = input.hostTurnId !== undefined && candidate !== undefined && candidate.turn_id !== null && candidate.turn_id !== input.hostTurnId
|
|
346
|
+
? undefined
|
|
347
|
+
: candidate;
|
|
293
348
|
const boundedPreview = typeof input.outputPreview === 'string' && input.outputPreview.length > 0
|
|
294
349
|
? input.outputPreview.slice(0, MAX_PREVIEW)
|
|
295
350
|
: null;
|
|
296
351
|
if (existing !== undefined) {
|
|
297
352
|
if (existing.outcome === 'unknown') {
|
|
298
|
-
upgradeUnknown.run(finalOutcome, input.exitCode, boundedPreview, existing.id);
|
|
353
|
+
upgradeUnknown.run(finalOutcome, input.exitCode, boundedPreview, input.hostTurnId ?? null, existing.id);
|
|
354
|
+
if (args.hostKind !== undefined && forwardAuthorizedAtWrite) {
|
|
355
|
+
linkToolCallToOpportunity(database, {
|
|
356
|
+
hostKind: args.hostKind,
|
|
357
|
+
sessionId: args.sessionId,
|
|
358
|
+
turnId: input.hostTurnId ?? null,
|
|
359
|
+
toolCallId: input.toolUseId,
|
|
360
|
+
toolCallRowid: existing.id,
|
|
361
|
+
outcome: finalOutcome,
|
|
362
|
+
toolName: input.toolName,
|
|
363
|
+
paramsJson: typeof existing.params_json === 'string' ? existing.params_json : inputParamsJson,
|
|
364
|
+
evidenceAt: createdAt,
|
|
365
|
+
});
|
|
366
|
+
}
|
|
299
367
|
results.push({ status: 'updated', id: existing.id });
|
|
300
368
|
}
|
|
301
369
|
else {
|
|
370
|
+
if (args.hostKind !== undefined && forwardAuthorizedAtWrite) {
|
|
371
|
+
// A verified final outcome that contradicts an already-final
|
|
372
|
+
// same-key row must invalidate any derived exact link. Calling
|
|
373
|
+
// the linker lets it compare the durable row with the claimed
|
|
374
|
+
// verified outcome; identical redelivery remains idempotent.
|
|
375
|
+
linkToolCallToOpportunity(database, {
|
|
376
|
+
hostKind: args.hostKind,
|
|
377
|
+
sessionId: args.sessionId,
|
|
378
|
+
turnId: input.hostTurnId ?? null,
|
|
379
|
+
toolCallId: input.toolUseId,
|
|
380
|
+
toolCallRowid: existing.id,
|
|
381
|
+
outcome: finalOutcome,
|
|
382
|
+
toolName: input.toolName,
|
|
383
|
+
paramsJson: typeof existing.params_json === 'string' ? existing.params_json : inputParamsJson,
|
|
384
|
+
evidenceAt: createdAt,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
302
387
|
results.push({ status: 'skipped_final', id: existing.id, reason: 'outcome_already_final' });
|
|
303
388
|
}
|
|
304
389
|
continue;
|
|
305
390
|
}
|
|
306
391
|
upsertSession.run(args.sessionId, createdAt, createdAt);
|
|
307
|
-
const sanitizedParams = sanitizeToolParams(input.params ?? {}, args.workspaceDir);
|
|
308
392
|
// GFI-COMPLETE-REMOVAL-001 follow-up: commit 62e2cab15 dropped the two
|
|
309
393
|
// retired GFI columns from this INSERT but left their placeholder
|
|
310
394
|
// arguments behind, so every verified-outcome write threw
|
|
311
395
|
// "Too many parameter values were provided". Keep the values aligned
|
|
312
396
|
// with the 12 remaining columns.
|
|
313
|
-
const info = insertVerified.run(args.sessionId, input.toolName, finalOutcome, null, input.exitCode, null, null, stable(sanitizedParams), boundedPreview, createdAt, input.toolUseId, args.hostKind ?? null);
|
|
314
|
-
|
|
397
|
+
const info = insertVerified.run(args.sessionId, input.toolName, finalOutcome, null, input.exitCode, null, null, stable(sanitizedParams), boundedPreview, createdAt, input.toolUseId, args.hostKind ?? null, input.hostTurnId ?? null);
|
|
398
|
+
const rowid = Number(info.lastInsertRowid);
|
|
399
|
+
if (args.hostKind !== undefined && forwardAuthorizedAtWrite) {
|
|
400
|
+
claimFirstWriterProvenance(database, {
|
|
401
|
+
hostKind: args.hostKind,
|
|
402
|
+
sessionId: args.sessionId,
|
|
403
|
+
writerKind: 'verified_outcome_ingestion',
|
|
404
|
+
evidenceTable: 'tool_calls',
|
|
405
|
+
evidenceRowid: rowid,
|
|
406
|
+
sourceEventIdentity: { sessionId: args.sessionId, turnId: input.hostTurnId ?? null, toolCallId: input.toolUseId },
|
|
407
|
+
inceptionStatus: 'UNKNOWN',
|
|
408
|
+
identityCompleteness: input.hostTurnId !== undefined ? 'complete' : 'incomplete',
|
|
409
|
+
writeTime: createdAt,
|
|
410
|
+
});
|
|
411
|
+
linkToolCallToOpportunity(database, {
|
|
412
|
+
hostKind: args.hostKind,
|
|
413
|
+
sessionId: args.sessionId,
|
|
414
|
+
turnId: input.hostTurnId ?? null,
|
|
415
|
+
toolCallId: input.toolUseId,
|
|
416
|
+
toolCallRowid: rowid,
|
|
417
|
+
outcome: finalOutcome,
|
|
418
|
+
toolName: input.toolName,
|
|
419
|
+
paramsJson: inputParamsJson,
|
|
420
|
+
evidenceAt: createdAt,
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
results.push({ status: 'inserted', id: rowid });
|
|
315
424
|
}
|
|
316
|
-
})();
|
|
425
|
+
}).immediate();
|
|
317
426
|
}
|
|
318
427
|
catch (error) {
|
|
319
428
|
const reason = `trajectory_write_failed:${error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)}`;
|
|
320
|
-
|
|
321
|
-
|
|
429
|
+
// The transaction is all-or-nothing. Entries pushed inside the transaction
|
|
430
|
+
// are not durable once it throws, so retaining them would report rolled-back
|
|
431
|
+
// writes as verified successes.
|
|
432
|
+
results.length = 0;
|
|
433
|
+
for (let i = 0; i < args.outcomes.length; i += 1)
|
|
322
434
|
results.push({ status: 'unavailable', reason });
|
|
323
435
|
}
|
|
324
436
|
finally {
|
|
@@ -342,9 +454,6 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
342
454
|
* writer. Omitted -> NULL (unknown).
|
|
343
455
|
*/
|
|
344
456
|
export function createProductionPainEvidenceHandler(options = {}) {
|
|
345
|
-
// PD Phase 1.5: sessions whose environment evidence was already captured by
|
|
346
|
-
// THIS handler process — one row per session, not one per tool call.
|
|
347
|
-
const envCapturedSessions = new Set();
|
|
348
457
|
return async (event) => {
|
|
349
458
|
// PRI-750: shared-path tool event with the host's natural turn/tool ids
|
|
350
459
|
// (Codex turn_id → runId, tool_use_id → toolCallId) so receipt events
|
|
@@ -445,6 +554,13 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
445
554
|
let identityConflict = false;
|
|
446
555
|
try {
|
|
447
556
|
db.transaction(() => {
|
|
557
|
+
// Re-read authorization inside the immediate write transaction. The
|
|
558
|
+
// enrichment provider is asynchronous host I/O; a marker valid before
|
|
559
|
+
// that await may have expired, been deleted, or been replaced by the
|
|
560
|
+
// time the durable write begins. Forward evidence must follow the
|
|
561
|
+
// authorization state at the write boundary, not the earlier hook
|
|
562
|
+
// entry point.
|
|
563
|
+
const forwardAuthorizedAtWrite = forwardObservationScopeAuthorized(event.context.workspaceDir);
|
|
448
564
|
// CR-01: the host tool-call id is the stable join key for the
|
|
449
565
|
// consent-gated transcript upgrade (recordVerifiedToolOutcomes);
|
|
450
566
|
// content-shape probing stays the fallback for hosts without ids.
|
|
@@ -453,12 +569,78 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
453
569
|
// NOT this delivery's duplicate, so both hosts keep independent
|
|
454
570
|
// records instead of the second being swallowed.
|
|
455
571
|
if (event.context.toolCallId !== undefined) {
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
572
|
+
// Versioned exact correlation key: session + host-native turn +
|
|
573
|
+
// tool-use id when the host supplied a turn. Partial NULL-turn rows
|
|
574
|
+
// may be upgraded only when they are the SINGLE compatible candidate.
|
|
575
|
+
// Evidence that the host reused the same call id in another turn is
|
|
576
|
+
// ambiguity: never consume the partial row and never exact-link by
|
|
577
|
+
// proximity or content shape.
|
|
578
|
+
let existingRow;
|
|
579
|
+
let ambiguousIdentity = false;
|
|
580
|
+
if (options.hostKind !== undefined && event.context.turnId !== undefined) {
|
|
581
|
+
const candidates = db.prepare('SELECT id, 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 = ? ORDER BY CASE WHEN turn_id = ? THEN 0 WHEN turn_id IS NULL THEN 1 ELSE 2 END, id LIMIT 5')
|
|
582
|
+
.all(event.context.sessionId, event.context.toolCallId, options.hostKind, event.context.turnId);
|
|
583
|
+
const exact = candidates.find((row) => isRecord(row) && row.turn_id === event.context.turnId);
|
|
584
|
+
if (exact !== undefined) {
|
|
585
|
+
existingRow = exact;
|
|
586
|
+
}
|
|
587
|
+
else {
|
|
588
|
+
const nullTurn = candidates.filter((row) => isRecord(row) && (row.turn_id ?? null) === null);
|
|
589
|
+
const differentTurn = candidates.filter((row) => isRecord(row) && row.turn_id !== null && row.turn_id !== event.context.turnId);
|
|
590
|
+
const solePartial = differentTurn.length === 0 && nullTurn.length === 1 && candidates.length === 1 ? nullTurn[0] : undefined;
|
|
591
|
+
if (solePartial !== undefined && isRecord(solePartial) && solePartial.tool_name === toolName && jsonEvidenceTextEquivalent(String(solePartial.params_json), paramsJson)) {
|
|
592
|
+
existingRow = solePartial;
|
|
593
|
+
}
|
|
594
|
+
else if (candidates.length > 0) {
|
|
595
|
+
ambiguousIdentity = true;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
else if (options.hostKind !== undefined) {
|
|
600
|
+
const candidates = db.prepare('SELECT id, 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 = ? ORDER BY id LIMIT 5')
|
|
601
|
+
.all(event.context.sessionId, event.context.toolCallId, options.hostKind);
|
|
602
|
+
existingRow = candidates.length === 1 ? candidates[0] : undefined;
|
|
603
|
+
ambiguousIdentity = candidates.length > 1;
|
|
604
|
+
}
|
|
605
|
+
else {
|
|
606
|
+
existingRow = db.prepare('SELECT id, 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);
|
|
607
|
+
}
|
|
608
|
+
if (ambiguousIdentity && forwardAuthorizedAtWrite) {
|
|
609
|
+
recordCoverageDiagnostic(db, {
|
|
610
|
+
hostKind: options.hostKind ?? null,
|
|
611
|
+
sessionId: event.context.sessionId,
|
|
612
|
+
eventKind: 'after_tool_call',
|
|
613
|
+
diagnosticKind: 'tool_call_identity_ambiguous',
|
|
614
|
+
reason: 'multiple same-call-id candidates exist; incomplete/reused identity is not consumed or exact-linked',
|
|
615
|
+
sourceEventIdentity: { sessionId: event.context.sessionId, turnId: event.context.turnId ?? null, toolCallId: event.context.toolCallId },
|
|
616
|
+
});
|
|
617
|
+
warnings.push('tool_call_identity_ambiguous:multiple same-call-id candidates; evidence preserved without exact reuse');
|
|
618
|
+
}
|
|
459
619
|
const existing = isRecord(existingRow) ? existingRow : undefined;
|
|
460
620
|
if (existing !== undefined) {
|
|
461
621
|
duplicate = true;
|
|
622
|
+
// partial-to-full upgrade: one compatible NULL-turn row receives
|
|
623
|
+
// the host turn key in place. Mutable outcome finalization is
|
|
624
|
+
// upgraded only while the stored outcome is still unknown; a final
|
|
625
|
+
// verified fact is never overwritten by lower-confidence live text.
|
|
626
|
+
if ((existing.turn_id ?? null) === null
|
|
627
|
+
&& event.context.turnId !== undefined
|
|
628
|
+
&& existing.tool_name === toolName
|
|
629
|
+
&& jsonEvidenceTextEquivalent(String(existing.params_json), paramsJson)) {
|
|
630
|
+
if (existing.outcome === 'unknown' && outcome.outcome !== 'unknown') {
|
|
631
|
+
db.prepare('UPDATE tool_calls SET turn_id = ?, outcome = ?, exit_code = ?, error_message = ?, result_preview = ? WHERE id = ?')
|
|
632
|
+
.run(event.context.turnId, outcome.outcome, outcome.exitCode ?? null, outcome.error ?? null, resultPreview, Number(existing.id));
|
|
633
|
+
existing.outcome = outcome.outcome;
|
|
634
|
+
existing.exit_code = outcome.exitCode ?? null;
|
|
635
|
+
existing.error_message = outcome.error ?? null;
|
|
636
|
+
existing.result_preview = resultPreview;
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
db.prepare('UPDATE tool_calls SET turn_id = ? WHERE id = ?')
|
|
640
|
+
.run(event.context.turnId, Number(existing.id));
|
|
641
|
+
}
|
|
642
|
+
existing.turn_id = event.context.turnId;
|
|
643
|
+
}
|
|
462
644
|
// Same physical host-call identity is idempotent only when the
|
|
463
645
|
// evidence content agrees. A same-id/different-content delivery is
|
|
464
646
|
// a conflict: preserve the first evidence and surface the anomaly
|
|
@@ -471,16 +653,43 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
471
653
|
// direction ignores mutable outcome/exit/preview finalization
|
|
472
654
|
// facts while still comparing immutable call facts below.
|
|
473
655
|
const verifiedUpgradeReplay = outcome.outcome === 'unknown' && existing.outcome !== 'unknown';
|
|
656
|
+
const incompleteTurnEvidence = (existing.turn_id ?? null) === null || (event.context.turnId ?? null) === null;
|
|
474
657
|
identityConflict = existing.tool_name !== toolName
|
|
475
|
-
|| (existing.duration_ms ?? null) !== (outcome.durationMs ?? null)
|
|
476
|
-
|| existing.params_json
|
|
477
|
-
|| (existing.turn_id
|
|
478
|
-
|| (!verifiedUpgradeReplay && (existing.outcome !== outcome.outcome
|
|
658
|
+
|| ((existing.duration_ms ?? null) !== null && (outcome.durationMs ?? null) !== null && existing.duration_ms !== outcome.durationMs)
|
|
659
|
+
|| !jsonEvidenceTextEquivalent(String(existing.params_json), paramsJson)
|
|
660
|
+
|| (!incompleteTurnEvidence && existing.turn_id !== event.context.turnId)
|
|
661
|
+
|| (!incompleteTurnEvidence && !verifiedUpgradeReplay && (existing.outcome !== outcome.outcome
|
|
479
662
|
|| (existing.exit_code ?? null) !== (outcome.exitCode ?? null)
|
|
480
663
|
|| (existing.error_message ?? null) !== (outcome.error ?? null)
|
|
481
664
|
|| existing.result_preview !== resultPreview));
|
|
482
665
|
if (identityConflict) {
|
|
483
666
|
warnings.push('tool_call_identity_conflict:same host toolCallId delivered with different evidence content; original row preserved');
|
|
667
|
+
if (options.hostKind !== undefined && forwardAuthorizedAtWrite) {
|
|
668
|
+
linkToolCallToOpportunity(db, {
|
|
669
|
+
hostKind: options.hostKind,
|
|
670
|
+
sessionId: event.context.sessionId,
|
|
671
|
+
turnId: event.context.turnId ?? null,
|
|
672
|
+
toolCallId: event.context.toolCallId ?? null,
|
|
673
|
+
toolCallRowid: Number(existing.id),
|
|
674
|
+
outcome: outcome.outcome,
|
|
675
|
+
toolName,
|
|
676
|
+
paramsJson,
|
|
677
|
+
evidenceAt: createdAt,
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
else if (options.hostKind !== undefined && forwardAuthorizedAtWrite) {
|
|
682
|
+
linkToolCallToOpportunity(db, {
|
|
683
|
+
hostKind: options.hostKind,
|
|
684
|
+
sessionId: event.context.sessionId,
|
|
685
|
+
turnId: event.context.turnId ?? null,
|
|
686
|
+
toolCallId: event.context.toolCallId ?? null,
|
|
687
|
+
toolCallRowid: Number(existing.id),
|
|
688
|
+
outcome: String(existing.outcome),
|
|
689
|
+
toolName,
|
|
690
|
+
paramsJson,
|
|
691
|
+
evidenceAt: createdAt,
|
|
692
|
+
});
|
|
484
693
|
}
|
|
485
694
|
return;
|
|
486
695
|
}
|
|
@@ -498,38 +707,75 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
498
707
|
return;
|
|
499
708
|
}
|
|
500
709
|
db.prepare(`INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at`).run(event.context.sessionId, createdAt, createdAt);
|
|
501
|
-
db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, project_dir, host_kind, turn_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
710
|
+
const insertedToolCall = db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, project_dir, host_kind, turn_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
502
711
|
.run(event.context.sessionId, toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? null, paramsJson, resultPreview, createdAt, event.context.toolCallId ?? null, path.resolve(options.projectDir ?? event.context.workspaceDir), options.hostKind ?? null, event.context.turnId ?? null);
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
712
|
+
const toolCallRowid = Number(insertedToolCall.lastInsertRowid);
|
|
713
|
+
if (options.hostKind !== undefined && forwardAuthorizedAtWrite && event.context.sessionId !== 'openclaw:session-unavailable') {
|
|
714
|
+
claimFirstWriterProvenance(db, {
|
|
715
|
+
hostKind: options.hostKind,
|
|
716
|
+
sessionId: event.context.sessionId,
|
|
717
|
+
writerKind: 'live_tool_call',
|
|
718
|
+
evidenceTable: 'tool_calls',
|
|
719
|
+
evidenceRowid: toolCallRowid,
|
|
720
|
+
sourceEventIdentity: { sessionId: event.context.sessionId, turnId: event.context.turnId ?? null, toolCallId: event.context.toolCallId ?? null },
|
|
721
|
+
inceptionStatus: 'UNKNOWN',
|
|
722
|
+
identityCompleteness: event.context.turnId !== undefined && event.context.toolCallId !== undefined ? 'complete' : 'incomplete',
|
|
723
|
+
writeTime: createdAt,
|
|
724
|
+
});
|
|
725
|
+
const correlation = linkToolCallToOpportunity(db, {
|
|
726
|
+
hostKind: options.hostKind,
|
|
727
|
+
sessionId: event.context.sessionId,
|
|
728
|
+
turnId: event.context.turnId ?? null,
|
|
729
|
+
toolCallId: event.context.toolCallId ?? null,
|
|
730
|
+
toolCallRowid,
|
|
731
|
+
outcome: outcome.outcome,
|
|
732
|
+
toolName,
|
|
733
|
+
paramsJson,
|
|
734
|
+
evidenceAt: createdAt,
|
|
735
|
+
});
|
|
736
|
+
let quarantinedExactAssociation = false;
|
|
737
|
+
if (event.context.turnId === undefined && event.context.toolCallId !== undefined) {
|
|
738
|
+
// A newly inserted turn-less row cannot be attributed to a host
|
|
739
|
+
// turn. If an exact association for the same host/session/call id
|
|
740
|
+
// already exists, that durable ambiguity affects the old exact
|
|
741
|
+
// link too. Re-run the exact linker inside this same transaction
|
|
742
|
+
// instead of leaving a stale linked_exact cache alive merely
|
|
743
|
+
// because the turn-less evidence arrived after the exact row.
|
|
744
|
+
const exactAssociations = db.prepare(`SELECT opportunity_id, turn_id, tool_call_rowid FROM observation_opportunities
|
|
745
|
+
WHERE host_kind = ? AND host_session_id = ? AND native_tool_call_id = ?
|
|
746
|
+
AND turn_id IS NOT NULL AND tool_call_rowid IS NOT NULL AND correlation_status = 'linked_exact'`)
|
|
747
|
+
.all(options.hostKind, event.context.sessionId, event.context.toolCallId);
|
|
748
|
+
for (const associationRow of exactAssociations) {
|
|
749
|
+
if (!isRecord(associationRow) || typeof associationRow.turn_id !== 'string' || typeof associationRow.tool_call_rowid !== 'number')
|
|
750
|
+
continue;
|
|
751
|
+
const evidenceRow = db.prepare('SELECT outcome, tool_name, params_json FROM tool_calls WHERE rowid = ?').get(associationRow.tool_call_rowid);
|
|
752
|
+
if (!isRecord(evidenceRow) || typeof evidenceRow.outcome !== 'string' || typeof evidenceRow.tool_name !== 'string')
|
|
753
|
+
continue;
|
|
754
|
+
const relink = linkToolCallToOpportunity(db, {
|
|
755
|
+
hostKind: options.hostKind,
|
|
756
|
+
sessionId: event.context.sessionId,
|
|
757
|
+
turnId: associationRow.turn_id,
|
|
758
|
+
toolCallId: event.context.toolCallId,
|
|
759
|
+
toolCallRowid: associationRow.tool_call_rowid,
|
|
760
|
+
outcome: evidenceRow.outcome,
|
|
761
|
+
toolName: evidenceRow.tool_name,
|
|
762
|
+
...(typeof evidenceRow.params_json === 'string' ? { paramsJson: evidenceRow.params_json } : {}),
|
|
763
|
+
evidenceAt: createdAt,
|
|
764
|
+
});
|
|
765
|
+
quarantinedExactAssociation ||= relink.status === 'conflict';
|
|
766
|
+
}
|
|
531
767
|
}
|
|
768
|
+
// Incomplete/orphan exact correlation is a normal coverage state for
|
|
769
|
+
// hosts whose Pre identity is unavailable and is already persisted in
|
|
770
|
+
// observation_coverage_diagnostics. Do not turn every otherwise
|
|
771
|
+
// successful Post write into a user-visible hook degradation; only a
|
|
772
|
+
// same-key evidence conflict is anomalous enough to surface here.
|
|
773
|
+
if (correlation.status === 'conflict' || quarantinedExactAssociation)
|
|
774
|
+
warnings.push('forward_post_correlation_conflict');
|
|
532
775
|
}
|
|
776
|
+
// PRI-1333 P0-2 cutover: PostToolUse must not mint legacy session-first
|
|
777
|
+
// research snapshots. Event-scoped before_tool_call captures are owned
|
|
778
|
+
// by forward-observation.ts; historical NULL-linked rows remain read-only.
|
|
533
779
|
// The dedupe probes above must hold the write lock before reading:
|
|
534
780
|
// otherwise two processes can both observe no row and both insert the
|
|
535
781
|
// same physical redelivery. `.immediate()` serializes that check-write
|
|
@@ -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
|
|
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
|