@nimiplatform/nimi-coding 0.2.7 → 0.3.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.
Files changed (207) hide show
  1. package/CHANGELOG.md +8 -80
  2. package/CONTRIBUTING.md +5 -34
  3. package/README.md +47 -350
  4. package/README.zh-CN.md +33 -287
  5. package/cli/commands/start.mjs +48 -688
  6. package/cli/commands/validate-spec-audit.mjs +1 -5
  7. package/cli/constants.mjs +9 -417
  8. package/cli/dev/run-cli-smoke.mjs +24 -0
  9. package/cli/dev/run-suite.mjs +17 -0
  10. package/cli/help.mjs +28 -145
  11. package/cli/index.mjs +5 -33
  12. package/cli/lib/blueprint-audit.mjs +5 -12
  13. package/cli/lib/bootstrap.mjs +0 -9
  14. package/cli/lib/contracts.mjs +0 -163
  15. package/cli/lib/doctor.mjs +155 -10
  16. package/cli/lib/entrypoints.mjs +63 -167
  17. package/cli/lib/internal/contracts-loaders.mjs +0 -85
  18. package/cli/lib/internal/contracts-parse.mjs +84 -520
  19. package/cli/lib/internal/governance/ai/check-agents-freshness.mjs +13 -8
  20. package/cli/lib/internal/surface-taxonomy-validators.mjs +316 -66
  21. package/cli/lib/internal/validators-shared.mjs +0 -16
  22. package/cli/lib/internal/validators-spec-helpers.mjs +7 -140
  23. package/cli/lib/internal/validators-spec.mjs +103 -342
  24. package/cli/lib/shared.mjs +1 -42
  25. package/cli/lib/validators.mjs +0 -48
  26. package/cli/seeds/seed-policy.yaml +0 -3
  27. package/config/bootstrap.yaml +4 -4
  28. package/config/spec-generation-inputs.yaml +6 -12
  29. package/contracts/domain-admission.schema.yaml +3 -3
  30. package/contracts/migration-inventory.schema.yaml +12 -75
  31. package/contracts/negative-fixtures.yaml +19 -99
  32. package/contracts/placement-contract.schema.yaml +49 -78
  33. package/contracts/projection-edge.schema.yaml +37 -121
  34. package/contracts/shared-enums.yaml +4 -8
  35. package/contracts/spec-generation-inputs.schema.yaml +15 -112
  36. package/contracts/spec-layout.schema.yaml +32 -0
  37. package/contracts/surface-taxonomy.schema.yaml +43 -94
  38. package/contracts/table-family.schema.yaml +1 -1
  39. package/contracts/tracked-output-admission.schema.yaml +13 -66
  40. package/methodology/core.yaml +33 -25
  41. package/methodology/four-closure-policy.yaml +18 -26
  42. package/methodology/role-separation-policy.yaml +21 -27
  43. package/methodology/spec-reconstruction.yaml +17 -34
  44. package/package.json +4 -6
  45. package/spec/_meta/spec-tree-model.yaml +5 -101
  46. package/spec/product-scope.yaml +25 -57
  47. package/adapters/README.md +0 -25
  48. package/adapters/claude/README.md +0 -89
  49. package/adapters/claude/profile.yaml +0 -70
  50. package/adapters/codex/README.md +0 -53
  51. package/adapters/codex/profile.yaml +0 -78
  52. package/adapters/oh-my-codex/README.md +0 -184
  53. package/adapters/oh-my-codex/profile.yaml +0 -46
  54. package/cli/commands/admit-high-risk-decision.mjs +0 -108
  55. package/cli/commands/audit-sweep.mjs +0 -364
  56. package/cli/commands/closeout.mjs +0 -186
  57. package/cli/commands/decide-high-risk-execution.mjs +0 -124
  58. package/cli/commands/handoff.mjs +0 -123
  59. package/cli/commands/ingest-high-risk-execution.mjs +0 -95
  60. package/cli/commands/review-high-risk-execution.mjs +0 -95
  61. package/cli/commands/sweep-design.mjs +0 -295
  62. package/cli/commands/sweep.mjs +0 -22
  63. package/cli/commands/topic-formatters.mjs +0 -382
  64. package/cli/commands/topic-goal.mjs +0 -33
  65. package/cli/commands/topic-options-shared.mjs +0 -27
  66. package/cli/commands/topic-options-workflow.mjs +0 -767
  67. package/cli/commands/topic-options.mjs +0 -626
  68. package/cli/commands/topic-runner.mjs +0 -169
  69. package/cli/commands/topic.mjs +0 -795
  70. package/cli/commands/validate-acceptance.mjs +0 -5
  71. package/cli/commands/validate-execution-packet.mjs +0 -5
  72. package/cli/commands/validate-orchestration-state.mjs +0 -5
  73. package/cli/commands/validate-prompt.mjs +0 -5
  74. package/cli/commands/validate-worker-output.mjs +0 -5
  75. package/cli/lib/adapter-profiles.mjs +0 -403
  76. package/cli/lib/audit-execution.mjs +0 -52
  77. package/cli/lib/audit-sweep-runtime/admissions.mjs +0 -508
  78. package/cli/lib/audit-sweep-runtime/audit-validity.mjs +0 -356
  79. package/cli/lib/audit-sweep-runtime/chunks.mjs +0 -697
  80. package/cli/lib/audit-sweep-runtime/claude-auditor.mjs +0 -647
  81. package/cli/lib/audit-sweep-runtime/closeout.mjs +0 -144
  82. package/cli/lib/audit-sweep-runtime/codex-auditor-evidence.mjs +0 -654
  83. package/cli/lib/audit-sweep-runtime/codex-auditor.mjs +0 -516
  84. package/cli/lib/audit-sweep-runtime/common.mjs +0 -341
  85. package/cli/lib/audit-sweep-runtime/coverage-quality.mjs +0 -172
  86. package/cli/lib/audit-sweep-runtime/evidence-assignment.mjs +0 -155
  87. package/cli/lib/audit-sweep-runtime/format.mjs +0 -57
  88. package/cli/lib/audit-sweep-runtime/ingest.mjs +0 -486
  89. package/cli/lib/audit-sweep-runtime/inventory-spec-chunks.mjs +0 -425
  90. package/cli/lib/audit-sweep-runtime/inventory.mjs +0 -798
  91. package/cli/lib/audit-sweep-runtime/ledger.mjs +0 -315
  92. package/cli/lib/audit-sweep-runtime/p0p1-profile.mjs +0 -101
  93. package/cli/lib/audit-sweep-runtime/remediation.mjs +0 -349
  94. package/cli/lib/audit-sweep-runtime/rerun.mjs +0 -129
  95. package/cli/lib/audit-sweep-runtime/risk-budget.mjs +0 -300
  96. package/cli/lib/audit-sweep-runtime/status.mjs +0 -62
  97. package/cli/lib/audit-sweep-runtime/validators-ledger.mjs +0 -215
  98. package/cli/lib/audit-sweep-runtime/validators.mjs +0 -797
  99. package/cli/lib/audit-sweep.mjs +0 -19
  100. package/cli/lib/authority-convergence.mjs +0 -704
  101. package/cli/lib/closeout.mjs +0 -732
  102. package/cli/lib/codex-sdk-runner.mjs +0 -76
  103. package/cli/lib/external-execution.mjs +0 -101
  104. package/cli/lib/handoff.mjs +0 -812
  105. package/cli/lib/high-risk-admission.mjs +0 -512
  106. package/cli/lib/high-risk-decision.mjs +0 -353
  107. package/cli/lib/high-risk-ingest.mjs +0 -321
  108. package/cli/lib/high-risk-review.mjs +0 -267
  109. package/cli/lib/internal/contracts-parse-high-risk.mjs +0 -131
  110. package/cli/lib/internal/contracts-validators.mjs +0 -399
  111. package/cli/lib/internal/doctor-bootstrap-surface.mjs +0 -406
  112. package/cli/lib/internal/doctor-delegated-surface.mjs +0 -256
  113. package/cli/lib/internal/doctor-finalize.mjs +0 -383
  114. package/cli/lib/internal/doctor-format.mjs +0 -286
  115. package/cli/lib/internal/doctor-inspectors.mjs +0 -327
  116. package/cli/lib/internal/doctor-state.mjs +0 -205
  117. package/cli/lib/internal/validators-artifacts.mjs +0 -515
  118. package/cli/lib/sweep-design-runtime/common.mjs +0 -246
  119. package/cli/lib/sweep-design-runtime/engine.mjs +0 -733
  120. package/cli/lib/sweep-design-runtime/fix-topic.mjs +0 -414
  121. package/cli/lib/sweep-design-runtime/lifecycle.mjs +0 -54
  122. package/cli/lib/sweep-design-runtime/results.mjs +0 -324
  123. package/cli/lib/sweep-design.mjs +0 -8
  124. package/cli/lib/topic-artifacts.mjs +0 -186
  125. package/cli/lib/topic-authority-coverage.mjs +0 -73
  126. package/cli/lib/topic-closeout.mjs +0 -560
  127. package/cli/lib/topic-common.mjs +0 -404
  128. package/cli/lib/topic-decisions.mjs +0 -332
  129. package/cli/lib/topic-draft-packets.mjs +0 -167
  130. package/cli/lib/topic-execution.mjs +0 -515
  131. package/cli/lib/topic-goal.mjs +0 -440
  132. package/cli/lib/topic-ledger.mjs +0 -281
  133. package/cli/lib/topic-lifecycle-artifacts.mjs +0 -173
  134. package/cli/lib/topic-root-validation.mjs +0 -288
  135. package/cli/lib/topic-runner-commands.mjs +0 -174
  136. package/cli/lib/topic-runner-deferral.mjs +0 -532
  137. package/cli/lib/topic-runner-stale-gates.mjs +0 -114
  138. package/cli/lib/topic-runner-validation.mjs +0 -138
  139. package/cli/lib/topic-runner.mjs +0 -727
  140. package/cli/lib/topic-scaffold.mjs +0 -252
  141. package/cli/lib/topic-waves.mjs +0 -403
  142. package/cli/lib/topic.mjs +0 -81
  143. package/config/audit-execution-artifacts.yaml +0 -20
  144. package/config/external-execution-artifacts.yaml +0 -16
  145. package/config/host-adapter.yaml +0 -30
  146. package/config/host-profile.yaml +0 -29
  147. package/config/installer-evidence.yaml +0 -31
  148. package/config/skill-installer.yaml +0 -23
  149. package/config/skill-manifest.yaml +0 -48
  150. package/config/skills.yaml +0 -30
  151. package/contracts/acceptance.schema.yaml +0 -16
  152. package/contracts/admission-checklist.schema.yaml +0 -15
  153. package/contracts/audit-chunk.schema.yaml +0 -123
  154. package/contracts/audit-closeout.schema.yaml +0 -51
  155. package/contracts/audit-finding.schema.yaml +0 -61
  156. package/contracts/audit-ledger.schema.yaml +0 -138
  157. package/contracts/audit-plan.schema.yaml +0 -138
  158. package/contracts/audit-remediation-map.schema.yaml +0 -52
  159. package/contracts/audit-rerun.schema.yaml +0 -31
  160. package/contracts/audit-sweep-result.yaml +0 -53
  161. package/contracts/authority-convergence-audit.schema.yaml +0 -19
  162. package/contracts/closeout.schema.yaml +0 -25
  163. package/contracts/decision-review.schema.yaml +0 -16
  164. package/contracts/doc-spec-audit-result.yaml +0 -19
  165. package/contracts/execution-packet.schema.yaml +0 -49
  166. package/contracts/external-host-compatibility.yaml +0 -22
  167. package/contracts/forbidden-shortcuts.catalog.yaml +0 -23
  168. package/contracts/high-risk-admission.schema.yaml +0 -23
  169. package/contracts/high-risk-execution-result.yaml +0 -20
  170. package/contracts/orchestration-state.schema.yaml +0 -41
  171. package/contracts/overflow-continuation.schema.yaml +0 -12
  172. package/contracts/packet.schema.yaml +0 -30
  173. package/contracts/pending-note.schema.yaml +0 -17
  174. package/contracts/prompt.schema.yaml +0 -12
  175. package/contracts/remediation.schema.yaml +0 -16
  176. package/contracts/result.schema.yaml +0 -24
  177. package/contracts/spec-reconstruction-result.yaml +0 -41
  178. package/contracts/sweep-design-result.yaml +0 -349
  179. package/contracts/topic-goal.schema.yaml +0 -87
  180. package/contracts/topic-run-ledger.schema.yaml +0 -72
  181. package/contracts/topic-step-decision.schema.yaml +0 -45
  182. package/contracts/topic.schema.yaml +0 -65
  183. package/contracts/true-close.schema.yaml +0 -15
  184. package/contracts/wave.schema.yaml +0 -29
  185. package/contracts/worker-output.schema.yaml +0 -15
  186. package/contracts/workflow-consumer.schema.yaml +0 -110
  187. package/methodology/audit-sweep-p0p1-recall.yaml +0 -45
  188. package/methodology/authority-convergence-policy.yaml +0 -42
  189. package/methodology/overflow-continuation-policy.yaml +0 -14
  190. package/methodology/skill-exchange-projection.yaml +0 -114
  191. package/methodology/skill-handoff.yaml +0 -34
  192. package/methodology/skill-installer-result.yaml +0 -27
  193. package/methodology/skill-installer-summary-projection.yaml +0 -181
  194. package/methodology/skill-runtime.yaml +0 -23
  195. package/methodology/spec-target-truth-profile.yaml +0 -46
  196. package/methodology/topic-lifecycle-report.yaml +0 -144
  197. package/methodology/topic-lifecycle.yaml +0 -37
  198. package/methodology/topic-naming-ontology.yaml +0 -21
  199. package/methodology/topic-ontology.yaml +0 -38
  200. package/methodology/topic-validation-policy.yaml +0 -9
  201. package/methodology/wave-dag-policy.yaml +0 -14
  202. package/spec/_meta/command-gating-matrix.yaml +0 -143
  203. package/spec/_meta/generate-drift-migration-checklist.yaml +0 -137
  204. package/spec/_meta/governance-routing-cutover-checklist.yaml +0 -35
  205. package/spec/_meta/phase2-impacted-surface-matrix.yaml +0 -44
  206. package/spec/_meta/spec-authority-cutover-readiness.yaml +0 -102
  207. package/spec/bootstrap-state.yaml +0 -99
