@principles/codex-adapter 0.8.7 → 0.8.10

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.
package/dist/pd-hook.d.ts CHANGED
@@ -11,5 +11,26 @@ export interface CodexEvidenceContext {
11
11
  evidenceEnabled: boolean;
12
12
  warn: (diagnosticLine: string) => void;
13
13
  }
14
- export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string): Promise<PdHookResult>;
14
+ /**
15
+ * The host hook window is declared by the plugin manifest
16
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
17
+ * in seconds). Codex owns that timer and terminates the hook process when it
18
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
19
+ * window and leave the remainder to emit the Native body.
20
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
21
+ */
22
+ export declare const CODEX_HOOK_TIMEOUT_MS = 5000;
23
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
24
+ export declare const CODEX_NATIVE_RESERVE_MS = 800;
25
+ export declare const CODEX_ADAPTIVE_BUDGET_MS: number;
26
+ export interface PdHookDeps {
27
+ /** Test seam: replace the outbound transport without bypassing the hook entry. */
28
+ readonly fetchImpl?: typeof fetch;
29
+ readonly now?: () => number;
30
+ readonly firstByteTimeoutMs?: number;
31
+ readonly generationTimeoutMs?: number;
32
+ /** Test seam: effective adaptive budget inside the host hook window. */
33
+ readonly hookBudgetMs?: number;
34
+ }
35
+ export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string, deps?: PdHookDeps): Promise<PdHookResult>;
15
36
  export {};
package/dist/pd-hook.js CHANGED
@@ -5,8 +5,8 @@ import path from 'node:path';
5
5
  import process from 'node:process';
6
6
  import { pathToFileURL, fileURLToPath } from 'node:url';
7
7
  import { appendEventLogLine, redactTelemetryString, isRuleHostEvaluatedEventData } from '@principles/core/runtime';
