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,7 +1,7 @@
1
- import { computeFeatureFlagsFromConfig, renderPrinciplesToDirectives, resolvePromptBudget, trimToBudget, } from '@principles/core/runtime';
1
+ import { computeFeatureFlagsFromConfig, measureSharedDirectiveBlockChars, resolvePromptBudget, } from '@principles/core/runtime';
2
2
  import { escapeXml } from '@principles/core/prompt-builder';
3
3
  import { loadPdConfigForPlugin } from './pd-config.js';
4
- import { buildActivePrinciplePromptContext, readPromptActivationCandidates, MAX_SHARED_DIAGNOSTIC_IDS } from './active-principle-prompt.js';
4
+ import { buildActivePrinciplePromptContext, planSharedDirectivePacking, readPromptActivationCandidates, MAX_SHARED_DIAGNOSTIC_IDS, } from './active-principle-prompt.js';
5
5
  import { readWorkspaceHostKindFacts } from './host-liveness-contract.js';
6
6
  /** Single host roster (review P2): every consumer derives from this list, so a
7
7
  * new host cannot fork route-unconfirmed per-host forecasts from the routes. */
@@ -13,22 +13,55 @@ export const PROMPT_INJECTION_TARGET_HOSTS = ['openclaw', 'codex', 'workbuddy'];
13
13
  export function isPromptInjectionTargetHost(kind) {
14
14
  return typeof kind === 'string' && PROMPT_INJECTION_TARGET_HOSTS.includes(kind);
15
15
  }
16
+ /**
17
+ * A host's STATIC rotation capability (final review P1-1.4/P1-1.5): only
18
+ * OpenClaw supplies a trusted round authority (`nextSessionTurnOrdinal` over
19
+ * trajectory.db `user_turns`); Codex/WorkBuddy inject FIFO by their own
20
+ * policy and never fabricate a round key. One mapping, typed by the roster —
21
+ * consumers must not re-derive host capabilities from route names. A bound
22
+ * host always resolves to a definite state (never `unknown`).
23
+ */
24
+ export function hostRotationCapability(hostKind) {
25
+ return hostKind === 'openclaw' ? { state: 'rotates' } : { state: 'does_not_rotate' };
26
+ }
27
+ /**
28
+ * PRI-1137 final review: the rotation truth of the ONE production route.
29
+ * Explicit host binding resolves that host's actual capability; otherwise a
30
+ * workspace with exactly one applicable host resolves to that host's
31
+ * capability, and anything else (no host has ever operated here, several
32
+ * applicable hosts, unreadable host facts) stays `unknown` — aggregate host
33
+ * facts are never flattened into "all hosts are FIFO" (P1-1.6). Route
34
+ * confirmation (`shared_render` for everyone) and host binding are separate
35
+ * facts; this function only answers the binding question.
36
+ */
37
+ export function productionRouteRotationState(input) {
38
+ if (input.targetHost !== undefined) {
39
+ return hostRotationCapability(input.targetHost);
40
+ }
41
+ const facts = readWorkspaceHostKindFacts(input.workspaceDir);
42
+ if (!facts.ok) {
43
+ return { state: 'unknown', reason: 'host_facts_unreadable' };
44
+ }
45
+ const hosts = [...facts.effectiveKinds].filter(isPromptInjectionTargetHost);
46
+ const [host] = hosts;
47
+ if (hosts.length === 1 && host !== undefined) {
48
+ return hostRotationCapability(host);
49
+ }
50
+ return { state: 'unknown', reason: 'no_bound_host' };
51
+ }
16
52
  export const PROMPT_INJECTION_UNIT = 'utf16_code_units';
17
53
  /**
18
- * THE one route formula (P4): Codex always injects through the shared route
19
- * (codex-adapter has no flag branch); so does WorkBuddy (workbuddy-adapter
20
- * renders through the shared runtime unconditionally — it has no legacy
21
- * route); OpenClaw routes by its `abstraction_layer_v1` gate. Every consumer
22
- * that needs "which route would host X take" must call this — never re-type
23
- * the ternary.
54
+ * THE one route formula (P4 / PRI-1137): every standard host injects through
55
+ * the shared route. The OpenClaw legacy plugin-local route was deleted, so
56
+ * `legacy_trim` is retained only as a historical wire literal — production
57
+ * never returns it. Every consumer that needs "which route would host X take"
58
+ * must call this; never re-type the mapping.
24
59
  */
