@nimiplatform/nimi-coding 0.2.8 → 0.3.1

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 (206) hide show
  1. package/CHANGELOG.md +10 -90
  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/commands/validate-spec-governance.mjs +20 -0
  8. package/cli/constants.mjs +9 -417
  9. package/cli/help.mjs +28 -145
  10. package/cli/index.mjs +5 -33
  11. package/cli/lib/blueprint-audit.mjs +5 -12
  12. package/cli/lib/bootstrap.mjs +0 -9
  13. package/cli/lib/contracts.mjs +0 -163
  14. package/cli/lib/doctor.mjs +155 -10
  15. package/cli/lib/entrypoints.mjs +63 -167
  16. package/cli/lib/internal/contracts-loaders.mjs +0 -85
  17. package/cli/lib/internal/contracts-parse.mjs +84 -520
  18. package/cli/lib/internal/governance/ai/check-agents-freshness.mjs +13 -8
  19. package/cli/lib/internal/surface-taxonomy-validators.mjs +316 -66
  20. package/cli/lib/internal/validators-shared.mjs +0 -16
  21. package/cli/lib/internal/validators-spec-helpers.mjs +7 -140
  22. package/cli/lib/internal/validators-spec.mjs +103 -342
  23. package/cli/lib/shared.mjs +1 -42
  24. package/cli/lib/validators.mjs +0 -48
  25. package/cli/seeds/seed-policy.yaml +0 -3
  26. package/config/bootstrap.yaml +4 -4
  27. package/config/spec-generation-inputs.yaml +6 -12
  28. package/contracts/domain-admission.schema.yaml +3 -3
  29. package/contracts/migration-inventory.schema.yaml +12 -75
  30. package/contracts/negative-fixtures.yaml +19 -99
  31. package/contracts/placement-contract.schema.yaml +49 -78
  32. package/contracts/projection-edge.schema.yaml +37 -121
  33. package/contracts/shared-enums.yaml +4 -8
  34. package/contracts/spec-generation-inputs.schema.yaml +15 -112
  35. package/contracts/spec-layout.schema.yaml +32 -0
  36. package/contracts/surface-taxonomy.schema.yaml +43 -94
  37. package/contracts/table-family.schema.yaml +1 -1
  38. package/contracts/tracked-output-admission.schema.yaml +13 -66
  39. package/methodology/core.yaml +33 -25
  40. package/methodology/four-closure-policy.yaml +18 -26
  41. package/methodology/role-separation-policy.yaml +21 -27
  42. package/methodology/spec-reconstruction.yaml +17 -34
  43. package/package.json +2 -4
  44. package/spec/_meta/spec-tree-model.yaml +5 -101
  45. package/spec/product-scope.yaml +25 -57
  46. package/adapters/README.md +0 -25
  47. package/adapters/claude/README.md +0 -89
  48. package/adapters/claude/profile.yaml +0 -70
  49. package/adapters/codex/README.md +0 -53
  50. package/adapters/codex/profile.yaml +0 -78
  51. package/adapters/oh-my-codex/README.md +0 -184
  52. package/adapters/oh-my-codex/profile.yaml +0 -46
  53. package/cli/commands/admit-high-risk-decision.mjs +0 -108
  54. package/cli/commands/audit-sweep.mjs +0 -364
  55. package/cli/commands/closeout.mjs +0 -186
  56. package/cli/commands/decide-high-risk-execution.mjs +0 -124
  57. package/cli/commands/handoff.mjs +0 -123
  58. package/cli/commands/ingest-high-risk-execution.mjs +0 -95
  59. package/cli/commands/review-high-risk-execution.mjs +0 -95
  60. package/cli/commands/sweep-design.mjs +0 -295
  61. package/cli/commands/sweep.mjs +0 -22
  62. package/cli/commands/topic-formatters.mjs +0 -382
  63. package/cli/commands/topic-goal.mjs +0 -33
  64. package/cli/commands/topic-options-shared.mjs +0 -27
  65. package/cli/commands/topic-options-workflow.mjs +0 -767
  66. package/cli/commands/topic-options.mjs +0 -626
  67. package/cli/commands/topic-runner.mjs +0 -169
  68. package/cli/commands/topic.mjs +0 -795
  69. package/cli/commands/validate-acceptance.mjs +0 -5
  70. package/cli/commands/validate-execution-packet.mjs +0 -5
  71. package/cli/commands/validate-orchestration-state.mjs +0 -5
  72. package/cli/commands/validate-prompt.mjs +0 -5
  73. package/cli/commands/validate-worker-output.mjs +0 -5
  74. package/cli/lib/adapter-profiles.mjs +0 -403
  75. package/cli/lib/audit-execution.mjs +0 -52
  76. package/cli/lib/audit-sweep-runtime/admissions.mjs +0 -508
  77. package/cli/lib/audit-sweep-runtime/audit-validity.mjs +0 -356
  78. package/cli/lib/audit-sweep-runtime/chunks.mjs +0 -697
  79. package/cli/lib/audit-sweep-runtime/claude-auditor.mjs +0 -658
  80. package/cli/lib/audit-sweep-runtime/closeout.mjs +0 -144
  81. package/cli/lib/audit-sweep-runtime/codex-auditor-evidence.mjs +0 -654
  82. package/cli/lib/audit-sweep-runtime/codex-auditor.mjs +0 -527
  83. package/cli/lib/audit-sweep-runtime/common.mjs +0 -341
  84. package/cli/lib/audit-sweep-runtime/coverage-quality.mjs +0 -172
  85. package/cli/lib/audit-sweep-runtime/evidence-assignment.mjs +0 -155
  86. package/cli/lib/audit-sweep-runtime/format.mjs +0 -57
  87. package/cli/lib/audit-sweep-runtime/ingest.mjs +0 -486
  88. package/cli/lib/audit-sweep-runtime/inventory-spec-chunks.mjs +0 -425
  89. package/cli/lib/audit-sweep-runtime/inventory.mjs +0 -798
  90. package/cli/lib/audit-sweep-runtime/ledger.mjs +0 -315
  91. package/cli/lib/audit-sweep-runtime/p0p1-profile.mjs +0 -101
  92. package/cli/lib/audit-sweep-runtime/remediation.mjs +0 -349
  93. package/cli/lib/audit-sweep-runtime/rerun.mjs +0 -129
  94. package/cli/lib/audit-sweep-runtime/risk-budget.mjs +0 -300
  95. package/cli/lib/audit-sweep-runtime/status.mjs +0 -62
  96. package/cli/lib/audit-sweep-runtime/validators-ledger.mjs +0 -215
  97. package/cli/lib/audit-sweep-runtime/validators.mjs +0 -797
  98. package/cli/lib/audit-sweep.mjs +0 -19
  99. package/cli/lib/authority-convergence.mjs +0 -720
  100. package/cli/lib/closeout.mjs +0 -732
  101. package/cli/lib/codex-sdk-runner.mjs +0 -76
  102. package/cli/lib/external-execution.mjs +0 -101
  103. package/cli/lib/handoff.mjs +0 -812
  104. package/cli/lib/high-risk-admission.mjs +0 -512
  105. package/cli/lib/high-risk-decision.mjs +0 -353
  106. package/cli/lib/high-risk-ingest.mjs +0 -321
  107. package/cli/lib/high-risk-review.mjs +0 -267
  108. package/cli/lib/internal/contracts-parse-high-risk.mjs +0 -131
  109. package/cli/lib/internal/contracts-validators.mjs +0 -399
  110. package/cli/lib/internal/doctor-bootstrap-surface.mjs +0 -406
  111. package/cli/lib/internal/doctor-delegated-surface.mjs +0 -256
  112. package/cli/lib/internal/doctor-finalize.mjs +0 -383
  113. package/cli/lib/internal/doctor-format.mjs +0 -286
  114. package/cli/lib/internal/doctor-inspectors.mjs +0 -327
  115. package/cli/lib/internal/doctor-state.mjs +0 -205
  116. package/cli/lib/internal/validators-artifacts.mjs +0 -515
  117. package/cli/lib/sweep-design-runtime/common.mjs +0 -246
  118. package/cli/lib/sweep-design-runtime/engine.mjs +0 -733
  119. package/cli/lib/sweep-design-runtime/fix-topic.mjs +0 -414
  120. package/cli/lib/sweep-design-runtime/lifecycle.mjs +0 -54
  121. package/cli/lib/sweep-design-runtime/results.mjs +0 -324
  122. package/cli/lib/sweep-design.mjs +0 -8
  123. package/cli/lib/topic-artifacts.mjs +0 -186
  124. package/cli/lib/topic-authority-coverage.mjs +0 -73
  125. package/cli/lib/topic-closeout.mjs +0 -560
  126. package/cli/lib/topic-common.mjs +0 -404
  127. package/cli/lib/topic-decisions.mjs +0 -332
  128. package/cli/lib/topic-draft-packets.mjs +0 -167
  129. package/cli/lib/topic-execution.mjs +0 -533
  130. package/cli/lib/topic-goal.mjs +0 -440
  131. package/cli/lib/topic-ledger.mjs +0 -281
  132. package/cli/lib/topic-lifecycle-artifacts.mjs +0 -173
  133. package/cli/lib/topic-root-validation.mjs +0 -288
  134. package/cli/lib/topic-runner-commands.mjs +0 -174
  135. package/cli/lib/topic-runner-deferral.mjs +0 -532
  136. package/cli/lib/topic-runner-stale-gates.mjs +0 -114
  137. package/cli/lib/topic-runner-validation.mjs +0 -138
  138. package/cli/lib/topic-runner.mjs +0 -727
  139. package/cli/lib/topic-scaffold.mjs +0 -252
  140. package/cli/lib/topic-waves.mjs +0 -403
  141. package/cli/lib/topic.mjs +0 -81
  142. package/config/audit-execution-artifacts.yaml +0 -20
  143. package/config/external-execution-artifacts.yaml +0 -16
  144. package/config/host-adapter.yaml +0 -30
  145. package/config/host-profile.yaml +0 -29
  146. package/config/installer-evidence.yaml +0 -31
  147. package/config/skill-installer.yaml +0 -23
  148. package/config/skill-manifest.yaml +0 -48
  149. package/config/skills.yaml +0 -30
  150. package/contracts/acceptance.schema.yaml +0 -16
  151. package/contracts/admission-checklist.schema.yaml +0 -15
  152. package/contracts/audit-chunk.schema.yaml +0 -123
  153. package/contracts/audit-closeout.schema.yaml +0 -51
  154. package/contracts/audit-finding.schema.yaml +0 -61
  155. package/contracts/audit-ledger.schema.yaml +0 -138
  156. package/contracts/audit-plan.schema.yaml +0 -138
  157. package/contracts/audit-remediation-map.schema.yaml +0 -52
  158. package/contracts/audit-rerun.schema.yaml +0 -31
  159. package/contracts/audit-sweep-result.yaml +0 -53
  160. package/contracts/authority-convergence-audit.schema.yaml +0 -19
  161. package/contracts/closeout.schema.yaml +0 -25
  162. package/contracts/decision-review.schema.yaml +0 -16
  163. package/contracts/doc-spec-audit-result.yaml +0 -19
  164. package/contracts/execution-packet.schema.yaml +0 -49
  165. package/contracts/external-host-compatibility.yaml +0 -22
  166. package/contracts/forbidden-shortcuts.catalog.yaml +0 -23
  167. package/contracts/high-risk-admission.schema.yaml +0 -23
  168. package/contracts/high-risk-execution-result.yaml +0 -20
  169. package/contracts/orchestration-state.schema.yaml +0 -41
  170. package/contracts/overflow-continuation.schema.yaml +0 -12
  171. package/contracts/packet.schema.yaml +0 -30
  172. package/contracts/pending-note.schema.yaml +0 -17
  173. package/contracts/prompt.schema.yaml +0 -12
  174. package/contracts/remediation.schema.yaml +0 -16
  175. package/contracts/result.schema.yaml +0 -24
  176. package/contracts/spec-reconstruction-result.yaml +0 -41
  177. package/contracts/sweep-design-result.yaml +0 -349
  178. package/contracts/topic-goal.schema.yaml +0 -87
  179. package/contracts/topic-run-ledger.schema.yaml +0 -72
  180. package/contracts/topic-step-decision.schema.yaml +0 -45
  181. package/contracts/topic.schema.yaml +0 -65
  182. package/contracts/true-close.schema.yaml +0 -15
  183. package/contracts/wave.schema.yaml +0 -29
  184. package/contracts/worker-output.schema.yaml +0 -15
  185. package/contracts/workflow-consumer.schema.yaml +0 -110
  186. package/methodology/audit-sweep-p0p1-recall.yaml +0 -45
  187. package/methodology/authority-convergence-policy.yaml +0 -42
  188. package/methodology/overflow-continuation-policy.yaml +0 -14
  189. package/methodology/skill-exchange-projection.yaml +0 -114
  190. package/methodology/skill-handoff.yaml +0 -34
  191. package/methodology/skill-installer-result.yaml +0 -27
  192. package/methodology/skill-installer-summary-projection.yaml +0 -181
  193. package/methodology/skill-runtime.yaml +0 -23
  194. package/methodology/spec-target-truth-profile.yaml +0 -46
  195. package/methodology/topic-lifecycle-report.yaml +0 -144
  196. package/methodology/topic-lifecycle.yaml +0 -37
  197. package/methodology/topic-naming-ontology.yaml +0 -21
  198. package/methodology/topic-ontology.yaml +0 -38
  199. package/methodology/topic-validation-policy.yaml +0 -9
  200. package/methodology/wave-dag-policy.yaml +0 -14
  201. package/spec/_meta/command-gating-matrix.yaml +0 -143
  202. package/spec/_meta/generate-drift-migration-checklist.yaml +0 -137
  203. package/spec/_meta/governance-routing-cutover-checklist.yaml +0 -35
  204. package/spec/_meta/phase2-impacted-surface-matrix.yaml +0 -44
  205. package/spec/_meta/spec-authority-cutover-readiness.yaml +0 -102
  206. package/spec/bootstrap-state.yaml +0 -99
