@principles/host-runtime 2.2.3 → 3.0.1

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.
@@ -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
  }
@@ -10,6 +10,53 @@ export declare const PROMPT_INJECTION_TARGET_HOSTS: readonly PromptInjectionTarg
10
10
  * (review R1: each re-typed list forked the roster and dropped WorkBuddy). */
11
11
  export declare function isPromptInjectionTargetHost(kind: unknown): kind is PromptInjectionTargetHost;
12
12
  export type PromptInjectionRouteName = 'legacy_trim' | 'shared_render';
13
+ /**
14
+ * PRI-1137 final review (P1-1): rotation semantics of the production route as
15
+ * a THREE-STATE fact, never a boolean. A boolean conflates two different
16
+ * answers — "the bound host cannot rotate" (a real FIFO statement about a
17
+ * known host) and "no single host is bound, so rotation cannot be attributed"
18
+ * (an unknown). Downstream copy that reads the second as the first tells an
19
+ * OpenClaw Owner their principle is permanently FIFO-queued when it is not.
20
+ *
21
+ * This is the STATIC host capability. Whether a real OpenClaw round actually
22
+ * rotated is a runtime fact the plugin owns: a missing sessionId, a failed
23
+ * `user_turns` write, or an unreadable ordinal degrade that round to
24
+ * `legacy_fifo_prefix_v1` (existing FIFO fallback) — never fabricated here.
25
+ */
26
+ export type PromptProductionRotationState = {
27
+ readonly state: 'rotates';
28
+ } | {
29
+ readonly state: 'does_not_rotate';
30
+ } | {
31
+ readonly state: 'unknown';
32
+ /** Bounded reason rotation cannot be attributed (rc-3: fail loud, no silent guess). */
33
+ readonly reason: 'no_bound_host' | 'host_facts_unreadable';
34
+ };
35
+ /**
36
+ * A host's STATIC rotation capability (final review P1-1.4/P1-1.5): only
37
+ * OpenClaw supplies a trusted round authority (`nextSessionTurnOrdinal` over
38
+ * trajectory.db `user_turns`); Codex/WorkBuddy inject FIFO by their own
39
+ * policy and never fabricate a round key. One mapping, typed by the roster —
40
+ * consumers must not re-derive host capabilities from route names. A bound
41
+ * host always resolves to a definite state (never `unknown`).
42
+ */
43
+ export declare function hostRotationCapability(hostKind: PromptInjectionTargetHost): Extract<PromptProductionRotationState, {
44
+ state: 'rotates' | 'does_not_rotate';
45
+ }>;
46
+ /**
47
+ * PRI-1137 final review: the rotation truth of the ONE production route.
48
+ * Explicit host binding resolves that host's actual capability; otherwise a
49
+ * workspace with exactly one applicable host resolves to that host's
50
+ * capability, and anything else (no host has ever operated here, several
51
+ * applicable hosts, unreadable host facts) stays `unknown` — aggregate host
52
+ * facts are never flattened into "all hosts are FIFO" (P1-1.6). Route
53
+ * confirmation (`shared_render` for everyone) and host binding are separate
54
+ * facts; this function only answers the binding question.
55
+ */
56
+ export declare function productionRouteRotationState(input: {
57
+ workspaceDir: string;
58
+ targetHost?: PromptInjectionTargetHost;
59
+ }): PromptProductionRotationState;
13
60
  /**
14
61
  * Which serialization the budget is charged against (SPEC R-A2): the legacy
15
62
  * list route bills only the selected `- [id] text` lines (the directive
@@ -20,15 +67,14 @@ export type PromptInjectionRouteName = 'legacy_trim' | 'shared_render';
20
67
  export type PromptInjectionBudgetScope = 'selected_lines' | 'full_directive_context';
21
68
  export declare const PROMPT_INJECTION_UNIT: 'utf16_code_units';
22
69
  /**
23
- * AC-01: the effective injection route is a fact about WHICH HOST will run
24
- * the prompt build, not about the workspace flag alone. Codex always injects
25
- * through the shared route (`codex-adapter/src/pd-hook.ts`); OpenClaw routes
26
- * by its `abstraction_layer_v1` gate (`openclaw-plugin/src/index.ts`). Host
27
- * facts come from the existing durable provenance (declarations ∪ pain
28
- * evidence — `readWorkspaceHostKindFacts`); an explicit request-level target
29
- * overrides them. When the applicable hosts disagree (flag OFF + both hosts
30
- * possible, or no host facts at all) the decision is `unconfirmed` and every
31
- * consumer must say so instead of guessing FIFO or rotation (SPEC R-A1).
70
+ * AC-01 / PRI-1137: every standard host now injects through ONE shared route.
71
+ * `abstraction_layer_v1` is a gone tombstone and no longer selects a route, so
72
+ * the decision is about WHICH host will run the build (host attribution for
73
+ * the Owner), never about a per-host legacy/shared split. Host facts come from
74
+ * the existing durable provenance (declarations ∪ pain evidence —
75
+ * `readWorkspaceHostKindFacts`); an explicit request-level target overrides
76
+ * them. Unconfirmed remains for genuinely unreadable inputs (config, prompt
77
+ * flag, host facts, unknown host kinds) — never for "routes differ".
32
78
  */
