ruvnet-brain 4.0.8 → 4.0.24

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 (63) hide show
  1. package/README.md +3 -3
  2. package/bin/install.mjs +109 -42
  3. package/console/app.js +32 -11
  4. package/console/style.css +5 -0
  5. package/package.json +1 -1
  6. package/plugin/.claude-plugin/plugin.json +2 -2
  7. package/plugin/.codex-plugin/plugin.json +1 -1
  8. package/plugin/scripts/advocacy-outcomes.mjs +808 -0
  9. package/plugin/scripts/anticipate.sh +80 -14
  10. package/plugin/scripts/capability-registry.mjs +994 -0
  11. package/plugin/scripts/codex-hook-wrapper.mjs +1 -0
  12. package/plugin/scripts/continuation-gate.mjs +169 -1
  13. package/plugin/scripts/gates.mjs +146 -0
  14. package/plugin/scripts/goal-match.mjs +398 -0
  15. package/plugin/scripts/hijack-ruvnet.sh +69 -1
  16. package/plugin/scripts/hook-registry.mjs +616 -0
  17. package/plugin/scripts/hook-shim.mjs +13 -2
  18. package/plugin/scripts/learn-flush.mjs +37 -2
  19. package/plugin/scripts/learning-enable.mjs +382 -0
  20. package/plugin/scripts/lesson-promote.mjs +262 -0
  21. package/plugin/scripts/lesson-provenance.mjs +43 -0
  22. package/plugin/scripts/lesson-store.mjs +67 -56
  23. package/plugin/scripts/memory-doctor.mjs +345 -0
  24. package/plugin/scripts/nightly-controller.mjs +98 -0
  25. package/plugin/scripts/project-identity.mjs +89 -0
  26. package/plugin/scripts/ruflo-bin.mjs +81 -0
  27. package/plugin/scripts/runtime-preferences.mjs +18 -0
  28. package/plugin/scripts/session-snapshot-hook.mjs +4 -1
  29. package/plugin/scripts/session-start-core.mjs +19 -2
  30. package/plugin/scripts/unprompted-runtime.mjs +22 -7
  31. package/plugin/scripts/user-settings.mjs +672 -0
  32. package/plugin/skills/ruvnet-brain/SKILL.md +2 -2
  33. package/scripts/advocacy-outcomes.mjs +4 -808
  34. package/scripts/capability-registry.mjs +4 -876
  35. package/scripts/console-runtime-identity.mjs +74 -0
  36. package/scripts/corpus-qa.mjs +44 -6
  37. package/scripts/distill-project.mjs +9 -1
  38. package/scripts/doc-currency.mjs +45 -4
  39. package/scripts/gates.mjs +4 -146
  40. package/scripts/goal-match.mjs +4 -398
  41. package/scripts/health-repair.mjs +88 -11
  42. package/scripts/hook-registry.mjs +4 -567
  43. package/scripts/host-install-matrix.mjs +155 -0
  44. package/scripts/issue-watch.mjs +108 -0
  45. package/scripts/learning-enable.mjs +4 -380
  46. package/scripts/lesson-promote.mjs +4 -262
  47. package/scripts/memory-doctor.mjs +4 -342
  48. package/scripts/model-router-catalog.mjs +34 -0
  49. package/scripts/nightly-controller.mjs +4 -66
  50. package/scripts/nightly-wrapper.sh +23 -1
  51. package/scripts/onboarding-console.mjs +34 -12
  52. package/scripts/proactivity-metrics.mjs +8 -1
  53. package/scripts/publication-receipt.mjs +10 -1
  54. package/scripts/qe/ux-suite.mjs +72 -1
  55. package/scripts/release-abort-stale.mjs +111 -0
  56. package/scripts/release-convergence-watchdog.mjs +119 -0
  57. package/scripts/release-transaction-provider.mjs +76 -8
  58. package/scripts/release-transaction.mjs +55 -17
  59. package/scripts/rvf-generation.mjs +17 -0
  60. package/scripts/self-update.mjs +63 -10
  61. package/scripts/staged-host-verifier.mjs +27 -54
  62. package/scripts/sync-version.mjs +10 -10
  63. package/scripts/user-settings.mjs +4 -640
