@nimiplatform/nimi-coding 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/CHANGELOG.md +8 -80
  2. package/CONTRIBUTING.md +5 -34
  3. package/README.md +47 -350
  4. package/README.zh-CN.md +33 -287
  5. package/cli/commands/start.mjs +48 -688
  6. package/cli/commands/validate-spec-audit.mjs +1 -5
  7. package/cli/constants.mjs +9 -417
  8. package/cli/dev/run-cli-smoke.mjs +24 -0
  9. package/cli/dev/run-suite.mjs +17 -0
  10. package/cli/help.mjs +28 -145
  11. package/cli/index.mjs +5 -33
  12. package/cli/lib/blueprint-audit.mjs +5 -12
  13. package/cli/lib/bootstrap.mjs +0 -9
  14. package/cli/lib/contracts.mjs +0 -163
  15. package/cli/lib/doctor.mjs +155 -10
  16. package/cli/lib/entrypoints.mjs +63 -167
  17. package/cli/lib/internal/contracts-loaders.mjs +0 -85
  18. package/cli/lib/internal/contracts-parse.mjs +84 -520
  19. package/cli/lib/internal/governance/ai/check-agents-freshness.mjs +13 -8
  20. package/cli/lib/internal/surface-taxonomy-validators.mjs +316 -66
  21. package/cli/lib/internal/validators-shared.mjs +0 -16
  22. package/cli/lib/internal/validators-spec-helpers.mjs +7 -140
  23. package/cli/lib/internal/validators-spec.mjs +103 -342
  24. package/cli/lib/shared.mjs +1 -42
  25. package/cli/lib/validators.mjs +0 -48
  26. package/cli/seeds/seed-policy.yaml +0 -3
  27. package/config/bootstrap.yaml +4 -4
  28. package/config/spec-generation-inputs.yaml +6 -12
  29. package/contracts/domain-admission.schema.yaml +3 -3
  30. package/contracts/migration-inventory.schema.yaml +12 -75
  31. package/contracts/negative-fixtures.yaml +19 -99
  32. package/contracts/placement-contract.schema.yaml +49 -78
  33. package/contracts/projection-edge.schema.yaml +37 -121
  34. package/contracts/shared-enums.yaml +4 -8
  35. package/contracts/spec-generation-inputs.schema.yaml +15 -112
  36. package/contracts/spec-layout.schema.yaml +32 -0
  37. package/contracts/surface-taxonomy.schema.yaml +43 -94
  38. package/contracts/table-family.schema.yaml +1 -1
  39. package/contracts/tracked-output-admission.schema.yaml +13 -66
  40. package/methodology/core.yaml +33 -25
  41. package/methodology/four-closure-policy.yaml +18 -26
  42. package/methodology/role-separation-policy.yaml +21 -27
  43. package/methodology/spec-reconstruction.yaml +17 -34
  44. package/package.json +4 -6
  45. package/spec/_meta/spec-tree-model.yaml +5 -101
  46. package/spec/product-scope.yaml +25 -57
  47. package/adapters/README.md +0 -25
  48. package/adapters/claude/README.md +0 -89
  49. package/adapters/claude/profile.yaml +0 -70
  50. package/adapters/codex/README.md +0 -53
  51. package/adapters/codex/profile.yaml +0 -78
  52. package/adapters/oh-my-codex/README.md +0 -184
  53. package/adapters/oh-my-codex/profile.yaml +0 -46
  54. package/cli/commands/admit-high-risk-decision.mjs +0 -108
  55. package/cli/commands/audit-sweep.mjs +0 -364
  56. package/cli/commands/closeout.mjs +0 -186
  57. package/cli/commands/decide-high-risk-execution.mjs +0 -124
  58. package/cli/commands/handoff.mjs +0 -123
  59. package/cli/commands/ingest-high-risk-execution.mjs +0 -95
  60. package/cli/commands/review-high-risk-execution.mjs +0 -95
  61. package/cli/commands/sweep-design.mjs +0 -295
  62. package/cli/commands/sweep.mjs +0 -22
  63. package/cli/commands/topic-formatters.mjs +0 -382
  64. package/cli/commands/topic-goal.mjs +0 -33
  65. package/cli/commands/topic-options-shared.mjs +0 -27
  66. package/cli/commands/topic-options-workflow.mjs +0 -767
  67. package/cli/commands/topic-options.mjs +0 -626
  68. package/cli/commands/topic-runner.mjs +0 -169
  69. package/cli/commands/topic.mjs +0 -795
  70. package/cli/commands/validate-acceptance.mjs +0 -5
  71. package/cli/commands/validate-execution-packet.mjs +0 -5
  72. package/cli/commands/validate-orchestration-state.mjs +0 -5
  73. package/cli/commands/validate-prompt.mjs +0 -5
  74. package/cli/commands/validate-worker-output.mjs +0 -5
  75. package/cli/lib/adapter-profiles.mjs +0 -403
  76. package/cli/lib/audit-execution.mjs +0 -52
  77. package/cli/lib/audit-sweep-runtime/admissions.mjs +0 -508
  78. package/cli/lib/audit-sweep-runtime/audit-validity.mjs +0 -356
  79. package/cli/lib/audit-sweep-runtime/chunks.mjs +0 -697
  80. package/cli/lib/audit-sweep-runtime/claude-auditor.mjs +0 -647
  81. package/cli/lib/audit-sweep-runtime/closeout.mjs +0 -144
  82. package/cli/lib/audit-sweep-runtime/codex-auditor-evidence.mjs +0 -654
  83. package/cli/lib/audit-sweep-runtime/codex-auditor.mjs +0 -516
  84. package/cli/lib/audit-sweep-runtime/common.mjs +0 -341
  85. package/cli/lib/audit-sweep-runtime/coverage-quality.mjs +0 -172
  86. package/cli/lib/audit-sweep-runtime/evidence-assignment.mjs +0 -155
  87. package/cli/lib/audit-sweep-runtime/format.mjs +0 -57
  88. package/cli/lib/audit-sweep-runtime/ingest.mjs +0 -486
  89. package/cli/lib/audit-sweep-runtime/inventory-spec-chunks.mjs +0 -425
  90. package/cli/lib/audit-sweep-runtime/inventory.mjs +0 -798
  91. package/cli/lib/audit-sweep-runtime/ledger.mjs +0 -315
  92. package/cli/lib/audit-sweep-runtime/p0p1-profile.mjs +0 -101
  93. package/cli/lib/audit-sweep-runtime/remediation.mjs +0 -349
  94. package/cli/lib/audit-sweep-runtime/rerun.mjs +0 -129
  95. package/cli/lib/audit-sweep-runtime/risk-budget.mjs +0 -300
  96. package/cli/lib/audit-sweep-runtime/status.mjs +0 -62
  97. package/cli/lib/audit-sweep-runtime/validators-ledger.mjs +0 -215
  98. package/cli/lib/audit-sweep-runtime/validators.mjs +0 -797
  99. package/cli/lib/audit-sweep.mjs +0 -19
  100. package/cli/lib/authority-convergence.mjs +0 -704
  101. package/cli/lib/closeout.mjs +0 -732
  102. package/cli/lib/codex-sdk-runner.mjs +0 -76
  103. package/cli/lib/external-execution.mjs +0 -101
  104. package/cli/lib/handoff.mjs +0 -812
  105. package/cli/lib/high-risk-admission.mjs +0 -512
  106. package/cli/lib/high-risk-decision.mjs +0 -353
  107. package/cli/lib/high-risk-ingest.mjs +0 -321
  108. package/cli/lib/high-risk-review.mjs +0 -267
  109. package/cli/lib/internal/contracts-parse-high-risk.mjs +0 -131
  110. package/cli/lib/internal/contracts-validators.mjs +0 -399
  111. package/cli/lib/internal/doctor-bootstrap-surface.mjs +0 -406
  112. package/cli/lib/internal/doctor-delegated-surface.mjs +0 -256
  113. package/cli/lib/internal/doctor-finalize.mjs +0 -383
  114. package/cli/lib/internal/doctor-format.mjs +0 -286
  115. package/cli/lib/internal/doctor-inspectors.mjs +0 -327
  116. package/cli/lib/internal/doctor-state.mjs +0 -205
  117. package/cli/lib/internal/validators-artifacts.mjs +0 -515
  118. package/cli/lib/sweep-design-runtime/common.mjs +0 -246
  119. package/cli/lib/sweep-design-runtime/engine.mjs +0 -733
  120. package/cli/lib/sweep-design-runtime/fix-topic.mjs +0 -414
  121. package/cli/lib/sweep-design-runtime/lifecycle.mjs +0 -54
  122. package/cli/lib/sweep-design-runtime/results.mjs +0 -324
  123. package/cli/lib/sweep-design.mjs +0 -8
  124. package/cli/lib/topic-artifacts.mjs +0 -186
  125. package/cli/lib/topic-authority-coverage.mjs +0 -73
  126. package/cli/lib/topic-closeout.mjs +0 -560
  127. package/cli/lib/topic-common.mjs +0 -404
  128. package/cli/lib/topic-decisions.mjs +0 -332
  129. package/cli/lib/topic-draft-packets.mjs +0 -167
  130. package/cli/lib/topic-execution.mjs +0 -515
  131. package/cli/lib/topic-goal.mjs +0 -440
  132. package/cli/lib/topic-ledger.mjs +0 -281
  133. package/cli/lib/topic-lifecycle-artifacts.mjs +0 -173
  134. package/cli/lib/topic-root-validation.mjs +0 -288
  135. package/cli/lib/topic-runner-commands.mjs +0 -174
  136. package/cli/lib/topic-runner-deferral.mjs +0 -532
  137. package/cli/lib/topic-runner-stale-gates.mjs +0 -114
  138. package/cli/lib/topic-runner-validation.mjs +0 -138
  139. package/cli/lib/topic-runner.mjs +0 -727
  140. package/cli/lib/topic-scaffold.mjs +0 -252
  141. package/cli/lib/topic-waves.mjs +0 -403
  142. package/cli/lib/topic.mjs +0 -81
  143. package/config/audit-execution-artifacts.yaml +0 -20
  144. package/config/external-execution-artifacts.yaml +0 -16
  145. package/config/host-adapter.yaml +0 -30
  146. package/config/host-profile.yaml +0 -29
  147. package/config/installer-evidence.yaml +0 -31
  148. package/config/skill-installer.yaml +0 -23
  149. package/config/skill-manifest.yaml +0 -48
  150. package/config/skills.yaml +0 -30
  151. package/contracts/acceptance.schema.yaml +0 -16
  152. package/contracts/admission-checklist.schema.yaml +0 -15
  153. package/contracts/audit-chunk.schema.yaml +0 -123
  154. package/contracts/audit-closeout.schema.yaml +0 -51
  155. package/contracts/audit-finding.schema.yaml +0 -61
  156. package/contracts/audit-ledger.schema.yaml +0 -138
  157. package/contracts/audit-plan.schema.yaml +0 -138
  158. package/contracts/audit-remediation-map.schema.yaml +0 -52
  159. package/contracts/audit-rerun.schema.yaml +0 -31
  160. package/contracts/audit-sweep-result.yaml +0 -53
  161. package/contracts/authority-convergence-audit.schema.yaml +0 -19
  162. package/contracts/closeout.schema.yaml +0 -25
  163. package/contracts/decision-review.schema.yaml +0 -16
  164. package/contracts/doc-spec-audit-result.yaml +0 -19
  165. package/contracts/execution-packet.schema.yaml +0 -49
  166. package/contracts/external-host-compatibility.yaml +0 -22
  167. package/contracts/forbidden-shortcuts.catalog.yaml +0 -23
  168. package/contracts/high-risk-admission.schema.yaml +0 -23
  169. package/contracts/high-risk-execution-result.yaml +0 -20
  170. package/contracts/orchestration-state.schema.yaml +0 -41
  171. package/contracts/overflow-continuation.schema.yaml +0 -12
  172. package/contracts/packet.schema.yaml +0 -30
  173. package/contracts/pending-note.schema.yaml +0 -17
  174. package/contracts/prompt.schema.yaml +0 -12
  175. package/contracts/remediation.schema.yaml +0 -16
  176. package/contracts/result.schema.yaml +0 -24
  177. package/contracts/spec-reconstruction-result.yaml +0 -41
  178. package/contracts/sweep-design-result.yaml +0 -349
  179. package/contracts/topic-goal.schema.yaml +0 -87
  180. package/contracts/topic-run-ledger.schema.yaml +0 -72
  181. package/contracts/topic-step-decision.schema.yaml +0 -45
  182. package/contracts/topic.schema.yaml +0 -65
  183. package/contracts/true-close.schema.yaml +0 -15
  184. package/contracts/wave.schema.yaml +0 -29
  185. package/contracts/worker-output.schema.yaml +0 -15
  186. package/contracts/workflow-consumer.schema.yaml +0 -110
  187. package/methodology/audit-sweep-p0p1-recall.yaml +0 -45
  188. package/methodology/authority-convergence-policy.yaml +0 -42
  189. package/methodology/overflow-continuation-policy.yaml +0 -14
  190. package/methodology/skill-exchange-projection.yaml +0 -114
  191. package/methodology/skill-handoff.yaml +0 -34
  192. package/methodology/skill-installer-result.yaml +0 -27
  193. package/methodology/skill-installer-summary-projection.yaml +0 -181
  194. package/methodology/skill-runtime.yaml +0 -23
  195. package/methodology/spec-target-truth-profile.yaml +0 -46
  196. package/methodology/topic-lifecycle-report.yaml +0 -144
  197. package/methodology/topic-lifecycle.yaml +0 -37
  198. package/methodology/topic-naming-ontology.yaml +0 -21
  199. package/methodology/topic-ontology.yaml +0 -38
  200. package/methodology/topic-validation-policy.yaml +0 -9
  201. package/methodology/wave-dag-policy.yaml +0 -14
  202. package/spec/_meta/command-gating-matrix.yaml +0 -143
  203. package/spec/_meta/generate-drift-migration-checklist.yaml +0 -137
  204. package/spec/_meta/governance-routing-cutover-checklist.yaml +0 -35
  205. package/spec/_meta/phase2-impacted-surface-matrix.yaml +0 -44
  206. package/spec/_meta/spec-authority-cutover-readiness.yaml +0 -102
  207. package/spec/bootstrap-state.yaml +0 -99