25
- export function promptRouteForHost(hostKind, flagEnabled) {
26
- if (hostKind === 'codex' || hostKind === 'workbuddy')
27
- return 'shared_render';
28
- return flagEnabled ? 'shared_render' : 'legacy_trim';
60
+ export function promptRouteForHost(_hostKind) {
61
+ return 'shared_render';
29
62
  }
30
- function standardHostRoutes(flagEnabled) {
31
- return PROMPT_INJECTION_TARGET_HOSTS.map((hostKind) => ({ hostKind, route: promptRouteForHost(hostKind, flagEnabled) }));
63
+ function standardHostRoutes() {
64
+ return PROMPT_INJECTION_TARGET_HOSTS.map((hostKind) => ({ hostKind, route: promptRouteForHost(hostKind) }));
32
65
  }
33
66
  /**
34
67
  * Resolve the effective route for this workspace. Pure read of existing
@@ -37,31 +70,28 @@ function standardHostRoutes(flagEnabled) {
37
70
  export function resolvePromptInjectionRouteDecision(input) {
38
71
  const config = loadPdConfigForPlugin(input.workspaceDir);
39
72
  const { flags } = computeFeatureFlagsFromConfig(config.effective);
40
- const flagEnabled = flags.abstraction_layer_v1?.enabled === true;
41
73
  const facts = readWorkspaceHostKindFacts(input.workspaceDir);
42
74
  if (!config.ok) {
43
75
  const [error] = config.errors;
44
76
  return {
45
77
  status: 'unconfirmed',
46
- flagEnabled,
47
78
  declaredHostKinds: facts.ok ? facts.declaredKinds : [],
48
79
  effectiveHostKinds: facts.ok ? facts.effectiveKinds : [],
49
80
  ...(!facts.ok ? { hostFactsStatus: 'unreadable' } : {}),
50
81
  unconfirmedReason: `config_unreadable: ${error?.reason ?? 'workspace config is invalid'}`,
51
82
  nextAction: error?.nextAction ?? 'repair .pd/config.yaml before measuring prompt injection',
52
- perHost: standardHostRoutes(flagEnabled),
83
+ perHost: standardHostRoutes(),
53
84
  };
54
85
  }
55
86
  if (!flags.prompt?.enabled) {
56
87
  return {
57
88
  status: 'unconfirmed',
58
- flagEnabled,
59
89
  declaredHostKinds: facts.ok ? facts.declaredKinds : [],
60
90
  effectiveHostKinds: facts.ok ? facts.effectiveKinds : [],
61
91
  ...(!facts.ok ? { hostFactsStatus: 'unreadable' } : {}),
62
92
  unconfirmedReason: 'prompt_feature_disabled: the prompt injection surface is off',
63
93
  nextAction: 'set features.prompt.enabled=true in .pd/config.yaml',
64
- perHost: standardHostRoutes(flagEnabled),
94
+ perHost: standardHostRoutes(),
65
95
  };
66
96
  }
67
97
  // Explicit request-level host is sufficient to bind the route even when
@@ -71,9 +101,8 @@ export function resolvePromptInjectionRouteDecision(input) {
71
101
  return {
72
102
  status: 'confirmed',
73
103
  hostKind: input.targetHost,
74
- route: promptRouteForHost(input.targetHost, flagEnabled),
104
+ route: promptRouteForHost(input.targetHost),
75
105
  basis: 'explicit_target',
76
- flagEnabled,
77
106
  declaredHostKinds: facts.declaredKinds,
78
107
  effectiveHostKinds: facts.ok ? facts.effectiveKinds : [],
79
108
  ...(!facts.ok ? { hostFactsStatus: 'unreadable' } : {}),
@@ -82,13 +111,12 @@ export function resolvePromptInjectionRouteDecision(input) {
82
111
  if (!facts.ok) {
83
112
  return {
84
113
  status: 'unconfirmed',
85
- flagEnabled,
86
114
  declaredHostKinds: facts.declaredKinds,
87
115
  effectiveHostKinds: [],
88
116
  hostFactsStatus: 'unreadable',
89
117
  unconfirmedReason: `host_facts_unreadable: ${facts.detail}`,
90
118
  nextAction: facts.nextAction,
91
- perHost: standardHostRoutes(flagEnabled),
119
+ perHost: standardHostRoutes(),
92
120
  };
93
121
  }
94
122
  const knownKinds = facts.effectiveKinds.filter(isPromptInjectionTargetHost);
@@ -96,37 +124,24 @@ export function resolvePromptInjectionRouteDecision(input) {
96
124
  if (unknownKinds.length > 0) {
97
125
  return {
98
126
  status: 'unconfirmed',
99
- flagEnabled,
100
127
  declaredHostKinds: facts.declaredKinds,
101
128
  effectiveHostKinds: facts.effectiveKinds,
102
129
  unconfirmedReason: `unknown_host_kind_declared: ${unknownKinds.join(', ')} has no known prompt-injection route`,
103
130
  nextAction: 'pass an explicit target host (openclaw|codex|workbuddy) for this request, or remove the unknown host declaration',
104
- perHost: standardHostRoutes(flagEnabled),
131
+ perHost: standardHostRoutes(),
105
132
  };
106
133
  }
107
134
  if (knownKinds.length === 0) {
108
- // No host ever operated this workspace. With the flag ON both standard
109
- // hosts take the shared route, so the route IS confirmed; with the flag
110
- // OFF they genuinely differ (OpenClaw list vs Codex shared) and there is
111
- // no fact to pick one with — report unconfirmed instead of guessing.
112
- if (flagEnabled) {
113
- return {
114
- status: 'confirmed',
115
- route: 'shared_render',
116
- basis: 'flag_shared_all_hosts',
117
- flagEnabled,
118
- declaredHostKinds: facts.declaredKinds,
119
- effectiveHostKinds: facts.effectiveKinds,
120
- };
121
- }
135
+ // No host ever operated this workspace. Every standard host takes the
136
+ // shared route, so the ROUTE is confirmed even though no host is bound.
137
+ // Hosts stay unbound (`hostKind` absent) — attribution is unknown, not
138
+ // guessed.
122
139
  return {
123
- status: 'unconfirmed',
124
- flagEnabled,
140
+ status: 'confirmed',
141
+ route: 'shared_render',
142
+ basis: 'single_route_all_hosts',
125
143
  declaredHostKinds: facts.declaredKinds,
126
144
  effectiveHostKinds: facts.effectiveKinds,
127
- unconfirmedReason: 'no_host_facts_and_flag_off: no host declaration or host evidence exists, and the applicable hosts would take different routes',
128
- nextAction: 'pass an explicit target host (openclaw|codex|workbuddy), or let a host run once in this workspace so it persists its declaration',
129
- perHost: standardHostRoutes(flagEnabled),
130
145
  };
131
146
  }
132
147
  if (knownKinds.length === 1) {
@@ -135,54 +150,59 @@ export function resolvePromptInjectionRouteDecision(input) {
135
150
  return {
136
151
  status: 'confirmed',
137
152
  hostKind: maybeHostKind,
138
- route: promptRouteForHost(maybeHostKind, flagEnabled),
153
+ route: promptRouteForHost(maybeHostKind),
139
154
  basis: 'workspace_host_facts',
140
- flagEnabled,
141
155
  declaredHostKinds: facts.declaredKinds,
142
156
  effectiveHostKinds: facts.effectiveKinds,
143
157
  };
144
158
  }
145
159
  }
146
- // Both openclaw and codex are applicable.
147
- if (flagEnabled) {
148
- return {
149
- status: 'confirmed',
150
- route: 'shared_render',
151
- basis: 'flag_shared_all_hosts',
152
- flagEnabled,
153
- declaredHostKinds: facts.declaredKinds,
154
- effectiveHostKinds: facts.effectiveKinds,
155
- };
156
- }
160
+ // Several applicable hosts — the route is still one: shared_render.
157
161
  return {
158
- status: 'unconfirmed',
159
- flagEnabled,
162
+ status: 'confirmed',
163
+ route: 'shared_render',
164
+ basis: 'single_route_all_hosts',
160
165
  declaredHostKinds: facts.declaredKinds,
161
166
  effectiveHostKinds: facts.effectiveKinds,
162
- unconfirmedReason: 'multi_host_routes_differ: openclaw would take the legacy list route while codex/workbuddy would take the shared route under the current flag-off config',
163
- nextAction: 'pass an explicit target host (openclaw|codex|workbuddy) for this request, or enable abstraction_layer_v1 so all hosts share one route',
164
- perHost: standardHostRoutes(flagEnabled),
165
167
  };
166
168
  }
167
169
  /**
168
- * PR-1894: which activations a fair-rotation selector injects across the
169
- * whole ring. The plugin's round key advances by one per recorded user turn
170
- * within a continuously advancing session, so N consecutive turns cover all
171
- * N ring positions: an activation absent from the current window but present
172
- * in ANY round is reachable, not starved.
170
+ * PR-1894 / PRI-1137: which activations the production fair rotation injects
171
+ * across the whole ring. The plugin's round key advances by one per recorded
172
+ * user turn within a continuously advancing session, so N consecutive turns
173
+ * cover all N ring positions: an activation absent from the current window but
174
+ * present in ANY round is reachable, not starved.
175
+ *
176
+ * PRI-1137: reachability is replayed with the SHARED packer the production
177
+ * route actually runs (`packSharedDirectives`), not the retired list-route
178
+ * `trimToBudget` arithmetic — a forecast may not measure a deleted path.
173
179
  *
174
- * Kept here (not in the console) so the production selector's own arithmetic
175
- * stays the single authority for what "reachable" means.
180
+ * PRI-1137 final review P1-2 (CodeRabbit Major): the pack decision runs per
181
+ * round key via the string-free `planSharedDirectivePacking` over block costs
182
+ * measured ONCE — O(N²) integer adds total. The retired shape re-ran the full
183
+ * `packSharedDirectives` render per round (O(N³) cumulative string work),
184
+ * which made the console capacity read slower as the activation count grew.
176
185
  */
177
- function collectReachableActivationIds(principles, budget) {
186
+ function collectReachableActivationIds(principles, budget, selfReportEnabled) {
187
+ // One measurement per principle, shared by every simulated round.
188
+ const blockChars = new Map(principles.map((principle) => [
189
+ principle.activationId,
190
+ measureSharedDirectiveBlockChars(principle, { escapeFn: escapeXml, selfReportInstruction: selfReportEnabled }),
191
+ ]));
178
192
  const reachable = new Set();
179
- for (let roundKey = 0; roundKey < principles.length; roundKey += 1) {
180
- const result = trimToBudget(principles, budget, escapeXml, roundKey);
181
- for (const principleId of result.injectedIds) {
182
- const match = principles.find((p) => p.principleId === principleId);
183
- if (match)
184
- reachable.add(match.activationId);
185
- }
193
+ const n = principles.length;
194
+ for (let roundKey = 0; roundKey < n; roundKey += 1) {
195
+ const rotationStartIndex = ((roundKey % n) + n) % n;
196
+ const scanOrder = principles.slice(rotationStartIndex).concat(principles.slice(0, rotationStartIndex));
197
+ const { included } = planSharedDirectivePacking({
198
+ scanOrder,
199
+ budgetChars: budget,
200
+ selfReportEnabled,
201
+ continueOnNonFit: true,
202
+ blockCharsByActivationId: blockChars,
203
+ });
204
+ for (const principle of included)
205
+ reachable.add(principle.activationId);
186
206
  }
187
207
  return [...reachable];
188
208
  }
@@ -190,142 +210,79 @@ function isDiagnosticCapHit(ids) {
190
210
  return ids.length >= MAX_SHARED_DIAGNOSTIC_IDS;
191
211
  }
192
212
  /**
193
- * PR #1844 follow-up: forecast the prompt-injection budget from the SAME
194
- * projection the agent injection itself uses:
213
+ * PR #1844 follow-up / PRI-1137: forecast the prompt-injection budget from the
214
+ * SAME projection the agent injection itself uses — ONE route, no legacy path:
215
+ * `buildActivePrinciplePromptContext`, which IS the production shared path's
216
+ * projection source for every standard host.
195
217
  *
196
- * - legacy route: activation candidates from `readPromptActivationCandidates`
197
- * (same FIFO query + artifact resolve as the plugin's list path) trimmed by
198
- * the REAL `trimToBudget` — identical input × ordering × trim logic as
199
- * `openclaw-plugin/src/hooks/prompt.ts`;
200
- * - shared route: delegate to `buildActivePrinciplePromptContext`, which IS
201
- * the production shared path's projection source (Codex always; OpenClaw
202
- * when its `abstraction_layer_v1` gate is on).
218
+ * `targetHost` is host attribution only. It narrows which host's round
219
+ * authority the forecast may assume (see `productionRouteRotationState`); it
220
+ * never selects a different injection route.
203
221
  *
204
- * Route selection here is EXPLICIT: `targetHost: 'codex'` forces the shared
205
- * route (production truth for Codex), `targetHost: 'openclaw'` follows the
206
- * workspace flag, and no target follows the flag (the historical behavior —
207
- * callers that lack host context should prefer
208
- * `resolveLivePromptInjectionProjection`, which binds the route to real host
209
- * facts and refuses to guess).
210
- *
211
- * PR-1894 — round-key alignment. The plugin derives its fair-rotation round
212
- * key from the CURRENT session's turn ordinal (`nextSessionTurnOrdinal`),
213
- * which the console has no access to. Passing no key therefore does NOT make
214
- * the forecast "more conservative": it selects a DIFFERENT policy
215
- * (`legacy_fifo_prefix_v1`) than the one production runs. The console must
216
- * either supply the round key or report the policy honestly, so this
217
- * function takes the key as an explicit input and exposes
218
- * `selectionPolicy` on the result.
222
+ * PR-1894 — round-key alignment. Production derives its fair-rotation round
223
+ * key from the CURRENT session's turn ordinal. The console has no access to
224
+ * it, so passing no key selects `legacy_fifo_prefix_v1` for THIS forecast while
225
+ * production runs `fair_rotation_v1` on OpenClaw. The result therefore exposes
226
+ * both `selectionPolicy` (what this projection ran) and `productionRotation`
227
+ * (what the real injection will do) — never a single blended claim.
219
228
  */
220
229
  export async function buildLivePromptInjectionProjection(input) {
221
230
  const promptBudget = input.promptBudget ?? resolvePromptBudget();
222
- const flagEnabled = computeFeatureFlagsFromConfig(loadPdConfigForPlugin(input.workspaceDir).effective).flags.abstraction_layer_v1?.enabled === true;
223
- // Route face follows THE one route formula (review P2-2: a re-typed
224
- // codex-only ternary forecast WorkBuddy as legacy_trim while its adapter
225
- // renders shared unconditionally). No explicit target (console callers)
226
- // keeps the flag-gated workspace default.
227
- const sharedRoute = input.targetHost === undefined
228
- ? flagEnabled
229
- : promptRouteForHost(input.targetHost, flagEnabled) === 'shared_render';
230
- if (sharedRoute) {
231
- const context = await buildActivePrinciplePromptContext({ ...input, promptBudget });
232
- const oversized = context.oversizedActivationIds ?? [];
233
- const dropped = context.droppedActivationIds ?? [];
234
- return {
235
- route: 'shared_render',
236
- budget: context.budget,
237
- usedChars: context.additionalContext.length,
238
- truncated: context.truncated,
239
- injectedPrincipleIds: context.principleIds,
240
- injectedActivationIds: context.activationIds,
241
- warnings: context.warnings,
242
- // The shared production path deliberately passes no round key
243
- // (host-runtime/src/index.ts), so this route genuinely does not rotate
244
- // and claims nothing about eventual reachability.
245
- selectionPolicy: context.selectionPolicy ?? 'legacy_fifo_prefix_v1',
246
- eventuallyInjectedActivationIds: [],
247
- eligibleCount: context.eligibleCount ?? 0,
248
- productionRotates: false,
249
- unit: PROMPT_INJECTION_UNIT,
250
- budgetScope: 'full_directive_context',
251
- oversizedActivationIds: oversized,
252
- droppedActivationIds: dropped,
253
- oversizedDiagnosticTruncated: isDiagnosticCapHit(oversized),
254
- droppedDiagnosticTruncated: isDiagnosticCapHit(dropped),
255
- budgetCapacitySource: context.budgetCapacitySource,
256
- budgetCapacityStatus: context.budgetCapacityStatus,
257
- budgetContextWindowTokens: context.budgetContextWindowTokens,
258
- budgetPolicyVersion: context.budgetPolicyVersion,
259
- ...(context.budgetFallbackReason !== undefined ? { budgetFallbackReason: context.budgetFallbackReason } : {}),
260
- ...(context.budgetFallbackDetail !== undefined ? { budgetFallbackDetail: context.budgetFallbackDetail } : {}),
261
- };
262
- }
263
- const candidates = await readPromptActivationCandidates(input);
264
- const { principles, warnings } = candidates;
265
- if (candidates.aborted || principles.length === 0) {
266
- return {
267
- route: 'legacy_trim',
268
- budget: promptBudget.budgetChars,
269
- usedChars: 0,
270
- truncated: false,
271
- injectedPrincipleIds: [],
272
- injectedActivationIds: [],
273
- warnings,
274
- selectionPolicy: 'legacy_fifo_prefix_v1',
275
- eventuallyInjectedActivationIds: [],
276
- eligibleCount: 0,
277
- productionRotates: false,
278
- unit: PROMPT_INJECTION_UNIT,
279
- budgetScope: 'selected_lines',
280
- oversizedActivationIds: [],
281
- droppedActivationIds: [],
282
- oversizedDiagnosticTruncated: false,
283
- droppedDiagnosticTruncated: false,
284
- budgetCapacitySource: promptBudget.capacitySource,
285
- budgetCapacityStatus: promptBudget.capacityStatus,
286
- budgetContextWindowTokens: promptBudget.contextWindowTokens,
287
- budgetPolicyVersion: promptBudget.policyVersion,
288
- ...(promptBudget.fallbackReason !== undefined ? { budgetFallbackReason: promptBudget.fallbackReason } : {}),
289
- ...(promptBudget.fallbackDetail !== undefined ? { budgetFallbackDetail: promptBudget.fallbackDetail } : {}),
290
- };
231
+ // PRI-1137: ONE production route for every host. The retired plugin-local
232
+ // `legacy_trim` projection is gone, so the forecast can no longer describe
233
+ // a path production does not run.
234
+ const rotation = productionRouteRotationState(input);
235
+ // PRI-1137 final review P2: a round key is only meaningful on a host that
236
+ // OWNS a round authority. A caller-supplied key against an explicitly bound
237
+ // FIFO host (codex/workbuddy) would forecast `fair_rotation_v1` on a host
238
+ // whose real selection is FIFO — clamp it to `undefined` so the forecast
239
+ // can never diverge from that host's production policy. An UNBOUND caller
240
+ // (no targetHost) keeps its key: OpenClaw is the only key-owning host.
241
+ const roundKeyUsable = input.targetHost === undefined
242
+ || hostRotationCapability(input.targetHost).state === 'rotates';
243
+ const context = await buildActivePrinciplePromptContext({
244
+ ...input,
245
+ promptBudget,
246
+ ...(roundKeyUsable ? {} : { roundKey: undefined }),
247
+ });
248
+ const oversized = context.oversizedActivationIds ?? [];
249
+ const dropped = context.droppedActivationIds ?? [];
250
+ // Reachability is a property of the PRODUCTION rotation, not of this
251
+ // forecast (a console holds no session round key). It is computed only when
252
+ // the production host genuinely rotates, from the same candidate set. An
253
+ // `unknown` rotation (no bound host) computes nothing — an unattributable
254
+ // route cannot claim any reachability ring either.
255
+ let eventuallyInjectedActivationIds = [];
256
+ if (rotation.state === 'rotates') {
257
+ const candidates = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
258
+ if (!candidates.aborted) {
259
+ eventuallyInjectedActivationIds = collectReachableActivationIds(candidates.principles, context.budget, candidates.selfReportEnabled);
260
+ }
291
261
  }
292
- // PR-1894: pass the caller's round key so the forecast runs the SAME
293
- // packing policy production runs this turn.
294
- const trimmed = trimToBudget(principles, promptBudget.budgetChars, escapeXml, input.roundKey);
295
- const injected = principles.filter((p) => trimmed.injectedIds.has(p.principleId));
296
- // PR-1894: the legacy_trim route IS the OpenClaw plugin-local route, which
297
- // rotates on every recorded user turn (PRI-904). Reachability is therefore
298
- // computed under fair rotation regardless of whether THIS forecast holds a
299
- // round key — a console without a session key must still be able to tell
300
- // "queued behind rotation" apart from "structurally starved", otherwise it
301
- // keeps telling the Owner to deactivate healthy principles.
302
- const eventuallyInjectedActivationIds = collectReachableActivationIds(principles, promptBudget.budgetChars);
303
- const fullRenderChars = renderPrinciplesToDirectives(injected, trimmed.injectedIds, { escapeFn: escapeXml, selfReportInstruction: candidates.selfReportEnabled }).length;
304
262
  return {
305
- route: 'legacy_trim',
306
- budget: promptBudget.budgetChars,
307
- usedChars: trimmed.lines.join('\n').length,
308
- truncated: trimmed.truncated,
309
- injectedPrincipleIds: [...trimmed.injectedIds],
310
- injectedActivationIds: injected.map((p) => p.activationId),
311
- warnings,
312
- selectionPolicy: trimmed.selectionPolicy,
263
+ route: 'shared_render',
264
+ budget: context.budget,
265
+ usedChars: context.additionalContext.length,
266
+ truncated: context.truncated,
267
+ injectedPrincipleIds: context.principleIds,
268
+ injectedActivationIds: context.activationIds,
269
+ warnings: context.warnings,
270
+ selectionPolicy: context.selectionPolicy ?? 'legacy_fifo_prefix_v1',
313
271
  eventuallyInjectedActivationIds,
314
- eligibleCount: trimmed.eligibleCount,
315
- productionRotates: true,
272
+ eligibleCount: context.eligibleCount ?? 0,
273
+ productionRotation: rotation,
316
274
  unit: PROMPT_INJECTION_UNIT,
317
- budgetScope: 'selected_lines',
318
- oversizedActivationIds: trimmed.oversizedActivationIds,
319
- droppedActivationIds: trimmed.droppedActivationIds,
320
- oversizedDiagnosticTruncated: isDiagnosticCapHit(trimmed.oversizedActivationIds),
321
- droppedDiagnosticTruncated: isDiagnosticCapHit(trimmed.droppedActivationIds),
322
- ...(injected.length > 0 ? { fullRenderChars } : {}),
323
- budgetCapacitySource: promptBudget.capacitySource,
324
- budgetCapacityStatus: promptBudget.capacityStatus,
325
- budgetContextWindowTokens: promptBudget.contextWindowTokens,
326
- budgetPolicyVersion: promptBudget.policyVersion,
327
- ...(promptBudget.fallbackReason !== undefined ? { budgetFallbackReason: promptBudget.fallbackReason } : {}),
328
- ...(promptBudget.fallbackDetail !== undefined ? { budgetFallbackDetail: promptBudget.fallbackDetail } : {}),
275
+ budgetScope: 'full_directive_context',
276
+ oversizedActivationIds: oversized,
277
+ droppedActivationIds: dropped,
278
+ oversizedDiagnosticTruncated: isDiagnosticCapHit(oversized),
279
+ droppedDiagnosticTruncated: isDiagnosticCapHit(dropped),
280
+ budgetCapacitySource: context.budgetCapacitySource,
281
+ budgetCapacityStatus: context.budgetCapacityStatus,
282
+ budgetContextWindowTokens: context.budgetContextWindowTokens,
283
+ budgetPolicyVersion: context.budgetPolicyVersion,
284
+ ...(context.budgetFallbackReason !== undefined ? { budgetFallbackReason: context.budgetFallbackReason } : {}),
285
+ ...(context.budgetFallbackDetail !== undefined ? { budgetFallbackDetail: context.budgetFallbackDetail } : {}),
329
286
  };
330
287
  }
331
288
  export async function resolveLivePromptInjectionProjection(input) {
@@ -333,19 +290,40 @@ export async function resolveLivePromptInjectionProjection(input) {
333
290
  const decision = resolvePromptInjectionRouteDecision(projectionInput);
334
291
  if (decision.status === 'confirmed') {
335
292
  // PRI-1017: the route can be confirmed by WORKSPACE FACTS without any
336
- // request-level targetHost (a single-host workspace). The caller then has
337
- // no `promptBudget`, but it does have that host's own observation in the
338
- // per-host map — use it. A flag-shared route with no hostKind stays on
339
- // the honest fallback: no host was identified, so no host's window may
340
- // be borrowed.
341
- const decidedBudget = promptBudget
342
- ?? (decision.hostKind !== undefined ? perHostPromptBudget?.[decision.hostKind] : undefined);
293
+ // request-level targetHost. When ONE host is bound, that host's own
294
+ // observation is used. When NO host is bound, the headline stays a
295
+ // REFERENCE view: it may borrow the first standard host's budget BASIS so
296
+ // the numbers are real, but it must NOT borrow that host's rotation
297
+ // authority — `targetHost` stays undefined, so an unbound workspace never
298
+ // claims fair rotation on behalf of a host it has not identified.
299
+ const referenceHost = decision.hostKind ?? PROMPT_INJECTION_TARGET_HOSTS[0] ?? 'openclaw';
300
+ const decidedBudget = promptBudget ?? perHostPromptBudget?.[referenceHost];
343
301
  const projection = await buildLivePromptInjectionProjection({
344
302
  ...projectionInput,
345
303
  targetHost: decision.hostKind,
346
304
  ...(decidedBudget !== undefined ? { promptBudget: decidedBudget } : {}),
347
305
  });
348
- return { status: 'confirmed', decision, projection };
306
+ if (decision.hostKind !== undefined) {
307
+ return { status: 'confirmed', decision, projection };
308
+ }
309
+ // PRI-1137: no single host is bound (single-route workspace). The route is
310
+ // known, but each standard host's BUDGET basis is still its own fact —
311
+ // keep host attribution without letting the headline claim one host's
312
+ // rotation authority. Unconfirmed stays reserved for genuinely unreadable
313
+ // inputs.
314
+ const perHost = [];
315
+ for (const hostKind of PROMPT_INJECTION_TARGET_HOSTS) {
316
+ const hostBudget = perHostPromptBudget?.[hostKind];
317
+ perHost.push({
318
+ hostKind,
319
+ projection: await buildLivePromptInjectionProjection({
320
+ ...projectionInput,
321
+ targetHost: hostKind,
322
+ ...(hostBudget !== undefined ? { promptBudget: hostBudget } : {}),
323
+ }),
324
+ });
325
+ }
326
+ return { status: 'confirmed', decision, projection, perHost };
349
327
  }
350
328
  const hosts = decision.perHost?.map((entry) => entry.hostKind) ?? [...PROMPT_INJECTION_TARGET_HOSTS];
351
329
  const perHost = [];
@@ -3,7 +3,8 @@ import path from 'node:path';
3
3
  import { PROMPT_BUDGET_MAX_CHARS, PROMPT_BUDGET_MIN_CHARS, SqliteActivationStateStore, SqliteConnection, SqlitePIArtifactStore, classifySingleItemBudgetTier, computeFeatureFlagsFromConfig, filterPromptActivations, resolvePrincipleFromArtifact, } from '@principles/core/runtime';
4
4
  import { loadPdConfigForPlugin } from './pd-config.js';
5
5
  import { computePromptSingleItemFit } from './prompt-activation-deliverability.js';
6
- import { PROMPT_INJECTION_TARGET_HOSTS, buildLivePromptInjectionProjection, promptRouteForHost, resolvePromptInjectionRouteDecision, } from './prompt-injection-projection.js';
6
+ import { readPromptActivationAuthority } from './prompt-activation-authority.js';
7
+ import { PROMPT_INJECTION_TARGET_HOSTS, buildLivePromptInjectionProjection, resolvePromptInjectionRouteDecision, } from './prompt-injection-projection.js';
7
8
  export async function readPromptActivationInjectionStatuses(input) {
8
9
  const config = loadPdConfigForPlugin(input.workspaceDir);
9
10
  const warnings = [];
@@ -60,10 +61,21 @@ export async function readPromptActivationInjectionStatuses(input) {
60
61
  rows.push({ activationId: activation.activationId, failure: resolved.warning });
61
62
  continue;
62
63
  }
64
+ // PRI-1137: cost is measured exactly as the ONE shared prompt renders it,
65
+ // so an approval row must contribute its `authority` attribute here too.
66
+ // Unknown authority stays unannotated (never inferred).
67
+ let authority;
68
+ try {
69
+ ({ authority } = readPromptActivationAuthority(connection, artifact.artifactId, 'prompt'));
70
+ }
71
+ catch {
72
+ authority = undefined;
73
+ }
63
74
  rows.push({
64
75
  activationId: activation.activationId,
65
76
  principleId: resolved.principle.principleId,
66
77
  text: resolved.principle.text,
78
+ ...(authority !== undefined ? { authority } : {}),
67
79
  });
68
80
  }
69
81
  }
@@ -85,10 +97,8 @@ export async function readPromptActivationInjectionStatuses(input) {
85
97
  return { activationId: row.activationId, status: 'resolution_failed', reason: row.failure };
86
98
  }
87
99
  const perHostFits = PROMPT_INJECTION_TARGET_HOSTS.map((hostKind) => {
88
- const hostRoute = promptRouteForHost(hostKind, route.flagEnabled);
89
100
  const { costChars } = computePromptSingleItemFit({
90
- principle: { principleId: row.principleId, text: row.text, artifactId: '', activationId: row.activationId },
91
- route: hostRoute,
101
+ principle: { principleId: row.principleId, text: row.text, artifactId: '', activationId: row.activationId, ...(row.authority !== undefined ? { authority: row.authority } : {}) },
92
102
  selfReportEnabled,
93
103
  });
94
104
  return { hostKind, tierFit: classifySingleItemBudgetTier(costChars) };
@@ -116,14 +126,13 @@ export async function readPromptActivationInjectionStatuses(input) {
116
126
  return { activationId: row.activationId, status: 'resolution_failed', reason: row.failure };
117
127
  }
118
128
  const { fits, costChars } = computePromptSingleItemFit({
119
- principle: { principleId: row.principleId, text: row.text, artifactId: '', activationId: row.activationId },
120
- route: projection.route,
129
+ principle: { principleId: row.principleId, text: row.text, artifactId: '', activationId: row.activationId, ...(row.authority !== undefined ? { authority: row.authority } : {}) },
121
130
  selfReportEnabled,
122
131
  budget: projection.budget,
123
132
  });
124
133
  const inCurrentWindow = projection.injectedActivationIds.includes(row.activationId);
125
134
  const budgetScope = projection.budgetScope;
126
- const serialization = projection.route === 'shared_render' ? 'full directive render' : 'list entry';
135
+ const serialization = 'full directive render';
127
136
  // Tier verdict FIRST (SPEC §6.3): the projection budget on this surface
128
137
  // is the fixed fallback (2000) unless the caller passed a runtime budget
129
138
  // OBSERVATION (PRI-1017) — and even then an entry in (MIN, fallback]
@@ -102,7 +102,14 @@ export async function runStage2CorrectionCycle(input) {
102
102
  skipped += 1;
103
103
  continue;
104
104
  }
105
- const timeoutMs = Math.max(1, Math.min(classificationTimeoutMs, remaining));
105
+ // AbortSignal.timeout (pi-ai-runtime-adapter startRun) rejects
106
+ // fractional delays with ERR_OUT_OF_RANGE, and `remaining` is a
107
+ // performance.now() float — under the default 60s budget it is
108
+ // virtually always fractional, which made every classification fail
109
+ // before any network I/O (PRI-1147 real-LLM BDD, ERR-PRI-1147-D1).
110
+ // Clamp to whole milliseconds so the remaining budget reaches the
111
+ // adapter request itself instead of throwing.
112
+ const timeoutMs = Math.max(1, Math.floor(Math.min(classificationTimeoutMs, remaining)));
106
113
  // The remaining budget goes INTO the adapter request as well as the
107
114
  // outer race (v0.3.1 §2.2); an outer timeout does not cancel a
108
115
  // provider request that the adapter does not support cancelling.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "2.2.3",
3
+ "version": "3.0.2",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",