@@ -14,6 +14,13 @@ import path from 'node:path';
14
14
  import { execFileSync } from 'node:child_process';
15
15
  import { readStdinBounded } from './hook-input.mjs';
16
16
  import { loadRuntimePreferences } from './runtime-preferences.mjs';
17
+ import { resolveRuflo, RUFLO_MISSING } from './ruflo-bin.mjs';
18
+
19
+ // ONE BOUNDED LINE ON STDERR. stderr because a SessionEnd hook's stdout is not surfaced, and bounded
20
+ // because a hook that prints a stack trace on every `/clear` gets muted — and a muted diagnostic is
21
+ // no diagnostic at all (the same lesson as the session-start line that reported its own defect every
22
+ // session for eight days and went unread).
23
+ const warn = (msg) => { try { process.stderr.write(`learn-flush: ${msg}\n`); } catch { /* stderr gone */ } };
17
24
 
18
25
  const HOME = os.homedir();
19
26
  const PROJECT = process.env.RUVNET_BRAIN_PROJECT_DIR || process.cwd();
@@ -48,7 +55,11 @@ const QUEUE_ROOT = LEARNING_SCOPE === 'user'
48
55
  ? path.join(HOME, '.cache', 'ruvnet-brain', 'learn')
49
56
  : path.join(PROJECT, '.swarm', 'ruvnet-brain-learn');
50
57
  const QUEUE = process.env.LEARN_QUEUE || path.join(QUEUE_ROOT, `session-${SID}.jsonl`);
51
- const RUFLO = path.join(HOME, '.npm-global/bin/ruflo');
58
+ // Issue #105: this was a hardcoded `path.join(HOME, '.npm-global/bin/ruflo')` — the owner's npm
59
+ // prefix. On any other prefix (Homebrew, nvm, Volta, plain `npm -g`) the path simply did not exist,
60
+ // every feed below threw ENOENT, and every throw landed in a `catch {}` that said nothing. One
61
+ // resolver, shared with distill-project.mjs and health-repair.mjs's original — see ruflo-bin.mjs.
62
+ const RUFLO = resolveRuflo();
52
63
  const RUFLO_ENV = { ...process.env, RUFLO_DAEMON_AUTOSTART: '0' };
53
64
  const MAX_ACTIONS = 8; // bound the work so SessionEnd stays fast
54
65
 
