ruvnet-brain 4.0.1 → 4.0.4

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 (195) hide show
  1. package/.claude-plugin/marketplace.json +1 -0
  2. package/README.md +4 -4
  3. package/bin/install.mjs +303 -24
  4. package/console/CONTRACT.md +172 -0
  5. package/console/activity.js +753 -0
  6. package/console/app.js +4189 -0
  7. package/console/architecture.html +1221 -0
  8. package/console/assets/depth-1.webp +0 -0
  9. package/console/assets/depth-2.webp +0 -0
  10. package/console/assets/depth-3.webp +0 -0
  11. package/console/assets/harness-vs-plain.svg +259 -0
  12. package/console/assets/hero.webp +0 -0
  13. package/console/assets/memory.webp +0 -0
  14. package/console/assets/metaharness.svg +247 -0
  15. package/console/index.html +777 -0
  16. package/console/install-architecture.html +162 -0
  17. package/console/install-mockup.html +543 -0
  18. package/console/style.css +2144 -0
  19. package/console/tips.css +926 -0
  20. package/console/tips.html +858 -0
  21. package/console/tips.js +128 -0
  22. package/docs/RELEASE-NOTES-4.0.md +88 -0
  23. package/kb/model-requirements.mjs +37 -6
  24. package/keys/ruvnet-brain-signing.pub.pem +3 -0
  25. package/package.json +8 -22
  26. package/plugin/.claude-plugin/marketplace.json +1 -0
  27. package/plugin/.claude-plugin/plugin.json +2 -3
  28. package/plugin/.codex-plugin/plugin.json +1 -1
  29. package/plugin/commands/brain-console.md +2 -2
  30. package/plugin/commands/configure.md +3 -2
  31. package/plugin/commands/rvbc.md +4 -3
  32. package/plugin/commands/rvcb.md +2 -2
  33. package/plugin/commands/whats-new.md +6 -6
  34. package/plugin/docs/RELEASE-NOTES-4.0.md +88 -0
  35. package/plugin/hooks/hooks.json +1 -2
  36. package/plugin/mcp/managed-cli-interface.mjs +47 -4
  37. package/plugin/mcp/server.mjs +90 -32
  38. package/plugin/scripts/detach.mjs +14 -0
  39. package/plugin/scripts/first-session-worker.mjs +38 -0
  40. package/plugin/scripts/ground-ruvnet.sh +16 -6
  41. package/plugin/scripts/hook-shim.mjs +34 -29
  42. package/plugin/scripts/learn-capture.sh +22 -3
  43. package/plugin/scripts/learn-flush.mjs +21 -4
  44. package/plugin/scripts/runtime-preferences.mjs +269 -0
  45. package/plugin/scripts/session-start-core.mjs +503 -0
  46. package/plugin/scripts/session-start.sh +3 -858
  47. package/plugin/scripts/whats-new.mjs +42 -0
  48. package/plugin/skills/brain-console/SKILL.md +4 -2
  49. package/plugin/skills/release-proof/SKILL.md +98 -0
  50. package/plugin/skills/release-proof/agents/openai.yaml +4 -0
  51. package/plugin/skills/release-proof/references/receipt-contract.md +44 -0
  52. package/plugin/skills/release-proof/scripts/release-proof.mjs +286 -0
  53. package/plugin/skills/ruvnet-brain/PLAYBOOK.md +5 -1
  54. package/plugin/skills/ruvnet-brain/SKILL.md +22 -7
  55. package/plugin/skills/rvbc/SKILL.md +9 -6
  56. package/plugin/skills/whats-new/SKILL.md +4 -4
  57. package/scripts/adr-backfill.mjs +107 -0
  58. package/scripts/advocacy-outcomes.mjs +808 -0
  59. package/scripts/agentdb-context.mjs +216 -0
  60. package/scripts/agentdb-fleet-doctor.mjs +101 -0
  61. package/scripts/ascii-drift.mjs +236 -0
  62. package/scripts/behavioral-l1-l4.mjs +210 -0
  63. package/scripts/brain-capability-check.mjs +72 -0
  64. package/scripts/brain-grade-groundtruth.mjs +100 -0
  65. package/scripts/brain-latency-50.mjs +227 -0
  66. package/scripts/brain-novice-50.mjs +189 -0
  67. package/scripts/brain-stamp.mjs +94 -0
  68. package/scripts/brain-state.mjs +212 -0
  69. package/scripts/build-bundle.mjs +531 -0
  70. package/scripts/build-concepts.mjs +132 -0
  71. package/scripts/build-l2.mjs +71 -0
  72. package/scripts/build-primer.mjs +73 -0
  73. package/scripts/build-symbols.mjs +68 -0
  74. package/scripts/calibrate-router.mjs +97 -0
  75. package/scripts/capability-audit.mjs +321 -0
  76. package/scripts/capability-registry.mjs +876 -0
  77. package/scripts/check-indexation.mjs +108 -0
  78. package/scripts/check-legibility.mjs +189 -0
  79. package/scripts/ci/build-fixture-kb.mjs +67 -0
  80. package/scripts/ci/learning-replay-codex-adapter.mjs +62 -0
  81. package/scripts/ci/learning-replay-recorder.mjs +59 -0
  82. package/scripts/ci/mutate-hook-timeout.mjs +70 -0
  83. package/scripts/ci/stranger-fixture-stage.mjs +17 -0
  84. package/scripts/ci/stranger-scenario.mjs +228 -0
  85. package/scripts/ci/stranger-timeout.mjs +25 -0
  86. package/scripts/ci-verdict.mjs +29 -0
  87. package/scripts/claims-verify.mjs +710 -0
  88. package/scripts/clear-claude-tmp.sh +31 -0
  89. package/scripts/console-engine.mjs +434 -0
  90. package/scripts/console-engine.test.mjs +125 -0
  91. package/scripts/corpus-qa.mjs +250 -0
  92. package/scripts/correction-detect-embed.mjs +346 -0
  93. package/scripts/correction-detect-measure.mjs +270 -0
  94. package/scripts/correction-detect.mjs +686 -0
  95. package/scripts/count-chunks.mjs +54 -0
  96. package/scripts/described-questions.json +30 -0
  97. package/scripts/design-grade.mjs +58 -0
  98. package/scripts/dev-plugin-link.sh +105 -0
  99. package/scripts/distill-project.mjs +200 -0
  100. package/scripts/doc-currency.mjs +801 -0
  101. package/scripts/eval-brain.mjs +244 -0
  102. package/scripts/fix-metaharness-memretrieve.mjs +121 -0
  103. package/scripts/fix-workstream.mjs +291 -0
  104. package/scripts/full-hints.mjs +87 -0
  105. package/scripts/gate.sh +39 -0
  106. package/scripts/gates.mjs +146 -0
  107. package/scripts/gen-console-images.mjs +54 -0
  108. package/scripts/gen-images.mjs +47 -0
  109. package/scripts/git-clone-refresh.mjs +52 -0
  110. package/scripts/git-hooks/pre-push +126 -0
  111. package/scripts/goal-match.mjs +398 -0
  112. package/scripts/goldie-research.mjs +223 -0
  113. package/scripts/goldie-weekly.sh +67 -0
  114. package/scripts/health-repair.mjs +237 -0
  115. package/scripts/helix-scenario-questions.json +10 -0
  116. package/scripts/ingest-gists.mjs +230 -0
  117. package/scripts/ingest-meeting.mjs +115 -0
  118. package/scripts/ingest-repo.mjs +79 -0
  119. package/scripts/install-npx-witness.sh +49 -0
  120. package/scripts/issue-fix.mjs +558 -0
  121. package/scripts/issue-watch.mjs +276 -0
  122. package/scripts/issue4-close-note.md +31 -0
  123. package/scripts/key-canary.mjs +91 -0
  124. package/scripts/latency-to-surface.mjs +233 -0
  125. package/scripts/learning-enable.mjs +380 -0
  126. package/scripts/learning-replay.mjs +1570 -0
  127. package/scripts/learnings.mjs +62 -0
  128. package/scripts/lesson-gate.mjs +680 -0
  129. package/scripts/lesson-lifecycle.mjs +449 -0
  130. package/scripts/lesson-promote.mjs +262 -0
  131. package/scripts/lesson-ratify.mjs +98 -0
  132. package/scripts/lesson-seed.mjs +252 -0
  133. package/scripts/lesson-store.mjs +447 -0
  134. package/scripts/loop-checkpoint.mjs +86 -0
  135. package/scripts/memdb-health.sh +14 -0
  136. package/scripts/memory-doctor.mjs +326 -0
  137. package/scripts/model-catalog.mjs +79 -0
  138. package/scripts/nightly-controller.mjs +66 -0
  139. package/scripts/nightly-gists.sh +72 -0
  140. package/scripts/nightly-wrapper.sh +172 -0
  141. package/scripts/notify.sh +12 -0
  142. package/scripts/npx-witness.sh +56 -0
  143. package/scripts/onboarding-console.mjs +2922 -0
  144. package/scripts/private-fence.mjs +69 -0
  145. package/scripts/proactivity-metrics.mjs +118 -0
  146. package/scripts/proof-questions.json +56 -0
  147. package/scripts/protected-release-invocation.mjs +76 -0
  148. package/scripts/prove.mjs +95 -0
  149. package/scripts/proxy/claude-proxied.sh +57 -0
  150. package/scripts/proxy/proxy-revert.sh +59 -0
  151. package/scripts/proxy/proxy-up.sh +60 -0
  152. package/scripts/proxy/proxy-verify.mjs +142 -0
  153. package/scripts/publication-receipt.mjs +307 -0
  154. package/scripts/published-surface-probe.mjs +241 -0
  155. package/scripts/qe/card-lane-gate.mjs +162 -0
  156. package/scripts/qe/session-start-gate.mjs +229 -0
  157. package/scripts/qe/ux-suite.mjs +323 -0
  158. package/scripts/reconcile-project.mjs +0 -0
  159. package/scripts/record-lesson.mjs +113 -0
  160. package/scripts/refresh-model-catalog.mjs +99 -0
  161. package/scripts/release-authority.mjs +93 -0
  162. package/scripts/release-proof.mjs +9 -0
  163. package/scripts/release-vector.mjs +281 -0
  164. package/scripts/release.mjs +439 -0
  165. package/scripts/remedy-registry.mjs +247 -0
  166. package/scripts/rerank-cap-eval.mjs +265 -0
  167. package/scripts/rerank-cap-warm-ab.mjs +129 -0
  168. package/scripts/route-cheap.mjs +20 -15
  169. package/scripts/router-utilization.mjs +182 -0
  170. package/scripts/routing-flywheel.mjs +596 -0
  171. package/scripts/rvf-generation.mjs +104 -0
  172. package/scripts/rvf-index-audit.mjs +138 -0
  173. package/scripts/self-update.mjs +296 -0
  174. package/scripts/selfcheck.mjs +7 -1
  175. package/scripts/sign-bundle.mjs +69 -0
  176. package/scripts/signal-watch.mjs +171 -0
  177. package/scripts/stabilization-receipt.mjs +108 -0
  178. package/scripts/stack-sync.mjs +469 -0
  179. package/scripts/stamp-existing-rvf-generations.mjs +53 -0
  180. package/scripts/stamp-sweep.mjs +144 -0
  181. package/scripts/status-honesty.mjs +102 -0
  182. package/scripts/sync-version.mjs +217 -0
  183. package/scripts/token-report.mjs +102 -0
  184. package/scripts/top100-benchmark.mjs +479 -0
  185. package/scripts/top100-corpus.mjs +112 -0
  186. package/scripts/top100-semantic-assertions.mjs +449 -0
  187. package/scripts/update-apply.mjs +9 -0
  188. package/scripts/upgrade-notice.mjs +14 -0
  189. package/scripts/verify-bundle.mjs +51 -0
  190. package/scripts/verify-channels.mjs +184 -0
  191. package/scripts/verify-model-catalog.mjs +104 -0
  192. package/scripts/verify-nightly-close-issue4.sh +31 -0
  193. package/scripts/version.mjs +40 -0
  194. package/scripts/wired-check.mjs +867 -0
  195. package/plugin/scripts/finalize-token-meter.mjs +0 -25
