@principles/codex-adapter 0.15.0 → 0.16.0

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.
@@ -28,7 +28,7 @@
28
28
  * `tool_call` rows, or look-alike strings (SPEC TD §1.3).
29
29
  */
30
30
  import * as path from 'node:path';
31
- import { listGovernanceConversationTextsForHostTurn, readSourceMaterialAuthorization } from '@principles/host-runtime';
31
+ import { createConsentLedgerSourceMaterialAuthorization, listGovernanceConversationTextsForHostTurn, readSourceMaterialAuthorization } from '@principles/host-runtime';
32
32
  import { isSentinelSessionId } from '@principles/core/runtime';
33
33
  import { recoverTaskIdentityFromReceipt, validatePainSubmitReceipt, } from '@principles/core/runtime';
34
34
  import { isPainSubmitPostToolUseToolName } from '../codec/input-decoder.js';
@@ -205,7 +205,8 @@ export async function attemptPainReceiptFallback(input) {
205
205
  toolCallId,
206
206
  },
207
207
  authorization: { minimalMetadataGranted: input.minimalMetadataGranted },
208
- targetTurnTextAvailable: (hostSessionId, targetTurnId) => codexTargetTurnTextAvailable(normalizedWorkspace, hostSessionId, targetTurnId),
208
+ readTargetTurnEvidence: (hostSessionId, targetTurnId) => readCodexTargetTurnEvidence(normalizedWorkspace, hostSessionId, targetTurnId),
209
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(normalizedWorkspace),
209
210
  ...(input.now !== undefined ? { now: input.now } : {}),
210
211
  });
211
212
  return { status: 'attempted', outcome };
