@principles/host-runtime 5.1.0 → 5.3.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.
Files changed (56) hide show
  1. package/dist/advisory-delivery.d.ts +34 -0
  2. package/dist/advisory-delivery.js +69 -0
  3. package/dist/behavior-history.js +1 -1
  4. package/dist/cli-recovery-probe.d.ts +23 -2
  5. package/dist/cli-recovery-probe.js +98 -9
  6. package/dist/codex-ingestion-consent.d.ts +5 -6
  7. package/dist/codex-ingestion-consent.js +5 -6
  8. package/dist/codex-rule-context-provider.js +30 -7
  9. package/dist/conversation-ingestion/consent.d.ts +14 -31
  10. package/dist/conversation-ingestion/consent.js +14 -223
  11. package/dist/fact-assembler.d.ts +91 -0
  12. package/dist/fact-assembler.js +318 -0
  13. package/dist/forward-observation.d.ts +6 -0
  14. package/dist/forward-observation.js +2 -1
  15. package/dist/host-liveness-contract.js +12 -0
  16. package/dist/index.d.ts +11 -1
  17. package/dist/index.js +13 -32
  18. package/dist/internalization-consumer-cycle.js +1 -1
  19. package/dist/mode-state-facts.d.ts +41 -0
  20. package/dist/mode-state-facts.js +224 -0
  21. package/dist/pain-inbox.d.ts +28 -0
  22. package/dist/pain-inbox.js +194 -46
  23. package/dist/product-telemetry/consent-store.d.ts +9 -47
  24. package/dist/product-telemetry/consent-store.js +18 -131
  25. package/dist/production-pain-evidence.d.ts +9 -0
  26. package/dist/production-pain-evidence.js +22 -2
  27. package/dist/production-policy-gate.d.ts +104 -0
  28. package/dist/production-policy-gate.js +379 -0
  29. package/dist/production-rulehost-gate.d.ts +6 -0
  30. package/dist/production-rulehost-gate.js +160 -31
  31. package/dist/prompt-activation-event.d.ts +29 -0
  32. package/dist/prompt-activation-event.js +80 -0
  33. package/dist/prompt-injection-budget-observation.d.ts +0 -11
  34. package/dist/prompt-injection-budget-observation.js +0 -11
  35. package/dist/rule-policy-active.d.ts +80 -0
  36. package/dist/rule-policy-active.js +197 -0
  37. package/dist/rule-policy-host-defaults.d.ts +19 -0
  38. package/dist/rule-policy-host-defaults.js +12 -0
  39. package/dist/rule-policy-paths-fs.d.ts +20 -0
  40. package/dist/rule-policy-paths-fs.js +58 -0
  41. package/dist/rule-policy-replay-evidence.d.ts +52 -0
  42. package/dist/rule-policy-replay-evidence.js +259 -0
  43. package/dist/session-write-targets.d.ts +86 -0
  44. package/dist/session-write-targets.js +216 -0
  45. package/dist/signal-classifier.d.ts +1 -0
  46. package/dist/signal-classifier.js +1 -1
  47. package/dist/signal-rate-limiter.d.ts +34 -0
  48. package/dist/signal-rate-limiter.js +83 -0
  49. package/dist/trajectory-retention.d.ts +8 -0
  50. package/dist/trajectory-retention.js +29 -0
  51. package/dist/trusted-pd-binary.d.ts +10 -0
  52. package/dist/trusted-pd-binary.js +38 -0
  53. package/dist/workbuddy-rule-context-provider.js +31 -10
  54. package/dist/workspace-behavior-evidence.d.ts +55 -0
  55. package/dist/workspace-behavior-evidence.js +93 -0
  56. package/package.json +24 -4