@@ -98,7 +109,16 @@ for (const line of lines) {
98
109
  const actions = allDistinct.slice(0, MAX_ACTIONS);
99
110
  const deferred = allDistinct.slice(MAX_ACTIONS);
100
111
 
112
+ // ruflo is genuinely not on this machine. SAY SO — once — and keep the queue. Exiting 0 keeps the
113
+ // best-effort contract (an absent optional learner must never break SessionEnd); saying nothing at
114
+ // all is what turned #105 into eight invisible ENOENTs and a queue that never drained.
115
+ if (!RUFLO && actions.length) {
116
+ warn(`0/${actions.length} fed — ${RUFLO_MISSING}. The queue is KEPT for retry.`);
117
+ process.exit(0);
118
+ }
119
+
101
120
  let fed = 0;
121
+ const failures = []; // WHY each feed failed — the thing `catch {}` used to destroy
102
122
  let stoppedAt = actions.length; // how far the feed actually got before the deadline
103
123
  for (let i = 0; i < actions.length; i++) {
104
124
  const remaining = DEADLINE - Date.now();
@@ -120,7 +140,22 @@ for (let i = 0; i < actions.length; i++) {
120
140
  timeout: Math.min(6000, remaining),
121
141
  });
122
142
  fed++;
123
- } catch { /* best-effort — one slow/failed record must not stall session end */ }
143
+ } catch (e) {
144
+ // BEST-EFFORT, NOT SILENT. The old `catch { /* best-effort */ }` swallowed the reason, so a
145
+ // machine where every call failed looked exactly like one where every call worked: exit 0,
146
+ // no output, and the only trace a queue that never shrank. "Reports success while doing
147
+ // nothing" is the defect class this project treats as the worst thing it can ship. Keep going
148
+ // (one bad record must not stall session end), but keep the reason.
149
+ failures.push(String(e?.message || e).split('\n')[0].slice(0, 120));
150
+ }
151
+ }
152
+ // SURFACE IT. Distinct reasons only, at most two: eight copies of the same ENOENT is noise, and the
153
+ // second distinct reason is usually where the real information is.
154
+ if (failures.length) {
155
+ const distinct = [...new Set(failures)];
156
+ warn(`${failures.length}/${actions.length} feed call(s) FAILED via ${RUFLO}`
157
+ + ` — ${distinct.slice(0, 2).join(' | ')}${distinct.length > 2 ? ` (+${distinct.length - 2} more kind(s))` : ''}`
158
+ + (fed === 0 ? '. Nothing was learned; the queue is KEPT for retry.' : `. ${fed} succeeded.`));
124
159
  }
125
160
  // Whatever the deadline cut off is WORK, not waste: it goes back on the front of the queue so the
126
161
  // next flush continues from there. Dropping it would turn a time limit into the same silent data
