@principles/codex-adapter 0.2.3 → 0.2.5

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.
@@ -93,7 +93,7 @@ function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity,
93
93
  if (offset > window.fileSize) {
94
94
  // The file shrank below the committed cursor: replaced or truncated —
95
95
  // never guess; hold the checkpoint and degrade explicitly.
96
- return { status: 'degraded', reason: 'checkpoint_inconsistent', nextAction: 'the transcript is shorter than the committed checkpoint; run the audited recovery/quarantine path once available or re-ingest from a fresh rollout.', warnings: [] };
96
+ return { status: 'degraded', reason: 'checkpoint_inconsistent', nextAction: 'the transcript is shorter than the committed checkpoint; quarantine the stale rollout records via `pd codex ingest quarantine` or re-ingest from a fresh rollout.', warnings: [] };
97
97
  }
98
98
  const byteBoundReached = offset + window.bytes.length < window.fileSize;
99
99
  const decoded = decodeTranscriptWindow({
@@ -120,7 +120,7 @@ function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity,
120
120
  }
121
121
  const degradations = [];
122
122
  if (decoded.stop.kind === 'malformed') {
123
- degradations.push({ reason: 'transcript_record_malformed', ...(decoded.stop.ordinal !== null ? { ordinal: decoded.stop.ordinal } : {}), nextAction: 'the record is stable-invalid; run the audited quarantine command once available (Slice D). Later records remain as lag.' });
123
+ degradations.push({ reason: 'transcript_record_malformed', ...(decoded.stop.ordinal !== null ? { ordinal: decoded.stop.ordinal } : {}), nextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.' });
124
124
  }
125
125
  else if (decoded.stop.kind === 'oversized_record') {
126
126
  degradations.push({ reason: 'transcript_record_too_large', nextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.' });
@@ -164,7 +164,7 @@ function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity,
164
164
  return {
165
165
  status: 'degraded',
166
166
  reason: 'transcript_record_malformed',
167
- nextAction: 'the record is stable-invalid; run the audited quarantine command once available (Slice D). Later records remain as lag.',
167
+ nextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.',
168
168
  warnings,
169
169
  };
170
170
  }
@@ -1,13 +1,8 @@
1
- export type CodexTranscriptLookup = {
2
- ok: true;
3
- transcriptPath: string;
4
- } | {
5
- ok: false;
6
- reason: 'catch_up_rollout_identity_invalid' | 'catch_up_sessions_root_missing' | 'catch_up_transcript_missing' | 'catch_up_transcript_ambiguous' | 'catch_up_lookup_exhausted';
7
- nextAction: string;
8
- };
9
1
  /**
10
- * Resolve one previously-authenticated rollout identity to its transcript
11
- * path by exact-uuid filename match under `<codexHome>/sessions`.
2
+ * Codex transcript locator — Slice D (PRI-625) moved the implementation to
3
+ * @principles/host-runtime (codex-transcript-locate) so the §15 health
4
+ * service computes per-rollout lag with the SAME locator the catch-up path
5
+ * uses. This module re-exports it for compatibility with existing importers.
12
6
  */
13
- export declare function locateCodexTranscriptByRolloutIdentity(codexHome: string, rolloutIdentity: string): CodexTranscriptLookup;
7
+ export { locateCodexTranscriptByRolloutIdentity, parseRolloutFileName } from '@principles/host-runtime';
8
+ export type { CodexTranscriptLookup } from '@principles/host-runtime';
@@ -1,75 +1,7 @@
1
1
  /**
2
- * Codex transcript locator for catch-up (PRI-624 Slice C).
3
- *
4
- * The durable checkpoint stores only the rollout uuid (SPEC §18 scenario 9
5
- * forbids raw paths in the DB), so catch-up must resolve a checkpointed
6
- * rollout back to its transcript file. This is NOT session discovery: the
7
- * lookup searches for the EXACT rollout uuid of a rollout the authenticated
8
- * Workspace hook previously delivered (only hooks write checkpoints). It
9
- * never guesses a "latest session", never returns a partial match, and
10
- * refuses ambiguities (ADR-0020 §11.2 / SPEC §9).
2
+ * Codex transcript locator Slice D (PRI-625) moved the implementation to
3
+ * @principles/host-runtime (codex-transcript-locate) so the §15 health
4
+ * service computes per-rollout lag with the SAME locator the catch-up path
5
+ * uses. This module re-exports it for compatibility with existing importers.
11
6
  */
12
- import fs from 'node:fs';
13
- import path from 'node:path';
14
- import { parseRolloutFileName } from './transcript-path.js';
15
- /** Bounded walk: hard cap on visited directory entries so a pathological sessions tree cannot stall the worker. */
16
- const MAX_LOOKUP_ENTRIES = 5000;
17
- const ROLLOUT_IDENTITY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
18
- /**
19
- * Resolve one previously-authenticated rollout identity to its transcript
20
- * path by exact-uuid filename match under `<codexHome>/sessions`.
21
- */
22
- export function locateCodexTranscriptByRolloutIdentity(codexHome, rolloutIdentity) {
23
- if (!ROLLOUT_IDENTITY_PATTERN.test(rolloutIdentity)) {
24
- return { ok: false, reason: 'catch_up_rollout_identity_invalid', nextAction: 'the checkpointed rollout identity is not a rollout uuid; inspect the workspace trajectory database.' };
25
- }
26
- const sessionsRoot = path.join(codexHome, 'sessions');
27
- let rootStats;
28
- try {
29
- rootStats = fs.statSync(sessionsRoot);
30
- }
31
- catch {
32
- return { ok: false, reason: 'catch_up_sessions_root_missing', nextAction: 'the configured CODEX_HOME has no sessions root; verify the Codex home used by the hook and by catch-up matches.' };
33
- }
34
- if (!rootStats.isDirectory()) {
35
- return { ok: false, reason: 'catch_up_sessions_root_missing', nextAction: 'the configured CODEX_HOME sessions path is not a directory; verify the Codex home configuration.' };
36
- }
37
- const matches = [];
38
- let visited = 0;
39
- const stack = [sessionsRoot];
40
- while (stack.length > 0 && matches.length < 2) {
41
- const dir = stack.pop();
42
- if (dir === undefined)
43
- break;
44
- let entries;
45
- try {
46
- entries = fs.readdirSync(dir, { withFileTypes: true });
47
- }
48
- catch {
49
- continue; // unreadable subtree — other subtrees may still hold the rollout
50
- }
51
- for (const entry of entries) {
52
- visited += 1;
53
- if (visited > MAX_LOOKUP_ENTRIES) {
54
- return { ok: false, reason: 'catch_up_lookup_exhausted', nextAction: 'the sessions tree exceeded the bounded catch-up lookup; keep CODEX_HOME/sessions pruned or catch up rollouts manually.' };
55
- }
56
- if (entry.isDirectory()) {
57
- stack.push(path.join(dir, entry.name));
58
- }
59
- else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
60
- if (parseRolloutFileName(entry.name) === rolloutIdentity) {
61
- matches.push(path.join(dir, entry.name));
62
- if (matches.length >= 2)
63
- break;
64
- }
65
- }
66
- }
67
- }
68
- if (matches.length === 0) {
69
- return { ok: false, reason: 'catch_up_transcript_missing', nextAction: 'the checkpointed rollout has no transcript under the Codex sessions root (rotated or cleaned by Codex); its committed observations remain, the pending lag cannot be recovered.' };
70
- }
71
- if (matches.length > 1) {
72
- return { ok: false, reason: 'catch_up_transcript_ambiguous', nextAction: 'multiple transcripts match the rollout identity; refuse to guess — inspect the Codex sessions tree.' };
73
- }
74
- return { ok: true, transcriptPath: matches[0] };
75
- }
7
+ export { locateCodexTranscriptByRolloutIdentity, parseRolloutFileName } from '@principles/host-runtime';
@@ -20,6 +20,6 @@ export type TranscriptPathValidation = {
20
20
  reason: 'transcript_path_invalid' | 'transcript_path_outside_codex_home';
21
21
  nextAction: string;
22
22
  };
23
- /** rollout-<timestamp>-<uuid>.jsonl returns the rollout uuid, or null when the name is off-contract. */
24
- export declare function parseRolloutFileName(fileName: string): string | null;
23
+ import { parseRolloutFileName } from '@principles/host-runtime';
24
+ export { parseRolloutFileName };
25
25
  export declare function validateCodexTranscriptPath(transcriptPath: string, codexHome: string): TranscriptPathValidation;
@@ -16,27 +16,10 @@
16
16
  import fs from 'node:fs';
17
17
  import path from 'node:path';
18
18
  import { canonicalizePath } from './codex-home.js';
19
- const UUID_HEX = /^[0-9a-fA-F]+$/;
20
- function isHex(value) {
21
- return UUID_HEX.test(value);
22
- }
23
- /** rollout-<timestamp>-<uuid>.jsonl — returns the rollout uuid, or null when the name is off-contract. */
24
- export function parseRolloutFileName(fileName) {
25
- if (!fileName.startsWith('rollout-') || !fileName.endsWith('.jsonl'))
26
- return null;
27
- const stem = fileName.slice('rollout-'.length, -'.jsonl'.length);
28
- const parts = stem.split('-');
29
- if (parts.length < 6)
30
- return null; // at least one timestamp segment + the five uuid groups
31
- const [a, b, c, d, e] = parts.slice(-5);
32
- if (a === undefined || b === undefined || c === undefined || d === undefined || e === undefined)
33
- return null;
34
- if (a.length !== 8 || b.length !== 4 || c.length !== 4 || d.length !== 4 || e.length !== 12)
35
- return null;
36
- if (!isHex(a) || !isHex(b) || !isHex(c) || !isHex(d) || !isHex(e))
37
- return null;
38
- return parts.slice(-5).join('-').toLowerCase();
39
- }
19
+ // PRI-625 Slice D: the rollout filename contract has ONE implementation,
20
+ // moved to @principles/host-runtime with the transcript locator.
21
+ import { parseRolloutFileName } from '@principles/host-runtime';
22
+ export { parseRolloutFileName };
40
23
  function isAbsolutePath(value) {
41
24
  return path.isAbsolute(value);
42
25
  }
package/dist/pd-hook.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import process from 'node:process';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { createProductionHostRuntime, loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
6
+ import { CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
6
7
  import { computeFeatureFlagsFromConfig } from '@principles/core/runtime-v2';
7
8
  import { CodexHooksHostAdapter } from './host-adapter.js';
8
9
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
@@ -117,7 +118,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
117
118
  const ingestionDiagnostics = ingestionEnabled
118
119
  ? await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })
119
120
  : [];
120
- const result = await createProductionHostRuntime({ hostKind: 'codex' }).dispatch(event);
121
+ const result = await createProductionHostRuntime({ hostKind: 'codex', toolSemantics: CODEX_TOOL_SEMANTICS }).dispatch(event);
121
122
  const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...ingestionDiagnostics];
122
123
  return { stdout: adapter.encodeOutput(result, event.kind), exitCode: 0, stderr };
123
124
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Codex Tool Semantic Declaration — PRI-634-F R2 (review P1-2)
3
+ *
4
+ * PURPOSE: the Codex host layer of the Tool Semantic Registry. Codex names
5
+ * its shell tool `Bash` (capitalized — evidenced by the codex-adapter
6
+ * integration fixtures), which the core baseline's lowercase `bash` never
7
+ * matches: rules generated against the baseline name could pass replay and
8
+ * never fire on a real Codex event.
9
+ *
10
+ * EVIDENCE BOUND: this declaration contains only names with in-repo
11
+ * evidence — the installer's hook matcher `Bash|apply_patch`
12
+ * (create-principles-disciple/src/installers/codex-host-installer.ts:203,
13
+ * locked by codex-plugin-bundle.test.ts). Extending it with the remaining
14
+ * Codex tool surface is tracked as PRI-657 — a wrong guess would be worse
15
+ * than a gap (the reliability check rejects undeclared names, forcing
16
+ * correct names).
17
+ */
18
+ import { type ToolSemanticMappingV1, type ToolSemanticRegistry } from '@principles/core/runtime-v2';
19
+ export declare const CODEX_TOOL_SEMANTIC_MAPPINGS: readonly ToolSemanticMappingV1[];
20
+ export declare const CODEX_TOOL_SEMANTICS: ToolSemanticRegistry;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Codex Tool Semantic Declaration — PRI-634-F R2 (review P1-2)
3
+ *
4
+ * PURPOSE: the Codex host layer of the Tool Semantic Registry. Codex names
5
+ * its shell tool `Bash` (capitalized — evidenced by the codex-adapter
6
+ * integration fixtures), which the core baseline's lowercase `bash` never
7
+ * matches: rules generated against the baseline name could pass replay and
8
+ * never fire on a real Codex event.
9
+ *
10
+ * EVIDENCE BOUND: this declaration contains only names with in-repo
11
+ * evidence — the installer's hook matcher `Bash|apply_patch`
12
+ * (create-principles-disciple/src/installers/codex-host-installer.ts:203,
13
+ * locked by codex-plugin-bundle.test.ts). Extending it with the remaining
14
+ * Codex tool surface is tracked as PRI-657 — a wrong guess would be worse
15
+ * than a gap (the reliability check rejects undeclared names, forcing
16
+ * correct names).
17
+ */
18
+ import { buildToolSemanticRegistry } from '@principles/core/runtime-v2';
19
+ export const CODEX_TOOL_SEMANTIC_MAPPINGS = Object.freeze([
20
+ { rawToolName: 'Bash', canonicalKind: 'execute' },
21
+ { rawToolName: 'apply_patch', canonicalKind: 'write' },
22
+ ]);
23
+ const built = buildToolSemanticRegistry(CODEX_TOOL_SEMANTIC_MAPPINGS);
24
+ if (!built.ok) {
25
+ throw new Error(`[PD] Codex tool semantic declaration is invalid: ${built.errors.join('; ')}`);
26
+ }
27
+ export const CODEX_TOOL_SEMANTICS = built.registry;
@@ -45,15 +45,4 @@ export interface CodexWorkerStatusEvaluation {
45
45
  readonly reason?: string;
46
46
  readonly nextAction?: string;
47
47
  }
48
- /**
49
- * SPEC §15 worker mode, evaluated WITHOUT executing anything (no lease, no
50
- * LLM, no transcript I/O). `manual_action_required` means no
51
- * Companion-registered worker serves this workspace — the manual CLI path
52
- * (catch-up / diagnose / run-once) is the recovery route. 'ready' here means
53
- * "an automatic worker would run and hold the workspace task leases";
54
- * live-worker liveness surfacing belongs to the Slice D health surface.
55
- */
56
- export declare function computeCodexWorkerStatusMode(input: {
57
- workspaceDir: string;
58
- registeredInInstallManifest: boolean;
59
- }): CodexWorkerStatusEvaluation;
48
+ export { computeCodexWorkerStatusMode } from '@principles/host-runtime';
@@ -24,8 +24,9 @@
24
24
  import fs from 'node:fs';
25
25
  import path from 'node:path';
26
26
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime-v2';
27
- import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, } from '@principles/host-runtime';
27
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, saveHostToolDeclaration, } from '@principles/host-runtime';
28
28
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
29
+ import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
29
30
  const WORKER_OWNER = 'companion-worker';
30
31
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
31
32
  function workerLogger(logger) {
@@ -194,11 +195,24 @@ export async function runCodexWorkspaceWorkerCycle(options) {
194
195
  }
195
196
  // Step 7 — ONE bounded downstream consumer cycle via the shared executor
196
197
  // (same implementation the OpenClaw auto-consumer runs).
198
+ // PRI-634-F R2: persist the Codex tool declaration (workspace provenance
199
+ // for host-neutral consumers) and thread the registry into the cycle so
200
+ // activation-gate replay resolves Codex tool semantics (Bash, not bash).
201
+ const declared = saveHostToolDeclaration(workspaceDir, {
202
+ version: 1,
203
+ hostKind: 'codex',
204
+ mappings: CODEX_TOOL_SEMANTIC_MAPPINGS,
205
+ declaredAt: new Date().toISOString(),
206
+ });
207
+ if (!declared.ok) {
208
+ logger.warn?.(`[PD:CodexWorker] Failed to persist Codex tool declaration: ${declared.reason} — host-neutral consumers will not find it (rc-9)`);
209
+ }
197
210
  const downstream = await runInternalizationConsumerCycle(workspaceDir, {
198
211
  owner: WORKER_OWNER,
199
212
  logLabel: 'CodexWorker',
200
213
  logger,
201
214
  emitEvent,
215
+ toolSemantics: CODEX_TOOL_SEMANTICS,
202
216
  // No hostToolCatalog: PD has not declared a Codex tool catalog; a wrong
203
217
  // (OpenClaw) catalog would be worse than none (PRI-630 follow-up).
204
218
  });
@@ -220,37 +234,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
220
234
  report: { catchUp, reconcile, diagnostician, downstream },
221
235
  };
222
236
  }