@@ -0,0 +1,34 @@
1
+ import { type GovernanceHostKind } from '@principles/core/runtime';
2
+ import type { HostEventResult } from '@principles/core/host';
3
+ /**
4
+ * The reminder to deliver for an allowed call, or undefined. `metadata` is untrusted at this
5
+ * boundary (rc-1): anything but a non-blank string on an allow result is no reminder, and the
6
+ * text is bounded to the contract length.
7
+ */
8
+ export declare function liveAdvisoryOf(result: HostEventResult): string | undefined;
9
+ /** Exact rule ids whose complete reminder text is represented in `metadata.advisory`. */
10
+ export declare function liveAdvisoryRuleIdsOf(result: HostEventResult): readonly string[];
11
+ export interface PolicyAdvisoryDeliveryConfirmation {
12
+ /** Governance workspace whose `.pd/state.db` holds the Decision_Ledger. */
13
+ workspaceDir: string;
14
+ /** Project identity the gate used when it wrote the decision rows. */
15
+ projectWorkspacePath: string;
16
+ hostKind: GovernanceHostKind;
17
+ hostSessionId: string;
18
+ toolCallId: string;
19
+ /** Exact rules whose reminder text reached the host channel. */
20
+ ruleIds: readonly string[];
21
+ }
22
+ export type PolicyAdvisoryDeliveryResult = {
23
+ readonly ok: true;
24
+ readonly ruleIds: readonly string[];
25
+ } | {
26
+ readonly ok: false;
27
+ readonly reason: string;
28
+ };
29
+ /**
30
+ * Records the host-side delivery receipt for one physical tool call. Best-effort by
31
+ * contract: a database/write failure is reported to the adapter and never thrown back
32
+ * into the host hook. An empty `ruleIds` means no matching unconfirmed reminder existed.
33
+ */
34
+ export declare function confirmPolicyAdvisoryDelivered(input: PolicyAdvisoryDeliveryConfirmation): PolicyAdvisoryDeliveryResult;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Host-side reading of the gate's reminder text (SPEC-PD-RULE-POLICY-001 Requirement 12.5).
3
+ *
4
+ * The production gate puts the reminder of the LIVE RulePolicyV2 rules in `metadata.advisory` of
5
+ * an allow result (never shadow, never challenger, never a RuleCode rule). Each host adapter
6
+ * hands that text to the model through its own channel; this is the one place that validates it.
7
+ */
8
+ import { RULE_HOST_ADVISORY_MAX } from '@principles/core/runtime/internalization/rule-policy-gate';
9
+ import { SqliteDecisionLedgerStore } from '@principles/core/runtime/internalization/rule-policy-modes';
10
+ import { SqliteConnection } from '@principles/core/runtime';
11
+ /**
12
+ * The reminder to deliver for an allowed call, or undefined. `metadata` is untrusted at this
13
+ * boundary (rc-1): anything but a non-blank string on an allow result is no reminder, and the
14
+ * text is bounded to the contract length.
15
+ */
16
+ export function liveAdvisoryOf(result) {
17
+ if (result.decision !== 'allow')
18
+ return undefined;
19
+ const advisory = result.metadata !== undefined && Object.hasOwn(result.metadata, 'advisory') ? result.metadata.advisory : undefined;
20
+ if (typeof advisory !== 'string' || advisory.trim().length === 0)
21
+ return undefined;
22
+ return advisory.slice(0, RULE_HOST_ADVISORY_MAX);
23
+ }
24
+ /** Exact rule ids whose complete reminder text is represented in `metadata.advisory`. */
25
+ export function liveAdvisoryRuleIdsOf(result) {
26
+ if (result.decision !== 'allow')
27
+ return [];
28
+ const value = result.metadata !== undefined && Object.hasOwn(result.metadata, 'advisoryRuleIds') ? result.metadata.advisoryRuleIds : undefined;
29
+ if (!Array.isArray(value))
30
+ return [];
31
+ const ids = new Set();
32
+ for (const entry of value) {
33
+ if (typeof entry !== 'string' || entry.trim().length === 0)
34
+ return [];
35
+ ids.add(entry);
36
+ }
37
+ return [...ids].sort();
38
+ }
39
+ /**
40
+ * Records the host-side delivery receipt for one physical tool call. Best-effort by
41
+ * contract: a database/write failure is reported to the adapter and never thrown back
42
+ * into the host hook. An empty `ruleIds` means no matching unconfirmed reminder existed.
43
+ */
44
+ export function confirmPolicyAdvisoryDelivered(input) {
45
+ let connection = null;
46
+ try {
47
+ connection = new SqliteConnection({ workspaceDir: input.workspaceDir, readonly: false, bootstrapIfMissing: false });
48
+ const ruleIds = new SqliteDecisionLedgerStore(connection).markAdvisoryDelivered({
49
+ hostKind: input.hostKind,
50
+ projectWorkspacePath: input.projectWorkspacePath,
51
+ hostSessionId: input.hostSessionId,
52
+ toolCallId: input.toolCallId,
53
+ ruleIds: input.ruleIds,
54
+ });
55
+ return { ok: true, ruleIds };
56
+ }
57
+ catch (error) {
58
+ const message = error instanceof Error ? error.message : String(error);
59
+ return { ok: false, reason: message.replace(/\s+/g, ' ').slice(0, 300) };
60
+ }
61
+ finally {
62
+ try {
63
+ connection?.close();
64
+ }
65
+ catch {
66
+ // The receipt is best-effort; close failure must not affect the host hook.
67
+ }
68
+ }
69
+ }
@@ -7,7 +7,7 @@ export function computeConservativeBehaviorFacts(history, target, sameActionBloc
7
7
  }
8
8
  return computeCoreConservativeBehaviorFacts(history, target, sameActionBlockCount);
9
9
  }
