@principles/host-runtime 4.11.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/forward-observation.d.ts +29 -0
- package/dist/forward-observation.js +279 -0
- package/dist/governance-signal-admission.js +27 -3
- package/dist/index.d.ts +6 -5
- package/dist/index.js +33 -8
- package/dist/production-pain-evidence.d.ts +2 -2
- package/dist/production-pain-evidence.js +301 -55
- package/package.json +3 -3
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { HostEvent, HostEventResult } from '@principles/core/host';
|
|
2
|
+
import type { AfterToolCallEnvironmentFacts } from './environment-facts.js';
|
|
3
|
+
export interface ForwardObservationOptions {
|
|
4
|
+
hostKind?: string;
|
|
5
|
+
environmentProvider?: (event: HostEvent) => AfterToolCallEnvironmentFacts;
|
|
6
|
+
}
|
|
7
|
+
export declare function forwardObservationScopeAuthorized(workspaceDir: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Persist the opportunity and its event-scoped pre-gate environment snapshot
|
|
10
|
+
* in one immediate transaction. Returns null when evidence is unavailable;
|
|
11
|
+
* callers must continue the production gate regardless.
|
|
12
|
+
*/
|
|
13
|
+
export declare function capturePreGateOpportunity(event: HostEvent, options: ForwardObservationOptions): {
|
|
14
|
+
opportunityId: string | null;
|
|
15
|
+
warnings: string[];
|
|
16
|
+
};
|
|
17
|
+
export declare function recordForwardGateDecision(input: {
|
|
18
|
+
event: HostEvent;
|
|
19
|
+
result: HostEventResult;
|
|
20
|
+
opportunityId: string;
|
|
21
|
+
hostKind?: string;
|
|
22
|
+
}): string[];
|
|
23
|
+
/** Best-effort close-boundary observation for Stop/turn_complete hooks. */
|
|
24
|
+
export declare function observeForwardTurnClose(args: {
|
|
25
|
+
workspaceDir: string;
|
|
26
|
+
hostKind: 'codex' | 'workbuddy';
|
|
27
|
+
sessionId: string;
|
|
28
|
+
turnId?: string;
|
|
29
|
+
}): string[];
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-decision forward observation wrapper.
|
|
3
|
+
*
|
|
4
|
+
* One narrow host-runtime seam: it runs inside the shared production
|
|
5
|
+
* before_tool_call route BEFORE gate evaluation and before the gate's
|
|
6
|
+
* tool-class scope decisions. Research-write failure is observable in result
|
|
7
|
+
* warnings/metadata and never changes the production tool decision.
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import Database from 'better-sqlite3';
|
|
11
|
+
import { recordCoverageDiagnostic, recordObservationOpportunity, recordOpportunityGateDecision, markTurnCloseObserved, } from '@principles/core/runtime/forward-evidence';
|
|
12
|
+
import { forwardObservationScopeAuthorized as coreForwardObservationScopeAuthorized } from '@principles/core/runtime/forward-observation-scope';
|
|
13
|
+
import { convergeTrajectorySchemaVersion, recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
|
|
14
|
+
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
15
|
+
export function forwardObservationScopeAuthorized(workspaceDir) {
|
|
16
|
+
return coreForwardObservationScopeAuthorized(workspaceDir);
|
|
17
|
+
}
|
|
18
|
+
function bounded(error) {
|
|
19
|
+
return (error instanceof Error ? error.message : String(error)).replace(/\s+/g, ' ').slice(0, 220);
|
|
20
|
+
}
|
|
21
|
+
function gateAction(result, hostKind) {
|
|
22
|
+
if (result.decision === 'deny' || result.decision === 'modify' || result.decision === 'observe')
|
|
23
|
+
return result.decision;
|
|
24
|
+
if (result.metadata?.evaluationStatus === 'failed' || result.metadata?.evaluatedLiveRules === 0)
|
|
25
|
+
return 'unevaluated';
|
|
26
|
+
const metadataDecision = result.metadata?.decision;
|
|
27
|
+
const ruleDecision = result.metadata?.ruleDecision;
|
|
28
|
+
const evaluations = result.metadata?.evaluations;
|
|
29
|
+
const evaluationDecision = Array.isArray(evaluations) && typeof evaluations[0] === 'object' && evaluations[0] !== null
|
|
30
|
+
? evaluations[0].decision
|
|
31
|
+
: undefined;
|
|
32
|
+
if (metadataDecision === 'requireApproval' || ruleDecision === 'requireApproval' || evaluationDecision === 'requireApproval')
|
|
33
|
+
return 'requireApproval';
|
|
34
|
+
if (ruleDecision === 'auto_correct' || evaluationDecision === 'auto_correct') {
|
|
35
|
+
// Codex cannot encode or apply modified tool input. An auto_correct
|
|
36
|
+
// proposal there is therefore not a modify action; the host-visible
|
|
37
|
+
// outcome is an allow and the unapplied proposal is preserved in the
|
|
38
|
+
// decision reason below.
|
|
39
|
+
if (hostKind === 'codex' && result.modifiedInput === undefined)
|
|
40
|
+
return 'allow';
|
|
41
|
+
return 'modify';
|
|
42
|
+
}
|
|
43
|
+
if (result.decision !== 'allow')
|
|
44
|
+
return 'unevaluated';
|
|
45
|
+
const failOpenWarning = (result.warnings ?? []).some((warning) => [
|
|
46
|
+
'activation_db_not_found', 'gate_deadline_exceeded', 'global_rulecode_pause_active',
|
|
47
|
+
'rule_context_provider_failed', 'rule_context_invalid', 'rule_batch_result_missing',
|
|
48
|
+
].some((prefix) => warning.startsWith(prefix) || warning.includes(`:${prefix}`)));
|
|
49
|
+
const evaluationFaults = Array.isArray(result.metadata?.evaluationFaults) ? result.metadata.evaluationFaults : [];
|
|
50
|
+
const liveEvaluationFault = evaluationFaults.some((fault) => fault.mode === 'live' || fault.mode === undefined);
|
|
51
|
+
if (failOpenWarning || liveEvaluationFault)
|
|
52
|
+
return 'unevaluated';
|
|
53
|
+
return 'allow';
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Persist the opportunity and its event-scoped pre-gate environment snapshot
|
|
57
|
+
* in one immediate transaction. Returns null when evidence is unavailable;
|
|
58
|
+
* callers must continue the production gate regardless.
|
|
59
|
+
*/
|
|
60
|
+
export function capturePreGateOpportunity(event, options) {
|
|
61
|
+
const warnings = [];
|
|
62
|
+
if (!forwardObservationScopeAuthorized(event.context.workspaceDir)) {
|
|
63
|
+
return { opportunityId: null, warnings: [] };
|
|
64
|
+
}
|
|
65
|
+
const dbPath = resolveTrajectoryDbPath(event.context.workspaceDir);
|
|
66
|
+
if (!fs.existsSync(dbPath)) {
|
|
67
|
+
return { opportunityId: null, warnings: [] };
|
|
68
|
+
}
|
|
69
|
+
let db;
|
|
70
|
+
let opportunityId = null;
|
|
71
|
+
try {
|
|
72
|
+
db = new Database(dbPath);
|
|
73
|
+
db.pragma('busy_timeout = 100');
|
|
74
|
+
convergeTrajectorySchemaVersion(db);
|
|
75
|
+
const capturedAt = new Date().toISOString();
|
|
76
|
+
const database = db;
|
|
77
|
+
let authorizationAtWrite = false;
|
|
78
|
+
database.transaction(() => {
|
|
79
|
+
// Authorization must survive lock acquisition, not merely the earlier
|
|
80
|
+
// hook-entry check. If it is revoked while another writer holds the DB,
|
|
81
|
+
// this transaction observes the revocation before any forward row is written.
|
|
82
|
+
authorizationAtWrite = forwardObservationScopeAuthorized(event.context.workspaceDir);
|
|
83
|
+
if (!authorizationAtWrite)
|
|
84
|
+
return;
|
|
85
|
+
const opportunity = recordObservationOpportunity(database, {
|
|
86
|
+
hostKind: options.hostKind ?? 'unknown',
|
|
87
|
+
sessionId: event.context.sessionId,
|
|
88
|
+
turnId: event.context.turnId ?? null,
|
|
89
|
+
toolCallId: event.context.toolCallId ?? null,
|
|
90
|
+
toolName: event.context.toolName ?? 'unknown',
|
|
91
|
+
params: event.context.toolInput ?? {},
|
|
92
|
+
workspaceDir: event.context.workspaceDir,
|
|
93
|
+
preReceivedAt: capturedAt,
|
|
94
|
+
});
|
|
95
|
+
({ opportunityId } = opportunity);
|
|
96
|
+
// Environment evidence is scoped to the opportunity but must not
|
|
97
|
+
// destroy the opportunity when an adapter supplies malformed facts.
|
|
98
|
+
// Keep both writes inside the outer pre-gate transaction; a savepoint
|
|
99
|
+
// rolls back only the snapshot attempt, then persists explicit coverage
|
|
100
|
+
// loss in the same atomic unit as the surviving opportunity.
|
|
101
|
+
database.exec('SAVEPOINT forward_environment_capture');
|
|
102
|
+
try {
|
|
103
|
+
const facts = options.environmentProvider?.(event) ?? {};
|
|
104
|
+
recordEnvironmentSnapshot(database, {
|
|
105
|
+
sessionId: event.context.sessionId,
|
|
106
|
+
opportunityId,
|
|
107
|
+
captureKind: 'before_tool_call',
|
|
108
|
+
hostKind: options.hostKind ?? null,
|
|
109
|
+
hostVersion: facts.hostVersion ?? null,
|
|
110
|
+
runtimeVersion: facts.runtimeVersion === null || facts.runtimeVersion === undefined ? null : facts.runtimeVersion.startsWith('pd-hook-node:') ? facts.runtimeVersion : 'pd-hook-node:' + facts.runtimeVersion,
|
|
111
|
+
agentConfigDigest: facts.agentConfigDigest ?? null,
|
|
112
|
+
modelConfigDigest: facts.modelConfigDigest ?? null,
|
|
113
|
+
repoCommit: facts.repoCommit ?? null,
|
|
114
|
+
workspaceStateDigest: facts.workspaceStateDigest ?? null,
|
|
115
|
+
featureFlagsDigest: facts.featureFlagsDigest ?? null,
|
|
116
|
+
captureSchemaVersion: 'pd-environment-snapshot.v2',
|
|
117
|
+
capturedAt,
|
|
118
|
+
payload: {},
|
|
119
|
+
conflictSignal(reason) {
|
|
120
|
+
recordCoverageDiagnostic(database, {
|
|
121
|
+
hostKind: options.hostKind ?? null,
|
|
122
|
+
sessionId: event.context.sessionId,
|
|
123
|
+
eventKind: event.kind,
|
|
124
|
+
diagnosticKind: 'environment_capture_conflict',
|
|
125
|
+
reason,
|
|
126
|
+
sourceEventIdentity: { opportunityId },
|
|
127
|
+
});
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
database.exec('RELEASE SAVEPOINT forward_environment_capture');
|
|
131
|
+
}
|
|
132
|
+
catch (environmentError) {
|
|
133
|
+
database.exec('ROLLBACK TO SAVEPOINT forward_environment_capture');
|
|
134
|
+
database.exec('RELEASE SAVEPOINT forward_environment_capture');
|
|
135
|
+
const reason = bounded(environmentError);
|
|
136
|
+
recordCoverageDiagnostic(database, {
|
|
137
|
+
hostKind: options.hostKind ?? null,
|
|
138
|
+
sessionId: event.context.sessionId,
|
|
139
|
+
eventKind: event.kind,
|
|
140
|
+
diagnosticKind: 'environment_capture_failed',
|
|
141
|
+
reason,
|
|
142
|
+
sourceEventIdentity: { opportunityId },
|
|
143
|
+
});
|
|
144
|
+
warnings.push(`forward_environment_capture_failed:${reason}; nextAction=inspect_adapter_environment_facts`);
|
|
145
|
+
}
|
|
146
|
+
}).immediate();
|
|
147
|
+
if (!authorizationAtWrite)
|
|
148
|
+
opportunityId = null;
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
warnings.push(`forward_opportunity_write_failed:${bounded(error)}; nextAction=inspect_trajectory_storage`);
|
|
152
|
+
opportunityId = null;
|
|
153
|
+
try {
|
|
154
|
+
if (db !== undefined && forwardObservationScopeAuthorized(event.context.workspaceDir)) {
|
|
155
|
+
recordCoverageDiagnostic(db, {
|
|
156
|
+
hostKind: options.hostKind ?? null,
|
|
157
|
+
sessionId: event.context.sessionId,
|
|
158
|
+
eventKind: event.kind,
|
|
159
|
+
diagnosticKind: 'forward_opportunity_write_failed',
|
|
160
|
+
reason: bounded(error),
|
|
161
|
+
sourceEventIdentity: {
|
|
162
|
+
sessionId: event.context.sessionId,
|
|
163
|
+
turnId: event.context.turnId ?? null,
|
|
164
|
+
toolCallId: event.context.toolCallId ?? null,
|
|
165
|
+
toolName: event.context.toolName ?? null,
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
// The primary failure is already surfaced; diagnostic persistence is best-effort.
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
try {
|
|
176
|
+
db?.close();
|
|
177
|
+
}
|
|
178
|
+
catch { /* cleanup never changes the hook result */ }
|
|
179
|
+
}
|
|
180
|
+
return { opportunityId, warnings };
|
|
181
|
+
}
|
|
182
|
+
export function recordForwardGateDecision(input) {
|
|
183
|
+
const { event, result, opportunityId, hostKind } = input;
|
|
184
|
+
const warnings = [];
|
|
185
|
+
if (!forwardObservationScopeAuthorized(event.context.workspaceDir)) {
|
|
186
|
+
return ['forward_gate_decision_not_recorded:synthetic_scope_unavailable'];
|
|
187
|
+
}
|
|
188
|
+
const dbPath = resolveTrajectoryDbPath(event.context.workspaceDir);
|
|
189
|
+
let db;
|
|
190
|
+
try {
|
|
191
|
+
db = new Database(dbPath);
|
|
192
|
+
db.pragma('busy_timeout = 100');
|
|
193
|
+
const evaluations = Array.isArray(result.metadata?.evaluations) ? result.metadata.evaluations : [];
|
|
194
|
+
const liveEvaluation = evaluations.find((item) => item.activationMode === 'live');
|
|
195
|
+
let authorizationAtWrite = false;
|
|
196
|
+
const database = db;
|
|
197
|
+
database.transaction(() => {
|
|
198
|
+
// The gate is asynchronous host work. The decision write must revalidate
|
|
199
|
+
// after acquiring the write lock so expiry/revocation during evaluation
|
|
200
|
+
// cannot authorize a late forward row.
|
|
201
|
+
authorizationAtWrite = forwardObservationScopeAuthorized(event.context.workspaceDir);
|
|
202
|
+
if (!authorizationAtWrite)
|
|
203
|
+
return;
|
|
204
|
+
recordOpportunityGateDecision(database, opportunityId, {
|
|
205
|
+
action: gateAction(result, hostKind),
|
|
206
|
+
reason: (result.metadata?.ruleDecision === 'auto_correct' && hostKind === 'codex' && result.modifiedInput === undefined)
|
|
207
|
+
? `correction_proposal_unapplied:${typeof result.metadata.ruleReason === 'string' ? result.metadata.ruleReason : 'codex_encoder_cannot_apply_modified_input'}`
|
|
208
|
+
: result.reason ?? null,
|
|
209
|
+
ruleId: typeof liveEvaluation?.ruleId === 'string' ? liveEvaluation.ruleId : null,
|
|
210
|
+
activationId: typeof liveEvaluation?.activationId === 'string' ? liveEvaluation.activationId : null,
|
|
211
|
+
decidedAt: new Date().toISOString(),
|
|
212
|
+
});
|
|
213
|
+
}).immediate();
|
|
214
|
+
if (!authorizationAtWrite)
|
|
215
|
+
warnings.push('forward_gate_decision_not_recorded:synthetic_scope_unavailable');
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
warnings.push(`forward_gate_decision_write_failed:${bounded(error)}`);
|
|
219
|
+
try {
|
|
220
|
+
if (db !== undefined && forwardObservationScopeAuthorized(event.context.workspaceDir)) {
|
|
221
|
+
recordCoverageDiagnostic(db, {
|
|
222
|
+
hostKind: hostKind ?? null,
|
|
223
|
+
sessionId: event.context.sessionId,
|
|
224
|
+
eventKind: event.kind,
|
|
225
|
+
diagnosticKind: 'forward_gate_decision_write_failed',
|
|
226
|
+
reason: bounded(error),
|
|
227
|
+
sourceEventIdentity: { opportunityId },
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
catch { /* primary warning survives */ }
|
|
232
|
+
}
|
|
233
|
+
finally {
|
|
234
|
+
try {
|
|
235
|
+
db?.close();
|
|
236
|
+
}
|
|
237
|
+
catch { /* best-effort cleanup */ }
|
|
238
|
+
}
|
|
239
|
+
return warnings;
|
|
240
|
+
}
|
|
241
|
+
/** Best-effort close-boundary observation for Stop/turn_complete hooks. */
|
|
242
|
+
export function observeForwardTurnClose(args) {
|
|
243
|
+
if (!forwardObservationScopeAuthorized(args.workspaceDir))
|
|
244
|
+
return [];
|
|
245
|
+
if (args.turnId === undefined || args.turnId.trim().length === 0) {
|
|
246
|
+
return ['forward_close_incomplete:turn_id_missing'];
|
|
247
|
+
}
|
|
248
|
+
const { turnId } = args;
|
|
249
|
+
const dbPath = resolveTrajectoryDbPath(args.workspaceDir);
|
|
250
|
+
if (!fs.existsSync(dbPath))
|
|
251
|
+
return [];
|
|
252
|
+
let db;
|
|
253
|
+
try {
|
|
254
|
+
db = new Database(dbPath);
|
|
255
|
+
db.pragma('busy_timeout = 100');
|
|
256
|
+
const database = db;
|
|
257
|
+
database.transaction(() => {
|
|
258
|
+
// Close evidence is forward-only: validate inside the write-lock boundary.
|
|
259
|
+
if (!forwardObservationScopeAuthorized(args.workspaceDir))
|
|
260
|
+
return;
|
|
261
|
+
markTurnCloseObserved(database, {
|
|
262
|
+
hostKind: args.hostKind,
|
|
263
|
+
sessionId: args.sessionId,
|
|
264
|
+
turnId,
|
|
265
|
+
closeEvidenceKind: args.hostKind === 'codex' ? 'codex_stop_candidate' : 'workbuddy_stop_exact',
|
|
266
|
+
});
|
|
267
|
+
}).immediate();
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
return [`forward_close_write_failed:${bounded(error)}`];
|
|
272
|
+
}
|
|
273
|
+
finally {
|
|
274
|
+
try {
|
|
275
|
+
db?.close();
|
|
276
|
+
}
|
|
277
|
+
catch { /* best-effort */ }
|
|
278
|
+
}
|
|
279
|
+
}
|
|
@@ -36,6 +36,8 @@ import path from 'node:path';
|
|
|
36
36
|
import { randomUUID } from 'node:crypto';
|
|
37
37
|
import Database from 'better-sqlite3';
|
|
38
38
|
import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, fingerprintStatement, isOwnerManualCorrectionEvidence, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, parsePainIngressV1Payload, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
|
|
39
|
+
import { claimFirstWriterProvenance, invalidateSessionNoPainLabelsAfterPain } from '@principles/core/runtime/forward-evidence';
|
|
40
|
+
import { forwardObservationScopeAuthorized } from '@principles/core/runtime/forward-observation-scope';
|
|
39
41
|
import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
|
|
40
42
|
import { convergeTrajectorySchemaVersion } from '@principles/core/runtime/trajectory-schema';
|
|
41
43
|
import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
|
|
@@ -451,9 +453,31 @@ function insertCorrectionPain({ db, candidate, workspaceDir, painId, reason, now
|
|
|
451
453
|
// is NOT used here: buildEvidence already truncated it upstream, so a token
|
|
452
454
|
// straddling that cut would survive sanitization the same way.
|
|
453
455
|
const excerpt = sanitizeString(candidate.text, workspaceDir);
|
|
454
|
-
db.
|
|
455
|
-
|
|
456
|
-
|
|
456
|
+
db.transaction(() => {
|
|
457
|
+
const result = db.prepare(`INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, host_kind, created_at)
|
|
458
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
459
|
+
.run(candidate.rootSessionId, 'user_correction', GOVERNANCE_STRONG_PAIN_SCORE, reason.slice(0, MAX_REASON_BOUND), 'severe', 'system_infer', null, excerpt, painId, null, candidate.hostKind, nowIso);
|
|
460
|
+
if (forwardObservationScopeAuthorized(workspaceDir)) {
|
|
461
|
+
claimFirstWriterProvenance(db, {
|
|
462
|
+
hostKind: candidate.hostKind,
|
|
463
|
+
sessionId: candidate.rootSessionId,
|
|
464
|
+
writerKind: 'correction_pain_writer',
|
|
465
|
+
evidenceTable: 'pain_events',
|
|
466
|
+
evidenceRowid: Number(result.lastInsertRowid),
|
|
467
|
+
sourceEventIdentity: {
|
|
468
|
+
sessionId: candidate.rootSessionId,
|
|
469
|
+
hostTurnId: candidate.hostTurnId,
|
|
470
|
+
canonicalPainId: painId,
|
|
471
|
+
},
|
|
472
|
+
writeTime: nowIso,
|
|
473
|
+
});
|
|
474
|
+
invalidateSessionNoPainLabelsAfterPain(db, {
|
|
475
|
+
hostKind: candidate.hostKind,
|
|
476
|
+
sessionId: candidate.rootSessionId,
|
|
477
|
+
observedAt: nowIso,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
})();
|
|
457
481
|
return reason;
|
|
458
482
|
}
|
|
459
483
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ export * from './production-rulehost-gate.js';
|
|
|
20
20
|
export * from './rule-implementation-runtime.js';
|
|
21
21
|
export * from './production-pain-evidence.js';
|
|
22
22
|
export * from './environment-facts.js';
|
|
23
|
+
export * from './forward-observation.js';
|
|
23
24
|
export * from './governance-observation-store.js';
|
|
24
25
|
export * from './governance-trajectory-turn-reader.js';
|
|
25
26
|
export * from './plugin-trajectory-turn-store.js';
|
|
@@ -101,11 +102,11 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
|
|
|
101
102
|
/** Host project cwd, distinct from the workspace owning shared PD state. */
|
|
102
103
|
projectDir?: string;
|
|
103
104
|
/**
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
* allow-listed fields exist — an
|
|
107
|
-
*
|
|
108
|
-
* secret-bearing value.
|
|
105
|
+
* Adapter-known environment facts for the event-scoped pre-gate opportunity
|
|
106
|
+
* capture used by authorized E0 synthetic fixtures. PostToolUse no longer
|
|
107
|
+
* writes environment snapshots. Only these allow-listed fields exist — an
|
|
108
|
+
* adapter that does not know a fact omits it and the row records NULL
|
|
109
|
+
* (unknown), never a guess and never a secret-bearing value.
|
|
109
110
|
*/
|
|
110
111
|
afterToolCallEnvironment?: AfterToolCallEnvironmentFacts | ((event: HostEvent) => AfterToolCallEnvironmentFacts);
|
|
111
112
|
/** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
|
package/dist/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { loadPdConfigForPlugin } from './pd-config.js';
|
|
|
5
5
|
import { buildActivePrinciplePromptContext } from './active-principle-prompt.js';
|
|
6
6
|
import { createProductionRuleHostGate } from './production-rulehost-gate.js';
|
|
7
7
|
import { createProductionPainEvidenceHandler } from './production-pain-evidence.js';
|
|
8
|
+
import { capturePreGateOpportunity, recordForwardGateDecision } from './forward-observation.js';
|
|
8
9
|
export * from './active-principle-prompt.js';
|
|
9
10
|
export * from './prompt-activation-authority.js';
|
|
10
11
|
export * from './prompt-injection-projection.js';
|
|
@@ -32,6 +33,7 @@ export * from './production-rulehost-gate.js';
|
|
|
32
33
|
export * from './rule-implementation-runtime.js';
|
|
33
34
|
export * from './production-pain-evidence.js';
|
|
34
35
|
export * from './environment-facts.js';
|
|
36
|
+
export * from './forward-observation.js';
|
|
35
37
|
export * from './governance-observation-store.js';
|
|
36
38
|
// PRI-1265: the governance-observation-backed TrajectoryTurnReader injected by
|
|
37
39
|
// pd-cli diagnose/pain retry and the Codex/WorkBuddy workers.
|
|
@@ -266,15 +268,38 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
266
268
|
...(options.hostKind ? { hostKind: options.hostKind } : {}),
|
|
267
269
|
...(options.projectDir ? { projectDir: options.projectDir } : {}),
|
|
268
270
|
...(options.events ? { events: options.events } : {}),
|
|
269
|
-
// PD Phase 1.5 (SPEC R10): adapter-supplied environment facts for the
|
|
270
|
-
// forward evidence capture; fields the adapter omits stay NULL.
|
|
271
|
-
...(afterToolCallEnvironment ? {
|
|
272
|
-
environmentProvider: typeof afterToolCallEnvironment === 'function'
|
|
273
|
-
? afterToolCallEnvironment
|
|
274
|
-
: () => afterToolCallEnvironment,
|
|
275
|
-
} : {}),
|
|
276
271
|
}),
|
|
277
|
-
beforeToolCall:
|
|
272
|
+
beforeToolCall: (() => {
|
|
273
|
+
const gate = options.beforeToolCall ?? productionGate;
|
|
274
|
+
const environmentProvider = typeof afterToolCallEnvironment === 'function'
|
|
275
|
+
? afterToolCallEnvironment
|
|
276
|
+
: afterToolCallEnvironment !== undefined
|
|
277
|
+
? () => afterToolCallEnvironment
|
|
278
|
+
: undefined;
|
|
279
|
+
return async (event) => {
|
|
280
|
+
const capture = capturePreGateOpportunity(event, {
|
|
281
|
+
...(options.hostKind !== undefined ? { hostKind: options.hostKind } : {}),
|
|
282
|
+
...(environmentProvider !== undefined ? { environmentProvider } : {}),
|
|
283
|
+
});
|
|
284
|
+
const result = await gate(event);
|
|
285
|
+
const decisionWarnings = capture.opportunityId === null
|
|
286
|
+
? []
|
|
287
|
+
: recordForwardGateDecision({ event, result, opportunityId: capture.opportunityId, hostKind: options.hostKind });
|
|
288
|
+
const warnings = [...capture.warnings, ...decisionWarnings];
|
|
289
|
+
if (warnings.length === 0)
|
|
290
|
+
return result;
|
|
291
|
+
return {
|
|
292
|
+
...result,
|
|
293
|
+
warnings: [...(result.warnings ?? []).slice(0, 15), ...warnings].slice(0, 16),
|
|
294
|
+
metadata: {
|
|
295
|
+
...(result.metadata ?? {}),
|
|
296
|
+
forwardOpportunity: capture.opportunityId === null
|
|
297
|
+
? { status: 'write_degraded' }
|
|
298
|
+
: { status: 'persisted', opportunityId: capture.opportunityId },
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
};
|
|
302
|
+
})(),
|
|
278
303
|
async beforePromptBuild(event) {
|
|
279
304
|
// PRI-904 Phase-1 (Option 3): Codex never writes
|
|
280
305
|
// trajectory.db::user_turns — its ingestion writes governance_* rows
|
|
@@ -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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.12.0",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"lint": "eslint \"src/**/*.ts\""
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@principles/core": "^9.
|
|
42
|
+
"@principles/core": "^9.1.0",
|
|
43
43
|
"@principles/install-layout": "^0.12.0",
|
|
44
44
|
"better-sqlite3": "^13.0.3",
|
|
45
45
|
"js-yaml": "^5.4.3"
|
|
@@ -57,5 +57,5 @@
|
|
|
57
57
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
58
58
|
},
|
|
59
59
|
"license": "Apache-2.0",
|
|
60
|
-
"gitHead": "
|
|
60
|
+
"gitHead": "e14270ad721ec3a3352d629bb8254be81842cc38"
|
|
61
61
|
}
|