create-principles-disciple 1.147.14 → 1.147.16

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 (61) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/package.json +1 -1
  3. package/console/dist/server/models/ActivationsConsoleModel.js +9 -3
  4. package/console/dist/server/models/ApprovalsConsoleModel.js +35 -6
  5. package/console/dist/server/models/ApprovalsGroupedConsoleModel.js +42 -2
  6. package/console/dist/shared/prompt-injection-contract.d.ts +31 -4
  7. package/console/dist/web/assets/app.css +4 -0
  8. package/console/dist/web/assets/app.js +25 -25
  9. package/core/dist/runtime/activation/index.d.ts +1 -1
  10. package/core/dist/runtime/activation/index.d.ts.map +1 -1
  11. package/core/dist/runtime/activation/index.js +4 -1
  12. package/core/dist/runtime/activation/index.js.map +1 -1
  13. package/core/dist/runtime/activation/prompt-activation-reader-contract.d.ts +20 -0
  14. package/core/dist/runtime/activation/prompt-activation-reader-contract.d.ts.map +1 -1
  15. package/core/dist/runtime/activation/prompt-activation-reader-contract.js +86 -27
  16. package/core/dist/runtime/activation/prompt-activation-reader-contract.js.map +1 -1
  17. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  18. package/core/dist/runtime/feature-flags/feature-flag-contract.js +6 -1
  19. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  20. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  21. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +0 -8
  22. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  23. package/core/dist/runtime/index.d.ts +1 -1
  24. package/core/dist/runtime/index.d.ts.map +1 -1
  25. package/core/dist/runtime/index.js +3 -1
  26. package/core/dist/runtime/index.js.map +1 -1
  27. package/core/package.json +1 -1
  28. package/dist/mvp-config.d.ts +4 -0
  29. package/dist/mvp-config.d.ts.map +1 -1
  30. package/dist/mvp-config.js +4 -0
  31. package/dist/mvp-config.js.map +1 -1
  32. package/host-runtime/dist/active-principle-prompt.d.ts +87 -2
  33. package/host-runtime/dist/active-principle-prompt.js +132 -41
  34. package/host-runtime/dist/adaptive-principle-revalidation.js +1 -1
  35. package/host-runtime/dist/index.d.ts +10 -0
  36. package/host-runtime/dist/index.js +31 -13
  37. package/host-runtime/dist/prompt-activation-deliverability.d.ts +25 -15
  38. package/host-runtime/dist/prompt-activation-deliverability.js +60 -30
  39. package/host-runtime/dist/prompt-injection-projection.d.ts +105 -48
  40. package/host-runtime/dist/prompt-injection-projection.js +190 -212
  41. package/host-runtime/dist/prompt-injection-status.js +16 -7
  42. package/host-runtime/package.json +1 -1
  43. package/package.json +3 -3
  44. package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
  45. package/pd-cli/dist/commands/runtime-activation.js +4 -0
  46. package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
  47. package/pd-cli/package.json +1 -1
  48. package/plugin/dist/bundle.js +482 -486
  49. package/plugin/dist/core/signal-collector-host.d.ts +27 -7
  50. package/plugin/dist/hooks/prompt-presence-expectations.d.ts +69 -0
  51. package/plugin/dist/hooks/prompt.d.ts +40 -0
  52. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +24 -1
  53. package/plugin/dist/index.d.ts +16 -9
  54. package/plugin/dist/openclaw-sdk.d.ts +16 -0
  55. package/plugin/dist/openclaw.plugin.json +1 -1
  56. package/plugin/openclaw.plugin.json +1 -1
  57. package/plugin/package.json +1 -1
  58. package/release-manager/dist/mvp-config.js +4 -0
  59. package/release-manager/package.json +1 -1
  60. package/workbuddy-adapter/package.json +1 -1
  61. package/workbuddy-adapter/plugin/.codebuddy-plugin/plugin.json +1 -1