10
- const VALID_OUTCOMES = new Set(['success', 'failure', 'blocked']);
10
+ const VALID_OUTCOMES = new Set(['success', 'failure', 'blocked', 'unknown']);
11
11
  function isPlainObject(value) {
12
12
  return typeof value === 'object' && value !== null && !Array.isArray(value);
13
13
  }
@@ -14,7 +14,13 @@ import type { RecoveryCapabilityEvidence } from '@principles/core/runtime';
14
14
  * through real parsing, workspace binding, and target-resolution
15
15
  * preconditions, with the dry-run guard returning BEFORE any governance
16
16
  * audit write or store mutation. A nonexistent probe id keeps the
17
- * precondition honest without touching any real activation.
17
+ * precondition honest without touching any real activation;
18
+ * - mode_declare / mode_waive: the REAL pd mode declare|waive entry with a
19
+ * session id that cannot exist in the trajectory. Both commands refuse with
20
+ * session_not_found only AFTER the governance workspace's trajectory.db was
21
+ * opened and queried and BEFORE anything is written, so that refusal (not a
22
+ * success) is the evidence that the entry parses, binds the workspace and
23
+ * writes nothing.
18
24
  *
19
25
  * Console-channel capabilities (`rulecode_global_pause`,
20
26
  * `owner_review_access`) can never be verified from a CLI subprocess — the
