@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,732 +0,0 @@
1
- import { readdir, realpath } from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import {
5
- CLOSEOUT_PAYLOAD_CONTRACT_VERSION,
6
- SKILL_RESULT_CONTRACT_REFS,
7
- } from "../constants.mjs";
8
- import {
9
- loadAuditSweepContract,
10
- loadDocSpecAuditContract,
11
- loadHighRiskExecutionContract,
12
- loadSpecReconstructionContract,
13
- validateAuditSweepSummary,
14
- validateDocSpecAuditSummary,
15
- validateHighRiskExecutionSummary,
16
- validateSpecReconstructionSummary,
17
- } from "./contracts.mjs";
18
- import { inspectDoctorState } from "./doctor.mjs";
19
- import {
20
- loadExternalExecutionArtifactsConfig,
21
- validateHighRiskExecutionArtifactRefs,
22
- } from "./external-execution.mjs";
23
- import { validateAuditSweepArtifacts } from "./audit-sweep-runtime/validators.mjs";
24
- import { readTextIfFile } from "./fs-helpers.mjs";
25
- import {
26
- localize,
27
- styleCommand,
28
- styleHeading,
29
- styleLabel,
30
- styleStatus,
31
- } from "./ui.mjs";
32
- import { isIsoUtcTimestamp, isPlainObject } from "./value-helpers.mjs";
33
- import { parseSkillSection } from "./yaml-helpers.mjs";
34
-
35
- function translateCloseoutReason(reason) {
36
- const translations = new Map([
37
- ["spec_reconstruction result contract is missing or malformed", "spec_reconstruction 结果契约缺失或格式错误"],
38
- ["doc_spec_audit result contract is missing or malformed", "doc_spec_audit 结果契约缺失或格式错误"],
39
- ["audit_sweep result contract is missing or malformed", "audit_sweep 结果契约缺失或格式错误"],
40
- ["high_risk_execution result contract is missing or malformed", "high_risk_execution 结果契约缺失或格式错误"],
41
- ["Bootstrap or handoff validation is failing; repair doctor errors before projecting closeout results", "bootstrap 或 handoff 校验失败;请先修复 doctor 报错,再投影 closeout 结果"],
42
- ["Non-completed outcomes may be projected as local-only closeout artifacts", "非 completed 的 outcome 可以仅投影为本地 closeout 产物"],
43
- ["Completed closeout is not allowed in the current lifecycle state", "当前生命周期状态不允许完成该 closeout"],
44
- ["Completed closeout requires declared canonical tree files to be valid", "完成 closeout 需要声明的 canonical tree 文件有效"],
45
- ["Completed closeout requires a valid `.nimi/local/state/spec-generation/spec-generation-audit.yaml` artifact", "完成 closeout 需要一个有效的 `.nimi/local/state/spec-generation/spec-generation-audit.yaml` 产物"],
46
- ["Completed doc_spec_audit closeout must compare against `.nimi/spec`", "完成 doc_spec_audit closeout 时必须对 `.nimi/spec` 进行比较"],
47
- ["Completed closeout is consistent with the current canonical tree state", "completed closeout 与当前 canonical tree 状态一致"],
48
- ["Imported spec_reconstruction summary must match active spec-generation audit coverage", "导入的 spec_reconstruction 摘要必须与当前 spec-generation audit 覆盖情况一致"],
49
- ]);
50
-
51
- if (translations.has(reason)) {
52
- return translations.get(reason);
53
- }
54
-
55
- const statusPrefix = " summary.status must be ";
56
- if (reason.includes(statusPrefix)) {
57
- const [skillId, suffix] = reason.split(statusPrefix);
58
- const [expectedStatus, outcomePart] = suffix.split(" when outcome is ");
59
- return `当 outcome 为 ${outcomePart} 时,${skillId} 的 summary.status 必须为 ${expectedStatus}`;
60
- }
61
-
62
- const noSummarySuffix = " does not accept summary when outcome is failed";
63
- if (reason.endsWith(noSummarySuffix)) {
64
- return `${reason.slice(0, -noSummarySuffix.length)} 在 outcome 为 failed 时不得携带 summary`;
65
- }
66
-
67
- const summaryImportPrefix = "summary import is not supported for skill ";
68
- if (reason.startsWith(summaryImportPrefix)) {
69
- return `当前不支持为该 skill 导入 summary:${reason.slice(summaryImportPrefix.length)}`;
70
- }
71
-
72
- return reason;
73
- }
74
-
75
- function inferAuditSweepIdFromSummary(summary) {
76
- if (typeof summary?.ledger_ref !== "string") {
77
- return null;
78
- }
79
- const match = summary.ledger_ref.match(/^\.nimi\/local\/audit\/ledgers\/([^/]+)\/ledger-[a-f0-9]{16}\.yaml$/);
80
- return match ? match[1] : null;
81
- }
82
-
83
- async function validateCloseoutSummaryForSkill(projectRoot, skillId, summary, verifiedAt) {
84
- if (summary === undefined) {
85
- return { ok: true };
86
- }
87
-
88
- if (skillId === "spec_reconstruction") {
89
- const contract = await loadSpecReconstructionContract(projectRoot);
90
- if (!contract.ok) {
91
- return {
92
- ok: false,
93
- reason: "spec_reconstruction result contract is missing or malformed",
94
- };
95
- }
96
-
97
- return validateSpecReconstructionSummary(summary, contract, verifiedAt);
98
- }
99
-
100
- if (skillId === "doc_spec_audit") {
101
- const contract = await loadDocSpecAuditContract(projectRoot);
102
- if (!contract.ok) {
103
- return {
104
- ok: false,
105
- reason: "doc_spec_audit result contract is missing or malformed",
106
- };
107
- }
108
-
109
- return validateDocSpecAuditSummary(summary, contract, verifiedAt);
110
- }
111
-
112
- if (skillId === "audit_sweep") {
113
- const contract = await loadAuditSweepContract(projectRoot);
114
- if (!contract.ok) {
115
- return {
116
- ok: false,
117
- reason: "audit_sweep result contract is missing or malformed",
118
- };
119
- }
120
-
121
- const summaryValidation = validateAuditSweepSummary(summary, contract, verifiedAt);
122
- if (!summaryValidation.ok) {
123
- return summaryValidation;
124
- }
125
- const sweepId = inferAuditSweepIdFromSummary(summary);
126
- if (!sweepId) {
127
- return {
128
- ok: false,
129
- reason: "audit_sweep summary.ledger_ref must identify a local audit sweep ledger",
130
- };
131
- }
132
- const artifactValidation = await validateAuditSweepArtifacts(projectRoot, { sweepId, scope: "closeout" });
133
- if (!artifactValidation.ok) {
134
- const failed = artifactValidation.checks.find((entry) => !entry.ok);
135
- return {
136
- ok: false,
137
- reason: `audit_sweep artifact validation failed: ${failed?.reason ?? "unknown failure"}`,
138
- };
139
- }
140
- return { ok: true };
141
- }
142
-
143
- if (skillId === "high_risk_execution") {
144
- const contract = await loadHighRiskExecutionContract(projectRoot);
145
- if (!contract.ok) {
146
- return {
147
- ok: false,
148
- reason: "high_risk_execution result contract is missing or malformed",
149
- };
150
- }
151
-
152
- const summaryValidation = validateHighRiskExecutionSummary(summary, contract, verifiedAt);
153
- if (!summaryValidation.ok) {
154
- return summaryValidation;
155
- }
156
-
157
- const externalExecutionArtifacts = await loadExternalExecutionArtifactsConfig(projectRoot);
158
- return validateHighRiskExecutionArtifactRefs(summary, externalExecutionArtifacts);
159
- }
160
-
161
- return {
162
- ok: false,
163
- reason: `summary import is not supported for skill ${skillId}`,
164
- };
165
- }
166
-
167
- function validateOutcomeStatusConsistency(skillId, outcome, summary) {
168
- const expectedStatusBySkillAndOutcome = {
169
- spec_reconstruction: {
170
- completed: ["reconstructed", "partial"],
171
- blocked: ["blocked"],
172
- failed: [],
173
- },
174
- doc_spec_audit: {
175
- completed: ["aligned", "drift_detected"],
176
- blocked: ["blocked"],
177
- failed: [],
178
- },
179
- audit_sweep: {
180
- completed: ["candidate_ready", "partial"],
181
- blocked: ["blocked"],
182
- failed: [],
183
- },
184
- high_risk_execution: {
185
- completed: ["candidate_ready"],
186
- blocked: ["blocked"],
187
- failed: ["failed"],
188
- },
189
- };
190
-
191
- const expectedStatuses = expectedStatusBySkillAndOutcome[skillId]?.[outcome];
192
- if (!expectedStatuses) {
193
- return { ok: true };
194
- }
195
-
196
- if (outcome === "failed") {
197
- if (summary !== undefined) {
198
- return {
199
- ok: false,
200
- reason: `${skillId} does not accept summary when outcome is failed`,
201
- };
202
- }
203
- return { ok: true };
204
- }
205
-
206
- if (summary === undefined) {
207
- return { ok: true };
208
- }
209
-
210
- if (!expectedStatuses.includes(summary.status)) {
211
- return {
212
- ok: false,
213
- reason: `${skillId} summary.status must be ${expectedStatuses.join("|")} when outcome is ${outcome}`,
214
- };
215
- }
216
-
217
- return { ok: true };
218
- }
219
-
220
- async function collectSpecPaths(rootPath, relativePrefix) {
221
- let entries;
222
- try {
223
- entries = await readdir(rootPath, { withFileTypes: true });
224
- } catch {
225
- return [];
226
- }
227
-
228
- const files = [];
229
- for (const entry of entries) {
230
- const absolutePath = path.join(rootPath, entry.name);
231
- const relativePath = path.posix.join(relativePrefix, entry.name);
232
- if (entry.isDirectory()) {
233
- files.push(...await collectSpecPaths(absolutePath, relativePath));
234
- } else if (entry.isFile()) {
235
- files.push(relativePath);
236
- }
237
- }
238
-
239
- return files.sort();
240
- }
241
-
242
- async function synthesizeSpecReconstructionSummary(projectRoot, doctorResult, verifiedAt) {
243
- const generatedPaths = await collectSpecPaths(path.join(projectRoot, ".nimi", "spec"), ".nimi/spec");
244
- const auditSummary = doctorResult.specGenerationAudit?.summary ?? {};
245
- const unresolvedFileCount = Number.isInteger(auditSummary.unresolvedFiles) ? auditSummary.unresolvedFiles : 0;
246
- const inferredFileCount = Number.isInteger(auditSummary.inferredFiles) ? auditSummary.inferredFiles : 0;
247
- const placeholderFiles = Number.isInteger(auditSummary.placeholderFiles) ? auditSummary.placeholderFiles : 0;
248
- const partialFiles = Number.isInteger(auditSummary.partialFiles) ? auditSummary.partialFiles : unresolvedFileCount;
249
- const shouldBePartial = partialFiles > 0 || unresolvedFileCount > 0 || inferredFileCount > 0;
250
-
251
- return {
252
- generated_paths: generatedPaths,
253
- audit_ref: ".nimi/local/state/spec-generation/spec-generation-audit.yaml",
254
- placement_report_ref: ".nimi/local/state/spec-surface/current-inventory.json",
255
- coverage_summary: {
256
- complete_files: Math.max(generatedPaths.length - partialFiles - placeholderFiles, 0),
257
- partial_files: partialFiles,
258
- placeholder_files: placeholderFiles,
259
- },
260
- unresolved_file_count: unresolvedFileCount,
261
- inferred_file_count: inferredFileCount,
262
- status: doctorResult.specGenerationAudit?.ok && !shouldBePartial ? "reconstructed" : "partial",
263
- summary: doctorResult.specGenerationAudit?.ok && !shouldBePartial
264
- ? "Canonical spec generation completed with file-level audit coverage."
265
- : "Canonical spec generation is valid, but file-level audit still records inferred or unresolved coverage.",
266
- verified_at: verifiedAt,
267
- };
268
- }
269
-
270
- async function validateSpecReconstructionSummaryAgainstAudit(projectRoot, summary, doctorResult) {
271
- if (!summary) {
272
- return { ok: true };
273
- }
274
-
275
- const generatedPaths = await collectSpecPaths(path.join(projectRoot, ".nimi", "spec"), ".nimi/spec");
276
- const auditSummary = doctorResult.specGenerationAudit?.summary ?? {};
277
- const unresolvedFileCount = Number.isInteger(auditSummary.unresolvedFiles) ? auditSummary.unresolvedFiles : 0;
278
- const inferredFileCount = Number.isInteger(auditSummary.inferredFiles) ? auditSummary.inferredFiles : 0;
279
- const placeholderFiles = Number.isInteger(auditSummary.placeholderFiles) ? auditSummary.placeholderFiles : 0;
280
- const partialFiles = Number.isInteger(auditSummary.partialFiles) ? auditSummary.partialFiles : unresolvedFileCount;
281
- const shouldBePartial = partialFiles > 0 || unresolvedFileCount > 0 || inferredFileCount > 0;
282
- const expectedStatus = doctorResult.specGenerationAudit?.ok && !shouldBePartial ? "reconstructed" : "partial";
283
- const expectedCompleteUpperBound = Math.max(generatedPaths.length - partialFiles - placeholderFiles, 0);
284
-
285
- const coverageSummary = isPlainObject(summary.coverage_summary) ? summary.coverage_summary : {};
286
- const summaryPartialFiles = Number.isInteger(coverageSummary.partial_files) ? coverageSummary.partial_files : null;
287
- const summaryPlaceholderFiles = Number.isInteger(coverageSummary.placeholder_files) ? coverageSummary.placeholder_files : null;
288
- const summaryCompleteFiles = Number.isInteger(coverageSummary.complete_files) ? coverageSummary.complete_files : null;
289
- const summaryUnresolvedCount = Number.isInteger(summary.unresolved_file_count) ? summary.unresolved_file_count : null;
290
- const summaryInferredCount = Number.isInteger(summary.inferred_file_count) ? summary.inferred_file_count : null;
291
-
292
- const matchesAudit =
293
- summary.status === expectedStatus &&
294
- summaryPartialFiles === partialFiles &&
295
- summaryPlaceholderFiles === placeholderFiles &&
296
- summaryUnresolvedCount === unresolvedFileCount &&
297
- summaryInferredCount === inferredFileCount &&
298
- (summaryCompleteFiles === null || summaryCompleteFiles <= expectedCompleteUpperBound);
299
-
300
- return matchesAudit
301
- ? { ok: true }
302
- : {
303
- ok: false,
304
- reason: "Imported spec_reconstruction summary must match active spec-generation audit coverage",
305
- };
306
- }
307
-
308
- function evaluateCloseoutReadiness(skillId, outcome, doctorResult, summary) {
309
- if (outcome !== "completed") {
310
- if (!doctorResult.ok || !doctorResult.handoffReadiness.ok) {
311
- return {
312
- ok: false,
313
- reason: "Bootstrap or handoff validation is failing; repair doctor errors before projecting closeout results",
314
- };
315
- }
316
- return {
317
- ok: true,
318
- reason: "Non-completed outcomes may be projected as local-only closeout artifacts",
319
- };
320
- }
321
-
322
- const usesV2SurfaceModel = doctorResult.specGenerationInputs?.mode === "class_filtered";
323
- if (usesV2SurfaceModel && (doctorResult.commandGating?.entries ?? []).length === 0) {
324
- if (!doctorResult.ok || !doctorResult.handoffReadiness.ok) {
325
- return {
326
- ok: false,
327
- reason: "Bootstrap or handoff validation is failing; repair doctor errors before projecting closeout results",
328
- };
329
- }
330
- if (doctorResult.canonicalTree?.requiredFilesValid !== true) {
331
- return {
332
- ok: false,
333
- reason: "Completed closeout requires declared canonical tree files to be valid",
334
- };
335
- }
336
- if (doctorResult.specGenerationAudit?.ok !== true) {
337
- return {
338
- ok: false,
339
- reason: "Completed closeout requires a valid `.nimi/local/state/spec-generation/spec-generation-audit.yaml` artifact",
340
- };
341
- }
342
- if (skillId === "doc_spec_audit") {
343
- const comparedPaths = Array.isArray(summary?.compared_paths) ? summary.compared_paths : [];
344
- if (!comparedPaths.includes(".nimi/spec")) {
345
- return {
346
- ok: false,
347
- reason: "Completed doc_spec_audit closeout must compare against `.nimi/spec`",
348
- };
349
- }
350
- }
351
- return {
352
- ok: true,
353
- reason: "Completed closeout is consistent with the current canonical tree state",
354
- };
355
- }
356
-
357
- const rule = (doctorResult.commandGating?.entries ?? []).find((entry) => entry.command === "closeout" && entry.skill === skillId) ?? null;
358
- if (!rule?.completedRequires) {
359
- return {
360
- ok: false,
361
- reason: "Completed closeout is not allowed in the current lifecycle state",
362
- };
363
- }
364
-
365
- const treeState = doctorResult.lifecycleState?.treeState;
366
- if (rule.completedRequires.tree_state && rule.completedRequires.tree_state !== treeState) {
367
- return {
368
- ok: false,
369
- reason: "Completed closeout is not allowed in the current lifecycle state",
370
- };
371
- }
372
-
373
- if (rule.completedRequires.canonical_required_files_valid === true && doctorResult.canonicalTree?.requiredFilesValid !== true) {
374
- return {
375
- ok: false,
376
- reason: "Completed closeout requires declared canonical tree files to be valid",
377
- };
378
- }
379
-
380
- if (rule.completedRequires.spec_generation_audit_valid === true && doctorResult.specGenerationAudit?.ok !== true) {
381
- return {
382
- ok: false,
383
- reason: "Completed closeout requires a valid `.nimi/local/state/spec-generation/spec-generation-audit.yaml` artifact",
384
- };
385
- }
386
-
387
- if (rule.completedRequires.audit_references_canonical_root === true) {
388
- const comparedPaths = Array.isArray(summary?.compared_paths) ? summary.compared_paths : [];
389
- if (!comparedPaths.includes(".nimi/spec")) {
390
- return {
391
- ok: false,
392
- reason: "Completed doc_spec_audit closeout must compare against `.nimi/spec`",
393
- };
394
- }
395
- }
396
-
397
- if (!doctorResult.ok || !doctorResult.handoffReadiness.ok) {
398
- return {
399
- ok: false,
400
- reason: "Bootstrap or handoff validation is failing; repair doctor errors before projecting closeout results",
401
- };
402
- }
403
-
404
- return {
405
- ok: true,
406
- reason: "Completed closeout is consistent with the current canonical tree state",
407
- };
408
- }
409
-
410
- export async function validateImportedCloseoutShape(raw, projectRoot) {
411
- if (!isPlainObject(raw)) {
412
- return {
413
- ok: false,
414
- error: `${localize(
415
- "nimicoding closeout refused: imported closeout JSON must be an object.",
416
- "nimicoding closeout 已拒绝:导入的 closeout JSON 必须是对象。",
417
- )}\n`,
418
- };
419
- }
420
-
421
- if (raw.projectRoot) {
422
- let importedProjectRoot;
423
- let currentProjectRoot;
424
- try {
425
- importedProjectRoot = await realpath(raw.projectRoot);
426
- currentProjectRoot = await realpath(projectRoot);
427
- } catch {
428
- return {
429
- ok: false,
430
- error: `${localize(
431
- "nimicoding closeout refused: imported closeout projectRoot could not be resolved.",
432
- "nimicoding closeout 已拒绝:无法解析导入 closeout 的 projectRoot。",
433
- )}\n`,
434
- };
435
- }
436
-
437
- if (importedProjectRoot !== currentProjectRoot) {
438
- return {
439
- ok: false,
440
- error: `${localize(
441
- "nimicoding closeout refused: imported closeout projectRoot does not match the current project.",
442
- "nimicoding closeout 已拒绝:导入 closeout 的 projectRoot 与当前项目不匹配。",
443
- )}\n`,
444
- };
445
- }
446
- }
447
-
448
- const skillId = typeof raw.skill === "string"
449
- ? raw.skill
450
- : raw.skill && typeof raw.skill === "object" && typeof raw.skill.id === "string"
451
- ? raw.skill.id
452
- : null;
453
-
454
- if (!skillId) {
455
- return {
456
- ok: false,
457
- error: `${localize(
458
- "nimicoding closeout refused: imported closeout JSON must declare `skill.id`.",
459
- "nimicoding closeout 已拒绝:导入的 closeout JSON 必须声明 `skill.id`。",
460
- )}\n`,
461
- };
462
- }
463
-
464
- if (typeof raw.outcome !== "string" || !["completed", "blocked", "failed"].includes(raw.outcome)) {
465
- return {
466
- ok: false,
467
- error: `${localize(
468
- "nimicoding closeout refused: imported closeout JSON must declare a supported `outcome`.",
469
- "nimicoding closeout 已拒绝:导入的 closeout JSON 必须声明受支持的 `outcome`。",
470
- )}\n`,
471
- };
472
- }
473
-
474
- if (!isIsoUtcTimestamp(raw.verifiedAt)) {
475
- return {
476
- ok: false,
477
- error: `${localize(
478
- "nimicoding closeout refused: imported `verifiedAt` must be an ISO-8601 UTC timestamp.",
479
- "nimicoding closeout 已拒绝:导入的 `verifiedAt` 必须是 ISO-8601 UTC 时间戳。",
480
- )}\n`,
481
- };
482
- }
483
-
484
- if ("localOnly" in raw && raw.localOnly !== true) {
485
- return {
486
- ok: false,
487
- error: `${localize(
488
- "nimicoding closeout refused: imported closeout JSON cannot claim non-local semantic promotion.",
489
- "nimicoding closeout 已拒绝:导入的 closeout JSON 不能声明非本地语义提升。",
490
- )}\n`,
491
- };
492
- }
493
-
494
- if ("summary" in raw && !isPlainObject(raw.summary)) {
495
- return {
496
- ok: false,
497
- error: `${localize(
498
- "nimicoding closeout refused: imported closeout JSON `summary` must be an object when present.",
499
- "nimicoding closeout 已拒绝:导入的 closeout JSON 中 `summary` 如果存在,必须是对象。",
500
- )}\n`,
501
- };
502
- }
503
-
504
- return {
505
- ok: true,
506
- options: {
507
- skill: skillId,
508
- outcome: raw.outcome,
509
- verifiedAt: raw.verifiedAt,
510
- summary: raw.summary,
511
- },
512
- };
513
- }
514
-
515
- export async function loadImportedCloseoutOptions(projectRoot, fromPath) {
516
- const absolutePath = path.resolve(projectRoot, fromPath);
517
- const rawText = await readTextIfFile(absolutePath);
518
-
519
- if (rawText === null) {
520
- return {
521
- ok: false,
522
- error: `${localize(
523
- `nimicoding closeout refused: cannot read imported closeout JSON at ${absolutePath}.`,
524
- `nimicoding closeout 已拒绝:无法读取 ${absolutePath} 处的导入 closeout JSON。`,
525
- )}\n`,
526
- };
527
- }
528
-
529
- let parsed;
530
- try {
531
- parsed = JSON.parse(rawText);
532
- } catch {
533
- return {
534
- ok: false,
535
- error: `${localize(
536
- `nimicoding closeout refused: imported closeout JSON at ${absolutePath} is invalid JSON.`,
537
- `nimicoding closeout 已拒绝:${absolutePath} 处的导入 closeout JSON 不是合法 JSON。`,
538
- )}\n`,
539
- };
540
- }
541
-
542
- return validateImportedCloseoutShape(parsed, projectRoot);
543
- }
544
-
545
- export async function buildCloseoutPayload(projectRoot, options) {
546
- const doctorResult = await inspectDoctorState(projectRoot);
547
- const manifestText = await readTextIfFile(path.join(projectRoot, ".nimi", "config", "skill-manifest.yaml"));
548
- const skillsConfigText = await readTextIfFile(path.join(projectRoot, ".nimi", "config", "skills.yaml"));
549
- const manifestSkills = parseSkillSection(manifestText, "skills");
550
- const expectedSkills = parseSkillSection(skillsConfigText, "expected_skill_surfaces");
551
- const manifestSkill = manifestSkills.find((skill) => skill.id === options.skill) ?? null;
552
- const expectedSkill = expectedSkills.find((skill) => skill.id === options.skill) ?? null;
553
-
554
- if (!manifestSkill || !expectedSkill) {
555
- return {
556
- ok: false,
557
- exitCode: 1,
558
- error: localize(
559
- `Unknown or undeclared skill id: ${options.skill}`,
560
- `未知或未声明的 skill id:${options.skill}`,
561
- ),
562
- availableSkills: manifestSkills.map((skill) => skill.id),
563
- doctor: doctorResult,
564
- };
565
- }
566
-
567
- const resultContractRef = manifestSkill.result_contract_ref ?? SKILL_RESULT_CONTRACT_REFS[options.skill] ?? null;
568
- let effectiveSummary = options.summary;
569
- if (!effectiveSummary && options.skill === "spec_reconstruction" && options.outcome === "completed") {
570
- effectiveSummary = await synthesizeSpecReconstructionSummary(projectRoot, doctorResult, options.verifiedAt);
571
- }
572
- const summaryValidation = await validateCloseoutSummaryForSkill(
573
- projectRoot,
574
- options.skill,
575
- effectiveSummary,
576
- options.verifiedAt,
577
- );
578
-
579
- if (!summaryValidation.ok) {
580
- return {
581
- ok: false,
582
- exitCode: 2,
583
- inputError: true,
584
- readiness: null,
585
- error: `${localize(
586
- `nimicoding closeout refused: ${summaryValidation.reason}.`,
587
- `nimicoding closeout 已拒绝:${translateCloseoutReason(summaryValidation.reason)}。`,
588
- )}\n`,
589
- };
590
- }
591
-
592
- const statusConsistency = validateOutcomeStatusConsistency(
593
- options.skill,
594
- options.outcome,
595
- effectiveSummary,
596
- );
597
- if (!statusConsistency.ok) {
598
- return {
599
- ok: false,
600
- exitCode: 2,
601
- inputError: true,
602
- readiness: null,
603
- error: `${localize(
604
- `nimicoding closeout refused: ${statusConsistency.reason}.`,
605
- `nimicoding closeout 已拒绝:${translateCloseoutReason(statusConsistency.reason)}。`,
606
- )}\n`,
607
- };
608
- }
609
-
610
- if (options.skill === "spec_reconstruction" && options.outcome === "completed") {
611
- // Canonical tree must be intact before audit-coverage comparison; a
612
- // missing domain kernel file is a readiness fail with its own reason.
613
- if (doctorResult.canonicalTree?.requiredFilesValid !== true) {
614
- const reason = "Completed closeout requires declared canonical tree files to be valid";
615
- return {
616
- ok: false,
617
- exitCode: 1,
618
- readiness: { ok: false, reason },
619
- error: `${localize(
620
- `nimicoding closeout refused: ${reason}.`,
621
- `nimicoding closeout 已拒绝:${translateCloseoutReason(reason)}。`,
622
- )}\n`,
623
- };
624
- }
625
- if (doctorResult.specGenerationAudit?.ok !== true) {
626
- const reason = "Completed closeout requires a valid `.nimi/local/state/spec-generation/spec-generation-audit.yaml` artifact";
627
- return {
628
- ok: false,
629
- exitCode: 1,
630
- readiness: { ok: false, reason },
631
- error: `${localize(
632
- `nimicoding closeout refused: ${reason}.`,
633
- `nimicoding closeout 已拒绝:${translateCloseoutReason(reason)}。`,
634
- )}\n`,
635
- };
636
- }
637
- const auditConsistency = await validateSpecReconstructionSummaryAgainstAudit(
638
- projectRoot,
639
- effectiveSummary,
640
- doctorResult,
641
- );
642
- if (!auditConsistency.ok) {
643
- return {
644
- ok: false,
645
- exitCode: 2,
646
- inputError: true,
647
- readiness: null,
648
- error: `${localize(
649
- `nimicoding closeout refused: ${auditConsistency.reason}.`,
650
- `nimicoding closeout 已拒绝:${translateCloseoutReason(auditConsistency.reason)}。`,
651
- )}\n`,
652
- };
653
- }
654
- }
655
-
656
- const readiness = evaluateCloseoutReadiness(options.skill, options.outcome, doctorResult, effectiveSummary);
657
- const localArtifactPath = path.join(projectRoot, ".nimi", "local", "handoff-results", `${options.skill}.json`);
658
- const payload = {
659
- contractVersion: CLOSEOUT_PAYLOAD_CONTRACT_VERSION,
660
- ok: readiness.ok,
661
- exitCode: readiness.ok ? 0 : 1,
662
- projectRoot,
663
- skill: {
664
- id: options.skill,
665
- required: expectedSkill.required === "true",
666
- purpose: expectedSkill.purpose ?? null,
667
- source: manifestSkill.source ?? "external",
668
- resultContractRef,
669
- },
670
- outcome: options.outcome,
671
- verifiedAt: options.verifiedAt,
672
- localOnly: true,
673
- artifactPath: localArtifactPath,
674
- summary: effectiveSummary,
675
- contracts: {
676
- exchangeProjectionContractRef: ".nimi/methodology/skill-exchange-projection.yaml",
677
- handoffRef: ".nimi/methodology/skill-handoff.yaml",
678
- resultContractRef,
679
- },
680
- readiness,
681
- doctor: {
682
- ok: doctorResult.ok,
683
- handoffReadiness: doctorResult.handoffReadiness,
684
- delegatedContracts: doctorResult.delegatedContracts,
685
- specGenerationAudit: doctorResult.specGenerationAudit,
686
- auditArtifact: doctorResult.auditArtifact,
687
- },
688
- nextAction: readiness.ok
689
- ? options.writeLocal
690
- ? `Write the closeout artifact to ${localArtifactPath}.`
691
- : "Review the projected closeout payload or write it locally with `--write-local`."
692
- : readiness.reason,
693
- };
694
-
695
- return payload;
696
- }
697
-
698
- export function formatCloseoutPayload(payload) {
699
- const nextAction = !payload.readiness.ok
700
- ? translateCloseoutReason(payload.nextAction)
701
- : payload.nextAction.startsWith("Write the closeout artifact to ")
702
- ? localize(payload.nextAction, `将 closeout 产物写入 ${payload.artifactPath}。`)
703
- : localize(
704
- payload.nextAction,
705
- `检查投影后的 closeout payload,或使用 ${styleCommand("--write-local")} 将其写入本地。`,
706
- );
707
- const lines = [
708
- styleHeading(`nimicoding closeout: ${payload.projectRoot}`),
709
- "",
710
- styleLabel(localize("Skill:", "Skill:")),
711
- ` - id: ${payload.skill.id}`,
712
- ` - required: ${payload.skill.required ? "true" : "false"}`,
713
- ` - source: ${payload.skill.source}`,
714
- ` - purpose: ${payload.skill.purpose ?? localize("unknown", "未知")}`,
715
- ` - result_contract_ref: ${payload.skill.resultContractRef ?? "none"}`,
716
- "",
717
- styleLabel(localize("Result:", "结果:")),
718
- ` - outcome: ${payload.outcome}`,
719
- ` - verified_at: ${payload.verifiedAt}`,
720
- ` - ready: ${styleStatus(payload.readiness.ok ? "ready" : "needs_attention")}`,
721
- ` - local_only: ${payload.localOnly ? "true" : "false"}`,
722
- "",
723
- styleLabel(localize("Next:", "下一步:")),
724
- ` - ${nextAction}`,
725
- ];
726
-
727
- if (payload.summary?.status) {
728
- lines.splice(lines.length - 3, 0, "", styleLabel(localize("Summary:", "摘要:")), ` - status: ${payload.summary.status}`);
729
- }
730
-
731
- return `${lines.join("\n")}\n`;
732
- }