@@ -1,654 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { isDeepStrictEqual } from "node:util";
3
-
4
- import { writeJsonRef } from "./common.mjs";
5
- import { validateEvidenceEnvelope } from "./ingest.mjs";
6
- import { buildAuditValidityForEvidence } from "./audit-validity.mjs";
7
- import { isPlainObject } from "../value-helpers.mjs";
8
-
9
- const ALLOWED_TOP_LEVEL_FIELDS = new Set(["chunk_id", "auditor", "coverage", "findings"]);
10
- export const P0P1_RULE_CHECK_IDS = [
11
- "fail_open_or_pseudo_success",
12
- "partial_coverage_misrepresented_as_complete",
13
- "authority_boundary_or_private_import_bypass",
14
- "permission_or_capability_bypass",
15
- "ungated_destructive_action",
16
- "provider_or_model_hardcoding",
17
- "app_local_shadow_truth",
18
- ];
19
-
20
- function hasUnexpectedTopLevelFields(evidence) {
21
- return Object.keys(evidence).filter((key) => !ALLOWED_TOP_LEVEL_FIELDS.has(key));
22
- }
23
-
24
- function firstJsonObjectPrefix(rawText) {
25
- const start = rawText.indexOf("{");
26
- if (start < 0) {
27
- return null;
28
- }
29
- let depth = 0;
30
- let inString = false;
31
- let escaped = false;
32
- for (let index = start; index < rawText.length; index += 1) {
33
- const char = rawText[index];
34
- if (inString) {
35
- if (escaped) {
36
- escaped = false;
37
- } else if (char === "\\") {
38
- escaped = true;
39
- } else if (char === "\"") {
40
- inString = false;
41
- }
42
- continue;
43
- }
44
- if (char === "\"") {
45
- inString = true;
46
- continue;
47
- }
48
- if (char === "{") {
49
- depth += 1;
50
- }
51
- if (char === "}") {
52
- depth -= 1;
53
- if (depth === 0) {
54
- return {
55
- jsonText: rawText.slice(start, index + 1),
56
- trailing: rawText.slice(index + 1),
57
- };
58
- }
59
- if (depth < 0) {
60
- return null;
61
- }
62
- }
63
- }
64
- return null;
65
- }
66
-
67
- function parseCodexRawJson(rawText) {
68
- try {
69
- return { ok: true, value: JSON.parse(rawText) };
70
- } catch {
71
- const singleBraceRepair = parseWithUniqueDroppedClosingBrace(rawText);
72
- if (singleBraceRepair.ok) {
73
- return singleBraceRepair;
74
- }
75
- const prefix = firstJsonObjectPrefix(rawText);
76
- const trailing = prefix?.trailing?.trim() ?? "";
77
- if (prefix && /^}*$/.test(trailing)) {
78
- try {
79
- return { ok: true, value: JSON.parse(prefix.jsonText), repaired: trailing ? "ignored_trailing_closing_braces" : null };
80
- } catch {
81
- // Fall through to the contract error below.
82
- }
83
- }
84
- if (prefix && /^,\s*"findings_count"\s*:\s*\d+\s*[}]\s*$/u.test(trailing)) {
85
- try {
86
- const value = JSON.parse(prefix.jsonText);
87
- if (isPlainObject(value) && hasUnexpectedTopLevelFields(value).length === 0) {
88
- return { ok: true, value, repaired: "ignored_trailing_findings_count_metadata" };
89
- }
90
- } catch {
91
- // Fall through to the contract error below.
92
- }
93
- }
94
- const duplicateTrailingFieldRepair = parseWithDuplicateTrailingTopLevelFields(prefix, trailing);
95
- if (duplicateTrailingFieldRepair.ok) {
96
- return duplicateTrailingFieldRepair;
97
- }
98
- return { ok: false, error: "Codex auditor raw output must be exact JSON, without markdown or transcript prose" };
99
- }
100
- }
101
-
102
- function parseWithDuplicateTrailingTopLevelFields(prefix, trailing) {
103
- if (!prefix || !trailing.startsWith(",") || !trailing.endsWith("}")) {
104
- return { ok: false };
105
- }
106
- try {
107
- const value = JSON.parse(prefix.jsonText);
108
- if (!isPlainObject(value) || hasUnexpectedTopLevelFields(value).length > 0) {
109
- return { ok: false };
110
- }
111
- const trailingFields = JSON.parse(`{${trailing.slice(1)}`);
112
- if (!isPlainObject(trailingFields)) {
113
- return { ok: false };
114
- }
115
- const keys = Object.keys(trailingFields);
116
- if (keys.length === 0 || keys.some((key) => !ALLOWED_TOP_LEVEL_FIELDS.has(key))) {
117
- return { ok: false };
118
- }
119
- if (!keys.every((key) => isDeepStrictEqual(trailingFields[key], value[key]))) {
120
- return { ok: false };
121
- }
122
- return { ok: true, value, repaired: "ignored_duplicate_trailing_top_level_fields" };
123
- } catch {
124
- return { ok: false };
125
- }
126
- }
127
-
128
- function parseWithUniqueDroppedClosingBrace(rawText) {
129
- const candidates = [];
130
- const candidateKeys = new Set();
131
- for (let index = 0; index < rawText.length; index += 1) {
132
- if (rawText[index] !== "}") {
133
- continue;
134
- }
135
- try {
136
- const value = JSON.parse(`${rawText.slice(0, index)}${rawText.slice(index + 1)}`);
137
- if (isPlainObject(value) && hasUnexpectedTopLevelFields(value).length === 0) {
138
- const key = JSON.stringify(value);
139
- if (!candidateKeys.has(key)) {
140
- candidateKeys.add(key);
141
- candidates.push(value);
142
- }
143
- }
144
- } catch {
145
- // Keep searching for an unambiguous single-token structural repair.
146
- }
147
- if (candidates.length > 1) {
148
- return { ok: false };
149
- }
150
- }
151
- if (candidates.length === 1) {
152
- return { ok: true, value: candidates[0], repaired: "dropped_single_extra_closing_brace" };
153
- }
154
- return { ok: false };
155
- }
156
-
157
- function normalizeRefs(refs) {
158
- return Array.isArray(refs)
159
- ? refs.map((ref) => typeof ref === "string" ? ref.replace(/\\/g, "/") : ref)
160
- : [];
161
- }
162
-
163
- function uniqueRefs(refs) {
164
- return [...new Set(refs)].sort();
165
- }
166
-
167
- function refsOutsideSet(refs, allowedSet) {
168
- return refs.filter((ref) => typeof ref !== "string" || !allowedSet.has(ref));
169
- }
170
-
171
- function isNonImplementationContextRef(ref) {
172
- if (typeof ref !== "string") {
173
- return false;
174
- }
175
- const normalized = ref.replace(/\\/g, "/");
176
- return /(^|\/)AGENTS\.md$/u.test(normalized)
177
- || /(^|\/)README\.md$/u.test(normalized)
178
- || normalized.startsWith(".nimi/spec/")
179
- || normalized.startsWith(".nimi/contracts/")
180
- || normalized.startsWith(".nimi/methodology/")
181
- || normalized.startsWith("package://@nimiplatform/nimi-coding/methodology/")
182
- || normalized.startsWith("package://@nimiplatform/nimi-coding/spec/");
183
- }
184
-
185
- function stripNonImplementationContextRefs(refs, evidenceInventorySet) {
186
- return refs.filter((ref) => !isNonImplementationContextRef(ref));
187
- }
188
-
189
- function normalizeFindingEnvelope(finding, evidenceInventorySet, authorityRefSet = new Set()) {
190
- if (!isPlainObject(finding)) {
191
- return finding;
192
- }
193
- const severityInput = typeof finding.severity === "string" && finding.severity.trim()
194
- ? finding.severity
195
- : typeof finding.priority === "string" && finding.priority.trim()
196
- ? finding.priority
197
- : typeof finding.impact === "string" && finding.impact.trim()
198
- ? finding.impact
199
- : null;
200
- const severity = typeof severityInput === "string" ? severityInput.trim().toLowerCase() : "";
201
- const patch = {};
202
- if (severity === "p0") {
203
- patch.severity = "critical";
204
- }
205
- if (severity === "p1") {
206
- patch.severity = "high";
207
- }
208
- if (["critical", "high", "medium", "low"].includes(severity)) {
209
- patch.severity = severity;
210
- }
211
- const actionability = typeof finding.actionability === "string"
212
- ? finding.actionability.trim().toLowerCase().replace(/_/g, "-")
213
- : "";
214
- if (!actionability) {
215
- patch.actionability = "needs-decision";
216
- }
217
- if (["needs-fix", "manual-fix", "manual-review", "fix-required", "needs-remediation"].includes(actionability)) {
218
- patch.actionability = "needs-decision";
219
- }
220
- if (actionability === "auto-fix" || actionability === "autofix") {
221
- patch.actionability = "auto-fix";
222
- }
223
- if (actionability === "deferred" || actionability === "backlog" || actionability === "deferred-backlog") {
224
- patch.actionability = "deferred-backlog";
225
- }
226
- const confidence = typeof finding.confidence === "string"
227
- ? finding.confidence.trim().toLowerCase()
228
- : "";
229
- if (!confidence) {
230
- patch.confidence = "high";
231
- }
232
- if (["high", "medium", "low"].includes(confidence)) {
233
- patch.confidence = confidence;
234
- }
235
- if (typeof finding.category !== "string" || !finding.category.trim()) {
236
- const ruleId = Array.isArray(finding.rule_ids)
237
- ? finding.rule_ids.find((entry) => typeof entry === "string" && entry.trim())
238
- : null;
239
- if (ruleId) {
240
- patch.category = ruleId.trim();
241
- } else if (typeof finding.rule_check_id === "string" && finding.rule_check_id.trim()) {
242
- patch.category = finding.rule_check_id.trim();
243
- } else if (typeof finding.rule_id === "string" && finding.rule_id.trim()) {
244
- patch.category = finding.rule_id.trim();
245
- } else if (typeof finding.defect_class === "string" && finding.defect_class.trim()) {
246
- patch.category = finding.defect_class.trim();
247
- }
248
- }
249
- if (typeof finding.title !== "string" || !finding.title.trim()) {
250
- const summary = typeof finding.summary === "string" && finding.summary.trim() ? finding.summary.trim() : null;
251
- if (summary) {
252
- patch.title = summary;
253
- }
254
- }
255
- if (typeof finding.description !== "string" || !finding.description.trim()) {
256
- const reasoning = typeof finding.reasoning === "string" && finding.reasoning.trim()
257
- ? finding.reasoning.trim()
258
- : typeof finding.details === "string" && finding.details.trim()
259
- ? finding.details.trim()
260
- : typeof finding.summary === "string" && finding.summary.trim()
261
- ? finding.summary.trim()
262
- : null;
263
- if (reasoning) {
264
- patch.description = reasoning;
265
- }
266
- }
267
- if (!isPlainObject(finding.location) || typeof finding.location.file !== "string" || !finding.location.file.trim()) {
268
- const location = Array.isArray(finding.locations)
269
- ? finding.locations.find((entry) => isPlainObject(entry)
270
- && typeof entry.ref === "string"
271
- && evidenceInventorySet.has(entry.ref.replace(/\\/g, "/")))
272
- : null;
273
- if (location) {
274
- patch.location = {
275
- file: location.ref.replace(/\\/g, "/"),
276
- ...(Number.isInteger(location.line) && location.line > 0 ? { line: location.line } : {}),
277
- ...(typeof location.symbol === "string" && location.symbol.trim() ? { symbol: location.symbol.trim() } : {}),
278
- };
279
- }
280
- const implementationRefs = normalizeRefs(finding.implementation_refs);
281
- const locationFile = implementationRefs.find((ref) => evidenceInventorySet.has(ref));
282
- if (!patch.location && locationFile) {
283
- patch.location = {
284
- file: locationFile,
285
- };
286
- }
287
- const authorityRefs = normalizeRefs(finding.authority_refs);
288
- const authorityLocationFile = authorityRefs.find((ref) => authorityRefSet.has(ref));
289
- if (!patch.location && authorityLocationFile) {
290
- patch.location = {
291
- file: authorityLocationFile,
292
- };
293
- }
294
- }
295
- if (!isPlainObject(finding.evidence)) {
296
- const summary = typeof finding.description === "string" && finding.description.trim()
297
- ? finding.description.trim()
298
- : typeof finding.impact === "string" && finding.impact.trim()
299
- ? finding.impact.trim()
300
- : typeof finding.title === "string" && finding.title.trim()
301
- ? finding.title.trim()
302
- : "";
303
- const auditorReasoning = typeof finding.recommendation === "string" && finding.recommendation.trim()
304
- ? finding.recommendation.trim()
305
- : summary;
306
- if (summary && auditorReasoning) {
307
- patch.evidence = {
308
- summary,
309
- auditor_reasoning: auditorReasoning,
310
- };
311
- }
312
- }
313
- return Object.keys(patch).length > 0 ? { ...finding, ...patch } : finding;
314
- }
315
-
316
- function validateCodexProvenance(evidence, expectedPacketRef) {
317
- const provenance = evidence?.auditor?.provenance;
318
- if (!isPlainObject(provenance)) {
319
- return { ok: false, error: "auditor.provenance is required" };
320
- }
321
- if (provenance.kind !== "semantic_audit") {
322
- return { ok: false, error: "auditor.provenance.kind must be semantic_audit" };
323
- }
324
- if (provenance.packet_ref !== expectedPacketRef) {
325
- return { ok: false, error: "auditor.provenance.packet_ref must match the auditor packet" };
326
- }
327
- const tracePresent = ["session_ref", "transcript_ref", "review_ref"]
328
- .some((field) => typeof provenance[field] === "string" && provenance[field].trim().length > 0);
329
- if (!tracePresent) {
330
- return { ok: false, error: "auditor.provenance requires session_ref, transcript_ref, or review_ref" };
331
- }
332
- return { ok: true };
333
- }
334
-
335
- export function validateCodexAuditorEvidence(evidence, chunk, expectedPacketRef) {
336
- if (!isPlainObject(evidence)) {
337
- return { ok: false, error: "Codex auditor output must be a JSON object" };
338
- }
339
- if (Object.prototype.hasOwnProperty.call(evidence, "p0p1_rule_checks")) {
340
- return { ok: false, error: "Codex auditor output must place p0p1_rule_checks under coverage" };
341
- }
342
- const unexpectedFields = hasUnexpectedTopLevelFields(evidence);
343
- if (unexpectedFields.length > 0) {
344
- return { ok: false, error: `Codex auditor output has unexpected top-level fields: ${unexpectedFields.join(", ")}` };
345
- }
346
- if (!isPlainObject(evidence.auditor)
347
- || typeof evidence.auditor.mode !== "string"
348
- || !evidence.auditor.mode.trim()
349
- || typeof evidence.auditor.methodology_ref !== "string"
350
- || !evidence.auditor.methodology_ref.trim()) {
351
- return { ok: false, error: "Codex auditor output requires auditor.mode and auditor.methodology_ref" };
352
- }
353
- const provenance = validateCodexProvenance(evidence, expectedPacketRef);
354
- if (!provenance.ok) {
355
- return provenance;
356
- }
357
- const envelope = validateEvidenceEnvelope(evidence, chunk);
358
- if (!envelope.ok) {
359
- return envelope;
360
- }
361
- const auditValidity = buildAuditValidityForEvidence(chunk, evidence);
362
- if (auditValidity.posture === "invalid") {
363
- return {
364
- ok: false,
365
- error: `audit evidence is invalid (${auditValidity.blockers.map((blocker) => blocker.id).join(", ")})`,
366
- auditValidity,
367
- };
368
- }
369
- return { ok: true, auditValidity };
370
- }
371
-
372
- function semanticOutputRef(rawOutput, chunk, expectedAuthorityRefs) {
373
- if (rawOutput?.chunk_id !== chunk.chunk_id) {
374
- return { ok: false, error: "Codex auditor raw output chunk_id must match the chunk" };
375
- }
376
- if (Object.prototype.hasOwnProperty.call(rawOutput, "p0p1_rule_checks")) {
377
- return { ok: false, error: "Codex auditor output must place p0p1_rule_checks under coverage" };
378
- }
379
- const unexpectedFields = hasUnexpectedTopLevelFields(rawOutput);
380
- if (unexpectedFields.length > 0) {
381
- return { ok: false, error: `Codex auditor output has unexpected top-level fields: ${unexpectedFields.join(", ")}` };
382
- }
383
- if (!isPlainObject(rawOutput.coverage)) {
384
- return { ok: false, error: "Codex auditor raw output coverage is required" };
385
- }
386
- if (!Array.isArray(rawOutput.findings)) {
387
- return { ok: false, error: "Codex auditor raw output findings must be an array" };
388
- }
389
- const outcomes = rawOutput.coverage.authority_outcomes;
390
- if (!Array.isArray(outcomes)) {
391
- return { ok: false, error: "Codex auditor raw output coverage.authority_outcomes is required" };
392
- }
393
- if (outcomes.length !== expectedAuthorityRefs.length) {
394
- return { ok: false, error: "Codex auditor raw output must contain one authority_outcome per authority ref" };
395
- }
396
- return { ok: true };
397
- }
398
-
399
- function normalizeOutcome(rawOutcome, index, authorityRef, evidenceInventorySet) {
400
- if (!isPlainObject(rawOutcome)) {
401
- return { ok: false, error: `authority_outcomes[${index}] must be an object` };
402
- }
403
- const rawAuthorityRef = typeof rawOutcome.authority_ref === "string" ? rawOutcome.authority_ref.replace(/\\/g, "/") : authorityRef;
404
- if (rawAuthorityRef !== authorityRef) {
405
- return { ok: false, error: `authority_outcomes[${index}].authority_ref must match ${authorityRef}` };
406
- }
407
- const status = rawOutcome.status ?? "audited";
408
- if (!["audited", "blocked", "not_applicable"].includes(status)) {
409
- return { ok: false, error: `authority_outcomes[${index}].status must be audited, blocked, or not_applicable` };
410
- }
411
- const inspectedImplementationRefs = uniqueRefs([
412
- ...normalizeRefs(rawOutcome.inspected_implementation_refs),
413
- ...normalizeRefs(rawOutcome.implementation_evidence_refs),
414
- ]);
415
- const contextOnlyRefs = inspectedImplementationRefs.filter((ref) => isNonImplementationContextRef(ref));
416
- const implementationRefs = stripNonImplementationContextRefs(inspectedImplementationRefs, evidenceInventorySet);
417
- const invalidImplementationRefs = refsOutsideSet(implementationRefs, evidenceInventorySet);
418
- if (invalidImplementationRefs.length > 0) {
419
- return {
420
- ok: false,
421
- error: `authority_outcomes[${index}] inspected implementation refs must belong to chunk evidence inventory: ${invalidImplementationRefs.join(", ")}`,
422
- };
423
- }
424
- const normalized = {
425
- authority_ref: authorityRef,
426
- status,
427
- evidence_refs: uniqueRefs([authorityRef, ...implementationRefs]),
428
- implementation_evidence_refs: implementationRefs,
429
- };
430
- if (typeof rawOutcome.negative_reasoning === "string" && rawOutcome.negative_reasoning.trim()) {
431
- normalized.negative_reasoning = rawOutcome.negative_reasoning.trim();
432
- }
433
- if (!normalized.negative_reasoning && typeof rawOutcome.reasoning === "string" && rawOutcome.reasoning.trim()) {
434
- normalized.negative_reasoning = rawOutcome.reasoning.trim();
435
- }
436
- if (typeof rawOutcome.reason === "string" && rawOutcome.reason.trim()) {
437
- normalized.reason = rawOutcome.reason.trim();
438
- }
439
- if (typeof rawOutcome.implementation_not_applicable_reason === "string" && rawOutcome.implementation_not_applicable_reason.trim()) {
440
- normalized.implementation_not_applicable_reason = rawOutcome.implementation_not_applicable_reason.trim();
441
- }
442
- if (!normalized.implementation_not_applicable_reason && implementationRefs.length === 0 && contextOnlyRefs.length > 0) {
443
- normalized.implementation_not_applicable_reason = `Only non-implementation context refs were cited: ${uniqueRefs(contextOnlyRefs).join(", ")}.`;
444
- }
445
- if (!normalized.reason && status === "not_applicable" && normalized.implementation_not_applicable_reason) {
446
- normalized.reason = normalized.implementation_not_applicable_reason;
447
- }
448
- if (!normalized.reason && ["blocked", "not_applicable"].includes(status) && normalized.negative_reasoning) {
449
- normalized.reason = normalized.negative_reasoning;
450
- }
451
- return {
452
- ok: true,
453
- outcome: normalized,
454
- inspectedImplementationRefs: implementationRefs,
455
- };
456
- }
457
-
458
- function normalizeRuleChecks(rawRuleChecks, evidenceInventorySet, authorityRefSet) {
459
- if (rawRuleChecks === undefined) {
460
- return { ok: true, ruleChecks: [], implementationRefs: [] };
461
- }
462
- if (!Array.isArray(rawRuleChecks)) {
463
- return { ok: false, error: "coverage.p0p1_rule_checks must be an array when present" };
464
- }
465
- const ruleChecks = [];
466
- const implementationRefs = [];
467
- const checkedIds = [];
468
- for (const [index, rawCheck] of rawRuleChecks.entries()) {
469
- if (!isPlainObject(rawCheck)) {
470
- return { ok: false, error: `coverage.p0p1_rule_checks[${index}] must be an object` };
471
- }
472
- const id = typeof rawCheck.id === "string" ? rawCheck.id : "";
473
- if (!P0P1_RULE_CHECK_IDS.includes(id)) {
474
- return { ok: false, error: `coverage.p0p1_rule_checks[${index}].id is not a required P0/P1 rule id` };
475
- }
476
- checkedIds.push(id);
477
- if (!["checked", "not_applicable"].includes(rawCheck.status)) {
478
- return { ok: false, error: `coverage.p0p1_rule_checks[${index}].status must be checked or not_applicable` };
479
- }
480
- if (typeof rawCheck.negative_reasoning !== "string" || !rawCheck.negative_reasoning.trim()) {
481
- return { ok: false, error: `coverage.p0p1_rule_checks[${index}].negative_reasoning is required` };
482
- }
483
- const inputRefs = uniqueRefs(normalizeRefs(rawCheck.implementation_refs));
484
- const rawRefs = stripNonImplementationContextRefs(inputRefs, evidenceInventorySet);
485
- const refs = rawRefs.filter((ref) => evidenceInventorySet.has(ref));
486
- const invalidRawRefs = rawRefs.filter((ref) => !evidenceInventorySet.has(ref) && !authorityRefSet.has(ref));
487
- const status = rawCheck.status === "checked"
488
- && refs.length === 0
489
- && inputRefs.length > 0
490
- && inputRefs.every((ref) => isNonImplementationContextRef(ref))
491
- ? "not_applicable"
492
- : rawCheck.status;
493
- if (status === "checked" && refs.length === 0) {
494
- return { ok: false, error: `coverage.p0p1_rule_checks[${index}].implementation_refs is required when status is checked` };
495
- }
496
- if (invalidRawRefs.length > 0) {
497
- return {
498
- ok: false,
499
- error: `coverage.p0p1_rule_checks[${index}].implementation_refs must belong to chunk evidence inventory: ${invalidRawRefs.join(", ")}`,
500
- };
501
- }
502
- implementationRefs.push(...refs);
503
- ruleChecks.push({
504
- id,
505
- status,
506
- implementation_refs: refs,
507
- negative_reasoning: rawCheck.negative_reasoning.trim(),
508
- });
509
- }
510
- const missingRuleCheckIds = P0P1_RULE_CHECK_IDS.filter((id) => !checkedIds.includes(id));
511
- if (missingRuleCheckIds.length > 0) {
512
- return { ok: false, error: `coverage.p0p1_rule_checks must include every required P0/P1 rule id: missing ${missingRuleCheckIds.join(", ")}` };
513
- }
514
- return { ok: true, ruleChecks, implementationRefs: uniqueRefs(implementationRefs) };
515
- }
516
-
517
- function deriveP0P1NegativeReasoningFromRuleChecks(ruleChecks) {
518
- const reasons = uniqueRefs(ruleChecks
519
- .map((check) => typeof check.negative_reasoning === "string" ? check.negative_reasoning.trim() : "")
520
- .filter(Boolean));
521
- if (reasons.length === 0) {
522
- return null;
523
- }
524
- return reasons.join(" ");
525
- }
526
-
527
- function normalizeCodexSemanticOutput(rawOutput, chunk, options) {
528
- if (!isPlainObject(rawOutput)) {
529
- return { ok: false, error: "Codex auditor output must be a JSON object" };
530
- }
531
- const authorityRefs = chunk.authority_refs ?? chunk.files;
532
- const semanticShape = semanticOutputRef(rawOutput, chunk, authorityRefs);
533
- if (!semanticShape.ok) {
534
- return semanticShape;
535
- }
536
-
537
- const evidenceInventory = chunk.planning_basis === "spec_authority" ? (chunk.evidence_inventory ?? []) : (chunk.files ?? []);
538
- const p0p1ImplementationInventory = evidenceInventory.filter((ref) => !isNonImplementationContextRef(ref));
539
- const evidenceInventorySet = new Set(evidenceInventory);
540
- const authorityRefSet = new Set(authorityRefs);
541
- const outcomes = [];
542
- const inspectedRefs = [];
543
- for (const [index, authorityRef] of authorityRefs.entries()) {
544
- const rawOutcome = rawOutput.coverage.authority_outcomes[index];
545
- const normalized = normalizeOutcome(rawOutcome, index, authorityRef, evidenceInventorySet);
546
- if (!normalized.ok) {
547
- return normalized;
548
- }
549
- outcomes.push(normalized.outcome);
550
- inspectedRefs.push(...normalized.inspectedImplementationRefs);
551
- }
552
-
553
- const ruleChecks = normalizeRuleChecks(rawOutput.coverage.p0p1_rule_checks, evidenceInventorySet, authorityRefSet);
554
- if (!ruleChecks.ok) {
555
- return ruleChecks;
556
- }
557
- const p0p1EvidenceRefs = uniqueRefs([
558
- ...inspectedRefs,
559
- ...ruleChecks.implementationRefs,
560
- ...normalizeRefs(rawOutput.coverage.p0p1_evidence_refs),
561
- ...normalizeRefs(rawOutput.coverage.inspected_implementation_refs),
562
- ]);
563
- const normalizedP0P1EvidenceRefs = stripNonImplementationContextRefs(p0p1EvidenceRefs, evidenceInventorySet);
564
- const invalidP0P1EvidenceRefs = refsOutsideSet(normalizedP0P1EvidenceRefs, evidenceInventorySet);
565
- if (invalidP0P1EvidenceRefs.length > 0) {
566
- return {
567
- ok: false,
568
- error: `coverage inspected implementation refs must belong to chunk evidence inventory: ${invalidP0P1EvidenceRefs.join(", ")}`,
569
- };
570
- }
571
-
572
- const evidence = {
573
- chunk_id: chunk.chunk_id,
574
- auditor: {
575
- id: typeof rawOutput.auditor?.id === "string" && rawOutput.auditor.id.trim() ? rawOutput.auditor.id : options.auditorId,
576
- mode: options.auditorMode ?? "codex_semantic_audit",
577
- methodology_ref: "package://@nimiplatform/nimi-coding/methodology/audit-sweep-p0p1-recall.yaml",
578
- provenance: {
579
- kind: "semantic_audit",
580
- packet_ref: options.packetRef,
581
- session_ref: options.sessionRef,
582
- transcript_ref: options.transcriptRef,
583
- },
584
- },
585
- coverage: {
586
- files: chunk.files,
587
- authority_refs: authorityRefs,
588
- evidence_files: evidenceInventory,
589
- authority_outcomes: outcomes,
590
- p0p1_evidence_refs: normalizedP0P1EvidenceRefs,
591
- p0p1_rule_checks: ruleChecks.ruleChecks,
592
- },
593
- findings: rawOutput.findings.map((finding) => normalizeFindingEnvelope(finding, evidenceInventorySet, authorityRefSet)),
594
- };
595
- if (typeof rawOutput.coverage.p0p1_negative_reasoning === "string" && rawOutput.coverage.p0p1_negative_reasoning.trim()) {
596
- evidence.coverage.p0p1_negative_reasoning = rawOutput.coverage.p0p1_negative_reasoning.trim();
597
- } else if (evidence.findings.length === 0) {
598
- const derivedReasoning = deriveP0P1NegativeReasoningFromRuleChecks(ruleChecks.ruleChecks);
599
- if (derivedReasoning) {
600
- evidence.coverage.p0p1_negative_reasoning = derivedReasoning;
601
- }
602
- }
603
- if (typeof rawOutput.coverage.p0p1_implementation_not_applicable_reason === "string" && rawOutput.coverage.p0p1_implementation_not_applicable_reason.trim()) {
604
- evidence.coverage.p0p1_implementation_not_applicable_reason = rawOutput.coverage.p0p1_implementation_not_applicable_reason.trim();
605
- }
606
- if (!evidence.coverage.p0p1_implementation_not_applicable_reason && p0p1ImplementationInventory.length === 0) {
607
- const outcomeReasons = outcomes
608
- .map((outcome) => outcome.implementation_not_applicable_reason)
609
- .filter((reason) => typeof reason === "string" && reason.trim().length > 0);
610
- if (outcomeReasons.length > 0) {
611
- evidence.coverage.p0p1_implementation_not_applicable_reason = uniqueRefs(outcomeReasons).join(" ");
612
- } else {
613
- evidence.coverage.p0p1_implementation_not_applicable_reason = "The chunk has no in-scope implementation refs after excluding context/governance/authority documents.";
614
- }
615
- }
616
- return { ok: true, evidence };
617
- }
618
-
619
- export async function extractCodexAuditorEvidenceFile(projectRoot, options) {
620
- let rawText = "";
621
- try {
622
- rawText = await readFile(options.rawOutputPath, "utf8");
623
- } catch {
624
- return { ok: false, error: "Codex auditor raw output file is missing" };
625
- }
626
- const parsedRaw = parseCodexRawJson(rawText);
627
- if (!parsedRaw.ok) {
628
- return parsedRaw;
629
- }
630
- const parsed = parsedRaw.value;
631
-
632
- const normalized = normalizeCodexSemanticOutput(parsed, options.chunk, {
633
- packetRef: options.packetRef,
634
- sessionRef: options.sessionRef,
635
- transcriptRef: options.transcriptRef,
636
- auditorId: options.auditorId,
637
- auditorMode: options.auditorMode,
638
- });
639
- if (!normalized.ok) {
640
- return normalized;
641
- }
642
- const validation = validateCodexAuditorEvidence(normalized.evidence, options.chunk, options.packetRef);
643
- if (!validation.ok) {
644
- return validation;
645
- }
646
-
647
- await writeJsonRef(projectRoot, options.evidenceRef, normalized.evidence);
648
- return {
649
- ok: true,
650
- evidence: normalized.evidence,
651
- evidenceRef: options.evidenceRef,
652
- auditValidity: validation.auditValidity,
653
- };
654
- }