@principles/host-runtime 4.11.0 → 5.0.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/codex-disclosure.d.ts +1 -1
- package/dist/codex-disclosure.js +1 -1
- package/dist/diagnostician-auto-run.d.ts +1 -1
- package/dist/diagnostician-auto-run.js +15 -1
- package/dist/forward-observation.d.ts +29 -0
- package/dist/forward-observation.js +279 -0
- package/dist/governance-signal-admission.js +52 -6
- package/dist/index.d.ts +6 -5
- package/dist/index.js +33 -8
- package/dist/pain-inbox.d.ts +8 -0
- package/dist/pain-inbox.js +115 -1
- package/dist/production-pain-evidence.d.ts +2 -2
- package/dist/production-pain-evidence.js +301 -55
- package/dist/production-rulehost-gate.js +0 -19
- package/package.json +3 -3
- package/dist/legacy-rule-contract-symbols.d.ts +0 -20
- package/dist/legacy-rule-contract-symbols.js +0 -124
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D),
|
|
3
3
|
* amended by the Owner decision recorded as "Amendment 2 — disclosure v2"
|
|
4
4
|
* (2026-11-12) in:
|
|
5
|
-
*
|
|
5
|
+
* packages/host-runtime/tests/fixtures/codex-governance-closure-g0-g2a-decision.md
|
|
6
6
|
* § "Frozen consent disclosure text (setup will show this verbatim)"
|
|
7
7
|
*
|
|
8
8
|
* That document is the language SSoT. The frozen text "must not be weakened
|
package/dist/codex-disclosure.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Codex conversation-ingestion consent disclosure — G2A frozen text (Slice D),
|
|
3
3
|
* amended by the Owner decision recorded as "Amendment 2 — disclosure v2"
|
|
4
4
|
* (2026-11-12) in:
|
|
5
|
-
*
|
|
5
|
+
* packages/host-runtime/tests/fixtures/codex-governance-closure-g0-g2a-decision.md
|
|
6
6
|
* § "Frozen consent disclosure text (setup will show this verbatim)"
|
|
7
7
|
*
|
|
8
8
|
* That document is the language SSoT. The frozen text "must not be weakened
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
export declare const DIAGNOSTICIAN_AUTO_RUN_FLAG = "openclaw_diagnostician_consumer";
|
|
3
3
|
/** Owner string used for the diagnostics this module starts. */
|
|
4
4
|
export declare const DIAGNOSTICIAN_AUTO_RUN_OWNER = "pd-auto-diagnostician";
|
|
5
|
-
export type PendingDiagnosticianSkipReason = 'flag_off' | 'capability_disabled' | 'service_not_running' | 'no_candidate' | 'auto_pain_unauthorized';
|
|
5
|
+
export type PendingDiagnosticianSkipReason = 'flag_off' | 'capability_disabled' | 'service_not_running' | 'no_candidate' | 'auto_pain_unauthorized' | 'source_authorization_blocked' | 'candidate_changed';
|
|
6
6
|
export interface PendingDiagnosticianRunResult {
|
|
7
7
|
readonly served: boolean;
|
|
8
8
|
readonly taskId?: string;
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import * as path from 'node:path';
|
|
21
21
|
import { PrincipleTreeLedgerAdapter, createPainSignalBridge, createRuntimeStateHandle, pickDiagnosticianCandidate, resolveDiagnosticianCapability, } from '@principles/core/runtime';
|
|
22
22
|
import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js';
|
|
23
|
+
import { executeQueuedDiagnosisWithInboxRecovery } from './pain-inbox.js';
|
|
23
24
|
import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
|
|
24
25
|
import { resolveWorkspacePipelineHostDeps } from './workspace-pipeline-host-deps.js';
|
|
25
26
|
/** Quiet flag that owns the L3 half of the ladder. */
|
|
@@ -132,7 +133,20 @@ export async function runPendingDiagnosticianOnce(options) {
|
|
|
132
133
|
// execution still stops the run at the bridge boundary.
|
|
133
134
|
isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
|
|
134
135
|
}, (release) => { releaseBridge = release; });
|
|
135
|
-
const executed = await
|
|
136
|
+
const executed = await executeQueuedDiagnosisWithInboxRecovery({
|
|
137
|
+
workspaceDir: options.workspaceDir, task: candidate, stateManager: handle.stateManager,
|
|
138
|
+
execute: () => bridge.executePendingDiagnosis({ taskId: candidate.taskId }),
|
|
139
|
+
});
|
|
140
|
+
if (executed.status === 'skipped'
|
|
141
|
+
&& (executed.message === 'auto_pain_unauthorized' || executed.message === 'source_authorization_blocked'
|
|
142
|
+
|| executed.message === 'candidate_changed')) {
|
|
143
|
+
return {
|
|
144
|
+
served: false, taskId: candidate.taskId, reason: executed.message,
|
|
145
|
+
nextAction: executed.message === 'candidate_changed'
|
|
146
|
+
? 'The candidate changed during repair; the next worker cycle can retry.'
|
|
147
|
+
: 'The task remains queued. Review this workspace’s automatic Pain opt-in and host ingestion consent.',
|
|
148
|
+
};
|
|
149
|
+
}
|
|
136
150
|
if (executed.status === 'failed') {
|
|
137
151
|
return {
|
|
138
152
|
served: false,
|
|
@@ -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
|
+
}
|
|
@@ -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, parsePainIngressV1Payload, 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, deriveProvenanceFromIngressFacts, 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
|
/**
|
|
@@ -2077,9 +2101,31 @@ export async function ensureGovernanceDiagnosticianTask(input) {
|
|
|
2077
2101
|
if (ingressDecision.action === 'degrade')
|
|
2078
2102
|
ingressWarning = ingressDecision.warning;
|
|
2079
2103
|
}
|
|
2104
|
+
else if (payloadParsed.painIngress !== undefined) {
|
|
2105
|
+
// The Inbox has already evaluated this non-correction (or OpenClaw)
|
|
2106
|
+
// submission. Use the same validated facts that the worker checks on
|
|
2107
|
+
// re-entry, rather than overwriting an automatic origin with a legacy
|
|
2108
|
+
// host-bound default. The automatic submission gate below still runs.
|
|
2109
|
+
const ingress = parsePainIngressV1Payload(payloadParsed.painIngress);
|
|
2110
|
+
if (!ingress.ok) {
|
|
2111
|
+
return { ok: false, reason: ingress.reasonCode, nextAction: 'Repair the persisted Pain ingress facts before retrying the diagnosis.' };
|
|
2112
|
+
}
|
|
2113
|
+
const { origin, correlation } = ingress.payload;
|
|
2114
|
+
const resolved = deriveProvenanceFromIngressFacts(origin, correlation);
|
|
2115
|
+
if (correlation.status !== 'bound' || correlation.hostKind !== markerHostKind
|
|
2116
|
+
|| (correlation.hostKind === 'codex' ? correlation.rootSessionId : correlation.sessionId) !== payloadParsed.sessionId
|
|
2117
|
+
|| (resolved !== 'automatic_hook' && resolved !== 'host_context_bound')) {
|
|
2118
|
+
return {
|
|
2119
|
+
ok: false,
|
|
2120
|
+
reason: 'pain_ingress_marker_attribution_mismatch',
|
|
2121
|
+
nextAction: 'Repair the persisted Pain marker so its validated host and source agree with the submission.',
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
2124
|
+
provenance = resolved;
|
|
2125
|
+
}
|
|
2080
2126
|
else {
|
|
2081
|
-
//
|
|
2082
|
-
//
|
|
2127
|
+
// An older marker has no canonical envelope. Preserve its historical
|
|
2128
|
+
// provenance without manufacturing an origin or a new envelope.
|
|
2083
2129
|
provenance = 'host_context_bound';
|
|
2084
2130
|
}
|
|
2085
2131
|
// Preserve the existing fail-closed validation for linked tasks while
|
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
|
package/dist/pain-inbox.d.ts
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
* exclude `source_revoked` rows and re-verify `readSourceMaterialAuthorization()`
|
|
29
29
|
* live before admitting.
|
|
30
30
|
*/
|
|
31
|
+
import { type RuntimeStateManager, type TaskRecord, type PainSignalBridgeResult } from '@principles/core/runtime';
|
|
31
32
|
import type { ObservationDatabaseFactory } from './governance-observation-store.js';
|
|
32
33
|
export declare const PAIN_INBOX_TTL_MS: number;
|
|
33
34
|
export declare const PAIN_INBOX_APPROVING_TTL_MS: number;
|
|
@@ -102,6 +103,13 @@ export interface ExpireStalePainInboxResult {
|
|
|
102
103
|
readonly expiredOpenClaw: number;
|
|
103
104
|
readonly reason?: string;
|
|
104
105
|
}
|
|
106
|
+
/** All background diagnosis workers share this same narrow recovery boundary. */
|
|
107
|
+
export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
|
|
108
|
+
workspaceDir: string;
|
|
109
|
+
task: TaskRecord;
|
|
110
|
+
stateManager: Pick<RuntimeStateManager, 'updateTaskIfDiagnosticJsonUnchanged'>;
|
|
111
|
+
execute: () => Promise<PainSignalBridgeResult>;
|
|
112
|
+
}): Promise<PainSignalBridgeResult>;
|
|
105
113
|
/**
|
|
106
114
|
* List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
|
|
107
115
|
* Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
|