@@ -67,5 +73,20 @@ export declare function probeCliActivationStatus(options: CliRecoveryProbeOption
67
73
  * an honest not-found while the entry itself is proven executable.
68
74
  */
69
75
  export declare function probeCliDeactivateDryRun(options: CliRecoveryProbeOptions): Promise<RecoveryCapabilityEvidence>;
70
- /** Both CLI-channel capabilities plus explicit NOT-VERIFIED entries for the console channel (fail closed, never fabricated). */
76
+ /**
77
+ * `pd mode waive` against a session id that cannot exist: the real entry, parsing and
78
+ * workspace binding, refused with `session_not_found` before any quota or store write.
79
+ */
80
+ export declare function probeCliModeWaive(options: CliRecoveryProbeOptions): Promise<RecoveryCapabilityEvidence>;
81
+ /**
82
+ * `pd mode declare` with a valid declaration in a throw-away project directory and a
83
+ * session id that cannot exist: refused with `session_not_found` after the declaration
84
+ * was read and validated and before anything is recorded. The directory is removed again.
85
+ */
86
+ export declare function probeCliModeDeclare(options: CliRecoveryProbeOptions): Promise<RecoveryCapabilityEvidence>;
87
+ /**
88
+ * The four CLI-channel capabilities (run concurrently so the batch stays inside one console
89
+ * request budget) plus explicit NOT-VERIFIED entries for the console channel (fail closed,
90
+ * never fabricated).
91
+ */
71
92
  export declare function probeCliRecoveryCapabilities(options: CliRecoveryProbeOptions): Promise<RecoveryCapabilityEvidence[]>;
@@ -1,5 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { existsSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
3
5
  import path from 'node:path';
4
6
  import { fileURLToPath } from 'node:url';
5
7
  /**
@@ -17,7 +19,13 @@ import { fileURLToPath } from 'node:url';
17
19
  * through real parsing, workspace binding, and target-resolution
18
20
  * preconditions, with the dry-run guard returning BEFORE any governance
19
21
  * audit write or store mutation. A nonexistent probe id keeps the
20
- * precondition honest without touching any real activation.
22
+ * precondition honest without touching any real activation;
23
+ * - mode_declare / mode_waive: the REAL pd mode declare|waive entry with a
24
+ * session id that cannot exist in the trajectory. Both commands refuse with
25
+ * session_not_found only AFTER the governance workspace's trajectory.db was
26
+ * opened and queried and BEFORE anything is written, so that refusal (not a
27
+ * success) is the evidence that the entry parses, binds the workspace and
28
+ * writes nothing.
21
29
  *
22
30
  * Console-channel capabilities (`rulecode_global_pause`,
23
31
  * `owner_review_access`) can never be verified from a CLI subprocess — the
@@ -68,7 +76,8 @@ export function resolveCliRecoveryEntry() {
68
76
  function isRecord(value) {
69
77
  return typeof value === 'object' && value !== null && !Array.isArray(value);
70
78
  }
71
- function runCli(cliEntry, args, timeoutMs) {
79
+ function runCli(cliEntry, args, budget) {
80
+ const { timeoutMs, acceptedExitCodes = [0] } = budget;
72
81
  return new Promise(resolve => {
73
82
  // Static argv list — no shell, no interpolated command string.
74
83
  const child = spawn(process.execPath, [cliEntry, ...args], {
@@ -98,7 +107,7 @@ function runCli(cliEntry, args, timeoutMs) {
98
107
  child.stderr.on('data', () => { });
99
108
  child.on('error', error => finish({ ok: false, detail: `spawn failed: ${error instanceof Error ? error.message : String(error)}` }));
100
109
  child.on('close', code => {
101
- if (code !== 0) {
110
+ if (code === null || !acceptedExitCodes.includes(code)) {
102
111
  finish({ ok: false, detail: `exited with code ${code}` });
103
112
  return;
104
113
  }
@@ -122,7 +131,7 @@ function capability(capabilityId, evidence) {
122
131
  const CONSOLE_UNVERIFIABLE_DETAIL = 'console-channel control: verifying the HTTP-only recovery entry requires the Owner Console process; a CLI subprocess cannot produce this evidence';
123
132
  /** `pd activation list --json` — the pd_status status surface, read-only. */
124
133
  export async function probeCliActivationStatus(options) {
125
- const run = await runCli(options.cliEntry, ['activation', 'list', '--json', '--workspace', options.workspaceDir], options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS);
134
+ const run = await runCli(options.cliEntry, ['activation', 'list', '--json', '--workspace', options.workspaceDir], { timeoutMs: options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS });
126
135
  if (!run.ok)
127
136
  return capability('pd_status', { channel: 'cli', ok: false, workspaceMatched: false, detail: `pd activation list: ${run.detail}` });
128
137
  let parsed;
@@ -151,7 +160,7 @@ export async function probeCliActivationStatus(options) {
151
160
  * an honest not-found while the entry itself is proven executable.
152
161
  */
153
162
  export async function probeCliDeactivateDryRun(options) {
154
- const run = await runCli(options.cliEntry, ['activation', 'deactivate', '--activation-id', DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID, '--dry-run', '--json', '--workspace', options.workspaceDir], options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS);
163
+ const run = await runCli(options.cliEntry, ['activation', 'deactivate', '--activation-id', DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID, '--dry-run', '--json', '--workspace', options.workspaceDir], { timeoutMs: options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS });
155
164
  if (!run.ok)
156
165
  return capability('rulecode_deactivate', { channel: 'cli', ok: false, workspaceMatched: false, detail: `pd activation deactivate --dry-run: ${run.detail}` });
157
166
  let parsed;
@@ -169,13 +178,93 @@ export async function probeCliDeactivateDryRun(options) {
169
178
  }
170
179
  return capability('rulecode_deactivate', { channel: 'cli', ok: true, workspaceMatched: true });
171
180
  }
172
- /** Both CLI-channel capabilities plus explicit NOT-VERIFIED entries for the console channel (fail closed, never fabricated). */
181
+ /** A declaration `pd mode declare` accepts; the probe never gets as far as recording it. */
182
+ const MODE_PROBE_DECLARATION = JSON.stringify({
183
+ version: 1,
184
+ situation: { class: 'substantial', reason: 'recovery reachability probe' },
185
+ mode: 'plan',
186
+ acts: { scope: { inScope: ['src/a.ts'], outOfScope: ['everything else'] } },
187
+ });
188
+ const MODE_PROBE_REASON = 'recovery reachability probe, nothing is recorded';
189
+ /**
190
+ * Judges the output of a `pd mode ...` probe run. The only passing result is the refusal
191
+ * the command gives AFTER it queried the governance workspace's trajectory and BEFORE it
192
+ * writes anything; a run that recorded something, or was refused earlier, is not evidence.
193
+ */
194
+ function judgeModeProbe(command, run) {
195
+ if (!run.ok)
196
+ return { ok: false, detail: `${command}: ${run.detail}` };
197
+ let parsed;
198
+ try {
199
+ parsed = JSON.parse(run.stdout);
200
+ }
201
+ catch {
202
+ return { ok: false, detail: `${command}: stdout is not parseable JSON` };
203
+ }
204
+ if (!isRecord(parsed) || parsed.status !== 'refused' || typeof parsed.reason !== 'string') {
205
+ return { ok: false, detail: `${command}: output is not a structured refusal (the probe must never record anything)` };
206
+ }
207
+ if (parsed.reason !== 'session_not_found') {
208
+ return { ok: false, detail: `${command}: refused with ${parsed.reason} before the governance workspace was consulted` };
209
+ }
210
+ if (typeof parsed.detail !== 'string' || !parsed.detail.startsWith('session_not_present_in_trajectory')) {
211
+ return { ok: false, detail: `${command}: the governance workspace's trajectory was not queried (${typeof parsed.detail === 'string' ? parsed.detail.split(';')[0] : 'no detail'})` };
212
+ }
213
+ return { ok: true };
214
+ }
215
+ function modeEvidence(capabilityId, command, run) {
216
+ const verdict = judgeModeProbe(command, run);
217
+ if (!verdict.ok)
218
+ return capability(capabilityId, { channel: 'cli', ok: false, workspaceMatched: false, detail: verdict.detail });
219
+ return capability(capabilityId, { channel: 'cli', ok: true, workspaceMatched: true });
220
+ }
221
+ /**
222
+ * `pd mode waive` against a session id that cannot exist: the real entry, parsing and
223
+ * workspace binding, refused with `session_not_found` before any quota or store write.
224
+ */
225
+ export async function probeCliModeWaive(options) {
226
+ const run = await runCli(options.cliEntry, ['mode', 'waive', '--workspace', options.workspaceDir, '--project', options.workspaceDir, '--session', `pd-recovery-probe-${randomUUID()}`, '--rule', 'recovery-probe', '--reason', MODE_PROBE_REASON, '--json'], { timeoutMs: options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS, acceptedExitCodes: [1] });
227
+ return modeEvidence('mode_waive', 'pd mode waive', run);
228
+ }
229
+ /**
230
+ * `pd mode declare` with a valid declaration in a throw-away project directory and a
231
+ * session id that cannot exist: refused with `session_not_found` after the declaration
232
+ * was read and validated and before anything is recorded. The directory is removed again.
233
+ */
234
+ export async function probeCliModeDeclare(options) {
235
+ let projectDir;
236
+ try {
237
+ projectDir = mkdtempSync(path.join(tmpdir(), 'pd-recovery-probe-'));
238
+ mkdirSync(path.join(projectDir, '.principles', 'modes'), { recursive: true });
239
+ writeFileSync(path.join(projectDir, '.principles', 'modes', 'probe.json'), MODE_PROBE_DECLARATION, 'utf8');
240
+ const run = await runCli(options.cliEntry, ['mode', 'declare', '--workspace', options.workspaceDir, '--project', projectDir, '--session', `pd-recovery-probe-${randomUUID()}`, '--file', '.principles/modes/probe.json', '--json'], { timeoutMs: options.timeoutMs ?? CLI_RECOVERY_PROBE_TIMEOUT_MS, acceptedExitCodes: [1] });
241
+ return modeEvidence('mode_declare', 'pd mode declare', run);
242
+ }
243
+ catch (error) {
244
+ return capability('mode_declare', { channel: 'cli', ok: false, workspaceMatched: false, detail: `pd mode declare: probe setup failed: ${error instanceof Error ? error.message : String(error)}` });
245
+ }
246
+ finally {
247
+ if (projectDir !== undefined)
248
+ rmSync(projectDir, { recursive: true, force: true });
249
+ }
250
+ }
251
+ /**
252
+ * The four CLI-channel capabilities (run concurrently so the batch stays inside one console
253
+ * request budget) plus explicit NOT-VERIFIED entries for the console channel (fail closed,
254
+ * never fabricated).
255
+ */
173
256
  export async function probeCliRecoveryCapabilities(options) {
174
- const status = await probeCliActivationStatus(options);
175
- const deactivate = await probeCliDeactivateDryRun(options);
257
+ const [status, deactivate, modeDeclare, modeWaive] = await Promise.all([
258
+ probeCliActivationStatus(options),
259
+ probeCliDeactivateDryRun(options),
260
+ probeCliModeDeclare(options),
261
+ probeCliModeWaive(options),
262
+ ]);
176
263
  return [
177
264
  status,
178
265
  deactivate,
266
+ modeDeclare,
267
+ modeWaive,
179
268
  capability('rulecode_global_pause', { channel: 'console', ok: false, workspaceMatched: false, detail: CONSOLE_UNVERIFIABLE_DETAIL }),
180
269
  capability('owner_review_access', { channel: 'console', ok: false, workspaceMatched: false, detail: CONSOLE_UNVERIFIABLE_DETAIL }),
181
270
  ];
@@ -8,10 +8,9 @@
8
8
  * Codex-named API stable for existing consumers (pd-cli setup / health) for
9
9
  * ONE version cycle; new code reads the seam API directly.
10
10
  *
11
- * Behavior notes vs the pre-PRI-1171 store:
12
- * - the active authority file is now under `.state/` — the legacy
13
- * `.pd/codex-ingestion-consent.json` (v2) is migrated on first read and
14
- * renamed `.superseded` (kept for audit, never read again);
11
+ * Behavior notes:
12
+ * - the sole authority file is `<workspace>/.state/conversation-ingestion-consent.json`
13
+ * (v3; legacy `.pd/codex-ingestion-consent.json` v2 migration was retired in Clean-Slate Wave 2A);
15
14
  * - `decidedVia` additionally accepts `owner_directive` (with evidenceRef);
16
15
  * - records gain an optional `evidenceRef`;
17
16
  * - the disclosure version is still stamped from the frozen Codex
@@ -19,7 +18,7 @@
19
18
  */
20
19
  import { type ConversationIngestionConsentDecision, type ConversationIngestionConsentDecidedVia, type ConversationIngestionConsentRead, type ConversationIngestionConsentRecord, type ConversationIngestionConsentState, type ConversationIngestionConsentWrite } from './conversation-ingestion/consent.js';
21
20
  export declare const CODEX_INGESTION_CONSENT_FILENAME = "codex-ingestion-consent.json";
22
- /** Now the v3 ledger schema version (the v2 file format is legacy/migrating-only). */
21
+ /** Canonical v3 ledger schema version. */
23
22
  export declare const CODEX_INGESTION_CONSENT_SCHEMA_VERSION = "3";
24
23
  export type CodexIngestionConsentDecision = ConversationIngestionConsentDecision;
25
24
  export type CodexIngestionConsentDecidedVia = ConversationIngestionConsentDecidedVia;
@@ -29,7 +28,7 @@ export type CodexIngestionConsentWrite = ConversationIngestionConsentWrite;
29
28
  export type CodexIngestionConsentState = ConversationIngestionConsentState;
30
29
  /** Path of the ACTIVE authority (the v3 ledger under `.state/`). */
31
30
  export declare function getCodexIngestionConsentPath(workspaceDir: string): string;
32
- /** Read the Codex slot of the v3 ledger (migrating a legacy v2 file when present). */
31
+ /** Read the Codex slot of the v3 ledger. */
33
32
  export declare function readCodexIngestionConsent(workspaceDir: string): CodexIngestionConsentRead;
34
33
  /**
35
34
  * Record an explicit Codex consent decision. The disclosure version is stamped
@@ -8,10 +8,9 @@
8
8
  * Codex-named API stable for existing consumers (pd-cli setup / health) for
9
9
  * ONE version cycle; new code reads the seam API directly.
10
10
  *
11
- * Behavior notes vs the pre-PRI-1171 store:
12
- * - the active authority file is now under `.state/` — the legacy
13
- * `.pd/codex-ingestion-consent.json` (v2) is migrated on first read and
14
- * renamed `.superseded` (kept for audit, never read again);
11
+ * Behavior notes:
12
+ * - the sole authority file is `<workspace>/.state/conversation-ingestion-consent.json`
13
+ * (v3; legacy `.pd/codex-ingestion-consent.json` v2 migration was retired in Clean-Slate Wave 2A);
15
14
  * - `decidedVia` additionally accepts `owner_directive` (with evidenceRef);
16
15
  * - records gain an optional `evidenceRef`;
17
16
  * - the disclosure version is still stamped from the frozen Codex
@@ -20,13 +19,13 @@
20
19
  import { CODEX_INGESTION_DISCLOSURE_VERSION } from './codex-disclosure.js';
21
20
  import { CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION, deriveConversationIngestionConsentState, getConversationIngestionConsentPath, readConversationIngestionConsent, recordConversationIngestionConsent, } from './conversation-ingestion/consent.js';
22
21
  export const CODEX_INGESTION_CONSENT_FILENAME = 'codex-ingestion-consent.json';
23
- /** Now the v3 ledger schema version (the v2 file format is legacy/migrating-only). */
22
+ /** Canonical v3 ledger schema version. */
24
23
  export const CODEX_INGESTION_CONSENT_SCHEMA_VERSION = CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION;
25
24
  /** Path of the ACTIVE authority (the v3 ledger under `.state/`). */
26
25
  export function getCodexIngestionConsentPath(workspaceDir) {
27
26
  return getConversationIngestionConsentPath(workspaceDir);
28
27
  }
29
- /** Read the Codex slot of the v3 ledger (migrating a legacy v2 file when present). */
28
+ /** Read the Codex slot of the v3 ledger. */
30
29
  export function readCodexIngestionConsent(workspaceDir) {
31
30
  return readConversationIngestionConsent(workspaceDir, 'codex');
32
31
  }
@@ -3,6 +3,7 @@ import { computeBehaviorFacts, } from '@principles/core/runtime';
3
3
  import { extractFileHeaderPatchTargets } from '@principles/core/runtime/internalization/rule-host-input-builder';
4
4
  import { assembleBehaviorHistory, computeConservativeBehaviorFacts } from './behavior-history.js';
5
5
  import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
6
+ import { resolveWorkspaceSessionWriteTargets, unavailableSessionWriteTargets } from './session-write-targets.js';
6
7
  import { readLatestCodexDesignGateDeclaration, resolveCodexDesignGateFact } from './design-gate-facts.js';
7
8
  const HISTORY_LIMIT = 100;
8
9
  const MAX_REASON_LENGTH = 240;
@@ -30,17 +31,25 @@ function safeReadonlyCommand(params) {
30
31
  const command = typeof params.command === 'string' ? params.command : null;
31
32
  return command !== null && APPROVED_READONLY_COMMANDS.has(command.trim());
32
33
  }
33
- function unavailable(reason, designGate) {
34
+ function unavailable(reason, designGate, sessionWriteTargets) {
35
+ const normalizedReason = reason.replace(/\s+/g, ' ').slice(0, MAX_REASON_LENGTH);
34
36
  const history = {
35
37
  status: 'unavailable',
36
- unavailableReason: reason.replace(/\s+/g, ' ').slice(0, MAX_REASON_LENGTH),
38
+ unavailableReason: normalizedReason,
37
39
  truncated: false,
38
40
  calls: [],
39
41
  };
40
42
  return {
41
43
  version: 2,
42
44
  history,
43
- facts: { ...computeBehaviorFacts(history, null, null), ...(designGate !== undefined ? { designGate } : {}) },
45
+ facts: {
46
+ ...computeBehaviorFacts(history, null, null),
47
+ ...(designGate !== undefined ? { designGate } : {}),
48
+ // An early exit means session/project scope could not be located, so the
49
+ // session-wide bound is unavailable for the same structured reason. Only
50
+ // branches that DID locate scope pass a computed value.
51
+ sessionWriteTargets: sessionWriteTargets ?? unavailableSessionWriteTargets(normalizedReason),
52
+ },
44
53
  };
45
54
  }
46
55
  /**
@@ -106,6 +115,20 @@ export function createCodexRuleContextProvider(options) {
106
115
  const cutoff = options.cutoffAt;
107
116
  if (!(cutoff instanceof Date) || !Number.isFinite(cutoff.getTime()))
108
117
  return unavailable('history_cutoff_invalid', designGate);
118
+ // Session scope (session id, governance workspace, project cwd, cutoff, current
119
+ // tool_use_id) is proven by this point, so the session-wide lower bound is
120
+ // computed independently of the 100-row window: every later history verdict
121
+ // (scope incomplete, no prior history, failure) still carries it.
122
+ const sessionWriteTargets = resolveWorkspaceSessionWriteTargets({
123
+ workspaceDir,
124
+ projectDir,
125
+ hostKind: 'codex',
126
+ sessionId: request.sessionId,
127
+ cutoffAt: cutoff,
128
+ currentToolUseId: options.currentToolUseId,
129
+ request,
130
+ toolSemantics: options.toolSemantics,
131
+ });
109
132
  try {
110
133
  const historyRows = readWorkspaceRuleContextRowsBefore(workspaceDir, {
111
134
  sessionId: request.sessionId,
@@ -115,9 +138,9 @@ export function createCodexRuleContextProvider(options) {
115
138
  limit: HISTORY_LIMIT,
116
139
  });
117
140
  if (historyRows.unscopedPriorRows)
118
- return unavailable('trajectory_project_scope_incomplete', designGate);
141
+ return unavailable('trajectory_project_scope_incomplete', designGate, sessionWriteTargets);
119
142
  if (historyRows.rows.length === 0)
120
- return unavailable('no_prior_session_history', designGate);
143
+ return unavailable('no_prior_session_history', designGate, sessionWriteTargets);
121
144
  // Deliberately do not pass currentToolUseId here. Unlike WorkBuddy,
122
145
  // this reader does not yet prove strict same-host attribution for every
123
146
  // historical row, so Codex call identity conservatively remains
@@ -134,11 +157,11 @@ export function createCodexRuleContextProvider(options) {
134
157
  return {
135
158
  version: 2,
136
159
  history,
137
- facts: { ...facts, designGate },
160
+ facts: { ...facts, designGate, sessionWriteTargets },
138
161
  };
139
162
  }
140
163
  catch (error) {
141
- return unavailable(`trajectory_history_unavailable:${error instanceof Error ? error.message : String(error)}`, designGate);
164
+ return unavailable(`trajectory_history_unavailable:${error instanceof Error ? error.message : String(error)}`, designGate, sessionWriteTargets);
142
165
  }
143
166
  };
144
167
  }
@@ -1,24 +1,15 @@
1
1
  /**
2
2
  * Conversation-ingestion consent ledger v3 (PRI-1171; SPEC v0.2 §8.1).
3
3
  *
4
- * Host-neutral successor of the Codex-only consent store: ONE file per
5
- * workspace, keyed by host kind, at
4
+ * Host-neutral consent store: ONE file per workspace, keyed by host kind, at
6
5
  * `<workspace>/.state/conversation-ingestion-consent.json`.
7
6
  *
8
- * Authority model (P4, unchanged from v2): the FEATURE FLAGS stay the runtime
9
- * authority for whether ingestion runs; this ledger is the GOVERNANCE RECORD
10
- * that the conversation-ingestion flags may only be enabled THROUGH the
11
- * disclosed consent flow (or an explicit Owner directive). The unified
12
- * ingestion pipeline additionally consults the recorded decision as its
13
- * consent gate (SPEC §8.2: host AND ingestion-flag AND consent=granted).
14
- *
15
- * v2 → v3 migration (one-way, audit-preserving): when no v3 file exists but a
16
- * legacy `<workspace>/.pd/codex-ingestion-consent.json` (schema v2) does, the
17
- * first read migrates it — the v3 file is written FIRST (atomic), then the
18
- * legacy file is RENAMED with a `.superseded` suffix (never deleted). A crash
19
- * between the two steps is safe: v3 existing means the legacy file is ignored;
20
- * no v3 means the migration simply retries. Health and the pipeline read ONLY
21
- * v3 (single authority — no dual-file ambiguity).
7
+ * Authority model (P4): the FEATURE FLAGS stay the runtime authority for
8
+ * whether ingestion runs; this ledger is the GOVERNANCE RECORD that the
9
+ * conversation-ingestion flags may only be enabled THROUGH the disclosed
10
+ * consent flow (or an explicit Owner directive). The unified ingestion
11
+ * pipeline additionally consults the recorded decision as its consent gate
12
+ * (SPEC §8.2: host AND ingestion-flag AND consent=granted).
22
13
  *
23
14
  * Records carry `disclosureVersion`: consent binds to the disclosure text it
24
15
  * was granted against. The full-text tier additionally requires the record's
@@ -30,20 +21,15 @@
30
21
  * setup flows (e.g. SPEC approval), with `evidenceRef` pointing at the
31
22
  * decision record.
32
23
  *
33
- * Patterns mirror the v2 store: missing file is the normal never-asked case;
34
- * malformed files fail loud (rc-3/rc-9) because silently treating them as
35
- * "never asked" could re-enable against a recorded Owner decision; writes are
36
- * atomic (temp + rename); unknown/malformed fields are rejected via guards,
37
- * never `as` (rc-1/rc-2/rc-5). This file is consent control state — it never
38
- * contains captured conversation text.
24
+ * Missing file is the normal never-asked case; malformed files fail loud
25
+ * (rc-3/rc-9) because silently treating them as "never asked" could
26
+ * re-enable against a recorded Owner decision; writes are atomic (temp +
27
+ * rename); unknown/malformed fields are rejected via guards, never `as`
28
+ * (rc-1/rc-2/rc-5). This file is consent control state — it never contains
29
+ * captured conversation text.
39
30
  */
40
31
  export declare const CONVERSATION_INGESTION_CONSENT_FILENAME = "conversation-ingestion-consent.json";
41
32
  export declare const CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION = "3";
42
- /** Suffix applied to the superseded v2 file (kept on disk for audit; never read again). */
43
- export declare const CONVERSATION_INGESTION_CONSENT_SUPERSEDED_SUFFIX = ".superseded";
44
- /** Legacy v2 authority location (Codex-only era); migrated on first read. */
45
- export declare const LEGACY_CODEX_CONSENT_FILENAME = "codex-ingestion-consent.json";
46
- export declare const LEGACY_CODEX_CONSENT_SCHEMA_VERSION = "2";
47
33
  export type ConversationConsentHostKind = 'codex' | 'workbuddy' | 'openclaw';
48
34
  /**
49
35
  * Consent transition states (unchanged semantics from the v2 store):
@@ -76,8 +62,6 @@ export type ConversationIngestionConsentRead = {
76
62
  ok: true;
77
63
  existed: boolean;
78
64
  record: ConversationIngestionConsentRecord | null;
79
- migratedFromLegacy?: boolean;
80
- warnings?: readonly string[];
81
65
  } | {
82
66
  ok: false;
83
67
  reason: string;
@@ -106,8 +90,7 @@ export type ConversationIngestionConsentState = 'granted' | 'revoked' | 'pending
106
90
  export declare function getConversationIngestionConsentPath(workspaceDir: string): string;
107
91
  /**
108
92
  * Read one host's consent record from the v3 ledger (the ONLY authority).
109
- * A missing v3 file with an existing legacy v2 Codex file triggers the one-way
110
- * migration. ENOENT on both is the normal never-asked case.
93
+ * ENOENT is the normal never-asked case.
111
94
  */
112
95
  export declare function readConversationIngestionConsent(workspaceDir: string, hostKind: ConversationConsentHostKind): ConversationIngestionConsentRead;
113
96
  export declare function recordConversationIngestionConsent(workspaceDir: string, hostKind: ConversationConsentHostKind, input: {