@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,300 +0,0 @@
1
- import path from "node:path";
2
-
3
- import { SEVERITY_RANK, sha256Object } from "./common.mjs";
4
- import { isPlainObject } from "../value-helpers.mjs";
5
-
6
- const RISK_BUDGET_LIMIT_FIELDS = [
7
- "maxSweepFindings",
8
- "maxDomainFindings",
9
- "maxSweepHighRiskFindings",
10
- "maxDomainHighRiskFindings",
11
- ];
12
-
13
- function positiveIntegerOrNull(value) {
14
- return Number.isInteger(value) && value > 0 ? value : null;
15
- }
16
-
17
- function nonEmptyString(value) {
18
- return typeof value === "string" && value.trim().length > 0;
19
- }
20
-
21
- export function buildRiskBudgetPolicy(options = {}) {
22
- const hasLimit = RISK_BUDGET_LIMIT_FIELDS.some((field) => positiveIntegerOrNull(options[field]) !== null);
23
- if (!hasLimit) {
24
- return null;
25
- }
26
-
27
- return {
28
- mode: "root_cause_aware",
29
- duplicate_symptoms_count_as_remediation_obligations: false,
30
- high_risk_unique_root_causes_are_canonical: true,
31
- accepted_cluster_resume_skip: true,
32
- max_sweep_findings: positiveIntegerOrNull(options.maxSweepFindings),
33
- max_domain_findings: positiveIntegerOrNull(options.maxDomainFindings),
34
- max_sweep_high_risk_findings: positiveIntegerOrNull(options.maxSweepHighRiskFindings),
35
- max_domain_high_risk_findings: positiveIntegerOrNull(options.maxDomainHighRiskFindings),
36
- };
37
- }
38
-
39
- export function highRiskFinding(finding) {
40
- return finding?.severity === "critical" || finding?.severity === "high";
41
- }
42
-
43
- function evidenceRootForFile(chunk, fileRef) {
44
- for (const rootRef of chunk.evidence_roots ?? []) {
45
- const normalized = String(rootRef).replace(/\\/g, "/").replace(/\/$/, "");
46
- if (fileRef === normalized || fileRef.startsWith(`${normalized}/`)) {
47
- return normalized;
48
- }
49
- }
50
- return path.posix.dirname(fileRef) || ".";
51
- }
52
-
53
- function normalizeRootCauseField(rawFinding, name) {
54
- const rootCause = isPlainObject(rawFinding.root_cause) ? rawFinding.root_cause : {};
55
- const value = rootCause[name] ?? rawFinding[name];
56
- return nonEmptyString(value) ? String(value).trim().replace(/\\/g, "/") : null;
57
- }
58
-
59
- function normalizeEvidenceRootForChunk(chunk, evidenceRoot) {
60
- if (!evidenceRoot) {
61
- return null;
62
- }
63
- if (evidenceRoot === "packet:evidence_inventory") {
64
- return null;
65
- }
66
- for (const rootRef of chunk.evidence_roots ?? []) {
67
- const normalized = String(rootRef).replace(/\\/g, "/").replace(/\/$/, "");
68
- if (evidenceRoot === normalized || evidenceRoot.startsWith(`${normalized}/`)) {
69
- return normalized;
70
- }
71
- }
72
- return null;
73
- }
74
-
75
- export function deriveFindingCluster(rawFinding, finding, chunk, plan) {
76
- const authorityRef = normalizeRootCauseField(rawFinding, "authority_ref")
77
- ?? chunk.authority_refs?.[0]
78
- ?? chunk.files?.[0]
79
- ?? finding.location.file;
80
- const allowedAuthorityRefs = new Set([...(chunk.authority_refs ?? []), ...(chunk.files ?? [])]);
81
- if (chunk.planning_basis === "spec_authority" && !allowedAuthorityRefs.has(authorityRef)) {
82
- return { ok: false, error: "root_cause.authority_ref must belong to chunk authority refs" };
83
- }
84
-
85
- const explicitEvidenceRoot = normalizeRootCauseField(rawFinding, "evidence_root");
86
- const normalizedExplicitEvidenceRoot = normalizeEvidenceRootForChunk(chunk, explicitEvidenceRoot);
87
- const packetInventoryRootSentinel = explicitEvidenceRoot === "packet:evidence_inventory";
88
- if (explicitEvidenceRoot && !packetInventoryRootSentinel && chunk.planning_basis === "spec_authority" && !normalizedExplicitEvidenceRoot) {
89
- return { ok: false, error: "root_cause.evidence_root must belong to chunk evidence roots or a descendant of one" };
90
- }
91
-
92
- const rootCauseKey = normalizeRootCauseField(rawFinding, "key") ?? normalizeRootCauseField(rawFinding, "id");
93
- const evidenceRoot = normalizedExplicitEvidenceRoot ?? evidenceRootForFile(chunk, finding.location.file);
94
- const contractSeam = normalizeRootCauseField(rawFinding, "contract_seam") ?? finding.category;
95
- const repairTarget = normalizeRootCauseField(rawFinding, "repair_target") ?? finding.location.file;
96
- const fallbackUniqueKey = `${finding.title}:${finding.description}:${finding.location.file}`;
97
- const seed = {
98
- sweep_id: finding.sweep_id,
99
- authority_context: {
100
- inventory_hash: plan.inventory_hash,
101
- evidence_inventory_hash: plan.evidence_inventory_hash ?? null,
102
- },
103
- owner_domain: finding.owner_domain,
104
- category: finding.category,
105
- actionability: finding.actionability,
106
- authority_ref: authorityRef,
107
- evidence_root: evidenceRoot,
108
- contract_seam: contractSeam,
109
- repair_target: repairTarget,
110
- root_cause_key: rootCauseKey ?? fallbackUniqueKey,
111
- };
112
-
113
- return {
114
- ok: true,
115
- cluster: {
116
- cluster_id: `cluster-${sha256Object(seed).slice(0, 16)}`,
117
- cluster_key: sha256Object(seed),
118
- root_cause_key: rootCauseKey,
119
- authority_ref: authorityRef,
120
- evidence_root: evidenceRoot,
121
- contract_seam: contractSeam,
122
- repair_target: repairTarget,
123
- authority_context: seed.authority_context,
124
- },
125
- };
126
- }
127
-
128
- export function ensureClusterStore(store) {
129
- if (!Array.isArray(store.clusters)) {
130
- store.clusters = [];
131
- }
132
- if (!Number.isInteger(store.clustered_symptom_count)) {
133
- store.clustered_symptom_count = 0;
134
- }
135
- if (!Number.isInteger(store.accepted_cluster_skip_count)) {
136
- store.accepted_cluster_skip_count = 0;
137
- }
138
- store.remediation_obligation_count = store.findings.length;
139
- return store;
140
- }
141
-
142
- function severityRank(value) {
143
- return SEVERITY_RANK[value] ?? 99;
144
- }
145
-
146
- export function findingRequiresCanonicalInCluster(finding, cluster) {
147
- const currentRank = severityRank(cluster.max_severity);
148
- const incomingRank = severityRank(finding.severity);
149
- return incomingRank < currentRank;
150
- }
151
-
152
- export function clusterAcceptanceMatchesPlan(cluster, plan) {
153
- const acceptance = cluster.acceptance;
154
- if (!isPlainObject(acceptance)) {
155
- return false;
156
- }
157
- return acceptance.source_inventory_hash === plan.inventory_hash
158
- && (acceptance.source_evidence_inventory_hash ?? null) === (plan.evidence_inventory_hash ?? null);
159
- }
160
-
161
- export function buildDuplicateSymptom(finding, fingerprint, classification) {
162
- return {
163
- fingerprint,
164
- classification,
165
- chunk_id: finding.chunk_id,
166
- evidence_ref: finding.evidence_ref,
167
- severity: finding.severity,
168
- title: finding.title,
169
- location: finding.location,
170
- detected_at: finding.detected_at,
171
- };
172
- }
173
-
174
- export function updateClusterWithCanonical(cluster, finding) {
175
- if (!cluster.canonical_finding_ids.includes(finding.id)) {
176
- cluster.canonical_finding_ids.push(finding.id);
177
- cluster.canonical_finding_ids.sort();
178
- }
179
- if (severityRank(finding.severity) < severityRank(cluster.max_severity)) {
180
- cluster.max_severity = finding.severity;
181
- cluster.representative_finding_id = finding.id;
182
- }
183
- cluster.source_chunks = [...new Set([...cluster.source_chunks, finding.chunk_id])].sort();
184
- cluster.files = [...new Set([...cluster.files, finding.location.file])].sort();
185
- cluster.updated_at = finding.detected_at;
186
- }
187
-
188
- export function createCluster(clusterSeed, finding) {
189
- return {
190
- ...clusterSeed,
191
- representative_finding_id: finding.id,
192
- canonical_finding_ids: [finding.id],
193
- owner_domain: finding.owner_domain,
194
- category: finding.category,
195
- actionability: finding.actionability,
196
- max_severity: finding.severity,
197
- source_chunks: [finding.chunk_id],
198
- files: [finding.location.file],
199
- duplicate_symptom_count: 0,
200
- duplicate_symptoms: [],
201
- created_at: finding.detected_at,
202
- updated_at: finding.detected_at,
203
- };
204
- }
205
-
206
- export function buildRiskBudgetStatus(plan, store, verifiedAt) {
207
- const policy = plan.risk_budget_policy;
208
- if (!isPlainObject(policy)) {
209
- return null;
210
- }
211
-
212
- const findings = Array.isArray(store.findings) ? store.findings : [];
213
- const clusters = Array.isArray(store.clusters) ? store.clusters : [];
214
- const domains = new Map();
215
- for (const finding of findings) {
216
- const ownerDomain = finding.owner_domain ?? "root";
217
- const domain = domains.get(ownerDomain) ?? {
218
- owner_domain: ownerDomain,
219
- finding_count: 0,
220
- high_risk_finding_count: 0,
221
- cluster_count: 0,
222
- clustered_symptom_count: 0,
223
- state: "within_budget",
224
- reasons: [],
225
- };
226
- domain.finding_count += 1;
227
- if (highRiskFinding(finding)) {
228
- domain.high_risk_finding_count += 1;
229
- }
230
- domains.set(ownerDomain, domain);
231
- }
232
- for (const cluster of clusters) {
233
- const ownerDomain = cluster.owner_domain ?? "root";
234
- const domain = domains.get(ownerDomain) ?? {
235
- owner_domain: ownerDomain,
236
- finding_count: 0,
237
- high_risk_finding_count: 0,
238
- cluster_count: 0,
239
- clustered_symptom_count: 0,
240
- state: "within_budget",
241
- reasons: [],
242
- };
243
- domain.cluster_count += 1;
244
- domain.clustered_symptom_count += cluster.duplicate_symptom_count ?? 0;
245
- domains.set(ownerDomain, domain);
246
- }
247
-
248
- const sweep = {
249
- finding_count: findings.length,
250
- high_risk_finding_count: findings.filter(highRiskFinding).length,
251
- cluster_count: clusters.length,
252
- clustered_symptom_count: store.clustered_symptom_count ?? 0,
253
- state: "within_budget",
254
- reasons: [],
255
- };
256
-
257
- if (policy.max_sweep_findings && sweep.finding_count >= policy.max_sweep_findings) {
258
- sweep.state = "paused";
259
- sweep.reasons.push(`max_sweep_findings:${policy.max_sweep_findings}`);
260
- }
261
- if (policy.max_sweep_high_risk_findings && sweep.high_risk_finding_count >= policy.max_sweep_high_risk_findings) {
262
- sweep.state = "paused";
263
- sweep.reasons.push(`max_sweep_high_risk_findings:${policy.max_sweep_high_risk_findings}`);
264
- }
265
-
266
- for (const domain of domains.values()) {
267
- if (policy.max_domain_findings && domain.finding_count >= policy.max_domain_findings) {
268
- domain.state = "paused";
269
- domain.reasons.push(`max_domain_findings:${policy.max_domain_findings}`);
270
- }
271
- if (policy.max_domain_high_risk_findings && domain.high_risk_finding_count >= policy.max_domain_high_risk_findings) {
272
- domain.state = "paused";
273
- domain.reasons.push(`max_domain_high_risk_findings:${policy.max_domain_high_risk_findings}`);
274
- }
275
- }
276
-
277
- const domainStatuses = [...domains.values()].sort((left, right) => left.owner_domain.localeCompare(right.owner_domain));
278
- return {
279
- policy,
280
- state: sweep.state === "paused" || domainStatuses.some((domain) => domain.state === "paused") ? "paused" : "within_budget",
281
- sweep,
282
- domains: domainStatuses,
283
- updated_at: verifiedAt,
284
- };
285
- }
286
-
287
- export function budgetBlockForChunk(plan, chunk) {
288
- const status = plan.risk_budget_status;
289
- if (!isPlainObject(status)) {
290
- return null;
291
- }
292
- if (status.sweep?.state === "paused") {
293
- return `sweep risk budget paused (${(status.sweep.reasons ?? []).join(", ") || "budget reached"})`;
294
- }
295
- const domain = (status.domains ?? []).find((entry) => entry.owner_domain === chunk.owner_domain);
296
- if (domain?.state === "paused") {
297
- return `domain risk budget paused for ${chunk.owner_domain} (${(domain.reasons ?? []).join(", ") || "budget reached"})`;
298
- }
299
- return null;
300
- }
@@ -1,62 +0,0 @@
1
- import {
2
- ACTIVE_CHUNK_STATES,
3
- inputError,
4
- loadFindings,
5
- loadLatestLedger,
6
- loadPlan,
7
- safeSweepId,
8
- } from "./common.mjs";
9
- import { buildCoverageQuality } from "./coverage-quality.mjs";
10
- import { ensureClusterStore } from "./risk-budget.mjs";
11
-
12
- export async function getAuditSweepStatus(projectRoot, options) {
13
- const sweepId = safeSweepId(options.sweepId);
14
- if (!sweepId) {
15
- return inputError("nimicoding sweep audit refused: --sweep-id is required.\n");
16
- }
17
-
18
- const planResult = await loadPlan(projectRoot, sweepId);
19
- if (!planResult.ok) {
20
- return inputError(planResult.error);
21
- }
22
- const { findingsRef, store } = await loadFindings(projectRoot, sweepId);
23
- ensureClusterStore(store);
24
- const latestLedger = await loadLatestLedger(projectRoot, sweepId);
25
- const chunks = Array.isArray(planResult.plan.chunks) ? planResult.plan.chunks : [];
26
- const coverageQuality = latestLedger.ok
27
- ? latestLedger.ledger.coverage_quality ?? buildCoverageQuality(planResult.plan, chunks, planResult.plan.coverage)
28
- : buildCoverageQuality(planResult.plan, chunks, planResult.plan.coverage);
29
- const auditValidity = latestLedger.ok ? latestLedger.ledger.audit_validity ?? null : null;
30
-
31
- return {
32
- ok: true,
33
- exitCode: 0,
34
- sweepId,
35
- planRef: planResult.planRef,
36
- findingsRef,
37
- latestLedgerRef: latestLedger.ok ? latestLedger.ledgerRef : null,
38
- coverage: {
39
- totalFiles: planResult.plan.coverage?.total_files ?? 0,
40
- includedFiles: planResult.plan.coverage?.included_files ?? 0,
41
- ...(planResult.plan.planning_basis?.mode === "spec_authority" ? {
42
- authorityFiles: planResult.plan.coverage?.authority_files ?? 0,
43
- evidenceFiles: planResult.plan.coverage?.evidence_files ?? 0,
44
- unmappedEvidenceFiles: planResult.plan.coverage?.unmapped_evidence_files ?? 0,
45
- } : {}),
46
- frozenChunks: chunks.filter((chunk) => chunk.state === "frozen").length,
47
- activeChunks: chunks.filter((chunk) => ACTIVE_CHUNK_STATES.has(chunk.state)).length,
48
- chunks: chunks.reduce((acc, chunk) => {
49
- acc[chunk.state] = (acc[chunk.state] ?? 0) + 1;
50
- return acc;
51
- }, {}),
52
- },
53
- findingCount: store.findings.length,
54
- findingClusterCount: store.clusters.length,
55
- clusteredSymptomCount: store.clustered_symptom_count ?? 0,
56
- remediationObligationCount: store.remediation_obligation_count ?? store.findings.length,
57
- unresolvedFindingCount: store.findings.filter((finding) => finding.disposition === "open").length,
58
- riskBudgetStatus: planResult.plan.risk_budget_status ?? null,
59
- coverageQuality,
60
- auditValidity,
61
- };
62
- }
@@ -1,215 +0,0 @@
1
- import {
2
- ACTIVE_CHUNK_STATES,
3
- artifactPath,
4
- ledgerRef,
5
- loadLatestLedger,
6
- loadYamlRef,
7
- remediationMapRef,
8
- sha256Object,
9
- } from "./common.mjs";
10
- import { pathExists } from "../fs-helpers.mjs";
11
- import { isPlainObject } from "../value-helpers.mjs";
12
-
13
- function check(checks, id, ok, reason) {
14
- checks.push({ id, ok, reason });
15
- }
16
-
17
- function nonEmptyString(value) {
18
- return typeof value === "string" && value.trim().length > 0;
19
- }
20
-
21
- async function refExists(projectRoot, ref) {
22
- const info = await pathExists(artifactPath(projectRoot, ref));
23
- return Boolean(info?.isFile());
24
- }
25
-
26
- async function validateEvidenceRefs(projectRoot, refs, checks, prefix) {
27
- for (const ref of refs.filter((entry) => typeof entry === "string" && entry.trim())) {
28
- check(checks, `${prefix}_${ref.replace(/[^a-zA-Z0-9]+/g, "_")}_exists`, await refExists(projectRoot, ref), `referenced artifact exists: ${ref}`);
29
- }
30
- }
31
-
32
- export function deriveLedgerSnapshotId(sweepId, plan, chunks, findings, clusters = []) {
33
- const snapshotSeed = {
34
- sweepId,
35
- inventoryHash: plan.inventory_hash,
36
- evidenceInventoryHash: plan.evidence_inventory_hash ?? null,
37
- chunkStates: chunks.map((chunk) => ({
38
- chunk_id: chunk.chunk_id,
39
- state: chunk.state,
40
- evidence_ref: chunk.evidence_ref ?? null,
41
- finding_count: chunk.finding_count ?? 0,
42
- })),
43
- findings: findings.map((finding) => ({
44
- id: finding.id,
45
- fingerprint: finding.fingerprint,
46
- disposition: finding.disposition,
47
- resolution_evidence_ref: finding.resolution?.evidence_ref ?? null,
48
- })),
49
- clusters: clusters.map((cluster) => ({
50
- cluster_id: cluster.cluster_id,
51
- canonical_finding_ids: cluster.canonical_finding_ids,
52
- duplicate_symptom_count: cluster.duplicate_symptom_count ?? 0,
53
- })),
54
- };
55
- return `ledger-${sha256Object(snapshotSeed).slice(0, 16)}`;
56
- }
57
-
58
- export function validateClusterShape(cluster, findingIds, checks) {
59
- check(checks, `cluster_${cluster?.cluster_id ?? "unknown"}_required_fields`, isPlainObject(cluster)
60
- && nonEmptyString(cluster.cluster_id)
61
- && nonEmptyString(cluster.cluster_key)
62
- && nonEmptyString(cluster.representative_finding_id)
63
- && Array.isArray(cluster.canonical_finding_ids)
64
- && Array.isArray(cluster.duplicate_symptoms), "audit finding cluster has required fields");
65
- if (!isPlainObject(cluster)) {
66
- return;
67
- }
68
- check(checks, `cluster_${cluster.cluster_id}_findings_known`, findingIds.has(cluster.representative_finding_id)
69
- && cluster.canonical_finding_ids.every((findingId) => findingIds.has(findingId)), "audit finding cluster references known canonical findings");
70
- check(checks, `cluster_${cluster.cluster_id}_symptom_count_matches`, (cluster.duplicate_symptom_count ?? 0) === cluster.duplicate_symptoms.length, "audit finding cluster duplicate symptom count matches symptoms");
71
- }
72
-
73
- function buildLedgerExpectedCounts(plan, chunks, findings, clusters = []) {
74
- const frozenChunks = chunks.filter((chunk) => chunk.state === "frozen");
75
- const lifecycleCoverage = {
76
- frozen_chunks: frozenChunks.length,
77
- failed_chunks: chunks.filter((chunk) => chunk.state === "failed").length,
78
- skipped_chunks: chunks.filter((chunk) => chunk.state === "skipped").length,
79
- active_chunks: chunks.filter((chunk) => ACTIVE_CHUNK_STATES.has(chunk.state)).length,
80
- };
81
- const coverage = plan.planning_basis?.mode === "spec_authority"
82
- ? buildSpecAuthorityCoverage(plan, frozenChunks, lifecycleCoverage)
83
- : buildFileCoverage(plan, frozenChunks, lifecycleCoverage);
84
- const findingPosture = {
85
- open: findings.filter((finding) => finding.disposition === "open").length,
86
- remediated: findings.filter((finding) => finding.disposition === "remediated").length,
87
- accepted_risk: findings.filter((finding) => finding.disposition === "accepted-risk").length,
88
- false_positive: findings.filter((finding) => finding.disposition === "false-positive").length,
89
- deferred_backlog: findings.filter((finding) => finding.disposition === "deferred-backlog").length,
90
- };
91
- return {
92
- coverage,
93
- findingPosture,
94
- findingClusterCount: clusters.length,
95
- clusteredSymptomCount: clusters.reduce((total, cluster) => total + (cluster.duplicate_symptom_count ?? 0), 0),
96
- };
97
- }
98
-
99
- function buildSpecAuthorityCoverage(plan, frozenChunks, lifecycleCoverage) {
100
- const authorityTotal = plan.coverage?.authority_files ?? plan.coverage?.included_files ?? 0;
101
- const evidenceTotal = plan.coverage?.evidence_files ?? plan.evidence_inventory?.length ?? 0;
102
- const emptyEvidenceChunks = plan.coverage?.authority_chunks_without_evidence_inventory
103
- ?? (Array.isArray(plan.chunks) ? plan.chunks.filter((chunk) => (chunk.evidence_inventory ?? []).length === 0).length : 0)
104
- ?? 0;
105
- const auditedAuthorityFiles = new Set(frozenChunks.flatMap((chunk) => chunk.files));
106
- const auditedEvidenceFiles = new Set(frozenChunks.flatMap((chunk) => chunk.evidence_inventory ?? []));
107
- return {
108
- total_files: authorityTotal + evidenceTotal,
109
- included_files: authorityTotal + evidenceTotal,
110
- audited_files: auditedAuthorityFiles.size + auditedEvidenceFiles.size,
111
- authority_coverage: {
112
- total_files: authorityTotal,
113
- audited_files: auditedAuthorityFiles.size,
114
- chunks_without_evidence_inventory: emptyEvidenceChunks,
115
- },
116
- evidence_coverage: {
117
- total_files: evidenceTotal,
118
- audited_files: auditedEvidenceFiles.size,
119
- unmapped_files: plan.coverage?.unmapped_evidence_files ?? plan.unmapped_evidence_files?.length ?? 0,
120
- },
121
- ...lifecycleCoverage,
122
- };
123
- }
124
-
125
- function buildFileCoverage(plan, frozenChunks, lifecycleCoverage) {
126
- const auditedFiles = new Set(frozenChunks.flatMap((chunk) => chunk.files));
127
- return {
128
- total_files: plan.coverage.total_files,
129
- included_files: plan.coverage.included_files,
130
- audited_files: auditedFiles.size,
131
- ...lifecycleCoverage,
132
- };
133
- }
134
-
135
- export async function validateLatestLedger(projectRoot, sweepId, plan, chunks, findings, clusters, checks) {
136
- const latest = await loadLatestLedger(projectRoot, sweepId);
137
- check(checks, "latest_ledger_loadable", latest.ok, "latest ledger pointer and ledger are loadable");
138
- if (!latest.ok) {
139
- return null;
140
- }
141
- const ledger = latest.ledger;
142
- const expectedSnapshotId = deriveLedgerSnapshotId(sweepId, plan, chunks, findings, clusters);
143
- check(checks, "ledger_snapshot_id_content_hash", ledger.snapshot_id === expectedSnapshotId && latest.ledgerRef === ledgerRef(sweepId, expectedSnapshotId), "ledger snapshot id is content-derived and current");
144
- const expected = buildLedgerExpectedCounts(plan, chunks, findings, clusters);
145
- check(checks, "ledger_coverage_counts_match", JSON.stringify(ledger.coverage) === JSON.stringify(expected.coverage), "ledger coverage counts match plan and chunks");
146
- check(checks, "ledger_finding_counts_match", ledger.finding_count === findings.length
147
- && ledger.unresolved_finding_count === expected.findingPosture.open
148
- && JSON.stringify(ledger.finding_posture) === JSON.stringify(expected.findingPosture), "ledger finding counts match findings store");
149
- check(checks, "ledger_cluster_counts_match", (ledger.finding_cluster_count ?? 0) === expected.findingClusterCount
150
- && (ledger.clustered_symptom_count ?? 0) === expected.clusteredSymptomCount
151
- && (ledger.remediation_obligation_count ?? findings.length) === findings.length, "ledger cluster counts match findings store");
152
- check(checks, "ledger_latest_pointer_matches", latest.ledgerRef === ledgerRef(sweepId, ledger.snapshot_id), "latest pointer references the immutable ledger snapshot");
153
- check(checks, "ledger_status_valid", ["candidate_ready", "partial", "blocked", "blocked_evidence_incomplete", "partial_authority_only"].includes(ledger.status), "ledger status is valid");
154
- checkLedgerSpecCoverage(plan, ledger, checks);
155
- await validateEvidenceRefs(projectRoot, [
156
- ledger.plan_ref,
157
- ...(Array.isArray(ledger.chunk_refs) ? ledger.chunk_refs : []),
158
- ledger.findings_ref,
159
- ...(Array.isArray(ledger.evidence_refs) ? ledger.evidence_refs : []),
160
- ledger.report_ref,
161
- ledger.run_ledger_ref,
162
- ], checks, "ledger_ref");
163
- return { ledger, ledger_ref: latest.ledgerRef, snapshot_id: ledger.snapshot_id };
164
- }
165
-
166
- function checkLedgerSpecCoverage(plan, ledger, checks) {
167
- check(checks, "ledger_candidate_ready_strict", ledger.status !== "candidate_ready"
168
- || (ledger.coverage.included_files > 0 && ledger.coverage.audited_files === ledger.coverage.included_files && ledger.coverage.active_chunks === 0 && ledger.coverage.failed_chunks === 0 && ledger.coverage.skipped_chunks === 0), "candidate_ready requires all included files audited and all chunks frozen");
169
- if (plan.planning_basis?.mode !== "spec_authority") {
170
- return;
171
- }
172
- const authorityFull = ledger.coverage.authority_coverage?.total_files > 0
173
- && ledger.coverage.authority_coverage.audited_files === ledger.coverage.authority_coverage.total_files;
174
- const evidenceFull = ledger.coverage.evidence_coverage?.audited_files === ledger.coverage.evidence_coverage?.total_files
175
- && ledger.coverage.evidence_coverage?.unmapped_files === 0;
176
- check(checks, "ledger_spec_coverage_split_present", isPlainObject(ledger.coverage.authority_coverage)
177
- && isPlainObject(ledger.coverage.evidence_coverage), "spec-authority ledger splits authority and evidence coverage");
178
- check(checks, "ledger_spec_coverage_quality_present", isPlainObject(ledger.coverage_quality), "spec-authority ledger exposes coverage_quality");
179
- check(checks, "ledger_spec_audit_validity_present", isPlainObject(ledger.audit_validity), "spec-authority ledger exposes audit_validity");
180
- check(checks, "ledger_spec_candidate_ready_requires_evidence", ledger.status !== "candidate_ready"
181
- || (authorityFull && evidenceFull), "candidate_ready requires full authority and evidence coverage");
182
- check(checks, "ledger_spec_no_full_with_unmapped_evidence", ledger.status !== "candidate_ready"
183
- || ledger.coverage.evidence_coverage?.unmapped_files === 0, "candidate_ready requires zero unmapped evidence files");
184
- }
185
-
186
- export async function validateRemediationMap(projectRoot, sweepId, ledgerInfo, findings, clusters, checks) {
187
- if (!ledgerInfo) {
188
- check(checks, "remediation_map_ledger_available", false, "remediation map validation requires latest ledger");
189
- return null;
190
- }
191
- const mapRef = remediationMapRef(sweepId, ledgerInfo.snapshot_id);
192
- const remediationMap = await loadYamlRef(projectRoot, mapRef);
193
- const openFindings = findings.filter((finding) => finding.disposition === "open");
194
- if (!isPlainObject(remediationMap)) {
195
- check(checks, "remediation_map_required", false, "remediation map exists for the latest ledger");
196
- return null;
197
- }
198
- check(checks, "remediation_map_identity", remediationMap.kind === "audit-remediation-map" && remediationMap.sweep_id === sweepId && remediationMap.source_ledger_ref === ledgerInfo.ledger_ref, "remediation map references latest ledger");
199
- const findingIds = new Set(findings.map((finding) => finding.id));
200
- const clusterIds = new Set(clusters.map((cluster) => cluster.cluster_id));
201
- const mappedIds = new Set();
202
- const wavesOk = Array.isArray(remediationMap.waves) && remediationMap.waves.every((wave) => {
203
- if (!isPlainObject(wave) || !nonEmptyString(wave.wave_id) || !Array.isArray(wave.finding_ids) || !Array.isArray(wave.write_set)) {
204
- return false;
205
- }
206
- for (const findingId of wave.finding_ids) {
207
- mappedIds.add(findingId);
208
- }
209
- return wave.finding_ids.every((findingId) => findingIds.has(findingId))
210
- && (!Array.isArray(wave.cluster_ids) || wave.cluster_ids.every((clusterId) => clusterIds.has(clusterId)));
211
- });
212
- check(checks, "remediation_map_waves_valid", wavesOk, "remediation map waves reference known findings");
213
- check(checks, "remediation_map_open_findings_covered", openFindings.every((finding) => mappedIds.has(finding.id)), "all open findings are covered by remediation map waves");
214
- return { remediationMap, remediation_map_ref: mapRef };
215
- }