33
79
  export interface PromptInjectionRouteDecision {
34
80
  status: 'confirmed' | 'unconfirmed';
@@ -36,11 +82,9 @@ export interface PromptInjectionRouteDecision {
36
82
  hostKind?: PromptInjectionTargetHost;
37
83
  /** Present when status === 'confirmed'. */
38
84
  route?: PromptInjectionRouteName;
39
- basis?: 'explicit_target' | 'workspace_host_facts' | 'flag_shared_all_hosts';
85
+ basis?: 'explicit_target' | 'workspace_host_facts' | 'single_route_all_hosts';
40
86
  /** Present when explicit binding succeeds while workspace-wide host facts are unreadable. */
41
87
  hostFactsStatus?: 'unreadable';
42
- /** Raw `abstraction_layer_v1` flag state (context for the OpenClaw branch). */
43
- flagEnabled: boolean;
44
88
  declaredHostKinds: readonly string[];
45
89
  effectiveHostKinds: readonly string[];
46
90
  /** Present when status === 'unconfirmed'. */
@@ -54,14 +98,13 @@ export interface PromptInjectionRouteDecision {
54
98
  }[];
55
99
  }
56
100
  /**
57
- * THE one route formula (P4): Codex always injects through the shared route
58
- * (codex-adapter has no flag branch); so does WorkBuddy (workbuddy-adapter
59
- * renders through the shared runtime unconditionally — it has no legacy
60
- * route); OpenClaw routes by its `abstraction_layer_v1` gate. Every consumer
61
- * that needs "which route would host X take" must call this — never re-type
62
- * the ternary.
101
+ * THE one route formula (P4 / PRI-1137): every standard host injects through
102
+ * the shared route. The OpenClaw legacy plugin-local route was deleted, so
103
+ * `legacy_trim` is retained only as a historical wire literal — production
104
+ * never returns it. Every consumer that needs "which route would host X take"
105
+ * must call this; never re-type the mapping.
63
106
  */
64
- export declare function promptRouteForHost(hostKind: PromptInjectionTargetHost, flagEnabled: boolean): PromptInjectionRouteName;
107
+ export declare function promptRouteForHost(_hostKind: PromptInjectionTargetHost): PromptInjectionRouteName;
65
108
  /**
66
109
  * Resolve the effective route for this workspace. Pure read of existing
67
110
  * config + provenance facts — no new registry, no persisted state.
@@ -102,8 +145,13 @@ export interface PromptInjectionProjection {
102
145
  * entry within N turns. So this is computed under the production policy
103
146
  * (fair rotation whenever the route actually rotates) and is therefore
104
147
  * non-empty even for a caller that supplied no round key — which is
105
- * exactly the console's situation. Empty only when the production route
106
- * genuinely does not rotate (shared route) or nothing is eligible.
148
+ * exactly the console's situation. Final review P1-1: this is a CAPABILITY
149
+ * bound, not a per-round guarantee — it holds while the session's
150
+ * user-turn records keep succeeding; a round degraded to FIFO (missing
151
+ * sessionId / failed write / unreadable ordinal) does not advance the
152
+ * window. Empty when the production route genuinely does not rotate, when
153
+ * no single host is bound (`productionRotation.state === 'unknown'` — no
154
+ * attributable ring), or when nothing is eligible.
107
155
  */
108
156
  eventuallyInjectedActivationIds: string[];
109
157
  /** Number of eligible candidates that reached the selector. */
@@ -115,8 +163,12 @@ export interface PromptInjectionProjection {
115
163
  * round key; this answers "will the agent's real injection rotate",
116
164
  * which is what determines whether an out-of-window activation is queued
117
165
  * or starved. They differ exactly in the case this whole fix is about.
166
+ *
167
+ * PRI-1137 final review (P1-1): three-state — `unknown` when no single host
168
+ * is bound, which consumers MUST NOT read as "does not rotate". Consumers
169
+ * branch on `.state`; the wire string is exactly the `state` value.
118
170
  */
119
- productionRotates: boolean;
171
+ productionRotation: PromptProductionRotationState;
120
172
  /** R-A2: the unit `usedChars`/`budget` are counted in. */
121
173
  unit: typeof PROMPT_INJECTION_UNIT;
122
174
  /** R-A2: which serialization the budget is charged against on this route. */
@@ -156,43 +208,37 @@ export interface PromptInjectionProjection {
156
208
  budgetFallbackDetail?: string;
157
209
  }
158
210
  /**
159
- * PR #1844 follow-up: forecast the prompt-injection budget from the SAME
160
- * projection the agent injection itself uses:
161
- *
162
- * - legacy route: activation candidates from `readPromptActivationCandidates`
163
- * (same FIFO query + artifact resolve as the plugin's list path) trimmed by
164
- * the REAL `trimToBudget` — identical input × ordering × trim logic as
165
- * `openclaw-plugin/src/hooks/prompt.ts`;
166
- * - shared route: delegate to `buildActivePrinciplePromptContext`, which IS
167
- * the production shared path's projection source (Codex always; OpenClaw
168
- * when its `abstraction_layer_v1` gate is on).
211
+ * PR #1844 follow-up / PRI-1137: forecast the prompt-injection budget from the
212
+ * SAME projection the agent injection itself uses — ONE route, no legacy path:
213
+ * `buildActivePrinciplePromptContext`, which IS the production shared path's
214
+ * projection source for every standard host.
169
215
  *
170
- * Route selection here is EXPLICIT: `targetHost: 'codex'` forces the shared
171
- * route (production truth for Codex), `targetHost: 'openclaw'` follows the
172
- * workspace flag, and no target follows the flag (the historical behavior —
173
- * callers that lack host context should prefer
174
- * `resolveLivePromptInjectionProjection`, which binds the route to real host
175
- * facts and refuses to guess).
216
+ * `targetHost` is host attribution only. It narrows which host's round
217
+ * authority the forecast may assume (see `productionRouteRotationState`); it
218
+ * never selects a different injection route.
176
219
  *
177
- * PR-1894 — round-key alignment. The plugin derives its fair-rotation round
178
- * key from the CURRENT session's turn ordinal (`nextSessionTurnOrdinal`),
179
- * which the console has no access to. Passing no key therefore does NOT make
180
- * the forecast "more conservative": it selects a DIFFERENT policy
181
- * (`legacy_fifo_prefix_v1`) than the one production runs. The console must
182
- * either supply the round key or report the policy honestly, so this
183
- * function takes the key as an explicit input and exposes
184
- * `selectionPolicy` on the result.
220
+ * PR-1894 — round-key alignment. Production derives its fair-rotation round
221
+ * key from the CURRENT session's turn ordinal. The console has no access to
222
+ * it, so passing no key selects `legacy_fifo_prefix_v1` for THIS forecast while
223
+ * production runs `fair_rotation_v1` on OpenClaw. The result therefore exposes
224
+ * both `selectionPolicy` (what this projection ran) and `productionRotation`
225
+ * (what the real injection will do) — never a single blended claim.
185
226
  */
186
227
  export declare function buildLivePromptInjectionProjection(input: {
187
228
  workspaceDir: string;
188
229
  /**
189
- * PR-1894: the fair-rotation round key the production route is using this
230
+ * PRI-1137: the fair-rotation round key the production route is using this
190
231
  * turn. Callers that hold one (the plugin) pass it; callers that do not
191
232
  * (the console) omit it and MUST read `selectionPolicy` off the result
192
233
  * rather than assuming FIFO.
193
234
  */
194
235
  roundKey?: number;
195
- /** AC-01: explicit route binding — 'codex'/'workbuddy' always shared, 'openclaw' by flag. */
236
+ /**
237
+ * PRI-1137: host attribution only — every host now takes the same shared
238
+ * route. This narrows WHICH host's rotation authority the forecast may
239
+ * assume (rotation is an OpenClaw-only capability); it never selects a
240
+ * different injection route.
241
+ */
196
242
  targetHost?: PromptInjectionTargetHost;
197
243
  /**
198
244
  * SPEC-PD-MODEL-AWARE-PROMPT-BUDGET-001 §6.1: budget resolution this
@@ -213,6 +259,17 @@ export type LivePromptInjectionProjectionResolution = {
213
259
  status: 'confirmed';
214
260
  decision: PromptInjectionRouteDecision;
215
261
  projection: PromptInjectionProjection;
262
+ /**
263
+ * PRI-1137: with ONE shared route, a workspace that binds no single host
264
+ * still has per-host budget facts (host attribution is a fact, not a route
265
+ * split). Each standard host's forecast runs under ITS OWN budget basis —
266
+ * never another host's window. Absent when a single host is bound (the
267
+ * headline projection already is that host's).
268
+ */
269
+ perHost?: readonly {
270
+ hostKind: PromptInjectionTargetHost;
271
+ projection: PromptInjectionProjection;
272
+ }[];
216
273
  } | {
217
274
  status: 'unconfirmed';
218
275
  decision: PromptInjectionRouteDecision;