create-principles-disciple 1.147.14 → 1.147.17

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 (82) hide show
  1. package/_release/product-identity.json +2 -2
  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 +3 -3
  24. package/core/dist/runtime/index.d.ts.map +1 -1
  25. package/core/dist/runtime/index.js +4 -2
  26. package/core/dist/runtime/index.js.map +1 -1
  27. package/core/dist/runtime/types/event-types.d.ts +62 -3
  28. package/core/dist/runtime/types/event-types.d.ts.map +1 -1
  29. package/core/dist/runtime/types/event-types.js +43 -0
  30. package/core/dist/runtime/types/event-types.js.map +1 -1
  31. package/core/package.json +1 -1
  32. package/dist/mvp-config.d.ts +4 -0
  33. package/dist/mvp-config.d.ts.map +1 -1
  34. package/dist/mvp-config.js +4 -0
  35. package/dist/mvp-config.js.map +1 -1
  36. package/host-runtime/dist/active-principle-prompt.d.ts +111 -2
  37. package/host-runtime/dist/active-principle-prompt.js +168 -41
  38. package/host-runtime/dist/adaptive-principle-revalidation.js +1 -1
  39. package/host-runtime/dist/index.d.ts +10 -0
  40. package/host-runtime/dist/index.js +31 -13
  41. package/host-runtime/dist/product-telemetry/consent-store.d.ts +112 -14
  42. package/host-runtime/dist/product-telemetry/consent-store.js +343 -132
  43. package/host-runtime/dist/product-telemetry/control-state-lock.d.ts +99 -0
  44. package/host-runtime/dist/product-telemetry/control-state-lock.js +320 -0
  45. package/host-runtime/dist/product-telemetry/service.d.ts +26 -9
  46. package/host-runtime/dist/product-telemetry/service.js +90 -150
  47. package/host-runtime/dist/prompt-activation-deliverability.d.ts +25 -15
  48. package/host-runtime/dist/prompt-activation-deliverability.js +60 -30
  49. package/host-runtime/dist/prompt-injection-projection.d.ts +105 -48
  50. package/host-runtime/dist/prompt-injection-projection.js +190 -212
  51. package/host-runtime/dist/prompt-injection-status.js +16 -7
  52. package/host-runtime/dist/signal-stage2-cycle.js +8 -1
  53. package/host-runtime/package.json +1 -1
  54. package/package.json +3 -3
  55. package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
  56. package/pd-cli/dist/commands/runtime-activation.js +4 -0
  57. package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
  58. package/pd-cli/dist/commands/telemetry.d.ts.map +1 -1
  59. package/pd-cli/dist/commands/telemetry.js +3 -1
  60. package/pd-cli/dist/commands/telemetry.js.map +1 -1
  61. package/pd-cli/package.json +1 -1
  62. package/plugin/dist/bundle.js +487 -490
  63. package/plugin/dist/core/event-log.d.ts +8 -1
  64. package/plugin/dist/core/signal-collector-host.d.ts +27 -7
  65. package/plugin/dist/governance-audit.js +2 -2
  66. package/plugin/dist/hooks/llm-input-presence.d.ts +42 -0
  67. package/plugin/dist/hooks/prompt-presence-expectations.d.ts +74 -0
  68. package/plugin/dist/hooks/prompt-presence-lite.d.ts +53 -0
  69. package/plugin/dist/hooks/prompt-presence-measure.d.mts +1 -0
  70. package/plugin/dist/hooks/prompt-presence-registry.d.ts +150 -0
  71. package/plugin/dist/hooks/prompt.d.ts +40 -0
  72. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +24 -1
  73. package/plugin/dist/index.d.ts +16 -9
  74. package/plugin/dist/openclaw-sdk.d.ts +33 -0
  75. package/plugin/dist/openclaw.plugin.json +1 -1
  76. package/plugin/dist/types/event-types.d.ts +1 -1
  77. package/plugin/openclaw.plugin.json +1 -1
  78. package/plugin/package.json +1 -1
  79. package/release-manager/dist/mvp-config.js +4 -0
  80. package/release-manager/package.json +1 -1
  81. package/workbuddy-adapter/package.json +1 -1
  82. package/workbuddy-adapter/plugin/.codebuddy-plugin/plugin.json +1 -1
