@principles/codex-adapter 0.5.3 → 0.5.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.
package/LICENSE ADDED
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Principles Disciple
2
+ Copyright 2026 Principles Disciple Contributors
package/dist/index.d.ts CHANGED
@@ -21,5 +21,5 @@ export { catchUpCodexIngestion, CODEX_CATCH_UP_NEXT_ACTION } from './ingestion/c
21
21
  export type { CodexCatchUpOptions, CodexCatchUpResult, CodexCatchUpRolloutResult } from './ingestion/catch-up.js';
22
22
  export { locateCodexTranscriptByRolloutIdentity } from './ingestion/transcript-locate.js';
23
23
  export type { CodexTranscriptLookup } from './ingestion/transcript-locate.js';
24
- export { runCodexWorkspaceWorkerCycle, computeCodexWorkerStatusMode } from './worker/workspace-worker.js';
25
- export type { CodexWorkerMode, CodexWorkerCycleResult, CodexWorkerCycleStepReport, CodexWorkerCycleOptions, CodexWorkerStatusEvaluation } from './worker/workspace-worker.js';
24
+ export { runCodexWorkspaceWorkerCycle, computeCodexWorkerStatusMode, readCodexWorkerLiveness } from './worker/workspace-worker.js';
25
+ export type { CodexWorkerMode, CodexWorkerCycleResult, CodexWorkerCycleStepReport, CodexWorkerCycleOptions, CodexWorkerStatusEvaluation, CodexWorkerPostProcessingReport } from './worker/workspace-worker.js';
package/dist/index.js CHANGED
@@ -16,4 +16,4 @@ export { decodeTranscriptWindow, createNodeTranscriptPort, TranscriptReplacedErr
16
16
  // PRI-624 Slice C: bounded catch-up + per-workspace worker cycle.
17
17
  export { catchUpCodexIngestion, CODEX_CATCH_UP_NEXT_ACTION } from './ingestion/catch-up.js';
18
18
  export { locateCodexTranscriptByRolloutIdentity } from './ingestion/transcript-locate.js';
19
- export { runCodexWorkspaceWorkerCycle, computeCodexWorkerStatusMode } from './worker/workspace-worker.js';
19
+ export { runCodexWorkspaceWorkerCycle, computeCodexWorkerStatusMode, readCodexWorkerLiveness } from './worker/workspace-worker.js';
@@ -47,6 +47,15 @@ export function buildLiveToolCandidate(args) {
47
47
  hostTurnId: fields.turnId,
48
48
  toolName: fields.toolName ?? '',
49
49
  source: CODEX_POST_TOOL_USE_SOURCE,
50
+ // Merge semantics (WorkBuddy × SPEC-CODEX-PAIN-CLOSURE-001): the same host
51
+ // `tool_use_id` feeds TWO consumers, so the candidate carries both views.
52
+ // I1 identity parity — the live handler derives the canonical pain from the
53
+ // same tool_use_id, so `toolCallId` must be present (one real call → one
54
+ // canonical pain across the admission + dispatch deliveries).
55
+ toolCallId: fields.toolUseId,
56
+ // CR-01 — `toolUseId` is recorded into tool_calls.tool_use_id and used for
57
+ // the admission dedup join against the live PostToolUse row.
58
+ toolUseId: fields.toolUseId,
50
59
  ...(fields.toolInput !== undefined ? { toolInput: fields.toolInput } : {}),
51
60
  ...(fields.toolResponse !== undefined ? { toolOutput: fields.toolResponse } : {}),
52
61
  observedAt: new Date().toISOString(),
@@ -90,6 +99,13 @@ export function buildTranscriptCandidates(observations) {
90
99
  hostTurnId: observation.hostTurnId,
91
100
  toolName: typeof toolName === 'string' ? toolName : '',
92
101
  source: CODEX_POST_TOOL_USE_SOURCE,
102
+ // Merge semantics: both merged views of the same host tool_use_id.
103
+ // I1 identity parity — the decoded observation carries the same
104
+ // tool_use_id the live delivery derived its canonical pain from, so a
105
+ // transcript replay converges on that pain instead of a second one.
106
+ ...(typeof observation.toolUseId === 'string' && observation.toolUseId.length > 0 ? { toolCallId: observation.toolUseId } : {}),
107
+ // CR-01 — recorded into tool_calls.tool_use_id for the dedup join.
108
+ ...(observation.toolUseId !== undefined ? { toolUseId: observation.toolUseId } : {}),
93
109
  toolInput: own(facts, 'command') ?? null,
94
110
  ...(exitCode !== undefined ? { toolOutput: { exitCode, stdout: own(facts, 'stdout') ?? null, stderr: own(facts, 'stderr') ?? null } } : {}),
95
111
  observedAt: observation.observedAt,
@@ -3,9 +3,15 @@
3
3
  * Slice A; ADR-0020 §11.2 + G1 probe report §9).
4
4
  *
5
5
  * The G1 contract baseline is: minimum supported Codex 0.148.0, verified
6
- * on-device at 0.150.1. The transcript itself carries `session_meta.
7
- * payload.cli_version`, which is the version signal available inside a hook
8
- * subprocess (hook payloads carry no version field — G1 fixture contract).
6
+ * on-device at 0.150.1 and re-verified at 0.162.1 (PRI-953, 2026-10-13:
7
+ * on-device probe against real codex-cli 0.162.1 — 125/125 captured hook
8
+ * payloads decode, 8/8 real rollout transcripts ingest with only designed
9
+ * unknown-record-type skips; sanitized fixtures:
10
+ * tests/fixtures/g1-contract/hook-payloads/v0.162.1/ and
11
+ * transcripts/v0.162.1-tool-final-turn.jsonl). The transcript itself carries
12
+ * `session_meta.payload.cli_version`, which is the version signal available
13
+ * inside a hook subprocess (hook payloads carry no version field — G1
14
+ * fixture contract).
9
15
  *
10
16
  * Older-than-minimum and newer-than-verified versions both degrade
11
17
  * explicitly; an unknown version must never silently guess record fields.
@@ -13,7 +19,7 @@
13
19
  * refreshing the fixtures (G1 report §9 drift-detection boundary).
14
20
  */
15
21
  export declare const CODEX_INGESTION_MIN_VERSION = "0.148.0";
16
- export declare const CODEX_INGESTION_VERIFIED_VERSION = "0.150.1";
22
+ export declare const CODEX_INGESTION_VERIFIED_VERSION = "0.162.1";
17
23
  export type CodexVersionClassification = {
18
24
  status: 'supported';
19
25
  } | {
@@ -3,9 +3,15 @@
3
3
  * Slice A; ADR-0020 §11.2 + G1 probe report §9).
4
4
  *
5
5
  * The G1 contract baseline is: minimum supported Codex 0.148.0, verified
6
- * on-device at 0.150.1. The transcript itself carries `session_meta.
7
- * payload.cli_version`, which is the version signal available inside a hook
8
- * subprocess (hook payloads carry no version field — G1 fixture contract).
6
+ * on-device at 0.150.1 and re-verified at 0.162.1 (PRI-953, 2026-10-13:
7
+ * on-device probe against real codex-cli 0.162.1 — 125/125 captured hook
8
+ * payloads decode, 8/8 real rollout transcripts ingest with only designed
9
+ * unknown-record-type skips; sanitized fixtures:
10
+ * tests/fixtures/g1-contract/hook-payloads/v0.162.1/ and
11
+ * transcripts/v0.162.1-tool-final-turn.jsonl). The transcript itself carries
12
+ * `session_meta.payload.cli_version`, which is the version signal available
13
+ * inside a hook subprocess (hook payloads carry no version field — G1
14
+ * fixture contract).
9
15
  *
10
16
  * Older-than-minimum and newer-than-verified versions both degrade
11
17
  * explicitly; an unknown version must never silently guess record fields.
@@ -13,7 +19,7 @@
13
19
  * refreshing the fixtures (G1 report §9 drift-detection boundary).
14
20
  */
15
21
  export const CODEX_INGESTION_MIN_VERSION = '0.148.0';
16
- export const CODEX_INGESTION_VERIFIED_VERSION = '0.150.1';
22
+ export const CODEX_INGESTION_VERIFIED_VERSION = '0.162.1';
17
23
  export const CODEX_VERSION_NEXT_ACTION = 'rerun the Codex contract probe / update supported fixtures (docs/architecture/CODEX_G1_CONTRACT_PROBE_REPORT.md §9)';
18
24
  function isDigits(value) {
19
25
  return value.length > 0 && /^[0-9]+$/.test(value);
@@ -0,0 +1,48 @@
1
+ /** The exact prefix (fullwidth colon) defined by SPEC §6.4. */
2
+ export declare const CODEX_OWNER_STATEMENT_PREFIX = "PD\u8BB0\u5F55\u75DB\u82E6\uFF1A";
3
+ /** SPEC §6.1: reject instead of truncating the Owner's intent. */
4
+ export declare const MAX_OWNER_STATEMENT_CHARS = 500;
5
+ export type OwnerStatementPrefixParse = {
6
+ matched: false;
7
+ } | {
8
+ matched: true;
9
+ text: string | null;
10
+ reason?: 'statement_empty' | 'statement_too_long';
11
+ };
12
+ /**
13
+ * Deterministic prefix parse of the CURRENT user prompt. `text === null` means
14
+ * the prefix matched but the remainder was empty/blank — an explicit request
15
+ * with no content is a bounded rejection, never a fabricated statement.
16
+ */
17
+ export declare function parseOwnerStatementPrefix(prompt: unknown): OwnerStatementPrefixParse;
18
+ export type RecordOwnerStatementResult = {
19
+ status: 'received';
20
+ painId: string;
21
+ taskId: string;
22
+ disposition: 'admitted' | 'already_admitted';
23
+ logicalObservationKey: string;
24
+ /**
25
+ * SPEC §6.4.5: the durable task is what the receipt guarantees; evidence
26
+ * promotion may degrade (e.g. conversation ingestion off — no ingested
27
+ * rollout to promote from). The receipt discloses it instead of failing.
28
+ */
29
+ promotionDegraded?: string;
30
+ } | {
31
+ status: 'rejected';
32
+ reason: 'statement_empty' | 'statement_too_long' | 'transcript_unavailable' | 'lineage_invalid' | 'rate_limited' | 'continuation_failed';
33
+ nextAction: string;
34
+ };
35
+ /**
36
+ * Persist one explicit Owner statement. The consent-gated conversation
37
+ * ingestion flag does NOT gate this path (no conversation tables or transcript
38
+ * CONTENT are read — only the path is validated for the rollout identity),
39
+ * mirroring SPEC §6.4 rule 3.
40
+ */
41
+ export declare function recordExplicitOwnerStatement(args: {
42
+ rawPayload: unknown;
43
+ workspaceDir: string;
44
+ statementText: string;
45
+ env?: {
46
+ CODEX_HOME?: string | undefined;
47
+ };
48
+ }): Promise<RecordOwnerStatementResult>;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * SPEC-CODEX-PAIN-CLOSURE-001 CR-07 — the explicit Owner pain-report entry
3
+ * for Codex: the user types `PD记录痛苦:<反馈原文>` as the CURRENT message
4
+ * and this deterministic prefix parse turns exactly that text into one
5
+ * canonical pain signal through the existing governance admission +
6
+ * diagnostician-task continuation seams.
7
+ *
8
+ * Contract (SPEC §6.4):
9
+ * - ONLY an exact prefix match at the start of the CURRENT user prompt
10
+ * counts. Quoted text, tool output, model prose and ordinary corrections
11
+ * never trigger it (A17).
12
+ * - The statement is bounded at 500 chars (rejection, not truncation).
13
+ * - Identity comes from THIS hook payload's verified session/turn ids plus
14
+ * the transcript-path-derived rollout identity — the model never guesses
15
+ * ids and no other file is scanned.
16
+ * - The same logical observation key as the generic correction path
17
+ * (`codex|<rollout>|<turn>|user`) means explicit and generic detection of
18
+ * one turn converge on ONE canonical pain (unique marker dedup).
19
+ * - No LLM runs here: admission + durable enqueue only, well inside the
20
+ * 5s hook budget; the receipt carries painId/taskId.
21
+ */
22
+ import { admitGovernanceSignals, ensureGovernanceDiagnosticianTask, promoteAdmittedGovernanceEvidence, } from '@principles/host-runtime';
23
+ import { resolveCodexHome } from './codex-home.js';
24
+ import { validateCodexTranscriptPath } from './transcript-path.js';
25
+ import { extractFields } from './ingestion-fields.js';
26
+ /** The exact prefix (fullwidth colon) defined by SPEC §6.4. */
27
+ export const CODEX_OWNER_STATEMENT_PREFIX = 'PD记录痛苦:';
28
+ /** SPEC §6.1: reject instead of truncating the Owner's intent. */
29
+ export const MAX_OWNER_STATEMENT_CHARS = 500;
30
+ /**
31
+ * Deterministic prefix parse of the CURRENT user prompt. `text === null` means
32
+ * the prefix matched but the remainder was empty/blank — an explicit request
33
+ * with no content is a bounded rejection, never a fabricated statement.
34
+ */
35
+ export function parseOwnerStatementPrefix(prompt) {
36
+ if (typeof prompt !== 'string')
37
+ return { matched: false };
38
+ if (!prompt.startsWith(CODEX_OWNER_STATEMENT_PREFIX))
39
+ return { matched: false };
40
+ const remainder = prompt.slice(CODEX_OWNER_STATEMENT_PREFIX.length).trim();
41
+ if (remainder.length === 0)
42
+ return { matched: true, text: null, reason: 'statement_empty' };
43
+ if (remainder.length > MAX_OWNER_STATEMENT_CHARS)
44
+ return { matched: true, text: null, reason: 'statement_too_long' };
45
+ return { matched: true, text: remainder };
46
+ }
47
+ /**
48
+ * Persist one explicit Owner statement. The consent-gated conversation
49
+ * ingestion flag does NOT gate this path (no conversation tables or transcript
50
+ * CONTENT are read — only the path is validated for the rollout identity),
51
+ * mirroring SPEC §6.4 rule 3.
52
+ */
53
+ export async function recordExplicitOwnerStatement(args) {
54
+ const fields = extractFields(args.rawPayload);
55
+ if (fields === null || fields.sessionId.length === 0 || fields.turnId === null) {
56
+ return { status: 'rejected', reason: 'lineage_invalid', nextAction: 'The hook payload lacks the session/turn identity this explicit submission requires; nothing was recorded.' };
57
+ }
58
+ if (fields.transcriptPath === null) {
59
+ return { status: 'rejected', reason: 'transcript_unavailable', nextAction: 'Codex supplied no transcript path for this event; the explicit statement was NOT recorded — resubmit it in a new message.' };
60
+ }
61
+ const home = resolveCodexHome(args.env);
62
+ if (!home.ok) {
63
+ return { status: 'rejected', reason: 'transcript_unavailable', nextAction: `${home.reason}: ${home.nextAction}`.slice(0, 400) };
64
+ }
65
+ const validated = validateCodexTranscriptPath(fields.transcriptPath, home.home);
66
+ if (!validated.ok) {
67
+ return { status: 'rejected', reason: 'lineage_invalid', nextAction: `${validated.reason}: ${validated.nextAction}`.slice(0, 400) };
68
+ }
69
+ const candidate = {
70
+ kind: 'user_correction',
71
+ hostKind: 'codex',
72
+ logicalObservationKey: `codex|${validated.rolloutIdentity}|${fields.turnId}|user`,
73
+ rolloutIdentity: validated.rolloutIdentity,
74
+ rootSessionId: fields.sessionId,
75
+ hostTurnId: fields.turnId,
76
+ text: args.statementText,
77
+ observedAt: new Date().toISOString(),
78
+ explicitOwnerStatement: true,
79
+ };
80
+ const admitted = admitGovernanceSignals({ workspaceDir: args.workspaceDir, candidates: [candidate] });
81
+ if (!admitted.ok) {
82
+ return { status: 'rejected', reason: 'continuation_failed', nextAction: `${admitted.reason}: ${admitted.nextAction}`.slice(0, 400) };
83
+ }
84
+ const [outcome] = admitted.outcomes;
85
+ if (outcome === undefined || !('disposition' in outcome)) {
86
+ return { status: 'rejected', reason: 'continuation_failed', nextAction: 'The governance admission returned no disposition; nothing was recorded.' };
87
+ }
88
+ if (outcome.disposition === 'not_a_signal' || outcome.disposition === 'not_admitted') {
89
+ return { status: 'rejected', reason: 'continuation_failed', nextAction: 'reason' in outcome ? String(outcome.reason) : 'the signal was not admitted' };
90
+ }
91
+ if (outcome.disposition === 'rate_limited') {
92
+ return { status: 'rejected', reason: 'rate_limited', nextAction: 'The per-root-session correction quota (5/hour) is exhausted; resubmit later — the statement was NOT recorded.' };
93
+ }
94
+ // Task ensure is the receipt's hard guarantee; evidence promotion is
95
+ // best-effort (SPEC §6.4.5 — a degraded promotion is disclosed, never a
96
+ // failed receipt: the pain + task are durably recorded).
97
+ const ensured = await ensureGovernanceDiagnosticianTask({
98
+ workspaceDir: args.workspaceDir,
99
+ logicalObservationKey: candidate.logicalObservationKey,
100
+ canonicalPainId: outcome.canonicalPainId,
101
+ });
102
+ if (!ensured.ok) {
103
+ return { status: 'rejected', reason: 'continuation_failed', nextAction: `${ensured.reason}: ${ensured.nextAction}`.slice(0, 400) };
104
+ }
105
+ let promotionDegraded;
106
+ const promoted = promoteAdmittedGovernanceEvidence({
107
+ workspaceDir: args.workspaceDir,
108
+ rolloutIdentity: validated.rolloutIdentity,
109
+ triggerLogicalKey: candidate.logicalObservationKey,
110
+ canonicalPainId: outcome.canonicalPainId,
111
+ });
112
+ if (!promoted.ok) {
113
+ promotionDegraded = `${promoted.reason}`.slice(0, 160);
114
+ }
115
+ return {
116
+ status: 'received',
117
+ painId: outcome.canonicalPainId,
118
+ taskId: ensured.taskId,
119
+ disposition: outcome.disposition === 'already_admitted' ? 'already_admitted' : 'admitted',
120
+ logicalObservationKey: candidate.logicalObservationKey,
121
+ ...(promotionDegraded !== undefined ? { promotionDegraded } : {}),
122
+ };
123
+ }
@@ -1,4 +1,4 @@
1
- import { ingestGovernanceObservations, readGovernanceCheckpoint, } from '@principles/host-runtime';
1
+ import { ingestGovernanceObservations, readGovernanceCheckpoint, recordVerifiedToolOutcomes, } from '@principles/host-runtime';
2
2
  import { resolveCodexHome } from './codex-home.js';
3
3
  import { validateCodexTranscriptPath } from './transcript-path.js';
4
4
  import { classifyCodexVersion, CODEX_VERSION_NEXT_ACTION } from './codex-version.js';
@@ -70,6 +70,43 @@ function ingestLiveObservation({ fields, rolloutIdentity, workspaceDir, now }) {
70
70
  rolloutIdentity,
71
71
  };
72
72
  }
73
+ /**
74
+ * SPEC-CODEX-PAIN-CLOSURE-001 CR-01: project decoded CommandExecution facts
75
+ * onto the shared verified-outcome upgrade. The transcript's model-level call
76
+ * name for the shell tool is `exec` while the PostToolUse hook names it
77
+ * `Bash` (g1 fixture 04-post-tool-use.json ↔ normal-tool-final-turn.jsonl,
78
+ * same tool_use_id) — the host-specific mapping stays here in the adapter.
79
+ */
80
+ function collectVerifiedToolOutcomes(observations) {
81
+ const outcomes = [];
82
+ for (const observation of observations) {
83
+ if (observation.kind !== 'tool_call' || observation.toolUseId === undefined)
84
+ continue;
85
+ const facts = observation.toolFacts;
86
+ if (typeof facts !== 'object' || facts === null || Array.isArray(facts))
87
+ continue;
88
+ const { exitCode } = facts;
89
+ if (typeof exitCode !== 'number' || !Number.isInteger(exitCode))
90
+ continue;
91
+ const rawName = facts.toolName;
92
+ const toolName = rawName === 'exec' || typeof rawName !== 'string' || rawName.length === 0 ? 'Bash' : rawName;
93
+ const { stdout } = facts;
94
+ const { stderr } = facts;
95
+ const previewParts = [];
96
+ if (typeof stderr === 'string' && stderr.length > 0)
97
+ previewParts.push(stderr);
98
+ if (typeof stdout === 'string' && stdout.length > 0)
99
+ previewParts.push(stdout);
100
+ outcomes.push({
101
+ toolUseId: observation.toolUseId,
102
+ toolName,
103
+ params: facts.command ?? undefined,
104
+ exitCode,
105
+ ...(previewParts.length > 0 ? { outputPreview: previewParts.join('\n') } : {}),
106
+ });
107
+ }
108
+ return outcomes;
109
+ }
73
110
  function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity, rolloutIdentity, workspaceDir, now, port }) {
74
111
  const checkpoint = readGovernanceCheckpoint({ workspaceDir, hostKind: 'codex', rolloutIdentity });
75
112
  if (checkpoint !== null && !('byteOffset' in checkpoint) && 'ok' in checkpoint && checkpoint.ok === false) {
@@ -126,6 +163,18 @@ function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity,
126
163
  degradations.push({ reason: 'transcript_record_too_large', nextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.' });
127
164
  }
128
165
  const rootSessionId = decoded.rolloutMeta.rootSessionId ?? existing?.rootSessionId ?? fallbackRootSessionId;
166
+ // CR-01: upgrade text-only live observations with the host-verified exit
167
+ // codes BEFORE the checkpoint advances, so a write failure holds the delta
168
+ // and the next Stop retries instead of silently losing the verified facts.
169
+ const verifiedOutcomes = collectVerifiedToolOutcomes(decoded.observations);
170
+ if (verifiedOutcomes.length > 0) {
171
+ const verified = recordVerifiedToolOutcomes({ workspaceDir, sessionId: rootSessionId, outcomes: verifiedOutcomes });
172
+ const failed = verified.find((result) => result.status === 'unavailable');
173
+ if (failed !== undefined) {
174
+ const reason = failed.reason === 'trajectory_db_not_found' ? 'verified_outcome_db_unavailable' : `verified_outcome_write_failed:${failed.reason.split(':', 2)[1] ?? ''}`;
175
+ return { status: 'degraded', reason, nextAction: 'inspect the workspace trajectory database; the transcript checkpoint was NOT advanced, the next Stop retries this delta.', warnings: decoded.warnings };
176
+ }
177
+ }
129
178
  const result = ingestGovernanceObservations({
130
179
  workspaceDir,
131
180
  rollout: {
package/dist/pd-hook.js CHANGED
@@ -12,6 +12,7 @@ import { CodexHooksHostAdapter } from './host-adapter.js';
12
12
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
13
13
  import { ingestCodexConversation } from './ingestion/ingestion.js';
14
14
  import { runGovernanceAdmission } from './ingestion/admission.js';
15
+ import { parseOwnerStatementPrefix, recordExplicitOwnerStatement } from './ingestion/explicit-owner-statement.js';
15
16
  import { recordCodexPromptDeliveryEvidence, recordCodexDenyEvidence } from './codex-evidence-recorder.js';
16
17
  const MAX_DIAGNOSTIC = 500;
17
18
  function diagnostic(reason, nextAction) {
@@ -190,9 +191,15 @@ async function runConversationIngestion(args) {
190
191
  // Slice B admission: hook awaits only admission + durable enqueue —
191
192
  // never an LLM (SPEC §12/§13). Ordinary conversation returns no
192
193
  // candidates/no admissions and stays completely silent.
194
+ // CR-07: when the explicit Owner-statement entry already handled this
195
+ // turn's prompt, its generic correction candidate is suppressed so the
196
+ // observation passes through exactly one pain writer.
197
+ const candidates = args.suppressCorrectionCandidate === true
198
+ ? outcome.admissionCandidates.filter((candidate) => candidate.kind !== 'user_correction')
199
+ : outcome.admissionCandidates;
193
200
  const admission = await runGovernanceAdmission({
194
201
  workspaceDir,
195
- candidates: outcome.admissionCandidates,
202
+ candidates,
196
203
  });
197
204
  for (const degradation of admission.degradations.slice(0, 2)) {
198
205
  diagnostics.push(diagnostic(degradation.reason, degradation.nextAction));
@@ -276,8 +283,53 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
276
283
  return { stdout: {}, exitCode: 0, stderr: [diagnostic(health.reason ?? 'runtime_unhealthy', health.nextAction ?? 'Inspect the Workspace runtime.')] };
277
284
  return { stdout: adapter.encodeOutput({ decision: 'allow', source: event.source }, 'session_start'), exitCode: 0, stderr: [] };
278
285
  }
286
+ // SPEC-CODEX-PAIN-CLOSURE-001 CR-07: the explicit Owner statement entry
287
+ // runs FIRST for the current user prompt — before the generic correction
288
+ // detection, so the same turn can never pass through two pain writers
289
+ // (the shared unique observation key dedups any replay). Works regardless
290
+ // of the codex_conversation_ingestion flag: only the transcript PATH is
291
+ // validated (rollout identity), never conversation content.
292
+ let explicitReceiptContext;
293
+ let explicitSuppressedGeneric = false;
294
+ const explicitDiagnostics = [];
295
+ if (event.kind === 'before_prompt_build') {
296
+ const rawRecord = parsed;
297
+ const prefixParse = parseOwnerStatementPrefix(typeof rawRecord?.prompt === 'string' ? rawRecord.prompt : undefined);
298
+ if (prefixParse.matched) {
299
+ explicitSuppressedGeneric = true;
300
+ if (prefixParse.text === null) {
301
+ explicitDiagnostics.push(diagnostic(`owner_statement_${prefixParse.reason ?? 'rejected'}`, prefixParse.reason === 'statement_too_long'
302
+ ? `The statement exceeds 500 characters; nothing was recorded. Resubmit within the limit.`
303
+ : 'The prefix carried no statement text; nothing was recorded. Resubmit as PD记录痛苦:<反馈原文>.'));
304
+ }
305
+ else {
306
+ const receipt = await recordExplicitOwnerStatement({
307
+ rawPayload: parsed,
308
+ workspaceDir: resolution.workspaceDir,
309
+ statementText: prefixParse.text,
310
+ env: _env,
311
+ });
312
+ if (receipt.status === 'received') {
313
+ explicitReceiptContext = `[PD] 已收到痛苦反馈(painId=${receipt.painId}, taskId=${receipt.taskId}${receipt.disposition === 'already_admitted' ? ', 重复提交已合并为同一信号' : ''})。后台将自动诊断;请在回复中如实转述本回执,不要声称仍在等待用户输入,也不要虚构诊断结论。${receipt.promotionDegraded !== undefined ? `(注意:会话证据提升暂不可用:${receipt.promotionDegraded};诊断仍会基于你提交的陈述进行。)` : ''}`;
314
+ explicitDiagnostics.push(diagnostic(`owner_statement_received:${receipt.painId}:${receipt.taskId}${receipt.promotionDegraded !== undefined ? `:promotion_degraded:${receipt.promotionDegraded}` : ''}`, 'Durable enqueue complete; the workspace worker continues diagnosis in the background.'));
315
+ }
316
+ else {
317
+ explicitDiagnostics.push(diagnostic(`owner_statement_${receipt.reason}`, receipt.nextAction));
318
+ }
319
+ }
320
+ }
321
+ }
279
322
  const ingestionDiagnostics = ingestionEnabled
280
- ? await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })
323
+ ? await runConversationIngestion({
324
+ rawPayload: parsed,
325
+ kind: event.kind,
326
+ workspaceDir: resolution.workspaceDir,
327
+ env: _env,
328
+ // CR-07: the explicit path already handled this turn's user prompt —
329
+ // suppress the generic correction candidate so exactly one writer
330
+ // processed the observation (A17).
331
+ ...(explicitSuppressedGeneric && event.kind === 'before_prompt_build' ? { suppressCorrectionCandidate: true } : {}),
332
+ })
281
333
  : [];
282
334
  // PD v2 Phase 1: evidence context for this subprocess invocation. The
283
335
  // ledger flag follows the OpenClaw convention (principle_receipt_ledger
@@ -314,6 +366,17 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
314
366
  // v2 enforcement is suspended (PRI-780); wired honestly for the day it
315
367
  // is not.
316
368
  const encoded = adapter.encodeOutput(result, event.kind);
369
+ // CR-07 (A16): the explicit-statement receipt rides as additional context
370
+ // so the model can answer truthfully about what happened (received +
371
+ // queued), instead of guessing or claiming it is still waiting for input.
372
+ if (explicitReceiptContext !== undefined && event.kind === 'before_prompt_build') {
373
+ const output = encoded;
374
+ if (output.hookSpecificOutput !== undefined) {
375
+ output.hookSpecificOutput.additionalContext = output.hookSpecificOutput.additionalContext !== undefined
376
+ ? `${output.hookSpecificOutput.additionalContext}\n${explicitReceiptContext}`
377
+ : explicitReceiptContext;
378
+ }
379
+ }
317
380
  if (result.decision === 'deny') {
318
381
  try {
319
382
  let liveActivationId;
@@ -356,7 +419,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
356
419
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
357
420
  }
358
421
  }
359
- const stderr = [...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics];
422
+ const stderr = [...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...explicitDiagnostics, ...ingestionDiagnostics];
360
423
  return { stdout: encoded, exitCode: 0, stderr };
361
424
  }
362
425
  catch (error) {
@@ -2,9 +2,22 @@ import { type InternalizationConsumerCycleOutcome, type ConsumerCycleLogger, typ
2
2
  import { type CodexCatchUpResult } from '../ingestion/catch-up.js';
3
3
  import type { TranscriptPort } from '../ingestion/transcript-decoder.js';
4
4
  export type CodexWorkerMode = 'ready' | 'manual_action_required' | 'paused' | 'degraded';
5
+ export interface CodexWorkerPostProcessingReport {
6
+ readonly resumedTaskIds: readonly string[];
7
+ readonly processedCount: number;
8
+ /** Eligible-after-this-cycle backlog size (oldest-first scan is bounded). */
9
+ readonly remainingCount: number;
10
+ readonly oldestAgeMs: number | null;
11
+ readonly blocked: readonly {
12
+ candidateId: string;
13
+ reason: string;
14
+ }[];
15
+ }
5
16
  export interface CodexWorkerCycleStepReport {
6
17
  readonly catchUp: CodexCatchUpResult;
7
18
  readonly reconcile: ReconcileGovernanceContinuationResult;
19
+ /** CR-05: succeeded-diagnosis post-processing continuation (no LLM). */
20
+ readonly postProcessing: CodexWorkerPostProcessingReport | null;
8
21
  /** At most ONE diagnostician execution per cycle (bounded work). */
9
22
  readonly diagnostician: {
10
23
  readonly taskId: string;
@@ -41,6 +54,7 @@ export interface CodexWorkerCycleOptions {
41
54
  /** Cap on diagnostician candidates inspected per cycle (default 5). */
42
55
  readonly diagnosticianCandidateLimit?: number;
43
56
  }
57
+ export declare function readCodexWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
44
58
  /**
45
59
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
46
60
  * every failure becomes a structured degraded result with a nextAction.
@@ -9,6 +9,10 @@
9
9
  * 3. lease + run one Diagnostician task, then ONE bounded downstream
10
10
  * consumer cycle through the SHARED host-neutral executor
11
11
  * (internalization_auto_consumer = workspace execution authority)
12
+ * 4. SPEC-CODEX-PAIN-CLOSURE-001 CR-05: continue the post-processing of
13
+ * succeeded diagnoses (pending candidates, intake/seed orphans) WITHOUT
14
+ * re-running the diagnosis LLM; CR-08: persist cycle liveness facts
15
+ * (readiness is computed elsewhere and never implies liveness).
12
16
  *
13
17
  * Every step reuses existing authority: catch-up reuses the Slice A/B
14
18
  * ingestion + admission seams, reconciliation reuses
@@ -29,6 +33,29 @@ import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
29
33
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
30
34
  const WORKER_OWNER = 'companion-worker';
31
35
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
36
+ /** CR-05 §9.1: bounded per-cycle post-processing continuation budget. */
37
+ const DEFAULT_POST_PROCESSING_LIMIT = 2;
38
+ /** CR-08 §9.3: liveness facts are worker-owned runtime state (not governance truth). */
39
+ function isPlainRecord(value) {
40
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
41
+ }
42
+ const LIVENESS_FILE = 'codex-worker-liveness.json';
43
+ const LIVENESS_STAGE_DEADLINE_MS = {
44
+ catch_up: 5 * 60_000,
45
+ reconcile: 5 * 60_000,
46
+ diagnosis_execution: 15 * 60_000,
47
+ post_processing: 5 * 60_000,
48
+ downstream_cycle: 10 * 60_000,
49
+ };
50
+ export function readCodexWorkerLiveness(workspaceDir) {
51
+ try {
52
+ const parsed = JSON.parse(fs.readFileSync(path.join(path.resolve(workspaceDir), '.state', LIVENESS_FILE), 'utf8'));
53
+ return isPlainRecord(parsed) ? parsed : null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
32
59
  function workerLogger(logger) {
33
60
  return logger ?? {
34
61
  info: () => undefined,
@@ -44,6 +71,46 @@ function directoryExists(dir) {
44
71
  return false;
45
72
  }
46
73
  }
74
+ function writeLiveness(workspaceDir, patch) {
75
+ try {
76
+ const root = path.resolve(workspaceDir);
77
+ const stateDir = path.join(root, '.state');
78
+ const file = path.join(stateDir, LIVENESS_FILE);
79
+ // The subpath is a constant, so containment always holds — the explicit
80
+ // check keeps the write boundary auditable (defense in depth).
81
+ if (!file.startsWith(root + path.sep))
82
+ return;
83
+ if (!directoryExists(stateDir))
84
+ fs.mkdirSync(stateDir, { recursive: true });
85
+ let current = {};
86
+ try {
87
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
88
+ if (isPlainRecord(parsed))
89
+ current = parsed;
90
+ }
91
+ catch {
92
+ current = {};
93
+ }
94
+ const merged = { ...current, ...patch, updatedAt: new Date().toISOString() };
95
+ // CodeQL (insecure temporary file): the fixed predictable `.tmp` name is a
96
+ // symlink-swap surface in a shared state dir. Write+rename through an
97
+ // EXCLUSIVE random temp file in the same directory (O_EXCL | 0600) — the
98
+ // rename stays atomic within the directory.
99
+ const tmp = path.join(stateDir, `${LIVENESS_FILE}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 10)}.tmp`);
100
+ const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
101
+ try {
102
+ fs.writeFileSync(fd, JSON.stringify(merged));
103
+ }
104
+ finally {
105
+ fs.closeSync(fd);
106
+ }
107
+ fs.renameSync(tmp, file);
108
+ }
109
+ catch {
110
+ // liveness bookkeeping must never break the cycle (rc-9: the cycle report
111
+ // itself remains the observable degradation channel)
112
+ }
113
+ }
47
114
  /**
48
115
  * Oldest pending diagnostician first; retry_wait candidates are filtered to
49
116
  * those whose backoff window has ELAPSED, so an old-but-still-waiting task
@@ -51,18 +118,42 @@ function directoryExists(dir) {
51
118
  * bounded (`limit`), and executePendingDiagnosis re-enforces the backoff
52
119
  * window on the chosen task — no double bookkeeping.
53
120
  */
54
- async function pickDiagnosticianCandidate(stateManager, limit) {
121
+ const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
122
+ /**
123
+ * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
124
+ * continuously-eligible classes; neither may starve the other while new
125
+ * pending signals keep arriving. A persistent round-robin cursor (stored in
126
+ * the existing reconciliation_cursor authority, so a worker restart does NOT
127
+ * reset it to pending-priority) alternates service between the two classes —
128
+ * each eligible class is served at least every other cycle, well inside the
129
+ * 3-full-cycle bound. Single-eligible work is always served.
130
+ */
131
+ async function pickDiagnosticianCandidate(stateManager, limit, nowIso) {
55
132
  const pending = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'pending', orderBy: 'updated_at_asc', limit });
56
- const [first] = pending;
57
- if (first !== undefined)
58
- return first;
133
+ const [pendingTask] = pending;
134
+ let retryTask = null;
59
135
  const retrying = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit });
60
136
  for (const candidate of retrying) {
61
137
  if (isRetryWaitBackoffElapsed(candidate.status, candidate.leaseExpiresAt)) {
62
- return candidate;
138
+ retryTask = candidate;
139
+ break;
63
140
  }
64
141
  }
65
- return null;
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;
66
157
  }
67
158
  /**
68
159
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
@@ -73,6 +164,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
73
164
  const logger = workerLogger(options.logger);
74
165
  const emitEvent = options.emitEvent ?? ((_event, _payload) => undefined);
75
166
  const base = { workspaceDir };
167
+ const cycleStartedAt = new Date();
76
168
  // Step 1 — Workspace eligibility.
77
169
  if (!directoryExists(workspaceDir)) {
78
170
  return { ...base, mode: 'degraded', reason: 'workspace_missing', nextAction: 'The workspace directory no longer exists; remove it from the install manifest or restore it. No PD state was mutated.' };
@@ -86,6 +178,13 @@ export async function runCodexWorkspaceWorkerCycle(options) {
86
178
  if (flags['host.codex']?.enabled !== true) {
87
179
  return { ...base, mode: 'paused', reason: 'host.codex_disabled', nextAction: 'Set features.host.codex.enabled=true in the Workspace .pd/config.yaml to enable Codex PD behavior.' };
88
180
  }
181
+ // CR-08: liveness bookkeeping starts only after the workspace proved
182
+ // eligible — writing into a missing workspace directory would fabricate it.
183
+ writeLiveness(workspaceDir, {
184
+ lastCycleStartedAt: cycleStartedAt.toISOString(),
185
+ runningStage: 'catch_up',
186
+ stageDeadline: new Date(cycleStartedAt.getTime() + LIVENESS_STAGE_DEADLINE_MS.catch_up).toISOString(),
187
+ });
89
188
  const consumerFlag = loadFeatureFlagFromConfig(workspaceDir, 'internalization_auto_consumer', { info: (m) => logger.info(m), warn: (m) => logger.warn(m) });
90
189
  // PRI-638 P1-C: the Diagnostician capability gate is resolved from the same
91
190
  // canonical authority the runtime factory uses. An Owner-disabled agent is
@@ -128,7 +227,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
128
227
  mode: 'paused',
129
228
  reason: 'internalization_auto_consumer_disabled',
130
229
  nextAction: 'Automatic internalization execution is paused for this Workspace; manual commands remain available: pd diagnose, pd runtime internalization run-once.',
131
- report: { catchUp, reconcile, diagnostician: null, downstream: null },
230
+ report: { catchUp, reconcile, postProcessing: null, diagnostician: null, downstream: null },
132
231
  };
133
232
  }
134
233
  else {
@@ -144,7 +243,7 @@ export async function runCodexWorkspaceWorkerCycle(options) {
144
243
  if (sweep.recovered > 0 || sweep.errors.length > 0) {
145
244
  emitEvent('CODEX_WORKER_RECOVERY_SWEEP', JSON.stringify({ recovered: sweep.recovered, failed: sweep.errors.length }));
146
245
  }
147
- const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
246
+ const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT, new Date().toISOString());
148
247
  if (candidate !== null) {
149
248
  const stateDir = path.join(workspaceDir, '.state');
150
249
  const bridge = await createPainSignalBridge({
@@ -196,7 +295,82 @@ export async function runCodexWorkspaceWorkerCycle(options) {
196
295
  mode: 'degraded',
197
296
  reason: `diagnostician_execution_failed:${detail}`,
198
297
  nextAction: 'Inspect the Workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
199
- report: { catchUp, reconcile, diagnostician: null, downstream: null },
298
+ report: { catchUp, reconcile, postProcessing: null, diagnostician: null, downstream: null },
299
+ };
300
+ }
301
+ }
302
+ // Step 6b — SPEC-CODEX-PAIN-CLOSURE-001 CR-05 (SPEC §9.1): continue the
303
+ // post-processing of SUCCEEDED diagnoses (candidates stuck before
304
+ // admission/intake/seed — the original incident shape) without re-running
305
+ // the diagnosis LLM. Runs in the SAME consumer-flag authority as fresh
306
+ // diagnoses; every class (pending / due-retry / post-processing) is served
307
+ // every cycle it has eligible work, so no class can starve another
308
+ // (SPEC §9.1: each eligible class served within 3 full cycles).
309
+ let postProcessing = null;
310
+ writeLiveness(workspaceDir, { runningStage: 'post_processing', stageDeadline: new Date(Date.now() + LIVENESS_STAGE_DEADLINE_MS.post_processing).toISOString() });
311
+ if (consumerFlag.enabled && !diagnosticianDisabled) {
312
+ try {
313
+ const handle = await createRuntimeStateHandle({ workspaceDir, readonly: false });
314
+ try {
315
+ const { eligible: backlog, corrupt } = await handle.stateManager.listDiagnosisPostProcessingBacklog({ limit: DEFAULT_POST_PROCESSING_LIMIT });
316
+ const { eligible: backlogAll, corrupt: corruptAll } = await handle.stateManager.listDiagnosisPostProcessingBacklog({ limit: 200 });
317
+ const oldestCreatedAt = backlogAll[0]?.createdAt;
318
+ const blocked = [];
319
+ // SPEC review round-4 P1: corrupt admission_json rows are surfaced as a
320
+ // candidate-level queryable blocker — never deleted, never eligible for
321
+ // writes, never blocking healthy work (the scan filters via json_valid).
322
+ for (const item of corruptAll) {
323
+ blocked.push({ candidateId: item.candidateId, reason: 'admission_json_corrupt: repair or re-run the diagnosis (pd candidate show reports the unreadable disposition)' });
324
+ }
325
+ const resumedTaskIds = new Set();
326
+ if (backlog.length > 0) {
327
+ const stateDir = path.join(workspaceDir, '.state');
328
+ const bridge = await createPainSignalBridge({
329
+ workspaceDir,
330
+ stateDir,
331
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
332
+ owner: WORKER_OWNER,
333
+ effectiveConfig: config.effective,
334
+ getEnvVar: (name) => process.env[name],
335
+ });
336
+ for (const item of backlog) {
337
+ const resumed = await bridge.resumeSucceededDiagnosisPostProcessing({ taskId: item.taskId });
338
+ if (resumed.status === 'resumed') {
339
+ resumedTaskIds.add(item.taskId);
340
+ }
341
+ else if (resumed.status === 'blocked') {
342
+ blocked.push({ candidateId: item.candidateId, reason: resumed.reason ?? 'blocked' });
343
+ }
344
+ for (const skip of resumed.skipped ?? [])
345
+ blocked.push(skip);
346
+ }
347
+ }
348
+ postProcessing = {
349
+ resumedTaskIds: [...resumedTaskIds],
350
+ processedCount: backlog.length,
351
+ remainingCount: Math.max(0, backlogAll.length - backlog.length),
352
+ oldestAgeMs: oldestCreatedAt !== undefined ? Math.max(0, Date.now() - Date.parse(oldestCreatedAt)) : null,
353
+ blocked,
354
+ };
355
+ if (corrupt.length > 0) {
356
+ emitEvent('CODEX_WORKER_ADMISSION_CORRUPT', JSON.stringify({ candidateIds: corruptAll.map((c) => c.candidateId) }));
357
+ }
358
+ if (backlog.length > 0) {
359
+ emitEvent('CODEX_WORKER_POST_PROCESSING', JSON.stringify(postProcessing));
360
+ }
361
+ }
362
+ finally {
363
+ await handle.close().catch(() => undefined);
364
+ }
365
+ }
366
+ catch (error) {
367
+ const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
368
+ return {
369
+ ...base,
370
+ mode: 'degraded',
371
+ reason: `post_processing_continuation_failed:${detail}`,
372
+ nextAction: 'Inspect the workspace state.db principle_candidates/tasks; the worker retries automatically on the next cycle.',
373
+ report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null },
200
374
  };
201
375
  }
202
376
  }
@@ -223,9 +397,10 @@ export async function runCodexWorkspaceWorkerCycle(options) {
223
397
  mode: 'degraded',
224
398
  reason: `host_tool_declaration_persist_failed:${declared.reason}`,
225
399
  nextAction: 'Repair Codex host declaration persistence (.pd/host-tool-semantics/codex.json) before running the downstream internalization cycle; the worker retries automatically on the next cycle.',
226
- report: { catchUp, reconcile, diagnostician, downstream: null },
400
+ report: { catchUp, reconcile, postProcessing: null, diagnostician, downstream: null },
227
401
  };
228
402
  }
403
+ writeLiveness(workspaceDir, { runningStage: 'downstream_cycle', stageDeadline: new Date(Date.now() + LIVENESS_STAGE_DEADLINE_MS.downstream_cycle).toISOString() });
229
404
  const downstream = await runInternalizationConsumerCycle(workspaceDir, {
230
405
  owner: WORKER_OWNER,
231
406
  logLabel: 'CodexWorker',
@@ -249,11 +424,19 @@ export async function runCodexWorkspaceWorkerCycle(options) {
249
424
  : diagnostician?.status === 'degraded' ? `diagnostician_degraded:${diagnostician.message ?? 'unknown'}`
250
425
  : downstream.skipReason === 'runtime_config_error' || downstream.skipReason === 'cycle_error' || downstream.skipReason === 'config_malformed' ? `downstream:${downstream.skipReason}`
251
426
  : undefined;
427
+ writeLiveness(workspaceDir, {
428
+ runningStage: null,
429
+ stageDeadline: null,
430
+ lastCycleCompletedAt: new Date().toISOString(),
431
+ lastCycleDurationMs: Date.now() - cycleStartedAt.getTime(),
432
+ lastCycleMode: degradedReason !== undefined ? 'degraded' : 'ready',
433
+ ...(degradedReason !== undefined ? { lastDegradedReason: degradedReason } : {}),
434
+ });
252
435
  return {
253
436
  ...base,
254
437
  mode: degradedReason !== undefined ? 'degraded' : 'ready',
255
438
  ...(degradedReason !== undefined ? { reason: degradedReason, nextAction: 'Inspect the Workspace .pd/config.yaml runtime profile and the per-step report above; the worker retries automatically on the next cycle.' } : {}),
256
- report: { catchUp, reconcile, diagnostician, downstream },
439
+ report: { catchUp, reconcile, postProcessing, diagnostician, downstream },
257
440
  };
258
441
  }
259
442
  // Slice D (PRI-625): the mode authority moved to host-runtime so the CLI and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.5.3",
3
+ "version": "0.5.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",
@@ -22,7 +22,9 @@
22
22
  },
23
23
  "files": [
24
24
  "dist",
25
- "README.md"
25
+ "README.md",
26
+ "LICENSE",
27
+ "NOTICE"
26
28
  ],
27
29
  "scripts": {
28
30
  "build": "tsc",
@@ -31,17 +33,17 @@
31
33
  "lint": "eslint \"src/**/*.ts\""
32
34
  },
33
35
  "dependencies": {
34
- "@principles/core": "^1.291.3",
35
- "@principles/host-runtime": "^0.8.2",
36
- "@principles/install-layout": "^0.2.7"
36
+ "@principles/core": "^1.292.1",
37
+ "@principles/host-runtime": "^0.9.1",
38
+ "@principles/install-layout": "^0.3.1"
37
39
  },
38
40
  "devDependencies": {
39
41
  "@types/node": "^26.4.1",
40
42
  "typescript": "^7.0.2",
41
- "vite": "^8.3.0",
43
+ "vite": "^8.3.4",
42
44
  "vitest": "^5.0.0"
43
45
  },
44
- "license": "MIT",
46
+ "license": "Apache-2.0",
45
47
  "repository": {
46
48
  "type": "git",
47
49
  "url": "git+https://github.com/csuzngjh/principles.git",