@principles/host-runtime 4.2.1 → 4.3.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.
@@ -0,0 +1,70 @@
1
+ import { type ActivatedPrinciple } from '@principles/core/runtime';
2
+ export interface AdaptiveAppendTargetRef {
3
+ readonly principleId: string;
4
+ readonly activationId: string;
5
+ readonly artifactId: string;
6
+ readonly revisionFingerprint: string;
7
+ }
8
+ export declare function fingerprintAdaptiveAppendRevision(principle: ActivatedPrinciple): string | null;
9
+ export interface AdaptiveBackgroundSelectionInput {
10
+ readonly workspaceDir: string;
11
+ readonly sessionId: string;
12
+ readonly turnId: string;
13
+ /** Current Owner prompt. Used ONLY for the decision request; never persisted. */
14
+ readonly promptContent: string;
15
+ /** Activation ids that the already-sent Native request contained. */
16
+ readonly nativeActivationIds: readonly string[];
17
+ /** Characters of the Native additionalContext actually encoded for this turn. */
18
+ readonly nativeChars: number;
19
+ /** The budget that Native ran under. */
20
+ readonly budgetChars: number;
21
+ /** Absolute end of the background window (turn start + TTL). */
22
+ readonly deadlineAt: number;
23
+ readonly env?: Record<string, string | undefined>;
24
+ readonly fetchImpl?: typeof fetch;
25
+ readonly now?: () => number;
26
+ }
27
+ export interface AdaptiveBackgroundDiagnostic {
28
+ readonly status: string;
29
+ readonly reason: string;
30
+ readonly sends: number;
31
+ }
32
+ export type AdaptiveBackgroundSelectionOutcome = {
33
+ readonly status: 'selected';
34
+ readonly target: AdaptiveAppendTargetRef;
35
+ /** The exact directive slice a later request may append. */
36
+ readonly directive: string;
37
+ readonly diagnostic: AdaptiveBackgroundDiagnostic;
38
+ } | {
39
+ readonly status: 'skipped' | 'unavailable';
40
+ readonly reason: string;
41
+ readonly diagnostic: AdaptiveBackgroundDiagnostic;
42
+ };
43
+ /** The one directive body, identical to what the shared packer would render. */
44
+ export declare function renderAppendDirective(principle: ActivatedPrinciple): string | null;
45
+ /**
46
+ * Runs ONE background selection for a turn whose Native request already left.
47
+ *
48
+ * Returns `selected` only when the shared measurement proves the target fits
49
+ * the budget Native did not use, and the shared revalidator proves the exact
50
+ * authorized revision still holds at decision time.
51
+ */
52
+ export declare function runAdaptiveBackgroundSelection(input: AdaptiveBackgroundSelectionInput): Promise<AdaptiveBackgroundSelectionOutcome>;
53
+ export type AdaptiveAppendRenderResult = {
54
+ readonly ok: true;
55
+ readonly directive: string;
56
+ readonly principle: ActivatedPrinciple;
57
+ } | {
58
+ readonly ok: false;
59
+ readonly reason: string;
60
+ };
61
+ /**
62
+ * Consume-time revalidation. Runs in the LATER hook process and therefore
63
+ * proves the authorization/body facts again — a background decision is not a
64
+ * license to append a revision that changed while the turn was running.
65
+ */
66
+ export declare function renderAcceptedAdaptiveAppend(input: {
67
+ readonly workspaceDir: string;
68
+ readonly target: AdaptiveAppendTargetRef;
69
+ readonly signal: AbortSignal;
70
+ }): Promise<AdaptiveAppendRenderResult>;
@@ -0,0 +1,165 @@
1
+ /**
2
+ * PRI-1196 — Adaptive Activation, background selection (Codex desktop).
3
+ *
4
+ * The synchronous path decides BEFORE the first model request. This module is
5
+ * the asynchronous counterpart: the first request already left as Native, and
6
+ * the decision runs in a detached process. It reuses the SAME candidate read,
7
+ * skip gate, decision protocol, authorization revalidation and capacity
8
+ * measurement as the synchronous path; only the orchestration differs.
9
+ *
10
+ * Append-only by construction: the feasible gap is the budget the sent Native
11
+ * did NOT use, and the target is never offered a replacement slot. The chosen
12
+ * directive is rendered for a LATER request of the same turn.
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { escapeXml } from '@principles/core/prompt-builder';
16
+ import { measureSharedDirectiveBlockChars, renderPrinciplesToDirectives, } from '@principles/core/runtime';
17
+ import { readPromptActivationCandidates } from './active-principle-prompt.js';
18
+ import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
19
+ import { createAdaptivePriorityProviderForConfig, } from './adaptive-priority-provider.js';
20
+ import { loadPdConfigForPlugin } from './pd-config.js';
21
+ export function fingerprintAdaptiveAppendRevision(principle) {
22
+ if (!principle.artifactContentSha256)
23
+ return null;
24
+ return createHash('sha256').update(JSON.stringify([
25
+ principle.artifactContentSha256, principle.text, principle.authority, principle.approvedBy,
26
+ ])).digest('hex');
27
+ }
28
+ /** The one directive body, identical to what the shared packer would render. */
29
+ export function renderAppendDirective(principle) {
30
+ const rendered = renderPrinciplesToDirectives([principle], new Set([principle.principleId]), { escapeFn: escapeXml });
31
+ const start = rendered.indexOf('<directive ');
32
+ const end = rendered.indexOf('</directive>');
33
+ if (start < 0 || end < 0)
34
+ return null;
35
+ return rendered.slice(start, end + '</directive>'.length);
36
+ }
37
+ /**
38
+ * Runs ONE background selection for a turn whose Native request already left.
39
+ *
40
+ * Returns `selected` only when the shared measurement proves the target fits
41
+ * the budget Native did not use, and the shared revalidator proves the exact
42
+ * authorized revision still holds at decision time.
43
+ */
44
+ export async function runAdaptiveBackgroundSelection(input) {
45
+ let diagnostic = { status: 'skipped', reason: 'no_appendable_gap', sends: 0 };
46
+ const config = loadPdConfigForPlugin(input.workspaceDir);
47
+ if (!config.ok) {
48
+ return { status: 'unavailable', reason: 'config_invalid', diagnostic: { status: 'unavailable', reason: 'config_invalid', sends: 0 } };
49
+ }
50
+ const candidates = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
51
+ if (candidates.aborted || candidates.warnings.length > 0) {
52
+ const reason = candidates.aborted ? 'reader_aborted' : 'reader_warnings';
53
+ return { status: 'unavailable', reason, diagnostic: { status: 'unavailable', reason, sends: 0 } };
54
+ }
55
+ const nativeIds = new Set(input.nativeActivationIds);
56
+ const omitted = candidates.principles.filter((principle) => !nativeIds.has(principle.activationId));
57
+ const renderOptions = { escapeFn: escapeXml, selfReportInstruction: candidates.selfReportEnabled };
58
+ const remaining = input.budgetChars - input.nativeChars;
59
+ const feasible = remaining > 0
60
+ ? omitted.filter((principle) => measureSharedDirectiveBlockChars(principle, renderOptions) <= remaining)
61
+ : [];
62
+ if (feasible.length === 0) {
63
+ return { status: 'skipped', reason: 'no_appendable_gap', diagnostic };
64
+ }
65
+ const resolution = createAdaptivePriorityProviderForConfig(config.effective.config, input.workspaceDir, {
66
+ ...(input.env ? { env: input.env } : {}),
67
+ ...(input.fetchImpl ? { fetchImpl: input.fetchImpl } : {}),
68
+ ...(input.now ? { now: input.now } : {}),
69
+ outerDeadlineAt: input.deadlineAt,
70
+ // Nothing needs to be reserved for a second assembly: the directive is
71
+ // already rendered by the time the process exits.
72
+ outputReserveMs: 0,
73
+ onDiagnostic: (line) => {
74
+ diagnostic = { status: line.status, reason: line.reason, sends: line.sends };
75
+ },
76
+ });
77
+ if (!resolution.ok) {
78
+ return {
79
+ status: 'skipped',
80
+ reason: `needs_setup:${resolution.reason}`,
81
+ diagnostic: { status: 'needs_setup', reason: resolution.reason, sends: 0 },
82
+ };
83
+ }
84
+ // The provider only needs the host-supplied turn identity and prompt body.
85
+ const event = {
86
+ kind: 'before_prompt_build',
87
+ source: 'codex:adaptive_background_selection',
88
+ rawPayload: null,
89
+ context: {
90
+ workspaceDir: input.workspaceDir,
91
+ sessionId: input.sessionId,
92
+ turnId: input.turnId,
93
+ promptContent: input.promptContent,
94
+ },
95
+ };
96
+ const selection = await resolution.provider(event, feasible, {
97
+ excludedByBudget: feasible.length < omitted.length,
98
+ // Background mode is append-only: never offer a replacement slot.
99
+ replacementByActivationId: new Map(),
100
+ });
101
+ if (!selection) {
102
+ return { status: 'skipped', reason: diagnostic.reason, diagnostic };
103
+ }
104
+ const selected = feasible.find((principle) => principle.activationId === selection.activationId
105
+ && principle.artifactId === selection.artifactId);
106
+ if (!selected) {
107
+ return { status: 'unavailable', reason: 'selection_target_missing', diagnostic };
108
+ }
109
+ const revalidationBudgetMs = Math.max(1, Math.min(1500, input.deadlineAt - (input.now?.() ?? Date.now())));
110
+ if (!await revalidateAdaptivePrinciple(input.workspaceDir, selected, AbortSignal.timeout(revalidationBudgetMs))) {
111
+ return { status: 'unavailable', reason: 'target_changed', diagnostic };
112
+ }
113
+ const revisionFingerprint = fingerprintAdaptiveAppendRevision(selected);
114
+ if (!revisionFingerprint)
115
+ return { status: 'unavailable', reason: 'target_changed', diagnostic };
116
+ const directive = renderAppendDirective(selected);
117
+ if (directive === null) {
118
+ return { status: 'unavailable', reason: 'target_render_failed', diagnostic };
119
+ }
120
+ if (input.nativeChars + directive.length > input.budgetChars) {
121
+ return { status: 'unavailable', reason: 'budget_exhausted', diagnostic };
122
+ }
123
+ return {
124
+ status: 'selected',
125
+ target: {
126
+ principleId: selected.principleId,
127
+ activationId: selected.activationId,
128
+ artifactId: selected.artifactId,
129
+ revisionFingerprint,
130
+ },
131
+ directive,
132
+ diagnostic,
133
+ };
134
+ }
135
+ /**
136
+ * Consume-time revalidation. Runs in the LATER hook process and therefore
137
+ * proves the authorization/body facts again — a background decision is not a
138
+ * license to append a revision that changed while the turn was running.
139
+ */
140
+ export async function renderAcceptedAdaptiveAppend(input) {
141
+ const read = await readPromptActivationCandidates({
142
+ workspaceDir: input.workspaceDir,
143
+ includeAuthority: true,
144
+ noBusyWait: true,
145
+ });
146
+ if (read.aborted || read.warnings.length > 0)
147
+ return { ok: false, reason: 'authority_unavailable' };
148
+ const matches = read.principles.filter((principle) => principle.activationId === input.target.activationId && principle.artifactId === input.target.artifactId);
149
+ if (matches.length !== 1)
150
+ return { ok: false, reason: 'target_unavailable' };
151
+ const [principle] = matches;
152
+ if (!principle
153
+ || principle.principleId !== input.target.principleId
154
+ || fingerprintAdaptiveAppendRevision(principle) !== input.target.revisionFingerprint
155
+ || read.principles.filter((candidate) => candidate.principleId === principle.principleId).length !== 1) {
156
+ return { ok: false, reason: 'target_changed' };
157
+ }
158
+ if (!await revalidateAdaptivePrinciple(input.workspaceDir, principle, input.signal)) {
159
+ return { ok: false, reason: 'target_changed' };
160
+ }
161
+ const directive = renderAppendDirective(principle);
162
+ if (directive === null)
163
+ return { ok: false, reason: 'target_render_failed' };
164
+ return { ok: true, directive, principle };
165
+ }
@@ -35,7 +35,7 @@ import fs from 'node:fs';
35
35
  import path from 'node:path';