@@ -1,341 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { appendFile, mkdir, open, readFile, rm, writeFile } from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- import YAML from "yaml";
6
-
7
- import { AUDIT_SWEEP_ARTIFACT_ROOTS } from "../../constants.mjs";
8
- import { pathExists } from "../fs-helpers.mjs";
9
- import { loadYamlFile } from "../yaml-helpers.mjs";
10
- import { isIsoUtcTimestamp, isPlainObject } from "../value-helpers.mjs";
11
-
12
- export const DEFAULT_MAX_FILES_PER_CHUNK = 60;
13
- export const DEFAULT_CRITERIA = ["quality"];
14
- export const AUDITABLE_EXTENSIONS = new Set([
15
- ".cjs",
16
- ".css",
17
- ".go",
18
- ".js",
19
- ".jsx",
20
- ".json",
21
- ".md",
22
- ".mjs",
23
- ".prisma",
24
- ".proto",
25
- ".py",
26
- ".rs",
27
- ".ts",
28
- ".tsx",
29
- ".yaml",
30
- ".yml",
31
- ]);
32
- export const DEFAULT_EXCLUDE_PATTERNS = [
33
- ".git/",
34
- ".agents/",
35
- ".claude/",
36
- ".iterate/",
37
- ".next/",
38
- ".nimi/local/",
39
- ".openclaw/",
40
- ".turbo/",
41
- "AGENTS.md",
42
- "archive/",
43
- "dist/",
44
- "docs/_archive/",
45
- "generated/",
46
- "node_modules/",
47
- "README.md",
48
- "**/AGENTS.md",
49
- "**/README.md",
50
- "_archive/",
51
- "**/_archive/**",
52
- "pnpm-lock.yaml",
53
- "package-lock.json",
54
- "yarn.lock",
55
- ];
56
- export const FINDING_SEVERITY = new Set(["critical", "high", "medium", "low"]);
57
- export const FINDING_ACTIONABILITY = new Set(["auto-fix", "needs-decision", "deferred-backlog"]);
58
- export const FINDING_CONFIDENCE = new Set(["high", "medium", "low"]);
59
- export const FINDING_DISPOSITION = new Set(["open", "remediated", "accepted-risk", "false-positive", "deferred-backlog"]);
60
- export const RERUN_VERDICT = new Set(["not_reproduced", "still_reproduced", "manager_accepted", "deferred"]);
61
- export const CHUNK_STATES = new Set(["planned", "dispatched", "ingested", "reviewed", "frozen", "failed", "skipped"]);
62
- export const ACTIVE_CHUNK_STATES = new Set(["planned", "dispatched", "ingested", "reviewed"]);
63
- export const SEVERITY_RANK = {
64
- critical: 0,
65
- high: 1,
66
- medium: 2,
67
- low: 3,
68
- };
69
-
70
- export function nowIso() {
71
- return new Date().toISOString();
72
- }
73
-
74
- export function toPosix(filePath) {
75
- return filePath.split(path.sep).join(path.posix.sep);
76
- }
77
-
78
- export function stableJson(value) {
79
- if (Array.isArray(value)) {
80
- return `[${value.map(stableJson).join(",")}]`;
81
- }
82
-
83
- if (isPlainObject(value)) {
84
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
85
- }
86
-
87
- return JSON.stringify(value);
88
- }
89
-
90
- export function sha256Text(text) {
91
- return createHash("sha256").update(text).digest("hex");
92
- }
93
-
94
- export function sha256Object(value) {
95
- return sha256Text(stableJson(value));
96
- }
97
-
98
- export function relPath(projectRoot, absolutePath) {
99
- return toPosix(path.relative(projectRoot, absolutePath));
100
- }
101
-
102
- export function isPathInside(parent, child) {
103
- const relative = path.relative(parent, child);
104
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
105
- }
106
-
107
- export function resolveInsideProject(projectRoot, inputPath, label) {
108
- const absolutePath = path.resolve(projectRoot, inputPath);
109
- if (!isPathInside(projectRoot, absolutePath)) {
110
- return {
111
- ok: false,
112
- error: `nimicoding sweep audit refused: ${label} must stay inside the project root.\n`,
113
- };
114
- }
115
-
116
- return {
117
- ok: true,
118
- absolutePath,
119
- ref: relPath(projectRoot, absolutePath),
120
- };
121
- }
122
-
123
- export function normalizeCsv(value, fallback = []) {
124
- if (!value) {
125
- return [...fallback];
126
- }
127
-
128
- return String(value)
129
- .split(",")
130
- .map((entry) => entry.trim())
131
- .filter(Boolean);
132
- }
133
-
134
- export function safeSweepId(value) {
135
- if (typeof value !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{2,120}$/.test(value)) {
136
- return null;
137
- }
138
-
139
- return value;
140
- }
141
-
142
- export function deriveSweepId(targetRootRef, date = new Date()) {
143
- const day = date.toISOString().slice(0, 10);
144
- const slug = targetRootRef
145
- .replace(/[^a-zA-Z0-9]+/g, "-")
146
- .replace(/^-+|-+$/g, "")
147
- .toLowerCase() || "project";
148
- return `audit-sweep-${day}-${slug}`;
149
- }
150
-
151
- export function artifactRef(kind, ...parts) {
152
- return path.posix.join(AUDIT_SWEEP_ARTIFACT_ROOTS[kind], ...parts);
153
- }
154
-
155
- export function artifactPath(projectRoot, ref) {
156
- return path.join(projectRoot, ...ref.split("/"));
157
- }
158
-
159
- export async function writeYamlRef(projectRoot, ref, value) {
160
- const destination = artifactPath(projectRoot, ref);
161
- await mkdir(path.dirname(destination), { recursive: true });
162
- await writeFile(destination, YAML.stringify(value, { aliasDuplicateObjects: false }), "utf8");
163
- }
164
-
165
- export async function writeJsonRef(projectRoot, ref, value) {
166
- const destination = artifactPath(projectRoot, ref);
167
- await mkdir(path.dirname(destination), { recursive: true });
168
- await writeFile(destination, `${JSON.stringify(value, null, 2)}\n`, "utf8");
169
- }
170
-
171
- function auditSweepLockPath(projectRoot, sweepId) {
172
- return path.join(projectRoot, ".nimi", "local", "audit", "locks", `${sweepId}.lock`);
173
- }
174
-
175
- export async function withAuditSweepMutationLock(projectRoot, sweepId, label, fn) {
176
- const lockPath = auditSweepLockPath(projectRoot, sweepId);
177
- await mkdir(path.dirname(lockPath), { recursive: true });
178
- let handle = null;
179
- try {
180
- handle = await open(lockPath, "wx");
181
- } catch (error) {
182
- if (error?.code === "EEXIST") {
183
- return inputError(`nimicoding sweep audit refused: ${label} mutation already in progress for ${sweepId}; retry after the current command finishes.\n`);
184
- }
185
- throw error;
186
- }
187
-
188
- try {
189
- await handle.writeFile(`${JSON.stringify({
190
- sweep_id: sweepId,
191
- label,
192
- pid: process.pid,
193
- locked_at: nowIso(),
194
- })}\n`, "utf8");
195
- await handle.close();
196
- handle = null;
197
- return await fn();
198
- } finally {
199
- if (handle) {
200
- await handle.close();
201
- }
202
- await rm(lockPath, { force: true });
203
- }
204
- }
205
-
206
- export async function loadYamlRef(projectRoot, ref) {
207
- return loadYamlFile(artifactPath(projectRoot, ref));
208
- }
209
-
210
- export async function loadJsonFile(filePath) {
211
- try {
212
- return { ok: true, value: JSON.parse(await readFile(filePath, "utf8")) };
213
- } catch {
214
- return { ok: false, error: "must contain valid JSON" };
215
- }
216
- }
217
-
218
- export async function assertExistingFile(filePath, message) {
219
- const info = await pathExists(filePath);
220
- if (!info || !info.isFile()) {
221
- return { ok: false, error: message };
222
- }
223
- return { ok: true };
224
- }
225
-
226
- export function planRef(sweepId) {
227
- return artifactRef("plan_ref", `${sweepId}.yaml`);
228
- }
229
-
230
- export function chunkRef(sweepId, chunkId) {
231
- return artifactRef("chunk_refs", sweepId, `${chunkId}.yaml`);
232
- }
233
-
234
- export function findingsRef(sweepId) {
235
- return artifactRef("evidence_refs", sweepId, "findings.yaml");
236
- }
237
-
238
- export function runLedgerRef(sweepId) {
239
- return artifactRef("run_ledger_ref", `${sweepId}.jsonl`);
240
- }
241
-
242
- export function reportRef(sweepId, snapshotId) {
243
- return artifactRef("report_ref", sweepId, `${snapshotId}.md`);
244
- }
245
-
246
- export function ledgerRef(sweepId, snapshotId) {
247
- return artifactRef("ledger_ref", sweepId, `${snapshotId}.yaml`);
248
- }
249
-
250
- export function remediationMapRef(sweepId, snapshotId) {
251
- return artifactRef("remediation_map_ref", sweepId, `${snapshotId}.yaml`);
252
- }
253
-
254
- export function auditCloseoutRef(sweepId, snapshotId) {
255
- return artifactRef("audit_closeout_ref", sweepId, `${snapshotId}.yaml`);
256
- }
257
-
258
- export function packetRef(sweepId, chunkId) {
259
- return artifactRef("packet_ref", sweepId, `${chunkId}.auditor-packet.yaml`);
260
- }
261
-
262
- export async function appendRunEvent(projectRoot, sweepId, event) {
263
- const ref = runLedgerRef(sweepId);
264
- const destination = artifactPath(projectRoot, ref);
265
- await mkdir(path.dirname(destination), { recursive: true });
266
- await appendFile(destination, `${JSON.stringify({
267
- event_id: sha256Object({ sweepId, event, ordinal_hint: Date.now() }).slice(0, 16),
268
- sweep_id: sweepId,
269
- recorded_at: nowIso(),
270
- ...event,
271
- })}\n`, "utf8");
272
- return ref;
273
- }
274
-
275
- export async function loadPlan(projectRoot, sweepId) {
276
- const ref = planRef(sweepId);
277
- const plan = await loadYamlRef(projectRoot, ref);
278
- if (!isPlainObject(plan) || plan.kind !== "audit-plan" || plan.sweep_id !== sweepId) {
279
- return { ok: false, error: `nimicoding sweep audit refused: plan not found for ${sweepId}.\n` };
280
- }
281
- return { ok: true, plan, planRef: ref };
282
- }
283
-
284
- export async function loadChunk(projectRoot, sweepId, chunkId) {
285
- const ref = chunkRef(sweepId, chunkId);
286
- const chunk = await loadYamlRef(projectRoot, ref);
287
- if (!isPlainObject(chunk) || chunk.kind !== "audit-chunk" || chunk.sweep_id !== sweepId || chunk.chunk_id !== chunkId) {
288
- return { ok: false, error: `nimicoding sweep audit refused: chunk not found for ${sweepId}/${chunkId}.\n` };
289
- }
290
- return { ok: true, chunk, chunkRef: ref };
291
- }
292
-
293
- export async function loadFindings(projectRoot, sweepId) {
294
- const ref = findingsRef(sweepId);
295
- const existing = await loadYamlRef(projectRoot, ref);
296
- if (isPlainObject(existing) && existing.kind === "audit-findings" && existing.sweep_id === sweepId && Array.isArray(existing.findings)) {
297
- return { findingsRef: ref, store: existing };
298
- }
299
-
300
- return {
301
- findingsRef: ref,
302
- store: {
303
- version: 1,
304
- kind: "audit-findings",
305
- sweep_id: sweepId,
306
- findings: [],
307
- duplicate_count: 0,
308
- clusters: [],
309
- clustered_symptom_count: 0,
310
- accepted_cluster_skip_count: 0,
311
- remediation_obligation_count: 0,
312
- updated_at: nowIso(),
313
- },
314
- };
315
- }
316
-
317
- export async function loadLatestLedger(projectRoot, sweepId) {
318
- const latestRef = artifactRef("ledger_ref", sweepId, "latest.yaml");
319
- const pointer = await loadYamlRef(projectRoot, latestRef);
320
- if (!isPlainObject(pointer) || typeof pointer.ledger_ref !== "string") {
321
- return { ok: false, error: `nimicoding sweep audit refused: latest ledger not found for ${sweepId}.\n` };
322
- }
323
-
324
- const ledger = await loadYamlRef(projectRoot, pointer.ledger_ref);
325
- if (!isPlainObject(ledger) || ledger.kind !== "audit-ledger" || ledger.sweep_id !== sweepId) {
326
- return { ok: false, error: `nimicoding sweep audit refused: latest ledger is malformed for ${sweepId}.\n` };
327
- }
328
-
329
- return { ok: true, ledger, ledgerRef: pointer.ledger_ref, pointerRef: latestRef };
330
- }
331
-
332
- export function inputError(error) {
333
- return { ok: false, inputError: true, exitCode: 2, error };
334
- }
335
-
336
- export function ensureIsoTimestamp(value, label = "--verified-at") {
337
- if (!isIsoUtcTimestamp(value)) {
338
- return inputError(`nimicoding sweep audit refused: ${label} must be an ISO-8601 UTC timestamp.\n`);
339
- }
340
- return null;
341
- }
@@ -1,172 +0,0 @@
1
- export const COVERAGE_SCOPE_LABEL = "declared_authority_and_evidence_inventory";
2
- export const FILE_INVENTORY_SCOPE_LABEL = "file_inventory";
3
-
4
- function makeDiagnostic(id, message, details = {}) {
5
- return { id, message, ...details };
6
- }
7
-
8
- function ownerDomainCoverage(chunks) {
9
- const byOwner = {};
10
- for (const chunk of chunks) {
11
- const ownerDomain = chunk.owner_domain ?? "unknown";
12
- const evidenceCount = Array.isArray(chunk.evidence_inventory) ? chunk.evidence_inventory.length : 0;
13
- const entry = byOwner[ownerDomain] ?? {
14
- authority_chunks: 0,
15
- chunks_with_evidence_inventory: 0,
16
- chunks_without_evidence_inventory: 0,
17
- evidence_file_refs: new Set(),
18
- posture: "strong",
19
- };
20
- entry.authority_chunks += 1;
21
- for (const fileRef of Array.isArray(chunk.evidence_inventory) ? chunk.evidence_inventory : []) {
22
- entry.evidence_file_refs.add(fileRef);
23
- }
24
- if (evidenceCount > 0) {
25
- entry.chunks_with_evidence_inventory += 1;
26
- } else {
27
- entry.chunks_without_evidence_inventory += 1;
28
- }
29
- byOwner[ownerDomain] = entry;
30
- }
31
- for (const entry of Object.values(byOwner)) {
32
- entry.evidence_files = entry.evidence_file_refs.size;
33
- delete entry.evidence_file_refs;
34
- entry.posture = entry.authority_chunks > 0 && entry.evidence_files === 0 ? "warning" : "strong";
35
- }
36
- return byOwner;
37
- }
38
-
39
- export function buildCoverageQuality(plan, chunks, coverage = plan.coverage ?? {}) {
40
- if (plan?.planning_basis?.mode !== "spec_authority") {
41
- return {
42
- scope_label: FILE_INVENTORY_SCOPE_LABEL,
43
- posture: "strong",
44
- authority_chunk_count: chunks.length,
45
- chunks_with_evidence_inventory: 0,
46
- chunks_without_evidence_inventory: 0,
47
- empty_evidence_chunk_ratio: 0,
48
- evidence_file_count: 0,
49
- max_evidence_files_per_chunk: 0,
50
- max_evidence_chunk_id: null,
51
- evidence_concentration_ratio: 0,
52
- owner_domain_coverage: ownerDomainCoverage(chunks),
53
- warnings: [],
54
- blockers: [],
55
- };
56
- }
57
-
58
- const authorityChunkCount = chunks.length;
59
- const evidenceCounts = chunks.map((chunk) => Array.isArray(chunk.evidence_inventory) ? chunk.evidence_inventory.length : 0);
60
- const chunksWithEvidenceInventory = evidenceCounts.filter((count) => count > 0).length;
61
- const chunksWithoutEvidenceInventory = authorityChunkCount - chunksWithEvidenceInventory;
62
- const evidenceFileCount = coverage.evidence_coverage?.total_files
63
- ?? coverage.evidence_files
64
- ?? plan.evidence_inventory?.length
65
- ?? 0;
66
- const maxEvidenceFilesPerChunk = evidenceCounts.length > 0 ? Math.max(...evidenceCounts) : 0;
67
- const maxEvidenceChunkIndex = evidenceCounts.findIndex((count) => count === maxEvidenceFilesPerChunk);
68
- const maxEvidenceChunkId = maxEvidenceChunkIndex >= 0 ? chunks[maxEvidenceChunkIndex]?.chunk_id ?? null : null;
69
- const evidenceConcentrationRatio = evidenceFileCount > 0 ? maxEvidenceFilesPerChunk / evidenceFileCount : 0;
70
- const emptyEvidenceChunkRatio = authorityChunkCount > 0 ? chunksWithoutEvidenceInventory / authorityChunkCount : 0;
71
- const ownerCoverage = ownerDomainCoverage(chunks);
72
- const warnings = [];
73
- const blockers = [];
74
-
75
- if (chunksWithoutEvidenceInventory > 0) {
76
- warnings.push(makeDiagnostic("sparse_evidence_inventory", "Some authority chunks have no mapped evidence inventory.", {
77
- chunks_without_evidence_inventory: chunksWithoutEvidenceInventory,
78
- authority_chunk_count: authorityChunkCount,
79
- }));
80
- }
81
-
82
- for (const [owner_domain, entry] of Object.entries(ownerCoverage)) {
83
- if (entry.authority_chunks > 0 && entry.evidence_files === 0) {
84
- warnings.push(makeDiagnostic("owner_domain_authority_only", "Owner domain has authority chunks but no mapped evidence files.", {
85
- owner_domain,
86
- authority_chunks: entry.authority_chunks,
87
- }));
88
- }
89
- }
90
-
91
- if (evidenceFileCount > 0 && evidenceConcentrationRatio >= 0.5 && chunksWithEvidenceInventory > 1) {
92
- warnings.push(makeDiagnostic("evidence_fan_in_concentrated", "One chunk owns a concentrated share of the mapped evidence inventory.", {
93
- chunk_id: maxEvidenceChunkId,
94
- evidence_concentration_ratio: evidenceConcentrationRatio,
95
- }));
96
- }
97
-
98
- const unresolvedChunks = chunks
99
- .filter((chunk) => Array.isArray(chunk.declared_evidence_unresolved) && chunk.declared_evidence_unresolved.length > 0)
100
- .map((chunk) => chunk.chunk_id);
101
- if (unresolvedChunks.length > 0) {
102
- blockers.push(makeDiagnostic("declared_evidence_target_unresolved", "Declared evidence targets remain unresolved.", {
103
- chunk_ids: unresolvedChunks,
104
- }));
105
- }
106
-
107
- const unmappedEvidenceFiles = coverage.evidence_coverage?.unmapped_files
108
- ?? coverage.unmapped_evidence_files
109
- ?? plan.unmapped_evidence_files?.length
110
- ?? 0;
111
- if (unmappedEvidenceFiles > 0) {
112
- blockers.push(makeDiagnostic("unmapped_evidence_files", "Evidence inventory contains files that no authority chunk can accept.", {
113
- unmapped_evidence_files: unmappedEvidenceFiles,
114
- }));
115
- }
116
-
117
- return {
118
- scope_label: COVERAGE_SCOPE_LABEL,
119
- posture: blockers.length > 0 ? "blocked" : warnings.length > 0 ? "warning" : "strong",
120
- authority_chunk_count: authorityChunkCount,
121
- chunks_with_evidence_inventory: chunksWithEvidenceInventory,
122
- chunks_without_evidence_inventory: chunksWithoutEvidenceInventory,
123
- empty_evidence_chunk_ratio: emptyEvidenceChunkRatio,
124
- evidence_file_count: evidenceFileCount,
125
- max_evidence_files_per_chunk: maxEvidenceFilesPerChunk,
126
- max_evidence_chunk_id: maxEvidenceChunkId,
127
- evidence_concentration_ratio: evidenceConcentrationRatio,
128
- owner_domain_coverage: ownerCoverage,
129
- warnings,
130
- blockers,
131
- };
132
- }
133
-
134
- export function withFullScopeWarning(coverageQuality) {
135
- if (!coverageQuality) {
136
- return coverageQuality;
137
- }
138
- if (coverageQuality.scope_label !== COVERAGE_SCOPE_LABEL) {
139
- return coverageQuality;
140
- }
141
- if (coverageQuality.warnings?.some((warning) => warning.id === "full_status_scope_is_declared_inventory")) {
142
- return coverageQuality;
143
- }
144
- return {
145
- ...coverageQuality,
146
- posture: coverageQuality.posture === "strong" ? "warning" : coverageQuality.posture,
147
- warnings: [
148
- ...(coverageQuality.warnings ?? []),
149
- makeDiagnostic("full_status_scope_is_declared_inventory", "Full spec-authority coverage is scoped to declared authority and admitted evidence inventory."),
150
- ],
151
- };
152
- }
153
-
154
- export function deriveCoverageStatus(ledgerStatus) {
155
- if (ledgerStatus === "candidate_ready") {
156
- return "full";
157
- }
158
- if (ledgerStatus === "blocked") {
159
- return "blocked";
160
- }
161
- return "partial";
162
- }
163
-
164
- export function deriveCoverageCloseoutPosture({ coverageStatus, openFindingCount }) {
165
- if (coverageStatus === "blocked") {
166
- return "blocked";
167
- }
168
- if (coverageStatus === "partial") {
169
- return openFindingCount > 0 ? "partial_coverage_findings_open" : "partial_coverage_all_findings_postured";
170
- }
171
- return openFindingCount > 0 ? "audit_complete_findings_open" : "audit_complete_all_findings_postured";
172
- }
@@ -1,155 +0,0 @@
1
- function chunkMatchesEvidenceFile(chunk, fileRef) {
2
- const roots = Array.isArray(chunk.admitted_evidence_roots) && chunk.admitted_evidence_roots.length > 0
3
- ? chunk.admitted_evidence_roots
4
- : chunk.evidence_roots;
5
- return Array.isArray(roots)
6
- && roots.some((rootRef) => {
7
- const normalizedRoot = rootRef.replace(/\\/g, "/").replace(/\/$/, "");
8
- return fileRef === normalizedRoot || fileRef.startsWith(`${normalizedRoot}/`);
9
- });
10
- }
11
-
12
- function normalizedRef(value) {
13
- return String(value ?? "").replace(/\\/g, "/").replace(/\/$/, "");
14
- }
15
-
16
- function refInsideRoot(fileRef, rootRef) {
17
- const normalizedRoot = normalizedRef(rootRef);
18
- return Boolean(normalizedRoot) && (fileRef === normalizedRoot || fileRef.startsWith(`${normalizedRoot}/`));
19
- }
20
-
21
- function chunkHasExactAdmittedEvidenceRef(chunk, fileRef) {
22
- return Array.isArray(chunk.evidence_root_admission_refs)
23
- && Array.isArray(chunk.admitted_evidence_roots)
24
- && chunk.admitted_evidence_roots.some((rootRef) => normalizedRef(rootRef) === fileRef);
25
- }
26
-
27
- function topLevelEvidenceDocForRoot(rootRef, fileRef) {
28
- const normalizedRoot = normalizedRef(rootRef);
29
- if (!normalizedRoot || !refInsideRoot(fileRef, normalizedRoot)) {
30
- return false;
31
- }
32
- const relative = fileRef === normalizedRoot ? "" : fileRef.slice(normalizedRoot.length + 1);
33
- return !relative.includes("/") && /^(README|AGENTS)(?:\.[^.]+)?$/i.test(relative);
34
- }
35
-
36
- function chunkDeclaredEvidenceRoots(chunk) {
37
- if (!Array.isArray(chunk.declared_evidence_targets)) {
38
- return [];
39
- }
40
- return chunk.declared_evidence_targets
41
- .flatMap((target) => Array.isArray(target.candidates) ? target.candidates : [])
42
- .map((candidate) => normalizedRef(candidate))
43
- .filter(Boolean);
44
- }
45
-
46
- function chunkAcceptsEvidenceFile(chunk, fileRef) {
47
- const surface = String(chunk.spec_surface ?? "");
48
- if (chunkDeclaredEvidenceRoots(chunk).some((rootRef) => refInsideRoot(fileRef, rootRef))) {
49
- return true;
50
- }
51
- const roots = Array.isArray(chunk.admitted_evidence_roots) && chunk.admitted_evidence_roots.length > 0
52
- ? chunk.admitted_evidence_roots
53
- : chunk.evidence_roots;
54
- const isTopLevelDoc = (roots ?? []).some((rootRef) => topLevelEvidenceDocForRoot(rootRef, fileRef));
55
- if (isTopLevelDoc) {
56
- return surface === "domain-guides" || surface === "app-domain-guides" || surface === "package-root" || surface === "INDEX";
57
- }
58
- if (
59
- surface === "kernel-contracts"
60
- || surface === "app-kernel-contracts"
61
- || surface === "kernel-tables"
62
- || surface === "app-kernel-tables"
63
- || surface === "package-kernel-tables"
64
- ) {
65
- return true;
66
- }
67
- if (surface === "spec-generation-audit" || surface === "high-risk-admissions" || surface === "package-meta" || surface === "package-root") {
68
- return true;
69
- }
70
- if (surface === "delegated-projection") {
71
- return true;
72
- }
73
- return false;
74
- }
75
-
76
- function unresolvedDeclaredEvidenceTargets(chunk, evidenceEntries) {
77
- if (!Array.isArray(chunk.declared_evidence_targets)) {
78
- return [];
79
- }
80
- return chunk.declared_evidence_targets
81
- .map((target) => {
82
- const candidates = Array.isArray(target.candidates)
83
- ? target.candidates.map((candidate) => normalizedRef(candidate)).filter(Boolean)
84
- : [];
85
- const resolved = candidates.some((candidate) => evidenceEntries.some((entry) => refInsideRoot(entry.file_ref, candidate)));
86
- return resolved ? null : {
87
- source_path: target.source_path,
88
- candidates,
89
- };
90
- })
91
- .filter(Boolean);
92
- }
93
-
94
- function deriveEmptyEvidenceInventoryReason(chunk) {
95
- if (chunk.spec_surface === "kernel-generated" || String(chunk.spec_surface ?? "").includes("generated")) {
96
- return "generated_projection_authority_no_direct_implementation_evidence";
97
- }
98
- if (chunk.spec_surface === "kernel-tables" || String(chunk.spec_surface ?? "").includes("tables")) {
99
- return "structured_fact_authority_no_direct_implementation_evidence";
100
- }
101
- if (chunk.spec_surface === "domain-guides" || String(chunk.spec_surface ?? "").endsWith("guides")) {
102
- return "domain_guide_authority_no_direct_implementation_evidence";
103
- }
104
- return "no_matching_evidence_files_after_spec_authority_assignment";
105
- }
106
-
107
- export function assignEvidenceInventory(evidenceEntries, chunks, options = {}) {
108
- const chunksById = new Map(chunks.map((chunk) => [chunk.chunk_id, { ...chunk, evidence_inventory: [] }]));
109
- const unmapped = [];
110
-
111
- for (const entry of evidenceEntries.sort((left, right) => left.file_ref.localeCompare(right.file_ref))) {
112
- const candidates = chunks.filter((chunk) => chunkMatchesEvidenceFile(chunk, entry.file_ref));
113
- if (candidates.length === 0) {
114
- unmapped.push(entry.file_ref);
115
- continue;
116
- }
117
- const exactAdmissionCandidates = candidates.filter((chunk) => chunkHasExactAdmittedEvidenceRef(chunk, entry.file_ref));
118
- const selectedChunks = (exactAdmissionCandidates.length > 0 ? exactAdmissionCandidates : candidates.filter((chunk) => chunkAcceptsEvidenceFile(chunk, entry.file_ref)))
119
- .sort((left, right) => left.chunk_id.localeCompare(right.chunk_id));
120
- if (selectedChunks.length === 0) {
121
- unmapped.push(entry.file_ref);
122
- continue;
123
- }
124
- for (const selected of selectedChunks) {
125
- chunksById.get(selected.chunk_id).evidence_inventory.push(entry.file_ref);
126
- }
127
- }
128
-
129
- return {
130
- chunks: chunks.map((chunk) => {
131
- const enriched = chunksById.get(chunk.chunk_id);
132
- const evidenceInventory = enriched.evidence_inventory.sort();
133
- const evidenceInventoryEmpty = evidenceInventory.length === 0;
134
- const declaredEvidenceUnresolved = unresolvedDeclaredEvidenceTargets(chunk, evidenceEntries);
135
- return {
136
- ...chunk,
137
- evidence_inventory: evidenceInventory,
138
- evidence_inventory_status: evidenceInventoryEmpty ? "empty" : "mapped",
139
- ...(declaredEvidenceUnresolved.length > 0 ? {
140
- declared_evidence_unresolved: declaredEvidenceUnresolved,
141
- } : {}),
142
- ...(evidenceInventoryEmpty ? {
143
- evidence_inventory_empty_reason: deriveEmptyEvidenceInventoryReason(chunk),
144
- } : {}),
145
- coverage_contract: {
146
- authority_refs_required: true,
147
- evidence_inventory_required: true,
148
- evidence_files_must_cover_inventory: true,
149
- empty_evidence_inventory_requires_reason: true,
150
- },
151
- };
152
- }),
153
- unmappedEvidenceFiles: unmapped.sort(),
154
- };
155
- }