@@ -1,4 +1,7 @@
1
- import { SqliteActivationStateStore, SqliteConnection, SqlitePIArtifactStore, computeFeatureFlagsFromConfig, filterPromptActivations, renderPrinciplesToDirectives, resolvePrincipleFromArtifact, resolvePromptBudget, } from '@principles/core/runtime';
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
@@ -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
  }
@@ -77,6 +77,16 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
77
77
  projectDir?: string;
78
78
  /** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
79
79
  toolSemantics?: ToolSemanticRegistry;
80
+ /**
81
+ * PRI-1137: optional authoritative session-round key supplied by the host
82
+ * adapter that actually owns an advancing user-turn authority. The
83
+ * OpenClaw adapter forwards the trusted `nextSessionTurnOrdinal` value
84
+ * here; Codex / WorkBuddy supply nothing because they have no user_turns
85
+ * authority (a constant or a synthetic value would be a false fair-rotation
86
+ * claim). Absent / `undefined` → `legacy_fifo_prefix_v1`, exactly as
87
+ * before this convergence. Must be a positive integer when present.
88
+ */
89
+ roundKeyProvider?: (event: HostEvent) => number | undefined | Promise<number | undefined>;
80
90
  /** Optional, already-scoped single prompt target from the host adapter. Errors fail closed to Native. */
81
91
  adaptivePriorityProvider?: (event: HostEvent) => {
82
92
  artifactId: string;
@@ -203,16 +203,32 @@ export function createProductionHostRuntime(options = {}) {
203
203
  }),
204
204
  beforeToolCall: options.beforeToolCall ?? productionGate,
