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
@@ -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';
@@ -7,6 +10,8 @@ import { readPromptActivationAuthority } from './prompt-activation-authority.js'
7
10
  import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
8
11
  /** PRI-904 SPEC §10: bounded diagnostic id lists (mirrors the core selector's cap of 16). */
9
12
  export const MAX_SHARED_DIAGNOSTIC_IDS = 16;
13
+ /** PRI-1150: bounded per-assembly presence-expectation entries (design v2 §2.1). */
14
+ export const MAX_SHARED_PRESENCE_EXPECTATIONS = 64;
10
15
  /**
11
16
  * PR #1844 follow-up: the activation READ half of buildActivePrinciplePromptContext,
12
17
  * exported so the console budget projection can share the exact same input
@@ -21,10 +26,9 @@ export async function readPromptActivationCandidates(input) {
21
26
  }
22
27
  const { flags } = computeFeatureFlagsFromConfig(config.effective);
23
28
  const { prompt: promptFlag } = flags;
24
- const abstractionLayerEnabled = flags.abstraction_layer_v1?.enabled === true;
25
29
  if (!promptFlag?.enabled) {
26
30
  warnings.push('prompt_feature_disabled; nextAction=set features.prompt.enabled=true in .pd/config.yaml');
27
- return { principles, warnings, aborted: true, selfReportEnabled: false, abstractionLayerEnabled };
31
+ return { principles, warnings, aborted: true, selfReportEnabled: false };
28
32
  }
29
33
  // PRI-532: agent self-report instruction rides the directive template when
30
34
  // the flag is on (flag-off keeps the template byte-identical).
@@ -33,12 +37,12 @@ export async function readPromptActivationCandidates(input) {
33
37
  const stateDbPath = path.join(input.workspaceDir, '.pd', 'state.db');
34
38
  if (!fs.existsSync(stateDbPath)) {
35
39
  warnings.push('activation_db_not_found; nextAction=initialize_workspace_runtime_state');
36
- return { principles, warnings, aborted: true, selfReportEnabled, abstractionLayerEnabled };
40
+ return { principles, warnings, aborted: true, selfReportEnabled };
37
41
  }
38
42
  try {
39
43
  connection = new SqliteConnection({ workspaceDir: input.workspaceDir, readonly: true, bootstrapIfMissing: false,
40
44
  // Additional adaptive reads must not hold the host behind SQLite's synchronous busy wait.
41
- ...(input.includeAuthority === true ? { busyTimeoutMs: 0 } : {}),
45
+ ...(input.noBusyWait === true ? { busyTimeoutMs: 0 } : {}),
42
46
  });
43
47
  const activations = filterPromptActivations(await new SqliteActivationStateStore(connection).listPromptActivations());
44
48
  const artifactStore = new SqlitePIArtifactStore(connection);
@@ -89,14 +93,111 @@ export async function readPromptActivationCandidates(input) {
89
93
  finally {
90
94
  connection?.close();
91
95
  }
92
- return { principles, warnings, aborted: false, selfReportEnabled, abstractionLayerEnabled };
96
+ return { principles, warnings, aborted: false, selfReportEnabled };
97
+ }
98
+ /**
99
+ * PRI-1137 final review P1-5: did the AUTHORIZATION FACTS of the adaptive
100
+ * priority target change between the native snapshot (first read) and the
101
+ * authorized snapshot (second read)? The packed directive is annotated from
102
+ * the facts as of packing time, so a drift in `authority` (e.g. owner →
103
+ * system_policy after an approval-state change) or `approvedBy` means the
104
+ * first snapshot's annotation would be a stale authorization claim — the
105
+ * caller must exclude the target rather than inject it. Content drift
106
+ * (text/sha) is checked separately (`target_changed`).
107
+ */
108
+ export function adaptiveTargetAuthorizationChanged(native, authorized) {
109
+ return native.authority !== authorized.authority || native.approvedBy !== authorized.approvedBy;
110
+ }
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 function planSharedDirectivePacking(input) {
121
+ const { scanOrder, budgetChars, selfReportEnabled, continueOnNonFit } = input;
122
+ const blockChars = input.blockCharsByActivationId
123
+ ?? new Map(scanOrder.map((principle) => [
124
+ principle.activationId,
125
+ measureSharedDirectiveBlockChars(principle, { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled }),
126
+ ]));
127
+ // Chars any non-empty render carries (header + footer + note). An empty
128
+ // included set renders '' (the renderer's own empty contract).
129
+ const baseChars = sharedDirectiveBaseChars({ escapeFn: escapeXml, selfReportInstruction: selfReportEnabled });
130
+ const included = [];
131
+ let runningChars = baseChars;
132
+ let truncated = false;
133
+ const dropped = [];
134
+ const oversized = [];
135
+ for (const principle of scanOrder) {
136
+ const marginal = blockChars.get(principle.activationId);
137
+ if (marginal === undefined) {
138
+ // Unknown cost must never silently pass as zero (rc-3): treat as
139
+ // oversized-for-planning and record it.
140
+ if (oversized.length < MAX_SHARED_DIAGNOSTIC_IDS)
141
+ oversized.push(principle.activationId);
142
+ if (!continueOnNonFit)
143
+ break;
144
+ continue;
145
+ }
146
+ if (runningChars + marginal > budgetChars) {
147
+ // Standalone fit = base + own block within budget — the same fact the
148
+ // single-principle render expresses, derived additively.
149
+ if (baseChars + marginal <= budgetChars) {
150
+ truncated = true;
151
+ if (dropped.length < MAX_SHARED_DIAGNOSTIC_IDS)
152
+ dropped.push(principle.activationId);
153
+ }
154
+ else if (oversized.length < MAX_SHARED_DIAGNOSTIC_IDS) {
155
+ oversized.push(principle.activationId);
156
+ }
157
+ if (!continueOnNonFit)
158
+ break;
159
+ continue;
160
+ }
161
+ included.push(principle);
162
+ runningChars += marginal;
163
+ }
164
+ return { included, truncated, dropped, oversized };
165
+ }
166
+ /**
167
+ * PRI-1137: THE shared directive packer. `buildActivePrinciplePromptContext`
168
+ * selects through it, and the console projection reuses it to answer "which
169
+ * activations this route reaches across rounds". One policy implementation —
170
+ * the retired list-route `trimToBudget` arithmetic must not survive as a
171
+ * second forecast authority.
172
+ *
173
+ * PRI-1137 final review P1-2 (CodeRabbit Major): the previous loop re-rendered
174
+ * the ENTIRE growing prefix per candidate — O(N²) render work per pack, and
175
+ * the rotation reachability replay called it once per round key. The render is
176
+ * strictly additive over per-principle directive blocks (see
177
+ * `measureSharedDirectiveBlockChars`), so inclusion is decided by integer
178
+ * arithmetic over per-block costs measured ONCE, and the string is rendered a
179
+ * single time at the end. Output is byte-identical to the retired loop
180
+ * (locked by characterization tests); only the work profile changed.
181
+ */
182
+ export function packSharedDirectives(input) {
183
+ const plan = planSharedDirectivePacking(input);
184
+ const additionalContext = renderPrinciplesToDirectives(plan.included, new Set(plan.included.map((entry) => entry.principleId)), { escapeFn: escapeXml, selfReportInstruction: input.selfReportEnabled });
185
+ return { ...plan, additionalContext };
93
186
  }