@@ -77,10 +77,18 @@ export interface CodexWorkerCycleOptions {
77
77
  /**
78
78
  * WHO drove this cycle (PRI-1264 attribution, Phase 2 extension). The
79
79
  * Service Host sets `PD_INVOCATION_SOURCE=service_host` on its Worker
80
- * children (shadow mode); without the third value the stall attribution
81
- * would misreport service-driven cycles as manual (TD §5.2).
80
+ * children; without the second value the stall attribution would misreport
81
+ * service-driven cycles as manual (TD §5.2).
82
+ *
83
+ * PRI-1278 Phase 5 (Companion-runtime removal): the companion worker driver
84
+ * is retired — there is no Companion runtime left that could legitimately
85
+ * produce it. A process still self-declaring `PD_INVOCATION_SOURCE=companion`
86
+ * (a legacy env leftover) is not authoritative: no resident supervisor backs
87
+ * it, so it is attributed as what it factually is — manual. Historical
88
+ * liveness records already persisted with `lastCycleDriver: 'companion'`
89
+ * stay readable as-is; they are durable facts and are never rewritten.
82
90
  */
83
- export declare function codexWorkerCycleDriver(): 'companion' | 'service_host' | 'manual';
91
+ export declare function codexWorkerCycleDriver(): 'service_host' | 'manual';
84
92
  export declare function readCodexWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
85
93
  /**
86
94
  * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
@@ -28,11 +28,16 @@
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
30
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, reconcileWaitingTargetEvidenceTasks, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
- import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
31
+ import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createConsentLedgerSourceMaterialAuthorization, resolveWorkspacePipelineHostDeps, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
32
32
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
33
33
  import { readCodexTargetTurnEvidence } from '../ingestion/pain-receipt-fallback.js';
34
34
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
35
- const WORKER_OWNER = 'companion-worker';
35
+ // PRI-1278 Phase 5 (Companion-runtime removal): the lease/consumer owner
36
+ // label for NEW writes is the Service Host worker identity — the PD Service
37
+ // Host is the only background runtime and spawns these bounded worker cycles.
38
+ // Historical lease records keep the retired 'companion-worker' string; they
39
+ // are durable facts and are deliberately NOT migrated.
40
+ const WORKER_OWNER = 'service-host-worker';
36
41
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
37
42
  /** CR-05 §9.1: bounded per-cycle post-processing continuation budget. */
38
43
  const DEFAULT_POST_PROCESSING_LIMIT = 2;
@@ -51,13 +56,19 @@ const LIVENESS_STAGE_DEADLINE_MS = {
51
56
  /**
52
57
  * WHO drove this cycle (PRI-1264 attribution, Phase 2 extension). The
53
58
  * Service Host sets `PD_INVOCATION_SOURCE=service_host` on its Worker
54
- * children (shadow mode); without the third value the stall attribution
55
- * would misreport service-driven cycles as manual (TD §5.2).
59
+ * children; without the second value the stall attribution would misreport
60
+ * service-driven cycles as manual (TD §5.2).
61
+ *
62
+ * PRI-1278 Phase 5 (Companion-runtime removal): the companion worker driver
63
+ * is retired — there is no Companion runtime left that could legitimately
64
+ * produce it. A process still self-declaring `PD_INVOCATION_SOURCE=companion`
65
+ * (a legacy env leftover) is not authoritative: no resident supervisor backs
66
+ * it, so it is attributed as what it factually is — manual. Historical
67
+ * liveness records already persisted with `lastCycleDriver: 'companion'`
68
+ * stay readable as-is; they are durable facts and are never rewritten.
56
69
  */
57
70
  export function codexWorkerCycleDriver() {
58
71
  const source = process.env.PD_INVOCATION_SOURCE;
59
- if (source === 'companion')
60
- return 'companion';
61
72
  if (source === 'service_host')
62
73
  return 'service_host';
63
74
  return 'manual';
@@ -66,9 +77,9 @@ export function codexWorkerCycleDriver() {
66
77
  * F13 (TD §5.2): the coordinator passes a unique invocation id; when
67
78
  * present it lands in the liveness record so the shared per-workspace file
68
79
  * can be correlated back to the exact Service Host invocation.
69
- * R5 review fix: a manual/companion cycle carries NO invocation id, so the
70
- * patch must CLEAR the field — otherwise a completed manual run would keep
71
- * masquerading under the previous shadow run's id.
80
+ * R5 review fix: a manual (non-Service-Host) cycle carries NO invocation
81
+ * id, so the patch must CLEAR the field — otherwise a completed manual run
82
+ * would keep masquerading under the previous shadow run's id.
72
83
  */
73
84
  function invocationIdLivenessPatch() {
74
85
  const invocationId = process.env.PD_INVOCATION_ID;
@@ -198,11 +209,13 @@ export async function runCodexWorkspaceWorkerCycle(options) {
198
209
  // PRI-1264 review round (2026-11-18): an intentional CONFIG pause must
199
210
  // keep the liveness heartbeat alive — the worker process IS alive and
200
211
  // cycling, it is just deliberately idle. Without this heartbeat the
201
- // Companion's stall detector (completion age > 2× interval) read the stale
202
- // pre-pause record and raised a false `workspace_worker_stalled`
203
- // notification whose "restart Companion" guidance could never fix the
204
- // config pause. The workspace directory and config were already proven
205
- // readable above (CR-08 ordering), so the write is legitimate.
212
+ // stall attribution reading this record (last-completed-cycle age —
213
+ // originally the retired Companion's detector, now the `pd codex worker
214
+ // --status` verdict and the Service Host health projection) read the
215
+ // stale pre-pause record and reported a deliberately idle worker as
216
+ // stalled — guidance no restart could ever fix, because the pause is
217
+ // config-intentional. The workspace directory and config were already
218
+ // proven readable above (CR-08 ordering), so the write is legitimate.
206
219
  writeLiveness(workspaceDir, {
207
220
  runningStage: 'paused',
208
221
  // Explicit null: a paused state has no in-flight stage, and the merge
@@ -221,9 +234,10 @@ export async function runCodexWorkspaceWorkerCycle(options) {
221
234
  runningStage: 'catch_up',
222
235
  stageDeadline: new Date(cycleStartedAt.getTime() + LIVENESS_STAGE_DEADLINE_MS.catch_up).toISOString(),
223
236
  // PRI-1264: record WHO drove this cycle. `pd codex worker --status` reads
224
- // the marker so the Owner can tell a companion-driven (resident, should
225
- // keep cycling) worker from a manual one-shot — "registered" alone said
226
- // nothing about whether a driver is actually alive.
237
+ // the marker so the Owner can tell a Service-Host-driven cycle (a bounded
238
+ // worker spawned by the OS-scheduled Service Host, expected to recur on
239
+ // its interval) from a manual one-shot — "registered" alone says nothing
240
+ // about whether a driver is actually alive.
227
241
  lastCycleDriver: codexWorkerCycleDriver(),
228
242
  });
229
243
  const consumerFlag = loadFeatureFlagFromConfig(workspaceDir, 'internalization_auto_consumer', { info: (m) => logger.info(m), warn: (m) => logger.warn(m) });
@@ -310,6 +324,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
310
324
  stateManager: handle.stateManager,
311
325
  readTargetTurnEvidence: (sessionId, turnId) => readCodexTargetTurnEvidence(path.resolve(workspaceDir), sessionId, turnId),
312
326
  sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(path.resolve(workspaceDir)),
327
+ hostKind: 'codex',
313
328
  nowIso: new Date().toISOString(),
314
329
  });
315
330
  if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.blocked > 0 || targetEvidenceReconcile.errors.length > 0) {
@@ -320,6 +335,26 @@ export async function runCodexWorkspaceWorkerCycle(options) {
320
335
  const stateDir = path.join(workspaceDir, '.state');
321
336
  let releaseBridge;
322
337
  try {
338
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2 (PRI-1292 Phase 2A): ONE assembly
339
+ // point for the five host collaborators. The trajectory reader and
340
+ // the source-material gate share the SAME consent-ledger
341
+ // authorization instance (previously two separate instances per
342
+ // call). PRI-1233 / SPEC §9.2: this worker is where Stage A
343
+ // actually runs for governance-admitted Codex pains; PRI-1265: the
344
+ // Stage A gets the bound session's ORIGINAL turns from the
345
+ // workspace's consent-tiered governance store.
346
+ const hostDeps = resolveWorkspacePipelineHostDeps({
347
+ workspaceDir,
348
+ effectiveConfig: config.effective,
349
+ telemetryPersistenceFailureHandler: (detail) => {
350
+ try {
351
+ emitEvent('CODEX_WORKER_CRITICAL_TELEMETRY_PERSIST_FAILED', detail);
352
+ }
353
+ catch {
354
+ // Telemetry persistence warnings must never fail the worker cycle.
355
+ }
356
+ },
357
+ });
323
358
  const bridge = await createPainSignalBridge({
324
359
  workspaceDir,
325
360
  stateDir,
@@ -327,18 +362,15 @@ export async function runCodexWorkspaceWorkerCycle(options) {
327
362
  owner: WORKER_OWNER,
328
363
  effectiveConfig: config.effective,
329
364
  getEnvVar: (name) => process.env[name],
330
- // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
331
- // for governance-admitted Codex pains — the neutral host reader
332
- // must ride along (flag-off = zero filesystem access inside it).
333
- intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
334
- // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
335
- // turns from the workspace's own consent-tiered governance store.
336
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
337
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
338
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
365
+ intentDocReader: hostDeps.intentDocReader,
366
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
367
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
368
+ // PRI-939 Option A: allowlisted runner/bridge events persist to
369
+ // the workspace sink instead of the unsubscribed singleton.
370
+ telemetrySink: hostDeps.telemetrySink,
339
371
  // SPEC §9.6: lazy probe — a revoked flag stops persisted
340
372
  // automatic_hook tasks at the bridge's execution boundary.
341
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
373
+ isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
342
374
  }, (release) => { releaseBridge = release; });
343
375
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
344
376
  // PRI-917 v0.3.3 review fix (P2-2): forward the parked-candidate
@@ -421,6 +453,22 @@ export async function runCodexWorkspaceWorkerCycle(options) {
421
453
  const stateDir = path.join(workspaceDir, '.state');
422
454
  let releaseBridge;
423
455
  try {
456
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2 (PRI-1292 Phase 2A): same single
457
+ // assembly point as the diagnosis site above — PRI-1265 authorized
458
+ // trajectory context, PRI-1283 R2 latest-consent gate, and the
459
+ // SAME consent-ledger authorization instance for both.
460
+ const hostDeps = resolveWorkspacePipelineHostDeps({
461
+ workspaceDir,
462
+ effectiveConfig: config.effective,
463
+ telemetryPersistenceFailureHandler: (detail) => {
464
+ try {
465
+ emitEvent('CODEX_WORKER_CRITICAL_TELEMETRY_PERSIST_FAILED', detail);
466
+ }
467
+ catch {
468
+ // Telemetry persistence warnings must never fail the worker cycle.
469
+ }
470
+ },
471
+ });
424
472
  const bridge = await createPainSignalBridge({
425
473
  workspaceDir,
426
474
  stateDir,
@@ -428,14 +476,15 @@ export async function runCodexWorkspaceWorkerCycle(options) {
428
476
  owner: WORKER_OWNER,
429
477
  effectiveConfig: config.effective,
430
478
  getEnvVar: (name) => process.env[name],
431
- // PRI-1265: post-processing resumes see the same authorized
432
- // trajectory context as the initial diagnosis run.
433
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
434
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
435
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
479
+ intentDocReader: hostDeps.intentDocReader,
480
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
481
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
482
+ // PRI-939 Option A: allowlisted runner/bridge events persist to
483
+ // the workspace sink instead of the unsubscribed singleton.
484
+ telemetrySink: hostDeps.telemetrySink,
436
485
  // SPEC §9.6: lazy probe — automatic_hook backlog resumes honor
437
486
  // the Workspace authorization too.
438
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
487
+ isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
439
488
  }, (release) => { releaseBridge = release; });
440
489
  for (const item of backlog) {
441
490
  const resumed = await bridge.resumeSucceededDiagnosisPostProcessing({ taskId: item.taskId });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
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": "^8.2.0",
37
- "@principles/host-runtime": "^4.7.0",
38
- "@principles/install-layout": "^0.11.0"
36
+ "@principles/core": "^8.4.0",
37
+ "@principles/host-runtime": "^4.8.0",
38
+ "@principles/install-layout": "^0.12.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": "06a20cb7842f41a6510937f92340343158164b9f"
55
+ "gitHead": "ff62137821c993773cc7df104a01625310776c51"
56
56
  }