@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,57 +0,0 @@
1
- export function formatAuditSweepPayload(payload) {
2
- if (!payload.ok) {
3
- if (payload.error) {
4
- return payload.error;
5
- }
6
- if (payload.checks) {
7
- const failed = payload.checks.filter((entry) => !entry.ok);
8
- return `sweep audit ${payload.sweepId ?? "result"} validation failed\nchecks: ${payload.checks.length - failed.length}/${payload.checks.length}\nfailed: ${failed.map((entry) => entry.reason).join("; ")}\n`;
9
- }
10
- return "sweep audit failed\n";
11
- }
12
-
13
- const lines = [`sweep audit ${payload.sweepId ?? payload.auditCloseout?.sweep_id ?? "result"}`];
14
- for (const [label, value] of [
15
- ["plan", payload.planRef],
16
- ["chunk", payload.chunkRef],
17
- ["ledger", payload.ledgerRef],
18
- ["latest ledger", payload.latestLedgerRef],
19
- ["report", payload.reportRef],
20
- ["remediation map", payload.remediationMapRef],
21
- ["audit closeout", payload.auditCloseoutRef],
22
- ["packet", payload.packetRef],
23
- ["run ledger", payload.runLedgerRef],
24
- ]) {
25
- if (value) {
26
- lines.push(`${label}: ${value}`);
27
- }
28
- }
29
- if (payload.state) {
30
- lines.push(`state: ${payload.state}`);
31
- }
32
- if (payload.chunkCount !== undefined) {
33
- lines.push(`chunks: ${payload.chunkCount}`);
34
- }
35
- if (payload.includedFiles !== undefined) {
36
- lines.push(`included files: ${payload.includedFiles}`);
37
- }
38
- if (payload.findingCount !== undefined) {
39
- lines.push(`findings: ${payload.findingCount}`);
40
- }
41
- if (payload.findingClusterCount !== undefined) {
42
- lines.push(`finding clusters: ${payload.findingClusterCount}`);
43
- }
44
- if (payload.clusteredSymptomCount !== undefined) {
45
- lines.push(`clustered symptoms: ${payload.clusteredSymptomCount}`);
46
- }
47
- if (payload.unresolvedFindingCount !== undefined) {
48
- lines.push(`open findings: ${payload.unresolvedFindingCount}`);
49
- }
50
- if (payload.waveCount !== undefined) {
51
- lines.push(`remediation waves: ${payload.waveCount}`);
52
- }
53
- if (payload.checks) {
54
- lines.push(`checks: ${payload.checks.filter((entry) => entry.ok).length}/${payload.checks.length}`);
55
- }
56
- return `${lines.join("\n")}\n`;
57
- }
@@ -1,486 +0,0 @@
1
- import { copyFile, mkdir, readFile } from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import {
5
- FINDING_ACTIONABILITY,
6
- FINDING_CONFIDENCE,
7
- FINDING_SEVERITY,
8
- appendRunEvent,
9
- artifactPath,
10
- artifactRef,
11
- chunkRef,
12
- ensureIsoTimestamp,
13
- findingsRef,
14
- inputError,
15
- loadChunk,
16
- loadFindings,
17
- loadJsonFile,
18
- loadPlan,
19
- resolveInsideProject,
20
- safeSweepId,
21
- sha256Object,
22
- withAuditSweepMutationLock,
23
- writeYamlRef,
24
- } from "./common.mjs";
25
- import {
26
- buildDuplicateSymptom,
27
- buildRiskBudgetStatus,
28
- clusterAcceptanceMatchesPlan,
29
- createCluster,
30
- deriveFindingCluster,
31
- ensureClusterStore,
32
- findingRequiresCanonicalInCluster,
33
- updateClusterWithCanonical,
34
- } from "./risk-budget.mjs";
35
- import { buildAuditValidityForEvidence, p0p1ImplementationRefsForChunk } from "./audit-validity.mjs";
36
- import { isPlainObject } from "../value-helpers.mjs";
37
- import { pathExists } from "../fs-helpers.mjs";
38
-
39
- export function validateEvidenceEnvelope(evidence, chunk) {
40
- if (!isPlainObject(evidence)) {
41
- return { ok: false, error: "audit evidence must be a JSON object" };
42
- }
43
- if (evidence.chunk_id !== chunk.chunk_id) {
44
- return { ok: false, error: "audit evidence chunk_id must match the ingested chunk" };
45
- }
46
- if (!isPlainObject(evidence.auditor) || typeof evidence.auditor.id !== "string" || !evidence.auditor.id.trim()) {
47
- return { ok: false, error: "audit evidence auditor.id is required" };
48
- }
49
- if (!isPlainObject(evidence.coverage) || !Array.isArray(evidence.coverage.files)) {
50
- return { ok: false, error: "audit evidence coverage.files is required" };
51
- }
52
- if (chunk.planning_basis === "spec_authority") {
53
- if (!Array.isArray(evidence.coverage.authority_refs)) {
54
- return { ok: false, error: "spec-authority audit evidence coverage.authority_refs is required" };
55
- }
56
- const coveredAuthority = [...evidence.coverage.authority_refs].sort();
57
- const expectedAuthority = [...(chunk.authority_refs ?? chunk.files)].sort();
58
- if (coveredAuthority.length !== expectedAuthority.length || coveredAuthority.some((fileRef, index) => fileRef !== expectedAuthority[index])) {
59
- return { ok: false, error: "audit evidence coverage.authority_refs must exactly match chunk authority refs" };
60
- }
61
- const coveredFiles = [...evidence.coverage.files].sort();
62
- if (coveredFiles.length !== expectedAuthority.length || coveredFiles.some((fileRef, index) => fileRef !== expectedAuthority[index])) {
63
- return { ok: false, error: "spec-authority audit evidence coverage.files must exactly match chunk authority refs" };
64
- }
65
- const evidenceFiles = evidence.coverage.evidence_files;
66
- if (!Array.isArray(evidenceFiles)) {
67
- return { ok: false, error: "spec-authority audit evidence coverage.evidence_files is required" };
68
- }
69
- const normalizedEvidenceFiles = evidenceFiles.map((fileRef) => typeof fileRef === "string" ? fileRef.replace(/\\/g, "/") : fileRef);
70
- if (normalizedEvidenceFiles.some((fileRef) => typeof fileRef !== "string")) {
71
- return { ok: false, error: "spec-authority audit evidence coverage.evidence_files must contain file refs" };
72
- }
73
- const expectedEvidenceFiles = [...(chunk.evidence_inventory ?? [])].sort();
74
- const coveredEvidenceFiles = [...normalizedEvidenceFiles].sort();
75
- if (coveredEvidenceFiles.length !== expectedEvidenceFiles.length
76
- || coveredEvidenceFiles.some((fileRef, index) => fileRef !== expectedEvidenceFiles[index])) {
77
- return { ok: false, error: "spec-authority audit evidence coverage.evidence_files must exactly match chunk evidence inventory" };
78
- }
79
- const outcomes = evidence.coverage.authority_outcomes;
80
- if (!Array.isArray(outcomes)) {
81
- return { ok: false, error: "spec-authority audit evidence coverage.authority_outcomes is required" };
82
- }
83
- const expectedAuthoritySet = new Set(expectedAuthority);
84
- const outcomeAuthorityRefs = new Set();
85
- const validStatuses = new Set(["audited", "blocked", "not_applicable"]);
86
- for (const [index, outcome] of outcomes.entries()) {
87
- if (!isPlainObject(outcome)) {
88
- return { ok: false, error: `authority_outcomes[${index}] must be an object` };
89
- }
90
- const authorityRef = typeof outcome.authority_ref === "string" ? outcome.authority_ref.replace(/\\/g, "/") : "";
91
- if (!expectedAuthoritySet.has(authorityRef)) {
92
- return { ok: false, error: `authority_outcomes[${index}].authority_ref must belong to chunk authority_refs` };
93
- }
94
- if (outcomeAuthorityRefs.has(authorityRef)) {
95
- return { ok: false, error: `authority_outcomes contains duplicate authority_ref ${authorityRef}` };
96
- }
97
- outcomeAuthorityRefs.add(authorityRef);
98
- if (!validStatuses.has(outcome.status)) {
99
- return { ok: false, error: `authority_outcomes[${index}].status must be audited, blocked, or not_applicable` };
100
- }
101
- if (!Array.isArray(outcome.evidence_refs)) {
102
- return { ok: false, error: `authority_outcomes[${index}].evidence_refs must be an array` };
103
- }
104
- for (const evidenceRef of outcome.evidence_refs) {
105
- if (typeof evidenceRef !== "string" || !chunkAllowsFindingFile(chunk, evidenceRef.replace(/\\/g, "/"))) {
106
- return { ok: false, error: `authority_outcomes[${index}].evidence_refs must belong to chunk authority refs or evidence inventory` };
107
- }
108
- }
109
- if (outcome.status === "audited" && outcome.evidence_refs.length === 0) {
110
- return { ok: false, error: `authority_outcomes[${index}] audited status requires evidence_refs` };
111
- }
112
- if (outcome.status !== "audited" && (typeof outcome.reason !== "string" || !outcome.reason.trim())) {
113
- return { ok: false, error: `authority_outcomes[${index}] ${outcome.status} status requires reason` };
114
- }
115
- }
116
- if (outcomeAuthorityRefs.size !== expectedAuthority.length) {
117
- return { ok: false, error: "spec-authority audit evidence coverage.authority_outcomes must contain exactly one entry per authority ref" };
118
- }
119
- } else {
120
- const covered = [...evidence.coverage.files].sort();
121
- const expected = [...chunk.files].sort();
122
- if (covered.length !== expected.length || covered.some((fileRef, index) => fileRef !== expected[index])) {
123
- return { ok: false, error: "audit evidence coverage.files must exactly match chunk files" };
124
- }
125
- }
126
- if (!Array.isArray(evidence.findings)) {
127
- return { ok: false, error: "audit evidence findings must be an array" };
128
- }
129
- const p0p1EvidenceRefsValidation = validateP0P1EvidenceRefs(evidence, chunk);
130
- if (!p0p1EvidenceRefsValidation.ok) {
131
- return p0p1EvidenceRefsValidation;
132
- }
133
- return { ok: true };
134
- }
135
-
136
- function isInsideRef(rootRef, fileRef) {
137
- const normalizedRoot = rootRef.replace(/\\/g, "/").replace(/\/$/, "");
138
- return fileRef === normalizedRoot || fileRef.startsWith(`${normalizedRoot}/`);
139
- }
140
-
141
- function chunkAllowsFindingFile(chunk, fileRef) {
142
- if (chunk.files.includes(fileRef)) {
143
- return true;
144
- }
145
- if (chunk.planning_basis !== "spec_authority") {
146
- return false;
147
- }
148
- return Array.isArray(chunk.evidence_inventory) && chunk.evidence_inventory.includes(fileRef);
149
- }
150
-
151
- function chunkAllowsP0P1EvidenceRef(chunk, fileRef) {
152
- return p0p1ImplementationRefsForChunk(chunk).includes(fileRef);
153
- }
154
-
155
- function validateP0P1EvidenceRefs(evidence, chunk) {
156
- if (evidence.coverage.p0p1_evidence_refs === undefined) {
157
- return { ok: true };
158
- }
159
- if (!Array.isArray(evidence.coverage.p0p1_evidence_refs)) {
160
- return { ok: false, error: "coverage.p0p1_evidence_refs must be an array when present" };
161
- }
162
- for (const [index, evidenceRef] of evidence.coverage.p0p1_evidence_refs.entries()) {
163
- const normalizedRef = typeof evidenceRef === "string" ? evidenceRef.replace(/\\/g, "/") : null;
164
- if (!normalizedRef || !chunkAllowsP0P1EvidenceRef(chunk, normalizedRef)) {
165
- return { ok: false, error: `coverage.p0p1_evidence_refs[${index}] must belong to the chunk implementation surface` };
166
- }
167
- }
168
- return { ok: true };
169
- }
170
-
171
- function normalizeFinding(rawFinding, index, chunk, sweepId, evidenceRef, verifiedAt) {
172
- if (!isPlainObject(rawFinding)) {
173
- return { ok: false, error: `finding ${index + 1} must be an object` };
174
- }
175
-
176
- const severity = String(rawFinding.severity ?? "");
177
- if (!FINDING_SEVERITY.has(severity)) {
178
- return { ok: false, error: `finding ${index + 1} severity must be one of critical, high, medium, low` };
179
- }
180
-
181
- const actionability = String(rawFinding.actionability ?? "");
182
- if (!FINDING_ACTIONABILITY.has(actionability)) {
183
- return { ok: false, error: `finding ${index + 1} actionability must be one of auto-fix, needs-decision, deferred-backlog` };
184
- }
185
-
186
- const confidence = String(rawFinding.confidence ?? "");
187
- if (!FINDING_CONFIDENCE.has(confidence)) {
188
- return { ok: false, error: `finding ${index + 1} confidence must be one of high, medium, low` };
189
- }
190
-
191
- const category = typeof rawFinding.category === "string" && rawFinding.category.trim() ? rawFinding.category.trim() : null;
192
- const impact = typeof rawFinding.impact === "string" && rawFinding.impact.trim() ? rawFinding.impact.trim() : null;
193
- const title = typeof rawFinding.title === "string" && rawFinding.title.trim() ? rawFinding.title.trim() : null;
194
- const description = typeof rawFinding.description === "string" && rawFinding.description.trim() ? rawFinding.description.trim() : null;
195
- if (!category || !impact || !title || !description) {
196
- return { ok: false, error: `finding ${index + 1} category, impact, title, and description are required` };
197
- }
198
-
199
- if (!isPlainObject(rawFinding.location) || typeof rawFinding.location.file !== "string" || !rawFinding.location.file.trim()) {
200
- return { ok: false, error: `finding ${index + 1} location.file is required` };
201
- }
202
- const fileRef = rawFinding.location.file.replace(/\\/g, "/");
203
- if (!chunkAllowsFindingFile(chunk, fileRef)) {
204
- return { ok: false, error: `finding ${index + 1} location.file must belong to chunk ${chunk.chunk_id}` };
205
- }
206
-
207
- if (!isPlainObject(rawFinding.evidence)) {
208
- return { ok: false, error: `finding ${index + 1} evidence object is required` };
209
- }
210
- const evidenceSummary = typeof rawFinding.evidence.summary === "string" && rawFinding.evidence.summary.trim()
211
- ? rawFinding.evidence.summary.trim()
212
- : null;
213
- const auditorReasoning = typeof rawFinding.evidence.auditor_reasoning === "string" && rawFinding.evidence.auditor_reasoning.trim()
214
- ? rawFinding.evidence.auditor_reasoning.trim()
215
- : null;
216
- if (!evidenceSummary || !auditorReasoning) {
217
- return { ok: false, error: `finding ${index + 1} evidence.summary and evidence.auditor_reasoning are required` };
218
- }
219
-
220
- const normalized = {
221
- sweep_id: sweepId,
222
- chunk_id: chunk.chunk_id,
223
- owner_domain: chunk.owner_domain,
224
- severity,
225
- category,
226
- actionability,
227
- confidence,
228
- impact,
229
- location: {
230
- file: fileRef,
231
- ...(Number.isInteger(rawFinding.location.line) && rawFinding.location.line > 0 ? { line: rawFinding.location.line } : {}),
232
- ...(typeof rawFinding.location.symbol === "string" && rawFinding.location.symbol.trim() ? { symbol: rawFinding.location.symbol.trim() } : {}),
233
- },
234
- title,
235
- description,
236
- root_cause: null,
237
- cluster_id: null,
238
- evidence: {
239
- summary: evidenceSummary,
240
- auditor_reasoning: auditorReasoning,
241
- ...(typeof rawFinding.evidence.snippet === "string" && rawFinding.evidence.snippet.trim() ? { snippet: rawFinding.evidence.snippet.trim() } : {}),
242
- },
243
- disposition: "open",
244
- evidence_ref: evidenceRef,
245
- detected_at: verifiedAt,
246
- };
247
-
248
- return {
249
- ok: true,
250
- finding: normalized,
251
- fingerprint: sha256Object({
252
- severity,
253
- category,
254
- actionability,
255
- file: normalized.location.file,
256
- line: normalized.location.line ?? null,
257
- symbol: normalized.location.symbol ?? null,
258
- title,
259
- description,
260
- evidenceSummary,
261
- }),
262
- };
263
- }
264
-
265
- function existingFindingForFingerprint(store, fingerprint) {
266
- return store.findings.find((finding) => finding.fingerprint === fingerprint) ?? null;
267
- }
268
-
269
- function sameLocation(left, right) {
270
- return left?.location?.file === right?.location?.file
271
- && (left?.location?.line ?? null) === (right?.location?.line ?? null)
272
- && (left?.location?.symbol ?? null) === (right?.location?.symbol ?? null);
273
- }
274
-
275
- function existingFindingForRetryLocation(store, finding) {
276
- return store.findings.find((existing) => existing.chunk_id === finding.chunk_id
277
- && existing.severity === finding.severity
278
- && sameLocation(existing, finding)) ?? null;
279
- }
280
-
281
- function clusterForFinding(store, finding) {
282
- if (!finding?.cluster_id) {
283
- return null;
284
- }
285
- return store.clusters.find((cluster) => cluster.cluster_id === finding.cluster_id) ?? null;
286
- }
287
-
288
- function recordClusteredSymptom(store, cluster, finding, fingerprint, classification) {
289
- cluster.duplicate_symptoms.push(buildDuplicateSymptom(finding, fingerprint, classification));
290
- cluster.duplicate_symptom_count = (cluster.duplicate_symptom_count ?? 0) + 1;
291
- cluster.source_chunks = [...new Set([...(cluster.source_chunks ?? []), finding.chunk_id])].sort();
292
- cluster.files = [...new Set([...(cluster.files ?? []), finding.location.file])].sort();
293
- cluster.updated_at = finding.detected_at;
294
- store.clustered_symptom_count = (store.clustered_symptom_count ?? 0) + 1;
295
- }
296
-
297
- export async function ingestAuditSweepChunk(projectRoot, options) {
298
- const sweepId = safeSweepId(options.sweepId);
299
- if (!sweepId || typeof options.chunkId !== "string") {
300
- return inputError("nimicoding sweep audit refused: --sweep-id and --chunk-id are required.\n");
301
- }
302
-
303
- const timestampError = ensureIsoTimestamp(options.verifiedAt);
304
- if (timestampError) {
305
- return timestampError;
306
- }
307
-
308
- const source = resolveInsideProject(projectRoot, options.fromPath ?? "", "--from");
309
- if (!source.ok) {
310
- return inputError(source.error);
311
- }
312
- const sourceInfo = await pathExists(source.absolutePath);
313
- if (!sourceInfo || !sourceInfo.isFile()) {
314
- return inputError("nimicoding sweep audit refused: --from must point to an existing JSON file.\n");
315
- }
316
-
317
- return withAuditSweepMutationLock(projectRoot, sweepId, "chunk ingest", async () => {
318
- const planResult = await loadPlan(projectRoot, sweepId);
319
- if (!planResult.ok) {
320
- return inputError(planResult.error);
321
- }
322
- const chunkResult = await loadChunk(projectRoot, sweepId, options.chunkId);
323
- if (!chunkResult.ok) {
324
- return inputError(chunkResult.error);
325
- }
326
- if (chunkResult.chunk.state !== "dispatched") {
327
- return inputError("nimicoding sweep audit refused: chunk ingest requires dispatched state.\n");
328
- }
329
-
330
- const evidenceJson = await loadJsonFile(source.absolutePath);
331
- if (!evidenceJson.ok) {
332
- return inputError("nimicoding sweep audit refused: --from must contain valid JSON.\n");
333
- }
334
- const envelope = validateEvidenceEnvelope(evidenceJson.value, chunkResult.chunk);
335
- if (!envelope.ok) {
336
- return inputError(`nimicoding sweep audit refused: ${envelope.error}.\n`);
337
- }
338
- const auditValidity = buildAuditValidityForEvidence(chunkResult.chunk, evidenceJson.value);
339
- if (auditValidity.posture === "invalid") {
340
- return inputError(`nimicoding sweep audit refused: audit evidence is invalid no-finding evidence (${auditValidity.blockers.map((blocker) => blocker.id).join(", ")}).\n`);
341
- }
342
-
343
- const evidenceRef = artifactRef("evidence_refs", sweepId, `${options.chunkId}.audit-evidence.json`);
344
- await mkdir(path.dirname(artifactPath(projectRoot, evidenceRef)), { recursive: true });
345
- await copyFile(source.absolutePath, artifactPath(projectRoot, evidenceRef));
346
-
347
- const { findingsRef: aggregateFindingsRef, store } = await loadFindings(projectRoot, sweepId);
348
- ensureClusterStore(store);
349
- const seen = new Set(store.findings.map((finding) => finding.fingerprint));
350
- const clustersByKey = new Map(store.clusters.map((cluster) => [cluster.cluster_key, cluster]));
351
- let addedCount = 0;
352
- let duplicateCount = 0;
353
- let clusteredCount = 0;
354
- let acceptedClusterSkipCount = 0;
355
- for (const [index, rawFinding] of evidenceJson.value.findings.entries()) {
356
- const normalized = normalizeFinding(rawFinding, index, chunkResult.chunk, sweepId, evidenceRef, options.verifiedAt);
357
- if (!normalized.ok) {
358
- return inputError(`nimicoding sweep audit refused: ${normalized.error}.\n`);
359
- }
360
- const clusterResult = deriveFindingCluster(rawFinding, normalized.finding, chunkResult.chunk, planResult.plan);
361
- if (!clusterResult.ok) {
362
- return inputError(`nimicoding sweep audit refused: finding ${index + 1} ${clusterResult.error}.\n`);
363
- }
364
- if (seen.has(normalized.fingerprint)) {
365
- duplicateCount += 1;
366
- const sourceFinding = existingFindingForFingerprint(store, normalized.fingerprint);
367
- const sourceCluster = clusterForFinding(store, sourceFinding);
368
- if (sourceCluster) {
369
- recordClusteredSymptom(store, sourceCluster, normalized.finding, normalized.fingerprint, "exact_duplicate");
370
- clusteredCount += 1;
371
- }
372
- continue;
373
- }
374
- const sameLocationRetry = existingFindingForRetryLocation(store, normalized.finding);
375
- if (sameLocationRetry) {
376
- duplicateCount += 1;
377
- const sourceCluster = clusterForFinding(store, sameLocationRetry);
378
- if (sourceCluster) {
379
- recordClusteredSymptom(store, sourceCluster, normalized.finding, normalized.fingerprint, "same_chunk_location_retry");
380
- clusteredCount += 1;
381
- }
382
- continue;
383
- }
384
-
385
- let cluster = clustersByKey.get(clusterResult.cluster.cluster_key) ?? null;
386
- const acceptedClusterSameContext = cluster && clusterAcceptanceMatchesPlan(cluster, planResult.plan);
387
- const acceptedClusterChangedContext = cluster && cluster.acceptance && !acceptedClusterSameContext;
388
- if (acceptedClusterSameContext) {
389
- recordClusteredSymptom(store, cluster, normalized.finding, normalized.fingerprint, "accepted_cluster_resume_skip");
390
- store.accepted_cluster_skip_count = (store.accepted_cluster_skip_count ?? 0) + 1;
391
- acceptedClusterSkipCount += 1;
392
- clusteredCount += 1;
393
- continue;
394
- }
395
- if (cluster && !acceptedClusterChangedContext && !findingRequiresCanonicalInCluster(normalized.finding, cluster)) {
396
- recordClusteredSymptom(store, cluster, normalized.finding, normalized.fingerprint, "clustered_duplicate_symptom");
397
- duplicateCount += 1;
398
- clusteredCount += 1;
399
- continue;
400
- }
401
-
402
- const finding = {
403
- id: `finding-${String(store.findings.length + 1).padStart(4, "0")}`,
404
- fingerprint: normalized.fingerprint,
405
- ...normalized.finding,
406
- root_cause: {
407
- key: clusterResult.cluster.root_cause_key,
408
- authority_ref: clusterResult.cluster.authority_ref,
409
- evidence_root: clusterResult.cluster.evidence_root,
410
- contract_seam: clusterResult.cluster.contract_seam,
411
- repair_target: clusterResult.cluster.repair_target,
412
- },
413
- cluster_id: clusterResult.cluster.cluster_id,
414
- };
415
- seen.add(normalized.fingerprint);
416
- store.findings.push(finding);
417
- if (cluster) {
418
- updateClusterWithCanonical(cluster, finding);
419
- } else {
420
- cluster = createCluster(clusterResult.cluster, finding);
421
- store.clusters.push(cluster);
422
- clustersByKey.set(cluster.cluster_key, cluster);
423
- }
424
- addedCount += 1;
425
- }
426
- store.duplicate_count = (store.duplicate_count ?? 0) + duplicateCount;
427
- store.remediation_obligation_count = store.findings.length;
428
- store.updated_at = options.verifiedAt;
429
- await writeYamlRef(projectRoot, aggregateFindingsRef, store);
430
- const riskBudgetStatus = buildRiskBudgetStatus(planResult.plan, store, options.verifiedAt);
431
-
432
- const updatedChunk = {
433
- ...chunkResult.chunk,
434
- state: "ingested",
435
- evidence_ref: evidenceRef,
436
- finding_count: evidenceJson.value.findings.length,
437
- audit_validity: auditValidity,
438
- lifecycle: {
439
- ...chunkResult.chunk.lifecycle,
440
- ingested_at: options.verifiedAt,
441
- },
442
- updated_at: options.verifiedAt,
443
- };
444
- await writeYamlRef(projectRoot, chunkResult.chunkRef, updatedChunk);
445
- await writeYamlRef(projectRoot, planResult.planRef, {
446
- ...planResult.plan,
447
- risk_budget_status: riskBudgetStatus,
448
- chunks: planResult.plan.chunks.map((chunk) => chunk.chunk_id === options.chunkId
449
- ? { ...chunk, state: "ingested", finding_count: evidenceJson.value.findings.length, evidence_ref: evidenceRef, audit_validity: auditValidity }
450
- : chunk),
451
- updated_at: options.verifiedAt,
452
- });
453
-
454
- const runRef = await appendRunEvent(projectRoot, sweepId, {
455
- event_type: "chunk_ingested",
456
- chunk_id: options.chunkId,
457
- chunk_ref: chunkRef(sweepId, options.chunkId),
458
- evidence_ref: evidenceRef,
459
- findings_ref: aggregateFindingsRef,
460
- finding_count: evidenceJson.value.findings.length,
461
- audit_validity: auditValidity,
462
- added_count: addedCount,
463
- duplicate_count: duplicateCount,
464
- clustered_count: clusteredCount,
465
- accepted_cluster_skip_count: acceptedClusterSkipCount,
466
- risk_budget_status: riskBudgetStatus,
467
- });
468
-
469
- return {
470
- ok: true,
471
- exitCode: 0,
472
- sweepId,
473
- chunkId: options.chunkId,
474
- state: "ingested",
475
- evidenceRef,
476
- findingsRef: aggregateFindingsRef,
477
- findingCount: evidenceJson.value.findings.length,
478
- addedCount,
479
- duplicateCount,
480
- clusteredCount,
481
- acceptedClusterSkipCount,
482
- riskBudgetStatus,
483
- runLedgerRef: runRef,
484
- };
485
- });
486
- }