94
187
  export async function buildActivePrinciplePromptContext(input) {
95
188
  // One resolution per request (SPEC §6.1): the caller's pre-resolved budget
96
189
  // or the fixed-fallback default — never a per-line constant read.
97
190
  const promptBudget = input.promptBudget ?? resolvePromptBudget();
98
191
  const { budgetChars } = promptBudget;
99
- const { principles, warnings, aborted, selfReportEnabled } = await readPromptActivationCandidates(input);
192
+ // PRI-1137 final review P2 (deliberate): this FIRST read keeps the default
193
+ // busy_timeout (≈5s) instead of noBusyWait. It is the source of the WHOLE
194
+ // injection — failing it on a transient SQLite lock would abort every
195
+ // principle (aborted ⇒ empty context), which is a far worse degradation
196
+ // than the bounded wait. Only the adaptive REVALIDATION read opts into
197
+ // noBusyWait (line ~459): that one is an optional enhancement whose
198
+ // fast-fail falls back to the native baseline, so waiting there would risk
199
+ // the hook timeout for no injection benefit.
200
+ const { principles, warnings, aborted, selfReportEnabled } = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
100
201
  if (aborted) {
101
202
  return {
102
203
  additionalContext: '', principleIds: [], activationIds: [], artifactIds: [], warnings,
@@ -131,52 +232,70 @@ export async function buildActivePrinciplePromptContext(input) {
131
232
  const nativeScanOrder = rotationStartIndex === undefined
132
233
  ? principles
133
234
  : 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
- };
235
+ const pack = (scanOrder) => packSharedDirectives({ scanOrder, budgetChars, selfReportEnabled, continueOnNonFit: selectionPolicy === 'fair_rotation_v1' });
163
236
  const makeResult = (packing, eligiblePrinciples, adaptivePacking) => {
164
237
  const resultWarnings = [...warnings];
165
238
  if (packing.truncated) {
166
239
  resultWarnings.push('prompt_context_truncated: production_prompt_cap; nextAction=reduce_active_prompt_principles');
167
240
  }
168
- const injectedIds = new Set(packing.included.map((principle) => principle.principleId));
241
+ // Evidence arrays are positional tuples (principle, activation, artifact).
242
+ // A principle can have multiple activated artifacts, so deduplicate the
243
+ // candidate objects once and derive every identity array from that same
244
+ // first-selected entry; independently deduplicating only principleIds
245
+ // would shift later activation/artifact associations.
246
+ const seenPrincipleIds = new Set();
247
+ const injectedPrinciples = packing.included.filter((principle) => {
248
+ if (seenPrincipleIds.has(principle.principleId))
249
+ return false;
250
+ seenPrincipleIds.add(principle.principleId);
251
+ return true;
252
+ });
253
+ // PRI-1150: freeze per-principle presence expectations SAME-SOURCE with the
254
+ // additionalContext above — one render pass over the already-included
255
+ // principles, no second read. Each entry is the exact escaped `<directive>`
256
+ // slice this assembly embedded; `bodyComplete` is containment against the
257
+ // assembly, so a truncated directive can never yield a full_hit downstream.
258
+ // Bounded at MAX_SHARED_PRESENCE_EXPECTATIONS with an overflow fact.
259
+ const injectedExpectations = [];
260
+ let injectedExpectationsOverflow = 0;
261
+ for (const principle of injectedPrinciples) {
262
+ if (injectedExpectations.length >= MAX_SHARED_PRESENCE_EXPECTATIONS) {
263
+ injectedExpectationsOverflow += 1;
264
+ continue;
265
+ }
266
+ const rendered = renderPrinciplesToDirectives([principle], new Set([principle.principleId]), { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled });
267
+ const start = rendered.indexOf('<directive ');
268
+ const end = rendered.indexOf('</directive>');
269
+ if (start === -1 || end === -1)
270
+ continue;
271
+ const bodyText = rendered.slice(start, end + '</directive>'.length);
272
+ if (!bodyText)
273
+ continue;
274
+ injectedExpectations.push({
275
+ activationId: principle.activationId,
276
+ bodyText,
277
+ bodyChars: bodyText.length,
278
+ bodyComplete: packing.additionalContext.includes(bodyText),
279
+ });
280
+ }
169
281
  return {
170
282
  additionalContext: packing.additionalContext,
171
- principleIds: [...injectedIds],
172
- activationIds: packing.included.map((principle) => principle.activationId),
173
- artifactIds: packing.included.map((principle) => principle.artifactId),
283
+ principleIds: injectedPrinciples.map((principle) => principle.principleId),
284
+ activationIds: injectedPrinciples.map((principle) => principle.activationId),
285
+ artifactIds: injectedPrinciples.map((principle) => principle.artifactId),
174
286
  warnings: resultWarnings,
175
287
  budget: budgetChars,
176
288
  truncated: packing.truncated,
177
289
  selectionPolicy,
178
290
  eligibleCount: eligiblePrinciples.length,
291
+ ...(injectedExpectations.length > 0 || injectedExpectationsOverflow > 0
292
+ ? {
293
+ injectedExpectations,
294
+ ...(injectedExpectationsOverflow > 0 ? { injectedExpectationsOverflow } : {}),
295
+ }
296
+ : {}),
179
297
  ...(rotationStartIndex !== undefined ? { rotationStartIndex } : {}),
298
+ ...(selectionPolicy === 'fair_rotation_v1' && roundKey !== undefined ? { selectionRoundOrdinal: roundKey } : {}),
180
299
  ...(packing.dropped.length > 0 ? { droppedActivationIds: packing.dropped } : {}),
181
300
  ...(packing.oversized.length > 0 ? { oversizedActivationIds: packing.oversized } : {}),
182
301
  budgetCapacitySource: promptBudget.capacitySource,
@@ -226,13 +345,21 @@ export async function buildActivePrinciplePromptContext(input) {
226
345
  if (principles.filter((principle) => principle.principleId === nativeTarget.principleId).length !== 1) {
227
346
  return { ...nativeResult, adaptivePacking: report('unavailable', 'target_ambiguous') };
228
347
  }
229
- const authorityRead = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
348
+ const authorityRead = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true, noBusyWait: true });
230
349
  const authorizedMatches = authorityRead.principles.filter((principle) => principle.artifactId === priority.artifactId && principle.activationId === priority.activationId);
231
350
  const [authorizedTarget] = authorizedMatches;
232
351
  if (authorityRead.aborted || authorityRead.warnings.length > 0 || authorizedMatches.length !== 1 || !authorizedTarget
233
352
  || authorityRead.principles.filter((principle) => principle.principleId === authorizedTarget.principleId).length !== 1) {
234
353
  return withoutTarget('authority_unavailable');
235
354
  }
355
+ // PRI-1137 final review P1-5: the second read must prove the AUTHORIZATION
356
+ // FACTS unchanged, not merely present. The packed directive carries the
357
+ // first snapshot's authority annotation, so an approval-state change
358
+ // between the two reads (owner → system_policy, or a different approver)
359
+ // must exclude the priority target instead of injecting stale authorization.
360
+ if (adaptiveTargetAuthorizationChanged(nativeTarget, authorizedTarget)) {
361
+ return withoutTarget('target_authority_changed');
362
+ }
236
363
  if (!authorizedTarget.authority
237
364
  || authorizedTarget.principleId !== nativeTarget.principleId
238
365
  || 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 } : {}),
@@ -14,15 +14,37 @@
14
14
  * (HMAC(secret, canonical workspace path); never uploaded). One
15
15
  * workspace succeeding must never suppress another workspace's export.
16
16
  *
17
- * Migration from schema v1: consent, consentVersion, and telemetrySecret are
18
- * preserved; legacy machine-global export bookkeeping (lastSucceededAt,
19
- * retry state, attempt counters) is DISCARDED — it cannot be attributed to a
20
- * workspace, and it is operational state, not a governance fact. Dropping it
21
- * can cause at most one extra same-day snapshot per installation.
17
+ * Single-format contract (PRI-1138, 6th dual-track convergence):
18
+ * - The ONLY writable/persisted format is the current schema version.
19
+ * writeProductTelemetryControlState refuses every state whose
20
+ * schemaVersion is not current, so no code path can persist or
21
+ * regenerate a legacy v1 file.
22
+ * - Legacy v1 files remain readable through migrateLegacyConsentFile — a
23
+ * one-way, read-only migrator (legacy reader / one-way migrator, never a
24
+ * writer). A read parses a v1 file in memory (identity preserved) but
25
+ * NEVER writes; persistence of the migration happens exclusively inside
26
+ * withControlStateLock transactions (PRI-1151): the legacy v1→v2
27
+ * migration write-back, enable/disable/reset, and workspace export
28
+ * bookkeeping merges all serialize on the same cross-process
29
+ * `<state>.state-lock`, so no writer can build its write from a stale
30
+ * read or overwrite a completed authorization change.
31
+ * - Migration from schema v1: consent, consentVersion, and telemetrySecret
32
+ * are preserved verbatim; legacy machine-global export bookkeeping
33
+ * (lastSucceededAt, retry state, attempt counters) is DISCARDED — it
34
+ * cannot be attributed to a workspace, and it is operational state, not a
35
+ * governance fact. Dropping it can cause at most one extra same-day
36
+ * snapshot per eligible workspace on the machine (each workspace re-exports
37
+ * once before its own fresh bookkeeping exists).
22
38
  */
23
39
  export declare const PRODUCT_TELEMETRY_STATE_FILENAME = "product-telemetry.json";
40
+ /** The ONE writable schema version (single-format contract, PRI-1138). */
24
41
  export declare const PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION = "2";
25
- /** v1 files are still read (then migrated in memory and rewritten as v2). */
42
+ /**
43
+ * Legacy schema v1 — LEGACY-READER SEMANTICS ONLY (PRI-1138): this constant
44
+ * exists solely so the one-way migrator can recognize historical files. It
45
+ * is never a writable target; writeProductTelemetryControlState refuses
46
+ * every state whose schemaVersion is not PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION.
47
+ */
26
48
  export declare const PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION = "1";
27
49
  /** Hard bound on tracked workspaces so the file cannot grow unboundedly. */
28
50
  export declare const MAX_WORKSPACE_EXPORT_ENTRIES = 200;
@@ -72,23 +94,99 @@ export type ControlStateWrite = {
72
94
  export declare function defaultProductTelemetryControlState(): ProductTelemetryControlState;
73
95
  export declare function getProductTelemetryStatePath(homeDir: string): string;
74
96
  /**
75
- * Read and validate the control state. A missing file is the normal
76
- * never-configured case (defaults, existed=false). A malformed file is a
77
- * loud failure — silently treating it as "unset" could re-prompt or re-export
78
- * against the user's recorded decision (rc-3/rc-9).
97
+ * Atomic write (temp file + rename) so a crash never truncates the state.
79
98
  *
80
- * v1 files are migrated in memory (export bookkeeping dropped, consent
81
- * identity preserved); the migration is persisted on the next write.
99
+ * Single-format contract (PRI-1138): ONLY the current schema version is
100
+ * writable. This is the structural guarantee that no code path can persist
101
+ * or regenerate a legacy v1 file — a state carrying any other schemaVersion
102
+ * is refused loud and the file on disk is left untouched.
103
+ *
104
+ * Concurrency convention (PRI-1151): production read-modify-write callers
105
+ * must run inside withControlStateLock (tx.write) so their write is built
106
+ * from a read taken under the same cross-process mutex as every other
107
+ * writer; calling this function directly is for lock-held transaction
108
+ * internals and single-writer utilities.
109
+ */
110
+ export declare function writeProductTelemetryControlState(homeDir: string, state: ProductTelemetryControlState): ControlStateWrite;
111
+ /**
112
+ * Lock-held read result: the parsed CURRENT disk state plus the schema
113
+ * version the bytes on disk actually carried (so a transaction can tell a
114
+ * migrated-in-memory v1 apart from a genuine v2 and persist the migration).
115
+ */
116
+ export type LatestControlStateRead = {
117
+ ok: true;
118
+ state: ProductTelemetryControlState;
119
+ existed: boolean;
120
+ diskSchemaVersion: '1' | '2';
121
+ } | {
122
+ ok: false;
123
+ reason: string;
124
+ nextAction: string;
125
+ };
126
+ /**
127
+ * Read and validate the control state — PURE READ, never writes (PRI-1151).
128
+ * A legacy v1 file is parsed in memory (identity preserved, bookkeeping
129
+ * dropped) so callers observe the migrated semantics, but persisting the
130
+ * migration happens exclusively inside withControlStateLock transactions;
131
+ * a read-only caller (status/preview) can therefore never race a concurrent
132
+ * authorization change.
82
133
  */
83
134
  export declare function readProductTelemetryControlState(homeDir: string): ControlStateRead;
135
+ /** Transactional read/write surface handed to withControlStateLock bodies. */
136
+ export interface ControlStateLockTx {
137
+ /**
138
+ * Read the CURRENT disk state inside the lock. No re-acquisition — the
139
+ * caller already holds the lock; nesting withControlStateLock inside a
140
+ * body is a programming error and would deadlock against the bounded
141
+ * wait.
142
+ */
143
+ readLatest(): LatestControlStateRead;
144
+ /** Atomic single-format write inside the lock. */
145
+ write(state: ProductTelemetryControlState): ControlStateWrite;
146
+ }
147
+ /**
148
+ * withControlStateLock — the ONE cross-process transaction entry for the
149
+ * control state (PRI-1151): acquire `<state>.state-lock` → run the body with
150
+ * lock-held readLatest/write primitives → release. Every control-state
151
+ * writer (legacy migration write-back, enable/disable/reset, workspace
152
+ * bookkeeping merge) goes through here, so each write is built from a read
153
+ * taken under the same mutex that serializes every other writer — a stale
154
+ * read can no longer overwrite a completed authorization change (e.g. a
155
+ * concurrent disable).
156
+ *
157
+ * Failure semantics: lock acquisition is bounded and CONTENTION (timeout) is
158
+ * distinguished from a FILESYSTEM failure (e.g. unwritable directory); on
159
+ * either failure nothing was written (no lock-free degradation). A body that
160
+ * runs longer than the lock's stale threshold may find its lock taken over
161
+ * by another process — tx.write then refuses (lock_lost) instead of
162
+ * committing without the mutex. A throwing body releases the lock and
163
+ * returns a structured failure — this function never throws.
164
+ */
165
+ export declare function withControlStateLock<T>(homeDir: string, body: (tx: ControlStateLockTx) => Promise<T> | T, options?: {
166
+ timeoutMs?: number;
167
+ }): Promise<{
168
+ ok: true;
169
+ value: T;
170
+ } | {
171
+ ok: false;
172
+ reason: string;
173
+ nextAction: string;
174
+ }>;
175
+ /**
176
+ * One-way legacy v1→v2 migration as a locked transaction (PRI-1151): read
177
+ * the CURRENT disk state under the lock; if it is still v1, persist the
178
+ * migrated state (identity preserved) through the normal atomic write; if it
179
+ * is already the current format, do nothing (idempotent — no rewrite). A
180
+ * concurrent disable/reset/enable serializes on the same lock, so this can
181
+ * never overwrite a completed authorization change.
182
+ */
183
+ export declare function migrateLegacyControlState(homeDir: string): Promise<ControlStateWrite>;
84
184
  /**
85
185
  * Drop `workspaceExports` entries whose most recent activity (attempt or
86
186
  * success) is older than WORKSPACE_EXPORT_STATE_MAX_AGE_DAYS. Bounded local
87
187
  * operational state only — this is not a workspace history database.
88
188
  */
89
189
  export declare function pruneWorkspaceExports(state: ProductTelemetryControlState, nowMs: number): ProductTelemetryControlState;
90
- /** Atomic write (temp file + rename) so a crash never truncates the state. */
91
- export declare function writeProductTelemetryControlState(homeDir: string, state: ProductTelemetryControlState): ControlStateWrite;
92
190
  /** State after `pd telemetry enable`: explicit granted consent + secret. */
93
191
  export declare function grantedControlState(previous: ProductTelemetryControlState): ProductTelemetryControlState;
94
192
  /**