8
- import { createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
- import { CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
8
+ import { createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
+ import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
10
10
  import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
11
11
  import { CodexHooksHostAdapter } from './host-adapter.js';
12
12
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
@@ -24,6 +24,19 @@ function diagnostic(reason, nextAction) {
24
24
  function errorMessage(error) {
25
25
  return error instanceof Error ? error.message.slice(0, MAX_DIAGNOSTIC) : 'unknown_error';
26
26
  }
27
+ /**
28
+ * PRI-1170: one bounded line per Adaptive turn. Records the facts needed to
29
+ * tell first-byte expiry, generation expiry, transport failure and ref/digest
30
+ * rejection apart — never the prompt, the raw response, or credentials.
31
+ */
32
+ function adaptiveSelectionDiagnostic(line) {
33
+ const status = line.status === 'selected' ? 'adaptive' : 'degraded';
34
+ const failures = line.failures.length > 0 ? line.failures.join('|') : 'none';
35
+ return `[PD] status=${status} reason=adaptive_selection_${line.status}:${line.reason} stage=${line.stage} sends=${line.sends} firstByteAt=${line.firstByteAt ?? 'unknown'} generationEndedAt=${line.generationEndedAt ?? 'unknown'} cancelledAt=${line.cancelledAt ?? 'unknown'} httpStatus=${line.httpStatus ?? 'unknown'} finishReason=${line.finishReason} failures=${failures}`
36
+ .replace(/\s+/g, ' ')
37
+ .trim()
38
+ .slice(0, MAX_DIAGNOSTIC * 2);
39
+ }
27
40
  function redactStringFields(data) {
28
41
  // rc-8: telemetry is redacted string-field by string field (same policy as
29
42
  // the OpenClaw EventLog redactEventData) — shared by every emitter here.
@@ -191,7 +204,25 @@ async function runConversationIngestion(args) {
191
204
  }
192
205
  return diagnostics;
193
206
  }
194
- export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd()) {
207
+ /**
208
+ * The host hook window is declared by the plugin manifest
209
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
210
+ * in seconds). Codex owns that timer and terminates the hook process when it
211
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
212
+ * window and leave the remainder to emit the Native body.
213
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
214
+ */
215
+ export const CODEX_HOOK_TIMEOUT_MS = 5_000;
216
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
217
+ export const CODEX_NATIVE_RESERVE_MS = 800;
218
+ export const CODEX_ADAPTIVE_BUDGET_MS = CODEX_HOOK_TIMEOUT_MS - CODEX_NATIVE_RESERVE_MS;
219
+ // stdin, env and cwd are the host CLI contract; `deps` is the optional transport
220
+ // seam that lets integration tests drive the real entry point without a network.
221
+ // eslint-disable-next-line @typescript-eslint/max-params
222
+ export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd(), deps = {}) {
223
+ // The host owns this window and kills the process when it expires; anchor at
224
+ // entry so decode/ingestion time counts against the same budget.
225
+ const adaptiveDeadlineAt = Date.now() + (deps.hookBudgetMs ?? CODEX_ADAPTIVE_BUDGET_MS);
195
226
  let parsed;
196
227
  try {
197
228
  parsed = JSON.parse(rawStdin);
@@ -385,17 +416,55 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
385
416
  // event-JSONL writer (same events_*.jsonl format as the OpenClaw EventLog;
386
417
  // the Codex adapter stays independent of the OpenClaw plugin). The line
387
418
  // writer appends synchronously — no flush/dispose needed for the subprocess.
419
+ // PRI-1170: Adaptive Activation is an INDEPENDENT, default-off switch on
420
+ // top of the PD hook. `host.codex.enabled` remains the whole-hook gate.
421
+ const adaptiveDiagnostics = [];
422
+ let adaptivePriorityProvider;
423
+ if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true) {
424
+ const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
425
+ env: _env,
426
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
427
+ ...(deps.now ? { now: deps.now } : {}),
428
+ ...(deps.firstByteTimeoutMs !== undefined ? { firstByteTimeoutMs: deps.firstByteTimeoutMs } : {}),
429
+ ...(deps.generationTimeoutMs !== undefined ? { generationTimeoutMs: deps.generationTimeoutMs } : {}),
430
+ outerDeadlineAt: adaptiveDeadlineAt,
431
+ onDiagnostic: (line) => { adaptiveDiagnostics.push(adaptiveSelectionDiagnostic(line)); },
432
+ });
433
+ if (adaptive.ok) {
434
+ adaptivePriorityProvider = adaptive.provider;
435
+ }
436
+ else {
437
+ // rc-9: an enabled-but-unusable switch is observable, never silent.
438
+ adaptiveDiagnostics.push(diagnostic(`adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
439
+ }
440
+ }
441
+ // B3: resolve tool semantics from the workspace declarations — the SAME
442
+ // source replay / evidence / Console read — with the compiled-in Codex
443
+ // declaration as the fallback. A malformed declaration degrades
444
+ // observably on stderr instead of blocking the tool call (rc-9).
445
+ const toolSemanticsResolution = resolveHostToolSemanticsForHook({
446
+ workspaceDir: resolution.workspaceDir,
447
+ hostKind: 'codex',
448
+ staticMappings: CODEX_TOOL_SEMANTIC_MAPPINGS,
449
+ });
450
+ const toolSemantics = toolSemanticsResolution.ok
451
+ ? toolSemanticsResolution.registry
452
+ : CODEX_TOOL_SEMANTICS;
453
+ const toolSemanticsDiagnostics = toolSemanticsResolution.ok
454
+ ? []
455
+ : [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
388
456
  const result = await createProductionHostRuntime({
389
457
  projectDir: requestedCwd,
390
458
  hostKind: 'codex',
391
- toolSemantics: CODEX_TOOL_SEMANTICS,
459
+ toolSemantics,
460
+ ...(adaptivePriorityProvider ? { adaptivePriorityProvider } : {}),
392
461
  ruleContextProvider: createCodexRuleContextProvider({
393
462
  workspaceDir: resolution.workspaceDir,
394
463
  projectDir: requestedCwd,
395
464
  enabled: flags.rulecode_context_v2?.enabled === true && ingestionEnabled,
396
465
  cutoffAt: hookEpoch,
397
466
  currentToolUseId: event.context.toolCallId ?? '',
398
- toolSemantics: CODEX_TOOL_SEMANTICS,
467
+ toolSemantics,
399
468
  }),
400
469
  events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
401
470
  }).dispatch(event);
@@ -463,7 +532,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
463
532
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
464
533
  }
465
534
  }
466
- const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics];
535
+ const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics];
467
536
  return { stdout: encoded, exitCode: 0, stderr };
468
537
  }
469
538
  catch (error) {
@@ -545,7 +614,12 @@ async function main() {
545
614
  }
546
615
  let result;
547
616
  try {
548
- result = await processHookInvocation(raw);
617
+ // The host's 5 s window starts at process spawn, not at this call: node
618
+ // boot and module loading already consumed part of it. Anchor the deadline
619
+ // at process start so the measured reserve really reaches Native.
620
+ const elapsedSinceProcessStartMs = Math.round(process.uptime() * 1000);
621
+ const remainingBudgetMs = Math.max(1, CODEX_ADAPTIVE_BUDGET_MS - elapsedSinceProcessStartMs);
622
+ result = await processHookInvocation(raw, process.env, process.cwd(), { hookBudgetMs: remainingBudgetMs });
549
623
  }
550
624
  catch (error) {
551
625
  // Fail-open belt for an unexpected pre-dispatch throw (e.g. a workspace
@@ -67,6 +67,21 @@ export interface CodexWorkerCycleOptions {
67
67
  readonly stage2AggregateBudgetMs?: number;
68
68
  }
69
69
  export declare function readCodexWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
70
+ /**
71
+ * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
72
+ * continuously-eligible classes; neither may starve the other while new
73
+ * pending signals keep arriving. A persistent round-robin cursor (stored in
74
+ * the existing reconciliation_cursor authority, so a worker restart does NOT
75
+ * reset it to pending-priority) alternates service between the two classes —
76
+ * each eligible class is served at least every other cycle, well inside the
77
+ * 3-full-cycle bound. Single-eligible work is always served.
78
+ *
79
+ * The implementation is shared with OpenClaw's L3 automatic run
80
+ * (`@principles/core/runtime` `pickDiagnosticianCandidate`); this file keeps no
81
+ * second copy. Oldest pending diagnostician first; retry_wait candidates are
82
+ * filtered to those whose backoff window has ELAPSED, so an old-but-still-
83
+ * waiting task cannot starve a younger eligible one (review P1).
84
+ */
70
85
  /**
71
86
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
72
87
  * every failure becomes a structured degraded result with a nextAction.
@@ -27,7 +27,7 @@
27
27
  */
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
- import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
30
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
31
  import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, } from '@principles/host-runtime';
32
32
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
33
33
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
@@ -111,14 +111,6 @@ function writeLiveness(workspaceDir, patch) {
111
111
  // itself remains the observable degradation channel)
112
112
  }
113
113
  }
114
- /**
115
- * Oldest pending diagnostician first; retry_wait candidates are filtered to
116
- * those whose backoff window has ELAPSED, so an old-but-still-waiting task
117
- * cannot starve a younger eligible one (review P1). The candidate set stays
118
- * bounded (`limit`), and executePendingDiagnosis re-enforces the backoff
119
- * window on the chosen task — no double bookkeeping.
120
- */
121
- const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
122
114
  /**
123
115
  * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
124
116
  * continuously-eligible classes; neither may starve the other while new
@@ -127,34 +119,13 @@ const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
127
119
  * reset it to pending-priority) alternates service between the two classes —
128
120
  * each eligible class is served at least every other cycle, well inside the
129
121
  * 3-full-cycle bound. Single-eligible work is always served.
122
+ *
123
+ * The implementation is shared with OpenClaw's L3 automatic run
124
+ * (`@principles/core/runtime` `pickDiagnosticianCandidate`); this file keeps no
125
+ * second copy. Oldest pending diagnostician first; retry_wait candidates are
126
+ * filtered to those whose backoff window has ELAPSED, so an old-but-still-
127
+ * waiting task cannot starve a younger eligible one (review P1).
130
128
  */
131
- async function pickDiagnosticianCandidate(stateManager, limit, nowIso) {
132
- const pending = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'pending', orderBy: 'updated_at_asc', limit });
133
- const [pendingTask] = pending;
134
- let retryTask = null;
135
- const retrying = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit });
136
- for (const candidate of retrying) {
137
- if (isRetryWaitBackoffElapsed(candidate.status, candidate.leaseExpiresAt)) {
138
- retryTask = candidate;
139
- break;
140
- }
141
- }
142
- if (pendingTask === undefined && retryTask === null)
143
- return null;
144
- if (retryTask === null) {
145
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: 'pending' });
146
- return pendingTask ?? null;
147
- }
148
- if (pendingTask === undefined) {
149
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: 'retry_wait' });
150
- return retryTask;
151
- }
152
- const cursor = await stateManager.getDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE);
153
- const serveRetryFirst = cursor?.lastTaskId !== 'retry_wait';
154
- const servedClass = serveRetryFirst ? 'retry_wait' : 'pending';
155
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: servedClass });
156
- return serveRetryFirst ? retryTask : pendingTask;
157
- }
158
129
  /**
159
130
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
160
131
  * every failure becomes a structured degraded result with a nextAction.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.8.7",
3
+ "version": "0.8.10",
4
4
  "description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -33,9 +33,9 @@
33
33
  "lint": "eslint \"src/**/*.ts\""
34
34
  },
35
35
  "dependencies": {
36
- "@principles/core": "^7.0.0",
37
- "@principles/host-runtime": "^3.2.1",
38
- "@principles/install-layout": "^0.6.0"
36
+ "@principles/core": "^7.3.1",
37
+ "@principles/host-runtime": "^3.3.1",
38
+ "@principles/install-layout": "^0.7.0"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/node": "^26.6.6",
@@ -52,5 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "gitHead": "80e8f5e27a6b7b395f73d2334477eb34317c3cc0"
55
+ "gitHead": "8851a3be8c3bcacb732609143bfe3d2ac4ba4ea5"
56
56
  }