@@ -0,0 +1,439 @@
1
+ #!/usr/bin/env node
2
+ // scripts/release.mjs — the DEFINITION OF DONE. The only path to the word "shipped."
3
+ //
4
+ // WHY (2026-07-17, Stuart): "You should be able to take the applied knowledge and build it into a set
5
+ // of criteria that you always use, not a bunch of suggestions you choose to ignore." Every failure
6
+ // this session was an ASSUMPTION that survived because the check was a suggestion, not a gate. This
7
+ // script turns the checklist into a gate: it runs the criteria in order, STOPS on the first failure,
8
+ // and only prints "SHIPPED" when every channel a user touches is proven current and working. There is
9
+ // no "I think it's fine" — there is pass or fail.
10
+ //
11
+ // It is idempotent and safe to re-run. Each step verifies the REAL artifact (registry, live URL, the
12
+ // actual command), never the repo state. Repo state != user experience (the whole lesson).
13
+ //
14
+ // Usage:
15
+ // node scripts/release.mjs --check # run every gate READ-ONLY (no publish) — the pre-flight
16
+ // node scripts/release.mjs --publish # sync version, npm publish, then run every gate
17
+ // node scripts/release.mjs # same as --check
18
+ //
19
+ // The gates, in order (fail fast):
20
+ // A. version single-source-of-truth agrees (sync-version --check)
21
+ // B. full test suite green (npm test — the 60/60)
22
+ // C. narrative + unit gates (vitest) incl. the tag/entity-aware "What's new" check
23
+ // C+. [--publish only] push to origin/main — ONLY now that A–C are green (a red tree can't reach GitHub)
24
+ // D. [--publish only] build + sign bundle, create/update the exact-SHA GitHub Release,
25
+ // then npm publish + force `latest` to the shipping version
26
+ // E. verify-channels — the LIVE walk of npm / self-update manifest / release bundle+sig / explainer / git
27
+
28
+ import path from 'node:path';
29
+ import { fileURLToPath } from 'node:url';
30
+ import { spawnSync, execFileSync } from 'node:child_process';
31
+ import fs from 'node:fs';
32
+ import crypto from 'node:crypto';
33
+ import { validateProtectedPublishInvocation } from './protected-release-invocation.mjs';
34
+
35
+ const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
36
+ const PUBLISH = process.argv.includes('--publish');
37
+ let protectedCandidate = null;
38
+ let sealedPackageArtifact = null;
39
+ let publicationReceiptPath = null;
40
+ let protectedReleaseMode = 'strict';
41
+ const c = { g: (s) => `\x1b[32m${s}\x1b[0m`, r: (s) => `\x1b[31m${s}\x1b[0m`, y: (s) => `\x1b[33m${s}\x1b[0m`, b: (s) => `\x1b[1m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m` };
42
+ const V = () => JSON.parse(fs.readFileSync(path.join(ROOT, 'plugin/.claude-plugin/plugin.json'), 'utf8')).version;
43
+
44
+ function step(n, label) { process.stdout.write(`\n${c.b('▸ ' + n)} ${label}\n`); }
45
+ function runOrDie(label, cmd, args, opts = {}) {
46
+ const r = spawnSync(cmd, args, { cwd: ROOT, stdio: 'inherit', ...opts });
47
+ if (r.error || r.status !== 0) {
48
+ console.error(`\n${c.r('✗ GATE FAILED: ' + label)} ${c.dim('(' + cmd + ' ' + args.join(' ') + ' → ' + (r.error ? r.error.message : 'exit ' + r.status) + ')')}`);
49
+ console.error(`${c.r(' NOT shipped. Fix this, then re-run. No assumptions past a red gate.')}\n`);
50
+ process.exit(1);
51
+ }
52
+ }
53
+
54
+ function remoteTagCommit(tag) {
55
+ const out = execFileSync('git', [
56
+ 'ls-remote', 'origin', `refs/tags/${tag}`, `refs/tags/${tag}^{}`,
57
+ ], { cwd: ROOT, encoding: 'utf8' }).trim();
58
+ if (!out) return '';
59
+ const rows = out.split('\n').map((line) => line.trim().split(/\s+/));
60
+ return rows.find(([, ref]) => ref?.endsWith('^{}'))?.[0] || rows[0]?.[0] || '';
61
+ }
62
+
63
+ function recordReleaseTransaction(state, data) {
64
+ const file = path.join(ROOT, 'dist', 'release-transaction.json');
65
+ fs.mkdirSync(path.dirname(file), { recursive: true });
66
+ const next = {
67
+ state,
68
+ updatedAt: new Date().toISOString(),
69
+ ...data,
70
+ };
71
+ const tmp = `${file}.tmp-${process.pid}`;
72
+ fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
73
+ fs.renameSync(tmp, file);
74
+ }
75
+
76
+ function readReleaseTransaction() {
77
+ try {
78
+ return JSON.parse(fs.readFileSync(path.join(ROOT, 'dist', 'release-transaction.json'), 'utf8'));
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ console.log(`\n${c.b('RuvNet Brain — release / definition-of-done')} ${c.dim('· ' + (PUBLISH ? 'PUBLISH' : 'check-only') + ' · shipping ' + V())}\n`);
85
+
86
+ // The local CLI remains useful as a read-only preflight, but publication authority lives only in
87
+ // the reviewer-protected workflow. Validate the exact candidate receipt and artifact bytes before
88
+ // any command capable of pushing, tagging, releasing, or publishing can run.
89
+ if (PUBLISH) {
90
+ const protectedInvocation = validateProtectedPublishInvocation({ root: ROOT });
91
+ if (protectedInvocation.verdict !== 'PASS') {
92
+ console.error(`\n${c.r('✗ PROTECTED RELEASE GATE FAILED')}`);
93
+ for (const failure of protectedInvocation.failures) console.error(` ${failure}`);
94
+ console.error(`${c.r(' NOT shipped. Run the protected-release workflow with exact candidate evidence.')}\n`);
95
+ process.exit(1);
96
+ }
97
+ protectedReleaseMode = protectedInvocation.mode;
98
+ protectedCandidate = JSON.parse(fs.readFileSync(path.resolve(ROOT, process.env.RUVNET_CANDIDATE_RECEIPT), 'utf8'));
99
+ sealedPackageArtifact = path.resolve(ROOT, protectedCandidate.artifact.path);
100
+ publicationReceiptPath = path.resolve(ROOT, process.env.RUVNET_PUBLICATION_RECEIPT || '.missing-publication-receipt');
101
+ const evidenceRoot = path.join(ROOT, 'release-evidence');
102
+ if (!publicationReceiptPath.startsWith(`${evidenceRoot}${path.sep}`) || fs.existsSync(publicationReceiptPath)) {
103
+ console.error(`\n${c.r('✗ PROTECTED RELEASE GATE FAILED')}\n publication receipt output must be a new file inside release-evidence\n`);
104
+ process.exit(1);
105
+ }
106
+ }
107
+
108
+ // A verdict is only about the exact committed candidate. Check-only used to permit a dirty tree
109
+ // while publish checked cleanliness much later, so preflight could certify bytes that would never
110
+ // ship. Both modes now bind to the same committed tree before any expensive gate runs.
111
+ const initialDirty = execFileSync('git', ['-C', ROOT, 'status', '--porcelain'], { encoding: 'utf8' }).trim();
112
+ if (initialDirty) {
113
+ console.error(`\n${c.r('✗ GATE FAILED: working tree not clean')} ${c.dim('— preflight and publish both certify committed bytes only.')}`);
114
+ console.error(initialDirty.split('\n').slice(0, 10).map((l) => ' ' + l).join('\n'));
115
+ process.exit(1);
116
+ }
117
+
118
+ // A. version single source of truth
119
+ step('A', 'version single-source-of-truth agrees across every surface');
120
+ runOrDie('version sync', process.execPath, ['scripts/sync-version.mjs', '--check']);
121
+ runOrDie('one protected publisher', process.execPath, ['scripts/release-authority.mjs']);
122
+
123
+ // WIRED-CHECK — refuses to ship a module with zero callers.
124
+ //
125
+ // Added 2026-07-22 after this project shipped built-tested-unwired code SEVEN times in one session
126
+ // (capability-registry, capability-audit, lesson-gate's five triggers, anticipate.sh,
127
+ // advocacy-outcomes, lesson-promote's demotion, continuation-gate's global path). Every one had
128
+ // passing tests, because a test imports the module directly — the one caller that proves nothing
129
+ // about whether the product uses it. Every one was found by a human running grep, hours later.
130
+ //
131
+ // Seven repetitions of one mistake is not a discipline problem; discipline is what failed. So it
132
+ // becomes a gate, on the ship path, where this repo's gates run 8/8 against prose's 0/6.
133
+ runOrDie('wired (no orphan modules)', process.execPath, ['scripts/wired-check.mjs', '--check']);
134
+
135
+ // THE NORTH-STAR PROMOTION VECTOR — strict/check-only releases may not average one broken or
136
+ // unknown invariant into a pass. The separately authorized stabilization class makes no 95 claim;
137
+ // it retains every safety, test, artifact, publication, and post-publication gate below while the
138
+ // promotion program remains open. Derive this only from the already-validated sealed receipt, never
139
+ // from a free-standing environment toggle.
140
+ if (protectedReleaseMode === 'strict') {
141
+ runOrDie('release vector (all critical invariants PASS)', process.execPath, ['scripts/release-vector.mjs']);
142
+
143
+ // The Top-100 corpus spans naive through expert prompts and grades semantic clauses, citations,
144
+ // abstention, and latency. A manual-only benchmark is a report; a strict release-path benchmark
145
+ // is a guarantee. The benchmark itself fails closed unless all 100 canonical questions run.
146
+ runOrDie('Top-100 source-grounded recall contract', process.execPath, ['scripts/top100-benchmark.mjs', '--no-write']);
147
+ } else {
148
+ console.log(c.y(' strict >=95 promotion gates: NOT CLAIMED (sealed stabilization; scoreClaimed:false)'));
149
+ }
150
+
151
+ // A2. Stable Spine restart classifier (ADR-023, red-team finding 18): diff the boot-frozen SHELL
152
+ // (hooks.json, hook-shim, MCP server, .mcp.json, skills/, commands/) against the previous release
153
+ // tag and SAY OUT LOUD whether this release needs a restart. The classification is computed, never
154
+ // remembered — the same shellDiff logic runs client-side in update-apply.mjs at every flip, so the
155
+ // user-facing nag stays honest even if this print is ignored. Informational at ship time; the
156
+ // releasing human sees exactly which shell files changed.
157
+ step('A2', 'Stable Spine — does this release change the boot-frozen shell? (requiresRestart classifier)');
158
+ {
159
+ const { execFileSync } = await import('node:child_process');
160
+ const SHELL = ['plugin/hooks/hooks.json', 'plugin/scripts/hook-shim.mjs', 'plugin/mcp/server.mjs', 'plugin/.mcp.json', 'plugin/skills', 'plugin/commands'];
161
+ let prevTag = '';
162
+ try { prevTag = execFileSync('git', ['describe', '--tags', '--abbrev=0'], { encoding: 'utf8' }).trim(); } catch { /* no tags yet */ }
163
+ if (!prevTag) {
164
+ console.log(c.dim(' no previous release tag — classifier has no baseline (first spine release: requiresRestart=true by definition)'));
165
+ } else {
166
+ let changed = [];
167
+ try {
168
+ const out = execFileSync('git', ['diff', '--name-only', `${prevTag}..HEAD`, '--', ...SHELL], { encoding: 'utf8' }).trim();
169
+ changed = out ? out.split('\n') : [];
170
+ } catch { /* diff failure = unknown; say so, never guess green */ changed = ['(diff failed — treat as changed)']; }
171
+ if (changed.length) {
172
+ console.log(` ${c.y('requiresRestart: TRUE')} — shell changed vs ${prevTag}:`);
173
+ for (const f of changed) console.log(` · ${f}`);
174
+ console.log(c.dim(' users get ONE honest restart notice (session-start reads active.json.shellChanged); everything else is live.'));
175
+ } else {
176
+ console.log(` ${c.g('requiresRestart: false')} — no shell change vs ${prevTag}; this release goes fully live with zero restarts.`);
177
+ }
178
+ }
179
+ }
180
+
181
+ // B. the full brain test suite (the 60/60)
182
+ step('B', 'full test suite (npm test)');
183
+ runOrDie('npm test', 'npm', ['test']);
184
+
185
+ // C. unit gates — narrative-version (tag/entity aware), claims, etc.
186
+ step('C', 'unit gates (vitest) — narrative version, claims, guards');
187
+ runOrDie('vitest unit', 'npx', ['vitest', 'run', 'tests/unit']);
188
+
189
+ // C+. PUSH — only now that A–C are green (publish only). Pushing AFTER the local gates is the fix
190
+ // for the drift that bit on 2026-07-18: a commit was pushed FIRST, then release.mjs's gate B caught a
191
+ // failing plugin-battery test, leaving GitHub at 3.4.10-dev while npm sat at 3.4.9-dev — the exact
192
+ // "pushed but didn't finish" split. The pre-push git hook only checks version/manifest (fast, always),
193
+ // so tests must gate the push HERE. A red tree can no longer reach origin ahead of npm.
194
+ if (PUBLISH) {
195
+ // C++. REMOTE CI IS A SHIP GATE (ADR-053 §5). Between 2026-07-21 and 07-26 the `ci` workflow was
196
+ // red for ~70 consecutive runs — six releases shipped right past it, because nothing on the ship
197
+ // path ever ASKED the remote verdict. Local gates prove this machine; only CI proves ubuntu and
198
+ // windows. So the latest COMPLETED run on origin/main must be green before we add commits on top
199
+ // and publish. (The current commit's own run starts after the push — this gate is "never build on
200
+ // a known-broken main", not "wait for my own run".) Escape hatch for a genuine hotfix:
201
+ // --ci-override "<reason>" — printed into the release log, never silent.
202
+ step('C++', 'remote CI on origin/main is green (the ubuntu+windows verdict this machine cannot produce)');
203
+ {
204
+ const { fetchLatestCiVerdict, assessCiGate } = await import('./ci-verdict.mjs');
205
+ const OVERRIDE_IX = process.argv.indexOf('--ci-override');
206
+ const overrideReason = OVERRIDE_IX >= 0 ? (process.argv[OVERRIDE_IX + 1] || '(no reason given)') : null;
207
+ const { verdict, sha } = await fetchLatestCiVerdict();
208
+ const gate = assessCiGate(verdict, overrideReason);
209
+ if (gate === 'ship') {
210
+ console.log(c.dim(` latest completed ci run on origin/main: success (${sha})`));
211
+ } else if (gate === 'override') {
212
+ console.log(` ${c.y('! CI gate OVERRIDDEN')} — verdict was ${verdict ?? 'unknown'} (${sha || 'no run found'}); reason: ${overrideReason}`);
213
+ } else {
214
+ console.error(`\n${c.r('✗ GATE FAILED: remote CI on origin/main is ' + (verdict ?? 'unknown'))} ${c.dim('(' + (sha || 'no completed run found') + ')')}`);
215
+ console.error(`${c.r(' A red or unknown main does not get shipped on top of. Fix CI first (gh run list --workflow ci.yml),')}`);
216
+ console.error(`${c.r(' or for a genuine hotfix: --ci-override "<reason>" (the reason is printed into the release log).')}\n`);
217
+ process.exit(1);
218
+ }
219
+ }
220
+
221
+ step('C+', 'push to origin/main — safe now that A–C passed');
222
+ let ahead = '0';
223
+ try { ahead = execFileSync('git', ['-C', ROOT, 'rev-list', '--count', 'origin/main..HEAD'], { encoding: 'utf8' }).trim(); } catch { /* origin/main ref missing — push will resolve */ ahead = '?'; }
224
+ if (ahead === '0') console.log(c.dim(' nothing to push — HEAD already on origin/main'));
225
+ else runOrDie('git push', 'git', ['-C', ROOT, 'push', 'origin', 'main']);
226
+ }
227
+
228
+ // D. Publish BOTH delivery channels. This used to advance npm without creating the GitHub Release
229
+ // that verify-channels immediately required, making the sanctioned manual ship path impossible to
230
+ // complete. Build and sign first, then create/update the exact-SHA Release before npm advances.
231
+ // Re-runs are idempotent: a matching Release gets its three assets replaced; a tag bound to any
232
+ // other commit is a hard provenance failure.
233
+ if (PUBLISH) {
234
+ const v = V();
235
+ const tag = `v${v}`;
236
+ const zip = path.join(ROOT, 'dist', 'ruvnet-brain.zip');
237
+ const assets = [zip, `${zip}.sig`, `${zip}.sha256`, sealedPackageArtifact];
238
+ const head = execFileSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
239
+ const priorTxn = readReleaseTransaction();
240
+ const unfinished = priorTxn && priorTxn.state !== 'channels-converged';
241
+ const samePendingCandidate = unfinished && priorTxn.tag === tag && priorTxn.head === head;
242
+
243
+ step('D', 'build + sign bundle and publish matching GitHub/npm channels');
244
+ if (unfinished && !samePendingCandidate) {
245
+ console.error(`\n${c.r('✗ GATE FAILED: unfinished release transaction requires reconciliation')}`);
246
+ console.error(c.dim(` ${priorTxn.state}: ${priorTxn.tag || '?'} @ ${priorTxn.head || '?'}; refusing to overwrite it with ${tag} @ ${head}`));
247
+ process.exit(1);
248
+ }
249
+ if (samePendingCandidate) {
250
+ if (!assets.every((asset) => fs.existsSync(asset))) {
251
+ console.error(`\n${c.r('✗ GATE FAILED: pending release assets are missing; reconcile before retrying')}`);
252
+ process.exit(1);
253
+ }
254
+ const declared = fs.readFileSync(`${zip}.sha256`, 'utf8').trim().split(/\s+/)[0];
255
+ const actual = crypto.createHash('sha256').update(fs.readFileSync(zip)).digest('hex');
256
+ const verify = spawnSync(process.execPath, ['scripts/verify-bundle.mjs', zip, `${zip}.sig`], {
257
+ cwd: ROOT, encoding: 'utf8',
258
+ });
259
+ if (declared !== priorTxn.bundleSha256 || actual !== declared || verify.status !== 0) {
260
+ console.error(`\n${c.r('✗ GATE FAILED: pending release assets do not match their signed transaction')}`);
261
+ process.exit(1);
262
+ }
263
+ console.log(c.dim(' resume existing signed release assets for the pending candidate'));
264
+ } else {
265
+ const buildArgs = ['scripts/build-bundle.mjs', '--version', tag];
266
+ if (process.env.RUVNET_RELEASE_ASSETS) buildArgs.push('--assets', process.env.RUVNET_RELEASE_ASSETS);
267
+ runOrDie('build release bundle', process.execPath, buildArgs);
268
+ runOrDie('sign release bundle', process.execPath, ['scripts/sign-bundle.mjs', '--bundle', zip]);
269
+ }
270
+ for (const asset of assets) {
271
+ if (!fs.existsSync(asset)) {
272
+ console.error(`\n${c.r('✗ GATE FAILED: signed release asset missing')} ${c.dim(asset)}`);
273
+ process.exit(1);
274
+ }
275
+ }
276
+ const bundleSha256 = fs.readFileSync(`${zip}.sha256`, 'utf8').trim().split(/\s+/)[0];
277
+ if (!/^[a-f0-9]{64}$/i.test(bundleSha256)) {
278
+ console.error(`\n${c.r('✗ GATE FAILED: release digest is not a SHA-256 value')}`);
279
+ process.exit(1);
280
+ }
281
+
282
+ let remoteTagSha = '';
283
+ try {
284
+ remoteTagSha = remoteTagCommit(tag);
285
+ } catch (e) {
286
+ console.error(`\n${c.r('✗ GATE FAILED: could not verify remote release tag')} ${c.dim(String(e.message || e).split('\n')[0])}`);
287
+ process.exit(1);
288
+ }
289
+ if (remoteTagSha && remoteTagSha !== head) {
290
+ console.error(`\n${c.r('✗ GATE FAILED: release tag already identifies different bytes')}`);
291
+ console.error(c.dim(` ${tag} -> ${remoteTagSha}; candidate HEAD -> ${head}`));
292
+ process.exit(1);
293
+ }
294
+
295
+ // Cross-provider publication cannot be truly atomic. Persist the exact convergence state before
296
+ // the first remote mutation so a failed npm publish is recoverable and the next run can converge
297
+ // the SAME tag/HEAD instead of guessing which channel moved.
298
+ if (priorTxn && !['channels-converged'].includes(priorTxn.state)) {
299
+ const sameCandidate = priorTxn.tag === tag
300
+ && priorTxn.head === head
301
+ && priorTxn.bundleSha256 === bundleSha256;
302
+ if (!sameCandidate) {
303
+ console.error(`\n${c.r('✗ GATE FAILED: unfinished release transaction requires reconciliation')}`);
304
+ if (priorTxn.tag === tag && priorTxn.head === head && priorTxn.bundleSha256 !== bundleSha256) {
305
+ console.error(c.dim(' release transaction artifact digest changed for the same tag and HEAD'));
306
+ }
307
+ console.error(c.dim(` ${priorTxn.state}: ${priorTxn.tag || '?'} @ ${priorTxn.head || '?'}; refusing to overwrite it with ${tag} @ ${head}`));
308
+ process.exit(1);
309
+ }
310
+ }
311
+ recordReleaseTransaction('prepared', { version: v, tag, head, bundleSha256 });
312
+
313
+ let releaseExists = false;
314
+ try {
315
+ execFileSync('gh', ['release', 'view', tag, '--repo', 'stuinfla/ruvnet-brain'], {
316
+ cwd: ROOT, stdio: ['ignore', 'ignore', 'ignore'],
317
+ });
318
+ releaseExists = true;
319
+ } catch { /* absent is the expected first-publish state */ }
320
+
321
+ if (releaseExists) {
322
+ if (!remoteTagSha) {
323
+ console.error(`\n${c.r('✗ GATE FAILED: GitHub Release exists without a verifiable matching tag')} ${c.dim(tag)}`);
324
+ process.exit(1);
325
+ }
326
+ runOrDie('replace signed GitHub Release assets', 'gh', [
327
+ 'release', 'upload', tag, ...assets, '--clobber', '--repo', 'stuinfla/ruvnet-brain',
328
+ ]);
329
+ } else {
330
+ runOrDie('create signed GitHub Release', 'gh', [
331
+ 'release', 'create', tag, ...assets,
332
+ '--repo', 'stuinfla/ruvnet-brain',
333
+ '--target', head,
334
+ '--title', `${tag} — verified release`,
335
+ '--generate-notes',
336
+ '--latest',
337
+ ]);
338
+ }
339
+
340
+ // Confirm the tag GitHub created/retained points to the candidate before touching npm.
341
+ let publishedTagSha = '';
342
+ try {
343
+ publishedTagSha = remoteTagCommit(tag);
344
+ } catch { /* handled by the mismatch below */ }
345
+ if (publishedTagSha !== head) {
346
+ console.error(`\n${c.r('✗ GATE FAILED: published GitHub Release tag is not candidate HEAD')}`);
347
+ console.error(c.dim(` ${tag} -> ${publishedTagSha || '(missing)'}; candidate HEAD -> ${head}`));
348
+ process.exit(1);
349
+ }
350
+ recordReleaseTransaction('github-published-npm-pending', { version: v, tag, head, bundleSha256 });
351
+
352
+ let already = '';
353
+ try { already = execFileSync('npm', ['view', `ruvnet-brain@${v}`, 'version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { /* not published yet */ }
354
+ if (already === v) console.log(c.dim(` ${v} already on npm — skipping publish, just re-asserting the tag`));
355
+ // npm requires an explicit tag for prerelease versions. This project intentionally serves its
356
+ // `-dev` release from `latest`, so make that policy explicit on the publish command itself.
357
+ else runOrDie('npm publish', 'npm', ['publish', sealedPackageArtifact, '--tag', 'latest']);
358
+ // npm does NOT auto-move `latest` to a prerelease (x.y.z-dev) — force it, or `@latest` stays stale.
359
+ runOrDie('npm dist-tag latest', 'npm', ['dist-tag', 'add', `ruvnet-brain@${v}`, 'latest']);
360
+ recordReleaseTransaction('publish-complete-verification-pending', { version: v, tag, head, bundleSha256 });
361
+ } else {
362
+ step('D', 'GitHub Release + npm publish — SKIPPED (check-only; pass --publish to publish)');
363
+ }
364
+
365
+ // D+. THE DEPLOY-SURFACE SWEEP (owner standing order, 2026-07-27): "ALWAYS check GitHub CLI and
366
+ // Vercel CLI for gotchas with anything you're pushing. This needs to be part of the protocol you use
367
+ // whenever you deploy. I don't want to have to tell you this again."
368
+ //
369
+ // Gate C++ already asks whether CI passed. That is one surface. This asks the two CLIs what the
370
+ // PLATFORMS think — failing workflows other than our own ci, security advisories, and whether the
371
+ // production deployment that serves the explainer is actually Ready. Each is a question a human
372
+ // would otherwise have to remember to ask, which is the definition of a check that eventually
373
+ // doesn't happen.
374
+ //
375
+ // ADVISORY BY DESIGN, LOUD BY CONTRACT: this prints findings and does not exit non-zero, because a
376
+ // GitHub-side hiccup must not wedge a correct release — EXCEPT where it overlaps a hard gate that
377
+ // already exists (C++ for ci, E for the live explainer). Anything it finds is printed in full so it
378
+ // cannot be a diagnostic nobody reads.
379
+ step('D+', 'deploy-surface sweep — what GitHub and Vercel think about what we are pushing');
380
+ {
381
+ const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore','pipe','ignore'], timeout: 45000 }); } catch { return null; } };
382
+
383
+ // 1. Failing workflow runs that are NOT our ci (ci is gate C++'s job). issue-watch exits 1 BY
384
+ // DESIGN on an SLA breach, so it is reported as an SLA signal, never as a broken pipeline —
385
+ // conflating the two is how a permanently-red workflow trains everyone to ignore red.
386
+ const runs = sh('gh', ['run','list','--repo','stuinfla/ruvnet-brain','--limit','15','--json','name,conclusion,headBranch']);
387
+ if (runs) {
388
+ let bad = [];
389
+ try { bad = JSON.parse(runs).filter((r) => r.conclusion && r.conclusion !== 'success' && r.name !== 'ci'); } catch { /* unparseable — reported below */ }
390
+ const sla = bad.filter((r) => r.name === 'issue-watch');
391
+ const real = bad.filter((r) => r.name !== 'issue-watch');
392
+ if (sla.length) console.log(` ${c.y('! issue-watch red x' + sla.length)} ${c.dim('— by design: an open issue is past its 4h SLA. Answer the issue, do not fix the workflow.')}`);
393
+ if (real.length) console.log(` ${c.y('! non-ci workflows failing:')} ${real.map((r) => r.name).join(', ')}`);
394
+ if (!sla.length && !real.length) console.log(c.dim(' no failing workflows outside ci'));
395
+ } else console.log(c.dim(' gh unavailable — workflow sweep SKIPPED (not a pass)'));
396
+
397
+ // 2. Security advisories against what we ship.
398
+ const dep = sh('gh', ['api','repos/stuinfla/ruvnet-brain/dependabot/alerts','--jq','[.[]|select(.state=="open")]|length']);
399
+ if (dep !== null) {
400
+ const n = parseInt(dep.trim(), 10);
401
+ console.log(n > 0 ? ` ${c.r('! ' + n + ' open dependabot alert(s)')}` : c.dim(' 0 open dependabot alerts'));
402
+ } else console.log(c.dim(' dependabot query unavailable — SKIPPED (not a pass)'));
403
+
404
+ // 3. Vercel: the explainer is a shipped surface; a Ready production deployment is the precondition
405
+ // for gate E's live check meaning anything.
406
+ const vc = sh('vercel', ['ls','--yes']);
407
+ if (vc) {
408
+ const prod = vc.split('\n').find((l) => l.includes('Production'));
409
+ const ready = prod && /●\s*Ready/.test(prod);
410
+ console.log(ready ? c.dim(' vercel: latest production deployment Ready') : ` ${c.y('! vercel: latest production deployment is NOT Ready')} ${c.dim((prod||'').trim().slice(0,90))}`);
411
+ } else console.log(c.dim(' vercel CLI unavailable/not logged in — SKIPPED (not a pass)'));
412
+ }
413
+
414
+ // E. the live channel walk — THE gate that would have caught the stale-2.9.1 + 404
415
+ step('E', 'verify-channels — the live walk of every user path');
416
+ runOrDie('verify-channels', process.execPath, ['scripts/verify-channels.mjs']);
417
+ if (PUBLISH) {
418
+ runOrDie('publication receipt', process.execPath, [
419
+ 'scripts/publication-receipt.mjs', '--candidate', process.env.RUVNET_CANDIDATE_RECEIPT,
420
+ '--out', process.env.RUVNET_PUBLICATION_RECEIPT,
421
+ ]);
422
+ runOrDie('publication seal', process.execPath, [
423
+ 'scripts/release-proof.mjs', '--candidate', process.env.RUVNET_CANDIDATE_RECEIPT,
424
+ '--publication', process.env.RUVNET_PUBLICATION_RECEIPT,
425
+ ]);
426
+ const txn = readReleaseTransaction();
427
+ recordReleaseTransaction('channels-converged', {
428
+ version: V(),
429
+ tag: `v${V()}`,
430
+ head: execFileSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(),
431
+ bundleSha256: txn?.bundleSha256 ?? null,
432
+ });
433
+ }
434
+
435
+ if (PUBLISH) {
436
+ console.log(`\n${c.g(c.b('✓✓✓ SHIPPED'))} — every gate passed and every live channel is current. ${c.dim('A user on any path (npm, npx, explainer, --update) gets the working, current build.')}\n`);
437
+ } else {
438
+ console.log(`\n${c.g(c.b('✓✓✓ PREFLIGHT PASS — NOT PUBLISHED'))} — the committed candidate passed every check-only gate.\n`);
439
+ }