@principles/host-runtime 4.8.1 → 4.9.1

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.
@@ -23,7 +23,6 @@
23
23
  * `@principles/core/runtime` → `behavior-example-pack.ts`.
24
24
  */
25
25
  import { buildRuleHostAction } from '@principles/core/runtime/internalization/rule-host-input-builder';
26
- import { computeBehaviorFacts } from '@principles/core/runtime/internalization/rule-context-v2';
27
26
  import { validateBehaviorExamplePack } from '@principles/core/runtime/internalization/behavior-example-pack';
28
27
  // Factory lives in evidence-readiness.ts (the classification authority); it is
29
28
  // consumed through its registered LEAF subpath. A VALUE import of the
@@ -31,7 +30,7 @@ import { validateBehaviorExamplePack } from '@principles/core/runtime/internaliz
31
30
  // fails the satellite-purity guard (OPT-002, scripts/build/check-satellite-purity.mjs) —
32
31
  // the leaf is on core's exports allowlist for exactly this consumer.
33
32
  import { createOwnerEvidenceScopeError } from '@principles/core/runtime/internalization/evidence-readiness';
34
- import { assembleBehaviorHistory } from './behavior-history.js';
33
+ import { assembleBehaviorHistory, computeConservativeBehaviorFacts } from './behavior-history.js';
35
34
  // ── internal constants ─────────────────────────────────────────────────────
36
35
  const MAX_POSITIVES = 3;
37
36
  const MAX_EVIDENCE_REFS = 5;
@@ -237,7 +236,7 @@ export class BehaviorExamplePackAssembler {
237
236
  const historyResult = readTrajectoryStore(`context history read for session=${row.sessionId} before id=${row.id}`, () => this.db.getRuleHostContextRowsBefore(row.sessionId, row.id, HISTORY_LIMIT));
238
237
  const history = assembleBehaviorHistory(historyResult.rows, historyResult.truncated, { projectDir, toolSemantics: this.toolSemantics });
239
238
  const action = buildRuleHostAction(row.toolName, redaction.redacted, projectDir, { canonicalKind: this.toolSemantics.resolve(row.toolName) });
240
- const ruleContext = { version: 2, history, facts: computeBehaviorFacts(history, action.normalizedPath || null, null) };
239
+ const ruleContext = { version: 2, history, facts: computeConservativeBehaviorFacts(history, { path: action.normalizedPath || null, evidence: action.targetEvidence }, null) };
241
240
  return { ...base, params: redaction.redacted, ruleContext };
242
241
  }
243
242
  }
@@ -1,6 +1,9 @@
1
- import type { RuleHistoryWindow, ToolSemanticRegistry } from '@principles/core/runtime';
1
+ import type { RuleBehaviorFacts, RuleHistoryWindow, ToolSemanticRegistry } from '@principles/core/runtime';
2
+ import type { RuleBehaviorFactsTarget } from '@principles/core/runtime/internalization/rule-context-v2';
2
3
  import type { RuleHostContextRow } from '@principles/core/trajectory-types';
4
+ export declare function computeConservativeBehaviorFacts(history: RuleHistoryWindow, target: string | null | RuleBehaviorFactsTarget, sameActionBlockCount: number | null): RuleBehaviorFacts;
3
5
  export declare function assembleBehaviorHistory(rows: readonly RuleHostContextRow[], truncated: boolean, options: {
4
6
  projectDir: string;
5
7
  toolSemantics: ToolSemanticRegistry;
8
+ currentToolUseId?: string;
6
9
  }): RuleHistoryWindow;
@@ -1,5 +1,6 @@
1
1
  /** Shared validated history assembly; host vocabulary is supplied by its owner. */
2
2
  import { buildRuleHostAction } from '@principles/core/runtime/internalization/rule-host-input-builder';
3
+ import { computeBehaviorFacts } from '@principles/core/runtime/internalization/rule-context-v2';
3
4
  const VALID_OUTCOMES = new Set(['success', 'failure', 'blocked']);