@@ -23,7 +23,8 @@ import { fileURLToPath } from 'node:url';
23
23
  import { bucketDateFromTime, buildProductTelemetrySnapshot, deriveDailyTelemetryId, isValidTelemetrySecretHex, } from '@principles/core/runtime';
24
24
  import { getInstallLayoutPaths, parseInstallManifest, resolveInstallLayout } from '@principles/install-layout';
25
25
  import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from '../pd-config.js';
26
- import { deniedControlState, defaultProductTelemetryControlState, getProductTelemetryStatePath, grantedControlState, pruneWorkspaceExports, readProductTelemetryControlState, resetControlState, writeProductTelemetryControlState, } from './consent-store.js';
26
+ import { deniedControlState, defaultProductTelemetryControlState, getProductTelemetryStatePath, grantedControlState, pruneWorkspaceExports, readProductTelemetryControlState, resetControlState, withControlStateLock, } from './consent-store.js';
27
+ import { releaseExclusiveLock, tryAcquireExclusiveLockSync } from './control-state-lock.js';
27
28
  import { computeTelemetryEnvironment } from './eligibility.js';
28
29
  import { DEFAULT_PRODUCT_TELEMETRY_ENDPOINT, exportSnapshot, nextRetryDelayMs } from './exporter.js';
29
30
  import { readMilestoneFacts } from './milestone-readers.js';
@@ -35,132 +36,42 @@ export const PREVIEW_BANNER = 'Preview only. Nothing was sent.';
35
36
  export const MAX_DAILY_EXPORT_ATTEMPTS = 5;
36
37
  /** A lock older than this is treated as orphaned (holder crashed) and taken over. */
37
38
  const EXPORT_LOCK_STALE_MS = 5 * 60 * 1000;
38
- /**
39
- * The state-update critical section (fresh read → prune → merge → atomic
40
- * write) holds for a few ms, so the poll budget and stale threshold are
41
- * tiny compared to the export lock's — a crashed holder blocks bookkeeping
42
- * for seconds, not minutes, and live holders can never be evicted (the
43
- * hold is far shorter than the stale threshold).
44
- */
45
- const STATE_UPDATE_LOCK_STALE_MS = 5 * 1000;
46
- const STATE_UPDATE_LOCK_TIMEOUT_MS = 3 * 1000;
47
- const STATE_UPDATE_LOCK_POLL_MS = 15;
48
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
49
39
  /**
50
40
  * Per-workspace cross-process export lock: exclusive create ('wx') is atomic,
51
41
  * so exactly one of N simultaneous holders wins — and the lock name embeds
52
42
  * only the opaque scope key, so workspace A's in-flight export never blocks
53
- * workspace B's (review remediation P1-1). Stale takeover uses mtime — a
54
- * crashed holder can block that workspace for at most EXPORT_LOCK_STALE_MS.
43
+ * workspace B's (review remediation P1-1). Stale takeover and release use the
44
+ * SAME ownership-checked rename-claim protocol as the control-state lock
45
+ * (control-state-lock.ts, PRI-1151): a crashed holder blocks that workspace
46
+ * for at most EXPORT_LOCK_STALE_MS, a live holder's lock is never deleted by
47
+ * another process, and a late release cannot delete a successor's lock.
55
48
  * Never throws: any filesystem failure degrades to "not acquired"
56
49
  * (telemetry skips, PD unaffected).
57
50
  */
