@nimiplatform/nimi-coding 0.2.8 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +10 -90
  2. package/CONTRIBUTING.md +5 -34
  3. package/README.md +47 -350
  4. package/README.zh-CN.md +33 -287
  5. package/cli/commands/start.mjs +48 -688
  6. package/cli/commands/validate-spec-audit.mjs +1 -5
  7. package/cli/commands/validate-spec-governance.mjs +20 -0
  8. package/cli/constants.mjs +9 -417
  9. package/cli/help.mjs +28 -145
  10. package/cli/index.mjs +5 -33
  11. package/cli/lib/blueprint-audit.mjs +5 -12
  12. package/cli/lib/bootstrap.mjs +0 -9
  13. package/cli/lib/contracts.mjs +0 -163
  14. package/cli/lib/doctor.mjs +155 -10
  15. package/cli/lib/entrypoints.mjs +63 -167
  16. package/cli/lib/internal/contracts-loaders.mjs +0 -85
  17. package/cli/lib/internal/contracts-parse.mjs +84 -520
  18. package/cli/lib/internal/governance/ai/check-agents-freshness.mjs +13 -8
  19. package/cli/lib/internal/surface-taxonomy-validators.mjs +316 -66
  20. package/cli/lib/internal/validators-shared.mjs +0 -16
  21. package/cli/lib/internal/validators-spec-helpers.mjs +7 -140
  22. package/cli/lib/internal/validators-spec.mjs +103 -342
  23. package/cli/lib/shared.mjs +1 -42
  24. package/cli/lib/validators.mjs +0 -48
  25. package/cli/seeds/seed-policy.yaml +0 -3
  26. package/config/bootstrap.yaml +4 -4
  27. package/config/spec-generation-inputs.yaml +6 -12
  28. package/contracts/domain-admission.schema.yaml +3 -3
  29. package/contracts/migration-inventory.schema.yaml +12 -75
  30. package/contracts/negative-fixtures.yaml +19 -99
  31. package/contracts/placement-contract.schema.yaml +49 -78
  32. package/contracts/projection-edge.schema.yaml +37 -121
  33. package/contracts/shared-enums.yaml +4 -8
  34. package/contracts/spec-generation-inputs.schema.yaml +15 -112
  35. package/contracts/spec-layout.schema.yaml +32 -0
  36. package/contracts/surface-taxonomy.schema.yaml +43 -94
  37. package/contracts/table-family.schema.yaml +1 -1
  38. package/contracts/tracked-output-admission.schema.yaml +13 -66
  39. package/methodology/core.yaml +33 -25
  40. package/methodology/four-closure-policy.yaml +18 -26
  41. package/methodology/role-separation-policy.yaml +21 -27
  42. package/methodology/spec-reconstruction.yaml +17 -34
  43. package/package.json +2 -4
  44. package/spec/_meta/spec-tree-model.yaml +5 -101
  45. package/spec/product-scope.yaml +25 -57
  46. package/adapters/README.md +0 -25
  47. package/adapters/claude/README.md +0 -89
  48. package/adapters/claude/profile.yaml +0 -70
  49. package/adapters/codex/README.md +0 -53
  50. package/adapters/codex/profile.yaml +0 -78
  51. package/adapters/oh-my-codex/README.md +0 -184
  52. package/adapters/oh-my-codex/profile.yaml +0 -46
  53. package/cli/commands/admit-high-risk-decision.mjs +0 -108
  54. package/cli/commands/audit-sweep.mjs +0 -364
  55. package/cli/commands/closeout.mjs +0 -186
  56. package/cli/commands/decide-high-risk-execution.mjs +0 -124
  57. package/cli/commands/handoff.mjs +0 -123
  58. package/cli/commands/ingest-high-risk-execution.mjs +0 -95
  59. package/cli/commands/review-high-risk-execution.mjs +0 -95
  60. package/cli/commands/sweep-design.mjs +0 -295
  61. package/cli/commands/sweep.mjs +0 -22
  62. package/cli/commands/topic-formatters.mjs +0 -382
  63. package/cli/commands/topic-goal.mjs +0 -33
  64. package/cli/commands/topic-options-shared.mjs +0 -27
  65. package/cli/commands/topic-options-workflow.mjs +0 -767
  66. package/cli/commands/topic-options.mjs +0 -626
  67. package/cli/commands/topic-runner.mjs +0 -169
  68. package/cli/commands/topic.mjs +0 -795
  69. package/cli/commands/validate-acceptance.mjs +0 -5
  70. package/cli/commands/validate-execution-packet.mjs +0 -5
  71. package/cli/commands/validate-orchestration-state.mjs +0 -5
  72. package/cli/commands/validate-prompt.mjs +0 -5
  73. package/cli/commands/validate-worker-output.mjs +0 -5
  74. package/cli/lib/adapter-profiles.mjs +0 -403
  75. package/cli/lib/audit-execution.mjs +0 -52
  76. package/cli/lib/audit-sweep-runtime/admissions.mjs +0 -508
  77. package/cli/lib/audit-sweep-runtime/audit-validity.mjs +0 -356
  78. package/cli/lib/audit-sweep-runtime/chunks.mjs +0 -697
  79. package/cli/lib/audit-sweep-runtime/claude-auditor.mjs +0 -658
  80. package/cli/lib/audit-sweep-runtime/closeout.mjs +0 -144
  81. package/cli/lib/audit-sweep-runtime/codex-auditor-evidence.mjs +0 -654
  82. package/cli/lib/audit-sweep-runtime/codex-auditor.mjs +0 -527
  83. package/cli/lib/audit-sweep-runtime/common.mjs +0 -341
  84. package/cli/lib/audit-sweep-runtime/coverage-quality.mjs +0 -172
  85. package/cli/lib/audit-sweep-runtime/evidence-assignment.mjs +0 -155
  86. package/cli/lib/audit-sweep-runtime/format.mjs +0 -57
  87. package/cli/lib/audit-sweep-runtime/ingest.mjs +0 -486
  88. package/cli/lib/audit-sweep-runtime/inventory-spec-chunks.mjs +0 -425
  89. package/cli/lib/audit-sweep-runtime/inventory.mjs +0 -798
  90. package/cli/lib/audit-sweep-runtime/ledger.mjs +0 -315
  91. package/cli/lib/audit-sweep-runtime/p0p1-profile.mjs +0 -101
  92. package/cli/lib/audit-sweep-runtime/remediation.mjs +0 -349
  93. package/cli/lib/audit-sweep-runtime/rerun.mjs +0 -129
  94. package/cli/lib/audit-sweep-runtime/risk-budget.mjs +0 -300
  95. package/cli/lib/audit-sweep-runtime/status.mjs +0 -62
  96. package/cli/lib/audit-sweep-runtime/validators-ledger.mjs +0 -215
  97. package/cli/lib/audit-sweep-runtime/validators.mjs +0 -797
  98. package/cli/lib/audit-sweep.mjs +0 -19
  99. package/cli/lib/authority-convergence.mjs +0 -720
  100. package/cli/lib/closeout.mjs +0 -732
  101. package/cli/lib/codex-sdk-runner.mjs +0 -76
  102. package/cli/lib/external-execution.mjs +0 -101
  103. package/cli/lib/handoff.mjs +0 -812
  104. package/cli/lib/high-risk-admission.mjs +0 -512
  105. package/cli/lib/high-risk-decision.mjs +0 -353
  106. package/cli/lib/high-risk-ingest.mjs +0 -321
  107. package/cli/lib/high-risk-review.mjs +0 -267
  108. package/cli/lib/internal/contracts-parse-high-risk.mjs +0 -131
  109. package/cli/lib/internal/contracts-validators.mjs +0 -399
  110. package/cli/lib/internal/doctor-bootstrap-surface.mjs +0 -406
  111. package/cli/lib/internal/doctor-delegated-surface.mjs +0 -256
  112. package/cli/lib/internal/doctor-finalize.mjs +0 -383
  113. package/cli/lib/internal/doctor-format.mjs +0 -286
  114. package/cli/lib/internal/doctor-inspectors.mjs +0 -327
  115. package/cli/lib/internal/doctor-state.mjs +0 -205
  116. package/cli/lib/internal/validators-artifacts.mjs +0 -515
  117. package/cli/lib/sweep-design-runtime/common.mjs +0 -246
  118. package/cli/lib/sweep-design-runtime/engine.mjs +0 -733
  119. package/cli/lib/sweep-design-runtime/fix-topic.mjs +0 -414
  120. package/cli/lib/sweep-design-runtime/lifecycle.mjs +0 -54
  121. package/cli/lib/sweep-design-runtime/results.mjs +0 -324
  122. package/cli/lib/sweep-design.mjs +0 -8
  123. package/cli/lib/topic-artifacts.mjs +0 -186
  124. package/cli/lib/topic-authority-coverage.mjs +0 -73
  125. package/cli/lib/topic-closeout.mjs +0 -560
  126. package/cli/lib/topic-common.mjs +0 -404
  127. package/cli/lib/topic-decisions.mjs +0 -332
  128. package/cli/lib/topic-draft-packets.mjs +0 -167
  129. package/cli/lib/topic-execution.mjs +0 -533
  130. package/cli/lib/topic-goal.mjs +0 -440
  131. package/cli/lib/topic-ledger.mjs +0 -281
  132. package/cli/lib/topic-lifecycle-artifacts.mjs +0 -173
  133. package/cli/lib/topic-root-validation.mjs +0 -288
  134. package/cli/lib/topic-runner-commands.mjs +0 -174
  135. package/cli/lib/topic-runner-deferral.mjs +0 -532
  136. package/cli/lib/topic-runner-stale-gates.mjs +0 -114
  137. package/cli/lib/topic-runner-validation.mjs +0 -138
  138. package/cli/lib/topic-runner.mjs +0 -727
  139. package/cli/lib/topic-scaffold.mjs +0 -252
  140. package/cli/lib/topic-waves.mjs +0 -403
  141. package/cli/lib/topic.mjs +0 -81
  142. package/config/audit-execution-artifacts.yaml +0 -20
  143. package/config/external-execution-artifacts.yaml +0 -16
  144. package/config/host-adapter.yaml +0 -30
  145. package/config/host-profile.yaml +0 -29
  146. package/config/installer-evidence.yaml +0 -31
  147. package/config/skill-installer.yaml +0 -23
  148. package/config/skill-manifest.yaml +0 -48
  149. package/config/skills.yaml +0 -30
  150. package/contracts/acceptance.schema.yaml +0 -16
  151. package/contracts/admission-checklist.schema.yaml +0 -15
  152. package/contracts/audit-chunk.schema.yaml +0 -123
  153. package/contracts/audit-closeout.schema.yaml +0 -51
  154. package/contracts/audit-finding.schema.yaml +0 -61
  155. package/contracts/audit-ledger.schema.yaml +0 -138
  156. package/contracts/audit-plan.schema.yaml +0 -138
  157. package/contracts/audit-remediation-map.schema.yaml +0 -52
  158. package/contracts/audit-rerun.schema.yaml +0 -31
  159. package/contracts/audit-sweep-result.yaml +0 -53
  160. package/contracts/authority-convergence-audit.schema.yaml +0 -19
  161. package/contracts/closeout.schema.yaml +0 -25
  162. package/contracts/decision-review.schema.yaml +0 -16
  163. package/contracts/doc-spec-audit-result.yaml +0 -19
  164. package/contracts/execution-packet.schema.yaml +0 -49
  165. package/contracts/external-host-compatibility.yaml +0 -22
  166. package/contracts/forbidden-shortcuts.catalog.yaml +0 -23
  167. package/contracts/high-risk-admission.schema.yaml +0 -23
  168. package/contracts/high-risk-execution-result.yaml +0 -20
  169. package/contracts/orchestration-state.schema.yaml +0 -41
  170. package/contracts/overflow-continuation.schema.yaml +0 -12
  171. package/contracts/packet.schema.yaml +0 -30
  172. package/contracts/pending-note.schema.yaml +0 -17
  173. package/contracts/prompt.schema.yaml +0 -12
  174. package/contracts/remediation.schema.yaml +0 -16
  175. package/contracts/result.schema.yaml +0 -24
  176. package/contracts/spec-reconstruction-result.yaml +0 -41
  177. package/contracts/sweep-design-result.yaml +0 -349
  178. package/contracts/topic-goal.schema.yaml +0 -87
  179. package/contracts/topic-run-ledger.schema.yaml +0 -72
  180. package/contracts/topic-step-decision.schema.yaml +0 -45
  181. package/contracts/topic.schema.yaml +0 -65
  182. package/contracts/true-close.schema.yaml +0 -15
  183. package/contracts/wave.schema.yaml +0 -29
  184. package/contracts/worker-output.schema.yaml +0 -15
  185. package/contracts/workflow-consumer.schema.yaml +0 -110
  186. package/methodology/audit-sweep-p0p1-recall.yaml +0 -45
  187. package/methodology/authority-convergence-policy.yaml +0 -42
  188. package/methodology/overflow-continuation-policy.yaml +0 -14
  189. package/methodology/skill-exchange-projection.yaml +0 -114
  190. package/methodology/skill-handoff.yaml +0 -34
  191. package/methodology/skill-installer-result.yaml +0 -27
  192. package/methodology/skill-installer-summary-projection.yaml +0 -181
  193. package/methodology/skill-runtime.yaml +0 -23
  194. package/methodology/spec-target-truth-profile.yaml +0 -46
  195. package/methodology/topic-lifecycle-report.yaml +0 -144
  196. package/methodology/topic-lifecycle.yaml +0 -37
  197. package/methodology/topic-naming-ontology.yaml +0 -21
  198. package/methodology/topic-ontology.yaml +0 -38
  199. package/methodology/topic-validation-policy.yaml +0 -9
  200. package/methodology/wave-dag-policy.yaml +0 -14
  201. package/spec/_meta/command-gating-matrix.yaml +0 -143
  202. package/spec/_meta/generate-drift-migration-checklist.yaml +0 -137
  203. package/spec/_meta/governance-routing-cutover-checklist.yaml +0 -35
  204. package/spec/_meta/phase2-impacted-surface-matrix.yaml +0 -44
  205. package/spec/_meta/spec-authority-cutover-readiness.yaml +0 -102
  206. package/spec/bootstrap-state.yaml +0 -99
