@principles/host-runtime 4.7.2 → 4.9.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-worker-status.d.ts +6 -4
- package/dist/codex-worker-status.js +7 -5
- package/dist/diagnostician-auto-run.js +2 -2
- package/dist/governance-signal-admission.d.ts +2 -1
- package/dist/governance-signal-admission.js +7 -2
- package/dist/governance-trajectory-turn-reader.js +85 -19
- package/dist/index.d.ts +21 -2
- package/dist/index.js +14 -2
- package/dist/internalization-consumer-cycle.d.ts +13 -106
- package/dist/internalization-consumer-cycle.js +21 -99
- package/dist/internalization-consumer-governance.d.ts +3 -3
- package/dist/internalization-consumer-governance.js +17 -96
- package/dist/internalization-task-executor.d.ts +127 -0
- package/dist/internalization-task-executor.js +121 -0
- package/dist/plugin-trajectory-turn-store.d.ts +40 -0
- package/dist/plugin-trajectory-turn-store.js +188 -0
- package/dist/production-pain-evidence.d.ts +9 -0
- package/dist/production-pain-evidence.js +60 -3
- package/dist/source-revocation-sweep.d.ts +31 -0
- package/dist/source-revocation-sweep.js +145 -5
- package/dist/workbuddy-worker-status.d.ts +6 -3
- package/dist/workbuddy-worker-status.js +7 -4
- package/dist/workspace-telemetry-emitter.js +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1319 / PD Evidence Integrity SPEC v1.1 §7.2 — read-only access to the
|
|
3
|
+
* OpenClaw plugin's own trajectory tables (`user_turns` / `assistant_turns`)
|
|
4
|
+
* for CLI/worker diagnosis paths.
|
|
5
|
+
*
|
|
6
|
+
* Audit B-2 fact: the plugin records verbatim Owner turns in its OWN tables
|
|
7
|
+
* inside the SAME workspace trajectory.db the governance reader already
|
|
8
|
+
* queries (`<workspace>/.pd/state/trajectory.db`, canonical schema owned by
|
|
9
|
+
* @principles/core trajectory-schema). The CLI-side governance reader only
|
|
10
|
+
* queried `governance_observations`, so a bound OpenClaw session with stored
|
|
11
|
+
* turns still produced an empty diagnosis window. This module closes that
|
|
12
|
+
* gap WITHOUT a second database, a copy pipeline or an IPC layer: it reads
|
|
13
|
+
* the same canonical store read-only (the precedent is
|
|
14
|
+
* `openTrajectoryDbReadonly` in @principles/core and pd-console's direct
|
|
15
|
+
* assistant_turns reads). WAL + busy_timeout make cross-process reads safe.
|
|
16
|
+
*
|
|
17
|
+
* Semantics (SPEC §7.2 / rc-9):
|
|
18
|
+
* - `session_id = ?` EXACT match only — no root-session fallback, so no
|
|
19
|
+
* other session's turns can leak into this window.
|
|
20
|
+
* - Inline text only (`raw_text`/`sanitized_text`), with the bounded
|
|
21
|
+
* `raw_excerpt` fallback when a large body was offloaded to a blob.
|
|
22
|
+
* Blob FILES are intentionally NOT read here (bounded inline surface,
|
|
23
|
+
* no second snapshot store); when a turn carries only an excerpt, the
|
|
24
|
+
* row says so (`textSource: 'excerpt'`) — never silently re-derives.
|
|
25
|
+
* - Plugin-table retention DELETES expired rows outright (the core
|
|
26
|
+
* retention engine's DELETE FROM; the visible_text-NULLing discipline
|
|
27
|
+
* is a governance_observations mechanism), so nothing extra to filter.
|
|
28
|
+
* - Every distinct failure shape has its own reason: `source_missing` vs
|
|
29
|
+
* `query_failed` vs success-with-zero-rows — a query failure is NEVER
|
|
30
|
+
* served as a successful empty result (SPEC AC-05).
|
|
31
|
+
*/
|
|
32
|
+
import fs from 'node:fs';
|
|
33
|
+
import Database from 'better-sqlite3';
|
|
34
|
+
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
35
|
+
/** Bound on turns per list call — the assembler bounds the window again. */
|
|
36
|
+
const MAX_TURNS_PER_SESSION = 200;
|
|
37
|
+
function openReadonly(workspaceDir, factory) {
|
|
38
|
+
const dbPath = resolveTrajectoryDbPath(workspaceDir);
|
|
39
|
+
if (!fs.existsSync(dbPath)) {
|
|
40
|
+
return {
|
|
41
|
+
ok: false,
|
|
42
|
+
reason: 'source_missing:trajectory_db_not_found',
|
|
43
|
+
nextAction: 'initialize the selected PD workspace (pd runtime init) before diagnosing OpenClaw pains',
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const db = (factory ? factory(dbPath) : new Database(dbPath, { readonly: true }));
|
|
48
|
+
db.pragma('busy_timeout = 5000');
|
|
49
|
+
return { ok: true, db };
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
53
|
+
return {
|
|
54
|
+
ok: false,
|
|
55
|
+
reason: `query_failed:${detail.slice(0, 120)}`,
|
|
56
|
+
nextAction: 'check the trajectory.db file permissions; the read is retried on the next diagnosis',
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** rc-2: better-sqlite3's `.all()` returns unknown[] — narrow per-field with
|
|
61
|
+
* type guards (no `as` on the row shape; ERR-001). */
|
|
62
|
+
function readRows(input) {
|
|
63
|
+
const boundedLimit = Math.min(Math.max(input.limit, 1), MAX_TURNS_PER_SESSION);
|
|
64
|
+
const statement = input.db.prepare(input.sql);
|
|
65
|
+
statement.raw(true);
|
|
66
|
+
const columns = statement.columns().map((column) => column.name);
|
|
67
|
+
const rows = statement.all(input.sessionId, boundedLimit);
|
|
68
|
+
return rows.map((row) => {
|
|
69
|
+
const record = {};
|
|
70
|
+
if (Array.isArray(row)) {
|
|
71
|
+
for (let i = 0; i < columns.length; i++) {
|
|
72
|
+
const column = columns[i];
|
|
73
|
+
if (typeof column === 'string')
|
|
74
|
+
record[column] = row[i];
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return record;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function readUserTurnRows(db, sessionId, limit) {
|
|
81
|
+
const rows = readRows({
|
|
82
|
+
db,
|
|
83
|
+
sql: 'SELECT id, raw_text, blob_ref, raw_excerpt, correction_detected, created_at FROM user_turns WHERE session_id = ? ORDER BY id ASC LIMIT ?',
|
|
84
|
+
sessionId,
|
|
85
|
+
limit,
|
|
86
|
+
});
|
|
87
|
+
const turns = [];
|
|
88
|
+
for (const row of rows) {
|
|
89
|
+
const rawText = typeof row.raw_text === 'string' ? row.raw_text : '';
|
|
90
|
+
const excerpt = typeof row.raw_excerpt === 'string' ? row.raw_excerpt : '';
|
|
91
|
+
const text = rawText.length > 0 ? rawText : excerpt;
|
|
92
|
+
if (text.length === 0)
|
|
93
|
+
continue;
|
|
94
|
+
turns.push({
|
|
95
|
+
id: Number(row.id),
|
|
96
|
+
kind: 'user_turn',
|
|
97
|
+
text,
|
|
98
|
+
textSource: rawText.length > 0 ? 'inline' : 'excerpt',
|
|
99
|
+
observedAt: typeof row.created_at === 'string' ? row.created_at : '',
|
|
100
|
+
correctionDetected: row.correction_detected === 1,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return turns;
|
|
104
|
+
}
|
|
105
|
+
function readAssistantTurnRows(db, sessionId, limit) {
|
|
106
|
+
const rows = readRows({
|
|
107
|
+
db,
|
|
108
|
+
sql: 'SELECT id, raw_text, sanitized_text, blob_ref, raw_excerpt, created_at FROM assistant_turns WHERE session_id = ? ORDER BY id ASC LIMIT ?',
|
|
109
|
+
sessionId,
|
|
110
|
+
limit,
|
|
111
|
+
});
|
|
112
|
+
const turns = [];
|
|
113
|
+
for (const row of rows) {
|
|
114
|
+
const rawText = typeof row.raw_text === 'string' ? row.raw_text : '';
|
|
115
|
+
const sanitized = typeof row.sanitized_text === 'string' ? row.sanitized_text : '';
|
|
116
|
+
const excerpt = typeof row.raw_excerpt === 'string' ? row.raw_excerpt : '';
|
|
117
|
+
const text = rawText.length > 0 ? rawText : (sanitized.length > 0 ? sanitized : excerpt);
|
|
118
|
+
if (text.length === 0)
|
|
119
|
+
continue;
|
|
120
|
+
turns.push({
|
|
121
|
+
id: Number(row.id),
|
|
122
|
+
kind: 'assistant_turn',
|
|
123
|
+
text,
|
|
124
|
+
textSource: rawText.length > 0 ? 'inline' : 'excerpt',
|
|
125
|
+
observedAt: typeof row.created_at === 'string' ? row.created_at : '',
|
|
126
|
+
correctionDetected: false,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return turns;
|
|
130
|
+
}
|
|
131
|
+
export function listPluginTurnTexts(input) {
|
|
132
|
+
if (input.sessionId.trim().length === 0)
|
|
133
|
+
return { ok: true, turns: [] };
|
|
134
|
+
const opened = openReadonly(input.workspaceDir, input.databaseFactory);
|
|
135
|
+
if (!('db' in opened))
|
|
136
|
+
return opened;
|
|
137
|
+
const { db } = opened;
|
|
138
|
+
try {
|
|
139
|
+
const turns = input.kind === 'user_turn'
|
|
140
|
+
? readUserTurnRows(db, input.sessionId, input.limit ?? MAX_TURNS_PER_SESSION)
|
|
141
|
+
: readAssistantTurnRows(db, input.sessionId, input.limit ?? MAX_TURNS_PER_SESSION);
|
|
142
|
+
return { ok: true, turns };
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
146
|
+
return {
|
|
147
|
+
ok: false,
|
|
148
|
+
reason: `query_failed:${detail.slice(0, 120)}`,
|
|
149
|
+
nextAction: 'check the trajectory.db schema; the read is retried on the next diagnosis',
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
try {
|
|
154
|
+
db.close();
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
// A close failure must not mask the already-determined read result.
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export function hasPluginUserTurns(input) {
|
|
162
|
+
if (input.sessionId.trim().length === 0)
|
|
163
|
+
return { ok: true, present: false };
|
|
164
|
+
const opened = openReadonly(input.workspaceDir, input.databaseFactory);
|
|
165
|
+
if (!('db' in opened))
|
|
166
|
+
return opened;
|
|
167
|
+
const { db } = opened;
|
|
168
|
+
try {
|
|
169
|
+
const row = db.prepare('SELECT 1 FROM user_turns WHERE session_id = ? LIMIT 1').get(input.sessionId);
|
|
170
|
+
return { ok: true, present: row !== undefined };
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
174
|
+
return {
|
|
175
|
+
ok: false,
|
|
176
|
+
reason: `query_failed:${detail.slice(0, 120)}`,
|
|
177
|
+
nextAction: 'check the trajectory.db schema; the read is retried on the next submission',
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
try {
|
|
182
|
+
db.close();
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
// Close failure must not mask the result.
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import Database from 'better-sqlite3';
|
|
2
|
+
import { recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
|
|
2
3
|
import type { GovernanceHostKind } from '@principles/core/runtime';
|
|
3
4
|
import type { HostEvent, HostEventEmitter, HostEventResult } from '@principles/core/host';
|
|
4
5
|
export interface ProductionPainEnrichment {
|
|
@@ -30,6 +31,13 @@ export declare function deriveProductionCorrectionPainIdentity(fields: {
|
|
|
30
31
|
painId: string;
|
|
31
32
|
};
|
|
32
33
|
declare function hasCanonicalSchema(db: Database.Database): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* PD Phase 1.5 (review round 2 — single migration authority): the local
|
|
36
|
+
* turn_id / environment_snapshots ensures were REMOVED — the migration lives
|
|
37
|
+
* only in @principles/core/runtime/trajectory-schema. Re-exported here so
|
|
38
|
+
* the governance admission store's existing import keeps working.
|
|
39
|
+
*/
|
|
40
|
+
export { ensureForwardEvidenceSchema } from '@principles/core/runtime/trajectory-schema';
|
|
33
41
|
/** One host-verified tool outcome (SPEC-CODEX-PAIN-CLOSURE-001 CR-01). */
|
|
34
42
|
export interface VerifiedToolOutcomeInput {
|
|
35
43
|
/** Host tool-call id — the join key written by the live PostToolUse path. */
|
|
@@ -88,5 +96,6 @@ export declare function createProductionPainEvidenceHandler(options?: {
|
|
|
88
96
|
hostKind?: GovernanceHostKind;
|
|
89
97
|
projectDir?: string;
|
|
90
98
|
events?: HostEventEmitter;
|
|
99
|
+
environmentProvider?: () => Pick<NonNullable<Parameters<typeof recordEnvironmentSnapshot>[1]>, 'hostVersion' | 'runtimeVersion' | 'agentConfigDigest' | 'modelConfigDigest' | 'repoCommit' | 'workspaceStateDigest' | 'featureFlagsDigest'>;
|
|
91
100
|
}): (event: HostEvent) => Promise<HostEventResult>;
|
|
92
101
|
export { hasCanonicalSchema as hasProductionPainSchema };
|
|
@@ -6,6 +6,7 @@ import { applyTrajectorySchemaBase, migrateLegacyGfiSchema, sanitizeToolParams,
|
|
|
6
6
|
// PRI-1135: the canonical column declaration lives with the DDL owner. Import
|
|
7
7
|
// the subpath directly so the public runtime barrel surface stays unchanged.
|
|
8
8
|
import { TRAJECTORY_REQUIRED_COLUMNS } from '@principles/core/runtime/trajectory-schema';
|
|
9
|
+
import { ensureForwardEvidenceSchema, recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
|
|
9
10
|
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
10
11
|
const MAX_PREVIEW = 500;
|
|
11
12
|
function isRecord(value) {
|
|
@@ -215,6 +216,18 @@ function hasCanonicalSchema(db) {
|
|
|
215
216
|
db.prepare('INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at');
|
|
216
217
|
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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
217
218
|
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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
219
|
+
// PD Phase 1.5: the forward-evidence statements this module WRITES. The
|
|
220
|
+
// probes are enforced on WRITABLE opens only: read-only opens (historical
|
|
221
|
+
// snapshot analysis, golden fixtures) legitimately read pre-Phase-1.5
|
|
222
|
+
// databases whose rows carry NULL turn_id, and demanding the new columns
|
|
223
|
+
// there would degrade every honest read-only analysis path. Writable opens
|
|
224
|
+
// converge the schema first (ensureForwardEvidenceSchema), so a failure
|
|
225
|
+
// here still means the column is truly absent.
|
|
226
|
+
if (!db.readonly) {
|
|
227
|
+
db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? AND turn_id = ?');
|
|
228
|
+
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
229
|
+
db.prepare('INSERT INTO environment_snapshots (session_id, capture_kind, host_kind, host_version, runtime_version, agent_config_digest, model_config_digest, repo_commit, workspace_state_digest, feature_flags_digest, capture_schema_version, captured_at, payload_json, payload_sha256) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
230
|
+
}
|
|
218
231
|
return true;
|
|
219
232
|
}
|
|
220
233
|
/**
|
|
@@ -266,6 +279,13 @@ function ensureToolCallsHostKindColumn(db) {
|
|
|
266
279
|
// Same concurrent-writer contract as the sibling migrations above.
|
|
267
280
|
}
|
|
268
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* PD Phase 1.5 (review round 2 — single migration authority): the local
|
|
284
|
+
* turn_id / environment_snapshots ensures were REMOVED — the migration lives
|
|
285
|
+
* only in @principles/core/runtime/trajectory-schema. Re-exported here so
|
|
286
|
+
* the governance admission store's existing import keeps working.
|
|
287
|
+
*/
|
|
288
|
+
export { ensureForwardEvidenceSchema } from '@principles/core/runtime/trajectory-schema';
|
|
269
289
|
/**
|
|
270
290
|
* SPEC-CODEX-PAIN-CLOSURE-001 CR-01: upgrade the live-hook observation of a
|
|
271
291
|
* tool call with the host-verified final result (exit code) read through the
|
|
@@ -380,6 +400,9 @@ export function recordVerifiedToolOutcomes(args) {
|
|
|
380
400
|
* writer. Omitted -> NULL (unknown).
|
|
381
401
|
*/
|
|
382
402
|
export function createProductionPainEvidenceHandler(options = {}) {
|
|
403
|
+
// PD Phase 1.5: sessions whose environment evidence was already captured by
|
|
404
|
+
// THIS handler process — one row per session, not one per tool call.
|
|
405
|
+
const envCapturedSessions = new Set();
|
|
383
406
|
return async (event) => {
|
|
384
407
|
// PRI-750: shared-path tool event with the host's natural turn/tool ids
|
|
385
408
|
// (Codex turn_id → runId, tool_use_id → toolCallId) so receipt events
|
|
@@ -414,6 +437,10 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
414
437
|
ensureToolCallsToolUseIdColumn(db);
|
|
415
438
|
ensureToolCallsProjectDirColumn(db);
|
|
416
439
|
ensureToolCallsHostKindColumn(db);
|
|
440
|
+
// PD Phase 1.5 (review round 2 — single migration authority): the
|
|
441
|
+
// turn_id column + environment_snapshots table come from the ONE core
|
|
442
|
+
// ensure (re-exported below).
|
|
443
|
+
ensureForwardEvidenceSchema(db);
|
|
417
444
|
// GFI-COMPLETE-REMOVAL-001: v1 databases are migrated before the canonical
|
|
418
445
|
// verdict; a failed migration is reported by name and never downgraded
|
|
419
446
|
// into "canonical" (rc-9 — no silent fallback).
|
|
@@ -502,8 +529,38 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
502
529
|
return;
|
|
503
530
|
}
|
|
504
531
|
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);
|
|
505
|
-
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) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
506
|
-
.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);
|
|
532
|
+
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
533
|
+
.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);
|
|
534
|
+
// PD Phase 1.5 (SPEC §R10): forward environment evidence — captured
|
|
535
|
+
// ONCE per session per handler process, on the first tool-evidence
|
|
536
|
+
// write. Facts come from the adapter-supplied environmentProvider;
|
|
537
|
+
// fields an adapter does not know stay NULL (unknown, never guessed).
|
|
538
|
+
// Capture failure degrades to a warning and never blocks the tool
|
|
539
|
+
// evidence write (rc-9).
|
|
540
|
+
if (!envCapturedSessions.has(event.context.sessionId)) {
|
|
541
|
+
envCapturedSessions.add(event.context.sessionId);
|
|
542
|
+
try {
|
|
543
|
+
const env = options.environmentProvider?.();
|
|
544
|
+
recordEnvironmentSnapshot(db, {
|
|
545
|
+
sessionId: event.context.sessionId,
|
|
546
|
+
captureKind: 'after_tool_call',
|
|
547
|
+
hostKind: options.hostKind ?? null,
|
|
548
|
+
hostVersion: env?.hostVersion ?? null,
|
|
549
|
+
runtimeVersion: env?.runtimeVersion ?? null,
|
|
550
|
+
agentConfigDigest: env?.agentConfigDigest ?? null,
|
|
551
|
+
modelConfigDigest: env?.modelConfigDigest ?? null,
|
|
552
|
+
repoCommit: env?.repoCommit ?? null,
|
|
553
|
+
workspaceStateDigest: env?.workspaceStateDigest ?? null,
|
|
554
|
+
featureFlagsDigest: env?.featureFlagsDigest ?? null,
|
|
555
|
+
captureSchemaVersion: 'pd-environment-snapshot.v1',
|
|
556
|
+
capturedAt: createdAt,
|
|
557
|
+
payload: {},
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
catch (envError) {
|
|
561
|
+
warnings.push(`environment_snapshot_failed:${envError instanceof Error ? envError.message.slice(0, 200) : String(envError).slice(0, 200)}`);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
507
564
|
})();
|
|
508
565
|
}
|
|
509
566
|
catch (error) {
|
|
@@ -518,7 +575,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
|
|
|
518
575
|
return {
|
|
519
576
|
decision: 'observe',
|
|
520
577
|
source: event.source,
|
|
521
|
-
...(emissionWarning ? { warnings: [emissionWarning] } : {}),
|
|
578
|
+
...(emissionWarning || warnings.length > 0 ? { warnings: [...(emissionWarning ? [emissionWarning] : []), ...warnings] } : {}),
|
|
522
579
|
metadata: {
|
|
523
580
|
eventId, outcome: outcome.outcome, ...(outcome.unknownReason !== undefined ? { outcomeReason: outcome.unknownReason } : {}), exitCode: outcome.exitCode, duplicate,
|
|
524
581
|
}
|
|
@@ -125,6 +125,22 @@ export interface SourceRevocationSweepCounts {
|
|
|
125
125
|
piArtifacts: number;
|
|
126
126
|
/** evidence entries removed from pi_artifacts. */
|
|
127
127
|
piArtifactEvidenceEntries: number;
|
|
128
|
+
/**
|
|
129
|
+
* Fix-E (P0 consent re-audit 2026-11-29): trajectory turn rows
|
|
130
|
+
* (user_turns + assistant_turns) whose body columns were NULLed. Turn
|
|
131
|
+
* tables carry the raw conversation bodies — they were previously OUTSIDE
|
|
132
|
+
* the sweep's scope, leaving undeletable orphans after revocation.
|
|
133
|
+
*/
|
|
134
|
+
trajectoryTurnRows: number;
|
|
135
|
+
/** raw-text blob files deleted together with the purged turn rows. */
|
|
136
|
+
trajectoryBlobFiles: number;
|
|
137
|
+
/**
|
|
138
|
+
* X1 (2026-11-29 directive §五B): signal_confirmations rows whose excerpt /
|
|
139
|
+
* recent-assistant-turn body columns were cleared. The table holds ≤400-char
|
|
140
|
+
* body excerpts and has no host_kind — same shared-workspace guard as the
|
|
141
|
+
* turn tables.
|
|
142
|
+
*/
|
|
143
|
+
trajectorySignalConfirmationRows: number;
|
|
128
144
|
}
|
|
129
145
|
export interface SourceRevocationSweepHostReport {
|
|
130
146
|
readonly hostKind: SweepHostKind;
|
|
@@ -136,6 +152,13 @@ export interface SourceRevocationSweepHostReport {
|
|
|
136
152
|
readonly notApplicable: readonly string[];
|
|
137
153
|
/** Non-sensitive per-item failure notes (bounded). */
|
|
138
154
|
readonly failures: readonly string[];
|
|
155
|
+
/**
|
|
156
|
+
* Fix-E: purge steps deliberately NOT run for this host, with the reason
|
|
157
|
+
* (e.g. turn-table purge skipped because another host holds a granted
|
|
158
|
+
* consent record on the same shared workspace and the turn tables are not
|
|
159
|
+
* host-attributable). Informational, never an error.
|
|
160
|
+
*/
|
|
161
|
+
readonly skipped?: readonly string[];
|
|
139
162
|
}
|
|
140
163
|
export type SourceRevocationSweepReport = {
|
|
141
164
|
readonly outcome: 'completed' | 'partial';
|
|
@@ -169,4 +192,12 @@ export interface RunSourceRevocationSweepOptions {
|
|
|
169
192
|
/** Injectable clock (tests). */
|
|
170
193
|
readonly now?: () => Date;
|
|
171
194
|
}
|
|
195
|
+
/**
|
|
196
|
+
* Containment guard for persisted blob refs (F4, 2026-11-29 review). A ref is
|
|
197
|
+
* trusted to be a plain filename produced by the trajectory writer
|
|
198
|
+
* (`<kind>-<sha256>.txt`), but a tampered or migrated value must never be
|
|
199
|
+
* allowed to address a path outside the blobs directory. Mirrors the
|
|
200
|
+
* EvidenceChainConsoleModel read-path idiom.
|
|
201
|
+
*/
|
|
202
|
+
export declare function resolveBlobRefWithin(blobDir: string, ref: string): string | null;
|
|
172
203
|
export declare function runSourceRevocationSweep(options: RunSourceRevocationSweepOptions): Promise<SourceRevocationSweepReport>;
|
|
@@ -120,8 +120,27 @@ function emptyCounts() {
|
|
|
120
120
|
runEvidenceEntries: 0,
|
|
121
121
|
piArtifacts: 0,
|
|
122
122
|
piArtifactEvidenceEntries: 0,
|
|
123
|
+
trajectoryTurnRows: 0,
|
|
124
|
+
trajectoryBlobFiles: 0,
|
|
125
|
+
trajectorySignalConfirmationRows: 0,
|
|
123
126
|
};
|
|
124
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* Containment guard for persisted blob refs (F4, 2026-11-29 review). A ref is
|
|
130
|
+
* trusted to be a plain filename produced by the trajectory writer
|
|
131
|
+
* (`<kind>-<sha256>.txt`), but a tampered or migrated value must never be
|
|
132
|
+
* allowed to address a path outside the blobs directory. Mirrors the
|
|
133
|
+
* EvidenceChainConsoleModel read-path idiom.
|
|
134
|
+
*/
|
|
135
|
+
export function resolveBlobRefWithin(blobDir, ref) {
|
|
136
|
+
if (ref.length === 0 || ref.includes('\0'))
|
|
137
|
+
return null;
|
|
138
|
+
const resolved = path.resolve(blobDir, ref);
|
|
139
|
+
const rel = path.relative(path.resolve(blobDir), resolved);
|
|
140
|
+
if (rel === '' || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
|
|
141
|
+
return null;
|
|
142
|
+
return resolved;
|
|
143
|
+
}
|
|
125
144
|
function isRecord(value) {
|
|
126
145
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
127
146
|
}
|
|
@@ -265,7 +284,8 @@ function revokedPendingTerminalPayload(attempts, nowIso) {
|
|
|
265
284
|
});
|
|
266
285
|
}
|
|
267
286
|
function sweepTrajectoryDb(args) {
|
|
268
|
-
const { dbPath, hostKind, apply, nowIso } = args;
|
|
287
|
+
const { dbPath, hostKind, apply, nowIso, otherGrantedHosts } = args;
|
|
288
|
+
const skipped = [];
|
|
269
289
|
const counts = emptyCounts();
|
|
270
290
|
const failures = [];
|
|
271
291
|
const notApplicable = [];
|
|
@@ -311,6 +331,118 @@ function sweepTrajectoryDb(args) {
|
|
|
311
331
|
counts.governanceObservations = observationIds.length;
|
|
312
332
|
}
|
|
313
333
|
}
|
|
334
|
+
// 1b. Fix-E: trajectory turn tables — the raw conversation bodies.
|
|
335
|
+
// The turn tables have NO host_kind column; they are purged only when no
|
|
336
|
+
// OTHER host holds a granted consent record on this workspace (otherwise
|
|
337
|
+
// the purge would destroy another host's authorized material).
|
|
338
|
+
// Fix-E r2 (2026-11-29 review F1/F3/F4 + directive §五B):
|
|
339
|
+
// - deletion order is FILE FIRST: a blob_ref is only cleared after its
|
|
340
|
+
// file was deleted or proven absent (never the reverse), so a failed
|
|
341
|
+
// or interrupted deletion stays retryable with no orphaned file;
|
|
342
|
+
// - sanitized_text uses '' (the column is NOT NULL — the previous NULL
|
|
343
|
+
// form violated the schema and rolled the whole purge back, F1);
|
|
344
|
+
// - every ref is containment-checked before it can address a path (F4).
|
|
345
|
+
if (otherGrantedHosts.length > 0) {
|
|
346
|
+
skipped.push(`trajectory_turns: shared workspace, other granted hosts present (${otherGrantedHosts.join(', ')}) — turn purge skipped`);
|
|
347
|
+
skipped.push(`signal_confirmations: shared workspace, other granted hosts present (${otherGrantedHosts.join(', ')}) — excerpt purge skipped`);
|
|
348
|
+
}
|
|
349
|
+
else {
|
|
350
|
+
const turnTablesMissing = [];
|
|
351
|
+
if (!tableExists('user_turns'))
|
|
352
|
+
turnTablesMissing.push('user_turns');
|
|
353
|
+
if (!tableExists('assistant_turns'))
|
|
354
|
+
turnTablesMissing.push('assistant_turns');
|
|
355
|
+
notApplicable.push(...turnTablesMissing);
|
|
356
|
+
if (!tableExists('signal_confirmations'))
|
|
357
|
+
notApplicable.push('signal_confirmations');
|
|
358
|
+
const blobDir = path.join(path.dirname(dbPath), 'blobs');
|
|
359
|
+
// Dry-run reporting: full candidate counts (every row that still
|
|
360
|
+
// carries body material or an unclaimed blob ref).
|
|
361
|
+
const userCandidates = tableExists('user_turns')
|
|
362
|
+
? db.prepare('SELECT COUNT(*) AS c FROM user_turns WHERE raw_text IS NOT NULL OR raw_excerpt IS NOT NULL OR correction_cue IS NOT NULL OR blob_ref IS NOT NULL').get().c
|
|
363
|
+
: 0;
|
|
364
|
+
const assistantCandidates = tableExists('assistant_turns')
|
|
365
|
+
? db.prepare("SELECT COUNT(*) AS c FROM assistant_turns WHERE raw_text IS NOT NULL OR sanitized_text <> '' OR raw_excerpt IS NOT NULL OR blob_ref IS NOT NULL").get().c
|
|
366
|
+
: 0;
|
|
367
|
+
const signalCandidates = tableExists('signal_confirmations')
|
|
368
|
+
? db.prepare("SELECT COUNT(*) AS c FROM signal_confirmations WHERE excerpt <> '' OR recent_assistant_turns_json IS NOT NULL").get().c
|
|
369
|
+
: 0;
|
|
370
|
+
const blobRefs = [];
|
|
371
|
+
if (tableExists('user_turns')) {
|
|
372
|
+
for (const r of db.prepare('SELECT DISTINCT blob_ref AS ref FROM user_turns WHERE blob_ref IS NOT NULL').all())
|
|
373
|
+
blobRefs.push(r.ref);
|
|
374
|
+
}
|
|
375
|
+
if (tableExists('assistant_turns')) {
|
|
376
|
+
for (const r of db.prepare('SELECT DISTINCT blob_ref AS ref FROM assistant_turns WHERE blob_ref IS NOT NULL').all())
|
|
377
|
+
blobRefs.push(r.ref);
|
|
378
|
+
}
|
|
379
|
+
if (!apply) {
|
|
380
|
+
counts.trajectoryTurnRows = userCandidates + assistantCandidates;
|
|
381
|
+
counts.trajectoryBlobFiles = blobRefs.length;
|
|
382
|
+
counts.trajectorySignalConfirmationRows = signalCandidates;
|
|
383
|
+
}
|
|
384
|
+
else {
|
|
385
|
+
// Phase 1 — delete blob FILES first. A ref becomes claimable only
|
|
386
|
+
// after its file is gone (or was never on disk). A failed or
|
|
387
|
+
// rejected ref leaves its row fully intact; the next run retries it
|
|
388
|
+
// (directive §五B: no orphan files, retryable, auditable).
|
|
389
|
+
const claimableRefs = new Set();
|
|
390
|
+
for (const ref of blobRefs) {
|
|
391
|
+
const fullPath = resolveBlobRefWithin(blobDir, ref);
|
|
392
|
+
if (fullPath === null) {
|
|
393
|
+
failures.push(`trajectory_blob_ref_rejected: ${ref.slice(0, 80)}`);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
if (fs.existsSync(fullPath)) {
|
|
398
|
+
fs.unlinkSync(fullPath);
|
|
399
|
+
counts.trajectoryBlobFiles += 1;
|
|
400
|
+
}
|
|
401
|
+
claimableRefs.add(ref);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
failures.push(`trajectory_blob_delete_failed: ${error instanceof Error ? error.message.slice(0, 120) : String(error).slice(0, 120)}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const claimable = [...claimableRefs];
|
|
408
|
+
const claimableClause = claimable.length > 0
|
|
409
|
+
? ` OR blob_ref IN (${claimable.map(() => '?').join(', ')})`
|
|
410
|
+
: '';
|
|
411
|
+
// Phase 2 — clear row bodies and the now-claimable refs in one
|
|
412
|
+
// transaction. Predicates mirror the candidate predicates so a rerun
|
|
413
|
+
// converges on zero remaining body material.
|
|
414
|
+
const purgeTurns = db.transaction(() => {
|
|
415
|
+
let purgedRows = 0;
|
|
416
|
+
if (tableExists('user_turns')) {
|
|
417
|
+
purgedRows += db.prepare(`UPDATE user_turns SET raw_text = NULL, raw_excerpt = NULL, correction_cue = NULL, blob_ref = NULL
|
|
418
|
+
WHERE ((raw_text IS NOT NULL OR raw_excerpt IS NOT NULL OR correction_cue IS NOT NULL) AND blob_ref IS NULL)${claimableClause}`).run(...claimable).changes;
|
|
419
|
+
}
|
|
420
|
+
if (tableExists('assistant_turns')) {
|
|
421
|
+
purgedRows += db.prepare(`UPDATE assistant_turns SET raw_text = NULL, sanitized_text = '', raw_excerpt = NULL, blob_ref = NULL
|
|
422
|
+
WHERE ((raw_text IS NOT NULL OR sanitized_text <> '' OR raw_excerpt IS NOT NULL) AND blob_ref IS NULL)${claimableClause}`).run(...claimable).changes;
|
|
423
|
+
}
|
|
424
|
+
if (tableExists('signal_confirmations')) {
|
|
425
|
+
// Review round 2 (2026-11-29): clearing the excerpt is not enough
|
|
426
|
+
// — a row left in 'pending' still feeds the batch confirmation
|
|
427
|
+
// reader (which filters on status='pending'), so the observer
|
|
428
|
+
// would classify an EMPTY message and push keyword TP/FP feedback
|
|
429
|
+
// from purged material. Every swept row loses its body material;
|
|
430
|
+
// rows still 'pending' are additionally terminated to 'abandoned'
|
|
431
|
+
// with a fixed revocation reason so they can never re-enter the
|
|
432
|
+
// confirmation queue. Rows in a terminal state (confirmed/
|
|
433
|
+
// rejected/abandoned) keep their historical status untouched.
|
|
434
|
+
counts.trajectorySignalConfirmationRows = db.prepare(`UPDATE signal_confirmations
|
|
435
|
+
SET excerpt = '', recent_assistant_turns_json = NULL,
|
|
436
|
+
status = CASE WHEN status = 'pending' THEN 'abandoned' ELSE status END,
|
|
437
|
+
resolution = CASE WHEN status = 'pending' THEN 'source_revoked' ELSE resolution END,
|
|
438
|
+
resolved_at = CASE WHEN status = 'pending' THEN ? ELSE resolved_at END
|
|
439
|
+
WHERE excerpt <> '' OR recent_assistant_turns_json IS NOT NULL`).run(nowIso).changes;
|
|
440
|
+
}
|
|
441
|
+
counts.trajectoryTurnRows = purgedRows;
|
|
442
|
+
});
|
|
443
|
+
purgeTurns();
|
|
444
|
+
}
|
|
445
|
+
}
|
|
314
446
|
// 2. Admission markers — per-marker provenance classification.
|
|
315
447
|
if (!tableExists('governance_signal_admissions')) {
|
|
316
448
|
notApplicable.push('governance_signal_admissions');
|
|
@@ -432,11 +564,11 @@ function sweepTrajectoryDb(args) {
|
|
|
432
564
|
counts.painEventTexts = targets.length;
|
|
433
565
|
}
|
|
434
566
|
}
|
|
435
|
-
return { counts, failures, notApplicable, automaticPainIds };
|
|
567
|
+
return { counts, failures, notApplicable, automaticPainIds, skipped };
|
|
436
568
|
}
|
|
437
569
|
catch (error) {
|
|
438
570
|
failures.push(`trajectory_step_failed: ${error instanceof Error ? error.message.slice(0, 160) : String(error).slice(0, 160)}`);
|
|
439
|
-
return { counts, failures, notApplicable, automaticPainIds };
|
|
571
|
+
return { counts, failures, notApplicable, automaticPainIds, skipped };
|
|
440
572
|
}
|
|
441
573
|
finally {
|
|
442
574
|
try {
|
|
@@ -801,6 +933,7 @@ export async function runSourceRevocationSweep(options) {
|
|
|
801
933
|
// still block), and the report says so loudly.
|
|
802
934
|
const hostReports = [];
|
|
803
935
|
let ledgerUnreadable = false;
|
|
936
|
+
const grantedHosts = [];
|
|
804
937
|
const toSweep = [];
|
|
805
938
|
for (const hostKind of ['codex', 'workbuddy', 'openclaw']) {
|
|
806
939
|
const read = readConversationIngestionConsent(workspaceDir, hostKind);
|
|
@@ -812,7 +945,10 @@ export async function runSourceRevocationSweep(options) {
|
|
|
812
945
|
if (record === null)
|
|
813
946
|
continue;
|
|
814
947
|
if (record.decision === 'granted' || record.decision === 'pending' || record.decision === 'failed' || record.decision === 'revoked') {
|
|
815
|
-
if (record.decision
|
|
948
|
+
if (record.decision === 'granted') {
|
|
949
|
+
grantedHosts.push(hostKind);
|
|
950
|
+
}
|
|
951
|
+
else {
|
|
816
952
|
toSweep.push({ hostKind, decidedAt: record.decidedAt });
|
|
817
953
|
}
|
|
818
954
|
}
|
|
@@ -848,8 +984,10 @@ export async function runSourceRevocationSweep(options) {
|
|
|
848
984
|
const purged = emptyCounts();
|
|
849
985
|
const failures = [];
|
|
850
986
|
const notApplicable = [];
|
|
987
|
+
const skipped = [];
|
|
988
|
+
const otherGrantedHosts = grantedHosts.filter((h) => h !== target.hostKind);
|
|
851
989
|
if (fs.existsSync(trajectoryDbPath)) {
|
|
852
|
-
const trajResult = sweepTrajectoryDb({ dbPath: trajectoryDbPath, hostKind: target.hostKind, apply, nowIso: ranAt });
|
|
990
|
+
const trajResult = sweepTrajectoryDb({ dbPath: trajectoryDbPath, hostKind: target.hostKind, apply, nowIso: ranAt, otherGrantedHosts });
|
|
853
991
|
if ('error' in trajResult) {
|
|
854
992
|
failures.push(trajResult.error);
|
|
855
993
|
}
|
|
@@ -857,6 +995,7 @@ export async function runSourceRevocationSweep(options) {
|
|
|
857
995
|
mergeCounts(purged, trajResult.counts);
|
|
858
996
|
failures.push(...trajResult.failures);
|
|
859
997
|
notApplicable.push(...trajResult.notApplicable);
|
|
998
|
+
skipped.push(...trajResult.skipped);
|
|
860
999
|
}
|
|
861
1000
|
}
|
|
862
1001
|
else {
|
|
@@ -905,6 +1044,7 @@ export async function runSourceRevocationSweep(options) {
|
|
|
905
1044
|
purged,
|
|
906
1045
|
notApplicable,
|
|
907
1046
|
failures: hostFailures,
|
|
1047
|
+
...(skipped.length > 0 ? { skipped } : {}),
|
|
908
1048
|
});
|
|
909
1049
|
}
|
|
910
1050
|
if (outcome === 'partial') {
|
|
@@ -8,9 +8,12 @@
|
|
|
8
8
|
* (SPEC workbuddy-host-adapter §1 Excluded: no transcript reads).
|
|
9
9
|
*
|
|
10
10
|
* SPEC §15 worker mode, evaluated WITHOUT executing anything (no lease, no
|
|
11
|
-
* LLM). `manual_action_required` means
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* LLM). `manual_action_required` means this governance workspace is not
|
|
12
|
+
* registered in the canonical install manifest, so the PD Service Host —
|
|
13
|
+
* the only background runtime, triggered by the OS scheduler — never
|
|
14
|
+
* discovers it and no automatic worker cycles run for it. Manual
|
|
15
|
+
* `pd diagnose` / `pd runtime internalization run-once` is the recovery
|
|
16
|
+
* route.
|
|
14
17
|
*/
|
|
15
18
|
export type WorkbuddyWorkerMode = 'ready' | 'manual_action_required' | 'paused' | 'degraded';
|
|
16
19
|
export interface WorkbuddyWorkerStatusEvaluation {
|
|
@@ -8,9 +8,12 @@
|
|
|
8
8
|
* (SPEC workbuddy-host-adapter §1 Excluded: no transcript reads).
|
|
9
9
|
*
|
|
10
10
|
* SPEC §15 worker mode, evaluated WITHOUT executing anything (no lease, no
|
|
11
|
-
* LLM). `manual_action_required` means
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* LLM). `manual_action_required` means this governance workspace is not
|
|
12
|
+
* registered in the canonical install manifest, so the PD Service Host —
|
|
13
|
+
* the only background runtime, triggered by the OS scheduler — never
|
|
14
|
+
* discovers it and no automatic worker cycles run for it. Manual
|
|
15
|
+
* `pd diagnose` / `pd runtime internalization run-once` is the recovery
|
|
16
|
+
* route.
|
|
14
17
|
*/
|
|
15
18
|
import * as fs from 'node:fs';
|
|
16
19
|
import * as path from 'node:path';
|
|
@@ -48,7 +51,7 @@ export function computeWorkbuddyWorkerStatusMode(input) {
|
|
|
48
51
|
return {
|
|
49
52
|
mode: 'manual_action_required',
|
|
50
53
|
reason: 'workspace_not_in_install_manifest',
|
|
51
|
-
nextAction: `
|
|
54
|
+
nextAction: `This governance workspace is not registered in the canonical install manifest, so the PD Service Host does not manage automatic worker cycles for it. Repair the registration with the PD installer (npx create-principles-disciple). Manual path: pd diagnose --workspace "${workspaceDir}", then pd runtime internalization run-once.`,
|
|
52
55
|
};
|
|
53
56
|
}
|
|
54
57
|
return { mode: 'ready' };
|
|
@@ -52,7 +52,7 @@ import { StoreEventEmitter } from '@principles/core/runtime';
|
|
|
52
52
|
* 事件,含完整 TelemetryEvent)。同步 append:事件量小(allowlist 限流),
|
|
53
53
|
* 换取 crash 前落盘的 durable 语义。写失败绝不影响 runner —— 降级为
|
|
54
54
|
* `onPersistFailure` 回调(宿主注入的结构化告警口;OpenClaw 是
|
|
55
|
-
* SystemLogger,
|
|
55
|
+
* SystemLogger,Service-Host 派生的 workspace worker 是自己的事件口)。
|
|
56
56
|
*/
|
|
57
57
|
const CRITICAL_EVENT_ALLOWLIST = new Set([
|
|
58
58
|
'evaluator_adversarial_replay_skipped',
|