58
51
  function tryAcquireExportLock(stateFilePath, workspaceScopeId) {
59
- const lockPath = workspaceExportLockPath(stateFilePath, workspaceScopeId);
60
- const create = () => {
61
- try {
62
- const fd = fs.openSync(lockPath, 'wx');
63
- try {
64
- fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}`);
65
- }
66
- finally {
67
- fs.closeSync(fd);
68
- }
69
- return true;
70
- }
71
- catch {
72
- return false;
73
- }
74
- };
75
- if (create())
76
- return { acquired: true, lockPath };
77
- try {
78
- const stat = fs.statSync(lockPath);
79
- if (Date.now() - stat.mtimeMs > EXPORT_LOCK_STALE_MS) {
80
- fs.rmSync(lockPath, { force: true });
81
- if (create())
82
- return { acquired: true, lockPath };
83
- }
84
- }
85
- catch {
86
- // stat/rm failure → treat as busy; never throw for telemetry
87
- }
88
- return { acquired: false };
89
- }
90
- function releaseExportLock(lockPath) {
91
- try {
92
- fs.rmSync(lockPath, { force: true });
93
- }
94
- catch {
95
- // best effort; a leaked lock is reclaimed after EXPORT_LOCK_STALE_MS
96
- }
52
+ return tryAcquireExclusiveLockSync(stateFilePath, {
53
+ lockPath: workspaceExportLockPath(stateFilePath, workspaceScopeId),
54
+ staleMs: EXPORT_LOCK_STALE_MS,
55
+ });
97
56
  }
98
57
  /**
99
- * Machine-scope state-update lock: serializes ONLY the control-state file
100
- * read→merge→write across workspaces (a few ms each) — the network export
101
- * itself stays fully concurrent. Review round 4: without it, two
102
- * concurrently-completing exports built their writes from the same stale
103
- * base and the later write silently dropped the earlier workspace's entry
104
- * (lost update), defeating once/day dedup, backoff, and the attempt cap.
105
- *
106
- * Lock acquisition polls asynchronously (never blocks the event loop) and
107
- * takes over a stale (crashed-holder) lock after STATE_UPDATE_LOCK_STALE_MS.
108
- */
109
- async function acquireStateUpdateLock(stateFilePath) {
110
- const lockPath = `${stateFilePath}.state-lock`;
111
- const deadline = Date.now() + STATE_UPDATE_LOCK_TIMEOUT_MS;
112
- const create = () => {
113
- try {
114
- const fd = fs.openSync(lockPath, 'wx');
115
- try {
116
- fs.writeSync(fd, `${process.pid} ${new Date().toISOString()}`);
117
- }
118
- finally {
119
- fs.closeSync(fd);
120
- }
121
- return true;
122
- }
123
- catch {
124
- return false;
125
- }
126
- };
127
- for (;;) {
128
- if (create())
129
- return { acquired: true, lockPath };
130
- try {
131
- const stat = fs.statSync(lockPath);
132
- if (Date.now() - stat.mtimeMs > STATE_UPDATE_LOCK_STALE_MS) {
133
- fs.rmSync(lockPath, { force: true });
134
- if (create())
135
- return { acquired: true, lockPath };
136
- }
137
- }
138
- catch {
139
- // disappeared between poll attempts → next loop's create decides
140
- }
141
- if (Date.now() >= deadline)
142
- return { acquired: false };
143
- await sleep(STATE_UPDATE_LOCK_POLL_MS);
144
- }
145
- }
146
- /**
147
- * Merge ONE workspace's export entry into the control state inside the
148
- * state-update critical section. The entry itself is built by the caller
149
- * (its inputs are stable for this workspace under the per-workspace export
150
- * lock); the OTHER workspaces' entries come from a FRESH read under the
151
- * lock, so concurrent completions compose instead of overwrite. Identity
152
- * transitions that raced the export (reset/disable/secret rotation mid-
153
- * flight) are detected and win — an in-flight result is never merged into
154
- * a rotated/denied identity. Best-effort by contract: every non-written
155
- * outcome is observable at the call site via structured logs (rc-9).
58
+ * Merge ONE workspace's export entry into the control state inside the ONE
59
+ * cross-process control-state transaction (withControlStateLock, PRI-1151)
60
+ * — the same lock that serializes enable/disable/reset and the legacy v1→v2
61
+ * migration write-back. The entry itself is built by the caller (its inputs
62
+ * are stable for this workspace under the per-workspace export lock); the
63
+ * OTHER workspaces' entries and the consent identity come from a FRESH read
64
+ * under the lock, so concurrent completions compose instead of overwrite,
65
+ * and identity transitions that raced the export (reset/disable/secret
66
+ * rotation mid-flight) are detected and win — an in-flight result is never
67
+ * merged into a rotated/denied identity. Best-effort by contract: every
68
+ * non-written outcome is observable at the call site via structured logs
69
+ * (rc-9). A legacy v1 file is migrated to the current format by this same
70
+ * transaction (migration + merge are one atomic write).
156
71
  */
157
72
  async function mergeWorkspaceExportEntry(args) {
158
- const stateFilePath = getProductTelemetryStatePath(args.homeDir);
159
- const lock = await acquireStateUpdateLock(stateFilePath);
160
- if (!lock.acquired)
161
- return 'skipped_contention';
162
- try {
163
- const read = readProductTelemetryControlState(args.homeDir);
73
+ const outcome = await withControlStateLock(args.homeDir, (tx) => {
74
+ const read = tx.readLatest();
164
75
  if (!read.ok)
165
76
  return 'skipped_unreadable';
166
77
  if (read.state.consent !== 'granted' || read.state.telemetrySecret !== args.secret)
@@ -170,11 +81,11 @@ async function mergeWorkspaceExportEntry(args) {
170
81
  ...pruned,
171
82
  workspaceExports: { ...(pruned.workspaceExports ?? {}), [args.scopeKey]: args.nextEntry },
172
83
  };
173
- return writeProductTelemetryControlState(args.homeDir, nextState).ok ? 'written' : 'skipped_unreadable';
174
- }
175
- finally {
176
- releaseExportLock(lock.lockPath);
177
- }
84
+ return tx.write(nextState).ok ? 'written' : 'skipped_unreadable';
85
+ });
86
+ if (!outcome.ok)
87
+ return 'skipped_contention';
88
+ return outcome.value;
178
89
  }
179
90
  const DEFAULT_MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
180
91
  function readJsonFile(filePath) {
@@ -337,40 +248,69 @@ export function createProductTelemetryService(deps = {}) {
337
248
  previewNotes.push(`control state unreadable (${read.reason}) — showing defaults`);
338
249
  return { banner: PREVIEW_BANNER, snapshot, gates, notes: previewNotes, secretEphemeral };
339
250
  },
340
- /** `pd telemetry enable --confirm`: explicit granted consent (+ secret). */
341
- enable() {
342
- const read = readProductTelemetryControlState(homeDir());
343
- if (!read.ok)
344
- return read;
345
- const next = grantedControlState(read.state);
346
- const written = writeProductTelemetryControlState(homeDir(), next);
347
- if (!written.ok)
348
- return written;
251
+ /**
252
+ * `pd telemetry enable --confirm`: explicit granted consent (+ secret).
253
+ * One locked transaction (PRI-1151): the latest disk state is read UNDER
254
+ * the same cross-process lock that serializes every other control-state
255
+ * writer, so the grant is computed from — and applied to — the current
256
+ * state; a concurrent disable/migration/reset cannot be overwritten by a
257
+ * stale one.
258
+ */
259
+ async enable() {
260
+ const outcome = await withControlStateLock(homeDir(), (tx) => {
261
+ const read = tx.readLatest();
262
+ if (!read.ok)
263
+ return read;
264
+ return tx.write(grantedControlState(read.state));
265
+ });
266
+ if (!outcome.ok)
267
+ return outcome;
268
+ if (!outcome.value.ok)
269
+ return outcome.value;
349
270
  logger.info?.(`[PD:Telemetry] Consent granted (control state: ${getProductTelemetryStatePath(homeDir())}).`);
350
271
  return { ok: true, consent: 'granted' };
351
272
  },
352
- /** `pd telemetry disable --confirm`: deny consent and delete export identity. */
353
- disable() {
354
- const read = readProductTelemetryControlState(homeDir());
355
- if (!read.ok)
356
- return read;
357
- const written = writeProductTelemetryControlState(homeDir(), deniedControlState());
358
- if (!written.ok)
359
- return written;
273
+ /**
274
+ * `pd telemetry disable --confirm`: deny consent and delete export
275
+ * identity — one locked transaction (PRI-1151). Once this returns ok,
276
+ * no concurrent migration, enable, reset, or bookkeeping merge can
277
+ * restore the previous granted consent or secret: they serialize on the
278
+ * same lock and re-read the denied state.
279
+ */
280
+ async disable() {
281
+ const outcome = await withControlStateLock(homeDir(), (tx) => {
282
+ const read = tx.readLatest();
283
+ if (!read.ok)
284
+ return read;
285
+ return tx.write(deniedControlState());
286
+ });
287
+ if (!outcome.ok)
288
+ return outcome;
289
+ if (!outcome.value.ok)
290
+ return outcome.value;
360
291
  logger.info?.('[PD:Telemetry] Consent denied; local telemetry secret and export status deleted. Future export requests: 0.');
361
292
  return { ok: true, consent: 'denied' };
362
293
  },
363
- /** `pd telemetry reset --confirm`: delete identity; fresh secret only if still enabled. */
364
- reset() {
365
- const read = readProductTelemetryControlState(homeDir());
366
- if (!read.ok)
367
- return read;
368
- const next = resetControlState(read.state);
369
- const written = writeProductTelemetryControlState(homeDir(), next);
370
- if (!written.ok)
371
- return written;
294
+ /**
295
+ * `pd telemetry reset --confirm`: delete identity; fresh secret only if
296
+ * still enabled — one locked transaction (PRI-1151) over the LATEST disk
297
+ * state (never a stale cached identity).
298
+ */
299
+ async reset() {
300
+ const outcome = await withControlStateLock(homeDir(), (tx) => {
301
+ const read = tx.readLatest();
302
+ if (!read.ok)
303
+ return read;
304
+ const next = resetControlState(read.state);
305
+ const written = tx.write(next);
306
+ return written.ok ? { ok: true, consent: next.consent } : written;
307
+ });
308
+ if (!outcome.ok)
309
+ return outcome;
310
+ if (!outcome.value.ok)
311
+ return outcome.value;
372
312
  logger.info?.('[PD:Telemetry] Telemetry identity reset; previous daily IDs are unlinkable going forward.');
373
- return { ok: true, consent: next.consent };
313
+ return { ok: true, consent: outcome.value.consent };
374
314
  },
375
315
  /**
376
316
  * One gate-checked export attempt for a normal-activity trigger.
@@ -422,7 +362,7 @@ export function createProductTelemetryService(deps = {}) {
422
362
  return { attempted: false, skipReason: 'daily_attempt_cap' };
423
363
  }
424
364
  const lock = tryAcquireExportLock(getProductTelemetryStatePath(homeDir()), scopeKey);
425
- if (!lock.acquired || lock.lockPath === undefined) {
365
+ if (lock === undefined) {
426
366
  // Another process is mid-export for THIS workspace; it will record
427
367
  // shared-day success and our next trigger will see
428
368
  // already_succeeded_today.
@@ -493,7 +433,7 @@ export function createProductTelemetryService(deps = {}) {
493
433
  nextEntry,
494
434
  });
495
435
  if (merged === 'skipped_contention') {
496
- logger.warn?.(`[PD:Telemetry] Export ${result.ok ? 'succeeded' : `failed (${result.code})`} but control state update was skipped after ${STATE_UPDATE_LOCK_TIMEOUT_MS / 1000}s of state-lock contention — this workspace may re-attempt today.`);
436
+ logger.warn?.(`[PD:Telemetry] Export ${result.ok ? 'succeeded' : `failed (${result.code})`} but control state update was skipped after 3s of state-lock contention — this workspace may re-attempt today.`);
497
437
  }
498
438
  else if (merged === 'skipped_unreadable') {
499
439
  logger.warn?.(`[PD:Telemetry] Export ${result.ok ? 'succeeded' : `failed (${result.code})`} but control state could not be read/updated — ${getProductTelemetryStatePath(homeDir())}`);
@@ -509,7 +449,7 @@ export function createProductTelemetryService(deps = {}) {
509
449
  return { attempted: true, ok: false, failureCode: result.code };
510
450
  }
511
451
  finally {
512
- releaseExportLock(lock.lockPath);
452
+ releaseExclusiveLock(lock);
513
453
  }
514
454
  },
515
455
  };
@@ -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
  }