@@ -1,720 +0,0 @@
1
- import { readdir, readFile, stat } from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import { loadTopicRuntimeContracts } from "./contracts.mjs";
5
-
6
- function stringList(value) {
7
- return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry.length > 0) : [];
8
- }
9
-
10
- function normalizeAuthorityConvergencePolicy(parsed) {
11
- const policy = parsed?.authority_convergence_policy ?? {};
12
- const postUpdateReview = policy.post_update_review ?? {};
13
- return {
14
- triggerPacketKinds: stringList(policy.trigger_packet_kinds),
15
- triggerRefPrefixes: stringList(policy.trigger_ref_prefixes),
16
- triggerWorkTypes: stringList(policy.trigger_topic_fields?.work_type),
17
- requiredResultKind: typeof policy.required_result?.result_kind === "string"
18
- ? policy.required_result.result_kind
19
- : "audit",
20
- passVerdict: typeof policy.required_result?.pass_verdict === "string"
21
- ? policy.required_result.pass_verdict
22
- : "PASS",
23
- blockedVerdicts: stringList(policy.blocked_verdicts),
24
- postUpdateReview: {
25
- triggerPacketKinds: stringList(postUpdateReview.trigger_packet_kinds),
26
- triggerRefPrefixes: stringList(postUpdateReview.trigger_ref_prefixes),
27
- requiredResultKind: typeof postUpdateReview.required_result?.result_kind === "string"
28
- ? postUpdateReview.required_result.result_kind
29
- : "judgement",
30
- passVerdict: typeof postUpdateReview.required_result?.pass_verdict === "string"
31
- ? postUpdateReview.required_result.pass_verdict
32
- : "PASS",
33
- },
34
- };
35
- }
36
-
37
- export async function loadAuthorityConvergencePolicy(projectRoot) {
38
- const loaded = await loadTopicRuntimeContracts(projectRoot);
39
- return normalizeAuthorityConvergencePolicy(loaded.authorityConvergencePolicy.data);
40
- }
41
-
42
- export function needsAuthorityConvergenceAudit(topic, packet, policy) {
43
- if (policy.triggerPacketKinds.includes(String(packet.packet_kind ?? ""))) return true;
44
- if (policy.triggerWorkTypes.includes(String(topic.work_type ?? ""))) return true;
45
- const refs = [
46
- ...stringList(packet.authority_owner),
47
- ...stringList(packet.canonical_seams),
48
- ];
49
- return refs.some((ref) => policy.triggerRefPrefixes.some((prefix) => (
50
- ref === prefix.slice(0, -1) || ref.startsWith(prefix) || ref.includes(prefix)
51
- )));
52
- }
53
-
54
- export function needsPostUpdateReview(packet, policy) {
55
- const reviewPolicy = policy.postUpdateReview ?? {};
56
- if (reviewPolicy.triggerPacketKinds?.includes(String(packet.packet_kind ?? ""))) return true;
57
- const refs = [
58
- ...stringList(packet.authority_owner),
59
- ...stringList(packet.canonical_seams),
60
- ];
61
- return refs.some((ref) => reviewPolicy.triggerRefPrefixes?.some((prefix) => (
62
- ref === prefix.slice(0, -1) || ref.startsWith(prefix) || ref.includes(prefix)
63
- )));
64
- }
65
-
66
- export function latestResultOfKind(results, kind) {
67
- return [...results].reverse().find((entry) => entry.result?.result_kind === kind) ?? null;
68
- }
69
-
70
- function verifiedAtMs(resultEntry) {
71
- const value = resultEntry?.result?.verified_at;
72
- if (typeof value !== "string" || value.length === 0) return Number.NaN;
73
- return Date.parse(value);
74
- }
75
-
76
- export function hasFreshPassingPostUpdateReview(results, implementationResult, policy) {
77
- const reviewPolicy = policy.postUpdateReview ?? {};
78
- const implementationVerifiedAt = verifiedAtMs(implementationResult);
79
- if (!Number.isFinite(implementationVerifiedAt)) return false;
80
- return [...results].reverse().some((entry) => (
81
- entry.result?.result_kind === reviewPolicy.requiredResultKind
82
- && entry.result?.verdict === reviewPolicy.passVerdict
83
- && verifiedAtMs(entry) >= implementationVerifiedAt
84
- ));
85
- }
86
-
87
- function hasPlaceholder(value) {
88
- return /<[^>]+>/u.test(String(value ?? ""));
89
- }
90
-
91
- function concreteRef(value) {
92
- return typeof value === "string"
93
- && value.length > 0
94
- && !hasPlaceholder(value)
95
- && !path.isAbsolute(value)
96
- && !value.includes("..");
97
- }
98
-
99
- function refsAreConcrete(values) {
100
- return stringList(values).length > 0 && stringList(values).every(concreteRef);
101
- }
102
-
103
- async function readJsonRef(projectRoot, ref) {
104
- if (!concreteRef(ref)) return null;
105
- try {
106
- return JSON.parse(await readFile(path.join(projectRoot, ref), "utf8"));
107
- } catch {
108
- return null;
109
- }
110
- }
111
-
112
- function extractTopicValidationEvidenceRefs(sourceText, waveId) {
113
- const refs = new Set();
114
- const pattern = new RegExp(`\\.nimi/topics/[^\\s)\\]'"<>]+/evidence-validation-${waveId.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}[^\\s)\\]'"<>]+\\.json`, "gu");
115
- for (const match of sourceText.matchAll(pattern)) {
116
- refs.add(match[0]);
117
- }
118
- return [...refs];
119
- }
120
-
121
- function extractPacketIdsFromSource(sourceText) {
122
- const ids = new Set();
123
- const patterns = [
124
- /^\s*packet_id:\s*`?([a-z0-9]+(?:-[a-z0-9]+)*)`?\s*$/gimu,
125
- /\bpacket_id\s*[:=]\s*`?([a-z0-9]+(?:-[a-z0-9]+)*)`?/gimu,
126
- /\bpacket\s+id\s*[:=]\s*`?([a-z0-9]+(?:-[a-z0-9]+)*)`?/gimu,
127
- ];
128
- for (const pattern of patterns) {
129
- for (const match of sourceText.matchAll(pattern)) {
130
- ids.add(match[1]);
131
- }
132
- }
133
- return [...ids];
134
- }
135
-
136
- function declaresPostUpdateAmbiguity(sourceText) {
137
- const ambiguityPattern = /\b(authority|scope|gate|product|semantic)\s+(ambiguity|ambiguous|fork|blocked|blocker|change required)\b/iu;
138
- const normalized = sourceText.replace(/\s+/gu, " ");
139
- for (const match of normalized.matchAll(new RegExp(ambiguityPattern.source, "giu"))) {
140
- const preceding = normalized.slice(0, match.index).toLowerCase();
141
- if (/\b(no|none|without)\b[^.!?\n]{0,120}$/u.test(preceding)) {
142
- continue;
143
- }
144
- return true;
145
- }
146
- return false;
147
- }
148
-
149
- function sourceContainsNegatedTerms(sourceText, terms) {
150
- const normalized = sourceText.replace(/\s+/gu, " ").toLowerCase();
151
- return terms.every((term) => {
152
- const escaped = term.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&").replace(/\\ /gu, "\\s+");
153
- return new RegExp(`\\b(no|not|without)\\b[^.!?]{0,160}\\b${escaped}\\b`, "iu").test(normalized)
154
- || new RegExp(`\\b${escaped}\\b[^.!?]{0,80}\\b(not\\s+mutated|not\\s+introduced)\\b`, "iu").test(normalized);
155
- });
156
- }
157
-
158
- function hasRequiredPostUpdateNegativeDeclarations(sourceText) {
159
- return sourceContainsNegatedTerms(sourceText, [
160
- "source audit findings",
161
- "source sweep-design artifacts",
162
- "pseudo-success",
163
- "fallback success",
164
- "compatibility shim",
165
- "dual-read",
166
- "dual-write",
167
- ]);
168
- }
169
-
170
- async function latestWorkerPromptPacketId(topicDir, packetEntries) {
171
- const packetIds = new Set(packetEntries.map((entry) => entry.packet?.packet_id).filter(Boolean));
172
- if (!topicDir || packetIds.size === 0) return null;
173
- let entries = [];
174
- try {
175
- entries = await readdir(topicDir, { withFileTypes: true });
176
- } catch {
177
- return null;
178
- }
179
- const prompts = [];
180
- for (const entry of entries) {
181
- if (!entry.isFile() || !entry.name.startsWith("prompt-") || !entry.name.endsWith("-worker.md")) continue;
182
- const packetId = entry.name.slice("prompt-".length, -"-worker.md".length);
183
- if (!packetIds.has(packetId)) continue;
184
- const promptPath = path.join(topicDir, entry.name);
185
- try {
186
- const promptStat = await stat(promptPath, { bigint: true });
187
- prompts.push({
188
- packetId,
189
- mtimeNs: promptStat.mtimeNs,
190
- ctimeNs: promptStat.ctimeNs,
191
- birthtimeNs: promptStat.birthtimeNs,
192
- promptRefName: entry.name,
193
- });
194
- } catch {
195
- return null;
196
- }
197
- }
198
- if (prompts.length === 0) return null;
199
- prompts.sort((left, right) => (
200
- Number(right.mtimeNs - left.mtimeNs)
201
- || Number(right.ctimeNs - left.ctimeNs)
202
- || Number(right.birthtimeNs - left.birthtimeNs)
203
- || left.promptRefName.localeCompare(right.promptRefName)
204
- ));
205
- if (
206
- prompts.length > 1
207
- && prompts[0].mtimeNs === prompts[1].mtimeNs
208
- && prompts[0].ctimeNs === prompts[1].ctimeNs
209
- && prompts[0].birthtimeNs === prompts[1].birthtimeNs
210
- ) return { ambiguous: true };
211
- return prompts[0];
212
- }
213
-
214
- async function workerPromptExists(topicDir, packetId) {
215
- if (!topicDir || !packetId) return false;
216
- try {
217
- const promptStat = await stat(path.join(topicDir, `prompt-${packetId}-worker.md`));
218
- return promptStat.isFile();
219
- } catch {
220
- return false;
221
- }
222
- }
223
-
224
- function passResultSourceRefSet(projectRoot, results, waveId) {
225
- const refs = new Set();
226
- for (const entry of results) {
227
- if (entry.result?.verdict !== "PASS") continue;
228
- if (entry.result?.wave_id && entry.result.wave_id !== waveId) continue;
229
- const sourceRef = entry.result?.source_ref;
230
- if (!concreteRef(sourceRef)) continue;
231
- refs.add(path.resolve(projectRoot, sourceRef));
232
- }
233
- return refs;
234
- }
235
-
236
- async function hasWaveRemediationArtifact(projectRoot, topicDir, waveId, results) {
237
- try {
238
- const passSourceRefs = passResultSourceRefSet(projectRoot, results, waveId);
239
- const entries = await readdir(topicDir, { withFileTypes: true });
240
- for (const entry of entries) {
241
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
242
- if (entry.name.startsWith(`packet-${waveId}-remediation-`)) return true;
243
- if (!entry.name.startsWith(`source-${waveId}-`) || !/remediat/iu.test(entry.name)) continue;
244
- const sourcePath = path.join(topicDir, entry.name);
245
- if (!passSourceRefs.has(path.resolve(sourcePath))) continue;
246
- const sourceText = await readFile(sourcePath, "utf8");
247
- if (
248
- /\bverdict:\s*PASS\b/iu.test(sourceText)
249
- && /\blocal_packet_authority_scope_remediation_only:\s*true\b/iu.test(sourceText)
250
- && /\bproduct_semantic_ambiguity:\s*false\b/iu.test(sourceText)
251
- && /\bsource_audit_findings_mutated:\s*false\b/iu.test(sourceText)
252
- && /\bsource_sweep_design_artifacts_mutated:\s*false\b/iu.test(sourceText)
253
- ) {
254
- return true;
255
- }
256
- }
257
- return false;
258
- } catch {
259
- return false;
260
- }
261
- }
262
-
263
- async function selectPostUpdateProofPacket({ topicDir, wave, specUpdatingPackets, sourceText }) {
264
- if (specUpdatingPackets.length === 0) {
265
- return { ok: false, reason: "post-update proof requires a spec-updating packet" };
266
- }
267
-
268
- const packetIds = extractPacketIdsFromSource(sourceText);
269
- const matchingSourcePackets = packetIds
270
- .map((packetId) => specUpdatingPackets.find((entry) => entry.packet?.packet_id === packetId) ?? null)
271
- .filter(Boolean);
272
- const uniqueMatchingSourcePackets = [...new Map(matchingSourcePackets.map((entry) => [entry.packet.packet_id, entry])).values()];
273
- if (uniqueMatchingSourcePackets.length > 1) {
274
- return { ok: false, reason: "implementation source names multiple post-update packets" };
275
- }
276
- if (packetIds.length > 0 && uniqueMatchingSourcePackets.length === 0) {
277
- return { ok: false, reason: "implementation source packet_id does not match a current post-update packet" };
278
- }
279
- if (uniqueMatchingSourcePackets.length === 1) {
280
- return { ok: true, entry: uniqueMatchingSourcePackets[0], selectionSource: "implementation_source" };
281
- }
282
-
283
- const promptLineage = await latestWorkerPromptPacketId(topicDir, specUpdatingPackets);
284
- if (promptLineage?.ambiguous) {
285
- return { ok: false, reason: "latest worker prompt lineage is ambiguous" };
286
- }
287
- if (promptLineage?.packetId) {
288
- const promptPacket = specUpdatingPackets.find((entry) => entry.packet?.packet_id === promptLineage.packetId);
289
- if (promptPacket) return { ok: true, entry: promptPacket, selectionSource: "worker_prompt" };
290
- }
291
-
292
- if (specUpdatingPackets.length === 1) {
293
- return { ok: true, entry: specUpdatingPackets[0], selectionSource: "single_packet" };
294
- }
295
-
296
- return { ok: false, reason: "post-update packet lineage is ambiguous" };
297
- }
298
-
299
- async function mechanicalPostUpdateJudgementProof({ projectRoot, topicDir, wave, specUpdatingPackets, results, implementationResult }) {
300
- if (!projectRoot || !topicDir) {
301
- return { ok: false, reason: "mechanical proof requires project and topic roots" };
302
- }
303
- const implementationVerifiedAt = verifiedAtMs(implementationResult);
304
- if (!Number.isFinite(implementationVerifiedAt)) {
305
- return { ok: false, reason: "implementation result verified_at is not concrete" };
306
- }
307
- const requiredKinds = new Map([
308
- ["audit", "audit result must pass"],
309
- ["preflight", "preflight result must pass"],
310
- ["implementation", "implementation result must pass"],
311
- ]);
312
- for (const [kind, reason] of requiredKinds) {
313
- const result = latestResultOfKind(results, kind);
314
- if (result?.result?.verdict !== "PASS") {
315
- return { ok: false, reason };
316
- }
317
- }
318
- const laterBlockingResult = results.find((entry) => {
319
- const verifiedAt = verifiedAtMs(entry);
320
- return Number.isFinite(verifiedAt)
321
- && verifiedAt >= implementationVerifiedAt
322
- && entry.result?.verdict !== "PASS";
323
- });
324
- if (laterBlockingResult) {
325
- return { ok: false, reason: "a later non-PASS result exists" };
326
- }
327
- const sourceRef = implementationResult?.result?.source_ref;
328
- if (!concreteRef(sourceRef)) {
329
- return { ok: false, reason: "implementation source ref is missing or non-concrete" };
330
- }
331
- let sourceText = "";
332
- try {
333
- sourceText = await readFile(path.join(projectRoot, sourceRef), "utf8");
334
- } catch {
335
- return { ok: false, reason: "implementation source ref is not readable" };
336
- }
337
- const selectedPacket = await selectPostUpdateProofPacket({
338
- topicDir,
339
- wave,
340
- specUpdatingPackets,
341
- sourceText,
342
- });
343
- if (!selectedPacket.ok) {
344
- return { ok: false, reason: selectedPacket.reason };
345
- }
346
- const packet = selectedPacket.entry.packet;
347
- if (packet.status !== "dispatched") {
348
- return { ok: false, reason: "post-update proof packet is not the current dispatched packet" };
349
- }
350
- if (!refsAreConcrete(packet.authority_owner) || !refsAreConcrete(packet.canonical_seams)) {
351
- return { ok: false, reason: "packet authority refs are missing or non-concrete" };
352
- }
353
- const promptLineage = await latestWorkerPromptPacketId(topicDir, specUpdatingPackets);
354
- if (selectedPacket.selectionSource === "implementation_source") {
355
- if (!await workerPromptExists(topicDir, packet.packet_id)) {
356
- return { ok: false, reason: "implementation result packet_id does not have worker prompt lineage" };
357
- }
358
- } else if (promptLineage?.ambiguous) {
359
- return { ok: false, reason: "latest worker prompt lineage is ambiguous" };
360
- }
361
- if (promptLineage?.ambiguous) {
362
- return { ok: false, reason: "latest worker prompt lineage is ambiguous" };
363
- }
364
- if (promptLineage?.packetId && promptLineage.packetId !== packet.packet_id) {
365
- return { ok: false, reason: "implementation result packet_id is not the latest worker prompt lineage" };
366
- }
367
- const isMultiAuthority = stringList(packet.authority_owner).length > 1;
368
- if (isMultiAuthority) {
369
- const hasExplicitPacketLineage = selectedPacket.selectionSource === "implementation_source"
370
- && extractPacketIdsFromSource(sourceText).includes(packet.packet_id);
371
- if (!hasExplicitPacketLineage) {
372
- return { ok: false, reason: "multi-authority post-update proof requires implementation-source packet lineage" };
373
- }
374
- if (!await hasWaveRemediationArtifact(projectRoot, topicDir, wave.wave_id, results) || !/\bremediat(?:e|ed|ion)\b/iu.test(sourceText)) {
375
- return { ok: false, reason: "multi-authority post-update proof requires explicit remediation lineage" };
376
- }
377
- }
378
- const evidenceRefs = extractTopicValidationEvidenceRefs(sourceText, wave.wave_id);
379
- if (evidenceRefs.length === 0) {
380
- return { ok: false, reason: "implementation source does not cite topic-local validation evidence" };
381
- }
382
- for (const ref of evidenceRefs) {
383
- if (!ref.startsWith(`${path.relative(projectRoot, topicDir).split(path.sep).join("/")}/`)) {
384
- return { ok: false, reason: `validation evidence is outside the topic root: ${ref}` };
385
- }
386
- const evidence = await readJsonRef(projectRoot, ref);
387
- if (!evidence || evidence.status !== "pass" || evidence.exit_code !== 0) {
388
- return { ok: false, reason: `validation evidence is not a clean pass: ${ref}` };
389
- }
390
- }
391
- if (declaresPostUpdateAmbiguity(sourceText)) {
392
- return { ok: false, reason: "implementation source declares authority/scope/gate/product/semantic ambiguity" };
393
- }
394
- if (!hasRequiredPostUpdateNegativeDeclarations(sourceText)) {
395
- return { ok: false, reason: "implementation source does not declare required mutation and shortcut negative checks" };
396
- }
397
- return { ok: true, evidenceRefs, sourceRef, packetId: packet.packet_id };
398
- }
399
-
400
- export async function buildPostUpdateReviewDecision({ projectRoot, topicDir, topicId, wave, packets, results, policy, commandRef }) {
401
- const wavePackets = packets.filter((entry) => entry.packet?.wave_id === wave.wave_id);
402
- const specUpdatingPackets = wavePackets.filter((entry) => needsPostUpdateReview(entry.packet, policy));
403
- const specUpdatingPacket = specUpdatingPackets[0] ?? null;
404
- const implementationResult = latestResultOfKind(results, "implementation");
405
- if (
406
- !specUpdatingPacket
407
- || implementationResult?.result?.verdict !== "PASS"
408
- || hasFreshPassingPostUpdateReview(results, implementationResult, policy)
409
- ) {
410
- return null;
411
- }
412
- const reviewPolicy = policy.postUpdateReview ?? {};
413
- const mechanicalProof = await mechanicalPostUpdateJudgementProof({
414
- projectRoot,
415
- topicDir,
416
- wave,
417
- specUpdatingPackets,
418
- results,
419
- implementationResult,
420
- });
421
- if (mechanicalProof.ok) {
422
- return {
423
- stopClass: "continue",
424
- recommendedAction: "record_result",
425
- reasonCode: "mechanical_post_update_judgement_pass",
426
- recommendedDecision: "record_mechanical_post_update_judgement_pass",
427
- recommendationRationale: "Post-update evidence proves the implementation stayed inside packet authority and all cited validation checks passed.",
428
- expectedArtifacts: [`result-${wave.wave_id}-${reviewPolicy.requiredResultKind}.md`],
429
- nextCommandRef: commandRef([
430
- "result",
431
- "record",
432
- topicId,
433
- "--kind",
434
- reviewPolicy.requiredResultKind,
435
- "--verdict",
436
- reviewPolicy.passVerdict,
437
- "--from",
438
- mechanicalProof.sourceRef,
439
- "--verified-at",
440
- implementationResult.result.verified_at,
441
- ]),
442
- };
443
- }
444
- return {
445
- stopClass: "require_human_confirmation",
446
- recommendedAction: "record_result",
447
- reasonCode: "spec_update_review_required",
448
- recommendedDecision: "record_post_spec_update_judgement_before_wave_closeout",
449
- recommendationRationale: "This wave updated spec/authority truth; manager judgement is required before automatic wave closeout.",
450
- expectedArtifacts: [`result-${wave.wave_id}-${reviewPolicy.requiredResultKind}.md`],
451
- nextCommandRef: commandRef([
452
- "result",
453
- "record",
454
- topicId,
455
- "--kind",
456
- reviewPolicy.requiredResultKind,
457
- "--verdict",
458
- "<verdict>",
459
- "--from",
460
- "<path>",
461
- "--verified-at",
462
- "<utc>",
463
- ]),
464
- blockingChecks: [{
465
- ok: false,
466
- code: "mechanical_post_update_judgement_not_proven",
467
- message: mechanicalProof.reason,
468
- }],
469
- };
470
- }
471
-
472
- export function authorityConvergenceAuditInstructions(role) {
473
- return role === "audit"
474
- ? `
475
- Authority Convergence Audit:
476
- - Check implementation readiness, owner split, parallel truth, canonical vocabulary, and blocking deferred scope.
477
- - Do not implement code, edit spec, or decide semantic acceptance.
478
- - Return PASS, NEEDS_REVISION, or FAIL with blocking_findings, concerns, deferred_non_blockers, authority_refs, and ready_for_implementation.
479
- `
480
- : "";
481
- }
482
-
483
- export function buildAuthorityConvergenceDecision({ topicId, wave, packet, auditResult, policy, commandRef }) {
484
- if (packet.status !== "dispatched") {
485
- return {
486
- stopClass: "continue",
487
- recommendedAction: "dispatch_audit",
488
- reasonCode: "authority_convergence_audit_required",
489
- recommendedDecision: "dispatch_authority_convergence_auditor",
490
- recommendationRationale: "This packet changes or anchors authority/spec truth.",
491
- expectedArtifacts: [`prompt-${packet.packet_id}-audit.md`],
492
- nextCommandRef: commandRef(["audit", "dispatch", topicId, "--packet", packet.packet_id]),
493
- };
494
- }
495
- if (auditResult?.result?.verdict === policy.passVerdict) {
496
- if (packet.packet_kind === "preflight") {
497
- return {
498
- stopClass: "require_human_confirmation",
499
- recommendedAction: "freeze_packet",
500
- reasonCode: "preflight_authority_audit_passed_requires_implementation_packet",
501
- recommendedDecision: "create_or_select_an_implementation_ready_packet_before_worker_dispatch",
502
- recommendationRationale: "The authority convergence audit passed for a preflight packet, but preflight evidence is not implementation admission.",
503
- expectedArtifacts: ["packet-<implementation-ready-packet-id>.md"],
504
- nextCommandRef: commandRef(["packet", "freeze", topicId, "--from", "<implementation-ready-draft-packet>"]),
505
- };
506
- }
507
- if (wave.state === "preflight_admitted") {
508
- return {
509
- stopClass: "continue",
510
- recommendedAction: "record_result",
511
- reasonCode: "implementation_admission_result_required",
512
- recommendedDecision: "record_preflight_pass_before_worker_dispatch",
513
- recommendationRationale: "The authority convergence audit passed, but the selected wave must explicitly enter implementation admission before worker dispatch.",
514
- expectedArtifacts: [`result-${wave.wave_id}-preflight.md`],
515
- nextCommandRef: commandRef([
516
- "result",
517
- "record",
518
- topicId,
519
- "--kind",
520
- "preflight",
521
- "--verdict",
522
- policy.passVerdict,
523
- "--from",
524
- auditResult.result.source_ref ?? "<authority-convergence-audit-source>",
525
- "--verified-at",
526
- auditResult.result.verified_at ?? "<utc>",
527
- ]),
528
- };
529
- }
530
- return {
531
- stopClass: "continue",
532
- recommendedAction: "dispatch_worker",
533
- reasonCode: "authority_convergence_audit_passed",
534
- recommendedDecision: "dispatch_the_selected_packet_to_the_worker",
535
- recommendationRationale: "The authority convergence audit passed.",
536
- expectedArtifacts: [`prompt-${packet.packet_id}-worker.md`],
537
- nextCommandRef: commandRef(["worker", "dispatch", topicId, "--packet", packet.packet_id]),
538
- };
539
- }
540
- if (auditResult && policy.blockedVerdicts.includes(auditResult.result?.verdict)) {
541
- return {
542
- stopClass: "blocked",
543
- recommendedAction: "open_remediation",
544
- reasonCode: "authority_convergence_audit_failed",
545
- recommendedDecision: "revise_authority_packet_before_implementation_dispatch",
546
- recommendationRationale: "The latest authority convergence audit result blocks implementation dispatch.",
547
- blockingChecks: [{
548
- id: "authority_convergence_audit_verdict",
549
- ok: false,
550
- reason: `audit verdict is ${auditResult.result?.verdict}`,
551
- }],
552
- nextCommandRef: commandRef([
553
- "remediation",
554
- "open",
555
- topicId,
556
- "--kind",
557
- "a",
558
- "--reason",
559
- "authority-convergence",
560
- ]),
561
- };
562
- }
563
- return {
564
- stopClass: "await_external_evidence",
565
- recommendedAction: "record_result",
566
- reasonCode: "awaiting_authority_convergence_audit_result",
567
- recommendedDecision: "record_the_authority_convergence_audit_result_when_available",
568
- recommendationRationale: "The authority convergence audit must be recorded before implementation dispatch.",
569
- expectedArtifacts: [`result-${wave.wave_id}-${policy.requiredResultKind}.md`],
570
- nextCommandRef: commandRef([
571
- "result",
572
- "record",
573
- topicId,
574
- "--kind",
575
- policy.requiredResultKind,
576
- "--verdict",
577
- "<verdict>",
578
- "--from",
579
- "<path>",
580
- "--verified-at",
581
- "<utc>",
582
- ]),
583
- };
584
- }
585
-
586
- function dispatchWorkerDecision(topicId, packet) {
587
- return {
588
- stopClass: "continue",
589
- recommendedAction: "dispatch_worker",
590
- reasonCode: "dispatchable_packet_available",
591
- recommendedDecision: "dispatch_the_selected_packet_to_the_worker",
592
- recommendationRationale: "A dispatchable packet exists for the admitted wave, so the next operational step is mechanical.",
593
- expectedArtifacts: [`prompt-${packet.packet_id}-worker.md`],
594
- nextCommandRef: null,
595
- };
596
- }
597
-
598
- function dispatchablePacketRank(packet) {
599
- const ranks = {
600
- candidate: 0,
601
- admitted: 1,
602
- preflight: 2,
603
- dispatched: 3,
604
- };
605
- return ranks[packet.status] ?? 99;
606
- }
607
-
608
- export async function buildPreImplementationDecision({
609
- projectRoot,
610
- loaded,
611
- wave,
612
- commandRef,
613
- listWavePackets,
614
- listWaveResults,
615
- findUniqueFreezableDraftPacket,
616
- loadTopicRuntimeAuthority,
617
- }) {
618
- const packets = await listWavePackets(loaded.topicDir, wave.wave_id);
619
- const dispatchable = packets
620
- .filter((entry) => ["candidate", "admitted", "preflight", "dispatched"].includes(entry.packet.status))
621
- .sort((left, right) => (
622
- dispatchablePacketRank(left.packet) - dispatchablePacketRank(right.packet)
623
- || left.packetRefName.localeCompare(right.packetRefName)
624
- ))[0];
625
- if (dispatchable) {
626
- const policy = await loadAuthorityConvergencePolicy(projectRoot);
627
- if (wave.state === "preflight_admitted" && needsAuthorityConvergenceAudit(loaded.topic, dispatchable.packet, policy)) {
628
- const auditResult = latestResultOfKind(await listWaveResults(loaded.topicDir, wave.wave_id), policy.requiredResultKind);
629
- return buildAuthorityConvergenceDecision({
630
- topicId: loaded.topicId,
631
- wave,
632
- packet: dispatchable.packet,
633
- auditResult,
634
- policy,
635
- commandRef,
636
- });
637
- }
638
- if (wave.state === "preflight_admitted") {
639
- return {
640
- stopClass: "require_human_confirmation",
641
- recommendedAction: "record_result",
642
- reasonCode: "implementation_admission_result_required",
643
- recommendedDecision: "record_preflight_pass_before_worker_dispatch",
644
- recommendationRationale: "A dispatchable implementation packet exists, but worker dispatch requires explicit implementation admission evidence.",
645
- expectedArtifacts: [`result-${wave.wave_id}-preflight.md`],
646
- nextCommandRef: commandRef([
647
- "result",
648
- "record",
649
- loaded.topicId,
650
- "--kind",
651
- "preflight",
652
- "--verdict",
653
- "PASS",
654
- "--from",
655
- "<implementation-readiness-evidence>",
656
- "--verified-at",
657
- "<utc>",
658
- ]),
659
- };
660
- }
661
- const decision = dispatchWorkerDecision(loaded.topicId, dispatchable.packet);
662
- decision.nextCommandRef = commandRef(["worker", "dispatch", loaded.topicId, "--packet", dispatchable.packet.packet_id]);
663
- return decision;
664
- }
665
-
666
- const autoDraft = await findUniqueFreezableDraftPacket(
667
- projectRoot,
668
- loaded,
669
- wave,
670
- await loadTopicRuntimeAuthority(projectRoot),
671
- );
672
- return autoDraft.ok
673
- ? {
674
- stopClass: "continue",
675
- recommendedAction: "freeze_packet",
676
- reasonCode: "draft_packet_ready",
677
- recommendedDecision: "freeze_packet",
678
- recommendationRationale: "One draft is freezeable.",
679
- expectedArtifacts: [`packet-${autoDraft.packet.packet_id}.md`],
680
- nextCommandRef: commandRef(["packet", "freeze", loaded.topicId, "--from", autoDraft.draftRef]),
681
- }
682
- : {
683
- stopClass: "require_human_confirmation",
684
- recommendedAction: "freeze_packet",
685
- reasonCode: autoDraft.reasonCode,
686
- recommendedDecision: "select_or_create_draft",
687
- recommendationRationale: "Draft packet is missing or ambiguous.",
688
- expectedArtifacts: ["packet-<packet-id>.md"],
689
- nextCommandRef: commandRef(["packet", "freeze", loaded.topicId, "--from", "<draft-packet>"]),
690
- };
691
- }
692
-
693
- export function buildDispatchPrompt(packet, topicId, role) {
694
- const auditInstructions = authorityConvergenceAuditInstructions(role);
695
- return `# ${role === "worker" ? "Worker" : "Audit"} Dispatch
696
- Topic: \`${topicId}\`
697
- Packet: \`${packet.packet_id}\`
698
- Wave: \`${packet.wave_id}\`
699
- Packet Kind: \`${packet.packet_kind}\`
700
- Role: \`${role}\`
701
- Authority Owner:
702
- ${(Array.isArray(packet.authority_owner) ? packet.authority_owner : []).map((entry) => `- ${entry}`).join(`
703
- `)}
704
- Canonical Seams:
705
- ${(Array.isArray(packet.canonical_seams) ? packet.canonical_seams : []).map((entry) => `- ${entry}`).join(`
706
- `)}
707
- Forbidden Shortcuts:
708
- ${(Array.isArray(packet.forbidden_shortcuts) ? packet.forbidden_shortcuts : []).map((entry) => `- ${entry}`).join(`
709
- `)}
710
- Acceptance Invariants:
711
- ${(Array.isArray(packet.acceptance_invariants) ? packet.acceptance_invariants : []).map((entry) => `- ${entry}`).join(`
712
- `)}
713
- Negative Tests:
714
- ${(Array.isArray(packet.negative_tests) ? packet.negative_tests : []).map((entry) => `- ${entry}`).join(`
715
- `)}
716
- Reopen Conditions:
717
- ${(Array.isArray(packet.reopen_conditions) ? packet.reopen_conditions : []).map((entry) => `- ${entry}`).join(`
718
- `)}
719
- ${auditInstructions}`;
720
- }