@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
|
@@ -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
|
+
}
|
|
@@ -176,7 +176,7 @@ export type AdmitGovernanceSignalsResult = {
|
|
|
176
176
|
export declare function admitGovernanceSignals(input: AdmitGovernanceSignalsInput): AdmitGovernanceSignalsResult;
|
|
177
177
|
export interface PendingReviewResult {
|
|
178
178
|
readonly ok: true;
|
|
179
|
-
readonly disposition: 'admitted' | 'resolved_none' | 'pending' | 'abandoned' | 'concurrent_loss' | 'not_pending';
|
|
179
|
+
readonly disposition: 'admitted' | 'inbox_candidate' | 'resolved_none' | 'pending' | 'abandoned' | 'concurrent_loss' | 'not_pending';
|
|
180
180
|
readonly logicalObservationKey: string;
|
|
181
181
|
readonly canonicalPainId?: string;
|
|
182
182
|
readonly taskId?: string;
|
|
@@ -272,6 +272,11 @@ export interface CompletePendingReviewInput {
|
|
|
272
272
|
readonly claimToken: string;
|
|
273
273
|
/** `null` = the classifier produced no usable verdict (timeout/exception). */
|
|
274
274
|
readonly llmResult: LlmClassificationResult | null;
|
|
275
|
+
/**
|
|
276
|
+
* SPEC-PD-PAIN-DETECTION-UPGRADE-001 R1-2 (Gate 3): host-hydrated count of
|
|
277
|
+
* prior assistant turns in this rollout (`null` = unknown, `0` = proven none).
|
|
278
|
+
*/
|
|
279
|
+
readonly priorAssistantTurnCount?: number | null;
|
|
275
280
|
readonly now?: Date;
|
|
276
281
|
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
277
282
|
}
|
|
@@ -35,7 +35,9 @@ import fs from 'node:fs';
|
|
|
35
35
|
import path from 'node:path';
|
|
36
36
|
import { randomUUID } from 'node:crypto';
|
|
37
37
|
import Database from 'better-sqlite3';
|
|
38
|
-
import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, fingerprintStatement, isOwnerManualCorrectionEvidence, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
|
|
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
|
/**
|
|
@@ -580,7 +604,7 @@ function parsePendingReviewMeta(value) {
|
|
|
580
604
|
return null;
|
|
581
605
|
const verdict = own(reviewRaw, 'verdict');
|
|
582
606
|
if (verdict !== 'correction' && verdict !== 'none'
|
|
583
|
-
&& verdict !== 'pending_low_confidence' && verdict !== 'pending_llm_error')
|
|
607
|
+
&& verdict !== 'inbox_candidate' && verdict !== 'pending_low_confidence' && verdict !== 'pending_llm_error')
|
|
584
608
|
return null;
|
|
585
609
|
const confidence = own(reviewRaw, 'confidence');
|
|
586
610
|
if (confidence !== null && (typeof confidence !== 'number' || !Number.isFinite(confidence)))
|
|
@@ -1416,7 +1440,9 @@ export function recordPendingCorrectionReview(input) {
|
|
|
1416
1440
|
if (currentClaimToken === undefined || currentClaimToken !== input.claimToken) {
|
|
1417
1441
|
return { ok: true, disposition: 'concurrent_loss', logicalObservationKey: input.logicalObservationKey, attempts: parsed.payload.review.attempts, reason: 'claim_not_owned' };
|
|
1418
1442
|
}
|
|
1419
|
-
const gate = evaluateStage2ConfidenceGate(input.llmResult
|
|
1443
|
+
const gate = evaluateStage2ConfidenceGate(input.llmResult, undefined, input.priorAssistantTurnCount !== undefined
|
|
1444
|
+
? { priorAssistantTurnCount: input.priorAssistantTurnCount }
|
|
1445
|
+
: undefined);
|
|
1420
1446
|
const attempts = parsed.payload.review.attempts + 1;
|
|
1421
1447
|
const reviewResult = { verdict: gate.verdict, confidence: gate.confidence, reason: gate.reason };
|
|
1422
1448
|
const nextPayload = {
|
|
@@ -1509,6 +1535,41 @@ export async function settlePendingCorrection(input) {
|
|
|
1509
1535
|
}
|
|
1510
1536
|
return { ok: true, disposition: 'abandoned', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'ttl_expired' };
|
|
1511
1537
|
}
|
|
1538
|
+
if (review.verdict === 'inbox_candidate') {
|
|
1539
|
+
const capRow = db.prepare(`
|
|
1540
|
+
SELECT COUNT(*) AS n
|
|
1541
|
+
FROM governance_signal_admissions
|
|
1542
|
+
WHERE host_kind = ?
|
|
1543
|
+
AND root_session_id = ?
|
|
1544
|
+
AND signal_kind = 'user_correction'
|
|
1545
|
+
AND decision IN ('inbox_candidate', 'inbox_approving')
|
|
1546
|
+
`).get(hostKind, rootSessionId);
|
|
1547
|
+
if ((capRow?.n ?? 0) >= 2) {
|
|
1548
|
+
const { changes } = db.prepare(`UPDATE governance_signal_admissions SET decision = 'abandoned', reason = ?, task_payload_json = ?, updated_at = ?
|
|
1549
|
+
WHERE logical_observation_key = ? AND decision = 'pending_llm_review' AND task_payload_json = ?`)
|
|
1550
|
+
.run('inbox_cap_reached', pendingTerminalPayload({ decision: 'abandoned', reason: 'inbox_cap_reached', attempts: payload.review.attempts, confidence: review.confidence, nowIso }), nowIso, input.logicalObservationKey, payloadText);
|
|
1551
|
+
if (changes !== 1) {
|
|
1552
|
+
return { ok: true, disposition: 'concurrent_loss', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'cas_lost' };
|
|
1553
|
+
}
|
|
1554
|
+
return { ok: true, disposition: 'abandoned', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'inbox_cap_reached' };
|
|
1555
|
+
}
|
|
1556
|
+
const inboxPayload = {
|
|
1557
|
+
...payload,
|
|
1558
|
+
inbox: {
|
|
1559
|
+
signalKind: 'mid_confidence_correction',
|
|
1560
|
+
confidence: review.confidence,
|
|
1561
|
+
reason: review.reason.slice(0, MAX_REASON_BOUND),
|
|
1562
|
+
routedAt: nowIso,
|
|
1563
|
+
},
|
|
1564
|
+
};
|
|
1565
|
+
const { changes } = db.prepare(`UPDATE governance_signal_admissions SET decision = 'inbox_candidate', reason = ?, task_payload_json = ?, updated_at = ?
|
|
1566
|
+
WHERE logical_observation_key = ? AND decision = 'pending_llm_review' AND task_payload_json = ?`)
|
|
1567
|
+
.run(review.reason.slice(0, MAX_REASON_BOUND) || 'stage2_inbox_candidate', JSON.stringify(inboxPayload), nowIso, input.logicalObservationKey, payloadText);
|
|
1568
|
+
if (changes !== 1) {
|
|
1569
|
+
return { ok: true, disposition: 'concurrent_loss', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: 'cas_lost' };
|
|
1570
|
+
}
|
|
1571
|
+
return { ok: true, disposition: 'inbox_candidate', logicalObservationKey: input.logicalObservationKey, attempts: payload.review.attempts, reason: review.reason };
|
|
1572
|
+
}
|
|
1512
1573
|
if (review.verdict !== 'correction' && review.verdict !== 'none') {
|
|
1513
1574
|
if (payload.review.attempts >= STAGE2_MAX_ATTEMPTS) {
|
|
1514
1575
|
const reason = review.verdict === 'pending_llm_error' ? 'llm_error' : 'low_confidence';
|
|
@@ -1773,7 +1834,7 @@ function isGovernanceTaskPayload(value) {
|
|
|
1773
1834
|
if (!isRecord(value))
|
|
1774
1835
|
return false;
|
|
1775
1836
|
const painType = own(value, 'painType');
|
|
1776
|
-
if (painType !== 'user_frustration' && painType !== 'tool_failure')
|
|
1837
|
+
if (painType !== 'user_frustration' && painType !== 'tool_failure' && painType !== 'principle_deviation')
|
|
1777
1838
|
return false;
|
|
1778
1839
|
for (const key of ['source', 'reason', 'sessionId']) {
|
|
1779
1840
|
const candidate = own(value, key);
|
|
@@ -1841,6 +1902,9 @@ function isGovernanceTaskPayload(value) {
|
|
|
1841
1902
|
if (typeof note !== 'string' || note.length > MAX_SANITIZED_NOTE_CHARS)
|
|
1842
1903
|
return false;
|
|
1843
1904
|
}
|
|
1905
|
+
const painIngress = own(value, 'painIngress');
|
|
1906
|
+
if (painIngress !== undefined && !parsePainIngressV1Payload(painIngress).ok)
|
|
1907
|
+
return false;
|
|
1844
1908
|
return true;
|
|
1845
1909
|
}
|
|
1846
1910
|
/**
|
|
@@ -1967,10 +2031,11 @@ export async function ensureGovernanceDiagnosticianTask(input) {
|
|
|
1967
2031
|
// from trajectory.db with the full lineage tuple. A marker that references a
|
|
1968
2032
|
// non-existent observation (or a WorkBuddy automatic correction) evaluates
|
|
1969
2033
|
// to observation_only and fails closed below.
|
|
1970
|
-
// A tool_failure pain
|
|
1971
|
-
//
|
|
1972
|
-
//
|
|
1973
|
-
|
|
2034
|
+
// A tool_failure or principle_deviation pain carries its own validated
|
|
2035
|
+
// ingress evidence; neither is a user-correction claim about behavior.
|
|
2036
|
+
// Only user-frustration corrections are gated on re-derived observation
|
|
2037
|
+
// evidence.
|
|
2038
|
+
const isCorrectionPayload = payloadParsed.painType === 'user_frustration';
|
|
1974
2039
|
const ingressEvidence = isCorrectionPayload && (markerHostKind === 'codex' || markerHostKind === 'workbuddy')
|
|
1975
2040
|
? (sourceMaterialReadable
|
|
1976
2041
|
? correctionIngressEvidence({
|
|
@@ -2142,6 +2207,7 @@ export async function ensureGovernanceDiagnosticianTask(input) {
|
|
|
2142
2207
|
// workbuddy markers attribute 'workbuddy').
|
|
2143
2208
|
hostKind: payloadParsed.hostKind,
|
|
2144
2209
|
evidence: [...ingressEvidence],
|
|
2210
|
+
...(payloadParsed.painIngress !== undefined ? { painIngress: payloadParsed.painIngress } : {}),
|
|
2145
2211
|
// CR-02: replay the explicit Owner statement verbatim (classified,
|
|
2146
2212
|
// channel-disclosed) so re-created tasks keep the same input basis.
|
|
2147
2213
|
...(payloadParsed.correctionEvidence !== undefined
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Idle Turn Lightweight Audit — SPEC-PD-PAIN-DETECTION-UPGRADE-001 R5 (W6).
|
|
3
|
+
*
|
|
4
|
+
* Performs a bounded, budget-protected post-turn review of idle sessions
|
|
5
|
+
* (`>= 5` turns and idle `>= 5` minutes after true turn completion) and routes
|
|
6
|
+
* verified principle deviations strictly to Pain Inbox
|
|
7
|
+
* (`governance_signal_admissions`, `signal_kind = 'idle_audit_deviation'`,
|
|
8
|
+
* `decision = 'inbox_candidate'`). Never writes directly to `pain_events`.
|
|
9
|
+
*
|
|
10
|
+
* Architectural invariants (TD-PD-PAIN-DETECTION-UPGRADE-001 §2.6 / W6):
|
|
11
|
+
* 1. Accurate turn-end trigger (zero new background services):
|
|
12
|
+
* - Codex / WorkBuddy update `idle_audit_session_activity` on `Stop`.
|
|
13
|
+
* - OpenClaw registers native `agent_end` (never relying solely on
|
|
14
|
+
* `llm_output`). Legacy hosts without `agent_end` require `has_active_run = 0`.
|
|
15
|
+
* 2. Real prompt injection evidence + immutable artifact version + lifecycle:
|
|
16
|
+
* - Visibility is proved ONLY from `runtime_v2_prompt_activations_injected`
|
|
17
|
+
* events (`principleIds`, `activationIds`, `artifactIds`, `runId`,
|
|
18
|
+
* `hostKind`, `eventId`) — never from `environment_snapshots`.
|
|
19
|
+
* - `principleVersion` is resolved strictly from immutable `pi_artifacts`
|
|
20
|
+
* via `artifactIds`.
|
|
21
|
+
* - Because `activations` uses `INSERT OR REPLACE` and `PRI-932`
|
|
22
|
+
* (`activation_lifecycle_events`) is still DRAFT, if `activations` shows
|
|
23
|
+
* reactivation overwrite (`activated_at > observedAt`), missing lifecycle
|
|
24
|
+
* bounds, or missing immutable `principleVersion`, MUST return
|
|
25
|
+
* `verdict: 'INCONCLUSIVE'` — never infer historical state from current
|
|
26
|
+
* state and never fabricate a `deviationAnchor`.
|
|
27
|
+
* 3. Atomic daily budget persistence (`idle_audit_daily_budgets`):
|
|
28
|
+
* - Stored inside existing `trajectory.db`.
|
|
29
|
+
* - Reserved via `BEGIN IMMEDIATE` transaction BEFORE calling the LLM
|
|
30
|
+
* (default 10 calls / workspace / UTC day). Timeouts (`<= 25s`) keep the
|
|
31
|
+
* 1 consumed unit (never refunded or double-charged).
|
|
32
|
+
*/
|
|
33
|
+
import Database from 'better-sqlite3';
|
|
34
|
+
import type { ObservationDatabaseFactory } from './governance-observation-store.js';
|
|
35
|
+
export declare const DEFAULT_IDLE_AUDIT_MIN_TURNS = 5;
|
|
36
|
+
export declare const DEFAULT_IDLE_AUDIT_IDLE_MS: number;
|
|
37
|
+
export declare const DEFAULT_IDLE_AUDIT_DAILY_LIMIT = 10;
|
|
38
|
+
export declare const DEFAULT_IDLE_AUDIT_TIMEOUT_MS = 25000;
|
|
39
|
+
export type IdleAuditHostKind = 'codex' | 'workbuddy' | 'openclaw';
|
|
40
|
+
export type IdleTurnEndSource = 'agent_end' | 'stop_hook' | 'legacy_idle_check';
|
|
41
|
+
export interface RecordTurnCompletedInput {
|
|
42
|
+
readonly workspaceDir: string;
|
|
43
|
+
readonly hostKind: IdleAuditHostKind;
|
|
44
|
+
readonly sessionId: string;
|
|
45
|
+
readonly turnEndSource: IdleTurnEndSource;
|
|
46
|
+
readonly completedAt?: Date;
|
|
47
|
+
readonly hasActiveRun?: boolean;
|
|
48
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
49
|
+
}
|
|
50
|
+
export interface ReserveDailyBudgetInput {
|
|
51
|
+
readonly workspaceDir: string;
|
|
52
|
+
readonly dailyLimit?: number;
|
|
53
|
+
readonly now?: Date;
|
|
54
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
55
|
+
}
|
|
56
|
+
export interface ReserveDailyBudgetResult {
|
|
57
|
+
readonly reserved: boolean;
|
|
58
|
+
readonly workspaceKey: string;
|
|
59
|
+
readonly utcDay: string;
|
|
60
|
+
readonly usedCount: number;
|
|
61
|
+
readonly dailyLimit: number;
|
|
62
|
+
readonly reason?: 'daily_budget_exhausted' | 'db_error';
|
|
63
|
+
}
|
|
64
|
+
export interface VerifiedDeviationAnchor {
|
|
65
|
+
readonly principleId: string;
|
|
66
|
+
readonly principleVersion: string;
|
|
67
|
+
readonly activationId: string;
|
|
68
|
+
readonly artifactId: string;
|
|
69
|
+
readonly eventId: string | null;
|
|
70
|
+
}
|
|
71
|
+
export type PrincipleVisibilityVerdict = {
|
|
72
|
+
readonly verdict: 'PROVEN';
|
|
73
|
+
readonly deviationAnchor: VerifiedDeviationAnchor;
|
|
74
|
+
} | {
|
|
75
|
+
readonly verdict: 'INCONCLUSIVE';
|
|
76
|
+
readonly reason: 'no_logs' | 'missing_injection_event' | 'missing_state_db' | 'missing_immutable_principle_version' | 'activation_lifecycle_overwritten_or_out_of_window' | 'verification_error';
|
|
77
|
+
};
|
|
78
|
+
export interface VerifyPrincipleVisibilityInput {
|
|
79
|
+
readonly workspaceDir: string;
|
|
80
|
+
readonly stateDir?: string;
|
|
81
|
+
readonly eventLogStateDir?: string;
|
|
82
|
+
readonly hostKind: IdleAuditHostKind;
|
|
83
|
+
readonly sessionId: string;
|
|
84
|
+
readonly principleId: string;
|
|
85
|
+
readonly observedAt: string;
|
|
86
|
+
readonly runId?: string;
|
|
87
|
+
readonly stateDbFactory?: ObservationDatabaseFactory;
|
|
88
|
+
}
|
|
89
|
+
export interface IdleAuditSessionCandidate {
|
|
90
|
+
readonly hostKind: IdleAuditHostKind;
|
|
91
|
+
readonly sessionId: string;
|
|
92
|
+
readonly rolloutIdentity: string;
|
|
93
|
+
readonly turnCount: number;
|
|
94
|
+
readonly lastObservationId: string;
|
|
95
|
+
readonly lastTurnCompletedAt: string;
|
|
96
|
+
readonly turnEndSource: string;
|
|
97
|
+
}
|
|
98
|
+
export interface IdleAuditLlmFinding {
|
|
99
|
+
readonly detected: boolean;
|
|
100
|
+
readonly principleId?: string;
|
|
101
|
+
readonly observedAt?: string;
|
|
102
|
+
readonly runId?: string;
|
|
103
|
+
readonly excerpt?: string;
|
|
104
|
+
readonly confidence?: number;
|
|
105
|
+
readonly reasoning?: string;
|
|
106
|
+
}
|
|
107
|
+
export type IdleTurnAuditor = (candidate: IdleAuditSessionCandidate) => Promise<IdleAuditLlmFinding | null>;
|
|
108
|
+
export interface RunIdleTurnAuditCycleInput {
|
|
109
|
+
readonly workspaceDir: string;
|
|
110
|
+
readonly stateDir?: string;
|
|
111
|
+
readonly eventLogStateDir?: string;
|
|
112
|
+
readonly auditor: IdleTurnAuditor | null;
|
|
113
|
+
readonly minTurns?: number;
|
|
114
|
+
readonly idleThresholdMs?: number;
|
|
115
|
+
readonly dailyLimit?: number;
|
|
116
|
+
readonly auditTimeoutMs?: number;
|
|
117
|
+
readonly now?: Date;
|
|
118
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
119
|
+
readonly stateDbFactory?: ObservationDatabaseFactory;
|
|
120
|
+
}
|
|
121
|
+
export interface RunIdleTurnAuditCycleReport {
|
|
122
|
+
readonly ok: boolean;
|
|
123
|
+
readonly auditedSessions: number;
|
|
124
|
+
readonly admittedInboxCandidates: number;
|
|
125
|
+
readonly inconclusiveCount: number;
|
|
126
|
+
readonly timedOutCount: number;
|
|
127
|
+
readonly budgetReserved: boolean;
|
|
128
|
+
readonly skippedReason?: string;
|
|
129
|
+
readonly idempotencyKey?: string;
|
|
130
|
+
}
|
|
131
|
+
export declare function ensureIdleAuditSchema(db: Database.Database): void;
|
|
132
|
+
/**
|
|
133
|
+
* Record an accurate turn-end timestamp (`agent_end` for OpenClaw, `stop_hook`
|
|
134
|
+
* for Codex/WorkBuddy) into `idle_audit_session_activity`.
|
|
135
|
+
*/
|
|
136
|
+
export declare function recordIdleAuditTurnCompleted(input: RecordTurnCompletedInput): {
|
|
137
|
+
ok: boolean;
|
|
138
|
+
reason?: string;
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* Atomically reserve 1 daily LLM audit slot for `(workspace_key, utc_day)`
|
|
142
|
+
* using a SQLite `BEGIN IMMEDIATE` transaction (W6).
|
|
143
|
+
*/
|
|
144
|
+
export declare function reserveIdleAuditDailyBudget(input: ReserveDailyBudgetInput): ReserveDailyBudgetResult;
|
|
145
|
+
/**
|
|
146
|
+
* Verify that `principleId` was genuinely injected into the turn, resolve its
|
|
147
|
+
* immutable `principleVersion` via `artifactIds`, and verify `activations`
|
|
148
|
+
* lifecycle contains `observedAt` without overwrite (W6).
|
|
149
|
+
*/
|
|
150
|
+
export declare function verifyPrincipleVisibilityForAudit(input: VerifyPrincipleVisibilityInput): PrincipleVisibilityVerdict;
|
|
151
|
+
/**
|
|
152
|
+
* Run one bounded Idle Turn Audit cycle (at most 1 eligible idle session per
|
|
153
|
+
* worker tick, zero new background daemons).
|
|
154
|
+
*/
|
|
155
|
+
export declare function runIdleTurnAuditCycle(input: RunIdleTurnAuditCycleInput): Promise<RunIdleTurnAuditCycleReport>;
|