@@ -1,516 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- import {
6
- appendRunEvent,
7
- artifactPath,
8
- artifactRef,
9
- chunkRef,
10
- ensureIsoTimestamp,
11
- inputError,
12
- loadChunk,
13
- loadPlan,
14
- packetRef,
15
- resolveInsideProject,
16
- safeSweepId,
17
- withAuditSweepMutationLock,
18
- writeYamlRef,
19
- } from "./common.mjs";
20
- import { buildAuditorPacket, reviewAuditSweepChunk, updatePlanChunk } from "./chunks.mjs";
21
- import { extractCodexAuditorEvidenceFile, P0P1_RULE_CHECK_IDS } from "./codex-auditor-evidence.mjs";
22
- import { ingestAuditSweepChunk } from "./ingest.mjs";
23
- import { budgetBlockForChunk } from "./risk-budget.mjs";
24
- import { validateAuditSweepArtifacts } from "./validators.mjs";
25
-
26
- const CODEX_AUDITOR_DEFAULT = "codex_semantic_auditor";
27
- const DEFAULT_CODEX_TIMEOUT_MS = 10 * 60 * 1000;
28
- const CODEX_TIMEOUT_KILL_GRACE_MS = 3000;
29
- const CODEX_RAW_SUFFIX = ".codex-raw.json";
30
- const CODEX_EVIDENCE_SUFFIX = ".codex-evidence.json";
31
-
32
- function codexOutputRef(sweepId, chunkId, suffix) {
33
- return artifactRef("evidence_refs", sweepId, "codex-output", `${chunkId}${suffix}`);
34
- }
35
-
36
- function codexRunToken(timestamp) {
37
- return timestamp.replace(/[^0-9A-Za-z]+/g, "-").replace(/^-+|-+$/g, "");
38
- }
39
-
40
- function projectRefForPath(projectRoot, absolutePath) {
41
- return path.relative(projectRoot, absolutePath).replace(/\\/g, "/");
42
- }
43
- function codexPrompt({ packet, auditorPacketRef, rawRef, sessionRef }) {
44
- return [
45
- "You are the Codex semantic auditor for a nimicoding sweep audit chunk.",
46
- "Run in read-only, audit-only mode. Do not edit files. Do not implement product fixes.",
47
- `Read the auditor packet from ${auditorPacketRef} and inspect the chunk authority refs and implementation evidence semantically.`,
48
- "Do not rely on this prompt as the chunk inventory; the packet file is the source for files, authority_refs, selected_implementation_refs, audit_depth, retrieval_prepass, and the raw semantic output contract.",
49
- "Scripts may not generate findings or no-findings; your conclusions must come from your own inspection.",
50
- "The packet is compact: evidence_inventory/selected_implementation_refs is the manager-selected implementation slice, not the full manager-owned inventory.",
51
- "Do not ask for, reconstruct, or echo the omitted full evidence_inventory. audit-codex will mechanically fill coverage.files, coverage.authority_refs, and full coverage.evidence_files from manager-owned chunk state.",
52
- "You only author semantic audit content: authority_outcomes reasoning/status, inspected_implementation_refs, P0/P1 rule checks, p0p1_negative_reasoning when applicable, and findings.",
53
- "For each authority outcome, set authority_ref to the packet authority_ref and put inspected implementation refs in inspected_implementation_refs or implementation_evidence_refs.",
54
- "Every implementation ref you cite must be an exact file ref from packet.selected_implementation_refs / packet.evidence_inventory.",
55
- "Never put AGENTS.md, README.md, spec files, authority refs, methodology docs, or governance docs in inspected_implementation_refs, implementation_evidence_refs, coverage.p0p1_evidence_refs, findings[].implementation_refs, or coverage.p0p1_rule_checks[].implementation_refs; even if packet.selected_implementation_refs includes them, treat them as context only.",
56
- "If only context/governance/authority documents are available after that exclusion, use status=\"not_applicable\" for P0/P1 rule checks and explain the lack of implementation surface in negative_reasoning.",
57
- "If a governance or authority document influenced reasoning, mention it only in negative_reasoning/description text, not in any implementation_refs array.",
58
- "Use packet.audit_depth to size your inspection: deep means inspect the selected slice thoroughly, normal means focused semantic inspection, shallow means audit generated/table/index invariants from the selected slice without expanding the omitted inventory.",
59
- "Return exactly one JSON object and nothing else. Do not wrap it in markdown.",
60
- "The JSON object must have exactly these top-level fields: chunk_id, auditor, coverage, findings.",
61
- `Set auditor.id to ${JSON.stringify(packet.auditor)}.`,
62
- `Set auditor.mode to "codex_semantic_audit".`,
63
- `Set auditor.methodology_ref to "package://@nimiplatform/nimi-coding/methodology/audit-sweep-p0p1-recall.yaml".`,
64
- "Put P0/P1 rule checks only at coverage.p0p1_rule_checks.",
65
- `Set auditor.provenance.kind to "semantic_audit".`,
66
- `Set auditor.provenance.packet_ref to ${JSON.stringify(packetRef(packet.sweep_id, packet.chunk_id))}.`,
67
- `Set auditor.provenance.session_ref to ${JSON.stringify(sessionRef)}.`,
68
- `Set auditor.provenance.transcript_ref to ${JSON.stringify(rawRef)}.`,
69
- "coverage.authority_outcomes must contain one outcome per authority_ref.",
70
- `coverage.p0p1_rule_checks must contain exactly these ids and no aliases: ${P0P1_RULE_CHECK_IDS.join(", ")}.`,
71
- "Each coverage.authority_outcomes[] object must include negative_reasoning when no critical/high finding is emitted for the chunk.",
72
- "Each coverage.p0p1_rule_checks[] object must include id, status, implementation_refs, and negative_reasoning.",
73
- "Use status=\"checked\" when implementation evidence was inspected; checked rules must cite at least one in-scope implementation ref.",
74
- "Use status=\"not_applicable\" only when the rule truly has no implementation surface, and explain that in negative_reasoning.",
75
- "When the packet evidence_inventory is empty and no critical/high finding is emitted, include coverage.p0p1_implementation_not_applicable_reason with the chunk-specific reason implementation refs are not applicable.",
76
- "Do not use priority defect class aliases such as authority_boundary_bypass, security_or_permission_bypass, destructive_action_without_gate, package_boundary_violation, or unadmitted_truth_or_evidence_source as rule check ids.",
77
- "Do not emit coverage.files, coverage.authority_refs, or coverage.evidence_files; those fields are manager-owned and will be populated from the packet.",
78
- "Do not emit authority_outcomes[].evidence_refs; it is manager-owned and will be built from authority_ref plus inspected implementation refs.",
79
- "Every finding must include severity, category, impact, title, description, and location.file. Set severity to critical or high for P0/P1 findings. Set finding.category to one of the exact P0/P1 rule ids when the finding maps to a P0/P1 rule; do not use rule_id as the primary finding category field.",
80
- "Set findings[].location.file to an exact packet.selected_implementation_refs file for implementation findings. For authority-only findings with no implementation surface, set findings[].location.file to the in-scope authority_ref that contains the defect.",
81
- "authority_outcomes[].status is an audit-process enum only: audited, blocked, or not_applicable.",
82
- "Use status=audited when the authority/evidence was inspected, even if you discovered violations.",
83
- "When an authority outcome uses status=blocked or status=not_applicable, include reason with the chunk-specific blocker or not-applicable explanation.",
84
- "Do not use compliance verdicts such as violated, pass, fail, compliant, or non_compliant in authority_outcomes[].status; put violations in findings.",
85
- "For no-finding chunks, include chunk-specific inspected implementation refs, P0/P1 rule checks, and negative reasoning.",
86
- ].join("\n");
87
- }
88
-
89
- function terminateProcess(child, signal) {
90
- try {
91
- if (process.platform !== "win32" && child.pid) {
92
- process.kill(-child.pid, signal);
93
- return;
94
- }
95
- } catch {
96
- // Fall through to direct child termination.
97
- }
98
- try {
99
- child.kill(signal);
100
- } catch {
101
- // Process may already have exited.
102
- }
103
- }
104
-
105
- function runCodexExec({ projectRoot, codexBin, rawOutputPath, prompt, timeoutMs }) {
106
- return new Promise((resolve) => {
107
- const boundedTimeoutMs = Number.isInteger(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_CODEX_TIMEOUT_MS;
108
- let timedOut = false;
109
- let settled = false;
110
- let killTimer = null;
111
- const child = spawn(codexBin, [
112
- "exec",
113
- "-C",
114
- projectRoot,
115
- "-s",
116
- "read-only",
117
- "--output-last-message",
118
- rawOutputPath,
119
- "-",
120
- ], {
121
- cwd: projectRoot,
122
- stdio: ["pipe", "pipe", "pipe"],
123
- detached: process.platform !== "win32",
124
- });
125
-
126
- const timeoutTimer = setTimeout(() => {
127
- timedOut = true;
128
- terminateProcess(child, "SIGTERM");
129
- killTimer = setTimeout(() => terminateProcess(child, "SIGKILL"), CODEX_TIMEOUT_KILL_GRACE_MS);
130
- }, boundedTimeoutMs);
131
-
132
- let stdout = "";
133
- let stderr = "";
134
- child.stdout.on("data", (chunk) => {
135
- stdout += chunk.toString();
136
- });
137
- child.stderr.on("data", (chunk) => {
138
- stderr += chunk.toString();
139
- });
140
- child.on("error", (error) => {
141
- if (settled) {
142
- return;
143
- }
144
- settled = true;
145
- clearTimeout(timeoutTimer);
146
- if (killTimer) {
147
- clearTimeout(killTimer);
148
- }
149
- resolve({ ok: false, exitCode: 1, timedOut, timeoutMs: boundedTimeoutMs, stdout, stderr: `${stderr}${error.message}` });
150
- });
151
- child.on("close", (exitCode, signal) => {
152
- if (settled) {
153
- return;
154
- }
155
- settled = true;
156
- clearTimeout(timeoutTimer);
157
- if (killTimer) {
158
- clearTimeout(killTimer);
159
- }
160
- resolve({ ok: exitCode === 0 && !timedOut, exitCode, signal, timedOut, timeoutMs: boundedTimeoutMs, stdout, stderr });
161
- });
162
- child.stdin.end(prompt);
163
- });
164
- }
165
-
166
- async function prepareCodexAuditPacket(projectRoot, options) {
167
- return withAuditSweepMutationLock(projectRoot, options.sweepId, "chunk codex audit prepare", async () => {
168
- const planResult = await loadPlan(projectRoot, options.sweepId);
169
- if (!planResult.ok) {
170
- return inputError(planResult.error);
171
- }
172
- const chunkResult = await loadChunk(projectRoot, options.sweepId, options.chunkId);
173
- if (!chunkResult.ok) {
174
- return inputError(chunkResult.error);
175
- }
176
- if (chunkResult.chunk.state === "skipped") {
177
- return inputError("nimicoding sweep audit refused: skipped chunks cannot be audited through Codex.\n");
178
- }
179
- const budgetBlock = budgetBlockForChunk(planResult.plan, chunkResult.chunk);
180
- if (budgetBlock && chunkResult.chunk.state !== "frozen") {
181
- return inputError(`nimicoding sweep audit refused: ${budgetBlock}; build or admit remediation bundles before continuing discovery.\n`);
182
- }
183
-
184
- const dispatch = {
185
- auditor: options.auditor ?? CODEX_AUDITOR_DEFAULT,
186
- criteria: chunkResult.chunk.criteria,
187
- files: chunkResult.chunk.files,
188
- authority_refs: chunkResult.chunk.authority_refs ?? chunkResult.chunk.files,
189
- host_authority_projection_refs: chunkResult.chunk.host_authority_projection_refs ?? [],
190
- evidence_roots: chunkResult.chunk.evidence_roots ?? [],
191
- admitted_evidence_roots: chunkResult.chunk.admitted_evidence_roots ?? [],
192
- evidence_inventory: chunkResult.chunk.evidence_inventory ?? [],
193
- evidence_inventory_status: chunkResult.chunk.evidence_inventory_status ?? null,
194
- evidence_inventory_empty_reason: chunkResult.chunk.evidence_inventory_empty_reason ?? null,
195
- execution_owner: "nimicoding_codex_auditor_path",
196
- };
197
- const packet = buildAuditorPacket(options.sweepId, chunkResult.chunk, dispatch.auditor, options.dispatchedAt, planResult.plan, { projectRoot });
198
- packet.execution_owner = "nimicoding_codex_auditor_path";
199
- packet.raw_output_contract = {
200
- raw_output_is_transcript_ref: true,
201
- raw_output_must_be_exact_json: true,
202
- schema_drift_rejected_fail_closed: true,
203
- scripts_may_only_extract_schema_conformant_evidence: true,
204
- };
205
-
206
- const auditorPacketRef = packetRef(options.sweepId, options.chunkId);
207
- const updatedChunk = {
208
- ...chunkResult.chunk,
209
- state: "dispatched",
210
- lifecycle: {
211
- ...chunkResult.chunk.lifecycle,
212
- dispatched_at: options.dispatchedAt,
213
- ingested_at: null,
214
- reviewed_at: null,
215
- frozen_at: null,
216
- failed_at: null,
217
- skipped_at: null,
218
- },
219
- dispatch,
220
- evidence_ref: null,
221
- finding_count: 0,
222
- audit_validity: null,
223
- review: null,
224
- failure: null,
225
- updated_at: options.dispatchedAt,
226
- };
227
-
228
- await writeYamlRef(projectRoot, auditorPacketRef, packet);
229
- await writeYamlRef(projectRoot, chunkResult.chunkRef, updatedChunk);
230
- await writeYamlRef(projectRoot, planResult.planRef, {
231
- ...updatePlanChunk(planResult.plan, options.chunkId, {
232
- state: "dispatched",
233
- evidence_ref: null,
234
- finding_count: 0,
235
- audit_validity: null,
236
- failure: null,
237
- }),
238
- updated_at: options.dispatchedAt,
239
- });
240
- const runLedgerRef = await appendRunEvent(projectRoot, options.sweepId, {
241
- event_type: "chunk_codex_audit_prepared",
242
- chunk_id: options.chunkId,
243
- chunk_ref: chunkRef(options.sweepId, options.chunkId),
244
- packet_ref: auditorPacketRef,
245
- auditor: dispatch.auditor,
246
- });
247
- return {
248
- ok: true,
249
- chunk: updatedChunk,
250
- packet,
251
- packetRef: auditorPacketRef,
252
- chunkRef: chunkResult.chunkRef,
253
- runLedgerRef,
254
- };
255
- });
256
- }
257
-
258
- async function markCodexAuditFailed(projectRoot, options) {
259
- return withAuditSweepMutationLock(projectRoot, options.sweepId, "chunk codex audit fail", async () => {
260
- const planResult = await loadPlan(projectRoot, options.sweepId);
261
- if (!planResult.ok) {
262
- return inputError(planResult.error);
263
- }
264
- const chunkResult = await loadChunk(projectRoot, options.sweepId, options.chunkId);
265
- if (!chunkResult.ok) {
266
- return inputError(chunkResult.error);
267
- }
268
- const failure = {
269
- reason: options.reason,
270
- failed_at: options.failedAt,
271
- packet_ref: options.packetRef,
272
- transcript_ref: options.transcriptRef,
273
- phase: options.phase,
274
- };
275
- const updatedChunk = {
276
- ...chunkResult.chunk,
277
- state: "failed",
278
- lifecycle: {
279
- ...chunkResult.chunk.lifecycle,
280
- failed_at: options.failedAt,
281
- skipped_at: null,
282
- },
283
- failure,
284
- updated_at: options.failedAt,
285
- };
286
- await writeYamlRef(projectRoot, chunkResult.chunkRef, updatedChunk);
287
- await writeYamlRef(projectRoot, planResult.planRef, {
288
- ...updatePlanChunk(planResult.plan, options.chunkId, {
289
- state: "failed",
290
- failure,
291
- }),
292
- updated_at: options.failedAt,
293
- });
294
- const runLedgerRef = await appendRunEvent(projectRoot, options.sweepId, {
295
- event_type: "chunk_failed",
296
- chunk_id: options.chunkId,
297
- chunk_ref: chunkResult.chunkRef,
298
- packet_ref: options.packetRef,
299
- transcript_ref: options.transcriptRef,
300
- summary: options.reason,
301
- phase: options.phase,
302
- });
303
- return {
304
- ok: true,
305
- state: "failed",
306
- chunkRef: chunkResult.chunkRef,
307
- runLedgerRef,
308
- };
309
- });
310
- }
311
-
312
- export async function runCodexAuditSweepChunk(projectRoot, options) {
313
- const sweepId = safeSweepId(options.sweepId);
314
- if (!sweepId || typeof options.chunkId !== "string") {
315
- return inputError("nimicoding sweep audit refused: --sweep-id and --chunk-id are required.\n");
316
- }
317
- const dispatchedAtError = ensureIsoTimestamp(options.dispatchedAt, "--dispatched-at");
318
- if (dispatchedAtError) {
319
- return dispatchedAtError;
320
- }
321
- const verifiedAtError = ensureIsoTimestamp(options.verifiedAt, "--verified-at");
322
- if (verifiedAtError) {
323
- return verifiedAtError;
324
- }
325
- const reviewedAtError = ensureIsoTimestamp(options.reviewedAt, "--reviewed-at");
326
- if (reviewedAtError) {
327
- return reviewedAtError;
328
- }
329
-
330
- const prepare = await prepareCodexAuditPacket(projectRoot, {
331
- ...options,
332
- sweepId,
333
- });
334
- if (!prepare.ok) {
335
- return prepare;
336
- }
337
-
338
- const outputSuffix = `.${codexRunToken(options.dispatchedAt)}`;
339
- let rawRef = codexOutputRef(sweepId, options.chunkId, `${outputSuffix}${CODEX_RAW_SUFFIX}`);
340
- const evidenceCandidateRef = codexOutputRef(sweepId, options.chunkId, `${outputSuffix}${CODEX_EVIDENCE_SUFFIX}`);
341
- let rawOutputPath = artifactPath(projectRoot, rawRef);
342
- let sessionRef = `codex-exec:${sweepId}:${options.chunkId}:${options.dispatchedAt}`;
343
- if (options.fromRawOutput) {
344
- const replaySource = resolveInsideProject(projectRoot, options.fromRawOutput, "--from-raw-output");
345
- if (!replaySource.ok) {
346
- await markCodexAuditFailed(projectRoot, {
347
- sweepId,
348
- chunkId: options.chunkId,
349
- failedAt: options.verifiedAt,
350
- packetRef: prepare.packetRef,
351
- transcriptRef: rawRef,
352
- phase: "raw_output_replay",
353
- reason: replaySource.error.trim(),
354
- });
355
- return inputError(replaySource.error);
356
- }
357
- rawOutputPath = replaySource.absolutePath;
358
- rawRef = projectRefForPath(projectRoot, rawOutputPath);
359
- sessionRef = `codex-replay:${sweepId}:${options.chunkId}:${options.dispatchedAt}`;
360
- } else {
361
- await mkdir(path.dirname(rawOutputPath), { recursive: true });
362
- const runResult = await runCodexExec({
363
- projectRoot,
364
- codexBin: options.codexBin ?? "codex",
365
- rawOutputPath,
366
- prompt: codexPrompt({
367
- packet: prepare.packet,
368
- auditorPacketRef: prepare.packetRef,
369
- rawRef,
370
- sessionRef,
371
- }),
372
- timeoutMs: options.timeoutMs,
373
- });
374
- if (!runResult.ok) {
375
- const failureReason = runResult.timedOut
376
- ? `Codex auditor execution timed out after ${runResult.timeoutMs}ms.`
377
- : `Codex auditor execution failed with exit code ${runResult.exitCode ?? "unknown"}.`;
378
- await markCodexAuditFailed(projectRoot, {
379
- sweepId,
380
- chunkId: options.chunkId,
381
- failedAt: options.verifiedAt,
382
- packetRef: prepare.packetRef,
383
- transcriptRef: rawRef,
384
- phase: "codex_execution",
385
- reason: failureReason,
386
- });
387
- await appendRunEvent(projectRoot, sweepId, {
388
- event_type: "chunk_codex_audit_failed",
389
- chunk_id: options.chunkId,
390
- chunk_ref: prepare.chunkRef,
391
- packet_ref: prepare.packetRef,
392
- transcript_ref: rawRef,
393
- exit_code: runResult.exitCode,
394
- timed_out: runResult.timedOut,
395
- timeout_ms: runResult.timeoutMs,
396
- stderr_tail: runResult.stderr.slice(-2000),
397
- });
398
- return inputError(`nimicoding sweep audit refused: ${failureReason}\n`);
399
- }
400
- }
401
-
402
- const extracted = await extractCodexAuditorEvidenceFile(projectRoot, {
403
- rawOutputPath,
404
- evidenceRef: evidenceCandidateRef,
405
- chunk: prepare.chunk,
406
- packetRef: prepare.packetRef,
407
- sessionRef,
408
- transcriptRef: rawRef,
409
- auditorId: options.auditor ?? CODEX_AUDITOR_DEFAULT,
410
- });
411
- if (!extracted.ok) {
412
- await markCodexAuditFailed(projectRoot, {
413
- sweepId,
414
- chunkId: options.chunkId,
415
- failedAt: options.verifiedAt,
416
- packetRef: prepare.packetRef,
417
- transcriptRef: rawRef,
418
- phase: "auditor_output_validation",
419
- reason: `Codex auditor output rejected: ${extracted.error}.`,
420
- });
421
- await appendRunEvent(projectRoot, sweepId, {
422
- event_type: "chunk_codex_auditor_output_rejected",
423
- chunk_id: options.chunkId,
424
- chunk_ref: prepare.chunkRef,
425
- packet_ref: prepare.packetRef,
426
- transcript_ref: rawRef,
427
- reason: extracted.error,
428
- });
429
- return inputError(`nimicoding sweep audit refused: Codex auditor output rejected for ${options.chunkId}: ${extracted.error}.\n`);
430
- }
431
-
432
- await appendRunEvent(projectRoot, sweepId, {
433
- event_type: "chunk_codex_auditor_output_accepted",
434
- chunk_id: options.chunkId,
435
- chunk_ref: prepare.chunkRef,
436
- packet_ref: prepare.packetRef,
437
- transcript_ref: rawRef,
438
- evidence_candidate_ref: evidenceCandidateRef,
439
- audit_validity: extracted.auditValidity,
440
- });
441
-
442
- const ingest = await ingestAuditSweepChunk(projectRoot, {
443
- sweepId,
444
- chunkId: options.chunkId,
445
- fromPath: evidenceCandidateRef,
446
- verifiedAt: options.verifiedAt,
447
- });
448
- if (!ingest.ok) {
449
- await markCodexAuditFailed(projectRoot, {
450
- sweepId,
451
- chunkId: options.chunkId,
452
- failedAt: options.verifiedAt,
453
- packetRef: prepare.packetRef,
454
- transcriptRef: rawRef,
455
- phase: "chunk_ingest",
456
- reason: `Codex auditor evidence ingest rejected: ${ingest.error ?? "unknown ingest failure"}.`,
457
- });
458
- return inputError(`nimicoding sweep audit refused: Codex auditor evidence ingest rejected for ${options.chunkId}: ${ingest.error ?? "unknown ingest failure"}.\n`);
459
- }
460
-
461
- const review = await reviewAuditSweepChunk(projectRoot, {
462
- sweepId,
463
- chunkId: options.chunkId,
464
- verdict: "pass",
465
- reviewedAt: options.reviewedAt,
466
- reviewer: options.reviewer ?? "nimicoding_codex_auditor_path",
467
- summary: options.summary ?? `Codex semantic audit accepted from ${rawRef}.`,
468
- });
469
- if (!review.ok) {
470
- await markCodexAuditFailed(projectRoot, {
471
- sweepId,
472
- chunkId: options.chunkId,
473
- failedAt: options.reviewedAt,
474
- packetRef: prepare.packetRef,
475
- transcriptRef: rawRef,
476
- phase: "chunk_review",
477
- reason: `Codex auditor evidence review rejected: ${review.error ?? "unknown review failure"}.`,
478
- });
479
- return inputError(`nimicoding sweep audit refused: Codex auditor evidence review rejected for ${options.chunkId}: ${review.error ?? "unknown review failure"}.\n`);
480
- }
481
-
482
- const validation = await validateAuditSweepArtifacts(projectRoot, {
483
- sweepId,
484
- scope: "chunks",
485
- });
486
- if (!validation.ok) {
487
- await markCodexAuditFailed(projectRoot, {
488
- sweepId,
489
- chunkId: options.chunkId,
490
- failedAt: options.reviewedAt,
491
- packetRef: prepare.packetRef,
492
- transcriptRef: rawRef,
493
- phase: "post_chunk_validation",
494
- reason: "Post-Codex chunk validation failed.",
495
- });
496
- return inputError(`nimicoding sweep audit refused: post-Codex chunk validation failed for ${options.chunkId}.\n`);
497
- }
498
-
499
- return {
500
- ok: true,
501
- exitCode: 0,
502
- sweepId,
503
- chunkId: options.chunkId,
504
- state: "frozen",
505
- packetRef: prepare.packetRef,
506
- transcriptRef: rawRef,
507
- extractedEvidenceRef: evidenceCandidateRef,
508
- evidenceRef: ingest.evidenceRef,
509
- findingsRef: ingest.findingsRef,
510
- findingCount: ingest.findingCount,
511
- addedCount: ingest.addedCount,
512
- duplicateCount: ingest.duplicateCount,
513
- reviewRef: review.runLedgerRef,
514
- validationScope: "chunks",
515
- };
516
- }