4
5
  function isPlainObject(value) {
5
6
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -15,10 +16,27 @@ function unavailable(reason) {
15
16
  calls: [],
16
17
  };
17
18
  }
19
+ export function computeConservativeBehaviorFacts(history, target, sameActionBlockCount) {
20
+ const incomplete = history.truncated || history.calls.some((call) => call.canonicalKind === 'execute' || call.canonicalKind === 'other');
21
+ if (incomplete) {
22
+ return {
23
+ priorReadOfTarget: 'unknown',
24
+ readCount: null,
25
+ writeCount: null,
26
+ uniqueWritePathCount: null,
27
+ sameActionBlockCount: null,
28
+ };
29
+ }
30
+ return target !== null && typeof target === 'object'
31
+ ? computeBehaviorFacts(history, target, sameActionBlockCount)
32
+ : computeBehaviorFacts(history, target, sameActionBlockCount);
33
+ }
18
34
  export function assembleBehaviorHistory(rows, truncated, options) {
19
- const { projectDir, toolSemantics } = options;
35
+ const { projectDir, toolSemantics, currentToolUseId } = options;
20
36
  const records = [];
21
37
  for (const row of rows) {
38
+ if (typeof currentToolUseId === 'string' && currentToolUseId.length > 0 && row.toolUseId === currentToolUseId)
39
+ continue;
22
40
  // ── validate tool_name (ERR-001: unknown) ──
23
41
  const { toolName } = row;
24
42
  if (typeof toolName !== 'string' || toolName.length === 0) {
@@ -53,14 +71,21 @@ export function assembleBehaviorHistory(rows, truncated, options) {
53
71
  const canonicalKind = toolSemantics.resolve(toolName);
54
72
  // Use the shared action builder so history and live/replay preserve the
55
73
  // same distinction between extracted paths and opaque shell commands.
56
- const { normalizedPath } = buildRuleHostAction(toolName, parsedParams, projectDir, { canonicalKind });
74
+ const action = buildRuleHostAction(toolName, parsedParams, projectDir, { canonicalKind });
75
+ const callIdentityRelation = typeof currentToolUseId === 'string' && currentToolUseId.length > 0
76
+ && typeof row.toolUseId === 'string' && row.toolUseId.length > 0
77
+ && row.toolUseId !== currentToolUseId
78
+ ? 'distinct_from_current'
79
+ : 'unproven';
57
80
  records.push({
58
81
  sequenceId: row.id,
59
82
  toolName,
60
83
  canonicalKind,
61
- normalizedPath: normalizedPath === '' ? null : normalizedPath,
84
+ normalizedPath: action.normalizedPath === '' ? null : action.normalizedPath,
62
85
  paramsSummary: parsedParams,
63
86
  outcome,
87
+ callIdentityRelation,
88
+ targetEvidence: action.targetEvidence,
64
89
  });
65
90
  }
66
91
  return {
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { computeBehaviorFacts, } from '@principles/core/runtime';
3
- import { assembleBehaviorHistory } from './behavior-history.js';
3
+ import { assembleBehaviorHistory, computeConservativeBehaviorFacts } from './behavior-history.js';
4
4
  import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
5
5
  import { readLatestCodexDesignGateDeclaration, resolveCodexDesignGateFact } from './design-gate-facts.js';
6
6
  const HISTORY_LIMIT = 100;
@@ -134,6 +134,10 @@ export function createCodexRuleContextProvider(options) {
134
134
  return unavailable('trajectory_project_scope_incomplete', designGate);
135
135
  if (historyRows.rows.length === 0)
136
136
  return unavailable('no_prior_session_history', designGate);
137
+ // Deliberately do not pass currentToolUseId here. Unlike WorkBuddy,
138
+ // this reader does not yet prove strict same-host attribution for every
139
+ // historical row, so Codex call identity conservatively remains
140
+ // `unproven` rather than borrowing WorkBuddy's stronger capability.
137
141
  const history = assembleBehaviorHistory(historyRows.rows, historyRows.truncated, {
138
142
  projectDir,
139
143
  toolSemantics: options.toolSemantics,
@@ -142,17 +146,7 @@ export function createCodexRuleContextProvider(options) {
142
146
  // absent from this host's semantic registry. Either may read or mutate
143
147
  // files, so neither target-read absence nor exact action counts can be
144
148
  // asserted from this partial semantic view.
145
- const factsIncomplete = history.truncated || history.calls.some((call) => call.canonicalKind === 'execute' || call.canonicalKind === 'other');
146
- const computedFacts = computeBehaviorFacts(history, factsIncomplete ? null : request.targetPath, null);
147
- const facts = factsIncomplete
148
- ? {
149
- priorReadOfTarget: 'unknown',
150
- readCount: null,
151
- writeCount: null,
152
- uniqueWritePathCount: null,
153
- sameActionBlockCount: null,
154
- }
155
- : computedFacts;
149
+ const facts = computeConservativeBehaviorFacts(history, { path: request.targetPath, evidence: request.targetEvidence }, null);
156
150
  return {
157
151
  version: 2,
158
152
  history,
@@ -36,7 +36,7 @@ import path from 'node:path';
36
36
  import { randomUUID } from 'node:crypto';
37
37
  import Database from 'better-sqlite3';
38
38
  import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, fingerprintStatement, isOwnerManualCorrectionEvidence, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
- import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
39
+ import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, ensureForwardEvidenceSchema, } from './production-pain-evidence.js';
40
40
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
41
  import { readSourceMaterialAuthorization } from './source-material-authorization.js';
42
42
  import { readConversationIngestionConsent } from './conversation-ingestion/consent.js';
@@ -368,6 +368,10 @@ function openAdmissionStore(workspaceDir, factory) {
368
368
  // hasProductionPainSchema and refused. Converge it here with the SAME
369
369
  // migration the other raw open paths use (idempotent, no-op on v2).
370
370
  migrateLegacyGfiSchema(db);
371
+ // PD Phase 1.5: the canonical readiness probe now also proves the
372
+ // forward-evidence schema (tool_calls.turn_id + environment_snapshots);
373
+ // converge it here like every other raw open path.
374
+ ensureForwardEvidenceSchema(db);
371
375
  // The reconciliation pass reads observation-owned tables (promotion
372
376
  // tails): one open makes the whole governance schema ready.
373
377
  ensureGovernanceSchema(db);
@@ -1,24 +1,57 @@
1
1
  import { denyAllSourceMaterialAuthorization, } from '@principles/core/runtime';
2
2
  import { listGovernanceConversationTextsForHostTurn, listGovernanceTurnTexts } from './governance-observation-store.js';
3
+ import { listPluginTurnTexts } from './plugin-trajectory-turn-store.js';
3
4
  /** Bound on turns per list call — the assembler bounds the window again. */
4
5
  const MAX_TURNS_PER_SESSION = 200;
5
6
  /** The governance-observation hosts whose turns this reader can serve. */
6
7
  const GOVERNANCE_TURN_HOSTS = ['codex', 'workbuddy'];
8
+ /** Map a plugin-store row into the governance row shape the reader serves. */
9
+ function pluginRowToGovernanceRow(row) {
10
+ return { id: row.id, sourceOrdinal: -1, visibleText: row.text, observedAt: row.observedAt };
11
+ }
12
+ function readGovernanceRows(input) {
13
+ const { workspaceDir, kind, sessionId, hostFilter } = input;
14
+ const result = 'hostKind' in hostFilter
15
+ ? listGovernanceTurnTexts({ workspaceDir, kind, sessionId, hostKind: hostFilter.hostKind, limit: MAX_TURNS_PER_SESSION })
16
+ : listGovernanceTurnTexts({ workspaceDir, kind, sessionId, authorizedHostKinds: hostFilter.authorizedHostKinds, limit: MAX_TURNS_PER_SESSION });
17
+ // Unreadable store: the empty result surfaces as an assembler ambiguity
18
+ // note ("no turns found"), never as a fabricated window.
19
+ return result.ok ? result.turns : [];
20
+ }
21
+ /**
22
+ * PRI-1319: read turn rows for one session. `hostKind` scopes the read:
23
+ * - codex/workbuddy → governance rows of THAT host only (unchanged legacy
24
+ * behavior when hostKind is omitted: all authorized governance hosts);
25
+ * - openclaw → the named host's governance rows (live target-turn capture)
26
+ * first, then the plugin's OWN user_turns/assistant_turns tables in the
27
+ * SAME workspace trajectory.db (audit B-2: verbatim turns the CLI reader
28
+ * could never see). Both surfaces sit behind the SAME openclaw consent
29
+ * decision; no other host's session can ever match.
30
+ */
7
31
  function readTurnRows(workspaceDir, kind, query) {
8
32
  const { sessionId, port } = query;
9
33
  if (sessionId.trim().length === 0)
10
34
  return [];
35
+ if (query.hostKind !== undefined) {
36
+ if (!port.isHostSourceMaterialAuthorized(query.hostKind).authorized) {
37
+ // Consent-blocked host: zero rows, and the caller's rc-9 note covers
38
+ // the degradation — consent text must never enter the window.
39
+ return [];
40
+ }
41
+ const governanceRows = readGovernanceRows({ workspaceDir, kind, sessionId, hostFilter: { hostKind: query.hostKind } });
42
+ if (query.hostKind !== 'openclaw' || governanceRows.length > 0)
43
+ return governanceRows;
44
+ const pluginResult = listPluginTurnTexts({ workspaceDir, kind, sessionId, limit: MAX_TURNS_PER_SESSION });
45
+ if (pluginResult.ok)
46
+ return pluginResult.turns.map(pluginRowToGovernanceRow);
47
+ // Plugin store unreadable: surface the failure shape through the same
48
+ // empty-row channel the assembler annotates — a query failure is never
49
+ // fabricated into a successful empty window at THIS layer either, so
50
+ // callers that need the distinction can consult the store directly.
51
+ return [];
52
+ }
11
53
  const authorizedHostKinds = GOVERNANCE_TURN_HOSTS.filter((host) => port.isHostSourceMaterialAuthorized(host).authorized);
12
- const result = listGovernanceTurnTexts({
13
- workspaceDir,
14
- kind,
15
- sessionId,
16
- authorizedHostKinds,
17
- limit: MAX_TURNS_PER_SESSION,
18
- });
19
- // Unreadable store: the empty result surfaces as an assembler ambiguity
20
- // note ("no turns found"), never as a fabricated window.
21
- return result.ok ? result.turns : [];
54
+ return readGovernanceRows({ workspaceDir, kind, sessionId, hostFilter: { authorizedHostKinds } });
22
55
  }
23
56
  /**
24
57
  * Build the governance-observation-backed turn reader for a workspace. The
@@ -31,8 +64,8 @@ function readTurnRows(workspaceDir, kind, query) {
31
64
  export function createGovernanceTrajectoryTurnReader(args) {
32
65
  const port = args.sourceMaterialAuthorization ?? denyAllSourceMaterialAuthorization;
33
66
  return {
34
- listUserTurnsForSession(sessionId) {
35
- return readTurnRows(args.workspaceDir, 'user_turn', { sessionId, port }).map((row, index) => ({
67
+ listUserTurnsForSession(sessionId, hostKind) {
68
+ return readTurnRows(args.workspaceDir, 'user_turn', { sessionId, port, ...(hostKind !== undefined ? { hostKind } : {}) }).map((row, index) => ({
36
69
  id: row.id,
37
70
  turnIndex: row.sourceOrdinal >= 0 ? row.sourceOrdinal : index,
38
71
  rawExcerpt: row.visibleText,
@@ -41,8 +74,8 @@ export function createGovernanceTrajectoryTurnReader(args) {
41
74
  createdAt: row.observedAt,
42
75
  }));
43
76
  },
44
- listAssistantTurns(sessionId) {
45
- return readTurnRows(args.workspaceDir, 'assistant_turn', { sessionId, port }).map((row) => ({
77
+ listAssistantTurns(sessionId, hostKind) {
78
+ return readTurnRows(args.workspaceDir, 'assistant_turn', { sessionId, port, ...(hostKind !== undefined ? { hostKind } : {}) }).map((row) => ({
46
79
  id: row.id,
47
80
  sessionId,
48
81
  runId: '',
@@ -66,12 +99,17 @@ export function createGovernanceTrajectoryTurnReader(args) {
66
99
  return { userTurns: [], assistantTurns: [] };
67
100
  }
68
101
  // Exact-turn reads are a separate entry point from the session-level
69
- // list methods above. Require an explicit supported host and consult
102
+ // reads above. Require an explicit supported host and consult
70
103
  // the latest consent decision on EVERY call before opening the store.
71
104
  // An omitted/unsupported host must never become an unscoped read.
72
- const authorizedHostKind = GOVERNANCE_TURN_HOSTS.find((candidate) => candidate === hostKind);
73
- if (authorizedHostKind === undefined
74
- || !port.isHostSourceMaterialAuthorized(authorizedHostKind).authorized) {
105
+ // PRI-1319: openclaw joins the supported set — its consent decision is
106
+ // consulted the same way, and its turns may live in governance
107
+ // observations (live capture) OR the plugin's own tables.
108
+ const supportedHost = hostKind !== undefined
109
+ && (hostKind === 'openclaw' || GOVERNANCE_TURN_HOSTS.includes(hostKind))
110
+ ? hostKind
111
+ : undefined;
112
+ if (supportedHost === undefined || !port.isHostSourceMaterialAuthorized(supportedHost).authorized) {
75
113
  return { userTurns: [], assistantTurns: [] };
76
114
  }
77
115
  // PRI-1273 (devin BUG_0002): the shared exact-turn selection rule —
@@ -81,13 +119,41 @@ export function createGovernanceTrajectoryTurnReader(args) {
81
119
  // old generic `ORDER BY id LIMIT 64` window cut it).
82
120
  const result = listGovernanceConversationTextsForHostTurn({
83
121
  workspaceDir: args.workspaceDir,
84
- hostKind: authorizedHostKind,
122
+ hostKind: supportedHost,
85
123
  rolloutIdentity: sessionId,
86
124
  hostTurnId,
87
125
  limit: 32,
88
126
  });
89
127
  if (!result.ok)
90
128
  return { userTurns: [], assistantTurns: [] };
129
+ // PRI-1319: an openclaw target turn the live capture did not mirror
130
+ // into governance observations may still exist as the plugin's own
131
+ // user_turns row (the capture's fallback identity is literally
132
+ // `user-turn-row:<rowid>`). Read THAT exact row — never a nearby one.
133
+ const emptyResult = result.rows.length === 0;
134
+ if (emptyResult && supportedHost === 'openclaw' && hostTurnId.startsWith('user-turn-row:')) {
135
+ const rowIdText = hostTurnId.slice('user-turn-row:'.length).trim();
136
+ const rowId = Number.parseInt(rowIdText, 10);
137
+ if (Number.isInteger(rowId) && rowId > 0) {
138
+ const pluginResult = listPluginTurnTexts({ workspaceDir: args.workspaceDir, kind: 'user_turn', sessionId, limit: MAX_TURNS_PER_SESSION });
139
+ if (pluginResult.ok) {
140
+ const matched = pluginResult.turns.find((turn) => turn.id === rowId);
141
+ if (matched !== undefined) {
142
+ return {
143
+ userTurns: [{
144
+ id: matched.id,
145
+ turnIndex: matched.id,
146
+ rawExcerpt: matched.text,
147
+ correctionDetected: matched.correctionDetected,
148
+ correctionCue: null,
149
+ createdAt: matched.observedAt,
150
+ }],
151
+ assistantTurns: [],
152
+ };
153
+ }
154
+ }
155
+ }
156
+ }
91
157
  return {
92
158
  userTurns: result.rows.flatMap((row, index) => row.kind === 'user_turn' ? [{
93
159
  id: row.id,
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export * from './rule-implementation-runtime.js';
20
20
  export * from './production-pain-evidence.js';
21
21
  export * from './governance-observation-store.js';
22
22
  export * from './governance-trajectory-turn-reader.js';
23
+ export * from './plugin-trajectory-turn-store.js';
23
24
  export * from './trajectory-retention.js';
24
25
  export * from './conversation-ingestion/index.js';
25
26
  export * from './source-material-authorization.js';
@@ -93,6 +94,22 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
93
94
  hostKind?: GovernanceHostKind;
94
95
  /** Host project cwd, distinct from the workspace owning shared PD state. */
95
96
  projectDir?: string;
97
+ /**
98
+ * PD Phase 1.5 (SPEC R10): adapter-known environment facts captured ONCE
99
+ * per session into trajectory.db::environment_snapshots. Only these
100
+ * allow-listed fields exist — an adapter that does not know a fact omits
101
+ * it and the row records NULL (unknown), never a guess and never a
102
+ * secret-bearing value.
103
+ */
104
+ afterToolCallEnvironment?: {
105
+ hostVersion?: string | null;
106
+ runtimeVersion?: string | null;
107
+ agentConfigDigest?: string | null;
108
+ modelConfigDigest?: string | null;
109
+ repoCommit?: string | null;
110
+ workspaceStateDigest?: string | null;
111
+ featureFlagsDigest?: string | null;
112
+ };
96
113
  /** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
97
114
  toolSemantics?: ToolSemanticRegistry;
98
115
  /**
package/dist/index.js CHANGED
@@ -35,6 +35,10 @@ export * from './governance-observation-store.js';
35
35
  // PRI-1265: the governance-observation-backed TrajectoryTurnReader injected by
36
36
  // pd-cli diagnose/pain retry and the Codex/WorkBuddy workers.
37
37
  export * from './governance-trajectory-turn-reader.js';
38
+ // PRI-1319: read-only access to the OpenClaw plugin's own user_turns/
39
+ // assistant_turns tables (same canonical workspace trajectory.db) — closes
40
+ // the audit's B-2 read gap for CLI/worker diagnosis paths.
41
+ export * from './plugin-trajectory-turn-store.js';
38
42
  // SPEC-PD-TR-001: trajectory retention I/O boundary (lock + marker + export
39
43
  // list + explicit VACUUM). The policy/batch engine is pure and lives in
40
44
  // `@principles/core/runtime`.
@@ -251,6 +255,7 @@ export function createProductionHostRuntime(options = {}) {
251
255
  ...(options.ruleImplementationRuntime ? { implementationRuntime: options.ruleImplementationRuntime } : {}),
252
256
  ...(options.toolSemantics ? { toolSemantics: options.toolSemantics } : {}),
253
257
  });
258
+ const { afterToolCallEnvironment } = options;
254
259
  return createHostRuntime({
255
260
  afterToolCall: options.afterToolCall ?? createProductionPainEvidenceHandler({
256
261
  ...(options.painEnrichmentProvider ? { painEnrichmentProvider: options.painEnrichmentProvider } : {}),
@@ -258,6 +263,9 @@ export function createProductionHostRuntime(options = {}) {
258
263
  ...(options.hostKind ? { hostKind: options.hostKind } : {}),
259
264
  ...(options.projectDir ? { projectDir: options.projectDir } : {}),
260
265
  ...(options.events ? { events: options.events } : {}),
266
+ // PD Phase 1.5 (SPEC R10): adapter-supplied environment facts for the
267
+ // forward evidence capture; fields the adapter omits stay NULL.
268
+ ...(afterToolCallEnvironment ? { environmentProvider: () => afterToolCallEnvironment } : {}),
261
269
  }),
262
270
  beforeToolCall: options.beforeToolCall ?? productionGate,
263
271
  async beforePromptBuild(event) {
@@ -0,0 +1,40 @@
1
+ export interface PluginTurnTextRow {
2
+ readonly id: number;
3
+ readonly kind: 'user_turn' | 'assistant_turn';
4
+ readonly text: string;
5
+ /** 'inline' = full stored text; 'excerpt' = bounded excerpt of a blob-offloaded body. */
6
+ readonly textSource: 'inline' | 'excerpt';
7
+ readonly observedAt: string;
8
+ readonly correctionDetected: boolean;
9
+ }
10
+ export type PluginTurnTextResult = {
11
+ readonly ok: true;
12
+ readonly turns: readonly PluginTurnTextRow[];
13
+ } | {
14
+ readonly ok: false;
15
+ readonly reason: string;
16
+ readonly nextAction: string;
17
+ };
18
+ export type PluginTurnsPresentResult = {
19
+ readonly ok: true;
20
+ readonly present: boolean;
21
+ } | {
22
+ readonly ok: false;
23
+ readonly reason: string;
24
+ readonly nextAction: string;
25
+ };
26
+ export interface ObservationDatabaseFactoryLike {
27
+ (dbPath: string): unknown;
28
+ }
29
+ export declare function listPluginTurnTexts(input: {
30
+ readonly workspaceDir: string;
31
+ readonly kind: 'user_turn' | 'assistant_turn';
32
+ readonly sessionId: string;
33
+ readonly limit?: number;
34
+ readonly databaseFactory?: ObservationDatabaseFactoryLike;
35
+ }): PluginTurnTextResult;
36
+ export declare function hasPluginUserTurns(input: {
37
+ readonly workspaceDir: string;
38
+ readonly sessionId: string;
39
+ readonly databaseFactory?: ObservationDatabaseFactoryLike;
40
+ }): PluginTurnsPresentResult;
@@ -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
  }
@@ -1,4 +1,5 @@
1
1
  import { type RuleHostResult, type ToolSemanticRegistry, type GovernanceHostKind } from '@principles/core/runtime';
2
+ import type { RuleTargetEvidence } from '@principles/core/runtime/internalization/rule-context-v2';
2
3
  import type { HostEvent, HostEventResult } from '@principles/core/host';
3
4
  import { type RuleImplementationRuntime } from './rule-implementation-runtime.js';
4
5
  /**
@@ -27,6 +28,8 @@ export interface ProductionRuleContextRequest {
27
28
  targetPath: string;
28
29
  toolName: string;
29
30
  rawPayload: unknown;
31
+ /** Provenance of targetPath when produced by the shared action builder; absent only for legacy/test providers. */
32
+ targetEvidence?: RuleTargetEvidence;
30
33
  }
31
34
  export type RuleContextProvider = (request: ProductionRuleContextRequest) => unknown | Promise<unknown>;
32
35
  export interface RuleInputEnrichment {
@@ -224,6 +224,7 @@ export function createProductionRuleHostGate(options = {}) {
224
224
  const request = {
225
225
  workspaceDir: event.context.workspaceDir, sessionId: event.context.sessionId,
226
226
  targetPath: action.normalizedPath, toolName: input.toolName, rawPayload: event.rawPayload,
227
+ targetEvidence: action.targetEvidence,
227
228
  };
228
229
  if (options.ruleInputEnrichmentProvider) {
229
230
  try {
@@ -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 !== 'granted') {
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') {
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { computeBehaviorFacts, } from '@principles/core/runtime';
3
- import { assembleBehaviorHistory } from './behavior-history.js';
3
+ import { assembleBehaviorHistory, computeConservativeBehaviorFacts } from './behavior-history.js';
4
4
  import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
5
5
  const HISTORY_LIMIT = 100;
6
6
  const MAX_REASON_LENGTH = 240;
@@ -96,23 +96,14 @@ export function createWorkbuddyRuleContextProvider(options) {
96
96
  const history = assembleBehaviorHistory(historyRows.rows, historyRows.truncated, {
97
97
  projectDir,
98
98
  toolSemantics: options.toolSemantics,
99
+ currentToolUseId: options.currentToolCallId,
99
100
  });
100
101
  // WorkBuddy exposes its shell as the Bash tool, and MCP-style tools may
101
102
  // resolve to 'other' absent from this host's semantic registry. Either
102
103
  // may read or mutate files, so target-read absence and exact action
103
104
  // counts cannot be asserted from this partial semantic view (same
104
105
  // conservative rule as the Codex provider).
105
- const factsIncomplete = history.truncated || history.calls.some((call) => call.canonicalKind === 'execute' || call.canonicalKind === 'other');
106
- const computedFacts = computeBehaviorFacts(history, factsIncomplete ? null : request.targetPath, null);
107
- const facts = factsIncomplete
108
- ? {
109
- priorReadOfTarget: 'unknown',
110
- readCount: null,
111
- writeCount: null,
112
- uniqueWritePathCount: null,
113
- sameActionBlockCount: null,
114
- }
115
- : computedFacts;
106
+ const facts = computeConservativeBehaviorFacts(history, { path: request.targetPath, evidence: request.targetEvidence }, null);
116
107
  return {
117
108
  version: 2,
118
109
  history,
@@ -21,7 +21,14 @@ function contextRow(value) {
21
21
  if (Object.keys(params).some((key) => key === '__proto__' || key === 'constructor' || key === 'prototype')) {
22
22
  throw new Error('Unsafe keys in persisted trajectory params');
23
23
  }
24
- return { id: value.id, toolName: value.tool_name, outcome: value.outcome, paramsJson: value.params_json };
24
+ const toolUseId = typeof value.tool_use_id === 'string' && value.tool_use_id.length > 0 ? value.tool_use_id : undefined;
25
+ return {
26
+ id: value.id,
27
+ toolName: value.tool_name,
28
+ outcome: value.outcome,
29
+ paramsJson: value.params_json,
30
+ ...(toolUseId !== undefined ? { toolUseId } : {}),
31
+ };
25
32
  }
26
33
  function source(db) {
27
34
  return {
@@ -102,7 +109,7 @@ export function readWorkspaceRuleContextRowsBefore(workspaceDir, input) {
102
109
  return db.transaction(() => {
103
110
  // Attribution-aware read: fetch one extra slot beyond the limit so the
104
111
  // partition counts stay truthful about a truncated window's tail.
105
- const selectColumns = includeHostKind ? 'id, tool_name, outcome, params_json, host_kind' : 'id, tool_name, outcome, params_json';
112
+ const selectColumns = includeHostKind ? 'id, tool_name, outcome, params_json, host_kind, tool_use_id' : 'id, tool_name, outcome, params_json, tool_use_id';
106
113
  const fetched = db.prepare(`
107
114
  SELECT ${selectColumns}
108
115
  FROM tool_calls
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.8.1",
3
+ "version": "4.9.1",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -39,7 +39,7 @@
39
39
  "lint": "eslint \"src/**/*.ts\""
40
40
  },
41
41
  "dependencies": {
42
- "@principles/core": "^8.4.1",
42
+ "@principles/core": "^8.5.1",
43
43
  "@principles/install-layout": "^0.12.0",
44
44
  "better-sqlite3": "^13.0.3",
45
45
  "js-yaml": "^5.4.3"
@@ -57,5 +57,5 @@
57
57
  "url": "git+https://github.com/csuzngjh/principles.git"
58
58
  },
59
59
  "license": "Apache-2.0",
60
- "gitHead": "ff62137821c993773cc7df104a01625310776c51"
60
+ "gitHead": "655a074ce2dc4bf776885303e04776f60996099c"
61
61
  }