@@ -0,0 +1,382 @@
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
+
88
+ /**
89
+ * Resolve HOME honestly. os.homedir() consults $HOME on POSIX, but reading it explicitly first
90
+ * means the tests can point this at a temp HOME without depending on that implementation detail
91
+ * — and means a caller can audit a different machine's dotfiles without lying about whose they are.
92
+ */
93
+ const homeOf = (home) => home || process.env.HOME || os.homedir();
94
+
95
+ /**
96
+ * Staleness threshold: a learner that hasn't adapted in a week is idle, not off.
97
+ *
98
+ * EXPORTED because capability-registry.mjs needs the same number and used to have no staleness check
99
+ * at all — it called a learner last adapted 400 days ago "on", while this file called the identical
100
+ * file "IDLE — nothing in 400 days". One constant, one definition; a second copy is a future
101
+ * disagreement with a delay fuse on it.
102
+ */
103
+ export const STALE_DAYS = 7;
104
+
105
+ /**
106
+ * Read the learner's accumulated state — the real signal.
107
+ *
108
+ * Rule: if the file is missing or unparseable we return null counters, NEVER 0. "0 patterns" is a
109
+ * claim that the learner ran and learned nothing; "not checked" is the truth when we never found
110
+ * the file. Shipping the former as the latter is how a detector starts lying.
111
+ */
112
+ export function readLearnerState({ home, now = Date.now() } = {}) {
113
+ const HOME = homeOf(home);
114
+ const statsPath = path.join(HOME, '.claude-flow', 'neural', 'stats.json');
115
+
116
+ let raw = null;
117
+ let parsed = null;
118
+ try { raw = fs.readFileSync(statsPath, 'utf8'); } catch { /* no learner on this machine yet */ }
119
+ if (raw !== null) { try { parsed = JSON.parse(raw); } catch { /* present but corrupt */ } }
120
+
121
+ // `Number(v)` was the bug, not the guard around it. Number(null) === 0, Number('') === 0 and
122
+ // Number(false) === 0 are all finite, so the previous `Number.isFinite(Number(v))` accepted three
123
+ // non-numbers as a MEASURED ZERO — the precise substitution this function's docstring above forbids.
124
+ // MEASURED: `{"trajectoriesRecorded": null}` produced the verdict "the learner file exists and
125
+ // GENUINELY records 0 trajectories", the word "genuinely" attached to a value nobody ever counted.
126
+ // A counter is a counter only when it arrives as a JSON number.
127
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
128
+
129
+ // Timestamps are NOT counters and must not share their reader. `lastAdaptation` is written as epoch
130
+ // milliseconds today, but an upstream switch to ISO-8601 is the single most ordinary schema change
131
+ // there is — and under num() an ISO string returns null, which nulls `days`, which makes the IDLE
132
+ // branch unreachable. MEASURED: a learner idle 400 days reported "ON — the learner is accumulating"
133
+ // purely because its timestamp was a string. The staleness check evaporated on exactly the drift it
134
+ // was written to survive, so this reader accepts both shapes and still refuses everything else.
135
+ const ts = (v) => {
136
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
137
+ if (typeof v === 'string' && v.trim()) {
138
+ const ms = Date.parse(v);
139
+ if (Number.isFinite(ms)) return ms;
140
+ }
141
+ return null;
142
+ };
143
+
144
+ const trajectories = parsed ? num(parsed.trajectoriesRecorded) : null;
145
+ const patterns = parsed ? num(parsed.patternsLearned) : null;
146
+ const lastMs = parsed ? ts(parsed.lastAdaptation) : null;
147
+
148
+ return {
149
+ statsPath,
150
+ present: raw !== null,
151
+ corrupt: raw !== null && parsed === null,
152
+ trajectories,
153
+ patterns,
154
+ lastAdaptationMs: lastMs,
155
+ // `lastMs ? …` treated epoch 0 as "no timestamp"; `=== null` is the only honest test for absence.
156
+ ageMinutes: lastMs === null ? null : Math.floor((now - lastMs) / 60000),
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Is the ruflo daemon alive? This is the process that feeds the learner, so its liveness is
162
+ * corroborating evidence — but NOT proof on its own, and not required: a dead daemon with fresh
163
+ * counters still means learning ran. Reported as a separate line, never folded into the verdict.
164
+ */
165
+ export function readDaemonState({ home } = {}) {
166
+ const HOME = homeOf(home);
167
+ const pidPath = path.join(HOME, '.claude-flow', 'daemon.pid');
168
+ let pid = null;
169
+ try { pid = Number(String(fs.readFileSync(pidPath, 'utf8')).trim()); } catch { return { pidPath, pid: null, alive: null }; }
170
+ if (!Number.isInteger(pid) || pid <= 0) return { pidPath, pid: null, alive: null };
171
+ // Signal 0 probes existence without touching the process.
172
+ try { process.kill(pid, 0); return { pidPath, pid, alive: true }; }
173
+ catch (e) { return { pidPath, pid, alive: e.code === 'EPERM' }; }
174
+ }
175
+
176
+ /**
177
+ * Count ruflo LEARNING hooks wired into Claude Code's settings.json.
178
+ *
179
+ * Reported for completeness and explicitly labelled NOT REQUIRED, because the honest finding is
180
+ * that this number was 0 on a machine that was actively learning. It is here so nobody re-derives
181
+ * the wrong conclusion from its absence later. A statusline helper is not a learning hook, so
182
+ * matching bare "ruflo" would overcount — we match a `ruflo hooks <subcommand>` invocation.
183
+ */
184
+ export function readSettingsWiring({ home } = {}) {
185
+ const HOME = homeOf(home);
186
+ const settingsPath = path.join(HOME, '.claude', 'settings.json');
187
+ let cfg = null;
188
+ try { cfg = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { return { settingsPath, present: false, learningHooks: null }; }
189
+
190
+ // TWO REAL CRASHES, both from a hand-edited settings.json, both reproduced with exit code 1 and a
191
+ // raw stack trace — which is the worst possible outcome for a command whose entire job is to tell
192
+ // a worried person whether learning is on. It left them unable to find out at all.
193
+ //
194
+ // `null` is valid JSON, so the try above succeeds and cfg is null → `cfg.hooks` threw
195
+ // "TypeError: Cannot read properties of null (reading 'hooks')".
196
+ // `hooks: {command: …}` written as an object instead of the array the schema wants → the inner
197
+ // for..of threw "TypeError: object is not iterable".
198
+ //
199
+ // This file invites hand-editing (it prints the path), so malformed shapes are an EXPECTED state,
200
+ // not an exceptional one. A structural surprise degrades to "not checked" — null, never 0, because
201
+ // a count of 0 is a claim about their configuration and null is the truth about our reading of it.
202
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) return { settingsPath, present: true, learningHooks: null };
203
+ if (cfg.hooks !== undefined && (!cfg.hooks || typeof cfg.hooks !== 'object' || Array.isArray(cfg.hooks))) {
204
+ return { settingsPath, present: true, learningHooks: null };
205
+ }
206
+ const groups = cfg.hooks || {};
207
+
208
+ // AN UNREADABLE SUB-STRUCTURE POISONS THE COUNT, and it must. Guarding the iteration with
209
+ // `Array.isArray(x) ? x : []` stops the crash and then quietly SKIPS the malformed entry — so a
210
+ // settings.json with one hook group written as an object came back as a confident `0`, meaning
211
+ // "we looked everywhere and found no ruflo learning hooks." We did not look everywhere; we
212
+ // skipped the part we could not parse. That is this file's own thesis violated three lines below
213
+ // where it is stated, and its regression test caught it.
214
+ //
215
+ // A partially-read structure yields null ("not checked"), never a total. Losing the count of the
216
+ // entries we COULD read is the correct trade: an incomplete count presented as a complete one is
217
+ // the failure mode, and there is no honest way to render "at least 3" in a field documented as
218
+ // an exact number.
219
+ let unreadable = false;
220
+ let count = 0;
221
+ for (const entries of Object.values(groups)) {
222
+ if (!Array.isArray(entries)) { unreadable = true; continue; }
223
+ for (const entry of entries) {
224
+ if (entry?.hooks !== undefined && !Array.isArray(entry.hooks)) { unreadable = true; continue; }
225
+ for (const h of Array.isArray(entry?.hooks) ? entry.hooks : []) {
226
+ if (/\bruflo\b[^"]*\bhooks\b/.test(String(h?.command || ''))) count += 1;
227
+ }
228
+ }
229
+ }
230
+ return { settingsPath, present: true, learningHooks: unreadable ? null : count };
231
+ }
232
+
233
+ /** Derive the verdict from the evidence. Never asserted, never cached, never guessed. */
234
+ export function verdict(learner) {
235
+ if (!learner.present) {
236
+ return { code: 'NO_LEARNER_STATE', headline: 'NOT LEARNING YET — no learner state on this machine' };
237
+ }
238
+ if (learner.corrupt) {
239
+ return { code: 'CORRUPT', headline: 'UNKNOWN — learner state file exists but is unreadable' };
240
+ }
241
+ const t = learner.trajectories;
242
+ const p = learner.patterns;
243
+ if (t === null && p === null) {
244
+ return { code: 'UNKNOWN_SHAPE', headline: 'UNKNOWN — learner state file has no recognisable counters' };
245
+ }
246
+
247
+ // PARTIAL DRIFT IS STILL DRIFT. Upstream does not rename both counters in the same release, and the
248
+ // half-renamed case is the one that reaches users. Every line below needs BOTH numbers — to compare
249
+ // them against zero, and to print them — so one unread counter is one unanswerable question.
250
+ //
251
+ // The two failures this replaces were mirror images of the same coercion, and both were MEASURED on
252
+ // real bytes. `{trajectories_recorded: 457, patternsLearned: 0}` fell through `(t || 0) === 0` —
253
+ // null coerced to 0 — and reported "genuinely records 0 trajectories and 0 patterns" to a machine
254
+ // holding 457. Read the other way, `{trajectoriesRecorded: null, patternsLearned: 457}` reached the
255
+ // ON branch and rendered the literal string "null work sessions recorded and 457 patterns learned".
256
+ // A confident OFF and a printed "null" from one missing field.
257
+ //
258
+ // This is the guard num() exists to enable, placed where it survives: the `|| 0` three lines below
259
+ // it discarded null the instant it was produced, so the correct reader upstream bought nothing.
260
+ if (t === null || p === null) {
261
+ const missing = t === null ? 'trajectoriesRecorded' : 'patternsLearned';
262
+ const seen = t === null ? `patternsLearned=${p}` : `trajectoriesRecorded=${t}`;
263
+ return {
264
+ code: 'UNKNOWN_PARTIAL',
265
+ missingField: missing,
266
+ headline: `UNKNOWN — learner state file is half-readable (${seen}, but ${missing} is not a number this version can read)`,
267
+ };
268
+ }
269
+
270
+ if (t === 0 && p === 0) {
271
+ return { code: 'INITIALISED_EMPTY', headline: 'INITIALISED BUT EMPTY — learner exists, has recorded nothing' };
272
+ }
273
+ const days = learner.ageMinutes === null ? null : Math.floor(learner.ageMinutes / 1440);
274
+ if (days !== null && days >= STALE_DAYS) {
275
+ return { code: 'IDLE', headline: `IDLE — learned before, but nothing in ${days} days` };
276
+ }
277
+ return { code: 'ON', headline: 'ON — the learner is accumulating' };
278
+ }
279
+
280
+ /**
281
+ * Gather everything, and NEVER throw doing it.
282
+ *
283
+ * The guards inside readSettingsWiring cover the two shapes that actually crashed, but the outer
284
+ * belt matters independently: this function is the entry point for the CLI *and* for
285
+ * capability-registry's learning row, so an unanticipated structural surprise anywhere below must
286
+ * degrade to an honest UNKNOWN rather than take down the page that was asked the question. A
287
+ * crashed probe and a probe reporting "off" are equally useless to the reader; only one of them is
288
+ * also a lie, and neither is acceptable when "I could not tell" is available and true.
289
+ */
290
+ export function gatherState(opts = {}) {
291
+ const learner = readLearnerState(opts);
292
+ const safe = (fn, fallback) => { try { return fn(); } catch { return fallback; } };
293
+ return {
294
+ learner,
295
+ daemon: safe(() => readDaemonState(opts), { pidPath: null, pid: null, alive: null }),
296
+ settings: safe(() => readSettingsWiring(opts), { settingsPath: null, present: false, learningHooks: null }),
297
+ verdict: safe(() => verdict(learner), { code: 'CORRUPT', headline: 'UNKNOWN — learner state could not be interpreted' }),
298
+ };
299
+ }
300
+
301
+ /** "not checked" beats a confident 0. Every rendered number passes through here. */
302
+ const show = (v) => (v === null || v === undefined ? 'not checked' : String(v));
303
+
304
+ const tilde = (p, HOME) => (p.startsWith(HOME) ? p.replace(HOME, '~') : p);
305
+
306
+ function renderStatus(state, HOME) {
307
+ const { learner, daemon, settings, verdict: v } = state;
308
+ const L = [];
309
+ L.push('');
310
+ L.push('rUv learning — actual state');
311
+ L.push('');
312
+ L.push(` ${v.headline}`);
313
+ L.push('');
314
+ L.push(' Evidence (all read at render time):');
315
+ L.push(` trajectories recorded : ${show(learner.trajectories)}`);
316
+ L.push(` patterns learned : ${show(learner.patterns)}`);
317
+ L.push(` last adaptation : ${learner.ageMinutes === null ? 'not checked' : `${learner.ageMinutes} min ago`}`);
318
+ L.push(` source : ${tilde(learner.statsPath, HOME)}${learner.present ? '' : ' (absent)'}`);
319
+ L.push(` ruflo daemon : ${daemon.alive === null ? 'no pid file' : daemon.alive ? `running (pid ${daemon.pid})` : `pid ${daemon.pid} not running`}`);
320
+ L.push('');
321
+ L.push(' Not evidence, despite appearances:');
322
+ L.push(' `ruflo hooks list` prints "Enabled: No" for all 26 hooks. That column is a');
323
+ L.push(' field-name bug, not a state — the handler returns `status: "active"` from a');
324
+ L.push(' hardcoded array and has no `enabled` key for the renderer to read. Proof:');
325
+ L.push(' `ruflo hooks list --enabled` still returns all 26. Ignore that table.');
326
+ L.push('');
327
+ L.push(` ruflo learning hooks in settings.json: ${show(settings.learningHooks)} — and this is NOT required.`);
328
+ L.push(' The learner is fed by the ruflo daemon and the mcp__ruflo__hooks_* tools, not by');
329
+ L.push(' Claude Code hook entries. A count of 0 here does not mean learning is off.');
330
+ L.push('');
331
+ return L.join('\n');
332
+ }
333
+
334
+ function renderRefusal(which) {
335
+ const L = [];
336
+ L.push('');
337
+ L.push(`REFUSING --${which}: there is nothing to ${which}.`);
338
+ L.push('');
339
+ L.push(' The 26 hooks in `ruflo hooks list` have no enabled state to toggle. The "Enabled"');
340
+ L.push(' column is a field-name bug (handler returns `status: "active"`; renderer reads a');
341
+ L.push(' nonexistent `enabled` key), and `ruflo hooks enable` / `ruflo hooks disable` do not');
342
+ L.push(' exist — both fall through to the help text.');
343
+ L.push('');
344
+ L.push(' This command will not edit ~/.claude/settings.json to fake it. That file affects every');
345
+ L.push(' project on this machine, and wiring `ruflo hooks ...` into it would duplicate capture');
346
+ L.push(' the daemon already performs — a guess dressed as a fix.');
347
+ L.push('');
348
+ L.push(' What actually drives the learner (verified commands, run them yourself):');
349
+ L.push(' ruflo hooks intelligence --status initialise / inspect the intelligence system');
350
+ L.push(' ruflo hooks intelligence --train force one training cycle');
351
+ L.push(' ruflo hooks metrics learning metrics dashboard');
352
+ L.push('');
353
+ L.push(' To see whether learning is on, with evidence:');
354
+ L.push(' node scripts/learning-enable.mjs --status');
355
+ L.push('');
356
+ return L.join('\n');
357
+ }
358
+
359
+ function main(argv) {
360
+ const has = (f) => argv.includes(f);
361
+ const HOME = homeOf();
362
+
363
+ if (has('--enable') || has('--disable')) {
364
+ process.stdout.write(renderRefusal(has('--enable') ? 'enable' : 'disable'));
365
+ return 2;
366
+ }
367
+
368
+ const state = gatherState();
369
+ if (has('--json')) {
370
+ process.stdout.write(`${JSON.stringify(state, null, 2)}\n`);
371
+ return 0;
372
+ }
373
+ process.stdout.write(`${renderStatus(state, HOME)}\n`);
374
+ return 0;
375
+ }
376
+
377
+ // BASENAME, not path identity — see the same note in hook-registry.mjs. The strict form stopped
378
+ // firing once `scripts/learning-enable.mjs` became a re-export shim over this payload copy, turning
379
+ // the documented `node scripts/learning-enable.mjs --status` into a silent no-op.
380
+ if (process.argv[1] && path.resolve(process.argv[1]).endsWith(`${path.sep}learning-enable.mjs`)) {
381
+ process.exit(main(process.argv.slice(2)));
382
+ }