@principles/host-runtime 2.2.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/active-principle-prompt.d.ts +88 -3
  2. package/dist/active-principle-prompt.js +132 -41
  3. package/dist/adaptive-journal-reconciliation.js +1 -1
  4. package/dist/adaptive-principle-revalidation.d.ts +1 -1
  5. package/dist/adaptive-principle-revalidation.js +1 -1
  6. package/dist/behavior-example-pack-assembler.d.ts +2 -2
  7. package/dist/behavior-example-pack-assembler.js +6 -6
  8. package/dist/behavior-history.d.ts +1 -1
  9. package/dist/behavior-history.js +1 -1
  10. package/dist/cli-recovery-probe.d.ts +1 -1
  11. package/dist/codex-artificer-trusted-facts.d.ts +1 -1
  12. package/dist/codex-rule-context-provider.d.ts +1 -1
  13. package/dist/codex-rule-context-provider.js +1 -1
  14. package/dist/codex-worker-status.js +1 -1
  15. package/dist/design-gate-facts.d.ts +1 -1
  16. package/dist/design-gate-facts.js +1 -1
  17. package/dist/evaluator-runtime-context.d.ts +1 -1
  18. package/dist/evaluator-runtime-context.js +1 -1
  19. package/dist/governance-observation-store.js +1 -1
  20. package/dist/governance-signal-admission.d.ts +2 -2
  21. package/dist/governance-signal-admission.js +3 -3
  22. package/dist/host-liveness-contract.d.ts +1 -1
  23. package/dist/host-tool-declaration.d.ts +1 -1
  24. package/dist/host-tool-declaration.js +1 -1
  25. package/dist/host-tool-semantic-resolver.d.ts +1 -1
  26. package/dist/host-tool-semantic-resolver.js +1 -1
  27. package/dist/index.d.ts +11 -1
  28. package/dist/index.js +33 -15
  29. package/dist/internalization-consumer-cycle.d.ts +2 -2
  30. package/dist/internalization-consumer-cycle.js +2 -2
  31. package/dist/internalization-consumer-governance.d.ts +1 -1
  32. package/dist/internalization-consumer-governance.js +1 -1
  33. package/dist/intervention-evidence-ingress.d.ts +1 -1
  34. package/dist/intervention-evidence-ingress.js +1 -1
  35. package/dist/pd-config.d.ts +1 -1
  36. package/dist/pd-config.js +1 -1
  37. package/dist/product-telemetry/consent-store.js +1 -1
  38. package/dist/product-telemetry/exporter.d.ts +1 -1
  39. package/dist/product-telemetry/milestone-readers.d.ts +1 -1
  40. package/dist/product-telemetry/service.d.ts +1 -1
  41. package/dist/product-telemetry/service.js +1 -1
  42. package/dist/product-telemetry/workspace-scope.js +1 -1
  43. package/dist/production-pain-evidence.d.ts +1 -1
  44. package/dist/production-pain-evidence.js +3 -3
  45. package/dist/production-rulehost-gate.d.ts +1 -1
  46. package/dist/production-rulehost-gate.js +3 -3
  47. package/dist/prompt-activation-authority.d.ts +1 -1
  48. package/dist/prompt-activation-deliverability.d.ts +26 -16
  49. package/dist/prompt-activation-deliverability.js +60 -30
  50. package/dist/prompt-injection-budget-observation.d.ts +16 -5
  51. package/dist/prompt-injection-budget-observation.js +23 -9
  52. package/dist/prompt-injection-projection.d.ts +106 -49
  53. package/dist/prompt-injection-projection.js +190 -212
  54. package/dist/prompt-injection-status.d.ts +1 -1
  55. package/dist/prompt-injection-status.js +17 -8
  56. package/dist/signal-classifier.d.ts +2 -2
  57. package/dist/signal-classifier.js +3 -3
  58. package/dist/workbuddy-rule-context-provider.d.ts +1 -1
  59. package/dist/workbuddy-rule-context-provider.js +1 -1
  60. package/dist/workbuddy-worker-status.js +1 -1
  61. package/dist/workspace-behavior-evidence.d.ts +1 -1
  62. package/dist/workspace-behavior-evidence.js +2 -2
  63. package/dist/workspace-telemetry-emitter.d.ts +1 -1
  64. package/dist/workspace-telemetry-emitter.js +1 -1
  65. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { type ActivatedPrinciple, type PromptBudgetResolution, type PromptSelectionPolicy } from '@principles/core/runtime-v2';
1
+ import { type ActivatedPrinciple, type PromptBudgetResolution, type PromptSelectionPolicy } from '@principles/core/runtime';
2
2
  /** PRI-904 SPEC §10: bounded diagnostic id lists (mirrors the core selector's cap of 16). */
3
3
  export declare const MAX_SHARED_DIAGNOSTIC_IDS = 16;
