@nimiplatform/nimi-coding 0.2.8 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/CHANGELOG.md +8 -92
  2. package/CONTRIBUTING.md +5 -34
  3. package/README.md +47 -350
  4. package/README.zh-CN.md +33 -287
  5. package/cli/commands/start.mjs +48 -688
  6. package/cli/commands/validate-spec-audit.mjs +1 -5
  7. package/cli/constants.mjs +9 -417
  8. package/cli/help.mjs +28 -145
  9. package/cli/index.mjs +5 -33
  10. package/cli/lib/blueprint-audit.mjs +5 -12
  11. package/cli/lib/bootstrap.mjs +0 -9
  12. package/cli/lib/contracts.mjs +0 -163
  13. package/cli/lib/doctor.mjs +155 -10
  14. package/cli/lib/entrypoints.mjs +63 -167
  15. package/cli/lib/internal/contracts-loaders.mjs +0 -85
  16. package/cli/lib/internal/contracts-parse.mjs +84 -520
  17. package/cli/lib/internal/governance/ai/check-agents-freshness.mjs +13 -8
  18. package/cli/lib/internal/surface-taxonomy-validators.mjs +316 -66
  19. package/cli/lib/internal/validators-shared.mjs +0 -16
  20. package/cli/lib/internal/validators-spec-helpers.mjs +7 -140
  21. package/cli/lib/internal/validators-spec.mjs +103 -342
  22. package/cli/lib/shared.mjs +1 -42
  23. package/cli/lib/validators.mjs +0 -48
  24. package/cli/seeds/seed-policy.yaml +0 -3
  25. package/config/bootstrap.yaml +4 -4
  26. package/config/spec-generation-inputs.yaml +6 -12
  27. package/contracts/domain-admission.schema.yaml +3 -3
  28. package/contracts/migration-inventory.schema.yaml +12 -75
  29. package/contracts/negative-fixtures.yaml +19 -99
  30. package/contracts/placement-contract.schema.yaml +49 -78
  31. package/contracts/projection-edge.schema.yaml +37 -121
  32. package/contracts/shared-enums.yaml +4 -8
  33. package/contracts/spec-generation-inputs.schema.yaml +15 -112
  34. package/contracts/spec-layout.schema.yaml +32 -0
  35. package/contracts/surface-taxonomy.schema.yaml +43 -94
  36. package/contracts/table-family.schema.yaml +1 -1
  37. package/contracts/tracked-output-admission.schema.yaml +13 -66
  38. package/methodology/core.yaml +33 -25
  39. package/methodology/four-closure-policy.yaml +18 -26
  40. package/methodology/role-separation-policy.yaml +21 -27
  41. package/methodology/spec-reconstruction.yaml +17 -34
  42. package/package.json +2 -4
  43. package/spec/_meta/spec-tree-model.yaml +5 -101
  44. package/spec/product-scope.yaml +25 -57
  45. package/adapters/README.md +0 -25
  46. package/adapters/claude/README.md +0 -89
  47. package/adapters/claude/profile.yaml +0 -70
  48. package/adapters/codex/README.md +0 -53
  49. package/adapters/codex/profile.yaml +0 -78
  50. package/adapters/oh-my-codex/README.md +0 -184
  51. package/adapters/oh-my-codex/profile.yaml +0 -46
  52. package/cli/commands/admit-high-risk-decision.mjs +0 -108
  53. package/cli/commands/audit-sweep.mjs +0 -364
  54. package/cli/commands/closeout.mjs +0 -186
  55. package/cli/commands/decide-high-risk-execution.mjs +0 -124
  56. package/cli/commands/handoff.mjs +0 -123
  57. package/cli/commands/ingest-high-risk-execution.mjs +0 -95
  58. package/cli/commands/review-high-risk-execution.mjs +0 -95
  59. package/cli/commands/sweep-design.mjs +0 -295
  60. package/cli/commands/sweep.mjs +0 -22
  61. package/cli/commands/topic-formatters.mjs +0 -382
  62. package/cli/commands/topic-goal.mjs +0 -33
  63. package/cli/commands/topic-options-shared.mjs +0 -27
  64. package/cli/commands/topic-options-workflow.mjs +0 -767
  65. package/cli/commands/topic-options.mjs +0 -626
  66. package/cli/commands/topic-runner.mjs +0 -169
  67. package/cli/commands/topic.mjs +0 -795
  68. package/cli/commands/validate-acceptance.mjs +0 -5
  69. package/cli/commands/validate-execution-packet.mjs +0 -5
  70. package/cli/commands/validate-orchestration-state.mjs +0 -5
  71. package/cli/commands/validate-prompt.mjs +0 -5
  72. package/cli/commands/validate-worker-output.mjs +0 -5
  73. package/cli/lib/adapter-profiles.mjs +0 -403
  74. package/cli/lib/audit-execution.mjs +0 -52
  75. package/cli/lib/audit-sweep-runtime/admissions.mjs +0 -508
  76. package/cli/lib/audit-sweep-runtime/audit-validity.mjs +0 -356
  77. package/cli/lib/audit-sweep-runtime/chunks.mjs +0 -697
  78. package/cli/lib/audit-sweep-runtime/claude-auditor.mjs +0 -658
  79. package/cli/lib/audit-sweep-runtime/closeout.mjs +0 -144
  80. package/cli/lib/audit-sweep-runtime/codex-auditor-evidence.mjs +0 -654
  81. package/cli/lib/audit-sweep-runtime/codex-auditor.mjs +0 -527
  82. package/cli/lib/audit-sweep-runtime/common.mjs +0 -341
  83. package/cli/lib/audit-sweep-runtime/coverage-quality.mjs +0 -172
  84. package/cli/lib/audit-sweep-runtime/evidence-assignment.mjs +0 -155
  85. package/cli/lib/audit-sweep-runtime/format.mjs +0 -57
  86. package/cli/lib/audit-sweep-runtime/ingest.mjs +0 -486
  87. package/cli/lib/audit-sweep-runtime/inventory-spec-chunks.mjs +0 -425
  88. package/cli/lib/audit-sweep-runtime/inventory.mjs +0 -798
  89. package/cli/lib/audit-sweep-runtime/ledger.mjs +0 -315
  90. package/cli/lib/audit-sweep-runtime/p0p1-profile.mjs +0 -101
  91. package/cli/lib/audit-sweep-runtime/remediation.mjs +0 -349
  92. package/cli/lib/audit-sweep-runtime/rerun.mjs +0 -129
  93. package/cli/lib/audit-sweep-runtime/risk-budget.mjs +0 -300
  94. package/cli/lib/audit-sweep-runtime/status.mjs +0 -62
  95. package/cli/lib/audit-sweep-runtime/validators-ledger.mjs +0 -215
  96. package/cli/lib/audit-sweep-runtime/validators.mjs +0 -797
  97. package/cli/lib/audit-sweep.mjs +0 -19
  98. package/cli/lib/authority-convergence.mjs +0 -720
  99. package/cli/lib/closeout.mjs +0 -732
  100. package/cli/lib/codex-sdk-runner.mjs +0 -76
  101. package/cli/lib/external-execution.mjs +0 -101
  102. package/cli/lib/handoff.mjs +0 -812
  103. package/cli/lib/high-risk-admission.mjs +0 -512
  104. package/cli/lib/high-risk-decision.mjs +0 -353
  105. package/cli/lib/high-risk-ingest.mjs +0 -321
  106. package/cli/lib/high-risk-review.mjs +0 -267
  107. package/cli/lib/internal/contracts-parse-high-risk.mjs +0 -131
  108. package/cli/lib/internal/contracts-validators.mjs +0 -399
  109. package/cli/lib/internal/doctor-bootstrap-surface.mjs +0 -406
  110. package/cli/lib/internal/doctor-delegated-surface.mjs +0 -256
  111. package/cli/lib/internal/doctor-finalize.mjs +0 -383
  112. package/cli/lib/internal/doctor-format.mjs +0 -286
  113. package/cli/lib/internal/doctor-inspectors.mjs +0 -327
  114. package/cli/lib/internal/doctor-state.mjs +0 -205
  115. package/cli/lib/internal/validators-artifacts.mjs +0 -515
  116. package/cli/lib/sweep-design-runtime/common.mjs +0 -246
  117. package/cli/lib/sweep-design-runtime/engine.mjs +0 -733
  118. package/cli/lib/sweep-design-runtime/fix-topic.mjs +0 -414
  119. package/cli/lib/sweep-design-runtime/lifecycle.mjs +0 -54
  120. package/cli/lib/sweep-design-runtime/results.mjs +0 -324
  121. package/cli/lib/sweep-design.mjs +0 -8
  122. package/cli/lib/topic-artifacts.mjs +0 -186
  123. package/cli/lib/topic-authority-coverage.mjs +0 -73
  124. package/cli/lib/topic-closeout.mjs +0 -560
  125. package/cli/lib/topic-common.mjs +0 -404
  126. package/cli/lib/topic-decisions.mjs +0 -332
  127. package/cli/lib/topic-draft-packets.mjs +0 -167
  128. package/cli/lib/topic-execution.mjs +0 -533
  129. package/cli/lib/topic-goal.mjs +0 -440
  130. package/cli/lib/topic-ledger.mjs +0 -281
  131. package/cli/lib/topic-lifecycle-artifacts.mjs +0 -173
  132. package/cli/lib/topic-root-validation.mjs +0 -288
  133. package/cli/lib/topic-runner-commands.mjs +0 -174
  134. package/cli/lib/topic-runner-deferral.mjs +0 -532
  135. package/cli/lib/topic-runner-stale-gates.mjs +0 -114
  136. package/cli/lib/topic-runner-validation.mjs +0 -138
  137. package/cli/lib/topic-runner.mjs +0 -727
  138. package/cli/lib/topic-scaffold.mjs +0 -252
  139. package/cli/lib/topic-waves.mjs +0 -403
  140. package/cli/lib/topic.mjs +0 -81
  141. package/config/audit-execution-artifacts.yaml +0 -20
  142. package/config/external-execution-artifacts.yaml +0 -16
  143. package/config/host-adapter.yaml +0 -30
  144. package/config/host-profile.yaml +0 -29
  145. package/config/installer-evidence.yaml +0 -31
  146. package/config/skill-installer.yaml +0 -23
  147. package/config/skill-manifest.yaml +0 -48
  148. package/config/skills.yaml +0 -30
  149. package/contracts/acceptance.schema.yaml +0 -16
  150. package/contracts/admission-checklist.schema.yaml +0 -15
  151. package/contracts/audit-chunk.schema.yaml +0 -123
  152. package/contracts/audit-closeout.schema.yaml +0 -51
  153. package/contracts/audit-finding.schema.yaml +0 -61
  154. package/contracts/audit-ledger.schema.yaml +0 -138
  155. package/contracts/audit-plan.schema.yaml +0 -138
  156. package/contracts/audit-remediation-map.schema.yaml +0 -52
  157. package/contracts/audit-rerun.schema.yaml +0 -31
  158. package/contracts/audit-sweep-result.yaml +0 -53
  159. package/contracts/authority-convergence-audit.schema.yaml +0 -19
  160. package/contracts/closeout.schema.yaml +0 -25
  161. package/contracts/decision-review.schema.yaml +0 -16
  162. package/contracts/doc-spec-audit-result.yaml +0 -19
  163. package/contracts/execution-packet.schema.yaml +0 -49
  164. package/contracts/external-host-compatibility.yaml +0 -22
  165. package/contracts/forbidden-shortcuts.catalog.yaml +0 -23
  166. package/contracts/high-risk-admission.schema.yaml +0 -23
  167. package/contracts/high-risk-execution-result.yaml +0 -20
  168. package/contracts/orchestration-state.schema.yaml +0 -41
  169. package/contracts/overflow-continuation.schema.yaml +0 -12
  170. package/contracts/packet.schema.yaml +0 -30
  171. package/contracts/pending-note.schema.yaml +0 -17
  172. package/contracts/prompt.schema.yaml +0 -12
  173. package/contracts/remediation.schema.yaml +0 -16
  174. package/contracts/result.schema.yaml +0 -24
  175. package/contracts/spec-reconstruction-result.yaml +0 -41
  176. package/contracts/sweep-design-result.yaml +0 -349
  177. package/contracts/topic-goal.schema.yaml +0 -87
  178. package/contracts/topic-run-ledger.schema.yaml +0 -72
  179. package/contracts/topic-step-decision.schema.yaml +0 -45
  180. package/contracts/topic.schema.yaml +0 -65
  181. package/contracts/true-close.schema.yaml +0 -15
  182. package/contracts/wave.schema.yaml +0 -29
  183. package/contracts/worker-output.schema.yaml +0 -15
  184. package/contracts/workflow-consumer.schema.yaml +0 -110
  185. package/methodology/audit-sweep-p0p1-recall.yaml +0 -45
  186. package/methodology/authority-convergence-policy.yaml +0 -42
  187. package/methodology/overflow-continuation-policy.yaml +0 -14
  188. package/methodology/skill-exchange-projection.yaml +0 -114
  189. package/methodology/skill-handoff.yaml +0 -34
  190. package/methodology/skill-installer-result.yaml +0 -27
  191. package/methodology/skill-installer-summary-projection.yaml +0 -181
  192. package/methodology/skill-runtime.yaml +0 -23
  193. package/methodology/spec-target-truth-profile.yaml +0 -46
  194. package/methodology/topic-lifecycle-report.yaml +0 -144
  195. package/methodology/topic-lifecycle.yaml +0 -37
  196. package/methodology/topic-naming-ontology.yaml +0 -21
  197. package/methodology/topic-ontology.yaml +0 -38
  198. package/methodology/topic-validation-policy.yaml +0 -9
  199. package/methodology/wave-dag-policy.yaml +0 -14
  200. package/spec/_meta/command-gating-matrix.yaml +0 -143
  201. package/spec/_meta/generate-drift-migration-checklist.yaml +0 -137
  202. package/spec/_meta/governance-routing-cutover-checklist.yaml +0 -35
  203. package/spec/_meta/phase2-impacted-surface-matrix.yaml +0 -44
  204. package/spec/_meta/spec-authority-cutover-readiness.yaml +0 -102
  205. package/spec/bootstrap-state.yaml +0 -99
