ruvnet-brain 4.0.1 → 4.0.2

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 (185) hide show
  1. package/.claude-plugin/marketplace.json +1 -0
  2. package/README.md +4 -4
  3. package/bin/install.mjs +100 -5
  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/hooks/hooks.json +1 -2
  34. package/plugin/mcp/managed-cli-interface.mjs +47 -4
  35. package/plugin/mcp/server.mjs +21 -0
  36. package/plugin/scripts/detach.mjs +14 -0
  37. package/plugin/scripts/first-session-worker.mjs +38 -0
  38. package/plugin/scripts/ground-ruvnet.sh +16 -6
  39. package/plugin/scripts/hook-shim.mjs +7 -7
  40. package/plugin/scripts/learn-capture.sh +22 -3
  41. package/plugin/scripts/learn-flush.mjs +21 -4
  42. package/plugin/scripts/runtime-preferences.mjs +269 -0
  43. package/plugin/scripts/session-start-core.mjs +477 -0
  44. package/plugin/scripts/session-start.sh +3 -858
  45. package/plugin/skills/brain-console/SKILL.md +4 -2
  46. package/plugin/skills/release-proof/SKILL.md +81 -0
  47. package/plugin/skills/release-proof/agents/openai.yaml +4 -0
  48. package/plugin/skills/release-proof/references/receipt-contract.md +38 -0
  49. package/plugin/skills/release-proof/scripts/release-proof.mjs +210 -0
  50. package/plugin/skills/ruvnet-brain/PLAYBOOK.md +5 -1
  51. package/plugin/skills/rvbc/SKILL.md +9 -6
  52. package/scripts/adr-backfill.mjs +107 -0
  53. package/scripts/advocacy-outcomes.mjs +808 -0
  54. package/scripts/agentdb-context.mjs +216 -0
  55. package/scripts/agentdb-fleet-doctor.mjs +101 -0
  56. package/scripts/ascii-drift.mjs +236 -0
  57. package/scripts/behavioral-l1-l4.mjs +210 -0
  58. package/scripts/brain-capability-check.mjs +72 -0
  59. package/scripts/brain-grade-groundtruth.mjs +100 -0
  60. package/scripts/brain-latency-50.mjs +227 -0
  61. package/scripts/brain-novice-50.mjs +189 -0
  62. package/scripts/brain-stamp.mjs +94 -0
  63. package/scripts/brain-state.mjs +212 -0
  64. package/scripts/build-bundle.mjs +522 -0
  65. package/scripts/build-concepts.mjs +132 -0
  66. package/scripts/build-l2.mjs +71 -0
  67. package/scripts/build-primer.mjs +73 -0
  68. package/scripts/build-symbols.mjs +68 -0
  69. package/scripts/calibrate-router.mjs +97 -0
  70. package/scripts/capability-audit.mjs +321 -0
  71. package/scripts/capability-registry.mjs +876 -0
  72. package/scripts/check-indexation.mjs +108 -0
  73. package/scripts/check-legibility.mjs +189 -0
  74. package/scripts/ci/build-fixture-kb.mjs +67 -0
  75. package/scripts/ci/learning-replay-codex-adapter.mjs +62 -0
  76. package/scripts/ci/learning-replay-recorder.mjs +59 -0
  77. package/scripts/ci/mutate-hook-timeout.mjs +70 -0
  78. package/scripts/ci/stranger-fixture-stage.mjs +17 -0
  79. package/scripts/ci/stranger-scenario.mjs +228 -0
  80. package/scripts/ci/stranger-timeout.mjs +25 -0
  81. package/scripts/ci-verdict.mjs +29 -0
  82. package/scripts/claims-verify.mjs +710 -0
  83. package/scripts/clear-claude-tmp.sh +31 -0
  84. package/scripts/console-engine.mjs +434 -0
  85. package/scripts/console-engine.test.mjs +125 -0
  86. package/scripts/corpus-qa.mjs +250 -0
  87. package/scripts/correction-detect-embed.mjs +346 -0
  88. package/scripts/correction-detect-measure.mjs +270 -0
  89. package/scripts/correction-detect.mjs +686 -0
  90. package/scripts/count-chunks.mjs +54 -0
  91. package/scripts/described-questions.json +30 -0
  92. package/scripts/design-grade.mjs +58 -0
  93. package/scripts/dev-plugin-link.sh +105 -0
  94. package/scripts/distill-project.mjs +200 -0
  95. package/scripts/doc-currency.mjs +801 -0
  96. package/scripts/eval-brain.mjs +244 -0
  97. package/scripts/fix-metaharness-memretrieve.mjs +121 -0
  98. package/scripts/full-hints.mjs +87 -0
  99. package/scripts/gate.sh +39 -0
  100. package/scripts/gates.mjs +146 -0
  101. package/scripts/gen-console-images.mjs +54 -0
  102. package/scripts/gen-images.mjs +47 -0
  103. package/scripts/git-clone-refresh.mjs +52 -0
  104. package/scripts/git-hooks/pre-push +126 -0
  105. package/scripts/goal-match.mjs +398 -0
  106. package/scripts/goldie-research.mjs +223 -0
  107. package/scripts/goldie-weekly.sh +67 -0
  108. package/scripts/health-repair.mjs +250 -0
  109. package/scripts/helix-scenario-questions.json +10 -0
  110. package/scripts/ingest-gists.mjs +230 -0
  111. package/scripts/ingest-meeting.mjs +115 -0
  112. package/scripts/ingest-repo.mjs +79 -0
  113. package/scripts/install-npx-witness.sh +49 -0
  114. package/scripts/issue-fix.mjs +639 -0
  115. package/scripts/issue-watch.mjs +276 -0
  116. package/scripts/issue4-close-note.md +31 -0
  117. package/scripts/key-canary.mjs +91 -0
  118. package/scripts/latency-to-surface.mjs +233 -0
  119. package/scripts/learning-enable.mjs +380 -0
  120. package/scripts/learning-replay.mjs +1570 -0
  121. package/scripts/learnings.mjs +62 -0
  122. package/scripts/lesson-gate.mjs +680 -0
  123. package/scripts/lesson-lifecycle.mjs +449 -0
  124. package/scripts/lesson-promote.mjs +262 -0
  125. package/scripts/lesson-ratify.mjs +98 -0
  126. package/scripts/lesson-seed.mjs +252 -0
  127. package/scripts/lesson-store.mjs +447 -0
  128. package/scripts/loop-checkpoint.mjs +86 -0
  129. package/scripts/memdb-health.sh +14 -0
  130. package/scripts/memory-doctor.mjs +271 -0
  131. package/scripts/model-catalog.mjs +79 -0
  132. package/scripts/nightly-controller.mjs +66 -0
  133. package/scripts/nightly-gists.sh +72 -0
  134. package/scripts/nightly-wrapper.sh +180 -0
  135. package/scripts/notify.sh +12 -0
  136. package/scripts/npx-witness.sh +56 -0
  137. package/scripts/onboarding-console.mjs +2749 -0
  138. package/scripts/private-fence.mjs +69 -0
  139. package/scripts/proactivity-metrics.mjs +118 -0
  140. package/scripts/proof-questions.json +56 -0
  141. package/scripts/prove.mjs +95 -0
  142. package/scripts/proxy/claude-proxied.sh +57 -0
  143. package/scripts/proxy/proxy-revert.sh +59 -0
  144. package/scripts/proxy/proxy-up.sh +60 -0
  145. package/scripts/proxy/proxy-verify.mjs +142 -0
  146. package/scripts/published-surface-probe.mjs +241 -0
  147. package/scripts/qe/card-lane-gate.mjs +162 -0
  148. package/scripts/qe/session-start-gate.mjs +229 -0
  149. package/scripts/qe/ux-suite.mjs +323 -0
  150. package/scripts/reconcile-project.mjs +0 -0
  151. package/scripts/record-lesson.mjs +113 -0
  152. package/scripts/refresh-model-catalog.mjs +99 -0
  153. package/scripts/release-proof.mjs +9 -0
  154. package/scripts/release-vector.mjs +281 -0
  155. package/scripts/release.mjs +395 -0
  156. package/scripts/remedy-registry.mjs +247 -0
  157. package/scripts/rerank-cap-eval.mjs +265 -0
  158. package/scripts/rerank-cap-warm-ab.mjs +129 -0
  159. package/scripts/route-cheap.mjs +20 -15
  160. package/scripts/router-utilization.mjs +182 -0
  161. package/scripts/routing-flywheel.mjs +596 -0
  162. package/scripts/rvf-generation.mjs +104 -0
  163. package/scripts/rvf-index-audit.mjs +138 -0
  164. package/scripts/self-update.mjs +508 -0
  165. package/scripts/selfcheck.mjs +7 -1
  166. package/scripts/sign-bundle.mjs +69 -0
  167. package/scripts/signal-watch.mjs +171 -0
  168. package/scripts/stack-sync.mjs +469 -0
  169. package/scripts/stamp-existing-rvf-generations.mjs +53 -0
  170. package/scripts/stamp-sweep.mjs +144 -0
  171. package/scripts/status-honesty.mjs +102 -0
  172. package/scripts/sync-version.mjs +217 -0
  173. package/scripts/token-report.mjs +102 -0
  174. package/scripts/top100-benchmark.mjs +479 -0
  175. package/scripts/top100-corpus.mjs +112 -0
  176. package/scripts/top100-semantic-assertions.mjs +449 -0
  177. package/scripts/update-apply.mjs +9 -0
  178. package/scripts/upgrade-notice.mjs +14 -0
  179. package/scripts/verify-bundle.mjs +51 -0
  180. package/scripts/verify-channels.mjs +184 -0
  181. package/scripts/verify-model-catalog.mjs +104 -0
  182. package/scripts/verify-nightly-close-issue4.sh +31 -0
  183. package/scripts/version.mjs +40 -0
  184. package/scripts/wired-check.mjs +864 -0
  185. package/plugin/scripts/finalize-token-meter.mjs +0 -25