205
205
  async beforePromptBuild(event) {
206
- // PRI-904 Phase-1 (Option 3): this production path is ALSO the Codex
207
- // route, and Codex never writes trajectory.db::user_turns — its
208
- // ingestion writes governance_* rows instead. Reading a session turn
209
- // ordinal here would therefore be a false round authority: on Codex it
210
- // either throws (→ legacy) or returns a constant 1 (→ fixed start, a
211
- // different positional starvation while the event still claimed a fair
212
- // rotation). So the shared production path passes NO round key and
213
- // reports `legacy_fifo_prefix_v1` honestly. The selector's fair-rotation
214
- // capability is retained and stays reachable for callers that DO hold a
215
- // legitimate advancing round authority.
206
+ // PRI-904 Phase-1 (Option 3): Codex never writes
207
+ // trajectory.db::user_turns — its ingestion writes governance_* rows
208
+ // instead. Reading a session turn ordinal there would be a false round
209
+ // authority: either it throws (→ legacy) or returns a constant 1 (→
210
+ // fixed start, a different positional starvation while the event still
211
+ // claimed a fair rotation). PRI-1137: this is now enforced through
212
+ // `roundKeyProvider` — only the host that owns a real advancing
213
+ // user-turn authority (OpenClaw) supplies one, and everything else
214
+ // honestly reports `legacy_fifo_prefix_v1`.
215
+ let roundKey;
216
+ if (options.roundKeyProvider) {
217
+ try {
218
+ // The provider may perform the host's PRE-SELECTION work (OpenClaw:
219
+ // signal collection + user_turns write) before returning the ordinal,
220
+ // so it must run before the prompt context is built.
221
+ const candidate = await options.roundKeyProvider(event);
222
+ if (typeof candidate === 'number' && Number.isInteger(candidate) && candidate >= 1) {
223
+ roundKey = candidate;
224
+ }
225
+ }
226
+ catch {
227
+ // Degradation is observable through the resulting selectionPolicy
228
+ // (`legacy_fifo_prefix_v1`); the provider logs its own reason.
229
+ roundKey = undefined;
230
+ }
231
+ }
216
232
  // PRI-1020: the Owner's declared window (.pd/config.yaml promptBudget)
217
233
  // is tier 0 of the budget chain — resolved per host and fed into the
218
234
  // SAME single resolver below. One extra sync config read per prompt
@@ -249,6 +265,7 @@ export function createProductionHostRuntime(options = {}) {
249
265
  }
250
266
  const prompt = await buildActivePrinciplePromptContext({
251
267
  workspaceDir: event.context.workspaceDir,
268
+ ...(roundKey !== undefined ? { roundKey } : {}),
252
269
  ...(adaptivePriority ? {
253
270
  adaptivePriority: { artifactId: adaptivePriority.artifactId, activationId: adaptivePriority.activationId },
254
271
  ...(adaptivePriority.signal ? { signal: adaptivePriority.signal } : {}),
@@ -318,9 +335,10 @@ export function createProductionHostRuntime(options = {}) {
318
335
  // operators can tell model-identity absence from catalog ambiguity
319
336
  // etc. without touching logs. Detail stays out of events.
320
337
  ...(prompt.budgetFallbackReason !== undefined ? { budgetFallbackReason: prompt.budgetFallbackReason } : {}),
321
- // PRI-904: selection diagnostics (bounded, optional). On this route
322
- // the policy is legacy_fifo_prefix_v1 and NO rotation provenance is
323
- // emitted — a fair claim would be untrue here (see above).
338
+ // PRI-904/PRI-1137: selection diagnostics (bounded, optional).
339
+ // The policy reflects the real selection: `fair_rotation_v1` only
340
+ // when a trusted roundKey was supplied, `legacy_fifo_prefix_v1`
341
+ // otherwise — never a claim the selection did not make.
324
342
  ...(prompt.selectionPolicy !== undefined ? { selectionPolicy: prompt.selectionPolicy } : {}),
325
343
  ...(prompt.eligibleCount !== undefined ? { eligibleCount: prompt.eligibleCount } : {}),
326
344
  ...(prompt.rotationStartIndex !== undefined ? { rotationStartIndex: prompt.rotationStartIndex } : {}),
@@ -3,11 +3,11 @@ import { PROMPT_INJECTION_UNIT, type PromptInjectionBudgetScope, type PromptInje
3
3
  /**
4
4
  * SPEC PD_PROMPT_CAPACITY_V1 R-B2: ONE route-aware single-artifact capacity
5
5
  * precheck, shared by every real prompt-activation write entry (Console
6
- * approve, CLI approve) and by the pre-approval candidate fit (R-A2). The
7
- * cost is measured with the SAME production serializer/selector the bound
8
- * route uses — list route bills the selected-lines entry (header + entry),
9
- * shared route bills the full single-principle directive render including
10
- * the self-report footer when that flag is on. The principle identity is
6
+ * approve, CLI approve) and by the pre-approval candidate fit (R-A2).
7
+ * PRI-1137: the cost is measured with the ONE live production serializer —
8
+ * the full single-principle directive render (including the self-report
9
+ * footer when that flag is on). The retired list-route selected-lines
10
+ * arithmetic is gone. The principle identity is
11
11
  * the REAL resolved id (content `principleId` or draft title) — never a
12
12
  * fixed-length UUID allowance (a title-derived id can only be longer).
13
13
  *
@@ -91,23 +91,21 @@ export declare function resolvePromptCandidatePrinciple(artifact: PromptDelivera
91
91
  warning: string;
92
92
  };
93
93
  /**
94
- * Positive single-item evidence under a given route, using the production
95
- * selector itself (AC-06: a row is "fits" because its own serialized entry
96
- * fits — never because it is absent from a bounded diagnostic list).
94
+ * Positive single-item evidence under the live route, using the production
95
+ * serializer itself (AC-06: a row is "fits" because its own serialized
96
+ * directive fits — never because it is absent from a bounded diagnostic list).
97
97
  *
98
- * `costChars` is what the single-entry selection would consume, measured the
99
- * same way the route's projection reports `usedChars` (the joined selected
100
- * lines). For an entry that does NOT fit, trimToBudget returns only the
101
- * header line, so the would-be cost is reconstructed from the header line it
102
- * DID return plus the real entry line (same format authority, listEntryLine).
98
+ * `costChars` is what the single-entry selection consumes, measured exactly as
99
+ * the shared projection reports `usedChars`. PRI-1137: there is one live route,
100
+ * so there is no route parameter and no list-route `trimToBudget` arithmetic to
101
+ * keep in sync — a forecast may not measure a deleted path.
103
102
  *
104
- * The budget parameter defaults to the legacy fixed budget: approval-time
103
+ * The budget parameter defaults to the fixed fallback budget: approval-time
105
104
  * callers hold no runtime model facts, and SPEC §6.3 requires the fixed
106
105
  * fallback — never an invented capacity — when none can be confirmed.
107
106
  */
108
107
  export declare function computePromptSingleItemFit(input: {
109
108
  principle: ActivatedPrinciple;
110
- route: PromptInjectionRouteName;
111
109
  selfReportEnabled: boolean;
112
110
  budget?: number;
113
111
  }): {
@@ -122,6 +120,16 @@ export declare function checkPromptArtifactDeliverability(input: {
122
120
  workspaceDir: string;
123
121
  targetHost?: PromptInjectionTargetHost;
124
122
  artifact: PromptDeliverabilityCandidateArtifact | null | undefined;
123
+ /**
124
+ * PRI-1137 final review P2: the authority the DECISION under measurement
125
+ * will stamp on this artifact. Approve-time callers pass `'owner'` (the
126
+ * console/CLI approval IS an owner decision — the post-approval directive
127
+ * bills `authority="owner"`, and billing the pre-approval default
128
+ * `system_policy` overstated the entry by the attribute delta and could
129
+ * refuse a borderline-fitting entry). Absent → the current DB fact (the
130
+ * honest pre-decision view for candidate-fit surfaces).
131
+ */
132
+ authority?: 'owner' | 'system_policy';
125
133
  }): Promise<PromptArtifactDeliverability>;
126
134
  /** Load one artifact read-only from `<workspace>/.pd/state.db`. Failures carry a reason (rc-9). */
127
135
  export declare function loadPromptArtifactById(workspaceDir: string, artifactId: string): Promise<{
@@ -136,4 +144,6 @@ export declare function checkPromptArtifactDeliverabilityById(input: {
136
144
  workspaceDir: string;
137
145
  artifactId: string;
138
146
  targetHost?: PromptInjectionTargetHost;
147
+ /** See `checkPromptArtifactDeliverability.authority` (approve-time = 'owner'). */
148
+ authority?: 'owner' | 'system_policy';
139
149
  }): Promise<PromptArtifactDeliverability>;
@@ -1,9 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { PROMPT_BUDGET_FALLBACK_CHARS, PROMPT_BUDGET_MAX_CHARS, PROMPT_BUDGET_MIN_CHARS, SqliteConnection, SqlitePIArtifactStore, classifySingleItemBudgetTier, computeFeatureFlagsFromConfig, listEntryLine, renderPrinciplesToDirectives, resolvePrincipleFromArtifact, trimToBudget, } from '@principles/core/runtime';
3
+ import { PROMPT_BUDGET_FALLBACK_CHARS, PROMPT_BUDGET_MAX_CHARS, PROMPT_BUDGET_MIN_CHARS, SqliteConnection, SqlitePIArtifactStore, classifySingleItemBudgetTier, computeFeatureFlagsFromConfig, renderPrinciplesToDirectives, resolvePrincipleFromArtifact, } from '@principles/core/runtime';
4
4
  import { escapeXml } from '@principles/core/prompt-builder';
5
5
  import { loadPdConfigForPlugin } from './pd-config.js';
6
- import { PROMPT_INJECTION_TARGET_HOSTS, PROMPT_INJECTION_UNIT, promptRouteForHost, resolvePromptInjectionRouteDecision, } from './prompt-injection-projection.js';
6
+ import { readPromptActivationAuthority } from './prompt-activation-authority.js';
7
+ import { PROMPT_INJECTION_TARGET_HOSTS, PROMPT_INJECTION_UNIT, resolvePromptInjectionRouteDecision, } from './prompt-injection-projection.js';
7
8
  function syntheticPendingActivation(artifactId) {
8
9
  return {
9
10
  activationId: `pending:${artifactId}`,
@@ -29,35 +30,52 @@ function selfReportEnabledFor(workspaceDir) {
29
30
  return computeFeatureFlagsFromConfig(loadPdConfigForPlugin(workspaceDir).effective).flags.principle_receipt_self_report?.enabled === true;
30
31
  }
31
32
  /**
32
- * Positive single-item evidence under a given route, using the production
33
- * selector itself (AC-06: a row is "fits" because its own serialized entry
34
- * fits — never because it is absent from a bounded diagnostic list).
33
+ * Positive single-item evidence under the live route, using the production
34
+ * serializer itself (AC-06: a row is "fits" because its own serialized
35
+ * directive fits — never because it is absent from a bounded diagnostic list).
35
36
  *
36
- * `costChars` is what the single-entry selection would consume, measured the
37
- * same way the route's projection reports `usedChars` (the joined selected
38
- * lines). For an entry that does NOT fit, trimToBudget returns only the
39
- * header line, so the would-be cost is reconstructed from the header line it
40
- * DID return plus the real entry line (same format authority, listEntryLine).
37
+ * `costChars` is what the single-entry selection consumes, measured exactly as
38
+ * the shared projection reports `usedChars`. PRI-1137: there is one live route,
39
+ * so there is no route parameter and no list-route `trimToBudget` arithmetic to
40
+ * keep in sync — a forecast may not measure a deleted path.
41
41
  *
42
- * The budget parameter defaults to the legacy fixed budget: approval-time
42
+ * The budget parameter defaults to the fixed fallback budget: approval-time
43
43
  * callers hold no runtime model facts, and SPEC §6.3 requires the fixed
44
44
  * fallback — never an invented capacity — when none can be confirmed.
45
45
  */
46
46
  export function computePromptSingleItemFit(input) {
47
47
  const budget = input.budget ?? PROMPT_BUDGET_FALLBACK_CHARS;
48
- if (input.route === 'shared_render') {
49
- const render = renderPrinciplesToDirectives([input.principle], new Set([input.principle.principleId]), { escapeFn: escapeXml, selfReportInstruction: input.selfReportEnabled });
50
- return { fits: render.length <= budget, costChars: render.length };
51
- }
52
- const trimmed = trimToBudget([input.principle], budget, escapeXml);
53
- const fits = trimmed.injectedIds.has(input.principle.principleId);
54
- const costChars = trimmed.lines.length > 1
55
- ? trimmed.lines.join('\n').length
56
- : (trimmed.lines[0]?.length ?? 0) + 1 + listEntryLine(input.principle, escapeXml).length;
57
- return { fits, costChars };
48
+ const render = renderPrinciplesToDirectives([input.principle], new Set([input.principle.principleId]), { escapeFn: escapeXml, selfReportInstruction: input.selfReportEnabled });
49
+ return { fits: render.length <= budget, costChars: render.length };
58
50
  }
59
51
  const UNDELIVERABLE_NEXT_ACTION = 'shorten the principle statement and resubmit, or use the activations page "modify to injectable version" entry to create a replacement artifact (the approval facts are preserved)';
60
52
  const MODEL_DEPENDENT_NEXT_ACTION = 'this principle fits the injection budget only on models with a larger context window; it may be excluded at runtime on smaller-context models — the approval itself is unaffected';
53
+ /**
54
+ * PRI-1137: the production prompt annotates each directive with its authority,
55
+ * so an approval-time cost that omitted the attribute would understate the real
56
+ * bytes. Unknown/unreadable stays unannotated — never inferred.
57
+ *
58
+ * PRI-1137 final review P2: a BROKEN authority read is distinguished from
59
+ * "no annotation" — the caller refuses as unconfirmed instead of silently
60
+ * billing an unannotated (cheaper) entry (rc-3/rc-9).
61
+ */
62
+ function readAuthorityForArtifact(workspaceDir, artifactId) {
63
+ const stateDbPath = path.join(workspaceDir, '.pd', 'state.db');
64
+ if (!fs.existsSync(stateDbPath))
65
+ return { ok: true, authority: undefined };
66
+ let connection;
67
+ try {
68
+ connection = new SqliteConnection({ workspaceDir, readonly: true, bootstrapIfMissing: false, busyTimeoutMs: 0 });
69
+ return { ok: true, authority: readPromptActivationAuthority(connection, artifactId, 'prompt').authority };
70
+ }
71
+ catch (error) {
72
+ const message = error instanceof Error ? error.message : String(error);
73
+ return { ok: false, reason: `authority_read_failed: ${message.slice(0, 160)}` };
74
+ }
75
+ finally {
76
+ connection?.close();
77
+ }
78
+ }
61
79
  /**
62
80
  * Precheck one artifact against the workspace's effective injection route.
63
81
  * Pure read — no state mutation, safe to call before any governance write.
@@ -79,19 +97,30 @@ export async function checkPromptArtifactDeliverability(input) {
79
97
  };
80
98
  }
81
99
  const selfReportEnabled = selfReportEnabledFor(input.workspaceDir);
100
+ const authorityRead = readAuthorityForArtifact(input.workspaceDir, input.artifact.artifactId);
101
+ if (!authorityRead.ok) {
102
+ // A broken authority read must not be billed as "unannotated" — the cost
103
+ // evidence would be fabricated-cheap (final review P2, rc-3).
104
+ return {
105
+ status: 'unconfirmed',
106
+ reason: `${authorityRead.reason}; the single-entry cost cannot be measured with the authority annotation this route bills`,
107
+ nextAction: 'repair the workspace state.db readability (the authority join read failed), then retry',
108
+ };
109
+ }
110
+ const authority = input.authority ?? authorityRead.authority;
111
+ const principle = authority === undefined
112
+ ? resolved.principle
113
+ : { ...resolved.principle, authority };
82
114
  const decision = resolvePromptInjectionRouteDecision({
83
115
  workspaceDir: input.workspaceDir,
84
116
  targetHost: input.targetHost,
85
117
  });
86
118
  if (decision.status === 'confirmed' && decision.route !== undefined) {
87
119
  const { costChars } = computePromptSingleItemFit({
88
- principle: resolved.principle,
89
- route: decision.route,
120
+ principle,
90
121
  selfReportEnabled,
91
122
  });
92
- const budgetScope = decision.route === 'shared_render'
93
- ? 'full_directive_context'
94
- : 'selected_lines';
123
+ const budgetScope = 'full_directive_context';
95
124
  const shared = {
96
125
  route: decision.route,
97
126
  ...(decision.hostKind !== undefined ? { hostKind: decision.hostKind } : {}),
@@ -135,10 +164,8 @@ export async function checkPromptArtifactDeliverability(input) {
135
164
  // hand-typed two-host array dropped WorkBuddy from unconfirmed
136
165
  // deliverability reports).
137
166
  const perHost = PROMPT_INJECTION_TARGET_HOSTS.map((hostKind) => {
138
- const route = promptRouteForHost(hostKind, decision.flagEnabled);
139
167
  const { costChars } = computePromptSingleItemFit({
140
- principle: resolved.principle,
141
- route,
168
+ principle,
142
169
  selfReportEnabled,
143
170
  });
144
171
  return { hostKind, tierFit: classifySingleItemBudgetTier(costChars), costChars };
@@ -191,5 +218,8 @@ export async function checkPromptArtifactDeliverabilityById(input) {
191
218
  nextAction: 'fix the artifact store readability, then retry the approval',
192
219
  };
193
220
  }
194
- return checkPromptArtifactDeliverability({ ...input, artifact: loaded.artifact });
221
+ return checkPromptArtifactDeliverability({
222
+ ...input,
223
+ artifact: loaded.artifact,
224
+ });
195
225
  }