223
- /**
224
- * SPEC §15 worker mode, evaluated WITHOUT executing anything (no lease, no
225
- * LLM, no transcript I/O). `manual_action_required` means no
226
- * Companion-registered worker serves this workspace — the manual CLI path
227
- * (catch-up / diagnose / run-once) is the recovery route. 'ready' here means
228
- * "an automatic worker would run and hold the workspace task leases";
229
- * live-worker liveness surfacing belongs to the Slice D health surface.
230
- */
231
- export function computeCodexWorkerStatusMode(input) {
232
- const workspaceDir = path.resolve(input.workspaceDir);
233
- if (!directoryExists(workspaceDir)) {
234
- return { mode: 'degraded', reason: 'workspace_missing', nextAction: 'The workspace directory does not exist; restore it or remove it from the install manifest.' };
235
- }
236
- const config = loadPdConfigForPlugin(workspaceDir);
237
- if (!config.ok) {
238
- const [first] = config.errors;
239
- return { mode: 'degraded', reason: `pd_config_invalid:${first?.reason ?? 'unknown'}`, nextAction: first?.nextAction ?? 'Repair .pd/config.yaml.' };
240
- }
241
- const { flags } = computeFeatureFlagsFromConfig(config.effective);
242
- if (flags['host.codex']?.enabled !== true) {
243
- return { mode: 'paused', reason: 'host.codex_disabled', nextAction: 'Set features.host.codex.enabled=true in the Workspace .pd/config.yaml to enable Codex PD behavior.' };
244
- }
245
- if (flags.internalization_auto_consumer?.enabled !== true) {
246
- return { mode: 'paused', reason: 'internalization_auto_consumer_disabled', nextAction: 'Automatic execution is paused; manual commands remain available: pd diagnose, pd runtime internalization run-once.' };
247
- }
248
- if (!input.registeredInInstallManifest) {
249
- return {
250
- mode: 'manual_action_required',
251
- reason: 'workspace_not_in_install_manifest',
252
- nextAction: `No Companion worker is registered for this workspace. Manual path: pd codex ingest catch-up --workspace "${workspaceDir}", then pd diagnose / pd runtime internalization run-once.`,
253
- };
254
- }
255
- return { mode: 'ready' };
256
- }
237
+ // Slice D (PRI-625): the mode authority moved to host-runtime so the CLI and
238
+ // Console §15 health surfaces share ONE semantics with the worker. Re-exported
239
+ // here for compatibility with every existing importer.
240
+ export { computeCodexWorkerStatusMode } from '@principles/host-runtime';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
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",