@@ -0,0 +1,380 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * learning-enable.mjs — answers "is rUv learning actually ON?" with EVIDENCE, and refuses to
4
+ * pretend there is a switch when there isn't one.
5
+ *
6
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
7
+ * THE FAILURE THIS FILE EXISTS TO PREVENT (2026-07-21, caught before it shipped)
8
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
9
+ * A survey of this machine reported, as the headline finding of the night: "26 rUv learning hooks
10
+ * are installed and ZERO are enabled — learning is off." Stuart had been asking "is learning
11
+ * actually on?" all evening and was told no.
12
+ *
13
+ * That finding was FALSE, in both directions, and it was read straight off `ruflo hooks list`:
14
+ *
15
+ * | pre-edit | PreToolUse | No | | | Never | ← "Enabled: No", 26 times
16
+ *
17
+ * Reading the actual installed source rather than trusting the table
18
+ * (~/.npm-global/lib/node_modules/ruflo/node_modules/@claude-flow/cli/dist/src/
19
+ * mcp-tools/hooks-tools.js, `export const hooksList`) shows the handler is a HARDCODED STATIC
20
+ * ARRAY. It takes no input (`inputSchema: { properties: {} }`), opens no file, reads no database,
21
+ * and stamps every one of the 26 entries with the literal `status: 'active'`. Confirmed live via
22
+ * `ruflo hooks list --format json` — the payload contains `"status": "active"` and has NO `enabled`
23
+ * key at all.
24
+ *
25
+ * The CLI renderer (commands/hooks.js, `listCommand`) then draws a column keyed `enabled`:
26
+ *
27
+ * { key: 'enabled', ..., format: (v) => v ? output.success('Yes') : output.dim('No') }
28
+ *
29
+ * `v` is `undefined` for every row, so it prints "No" 26 times. The same mismatch empties the
30
+ * Priority and Executions columns and makes Last Executed read "Never" for everything. Proof the
31
+ * table is inert: `ruflo hooks list --enabled`, which is documented as "show only enabled hooks",
32
+ * returns all 26 rows unchanged — the CLI passes the filter to a handler that accepts no arguments.
33
+ *
34
+ * So BOTH readings of that table are worthless as an answer to "is learning on?":
35
+ * • "Enabled: No" → a field-name bug. Not a state. Never was.
36
+ * • `status: "active"` → a hardcoded literal in a catalog of which subcommands exist. Also not a state.
37
+ *
38
+ * `ruflo hooks list` is a MENU, not a dashboard. It cannot answer the question in either direction.
39
+ *
40
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
41
+ * WHAT "ENABLED" ACTUALLY MEANS
42
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
43
+ * There is no ruflo-side enable flag: `ruflo hooks enable` and `ruflo hooks disable` do not exist
44
+ * (both fall through to the help text, verified live). There is no per-hook config file under
45
+ * ~/.ruflo or ~/.claude-flow — the only file there with an `enabled` key is first-run-enabled.json,
46
+ * which is `{"enabled":{"spinner":true}}`, about a CLI spinner, and a trap for any detector that
47
+ * greps for the word.
48
+ *
49
+ * rUv's learner is driven by the ruflo DAEMON and the `mcp__ruflo__hooks_*` MCP tools that agents
50
+ * call. It is NOT driven by entries in Claude Code's ~/.claude/settings.json. That distinction is
51
+ * the whole ballgame, because it is the second way to get this wrong: this machine has ZERO ruflo
52
+ * learning hooks wired into settings.json (the only `ruflo` command there is a statusline helper)
53
+ * and yet the learner had recorded 457 trajectories and 457 patterns, last adapted 67 minutes
54
+ * before this was written. A detector that concluded "no ruflo hooks in settings.json → learning is
55
+ * off" would be just as wrong as the one that read the table, and far more convincing.
56
+ *
57
+ * The ONLY honest signal is the learner's own accumulated state, which is a real file with real
58
+ * counters that move: ~/.claude-flow/neural/stats.json. scripts/learnings.mjs already treats it as
59
+ * the source of truth for the console's "What I've learned" panel; this agrees with it rather than
60
+ * inventing a second, disagreeing answer.
61
+ *
62
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
63
+ * WHY --enable REFUSES
64
+ * ─────────────────────────────────────────────────────────────────────────────────────────────
65
+ * You cannot enable something that has no enabled state. There is no verified command that turns
66
+ * those 26 rows to "Yes", because nothing reads them. The tempting move — wiring `ruflo hooks
67
+ * post-edit` into every PostToolUse in ~/.claude/settings.json — would be a GUESS dressed as a fix:
68
+ * it edits a file that affects every project on this machine, to solve a problem that does not
69
+ * exist, duplicating capture the daemon is already doing. So --enable writes nothing and prints
70
+ * what actually drives the learner instead.
71
+ *
72
+ * This whole file is therefore READ-ONLY BY CONSTRUCTION. It never opens a file for writing, which
73
+ * is a stronger guarantee than backing one up: there is no write path to get wrong, and the tests
74
+ * assert ~/.claude/settings.json is byte-identical afterwards.
75
+ *
76
+ * Usage:
77
+ * node scripts/learning-enable.mjs [--status] report real state with evidence (default)
78
+ * node scripts/learning-enable.mjs --enable refuse, and explain what genuinely drives learning
79
+ * node scripts/learning-enable.mjs --disable refuse, same reason, inverted
80
+ * node scripts/learning-enable.mjs --json machine-readable state
81
+ *
82
+ * Exit codes: 0 = reported. 2 = refused (deliberate non-action, distinct from 1 = error).
83
+ */
84
+ import fs from 'node:fs';
85
+ import os from 'node:os';
86
+ import path from 'node:path';
87
+ import { fileURLToPath } from 'node:url';
88
+
89
+ /**
90
+ * Resolve HOME honestly. os.homedir() consults $HOME on POSIX, but reading it explicitly first
91
+ * means the tests can point this at a temp HOME without depending on that implementation detail
92
+ * — and means a caller can audit a different machine's dotfiles without lying about whose they are.
93
+ */
94
+ const homeOf = (home) => home || process.env.HOME || os.homedir();
95
+
96
+ /**
97
+ * Staleness threshold: a learner that hasn't adapted in a week is idle, not off.
98
+ *
99
+ * EXPORTED because capability-registry.mjs needs the same number and used to have no staleness check
100
+ * at all — it called a learner last adapted 400 days ago "on", while this file called the identical
101
+ * file "IDLE — nothing in 400 days". One constant, one definition; a second copy is a future
102
+ * disagreement with a delay fuse on it.
103
+ */
104
+ export const STALE_DAYS = 7;
105
+
106
+ /**
107
+ * Read the learner's accumulated state — the real signal.
108
+ *
109
+ * Rule: if the file is missing or unparseable we return null counters, NEVER 0. "0 patterns" is a
110
+ * claim that the learner ran and learned nothing; "not checked" is the truth when we never found
111
+ * the file. Shipping the former as the latter is how a detector starts lying.
112
+ */
113
+ export function readLearnerState({ home, now = Date.now() } = {}) {
114
+ const HOME = homeOf(home);
115
+ const statsPath = path.join(HOME, '.claude-flow', 'neural', 'stats.json');
116
+
117
+ let raw = null;
118
+ let parsed = null;
119
+ try { raw = fs.readFileSync(statsPath, 'utf8'); } catch { /* no learner on this machine yet */ }
120
+ if (raw !== null) { try { parsed = JSON.parse(raw); } catch { /* present but corrupt */ } }
121
+
122
+ // `Number(v)` was the bug, not the guard around it. Number(null) === 0, Number('') === 0 and
123
+ // Number(false) === 0 are all finite, so the previous `Number.isFinite(Number(v))` accepted three
124
+ // non-numbers as a MEASURED ZERO — the precise substitution this function's docstring above forbids.
125
+ // MEASURED: `{"trajectoriesRecorded": null}` produced the verdict "the learner file exists and
126
+ // GENUINELY records 0 trajectories", the word "genuinely" attached to a value nobody ever counted.
127
+ // A counter is a counter only when it arrives as a JSON number.
128
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
129
+
130
+ // Timestamps are NOT counters and must not share their reader. `lastAdaptation` is written as epoch
131
+ // milliseconds today, but an upstream switch to ISO-8601 is the single most ordinary schema change
132
+ // there is — and under num() an ISO string returns null, which nulls `days`, which makes the IDLE
133
+ // branch unreachable. MEASURED: a learner idle 400 days reported "ON — the learner is accumulating"
134
+ // purely because its timestamp was a string. The staleness check evaporated on exactly the drift it
135
+ // was written to survive, so this reader accepts both shapes and still refuses everything else.
136
+ const ts = (v) => {
137
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
138
+ if (typeof v === 'string' && v.trim()) {
139
+ const ms = Date.parse(v);
140
+ if (Number.isFinite(ms)) return ms;
141
+ }
142
+ return null;
143
+ };
144
+
145
+ const trajectories = parsed ? num(parsed.trajectoriesRecorded) : null;
146
+ const patterns = parsed ? num(parsed.patternsLearned) : null;
147
+ const lastMs = parsed ? ts(parsed.lastAdaptation) : null;
148
+
149
+ return {
150
+ statsPath,
151
+ present: raw !== null,
152
+ corrupt: raw !== null && parsed === null,
153
+ trajectories,
154
+ patterns,
155
+ lastAdaptationMs: lastMs,
156
+ // `lastMs ? …` treated epoch 0 as "no timestamp"; `=== null` is the only honest test for absence.
157
+ ageMinutes: lastMs === null ? null : Math.floor((now - lastMs) / 60000),
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Is the ruflo daemon alive? This is the process that feeds the learner, so its liveness is
163
+ * corroborating evidence — but NOT proof on its own, and not required: a dead daemon with fresh
164
+ * counters still means learning ran. Reported as a separate line, never folded into the verdict.
165
+ */
166
+ export function readDaemonState({ home } = {}) {
167
+ const HOME = homeOf(home);
168
+ const pidPath = path.join(HOME, '.claude-flow', 'daemon.pid');
169
+ let pid = null;
170
+ try { pid = Number(String(fs.readFileSync(pidPath, 'utf8')).trim()); } catch { return { pidPath, pid: null, alive: null }; }
171
+ if (!Number.isInteger(pid) || pid <= 0) return { pidPath, pid: null, alive: null };
172
+ // Signal 0 probes existence without touching the process.
173
+ try { process.kill(pid, 0); return { pidPath, pid, alive: true }; }
174
+ catch (e) { return { pidPath, pid, alive: e.code === 'EPERM' }; }
175
+ }
176
+
177
+ /**
178
+ * Count ruflo LEARNING hooks wired into Claude Code's settings.json.
179
+ *
180
+ * Reported for completeness and explicitly labelled NOT REQUIRED, because the honest finding is
181
+ * that this number was 0 on a machine that was actively learning. It is here so nobody re-derives
182
+ * the wrong conclusion from its absence later. A statusline helper is not a learning hook, so
183
+ * matching bare "ruflo" would overcount — we match a `ruflo hooks <subcommand>` invocation.
184
+ */
185
+ export function readSettingsWiring({ home } = {}) {
186
+ const HOME = homeOf(home);
187
+ const settingsPath = path.join(HOME, '.claude', 'settings.json');
188
+ let cfg = null;
189
+ try { cfg = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { return { settingsPath, present: false, learningHooks: null }; }
190
+
191
+ // TWO REAL CRASHES, both from a hand-edited settings.json, both reproduced with exit code 1 and a
192
+ // raw stack trace — which is the worst possible outcome for a command whose entire job is to tell
193
+ // a worried person whether learning is on. It left them unable to find out at all.
194
+ //
195
+ // `null` is valid JSON, so the try above succeeds and cfg is null → `cfg.hooks` threw
196
+ // "TypeError: Cannot read properties of null (reading 'hooks')".
197
+ // `hooks: {command: …}` written as an object instead of the array the schema wants → the inner
198
+ // for..of threw "TypeError: object is not iterable".
199
+ //
200
+ // This file invites hand-editing (it prints the path), so malformed shapes are an EXPECTED state,
201
+ // not an exceptional one. A structural surprise degrades to "not checked" — null, never 0, because
202
+ // a count of 0 is a claim about their configuration and null is the truth about our reading of it.
203
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) return { settingsPath, present: true, learningHooks: null };
204
+ if (cfg.hooks !== undefined && (!cfg.hooks || typeof cfg.hooks !== 'object' || Array.isArray(cfg.hooks))) {
205
+ return { settingsPath, present: true, learningHooks: null };
206
+ }
207
+ const groups = cfg.hooks || {};
208
+
209
+ // AN UNREADABLE SUB-STRUCTURE POISONS THE COUNT, and it must. Guarding the iteration with
210
+ // `Array.isArray(x) ? x : []` stops the crash and then quietly SKIPS the malformed entry — so a
211
+ // settings.json with one hook group written as an object came back as a confident `0`, meaning
212
+ // "we looked everywhere and found no ruflo learning hooks." We did not look everywhere; we
213
+ // skipped the part we could not parse. That is this file's own thesis violated three lines below
214
+ // where it is stated, and its regression test caught it.
215
+ //
216
+ // A partially-read structure yields null ("not checked"), never a total. Losing the count of the
217
+ // entries we COULD read is the correct trade: an incomplete count presented as a complete one is
218
+ // the failure mode, and there is no honest way to render "at least 3" in a field documented as
219
+ // an exact number.
220
+ let unreadable = false;
221
+ let count = 0;
222
+ for (const entries of Object.values(groups)) {
223
+ if (!Array.isArray(entries)) { unreadable = true; continue; }
224
+ for (const entry of entries) {
225
+ if (entry?.hooks !== undefined && !Array.isArray(entry.hooks)) { unreadable = true; continue; }
226
+ for (const h of Array.isArray(entry?.hooks) ? entry.hooks : []) {
227
+ if (/\bruflo\b[^"]*\bhooks\b/.test(String(h?.command || ''))) count += 1;
228
+ }
229
+ }
230
+ }
231
+ return { settingsPath, present: true, learningHooks: unreadable ? null : count };
232
+ }
233
+
234
+ /** Derive the verdict from the evidence. Never asserted, never cached, never guessed. */
235
+ export function verdict(learner) {
236
+ if (!learner.present) {
237
+ return { code: 'NO_LEARNER_STATE', headline: 'NOT LEARNING YET — no learner state on this machine' };
238
+ }
239
+ if (learner.corrupt) {
240
+ return { code: 'CORRUPT', headline: 'UNKNOWN — learner state file exists but is unreadable' };
241
+ }
242
+ const t = learner.trajectories;
243
+ const p = learner.patterns;
244
+ if (t === null && p === null) {
245
+ return { code: 'UNKNOWN_SHAPE', headline: 'UNKNOWN — learner state file has no recognisable counters' };
246
+ }
247
+
248
+ // PARTIAL DRIFT IS STILL DRIFT. Upstream does not rename both counters in the same release, and the
249
+ // half-renamed case is the one that reaches users. Every line below needs BOTH numbers — to compare
250
+ // them against zero, and to print them — so one unread counter is one unanswerable question.
251
+ //
252
+ // The two failures this replaces were mirror images of the same coercion, and both were MEASURED on
253
+ // real bytes. `{trajectories_recorded: 457, patternsLearned: 0}` fell through `(t || 0) === 0` —
254
+ // null coerced to 0 — and reported "genuinely records 0 trajectories and 0 patterns" to a machine
255
+ // holding 457. Read the other way, `{trajectoriesRecorded: null, patternsLearned: 457}` reached the
256
+ // ON branch and rendered the literal string "null work sessions recorded and 457 patterns learned".
257
+ // A confident OFF and a printed "null" from one missing field.
258
+ //
259
+ // This is the guard num() exists to enable, placed where it survives: the `|| 0` three lines below
260
+ // it discarded null the instant it was produced, so the correct reader upstream bought nothing.
261
+ if (t === null || p === null) {
262
+ const missing = t === null ? 'trajectoriesRecorded' : 'patternsLearned';
263
+ const seen = t === null ? `patternsLearned=${p}` : `trajectoriesRecorded=${t}`;
264
+ return {
265
+ code: 'UNKNOWN_PARTIAL',
266
+ missingField: missing,
267
+ headline: `UNKNOWN — learner state file is half-readable (${seen}, but ${missing} is not a number this version can read)`,
268
+ };
269
+ }
270
+
271
+ if (t === 0 && p === 0) {
272
+ return { code: 'INITIALISED_EMPTY', headline: 'INITIALISED BUT EMPTY — learner exists, has recorded nothing' };
273
+ }
274
+ const days = learner.ageMinutes === null ? null : Math.floor(learner.ageMinutes / 1440);
275
+ if (days !== null && days >= STALE_DAYS) {
276
+ return { code: 'IDLE', headline: `IDLE — learned before, but nothing in ${days} days` };
277
+ }
278
+ return { code: 'ON', headline: 'ON — the learner is accumulating' };
279
+ }
280
+
281
+ /**
282
+ * Gather everything, and NEVER throw doing it.
283
+ *
284
+ * The guards inside readSettingsWiring cover the two shapes that actually crashed, but the outer
285
+ * belt matters independently: this function is the entry point for the CLI *and* for
286
+ * capability-registry's learning row, so an unanticipated structural surprise anywhere below must
287
+ * degrade to an honest UNKNOWN rather than take down the page that was asked the question. A
288
+ * crashed probe and a probe reporting "off" are equally useless to the reader; only one of them is
289
+ * also a lie, and neither is acceptable when "I could not tell" is available and true.
290
+ */
291
+ export function gatherState(opts = {}) {
292
+ const learner = readLearnerState(opts);
293
+ const safe = (fn, fallback) => { try { return fn(); } catch { return fallback; } };
294
+ return {
295
+ learner,
296
+ daemon: safe(() => readDaemonState(opts), { pidPath: null, pid: null, alive: null }),
297
+ settings: safe(() => readSettingsWiring(opts), { settingsPath: null, present: false, learningHooks: null }),
298
+ verdict: safe(() => verdict(learner), { code: 'CORRUPT', headline: 'UNKNOWN — learner state could not be interpreted' }),
299
+ };
300
+ }
301
+
302
+ /** "not checked" beats a confident 0. Every rendered number passes through here. */
303
+ const show = (v) => (v === null || v === undefined ? 'not checked' : String(v));
304
+
305
+ const tilde = (p, HOME) => (p.startsWith(HOME) ? p.replace(HOME, '~') : p);
306
+
307
+ function renderStatus(state, HOME) {
308
+ const { learner, daemon, settings, verdict: v } = state;
309
+ const L = [];
310
+ L.push('');
311
+ L.push('rUv learning — actual state');
312
+ L.push('');
313
+ L.push(` ${v.headline}`);
314
+ L.push('');
315
+ L.push(' Evidence (all read at render time):');
316
+ L.push(` trajectories recorded : ${show(learner.trajectories)}`);
317
+ L.push(` patterns learned : ${show(learner.patterns)}`);
318
+ L.push(` last adaptation : ${learner.ageMinutes === null ? 'not checked' : `${learner.ageMinutes} min ago`}`);
319
+ L.push(` source : ${tilde(learner.statsPath, HOME)}${learner.present ? '' : ' (absent)'}`);
320
+ L.push(` ruflo daemon : ${daemon.alive === null ? 'no pid file' : daemon.alive ? `running (pid ${daemon.pid})` : `pid ${daemon.pid} not running`}`);
321
+ L.push('');
322
+ L.push(' Not evidence, despite appearances:');
323
+ L.push(' `ruflo hooks list` prints "Enabled: No" for all 26 hooks. That column is a');
324
+ L.push(' field-name bug, not a state — the handler returns `status: "active"` from a');
325
+ L.push(' hardcoded array and has no `enabled` key for the renderer to read. Proof:');
326
+ L.push(' `ruflo hooks list --enabled` still returns all 26. Ignore that table.');
327
+ L.push('');
328
+ L.push(` ruflo learning hooks in settings.json: ${show(settings.learningHooks)} — and this is NOT required.`);
329
+ L.push(' The learner is fed by the ruflo daemon and the mcp__ruflo__hooks_* tools, not by');
330
+ L.push(' Claude Code hook entries. A count of 0 here does not mean learning is off.');
331
+ L.push('');
332
+ return L.join('\n');
333
+ }
334
+
335
+ function renderRefusal(which) {
336
+ const L = [];
337
+ L.push('');
338
+ L.push(`REFUSING --${which}: there is nothing to ${which}.`);
339
+ L.push('');
340
+ L.push(' The 26 hooks in `ruflo hooks list` have no enabled state to toggle. The "Enabled"');
341
+ L.push(' column is a field-name bug (handler returns `status: "active"`; renderer reads a');
342
+ L.push(' nonexistent `enabled` key), and `ruflo hooks enable` / `ruflo hooks disable` do not');
343
+ L.push(' exist — both fall through to the help text.');
344
+ L.push('');
345
+ L.push(' This command will not edit ~/.claude/settings.json to fake it. That file affects every');
346
+ L.push(' project on this machine, and wiring `ruflo hooks ...` into it would duplicate capture');
347
+ L.push(' the daemon already performs — a guess dressed as a fix.');
348
+ L.push('');
349
+ L.push(' What actually drives the learner (verified commands, run them yourself):');
350
+ L.push(' ruflo hooks intelligence --status initialise / inspect the intelligence system');
351
+ L.push(' ruflo hooks intelligence --train force one training cycle');
352
+ L.push(' ruflo hooks metrics learning metrics dashboard');
353
+ L.push('');
354
+ L.push(' To see whether learning is on, with evidence:');
355
+ L.push(' node scripts/learning-enable.mjs --status');
356
+ L.push('');
357
+ return L.join('\n');
358
+ }
359
+
360
+ function main(argv) {
361
+ const has = (f) => argv.includes(f);
362
+ const HOME = homeOf();
363
+
364
+ if (has('--enable') || has('--disable')) {
365
+ process.stdout.write(renderRefusal(has('--enable') ? 'enable' : 'disable'));
366
+ return 2;
367
+ }
368
+
369
+ const state = gatherState();
370
+ if (has('--json')) {
371
+ process.stdout.write(`${JSON.stringify(state, null, 2)}\n`);
372
+ return 0;
373
+ }
374
+ process.stdout.write(`${renderStatus(state, HOME)}\n`);
375
+ return 0;
376
+ }
377
+
378
+ if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
379
+ process.exit(main(process.argv.slice(2)));
380
+ }