4
4
  export interface ActivePrinciplePromptResult {
@@ -15,6 +15,13 @@ export interface ActivePrinciplePromptResult {
15
15
  eligibleCount?: number;
16
16
  /** PRI-904: circular scan start; present only under fair_rotation_v1. */
17
17
  rotationStartIndex?: number;
18
+ /**
19
+ * PRI-1137: the trusted round key this fair rotation actually advanced on.
20
+ * Present only under fair_rotation_v1 — the injection event mirrors it as
21
+ * `selectionRoundOrdinal`, so the recorded round can never disagree with
22
+ * the selection that produced the payload.
23
+ */
24
+ selectionRoundOrdinal?: number;
18
25
  /** PRI-904 (bounded, max 16): activation ids dropped for insufficient remaining budget. */
19
26
  droppedActivationIds?: string[];
20
27
  /** PRI-904 (bounded, max 16): activation ids that cannot fit even in an empty payload. */
@@ -55,7 +62,6 @@ export interface PromptActivationCandidates {
55
62
  /** true = prompt flag off or state.db missing — candidates are necessarily empty */
56
63
  aborted: boolean;
57
64
  selfReportEnabled: boolean;
58
- abstractionLayerEnabled: boolean;
59
65
  }
60
66
  /**
61
67
  * PR #1844 follow-up: the activation READ half of buildActivePrinciplePromptContext,
@@ -64,9 +70,88 @@ export interface PromptActivationCandidates {
64
70
  */
65
71
  export declare function readPromptActivationCandidates(input: {
66
72
  workspaceDir: string;
67
- /** Opt in for revalidation; default route keeps its historical prompt bytes. */
73
+ /**
74
+ * PRI-1137: annotate each candidate with its authority. The shared runtime is
75
+ * now the ONLY prompt route, so this must stay on for the production read —
76
+ * the retired OpenClaw list route rendered `authority="owner"`/`"system_policy"`
77
+ * per directive, and dropping it would silently weaken the P0-G INV-05
78
+ * guarantee that a low-risk auto-activation is never represented as Owner-approved.
79
+ */
68
80
  includeAuthority?: boolean;
81
+ /**
82
+ * Additional adaptive reads must not hold the host behind SQLite's synchronous
83
+ * busy wait. Only the adaptive revalidation read opts in.
84
+ */
85
+ noBusyWait?: boolean;
69
86
  }): Promise<PromptActivationCandidates>;
87
+ export interface SharedDirectivePacking {
88
+ included: ActivatedPrinciple[];
89
+ additionalContext: string;
90
+ truncated: boolean;
91
+ dropped: string[];
92
+ oversized: string[];
93
+ }
94
+ /**
95
+ * PRI-1137 final review P1-5: did the AUTHORIZATION FACTS of the adaptive
96
+ * priority target change between the native snapshot (first read) and the
97
+ * authorized snapshot (second read)? The packed directive is annotated from
98
+ * the facts as of packing time, so a drift in `authority` (e.g. owner →
99
+ * system_policy after an approval-state change) or `approvedBy` means the
100
+ * first snapshot's annotation would be a stale authorization claim — the
101
+ * caller must exclude the target rather than inject it. Content drift
102
+ * (text/sha) is checked separately (`target_changed`).
103
+ */
104
+ export declare function adaptiveTargetAuthorizationChanged(native: {
105
+ authority?: 'owner' | 'system_policy';
106
+ approvedBy?: string;
107
+ }, authorized: {
108
+ authority?: 'owner' | 'system_policy';
109
+ approvedBy?: string;
110
+ }): boolean;
111
+ /**
112
+ * PRI-1137 final review P1-2: the packing DECISION without the final render —
113
+ * the rotation reachability replay runs this once per round key over the SAME
114
+ * precomputed block costs (via `blockCharsByActivationId`), so N rounds cost
115
+ * O(N²) integer adds instead of O(N³) string work. The decision mirrors the
116
+ * render exactly because both derive from the same additive measurement
117
+ * (`baseChars + Σ blockChars === render(set).length` for any non-empty set).
118
+ * Declared before `packSharedDirectives` (no-use-before-define).
119
+ */
120
+ export declare function planSharedDirectivePacking(input: {
121
+ scanOrder: ActivatedPrinciple[];
122
+ budgetChars: number;
123
+ selfReportEnabled: boolean;
124
+ continueOnNonFit: boolean;
125
+ /**
126
+ * Precomputed exact marginal chars per activationId (P1-2 fast path). When
127
+ * absent each candidate is measured once here — still one render per
128
+ * PRINCIPLE, never per prefix.
129
+ */
130
+ blockCharsByActivationId?: ReadonlyMap<string, number>;
131
+ }): Omit<SharedDirectivePacking, 'additionalContext'>;
132
+ /**
133
+ * PRI-1137: THE shared directive packer. `buildActivePrinciplePromptContext`
134
+ * selects through it, and the console projection reuses it to answer "which
135
+ * activations this route reaches across rounds". One policy implementation —
136
+ * the retired list-route `trimToBudget` arithmetic must not survive as a
137
+ * second forecast authority.
138
+ *
139
+ * PRI-1137 final review P1-2 (CodeRabbit Major): the previous loop re-rendered
140
+ * the ENTIRE growing prefix per candidate — O(N²) render work per pack, and
141
+ * the rotation reachability replay called it once per round key. The render is
142
+ * strictly additive over per-principle directive blocks (see
143
+ * `measureSharedDirectiveBlockChars`), so inclusion is decided by integer
144
+ * arithmetic over per-block costs measured ONCE, and the string is rendered a
145
+ * single time at the end. Output is byte-identical to the retired loop
146
+ * (locked by characterization tests); only the work profile changed.
147
+ */
148
+ export declare function packSharedDirectives(input: {
149
+ scanOrder: ActivatedPrinciple[];
150
+ budgetChars: number;
151
+ selfReportEnabled: boolean;
152
+ /** Fair rotation continues past a non-fit; legacy FIFO stops at the first one. */
153
+ continueOnNonFit: boolean;
154
+ }): SharedDirectivePacking;
70
155
  export declare function buildActivePrinciplePromptContext(input: {
71
156
  workspaceDir: string;
72
157
  /**
@@ -1,4 +1,7 @@
1
- import { SqliteActivationStateStore, SqliteConnection, SqlitePIArtifactStore, computeFeatureFlagsFromConfig, filterPromptActivations, renderPrinciplesToDirectives, resolvePrincipleFromArtifact, resolvePromptBudget, } from '@principles/core/runtime-v2';
1
+ import { SqliteActivationStateStore, SqliteConnection, SqlitePIArtifactStore, computeFeatureFlagsFromConfig, filterPromptActivations, renderPrinciplesToDirectives,
2
+ // PRI-1137 final review P1-2: exact additive measurement of the shared
3
+ // directive render — the packer decides by arithmetic, renders once.
4
+ measureSharedDirectiveBlockChars, sharedDirectiveBaseChars, resolvePrincipleFromArtifact, resolvePromptBudget, } from '@principles/core/runtime';
2
5
  import fs from 'node:fs';
3
6
  import path from 'node:path';
4
7
  import { escapeXml } from '@principles/core/prompt-builder';
@@ -21,10 +24,9 @@ export async function readPromptActivationCandidates(input) {
21
24
  }
22
25
  const { flags } = computeFeatureFlagsFromConfig(config.effective);
23
26
  const { prompt: promptFlag } = flags;
24
- const abstractionLayerEnabled = flags.abstraction_layer_v1?.enabled === true;
25
27
  if (!promptFlag?.enabled) {
26
28
  warnings.push('prompt_feature_disabled; nextAction=set features.prompt.enabled=true in .pd/config.yaml');
27
- return { principles, warnings, aborted: true, selfReportEnabled: false, abstractionLayerEnabled };
29
+ return { principles, warnings, aborted: true, selfReportEnabled: false };
28
30
  }
29
31
  // PRI-532: agent self-report instruction rides the directive template when
30
32
  // the flag is on (flag-off keeps the template byte-identical).
@@ -33,12 +35,12 @@ export async function readPromptActivationCandidates(input) {
33
35
  const stateDbPath = path.join(input.workspaceDir, '.pd', 'state.db');
34
36
  if (!fs.existsSync(stateDbPath)) {
35
37
  warnings.push('activation_db_not_found; nextAction=initialize_workspace_runtime_state');
36
- return { principles, warnings, aborted: true, selfReportEnabled, abstractionLayerEnabled };
38
+ return { principles, warnings, aborted: true, selfReportEnabled };
37
39
  }
38
40
  try {
39
41
  connection = new SqliteConnection({ workspaceDir: input.workspaceDir, readonly: true, bootstrapIfMissing: false,
40
42
  // Additional adaptive reads must not hold the host behind SQLite's synchronous busy wait.
41
- ...(input.includeAuthority === true ? { busyTimeoutMs: 0 } : {}),
43
+ ...(input.noBusyWait === true ? { busyTimeoutMs: 0 } : {}),
42
44
  });
43
45
  const activations = filterPromptActivations(await new SqliteActivationStateStore(connection).listPromptActivations());
44
46
  const artifactStore = new SqlitePIArtifactStore(connection);
@@ -89,14 +91,111 @@ export async function readPromptActivationCandidates(input) {
89
91
  finally {
90
92
  connection?.close();
91
93
  }
92
- return { principles, warnings, aborted: false, selfReportEnabled, abstractionLayerEnabled };
94
+ return { principles, warnings, aborted: false, selfReportEnabled };
95
+ }
96
+ /**
97
+ * PRI-1137 final review P1-5: did the AUTHORIZATION FACTS of the adaptive
98
+ * priority target change between the native snapshot (first read) and the
99
+ * authorized snapshot (second read)? The packed directive is annotated from
100
+ * the facts as of packing time, so a drift in `authority` (e.g. owner →
101
+ * system_policy after an approval-state change) or `approvedBy` means the
102
+ * first snapshot's annotation would be a stale authorization claim — the
103
+ * caller must exclude the target rather than inject it. Content drift
104
+ * (text/sha) is checked separately (`target_changed`).
105
+ */
106
+ export function adaptiveTargetAuthorizationChanged(native, authorized) {
107
+ return native.authority !== authorized.authority || native.approvedBy !== authorized.approvedBy;
108
+ }
109
+ /**
110
+ * PRI-1137 final review P1-2: the packing DECISION without the final render —
111
+ * the rotation reachability replay runs this once per round key over the SAME
112
+ * precomputed block costs (via `blockCharsByActivationId`), so N rounds cost
113
+ * O(N²) integer adds instead of O(N³) string work. The decision mirrors the
114
+ * render exactly because both derive from the same additive measurement
115
+ * (`baseChars + Σ blockChars === render(set).length` for any non-empty set).
116
+ * Declared before `packSharedDirectives` (no-use-before-define).
117
+ */
118
+ export function planSharedDirectivePacking(input) {
119
+ const { scanOrder, budgetChars, selfReportEnabled, continueOnNonFit } = input;
120
+ const blockChars = input.blockCharsByActivationId
121
+ ?? new Map(scanOrder.map((principle) => [
122
+ principle.activationId,
123
+ measureSharedDirectiveBlockChars(principle, { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled }),
124
+ ]));
125
+ // Chars any non-empty render carries (header + footer + note). An empty
126
+ // included set renders '' (the renderer's own empty contract).
127
+ const baseChars = sharedDirectiveBaseChars({ escapeFn: escapeXml, selfReportInstruction: selfReportEnabled });
128
+ const included = [];
129
+ let runningChars = baseChars;
130
+ let truncated = false;
131
+ const dropped = [];
132
+ const oversized = [];
133
+ for (const principle of scanOrder) {
134
+ const marginal = blockChars.get(principle.activationId);
135
+ if (marginal === undefined) {
136
+ // Unknown cost must never silently pass as zero (rc-3): treat as
137
+ // oversized-for-planning and record it.
138
+ if (oversized.length < MAX_SHARED_DIAGNOSTIC_IDS)
139
+ oversized.push(principle.activationId);
140
+ if (!continueOnNonFit)
141
+ break;
142
+ continue;
143
+ }
144
+ if (runningChars + marginal > budgetChars) {
145
+ // Standalone fit = base + own block within budget — the same fact the
146
+ // single-principle render expresses, derived additively.
147
+ if (baseChars + marginal <= budgetChars) {
148
+ truncated = true;
149
+ if (dropped.length < MAX_SHARED_DIAGNOSTIC_IDS)
150
+ dropped.push(principle.activationId);
151
+ }
152
+ else if (oversized.length < MAX_SHARED_DIAGNOSTIC_IDS) {
153
+ oversized.push(principle.activationId);
154
+ }
155
+ if (!continueOnNonFit)
156
+ break;
157
+ continue;
158
+ }
159
+ included.push(principle);
160
+ runningChars += marginal;
161
+ }
162
+ return { included, truncated, dropped, oversized };
163
+ }
164
+ /**
165
+ * PRI-1137: THE shared directive packer. `buildActivePrinciplePromptContext`
166
+ * selects through it, and the console projection reuses it to answer "which
167
+ * activations this route reaches across rounds". One policy implementation —
168
+ * the retired list-route `trimToBudget` arithmetic must not survive as a
169
+ * second forecast authority.
170
+ *
171
+ * PRI-1137 final review P1-2 (CodeRabbit Major): the previous loop re-rendered
172
+ * the ENTIRE growing prefix per candidate — O(N²) render work per pack, and
173
+ * the rotation reachability replay called it once per round key. The render is
174
+ * strictly additive over per-principle directive blocks (see
175
+ * `measureSharedDirectiveBlockChars`), so inclusion is decided by integer
176
+ * arithmetic over per-block costs measured ONCE, and the string is rendered a
177
+ * single time at the end. Output is byte-identical to the retired loop
178
+ * (locked by characterization tests); only the work profile changed.
179
+ */
180
+ export function packSharedDirectives(input) {
181
+ const plan = planSharedDirectivePacking(input);
182
+ const additionalContext = renderPrinciplesToDirectives(plan.included, new Set(plan.included.map((entry) => entry.principleId)), { escapeFn: escapeXml, selfReportInstruction: input.selfReportEnabled });
183
+ return { ...plan, additionalContext };
93
184
  }
94
185
  export async function buildActivePrinciplePromptContext(input) {
95
186
  // One resolution per request (SPEC §6.1): the caller's pre-resolved budget
96
187
  // or the fixed-fallback default — never a per-line constant read.
97
188
  const promptBudget = input.promptBudget ?? resolvePromptBudget();
98
189
  const { budgetChars } = promptBudget;
99
- const { principles, warnings, aborted, selfReportEnabled } = await readPromptActivationCandidates(input);
190
+ // PRI-1137 final review P2 (deliberate): this FIRST read keeps the default
191
+ // busy_timeout (≈5s) instead of noBusyWait. It is the source of the WHOLE
192
+ // injection — failing it on a transient SQLite lock would abort every
193
+ // principle (aborted ⇒ empty context), which is a far worse degradation
194
+ // than the bounded wait. Only the adaptive REVALIDATION read opts into
195
+ // noBusyWait (line ~459): that one is an optional enhancement whose
196
+ // fast-fail falls back to the native baseline, so waiting there would risk
197
+ // the hook timeout for no injection benefit.
198
+ const { principles, warnings, aborted, selfReportEnabled } = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
100
199
  if (aborted) {
101
200
  return {
102
201
  additionalContext: '', principleIds: [], activationIds: [], artifactIds: [], warnings,
@@ -131,52 +230,36 @@ export async function buildActivePrinciplePromptContext(input) {
131
230
  const nativeScanOrder = rotationStartIndex === undefined
132
231
  ? principles
133
232
  : principles.slice(rotationStartIndex).concat(principles.slice(0, rotationStartIndex));
134
- const pack = (scanOrder) => {
135
- const included = [];
136
- let additionalContext = '';
137
- let truncated = false;
138
- const dropped = [];
139
- const oversized = [];
140
- const standaloneFits = (principle) => renderPrinciplesToDirectives([principle], new Set([principle.principleId]), { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled }).length
141
- <= budgetChars;
142
- for (const principle of scanOrder) {
143
- const candidate = [...included, principle];
144
- const candidateContext = renderPrinciplesToDirectives(candidate, new Set(candidate.map((entry) => entry.principleId)), { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled });
145
- if (candidateContext.length > budgetChars) {
146
- if (standaloneFits(principle)) {
147
- truncated = true;
148
- if (dropped.length < MAX_SHARED_DIAGNOSTIC_IDS)
149
- dropped.push(principle.activationId);
150
- }
151
- else if (oversized.length < MAX_SHARED_DIAGNOSTIC_IDS) {
152
- oversized.push(principle.activationId);
153
- }
154
- if (selectionPolicy === 'legacy_fifo_prefix_v1')
155
- break;
156
- continue;
157
- }
158
- included.push(principle);
159
- additionalContext = candidateContext;
160
- }
161
- return { included, additionalContext, truncated, dropped, oversized };
162
- };
233
+ const pack = (scanOrder) => packSharedDirectives({ scanOrder, budgetChars, selfReportEnabled, continueOnNonFit: selectionPolicy === 'fair_rotation_v1' });
163
234
  const makeResult = (packing, eligiblePrinciples, adaptivePacking) => {
164
235
  const resultWarnings = [...warnings];
165
236
  if (packing.truncated) {
166
237
  resultWarnings.push('prompt_context_truncated: production_prompt_cap; nextAction=reduce_active_prompt_principles');
167
238
  }
168
- const injectedIds = new Set(packing.included.map((principle) => principle.principleId));
239
+ // Evidence arrays are positional tuples (principle, activation, artifact).
240
+ // A principle can have multiple activated artifacts, so deduplicate the
241
+ // candidate objects once and derive every identity array from that same
242
+ // first-selected entry; independently deduplicating only principleIds
243
+ // would shift later activation/artifact associations.
244
+ const seenPrincipleIds = new Set();
245
+ const injectedPrinciples = packing.included.filter((principle) => {
246
+ if (seenPrincipleIds.has(principle.principleId))
247
+ return false;
248
+ seenPrincipleIds.add(principle.principleId);
249
+ return true;
250
+ });
169
251
  return {
170
252
  additionalContext: packing.additionalContext,
171
- principleIds: [...injectedIds],
172
- activationIds: packing.included.map((principle) => principle.activationId),
173
- artifactIds: packing.included.map((principle) => principle.artifactId),
253
+ principleIds: injectedPrinciples.map((principle) => principle.principleId),
254
+ activationIds: injectedPrinciples.map((principle) => principle.activationId),
255
+ artifactIds: injectedPrinciples.map((principle) => principle.artifactId),
174
256
  warnings: resultWarnings,
175
257
  budget: budgetChars,
176
258
  truncated: packing.truncated,
177
259
  selectionPolicy,
178
260
  eligibleCount: eligiblePrinciples.length,
179
261
  ...(rotationStartIndex !== undefined ? { rotationStartIndex } : {}),
262
+ ...(selectionPolicy === 'fair_rotation_v1' && roundKey !== undefined ? { selectionRoundOrdinal: roundKey } : {}),
180
263
  ...(packing.dropped.length > 0 ? { droppedActivationIds: packing.dropped } : {}),
181
264
  ...(packing.oversized.length > 0 ? { oversizedActivationIds: packing.oversized } : {}),
182
265
  budgetCapacitySource: promptBudget.capacitySource,
@@ -226,13 +309,21 @@ export async function buildActivePrinciplePromptContext(input) {
226
309
  if (principles.filter((principle) => principle.principleId === nativeTarget.principleId).length !== 1) {
227
310
  return { ...nativeResult, adaptivePacking: report('unavailable', 'target_ambiguous') };
228
311
  }
229
- const authorityRead = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
312
+ const authorityRead = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true, noBusyWait: true });
230
313
  const authorizedMatches = authorityRead.principles.filter((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
231
314
  const [authorizedTarget] = authorizedMatches;
232
315
  if (authorityRead.aborted || authorityRead.warnings.length > 0 || authorizedMatches.length !== 1 || !authorizedTarget
233
316
  || authorityRead.principles.filter((principle) => principle.principleId === authorizedTarget.principleId).length !== 1) {
234
317
  return withoutTarget('authority_unavailable');
235
318
  }
319
+ // PRI-1137 final review P1-5: the second read must prove the AUTHORIZATION
320
+ // FACTS unchanged, not merely present. The packed directive carries the
321
+ // first snapshot's authority annotation, so an approval-state change
322
+ // between the two reads (owner → system_policy, or a different approver)
323
+ // must exclude the priority target instead of injecting stale authorization.
324
+ if (adaptiveTargetAuthorizationChanged(nativeTarget, authorizedTarget)) {
325
+ return withoutTarget('target_authority_changed');
326
+ }
236
327
  if (!authorizedTarget.authority
237
328
  || authorizedTarget.principleId !== nativeTarget.principleId
238
329
  || authorizedTarget.text !== nativeTarget.text
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
- import { INTERVENTION_SHORT_SOURCE_RETENTION_DAYS, canonicalStringify, validateAdaptiveDeliveryRecord, } from '@principles/core/runtime-v2';
3
+ import { INTERVENTION_SHORT_SOURCE_RETENTION_DAYS, canonicalStringify, validateAdaptiveDeliveryRecord, } from '@principles/core/runtime';
4
4
  /**
5
5
  * PRI-1109 — conservative, read-only reconciliation of adaptive-delivery journal
6
6
  * records (approved design: docs/specs/PD-AA-PRI-1109-JOURNAL-RECONCILE-DESIGN-v0.2.md).
@@ -1,5 +1,5 @@
1
1
  import { type PromptActivationCandidates } from './active-principle-prompt.js';
2
- import type { ActivatedPrinciple } from '@principles/core/runtime-v2';
2
+ import type { ActivatedPrinciple } from '@principles/core/runtime';
3
3
  export type AdaptivePrincipleReader = (input: {
4
4
  workspaceDir: string;
5
5
  }) => Promise<PromptActivationCandidates>;
@@ -47,6 +47,6 @@ export function createAdaptivePrincipleRevalidator(reader) {
47
47
  return (workspaceDir, expected, signal) => revalidateWithReader({ workspaceDir, expected, signal }, reader);
48
48
  }
49
49
  export function revalidateAdaptivePrinciple(workspaceDir, expected, signal) {
50
- const readWithAuthority = ({ workspaceDir: currentWorkspaceDir }) => readPromptActivationCandidates({ workspaceDir: currentWorkspaceDir, includeAuthority: true });
50
+ const readWithAuthority = ({ workspaceDir: currentWorkspaceDir }) => readPromptActivationCandidates({ workspaceDir: currentWorkspaceDir, includeAuthority: true, noBusyWait: true });
51
51
  return revalidateWithReader({ workspaceDir, expected, signal }, readWithAuthority);
52
52
  }
@@ -1,6 +1,6 @@
1
- import type { BehaviorExamplePack } from '@principles/core/runtime-v2';
1
+ import type { BehaviorExamplePack } from '@principles/core/runtime';
2
2
  import type { RuleHostEvidenceRow, RuleHostContextRow } from '@principles/core/trajectory-types';
3
- import type { ToolSemanticRegistry } from '@principles/core/runtime-v2';
3
+ import type { ToolSemanticRegistry } from '@principles/core/runtime';
4
4
  export interface BehaviorExampleDataSource {
5
5
  getPainEventByCanonicalId(id: string): {
6
6
  id: number;
@@ -20,17 +20,17 @@
20
20
  * Spec: docs/superpowers/specs/2026-06-27-rulecode-context-vision-design.md §7.2
21
21
  *
22
22
  * Boundary: this module is I/O. Pure logic (type + validator) lives in
23
- * `@principles/core/runtime-v2` → `behavior-example-pack.ts`.
23
+ * `@principles/core/runtime` → `behavior-example-pack.ts`.
24
24
  */
25
- import { buildRuleHostAction } from '@principles/core/runtime-v2/internalization/rule-host-input-builder';
26
- import { computeBehaviorFacts } from '@principles/core/runtime-v2/internalization/rule-context-v2';
27
- import { validateBehaviorExamplePack } from '@principles/core/runtime-v2/internalization/behavior-example-pack';
25
+ import { buildRuleHostAction } from '@principles/core/runtime/internalization/rule-host-input-builder';
26
+ import { computeBehaviorFacts } from '@principles/core/runtime/internalization/rule-context-v2';
27
+ import { validateBehaviorExamplePack } from '@principles/core/runtime/internalization/behavior-example-pack';
28
28
  // Factory lives in evidence-readiness.ts (the classification authority); it is
29
29
  // consumed through its registered LEAF subpath. A VALUE import of the
30
- // runtime-v2 barrel on this satellite path re-pulls the whole LLM graph and
30
+ // runtime barrel on this satellite path re-pulls the whole LLM graph and
31
31
  // fails the satellite-purity guard (OPT-002, scripts/build/check-satellite-purity.mjs) —
32
32
  // the leaf is on core's exports allowlist for exactly this consumer.
33
- import { createOwnerEvidenceScopeError } from '@principles/core/runtime-v2/internalization/evidence-readiness';
33
+ import { createOwnerEvidenceScopeError } from '@principles/core/runtime/internalization/evidence-readiness';
34
34
  import { assembleBehaviorHistory } from './behavior-history.js';
35
35
  // ── internal constants ─────────────────────────────────────────────────────
36
36
  const MAX_POSITIVES = 3;
@@ -1,4 +1,4 @@
1
- import type { RuleHistoryWindow, ToolSemanticRegistry } from '@principles/core/runtime-v2';
1
+ import type { RuleHistoryWindow, ToolSemanticRegistry } from '@principles/core/runtime';
2
2
  import type { RuleHostContextRow } from '@principles/core/trajectory-types';
3
3
  export declare function assembleBehaviorHistory(rows: readonly RuleHostContextRow[], truncated: boolean, options: {
4
4
  projectDir: string;
@@ -1,5 +1,5 @@
1
1
  /** Shared validated history assembly; host vocabulary is supplied by its owner. */
2
- import { buildRuleHostAction } from '@principles/core/runtime-v2/internalization/rule-host-input-builder';
2
+ import { buildRuleHostAction } from '@principles/core/runtime/internalization/rule-host-input-builder';
3
3
  const VALID_OUTCOMES = new Set(['success', 'failure', 'blocked']);
4
4
  function isPlainObject(value) {
5
5
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -1,4 +1,4 @@
1
- import type { RecoveryCapabilityEvidence } from '@principles/core/runtime-v2';
1
+ import type { RecoveryCapabilityEvidence } from '@principles/core/runtime';
2
2
  export declare const DEACTIVATE_DRY_RUN_PROBE_ACTIVATION_ID = "recovery-probe-nonexistent";
3
3
  /**
4
4
  * Resolve the built pd CLI entry for the CURRENT environment. Both layouts
@@ -1,4 +1,4 @@
1
- import type { ArtificerTrustedFactsPort } from '@principles/core/runtime-v2';
1
+ import type { ArtificerTrustedFactsPort } from '@principles/core/runtime';
2
2
  /**
3
3
  * Codex generation can author rules against the same DesignGateFact schema
4
4
  * that the native PreToolUse provider supplies. This declares capability only;
@@ -1,4 +1,4 @@
1
- import { type ToolSemanticRegistry } from '@principles/core/runtime-v2';
1
+ import { type ToolSemanticRegistry } from '@principles/core/runtime';
2
2
  import type { RuleContextProvider } from './production-rulehost-gate.js';
3
3
  export interface CodexRuleContextProviderOptions {
4
4
  /** The resolved PD workspace whose trajectory database is authoritative. */
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { computeBehaviorFacts, } from '@principles/core/runtime-v2';
2
+ import { computeBehaviorFacts, } from '@principles/core/runtime';
3
3
  import { assembleBehaviorHistory } from './behavior-history.js';
4
4
  import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
5
5
  import { readLatestCodexDesignGateDeclaration, resolveCodexDesignGateFact } from './design-gate-facts.js';
@@ -15,7 +15,7 @@
15
15
  import * as fs from 'node:fs';
16
16
  import * as path from 'node:path';
17
17
  import { loadPdConfigForPlugin } from './pd-config.js';
18
- import { computeFeatureFlagsFromConfig } from '@principles/core/runtime-v2';
18
+ import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
19
19
  function directoryExists(dir) {
20
20
  try {
21
21
  return fs.statSync(dir).isDirectory();
@@ -1,4 +1,4 @@
1
- import { type DesignGateFact } from '@principles/core/runtime-v2';
1
+ import { type DesignGateFact } from '@principles/core/runtime';
2
2
  export declare const DESIGN_GATE_FACT_KIND: 'design_approval';
3
3
  export declare const DESIGN_GATE_FACT_INPUT_PATH: 'input.context.facts.designGate';
4
4
  export declare const CODEX_DESIGN_GATE_SOURCE: 'codex-native-pretool-design-gate-v1';
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import { DESIGN_GATE_FACT_SCHEMA_VERSION, SqliteConnection, SqliteDesignGateStore, isDesignGateDeclaration, } from '@principles/core/runtime-v2';
4
+ import { DESIGN_GATE_FACT_SCHEMA_VERSION, SqliteConnection, SqliteDesignGateStore, isDesignGateDeclaration, } from '@principles/core/runtime';
5
5
  export const DESIGN_GATE_FACT_KIND = 'design_approval';
6
6
  export const DESIGN_GATE_FACT_INPUT_PATH = 'input.context.facts.designGate';
7
7
  export const CODEX_DESIGN_GATE_SOURCE = 'codex-native-pretool-design-gate-v1';
@@ -32,7 +32,7 @@
32
32
  * consumer cycle (live registry) or a CLI entry (durable declaration), because
33
33
  * hosts persist the same mapping constants they pass in memory.
34
34
  */
35
- import { type RefinerRuleHostGateDeps, type ToolSemanticRegistry } from '@principles/core/runtime-v2';
35
+ import { type RefinerRuleHostGateDeps, type ToolSemanticRegistry } from '@principles/core/runtime';
36
36
  export interface EvaluatorRuntimeContextInput {
37
37
  /** Workspace root the replay normalizes paths against (projectDir). */
38
38
  readonly workspaceDir: string;
@@ -32,7 +32,7 @@
32
32
  * consumer cycle (live registry) or a CLI entry (durable declaration), because
33
33
  * hosts persist the same mapping constants they pass in memory.
34
34
  */
35
- import { createProductionGateDeps, } from '@principles/core/runtime-v2';
35
+ import { createProductionGateDeps, } from '@principles/core/runtime';
36
36
  import { resolveWorkspaceHostToolSemantics } from './host-tool-semantic-resolver.js';
37
37
  /**
38
38
  * Build the evaluator's deterministic replay context.
@@ -28,7 +28,7 @@ import fs from 'node:fs';
28
28
  import path from 'node:path';
29
29
  import { createHash } from 'node:crypto';
30
30
  import Database from 'better-sqlite3';
31
- import { sanitizeString, sanitizeValue } from '@principles/core/runtime-v2';
31
+ import { sanitizeString, sanitizeValue } from '@principles/core/runtime';
32
32
  // ─── Retention policy constants (Owner-approved, SPEC rev 2 §11) ────────────
33
33
  export const GOVERNANCE_RETENTION_MAX_TURNS = 32;
34
34
  export const GOVERNANCE_RETENTION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
@@ -1,4 +1,4 @@
1
- import { type LlmClassificationResult, type SignalCollectorOutput, type Stage2GateVerdict, type UnifiedKeywordStore } from '@principles/core/runtime-v2';
1
+ import { type LlmClassificationResult, type SignalCollectorOutput, type Stage2GateVerdict, type UnifiedKeywordStore } from '@principles/core/runtime';
2
2
  import { type ObservationDatabaseFactory } from './governance-observation-store.js';
3
3
  export declare const GOVERNANCE_STRONG_PAIN_SCORE = 70;
4
4
  export declare const GOVERNANCE_STRONG_RATE_LIMIT_PER_HOUR = 5;
@@ -388,7 +388,7 @@ export interface ReconcileGovernanceContinuationResult {
388
388
  }
389
389
  /**
390
390
  * Narrow idempotent reconciliation between the trajectory admission markers
391
- * and the Runtime V2 task store (separate SQLite databases — no cross-store
391
+ * and the Runtime task store (separate SQLite databases — no cross-store
392
392
  * transaction exists, SPEC §13). Current conversation-ingestion consent is
393
393
  * mandatory because it controls whether Codex observations may be read and
394
394
  * promoted; task/link recovery remains available when consent is off. Recovers:
@@ -19,7 +19,7 @@
19
19
  * process-local state dead state; OpenClaw's in-memory bucket and the
20
20
  * tool-pain cooldown keep their existing behavior);
21
21
  * - one admitted pain → exactly one pending Diagnostician task via
22
- * PainToPrincipleService async mode (Runtime V2 task authority), with the
22
+ * PainToPrincipleService async mode (Runtime task authority), with the
23
23
  * task link persisted on the admission marker;
24
24
  * - one narrow, idempotent reconciliation pass for the cross-store crash gaps
25
25
  * (trajectory.db ↔ .pd/state.db cannot share a transaction).
@@ -35,7 +35,7 @@ import fs from 'node:fs';
35
35
  import path from 'node:path';
36
36
  import { randomUUID } from 'node:crypto';
37
37
  import Database from 'better-sqlite3';
38
- import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, disposePainSignalBridgesForWorkspace, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime-v2';
38
+ import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, disposePainSignalBridgesForWorkspace, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
39
  import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
40
40
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
41
  import { loadPdConfigForPlugin } from './pd-config.js';
@@ -1977,7 +1977,7 @@ export async function ensureGovernanceContinuation(input) {
1977
1977
  }
1978
1978
  /**
1979
1979
  * Narrow idempotent reconciliation between the trajectory admission markers
1980
- * and the Runtime V2 task store (separate SQLite databases — no cross-store
1980
+ * and the Runtime task store (separate SQLite databases — no cross-store
1981
1981
  * transaction exists, SPEC §13). Current conversation-ingestion consent is
1982
1982
  * mandatory because it controls whether Codex observations may be read and
1983
1983
  * promoted; task/link recovery remains available when consent is off. Recovers:
@@ -1,4 +1,4 @@
1
- import type { HostLivenessContract } from '@principles/core/runtime-v2';
1
+ import type { HostLivenessContract } from '@principles/core/runtime';
2
2
  /** Adapter-owned facts consumed by the non-bypassable RuleCode promotion gate. */
3
3
  export declare const OPENCLAW_HOST_LIVENESS_CONTRACT: HostLivenessContract;
4
4
  /**
@@ -16,7 +16,7 @@
16
16
  * unknown and structurally validated (rc-1/rc-2/rc-4); malformed files fail
17
17
  * loud with a typed per-host reason, never degrade silently (rc-3/rc-9).
18
18
  */
19
- import { type ToolSemanticMappingV1 } from '@principles/core/runtime-v2';
19
+ import { type ToolSemanticMappingV1 } from '@principles/core/runtime';
20
20
  export declare const HOST_TOOL_DECLARATION_DIRNAME = "host-tool-semantics";
21
21
  export declare const HOST_TOOL_DECLARATION_VERSION: 1;
22
22
  export interface HostToolDeclaration {
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { readFileSync, writeFileSync, mkdirSync, mkdtempSync, renameSync, rmSync, readdirSync } from 'node:fs';
20
20
  import path from 'node:path';
21
- import { validateToolSemanticMappings, } from '@principles/core/runtime-v2';
21
+ import { validateToolSemanticMappings, } from '@principles/core/runtime';
22
22
  export const HOST_TOOL_DECLARATION_DIRNAME = 'host-tool-semantics';
23
23
  export const HOST_TOOL_DECLARATION_VERSION = 1;
24
24
  const MAX_DECLARATION_BYTES = 256 * 1024;
@@ -25,7 +25,7 @@
25
25
  *
26
26
  * Pure logic + declared-file I/O only. Merging is order-independent.
27
27
  */
28
- import { type ToolSemanticRegistry } from '@principles/core/runtime-v2';
28
+ import { type ToolSemanticRegistry } from '@principles/core/runtime';
29
29
  import { saveHostToolDeclaration, type HostToolDeclaration } from './host-tool-declaration.js';
30
30
  export type HostToolSemanticResolution = {
31
31
  readonly ok: true;
@@ -25,7 +25,7 @@
25
25
  *
26
26
  * Pure logic + declared-file I/O only. Merging is order-independent.
27
27
  */
28
- import { buildToolSemanticRegistry, } from '@principles/core/runtime-v2';
28
+ import { buildToolSemanticRegistry, } from '@principles/core/runtime';
29
29
  import { loadHostToolDeclarations, saveHostToolDeclaration, } from './host-tool-declaration.js';
30
30
  /**
31
31
  * Resolve the merged workspace registry from durable host provenance.