@@ -1,798 +0,0 @@
1
- import { execFile as execFileCallback } from "node:child_process";
2
- import { readdir, readFile, stat } from "node:fs/promises";
3
- import path from "node:path";
4
- import { promisify } from "node:util";
5
-
6
- import {
7
- AUDITABLE_EXTENSIONS,
8
- DEFAULT_CRITERIA,
9
- DEFAULT_EXCLUDE_PATTERNS,
10
- DEFAULT_MAX_FILES_PER_CHUNK,
11
- appendRunEvent,
12
- artifactPath,
13
- chunkRef,
14
- deriveSweepId,
15
- inputError,
16
- loadPlan,
17
- normalizeCsv,
18
- planRef,
19
- relPath,
20
- resolveInsideProject,
21
- runLedgerRef,
22
- safeSweepId,
23
- sha256Object,
24
- sha256Text,
25
- toPosix,
26
- writeYamlRef,
27
- } from "./common.mjs";
28
- import {
29
- APP_SLICE_ADMISSION_REF,
30
- AUDIT_SWEEP_PROJECT_CONFIG_REF,
31
- loadAppSliceAdmissions,
32
- loadAuditEvidenceRootAdmissions,
33
- loadAuditSweepProjectConfig,
34
- loadDelegatedProjectionAdmissions,
35
- loadPackageAuthorityAdmissions,
36
- } from "./admissions.mjs";
37
- import { buildCoverageQuality } from "./coverage-quality.mjs";
38
- import { assignEvidenceInventory } from "./evidence-assignment.mjs";
39
- import { buildSpecChunks } from "./inventory-spec-chunks.mjs";
40
- import { buildRiskBudgetPolicy } from "./risk-budget.mjs";
41
- import { pathExists } from "../fs-helpers.mjs";
42
- import {
43
- buildSpecSurfaceInventory,
44
- isProductAuthoritySurfaceClass,
45
- } from "../internal/surface-taxonomy-validators.mjs";
46
-
47
- const execFile = promisify(execFileCallback);
48
- async function listGitFiles(projectRoot, targetRootRef) {
49
- try {
50
- const result = await execFile(
51
- "git",
52
- ["ls-files", "--cached", "--others", "--exclude-standard", "--", targetRootRef],
53
- { cwd: projectRoot },
54
- );
55
- return result.stdout.split(/\r?\n/).filter(Boolean).sort();
56
- } catch {
57
- return [];
58
- }
59
- }
60
-
61
- function isExcluded(fileRef, excludePatterns) {
62
- return excludePatterns.some((pattern) => {
63
- const normalized = pattern.replace(/\\/g, "/");
64
- if (!normalized) {
65
- return false;
66
- }
67
- if (normalized.includes("*")) {
68
- let patternText = "";
69
- for (let index = 0; index < normalized.length; index += 1) {
70
- const char = normalized[index];
71
- if (char === "*" && normalized[index + 1] === "*") {
72
- patternText += ".*";
73
- index += 1;
74
- } else if (char === "*") {
75
- patternText += "[^/]*";
76
- } else {
77
- patternText += char.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
78
- }
79
- }
80
- return new RegExp(`^${patternText}$`).test(fileRef);
81
- }
82
- if (normalized.endsWith("/")) {
83
- return fileRef === normalized.slice(0, -1) || fileRef.startsWith(normalized);
84
- }
85
- return fileRef === normalized || fileRef.includes(normalized);
86
- });
87
- }
88
-
89
- async function listFallbackFiles(projectRoot, targetRootRef, excludePatterns) {
90
- const targetRoot = path.resolve(projectRoot, targetRootRef);
91
- const files = [];
92
-
93
- async function visit(currentPath) {
94
- const entries = await readdir(currentPath, { withFileTypes: true });
95
- for (const entry of entries) {
96
- const absolutePath = path.join(currentPath, entry.name);
97
- const fileRef = relPath(projectRoot, absolutePath);
98
- if (isExcluded(entry.isDirectory() ? `${fileRef}/` : fileRef, excludePatterns)) {
99
- continue;
100
- }
101
- if (entry.isDirectory()) {
102
- await visit(absolutePath);
103
- } else if (entry.isFile()) {
104
- files.push(fileRef);
105
- }
106
- }
107
- }
108
-
109
- await visit(targetRoot);
110
- return files.sort();
111
- }
112
-
113
- function classifyFile(fileRef) {
114
- const extension = path.posix.extname(fileRef);
115
- if ([".md", ".yaml", ".yml", ".json", ".prisma"].includes(extension)) {
116
- return "contract-or-doc";
117
- }
118
- if ([".test.ts", ".test.js", ".spec.ts", ".spec.js"].some((suffix) => fileRef.endsWith(suffix))) {
119
- return "test";
120
- }
121
- return "implementation";
122
- }
123
-
124
- function ownerDomainForFile(fileRef, targetRootRef) {
125
- const normalizedTarget = targetRootRef === "." ? "" : `${targetRootRef.replace(/\/$/, "")}/`;
126
- const withoutTarget = normalizedTarget && fileRef.startsWith(normalizedTarget)
127
- ? fileRef.slice(normalizedTarget.length)
128
- : fileRef;
129
- const parts = withoutTarget.split("/");
130
- if (parts.length <= 1) {
131
- return targetRootRef === "." ? "root" : targetRootRef;
132
- }
133
- return path.posix.join(targetRootRef === "." ? "" : targetRootRef, parts[0]) || parts[0];
134
- }
135
-
136
- function isSpecAuthorityRoot(ref) {
137
- return ref === ".nimi/spec" || ref === ".nimi/spec/";
138
- }
139
-
140
- async function hasSpecAuthorityRoot(projectRoot) {
141
- const info = await pathExists(path.join(projectRoot, ".nimi", "spec"));
142
- return info?.isDirectory() === true;
143
- }
144
-
145
- function resolveChunkBasis(targetRootRef, requested, specRootPresent) {
146
- const normalized = requested ? String(requested).trim() : "auto";
147
- if (!["auto", "files", "spec"].includes(normalized)) {
148
- return { ok: false, error: "nimicoding sweep audit refused: --chunk-basis must be auto, files, or spec.\n" };
149
- }
150
- if (normalized === "files") {
151
- return { ok: true, basis: "files" };
152
- }
153
- if (normalized === "spec") {
154
- return specRootPresent
155
- ? { ok: true, basis: "spec" }
156
- : { ok: false, error: "nimicoding sweep audit refused: --chunk-basis spec requires .nimi/spec.\n" };
157
- }
158
- return { ok: true, basis: (targetRootRef === "." || isSpecAuthorityRoot(targetRootRef)) && specRootPresent ? "spec" : "files" };
159
- }
160
-
161
- async function buildInventoryEntry(projectRoot, fileRef, targetRootRef, excludePatterns, options = {}) {
162
- const extension = path.posix.extname(fileRef);
163
- const excluded = !options.forceAuthority && !fileRef.startsWith(".nimi/spec/") && isExcluded(fileRef, excludePatterns);
164
- const auditable = AUDITABLE_EXTENSIONS.has(extension);
165
- const absolutePath = artifactPath(projectRoot, fileRef);
166
- const fileStat = await stat(absolutePath);
167
- const contents = await readFile(absolutePath);
168
- const included = !excluded && auditable;
169
-
170
- return {
171
- file_ref: fileRef,
172
- sha256: sha256Text(contents),
173
- bytes: fileStat.size,
174
- extension: extension || "none",
175
- owner_domain: options.ownerDomain ?? ownerDomainForFile(fileRef, targetRootRef),
176
- classification: classifyFile(fileRef),
177
- surface_class: options.surfaceClass ?? null,
178
- included,
179
- exclusion_reason: included
180
- ? null
181
- : (excluded ? "matched_exclude_pattern" : "extension_not_auditable"),
182
- };
183
- }
184
-
185
- function applySpecSurfaceAuthorityFilter(inventory, surfaceEntriesByRef) {
186
- return inventory.map((entry) => {
187
- const surfaceEntry = surfaceEntriesByRef.get(entry.file_ref);
188
- if (!surfaceEntry) {
189
- return entry;
190
- }
191
- const surfaceClass = surfaceEntry.current_inferred_class;
192
- if (isProductAuthoritySurfaceClass(surfaceClass)) {
193
- return { ...entry, surface_class: surfaceClass };
194
- }
195
- return {
196
- ...entry,
197
- surface_class: surfaceClass,
198
- included: false,
199
- exclusion_reason: `non_product_surface:${surfaceClass}`,
200
- };
201
- });
202
- }
203
-
204
- function buildFileChunks(includedInventory, options) {
205
- const byOwner = new Map();
206
- for (const entry of includedInventory) {
207
- const files = byOwner.get(entry.owner_domain) ?? [];
208
- files.push(entry);
209
- byOwner.set(entry.owner_domain, files);
210
- }
211
-
212
- const chunks = [];
213
- for (const [ownerDomain, entries] of [...byOwner.entries()].sort(([left], [right]) => left.localeCompare(right))) {
214
- const sortedEntries = entries.sort((left, right) => left.file_ref.localeCompare(right.file_ref));
215
- for (let index = 0; index < sortedEntries.length; index += options.maxFilesPerChunk) {
216
- const chunkEntries = sortedEntries.slice(index, index + options.maxFilesPerChunk);
217
- chunks.push({
218
- chunk_id: `chunk-${String(chunks.length + 1).padStart(3, "0")}`,
219
- state: "planned",
220
- owner_domain: ownerDomain,
221
- criteria: options.criteria,
222
- files: chunkEntries.map((entry) => entry.file_ref),
223
- file_count: chunkEntries.length,
224
- finding_count: 0,
225
- });
226
- }
227
- }
228
-
229
- return chunks;
230
- }
231
-
232
- function buildAuditIgnorePolicy(projectConfig, options) {
233
- const patterns = [
234
- ...(projectConfig.ignorePatterns ?? []),
235
- ...normalizeCsv(options.ignore),
236
- ];
237
- const ownerDomains = [
238
- ...(projectConfig.ignoreOwnerDomains ?? []),
239
- ...normalizeCsv(options.ignoreOwner),
240
- ];
241
- const reason = typeof options.ignoreReason === "string" && options.ignoreReason.trim()
242
- ? options.ignoreReason.trim()
243
- : projectConfig.ignoreReason;
244
- if (patterns.length === 0 && ownerDomains.length === 0) {
245
- return null;
246
- }
247
- if (!reason) {
248
- return {
249
- ok: false,
250
- error: "nimicoding sweep audit refused: --ignore or --ignore-owner requires --ignore-reason, or .nimi/config/audit-sweep.yaml audit_sweep.ignore_reason.\n",
251
- };
252
- }
253
- return {
254
- ok: true,
255
- policy: {
256
- mode: "explicit_scope_omission",
257
- patterns,
258
- owner_domains: ownerDomains,
259
- reason,
260
- },
261
- };
262
- }
263
-
264
- function chunkIgnoreMatches(chunk, ignorePolicy) {
265
- if (!ignorePolicy) {
266
- return [];
267
- }
268
- const matches = [];
269
- if (ignorePolicy.owner_domains.includes(chunk.owner_domain)) {
270
- matches.push(`owner:${chunk.owner_domain}`);
271
- }
272
- const refs = [
273
- ...(chunk.files ?? []),
274
- ...(chunk.authority_refs ?? []),
275
- ...(chunk.evidence_roots ?? []),
276
- ...(chunk.evidence_inventory ?? []),
277
- ];
278
- for (const pattern of ignorePolicy.patterns) {
279
- if (refs.some((ref) => isExcluded(ref, [pattern]))) {
280
- matches.push(`pattern:${pattern}`);
281
- }
282
- }
283
- return [...new Set(matches)].sort();
284
- }
285
-
286
- function applyAuditIgnorePolicy(chunks, ignorePolicy, ignoredAt) {
287
- if (!ignorePolicy) {
288
- return { chunks, ignoredChunks: [] };
289
- }
290
- const ignoredChunks = [];
291
- const nextChunks = chunks.map((chunk) => {
292
- const matches = chunkIgnoreMatches(chunk, ignorePolicy);
293
- if (matches.length === 0) {
294
- return chunk;
295
- }
296
- ignoredChunks.push({
297
- chunk_id: chunk.chunk_id,
298
- owner_domain: chunk.owner_domain,
299
- matches,
300
- files: chunk.files ?? [],
301
- authority_refs: chunk.authority_refs ?? chunk.files ?? [],
302
- evidence_roots: chunk.evidence_roots ?? [],
303
- });
304
- return {
305
- ...chunk,
306
- state: "skipped",
307
- skip: {
308
- reason: ignorePolicy.reason,
309
- ignored_by_policy: true,
310
- matches,
311
- skipped_at: ignoredAt,
312
- },
313
- };
314
- });
315
- return { chunks: nextChunks, ignoredChunks };
316
- }
317
-
318
- async function listAdmittedPackageAuthorityEntries(projectRoot, packageAuthorityAdmissions, excludePatterns) {
319
- const entries = [];
320
- for (const admission of packageAuthorityAdmissions) {
321
- const rootInfo = await pathExists(artifactPath(projectRoot, admission.authority_root));
322
- if (!rootInfo?.isDirectory()) {
323
- return {
324
- ok: false,
325
- error: `nimicoding sweep audit refused: package authority admission ${admission.id} authority_root is missing: ${admission.authority_root}.\n`,
326
- };
327
- }
328
- const gitFiles = await listGitFiles(projectRoot, admission.authority_root);
329
- const allFileRefs = gitFiles.length > 0
330
- ? gitFiles.map((entry) => toPosix(entry))
331
- : await listFallbackFiles(projectRoot, admission.authority_root, excludePatterns);
332
- for (const fileRef of allFileRefs) {
333
- const normalizedRef = toPosix(fileRef);
334
- const extension = path.posix.extname(normalizedRef);
335
- if (!AUDITABLE_EXTENSIONS.has(extension)) {
336
- continue;
337
- }
338
- entries.push(await buildInventoryEntry(projectRoot, normalizedRef, admission.authority_root, excludePatterns, {
339
- forceAuthority: true,
340
- ownerDomain: admission.owner_domain,
341
- }));
342
- }
343
- }
344
- return { ok: true, entries };
345
- }
346
-
347
- async function listAdmittedAppAuthorityEntries(projectRoot, appSliceAdmissions, excludePatterns) {
348
- const entries = [];
349
- for (const admission of appSliceAdmissions) {
350
- const rootInfo = await pathExists(artifactPath(projectRoot, admission.authority_root));
351
- if (!rootInfo?.isDirectory()) {
352
- return {
353
- ok: false,
354
- error: `nimicoding sweep audit refused: app-slice admission ${admission.app_id} authority_root is missing: ${admission.authority_root}.\n`,
355
- };
356
- }
357
- const gitFiles = await listGitFiles(projectRoot, admission.authority_root);
358
- const allFileRefs = gitFiles.length > 0
359
- ? gitFiles.map((entry) => toPosix(entry))
360
- : await listFallbackFiles(projectRoot, admission.authority_root, excludePatterns);
361
- for (const fileRef of allFileRefs) {
362
- const normalizedRef = toPosix(fileRef);
363
- const extension = path.posix.extname(normalizedRef);
364
- if (!AUDITABLE_EXTENSIONS.has(extension)) {
365
- continue;
366
- }
367
- entries.push(await buildInventoryEntry(projectRoot, normalizedRef, admission.authority_root, excludePatterns, {
368
- forceAuthority: true,
369
- ownerDomain: admission.owner_domain,
370
- }));
371
- }
372
- }
373
- return { ok: true, entries };
374
- }
375
-
376
- async function listAuditableEntriesForRoot(projectRoot, rootRef, excludePatterns) {
377
- const rootInfo = await pathExists(artifactPath(projectRoot, rootRef));
378
- if (!rootInfo) {
379
- return [];
380
- }
381
- const gitFiles = await listGitFiles(projectRoot, rootRef);
382
- const allFileRefs = gitFiles.length > 0
383
- ? gitFiles.map((entry) => toPosix(entry))
384
- : (rootInfo.isDirectory() ? await listFallbackFiles(projectRoot, rootRef, excludePatterns) : [rootRef]);
385
- const entries = [];
386
- for (const fileRef of allFileRefs) {
387
- const normalizedRef = toPosix(fileRef);
388
- if (isExcluded(normalizedRef, excludePatterns)) {
389
- continue;
390
- }
391
- const extension = path.posix.extname(normalizedRef);
392
- if (!AUDITABLE_EXTENSIONS.has(extension)) {
393
- continue;
394
- }
395
- entries.push(await buildInventoryEntry(projectRoot, normalizedRef, ".", excludePatterns));
396
- }
397
- return entries.filter((entry) => entry.included);
398
- }
399
-
400
- export async function createAuditSweepPlan(projectRoot, options) {
401
- const targetRoot = resolveInsideProject(projectRoot, options.root ?? ".", "--root");
402
- if (!targetRoot.ok) {
403
- return inputError(targetRoot.error);
404
- }
405
- const targetRootRef = targetRoot.ref || ".";
406
-
407
- const targetInfo = await pathExists(targetRoot.absolutePath);
408
- if (!targetInfo || !targetInfo.isDirectory()) {
409
- return inputError("nimicoding sweep audit refused: --root must point to an existing directory.\n");
410
- }
411
-
412
- const sweepId = options.sweepId ? safeSweepId(options.sweepId) : deriveSweepId(targetRootRef);
413
- if (!sweepId) {
414
- return inputError("nimicoding sweep audit refused: --sweep-id must be a safe id.\n");
415
- }
416
-
417
- const specRootPresent = await hasSpecAuthorityRoot(projectRoot);
418
- const chunkBasis = resolveChunkBasis(targetRootRef, options.chunkBasis, specRootPresent);
419
- if (!chunkBasis.ok) {
420
- return inputError(chunkBasis.error);
421
- }
422
- const inventoryRootRef = chunkBasis.basis === "spec" ? ".nimi/spec" : targetRootRef;
423
- const criteria = normalizeCsv(options.criteria, DEFAULT_CRITERIA);
424
- const projectConfig = await loadAuditSweepProjectConfig(projectRoot);
425
- if (!projectConfig.ok) {
426
- return inputError(projectConfig.error);
427
- }
428
- const auditIgnorePolicyResult = buildAuditIgnorePolicy(projectConfig, options);
429
- if (auditIgnorePolicyResult?.ok === false) {
430
- return inputError(auditIgnorePolicyResult.error);
431
- }
432
- const auditIgnorePolicy = auditIgnorePolicyResult?.policy ?? null;
433
- const excludePatterns = [
434
- ...DEFAULT_EXCLUDE_PATTERNS,
435
- ...projectConfig.excludePatterns,
436
- ...normalizeCsv(options.exclude),
437
- ];
438
- const maxFilesPerChunk = Number.isInteger(options.maxFilesPerChunk) && options.maxFilesPerChunk > 0
439
- ? options.maxFilesPerChunk
440
- : DEFAULT_MAX_FILES_PER_CHUNK;
441
- const riskBudgetPolicy = buildRiskBudgetPolicy(options);
442
- let appSliceAdmissions = [];
443
- let auditEvidenceRootAdmissions = [];
444
- let auditEvidenceRootAdmissionRefs = [];
445
- let delegatedProjectionAdmissions = [];
446
- let delegatedProjectionAdmissionRefs = [];
447
- let packageAuthorityAdmissions = [];
448
- let packageAuthorityAdmissionRefs = [];
449
- if (chunkBasis.basis === "spec") {
450
- const loadedAdmissions = await loadAppSliceAdmissions(projectRoot);
451
- if (!loadedAdmissions.ok) {
452
- return inputError(loadedAdmissions.error);
453
- }
454
- appSliceAdmissions = loadedAdmissions.admissions;
455
- const loadedEvidenceRootAdmissions = await loadAuditEvidenceRootAdmissions(projectRoot, listGitFiles, listFallbackFiles);
456
- if (!loadedEvidenceRootAdmissions.ok) {
457
- return inputError(loadedEvidenceRootAdmissions.error);
458
- }
459
- auditEvidenceRootAdmissions = loadedEvidenceRootAdmissions.admissions;
460
- auditEvidenceRootAdmissionRefs = loadedEvidenceRootAdmissions.tableRefs;
461
- const loadedDelegatedProjectionAdmissions = await loadDelegatedProjectionAdmissions(projectRoot, listGitFiles, listFallbackFiles);
462
- if (!loadedDelegatedProjectionAdmissions.ok) {
463
- return inputError(loadedDelegatedProjectionAdmissions.error);
464
- }
465
- delegatedProjectionAdmissions = loadedDelegatedProjectionAdmissions.admissions;
466
- delegatedProjectionAdmissionRefs = loadedDelegatedProjectionAdmissions.tableRefs;
467
- const loadedPackageAuthorityAdmissions = await loadPackageAuthorityAdmissions(projectRoot, listGitFiles, listFallbackFiles);
468
- if (!loadedPackageAuthorityAdmissions.ok) {
469
- return inputError(loadedPackageAuthorityAdmissions.error);
470
- }
471
- packageAuthorityAdmissions = loadedPackageAuthorityAdmissions.admissions;
472
- packageAuthorityAdmissionRefs = loadedPackageAuthorityAdmissions.tableRefs;
473
- }
474
- const gitFiles = await listGitFiles(projectRoot, inventoryRootRef);
475
- const allFileRefs = gitFiles.length > 0
476
- ? gitFiles.map((entry) => toPosix(entry))
477
- : await listFallbackFiles(projectRoot, inventoryRootRef, excludePatterns);
478
- const inventory = [];
479
- for (const fileRef of allFileRefs) {
480
- inventory.push(await buildInventoryEntry(projectRoot, fileRef, inventoryRootRef, excludePatterns, { forceAuthority: true }));
481
- }
482
- let specSurfaceReport = null;
483
- let authorityInventory = inventory;
484
- if (chunkBasis.basis === "spec") {
485
- specSurfaceReport = await buildSpecSurfaceInventory(projectRoot, { rootRef: inventoryRootRef });
486
- const surfaceEntriesByRef = new Map(specSurfaceReport.entries.map((entry) => [entry.source_path, entry]));
487
- authorityInventory = applySpecSurfaceAuthorityFilter(inventory, surfaceEntriesByRef);
488
- }
489
- if (chunkBasis.basis === "spec" && appSliceAdmissions.length > 0) {
490
- const appAuthorityEntries = await listAdmittedAppAuthorityEntries(projectRoot, appSliceAdmissions, excludePatterns);
491
- if (!appAuthorityEntries.ok) {
492
- return inputError(appAuthorityEntries.error);
493
- }
494
- const seenAuthorityRefs = new Set(authorityInventory.map((entry) => entry.file_ref));
495
- for (const entry of appAuthorityEntries.entries) {
496
- if (!seenAuthorityRefs.has(entry.file_ref)) {
497
- authorityInventory.push(entry);
498
- seenAuthorityRefs.add(entry.file_ref);
499
- }
500
- }
501
- }
502
- if (chunkBasis.basis === "spec" && packageAuthorityAdmissions.length > 0) {
503
- const packageAuthorityEntries = await listAdmittedPackageAuthorityEntries(projectRoot, packageAuthorityAdmissions, excludePatterns);
504
- if (!packageAuthorityEntries.ok) {
505
- return inputError(packageAuthorityEntries.error);
506
- }
507
- const seenAuthorityRefs = new Set(authorityInventory.map((entry) => entry.file_ref));
508
- for (const entry of packageAuthorityEntries.entries) {
509
- if (!seenAuthorityRefs.has(entry.file_ref)) {
510
- authorityInventory.push(entry);
511
- seenAuthorityRefs.add(entry.file_ref);
512
- }
513
- }
514
- }
515
-
516
- const includedInventory = authorityInventory.filter((entry) => entry.included);
517
- const authorityFileRefs = new Set(includedInventory.map((entry) => entry.file_ref));
518
- const authorityTextByRef = new Map();
519
- if (chunkBasis.basis === "spec") {
520
- for (const entry of includedInventory) {
521
- authorityTextByRef.set(entry.file_ref, await readFile(artifactPath(projectRoot, entry.file_ref), "utf8"));
522
- }
523
- }
524
- let chunks = chunkBasis.basis === "spec"
525
- ? buildSpecChunks(includedInventory, { criteria, targetRootRef, appSliceAdmissions, auditEvidenceRootAdmissions, delegatedProjectionAdmissions, packageAuthorityAdmissions, authorityTextByRef })
526
- : buildFileChunks(includedInventory, { criteria, maxFilesPerChunk });
527
- let evidenceInventory = [];
528
- let unmappedEvidenceFiles = [];
529
- let evidenceInventoryHash = null;
530
- if (chunkBasis.basis === "spec") {
531
- const evidenceRoots = [...new Set(chunks.flatMap((chunk) => chunk.evidence_roots ?? []))].sort();
532
- const evidenceByFile = new Map();
533
- for (const rootRef of evidenceRoots) {
534
- const entries = await listAuditableEntriesForRoot(projectRoot, rootRef, excludePatterns);
535
- for (const entry of entries) {
536
- if (!authorityFileRefs.has(entry.file_ref)) {
537
- evidenceByFile.set(entry.file_ref, entry);
538
- }
539
- }
540
- }
541
- evidenceInventory = [...evidenceByFile.values()].sort((left, right) => left.file_ref.localeCompare(right.file_ref));
542
- const assigned = assignEvidenceInventory(evidenceInventory, chunks, {
543
- maxEvidenceFilesPerChunk: maxFilesPerChunk,
544
- });
545
- chunks = assigned.chunks;
546
- unmappedEvidenceFiles = assigned.unmappedEvidenceFiles;
547
- evidenceInventoryHash = sha256Object(evidenceInventory.map((entry) => ({
548
- file_ref: entry.file_ref,
549
- sha256: entry.sha256,
550
- included: entry.included,
551
- exclusion_reason: entry.exclusion_reason,
552
- })));
553
- }
554
- const createdAt = options.createdAt ?? new Date().toISOString();
555
- const ignoreResult = applyAuditIgnorePolicy(chunks, auditIgnorePolicy, createdAt);
556
- chunks = ignoreResult.chunks;
557
- const inventoryHash = sha256Object(authorityInventory.map((entry) => ({
558
- file_ref: entry.file_ref,
559
- sha256: entry.sha256,
560
- included: entry.included,
561
- exclusion_reason: entry.exclusion_reason,
562
- })));
563
- const plan = {
564
- version: 1,
565
- kind: "audit-plan",
566
- sweep_id: sweepId,
567
- target_root: targetRootRef,
568
- planning_basis: {
569
- mode: chunkBasis.basis === "spec" ? "spec_authority" : "file_inventory",
570
- authority_root: chunkBasis.basis === "spec" ? ".nimi/spec" : null,
571
- inventory_root: inventoryRootRef,
572
- evidence_root: targetRootRef,
573
- files_are_evidence_only: chunkBasis.basis === "spec",
574
- },
575
- criteria,
576
- max_files_per_chunk: maxFilesPerChunk,
577
- ...(auditIgnorePolicy ? {
578
- audit_ignore_policy: {
579
- ...auditIgnorePolicy,
580
- ignored_chunk_count: ignoreResult.ignoredChunks.length,
581
- ignored_chunks: ignoreResult.ignoredChunks,
582
- },
583
- } : {}),
584
- ...(riskBudgetPolicy ? { risk_budget_policy: riskBudgetPolicy } : {}),
585
- risk_budget_status: null,
586
- audit_sweep_config_ref: projectConfig.found ? AUDIT_SWEEP_PROJECT_CONFIG_REF : null,
587
- ...(chunkBasis.basis === "spec" && appSliceAdmissions.length > 0 ? {
588
- app_slice_admission_ref: APP_SLICE_ADMISSION_REF,
589
- app_slice_admissions: appSliceAdmissions.map((admission) => ({
590
- app_id: admission.app_id,
591
- owner_domain: admission.owner_domain,
592
- status: admission.status,
593
- authority_root: admission.authority_root,
594
- evidence_roots: admission.evidence_roots,
595
- admission_ref: admission.admission_ref,
596
- })),
597
- } : {}),
598
- ...(chunkBasis.basis === "spec" && auditEvidenceRootAdmissionRefs.length > 0 ? {
599
- audit_evidence_root_refs: auditEvidenceRootAdmissionRefs,
600
- } : {}),
601
- ...(chunkBasis.basis === "spec" && delegatedProjectionAdmissions.length > 0 ? {
602
- delegated_projection_admission_refs: delegatedProjectionAdmissionRefs,
603
- delegated_projection_admissions: delegatedProjectionAdmissions.map((admission) => ({
604
- id: admission.id,
605
- owner_domain: admission.owner_domain,
606
- status: admission.status,
607
- authority_root: admission.authority_root,
608
- source_authority_root: admission.source_authority_root,
609
- local_projection_evidence_roots: admission.local_projection_evidence_roots,
610
- delegated_evidence_roots: admission.delegated_evidence_roots,
611
- delegated_declared_evidence_prefixes: admission.delegated_declared_evidence_prefixes,
612
- host_owned_relative_paths: admission.host_owned_relative_paths,
613
- required_verification_commands: admission.required_verification_commands,
614
- admission_ref: admission.admission_ref,
615
- })),
616
- } : {}),
617
- ...(chunkBasis.basis === "spec" && packageAuthorityAdmissions.length > 0 ? {
618
- package_authority_admission_refs: packageAuthorityAdmissionRefs,
619
- package_authority_admissions: packageAuthorityAdmissions.map((admission) => ({
620
- id: admission.id,
621
- owner_domain: admission.owner_domain,
622
- status: admission.status,
623
- authority_root: admission.authority_root,
624
- evidence_roots: admission.evidence_roots,
625
- host_authority_projection_refs: admission.host_authority_projection_refs ?? [],
626
- admission_ref: admission.admission_ref,
627
- })),
628
- } : {}),
629
- exclude_patterns: excludePatterns,
630
- inventory_hash: inventoryHash,
631
- ...(specSurfaceReport ? {
632
- surface_classification: {
633
- contract: specSurfaceReport.contract,
634
- summary: specSurfaceReport.summary,
635
- errors: specSurfaceReport.errors,
636
- },
637
- } : {}),
638
- ...(evidenceInventoryHash ? { evidence_inventory_hash: evidenceInventoryHash } : {}),
639
- inventory: authorityInventory,
640
- ...(chunkBasis.basis === "spec" ? {
641
- evidence_inventory: evidenceInventory.map((entry) => ({
642
- file_ref: entry.file_ref,
643
- sha256: entry.sha256,
644
- bytes: entry.bytes,
645
- extension: entry.extension,
646
- owner_domain: entry.owner_domain,
647
- classification: entry.classification,
648
- included: entry.included,
649
- exclusion_reason: entry.exclusion_reason,
650
- })),
651
- unmapped_evidence_files: unmappedEvidenceFiles,
652
- } : {}),
653
- chunks,
654
- coverage: {
655
- total_files: authorityInventory.length,
656
- included_files: includedInventory.length,
657
- excluded_files: authorityInventory.length - includedInventory.length,
658
- ...(chunkBasis.basis === "spec" ? {
659
- authority_files: includedInventory.length,
660
- evidence_files: evidenceInventory.length,
661
- unmapped_evidence_files: unmappedEvidenceFiles.length,
662
- authority_chunks_without_evidence_inventory: chunks.filter((chunk) => (chunk.evidence_inventory ?? []).length === 0).length,
663
- } : {}),
664
- ...(auditIgnorePolicy ? {
665
- ignored_chunks: ignoreResult.ignoredChunks.length,
666
- } : {}),
667
- chunk_count: chunks.length,
668
- },
669
- run_ledger_ref: runLedgerRef(sweepId),
670
- created_at: createdAt,
671
- updated_at: createdAt,
672
- };
673
- const coverageQuality = buildCoverageQuality(plan, chunks, plan.coverage);
674
- if (coverageQuality) {
675
- plan.coverage_quality = coverageQuality;
676
- }
677
-
678
- await writeYamlRef(projectRoot, planRef(sweepId), plan);
679
- for (const chunk of chunks) {
680
- const chunkInventory = includedInventory.filter((entry) => chunk.files.includes(entry.file_ref));
681
- const evidenceByFile = new Map(evidenceInventory.map((entry) => [entry.file_ref, entry]));
682
- await writeYamlRef(projectRoot, chunkRef(sweepId, chunk.chunk_id), {
683
- version: 1,
684
- kind: "audit-chunk",
685
- sweep_id: sweepId,
686
- chunk_id: chunk.chunk_id,
687
- state: chunk.state,
688
- owner_domain: chunk.owner_domain,
689
- criteria,
690
- files: chunk.files,
691
- ...(chunk.planning_basis ? { planning_basis: chunk.planning_basis } : {}),
692
- ...(chunk.spec_surface ? { spec_surface: chunk.spec_surface } : {}),
693
- ...(chunk.authority_refs ? { authority_refs: chunk.authority_refs } : {}),
694
- ...(chunk.authority_kind ? { authority_kind: chunk.authority_kind } : {}),
695
- ...(chunk.app_id ? { app_id: chunk.app_id } : {}),
696
- ...(chunk.package_authority_id ? { package_authority_id: chunk.package_authority_id } : {}),
697
- ...(chunk.delegated_projection_id ? { delegated_projection_id: chunk.delegated_projection_id } : {}),
698
- ...(chunk.admission_ref ? { admission_ref: chunk.admission_ref } : {}),
699
- ...(chunk.authority_root ? { authority_root: chunk.authority_root } : {}),
700
- ...(chunk.source_authority_root ? { source_authority_root: chunk.source_authority_root } : {}),
701
- ...(chunk.evidence_root_admission_refs ? { evidence_root_admission_refs: chunk.evidence_root_admission_refs } : {}),
702
- ...(chunk.admitted_evidence_roots ? { admitted_evidence_roots: chunk.admitted_evidence_roots } : {}),
703
- ...(chunk.host_authority_projection_refs ? { host_authority_projection_refs: chunk.host_authority_projection_refs } : {}),
704
- ...(chunk.delegated_evidence_roots ? { delegated_evidence_roots: chunk.delegated_evidence_roots } : {}),
705
- ...(chunk.delegated_declared_evidence_prefixes ? { delegated_declared_evidence_prefixes: chunk.delegated_declared_evidence_prefixes } : {}),
706
- ...(chunk.delegated_declared_evidence_refs ? { delegated_declared_evidence_refs: chunk.delegated_declared_evidence_refs } : {}),
707
- ...(chunk.declared_evidence_delegation ? { declared_evidence_delegation: chunk.declared_evidence_delegation } : {}),
708
- ...(chunk.required_verification_commands ? { required_verification_commands: chunk.required_verification_commands } : {}),
709
- ...(chunk.declared_evidence_targets ? { declared_evidence_targets: chunk.declared_evidence_targets } : {}),
710
- ...(chunk.evidence_roots ? { evidence_roots: chunk.evidence_roots } : {}),
711
- ...(chunk.declared_evidence_unresolved ? { declared_evidence_unresolved: chunk.declared_evidence_unresolved } : {}),
712
- ...(chunk.evidence_inventory ? { evidence_inventory: chunk.evidence_inventory } : {}),
713
- ...(chunk.evidence_inventory_status ? { evidence_inventory_status: chunk.evidence_inventory_status } : {}),
714
- ...(chunk.evidence_inventory_empty_reason ? { evidence_inventory_empty_reason: chunk.evidence_inventory_empty_reason } : {}),
715
- ...(chunk.coverage_contract ? { coverage_contract: chunk.coverage_contract } : {}),
716
- file_count: chunk.files.length,
717
- file_hashes: Object.fromEntries(chunkInventory.map((entry) => [entry.file_ref, entry.sha256])),
718
- ...(chunk.evidence_inventory ? {
719
- evidence_file_hashes: Object.fromEntries(chunk.evidence_inventory.map((fileRef) => [fileRef, evidenceByFile.get(fileRef)?.sha256]).filter(([, hash]) => Boolean(hash))),
720
- } : {}),
721
- lifecycle: {
722
- planned_at: createdAt,
723
- dispatched_at: null,
724
- ingested_at: null,
725
- reviewed_at: null,
726
- frozen_at: null,
727
- failed_at: null,
728
- skipped_at: chunk.state === "skipped" ? createdAt : null,
729
- },
730
- evidence_ref: null,
731
- review: null,
732
- failure: null,
733
- ...(chunk.skip ? { skip: chunk.skip } : {}),
734
- finding_count: 0,
735
- created_at: createdAt,
736
- updated_at: createdAt,
737
- });
738
- }
739
-
740
- let runRef = await appendRunEvent(projectRoot, sweepId, {
741
- event_type: "plan_created",
742
- plan_ref: planRef(sweepId),
743
- inventory_hash: inventoryHash,
744
- included_files: includedInventory.length,
745
- chunk_count: chunks.length,
746
- ignored_chunk_count: ignoreResult.ignoredChunks.length,
747
- });
748
- for (const ignoredChunk of ignoreResult.ignoredChunks) {
749
- runRef = await appendRunEvent(projectRoot, sweepId, {
750
- event_type: "chunk_skipped",
751
- chunk_id: ignoredChunk.chunk_id,
752
- chunk_ref: chunkRef(sweepId, ignoredChunk.chunk_id),
753
- reason: auditIgnorePolicy.reason,
754
- ignored_by_policy: true,
755
- matches: ignoredChunk.matches,
756
- });
757
- }
758
-
759
- return {
760
- ok: true,
761
- exitCode: 0,
762
- sweepId,
763
- planRef: planRef(sweepId),
764
- chunkRefs: chunks.map((chunk) => chunkRef(sweepId, chunk.chunk_id)),
765
- chunkIds: chunks.map((chunk) => chunk.chunk_id),
766
- runLedgerRef: runRef,
767
- chunkCount: chunks.length,
768
- totalFiles: authorityInventory.length,
769
- includedFiles: includedInventory.length,
770
- excludedFiles: authorityInventory.length - includedInventory.length,
771
- ...(chunkBasis.basis === "spec" ? {
772
- evidenceFiles: evidenceInventory.length,
773
- unmappedEvidenceFiles: unmappedEvidenceFiles.length,
774
- evidenceInventoryHash,
775
- } : {}),
776
- inventoryHash,
777
- criteria,
778
- maxFilesPerChunk,
779
- auditIgnorePolicy: auditIgnorePolicy ? {
780
- ...auditIgnorePolicy,
781
- ignored_chunk_count: ignoreResult.ignoredChunks.length,
782
- } : null,
783
- riskBudgetPolicy,
784
- chunkBasis: plan.planning_basis.mode,
785
- };
786
- }
787
-
788
- export async function getPlannedChunkRefs(projectRoot, sweepId) {
789
- const loaded = await loadPlan(projectRoot, sweepId);
790
- if (!loaded.ok) {
791
- return loaded;
792
- }
793
- return {
794
- ok: true,
795
- chunkRefs: loaded.plan.chunks.map((chunk) => chunkRef(sweepId, chunk.chunk_id)),
796
- chunkIds: loaded.plan.chunks.map((chunk) => chunk.chunk_id),
797
- };
798
- }