36
36
  import { randomUUID } from 'node:crypto';
37
37
  import Database from 'better-sqlite3';
38
- import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, disposePainSignalBridgesForWorkspace, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
38
+ import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
39
  import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
40
40
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
41
  import { loadPdConfigForPlugin } from './pd-config.js';
@@ -1880,10 +1880,6 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1880
1880
  : {}),
1881
1881
  recordObservability: true,
1882
1882
  });
1883
- // recordPain (async) leaves a cached bridge holding open SQLite
1884
- // handles; this seam runs per reconciliation cycle under the Slice C
1885
- // worker, so release it immediately (hook processes exit anyway).
1886
- await disposePainSignalBridgesForWorkspace(workspaceDir).catch(() => undefined);
1887
1883
  if (result.status === 'failed') {
1888
1884
  // Concurrent-ensure race (hook redelivery × worker reconcile): both
1889
1885
  // callers passed the getTask probe before either committed, and the
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export * from './governance-signal-admission.js';
24
24
  export * from './signal-classifier.js';
25
25
  export * from './adaptive-selection.js';
26
26
  export * from './adaptive-priority-provider.js';
27
+ export * from './adaptive-background-append.js';
27
28
  export * from './signal-stage2-cycle.js';
28
29
  export * from './host-liveness-contract.js';
29
30
  export * from './internalization-consumer-governance.js';
package/dist/index.js CHANGED
@@ -43,6 +43,11 @@ export * from './governance-signal-admission.js';
43
43
  export * from './signal-classifier.js';
44
44
  export * from './adaptive-selection.js';
45
45
  export * from './adaptive-priority-provider.js';
46
+ // PRI-1196: background (async) Adaptive selection for the Codex host. Reuses
47
+ // the same candidates/gate/protocol/revalidation/capacity primitives; the
48
+ // first request goes out as Native and one directive may be appended later in
49
+ // the same turn.
50
+ export * from './adaptive-background-append.js';
46
51
  export * from './signal-stage2-cycle.js';
47
52
  export * from './host-liveness-contract.js';
48
53
  // PRI-624 Slice C: shared internalization consumer execution (OpenClaw
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.2.1",
3
+ "version": "4.3.1",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -35,7 +35,7 @@
35
35
  "lint": "eslint \"src/**/*.ts\""
36
36
  },
37
37
  "dependencies": {
38
- "@principles/core": "^7.8.0",
38
+ "@principles/core": "^7.10.0",
39
39
  "@principles/install-layout": "^0.8.2",
40
40
  "better-sqlite3": "^13.0.3",
41
41
  "js-yaml": "^5.4.3"
@@ -53,5 +53,5 @@
53
53
  "url": "git+https://github.com/csuzngjh/principles.git"
54
54
  },
55
55
  "license": "Apache-2.0",
56
- "gitHead": "8ad7b7924a5edb2231486ef0ed99c2462ad78318"
56
+ "gitHead": "5ebfebcc384368a6f68f62fdd539507a03fd1d4a"
57
57
  }