geneseed 6.0.3 → 6.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 (75) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/DESIGN.md +1 -1
  3. package/SHIPPED.md +1 -1
  4. package/adapters/opencode/plugins/geneseed-context.js +0 -42
  5. package/adapters/opencode/plugins/geneseed-learn.js +13 -4
  6. package/bin/geneseed-hook.mjs +5 -0
  7. package/docs/concepts/hooks.md +6 -6
  8. package/docs/guides/install-scripted.md +1 -1
  9. package/docs/reference/env-context.md +2 -1
  10. package/docs/reference/plugin-activity.md +1 -1
  11. package/docs/reference/profiles.md +1 -0
  12. package/docs/understand/a-day.md +1 -1
  13. package/docs/understand/machine-claude.md +1 -1
  14. package/docs/web-ui.md +2 -2
  15. package/harness.config.json +1 -1
  16. package/js/build/args.mjs +4 -3
  17. package/js/build/driver.mjs +8 -8
  18. package/js/build/emit-claude.mjs +59 -4
  19. package/js/build/generate.mjs +11 -2
  20. package/js/build/profile.mjs +10 -5
  21. package/js/build/render.mjs +3 -1
  22. package/js/build/source.mjs +12 -1
  23. package/js/cli-table.json +37 -0
  24. package/js/hosts/hooks-context.mjs +1 -56
  25. package/js/hosts/hooks-learn.mjs +435 -55
  26. package/js/hosts/installs.mjs +22 -2
  27. package/js/hosts/memory-files.mjs +89 -6
  28. package/js/hosts/native.mjs +23 -1
  29. package/js/hosts/settings.mjs +77 -4
  30. package/js/inspect/diff.mjs +3 -1
  31. package/js/inspect/doctor.mjs +37 -3
  32. package/js/inspect/status.mjs +38 -5
  33. package/js/inspect/validate.mjs +1 -1
  34. package/js/lib/proc.mjs +36 -0
  35. package/js/maintain/profiles.mjs +15 -4
  36. package/js/maintain/setup.mjs +31 -7
  37. package/js/maintain/update.mjs +1 -1
  38. package/js/web/actions.mjs +5 -3
  39. package/js/web/api.mjs +2 -2
  40. package/js/web/profiles-api.mjs +2 -2
  41. package/js/web/state.mjs +13 -2
  42. package/package.json +1 -1
  43. package/src/AGENT.md.tmpl +1 -1
  44. package/src/agents/memory-curator.md +3 -0
  45. package/src/doctrines/process.md +2 -2
  46. package/src/memory/README.md +24 -4
  47. package/src/skills/rule.md +9 -5
  48. package/web/dist/assets/{Activity-IAxWF2wK.js → Activity-BsMFA5Aa.js} +1 -1
  49. package/web/dist/assets/{ActivityDetail-CtC2DLvh.js → ActivityDetail-C66n3oul.js} +1 -1
  50. package/web/dist/assets/{Bonsai-BoKo68Kw.js → Bonsai-BCd-qt7W.js} +1 -1
  51. package/web/dist/assets/{CopyButton-C0VTiqmb.js → CopyButton-Dpl0PFja.js} +1 -1
  52. package/web/dist/assets/{Dashboard-CRGCp2cV.js → Dashboard-CQxdiv7F.js} +2 -2
  53. package/web/dist/assets/{Docs-DwOwzaD6.js → Docs-D0XlXuiA.js} +1 -1
  54. package/web/dist/assets/{Factories-DxHD2T-1.js → Factories-CPVBoWoA.js} +1 -1
  55. package/web/dist/assets/{GreenhouseView-D5VOmhmR.js → GreenhouseView-C_2auUA8.js} +1 -1
  56. package/web/dist/assets/Installs-CXqjmqms.js +3 -0
  57. package/web/dist/assets/{JournalView-gUSGysTm.js → JournalView-S-igd-Nv.js} +1 -1
  58. package/web/dist/assets/{Kits-DYQvykZ0.js → Kits-K6mu91rm.js} +1 -1
  59. package/web/dist/assets/{Laws-UVk0uojS.js → Laws-j5vKNwLT.js} +1 -1
  60. package/web/dist/assets/{LibRows-CwK63kjB.js → LibRows-1yTY0Kwn.js} +1 -1
  61. package/web/dist/assets/{Library-DdzyrwUK.js → Library-BQZnFdWs.js} +1 -1
  62. package/web/dist/assets/{Loops-yHga7xdr.js → Loops-B5DgxpLm.js} +1 -1
  63. package/web/dist/assets/Models-C-4Y4jvx.js +1 -0
  64. package/web/dist/assets/{OperatorHudView-D1lQF-ZY.js → OperatorHudView-_8NBAvkd.js} +1 -1
  65. package/web/dist/assets/Personal-Bf7zHDc6.js +2 -0
  66. package/web/dist/assets/{Settings-Brgec4M0.js → Settings-BTrA6MXv.js} +1 -1
  67. package/web/dist/assets/{Tabs-BHjxciOL.js → Tabs-BDhZImxa.js} +1 -1
  68. package/web/dist/assets/controls-CREglcUF.js +1 -0
  69. package/web/dist/assets/{index-BfyZCNu7.css → index-9iBqq7i2.css} +1 -1
  70. package/web/dist/assets/{index-BILaKHbH.js → index-BiKWWv7Z.js} +3 -3
  71. package/web/dist/index.html +2 -2
  72. package/web/dist/assets/Installs-B5hFSUeN.js +0 -3
  73. package/web/dist/assets/Models-DAgkQ4CE.js +0 -1
  74. package/web/dist/assets/Personal-DjhIfa9v.js +0 -2
  75. package/web/dist/assets/controls-CK7qHA8H.js +0 -1
@@ -21,6 +21,7 @@ import path from 'node:path';
21
21
  import { readText, writeText, writeTextAtomic } from '../lib/fs.mjs';
22
22
  import { isDict, jsonDumpsIndent } from '../lib/json.mjs';
23
23
  import { normcase } from '../lib/paths.mjs';
24
+ import { sharedPaths } from '../lib/machine-dir.mjs';
24
25
  import { WHITESPACE, stripWhitespace } from '../lib/text.mjs';
25
26
  import { isFile, listDir, sortPaths, splitLines, splitWords } from './hooks-prims.mjs';
26
27
 
@@ -692,12 +693,94 @@ const DRAFT_BODY_MAX = 1500;
692
693
  const DRAFT_TITLE_MAX = 100;
693
694
  export const MEMORY_DRAFT_HOST = 'memory';
694
695
 
696
+ const LEARN_UNSET = 'dormant ($GENESEED_LLM unset)';
697
+
695
698
  /**
696
- * Whether `learn` can run here (D12): it needs `$GENESEED_LLM`, and with it unset the Stop hook
697
- * returns early and no fact is ever distilled, which nothing used to say. One wording for `status`
698
- * and `doctor`.
699
+ * The last distil run's verdict, `<machine cache>/learn-last.json`: `{ at, ok, reason, facts }`. The detached
700
+ * worker has no stdio, so this file is the only place its failure (a refused command, a timeout, a lapsed
701
+ * login) can surface: `status` and `doctor` read it, so "active" is never the whole story. `reason` is one line.
699
702
  */
700
- export const learnState = (env = process.env) => (env.GENESEED_LLM ? 'active' : 'dormant ($GENESEED_LLM unset)');
703
+ const LEARN_LAST = 'learn-last.json';
704
+ export function learnLastFile() {
705
+ try { return path.join(sharedPaths().root, 'cache', LEARN_LAST); } catch { return null; }
706
+ }
707
+ export function writeLearnLast(ok, reason, facts = 0, { runningFor = 0 } = {}) {
708
+ const file = learnLastFile();
709
+ if (!file) return;
710
+ try {
711
+ mkdirSync(path.dirname(file), { recursive: true });
712
+ const line = String(reason ?? '').replace(/\s+/g, ' ').trim().slice(0, 200);
713
+ const now = Date.now();
714
+ // `ok: null` + `by`: a run that has begun and says by when it must be over. Nothing else ever clears it but the
715
+ // run's own end, so a run still marked running past `by` hung: a model CLI whose own child never exits.
716
+ const row = runningFor > 0
717
+ ? { at: new Date(now).toISOString(), ok: null, running: true, by: new Date(now + runningFor * 1000).toISOString(), reason: 'running', facts: 0 }
718
+ : { at: new Date(now).toISOString(), ok: !!ok, reason: line, facts };
719
+ writeTextAtomic(file, `${JSON.stringify(row)}\n`);
720
+ } catch { /* a verdict is a favour, never a failed hook */ }
721
+ }
722
+ /** The verdict, or null: no run yet, or an unreadable file. */
723
+ export function readLearnLast(file = learnLastFile()) {
724
+ try {
725
+ const v = JSON.parse(readFileSync(file, 'utf8'));
726
+ return isDict(v) && (typeof v.ok === 'boolean' || v.running === true) ? v : null;
727
+ } catch { return null; }
728
+ }
729
+ /** ` · last run failed <date>: <reason>` for a failed verdict, else ''. A success adds nothing. */
730
+ export function learnLastNote(last, now = Date.now()) {
731
+ if (!last) return '';
732
+ // The file is read from disk and printed to a terminal: a date that is not an ISO date is dropped, and the reason
733
+ // loses its control characters (an ESC sequence would drive the terminal) and is cut.
734
+ const day = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+Z)?$/.test(String(last.at)) ? String(last.at).slice(0, 10) : 'an unknown date';
735
+ if (last.running === true) {
736
+ const by = Date.parse(String(last.by));
737
+ return Number.isFinite(by) && now > by ? ` · last run stuck since ${day}` : '';
738
+ }
739
+ if (last.ok !== false) return '';
740
+ const reason = String(last.reason || '').replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ').trim().slice(0, 200) || 'no reason recorded';
741
+ return ` · last run failed ${day}: ${reason}`;
742
+ }
743
+
744
+ /**
745
+ * Whether `learn` can run (D12, D9), per host of the installs present. One wording for `status` and
746
+ * `doctor`. Pure: the caller reads the files.
747
+ *
748
+ * Only the Claude-shaped hook needs `$GENESEED_LLM`, and it reads the HOOK's env — which Claude
749
+ * Code builds from the shell AND from the `"env"` object of the settings files. This verb runs in a
750
+ * terminal or in the web daemon, which see neither, so `settingsEnv` carries those objects in.
751
+ * Reading only `process.env` called a learning install dormant (6.0.3, on an install that learned).
752
+ * Who set the command is said too: a value equal to what the manifest recorded (`recorded`) is
753
+ * Geneseed's, from the `--learn` choice (`active (haiku)`); any other is the user's (`active (set by
754
+ * you)`). With no command, `--learn off` reads `off` and anything else `dormant`.
755
+ * OpenCode's learn plugin distils with the session's own model and reads no `$GENESEED_LLM` at all.
756
+ * Bob's Stop payload carries no transcript, so learn returns at once there: not dormant, n/a.
757
+ *
758
+ * `last` is `readLearnLast()`: a failed verdict appends ` · last run failed <date>: <reason>`, a run still marked
759
+ * running past its `by` ` · last run stuck since <date>`. The file is machine-wide: it holds the latest run of any install.
760
+ * `installs` is `[{ host, settingsEnv?: object[], recorded?: string|null, learn?: string|null }]`;
761
+ * with none, the env alone answers, as before.
762
+ */
763
+ export function learnState(env = process.env, installs = [], last = null) {
764
+ if (!installs.length) return env.GENESEED_LLM ? `active${learnLastNote(last)}` : LEARN_UNSET;
765
+ const byHost = new Map();
766
+ for (const { host, settingsEnv = [], recorded = null, learn = null } of installs) {
767
+ let state;
768
+ if (host === 'opencode') state = 'active (session model)';
769
+ else if (host === 'bob') state = 'n/a (Bob sends no transcript)';
770
+ else {
771
+ // The files run user < project < local, and Claude Code applies the later one: search from the end.
772
+ const llm = [...settingsEnv].reverse().find((e) => isDict(e) && e.GENESEED_LLM)?.GENESEED_LLM || env.GENESEED_LLM || '';
773
+ if (!llm) state = learn === 'off' ? 'off' : LEARN_UNSET;
774
+ else if (recorded && recorded === llm) state = `active (${/--model\s+(\S+)/.exec(llm)?.[1] ?? 'session model'})`;
775
+ else state = 'active (set by you)';
776
+ }
777
+ if (!byHost.has(host)) byHost.set(host, new Set());
778
+ byHost.get(host).add(state);
779
+ }
780
+ const line = [...byHost].map(([host, states]) => `${host}: ${[...states].join(' / ')}`).join(' · ');
781
+ // The verdict is the machine's, not a host's: said once, and only where something is active to be wrong.
782
+ return /active/.test(line) ? line + learnLastNote(last) : line;
783
+ }
701
784
 
702
785
  const oneLine = (text, max) => {
703
786
  const t = text.replace(/\s+/g, ' ').trim();
@@ -752,8 +835,8 @@ export function alwaysOnCandidates(memDir) {
752
835
 
753
836
  /**
754
837
  * Write each candidate as a draft through the fold's own path, one block and one ledger row, with
755
- * the fact's slug on the row: the session hook reads it for the bridge slot (D31), and the row
756
- * leaves the slot when the user decides. Idempotent: `draftItem` skips a key the ledger holds,
838
+ * the fact's slug on the row: the draft is not loaded until approved (D32), and the row
839
+ * is decided by the user. Idempotent: `draftItem` skips a key the ledger holds,
757
840
  * decided or not. Never touches `user-rules.md`; approval is the console's or the Rite's.
758
841
  */
759
842
  export function draftAlwaysOn(shared, candidates) {
@@ -32,7 +32,7 @@ import path from 'node:path';
32
32
  import { writeText, copyFile, readText } from '../lib/fs.mjs';
33
33
  import { jsonDumps, parseJson, formatValue, formatRepr, isTruthy, isDict } from '../lib/json.mjs';
34
34
  import { relPosix } from '../lib/text.mjs';
35
- import { aliasesOf, skillDescriptions } from '../build/source.mjs';
35
+ import { DEFAULT_LEARN, LEARN_CHOICES, aliasesOf, skillDescriptions } from '../build/source.mjs';
36
36
  import { resolvePath } from './hosts.mjs';
37
37
  import { claimLeaf, ownedState } from './owned.mjs';
38
38
  // `lstripNewlines` on spec bodies is a no-op on every input the generator produces today
@@ -595,6 +595,28 @@ export function tierModel(tier, map = {}, env = {}, host = 'claude') {
595
595
  return { model: String(value), warning };
596
596
  }
597
597
 
598
+ /**
599
+ * The model memory learning distils with on `host`, and where it came from (spec
600
+ * `2026-11-18-learn-model-row.md`, D3) — pure, so `tests/unit/learn_model.test.mjs` states every row.
601
+ * `learn` is the `--learn` value (`off`, `light`, `standard`, `session`); an unknown value is the
602
+ * default. `map`, `env` and `host` are `tierModel`'s: the tier resolves THERE, so the precedence
603
+ * has one home.
604
+ *
605
+ * - `off`: `{ model: null, from: 'off' }`: nothing distils.
606
+ * - `session`: `{ model: null, from: 'session' }`: the chat's own model, no override.
607
+ * - `light` / `standard`: that tier's model, `from: 'tier'`, with `tierModel`'s warning. A tier that
608
+ * gives none (OpenCode and OpenClaude with no map value) falls back to `from: 'session'`.
609
+ * - Bob: `{ model: null, from: 'n/a' }`: its Stop payload carries no transcript, so nothing learns.
610
+ */
611
+ export function learnModel(learn, map = {}, env = {}, host = 'claude') {
612
+ if (host === 'bob') return { model: null, from: 'n/a', warning: null };
613
+ const mode = LEARN_CHOICES.includes(learn) ? learn : DEFAULT_LEARN;
614
+ if (mode === 'off') return { model: null, from: 'off', warning: null };
615
+ if (mode === 'session') return { model: null, from: 'session', warning: null };
616
+ const { model, warning } = tierModel(mode, map, env, host);
617
+ return model ? { model, from: 'tier', warning } : { model: null, from: 'session', warning: null };
618
+ }
619
+
598
620
  /**
599
621
  * The model one agent gets, and why — THE ONE HOME of the precedence (spec D5), on every host,
600
622
  * highest first: the user's pin (`agents.<name>.model`), then the `tiers` map, then the host's
@@ -1064,11 +1064,13 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
1064
1064
  // (its `compact` source) re-seeds context AFTER, this captures memory BEFORE. Same
1065
1065
  // `|| exit 0`: never block.
1066
1066
  PreCompact: [{ hooks: [{ type: 'command', command: learn }] }],
1067
- // The activity view's turn start and session end (js/hosts/activity.mjs) — the two events no
1068
- // other verb runs on. Never `onFailure: 'block'`: on UserPromptSubmit a block erases the
1067
+ // The activity view's turn start (js/hosts/activity.mjs) and, on SessionEnd below, its session end. Never `onFailure: 'block'`: on UserPromptSubmit a block erases the
1069
1068
  // user's prompt, and the `activity` verb decides nothing.
1070
1069
  UserPromptSubmit: [{ hooks: [{ type: 'command', command: activity }] }],
1071
- SessionEnd: [{ hooks: [{ type: 'command', command: activity }] }],
1070
+ // `learn`, not `activity`: the entry's `trackActivity` records every learn event alike, so the
1071
+ // session end is still recorded, and `learn` starts the session's one distil here, in a detached
1072
+ // worker (js/hosts/hooks-learn.mjs: a SessionEnd hook is killed when the session ends).
1073
+ SessionEnd: [{ hooks: [{ type: 'command', command: learn }] }],
1072
1074
  // A sub-agent's start: `context` reads the event name and injects the user's rules, which no
1073
1075
  // sub-agent gets from SessionStart (spec 2026-11-08, agent loadout). The Activity garden's
1074
1076
  // branch at launch still records, since `trackActivity` runs after every verb. Never on Bob
@@ -1394,7 +1396,13 @@ export const CLAUDE_ENV = Object.freeze({ CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH:
1394
1396
  * value, is theirs and stays. Returns the `{key: value}` pairs actually written, which the
1395
1397
  * manifest records so uninstall removes only those.
1396
1398
  */
1397
- export function wireClaudeEnv(p, want = CLAUDE_ENV) {
1399
+ /**
1400
+ * @param {string} p
1401
+ * @param {Record<string, string>} [want]
1402
+ * @param {Record<string, string> | null} [recorded]
1403
+ */
1404
+ export function wireClaudeEnv(p, want = CLAUDE_ENV, recorded = null) {
1405
+ if (isDict(recorded)) return reconcileClaudeEnv(p, want, recorded);
1398
1406
  const loaded = readSettingsForMerge(p, 'Its "env" keys were not wired.');
1399
1407
  if (!loaded) return {};
1400
1408
  const [config, hadComments] = loaded;
@@ -1425,6 +1433,71 @@ export function wireClaudeEnv(p, want = CLAUDE_ENV) {
1425
1433
  return added;
1426
1434
  }
1427
1435
 
1436
+ /**
1437
+ * The replace-if-ours form of `wireClaudeEnv` (spec 2026-11-18-learn-model-row, D5), taken when the
1438
+ * caller passes what the manifest recorded. A value Geneseed owns can change (`GENESEED_LLM` follows the
1439
+ * `--learn` choice), so ownership is the record checked against the file, as `wireClaudeListing` does it:
1440
+ * - a key in `want` that is absent from the file is written and recorded;
1441
+ * - a key on file with exactly the recorded value is Geneseed's: replaced by `want`'s;
1442
+ * - any other key on file is the user's, even one equal to `want` with no record: untouched, unrecorded
1443
+ * (and said on stderr when it differs from `want`'s, so the user learns why the choice did not apply);
1444
+ * - a recorded key `want` no longer names is removed while it still holds the recorded value.
1445
+ * Returns the `{key: value}` pairs Geneseed owns on file afterwards, which the manifest records.
1446
+ * A commented file is never rewritten: the wanted changes are printed for a hand merge.
1447
+ */
1448
+ function reconcileClaudeEnv(p, want, recorded) {
1449
+ const wanted = want || {};
1450
+ // Nothing to write and nothing of ours to remove: the file is not read, so a settings file that is commented or
1451
+ // unreadable draws no warning for a key this build never touches (OpenClaude with `--learn off`).
1452
+ if (!Object.keys(wanted).length && !Object.keys(recorded).length) return {};
1453
+ const loaded = readSettingsForMerge(p, 'Its "env" keys were not wired.');
1454
+ if (!loaded) return { ...recorded };
1455
+ const [config, hadComments] = loaded;
1456
+ if (has(config, 'env') && !isDict(config.env)) {
1457
+ process.stderr.write(`[geneseed] WARN: "env" in ${path.basename(p)} is not an object — `
1458
+ + `NOT rewriting it. Add to it by hand once it is one: ${jsonDumpsCompact(wanted)}\n`);
1459
+ return { ...recorded };
1460
+ }
1461
+ const env = has(config, 'env') ? config.env : {};
1462
+ const ours = (k) => has(recorded, k) && has(env, k) && env[k] === recorded[k];
1463
+ const next = { ...env };
1464
+ const record = {};
1465
+ for (const k of new Set([...Object.keys(recorded), ...Object.keys(wanted)])) {
1466
+ if (has(wanted, k)) {
1467
+ if (!has(env, k) || ours(k)) { next[k] = wanted[k]; record[k] = wanted[k]; }
1468
+ // Only the learn command's refusal is news: MAX_SUBAGENT_SPAWN_DEPTH was always the user's to set, and said nothing.
1469
+ else if (env[k] !== wanted[k] && k === 'GENESEED_LLM') {
1470
+ process.stderr.write(`[geneseed] "env.${k}" in ${path.basename(p)} is set by you (${jsonDumpsCompact(env[k])}) `
1471
+ + `— kept, not replaced by ${jsonDumpsCompact(wanted[k])}. Remove it and rebuild to let Geneseed set it.\n`);
1472
+ }
1473
+ } else if (ours(k)) {
1474
+ delete next[k];
1475
+ }
1476
+ }
1477
+ const owned = () => Object.fromEntries(Object.keys(recorded).filter(ours).map((k) => [k, env[k]]));
1478
+ const changed = Object.keys({ ...env, ...next }).some((k) => has(env, k) !== has(next, k) || env[k] !== next[k]);
1479
+ if (!changed) return record;
1480
+ const config2 = { ...config };
1481
+ if (Object.keys(next).length) config2.env = next; else delete config2.env;
1482
+ if (hadComments) {
1483
+ const add = Object.fromEntries(Object.entries(record).filter(([k, v]) => env[k] !== v));
1484
+ const drop = Object.keys(env).filter((k) => !has(next, k));
1485
+ process.stderr.write(`[geneseed] ${path.basename(p)} has comments — not rewriting it `
1486
+ + '(your edits are kept). Merge its "env" keys by hand: set '
1487
+ + `${jsonDumpsCompact(add)}${drop.length ? `, remove ${drop.join(', ')}` : ''}\n`);
1488
+ return owned();
1489
+ }
1490
+ try {
1491
+ atomicWriteJson(p, config2);
1492
+ } catch (e) {
1493
+ if (!isOsError(e)) throw e;
1494
+ process.stderr.write(`[geneseed] WARN: could not write ${p} (${e.message}) — its "env" keys were not `
1495
+ + `wired. Set them by hand: ${jsonDumpsCompact(wanted)}\n`);
1496
+ return owned();
1497
+ }
1498
+ return record;
1499
+ }
1500
+
1428
1501
  /** Remove each recorded `env` key while it still holds the recorded value; drop an empty `env`. */
1429
1502
  export function unwireClaudeEnv(p, recorded) {
1430
1503
  if (!isDict(recorded) || !Object.keys(recorded).length) return;
@@ -40,7 +40,7 @@ import {
40
40
  } from '../hosts/hosts.mjs';
41
41
  import {
42
42
  EMIT_HOST_SCOPE, defaultTheme, doctrinesForBuild, excludedRulesOfDir,
43
- contextWindowOfDir, excludedSkillsOfDir, gatesOfDir, sharedTierOfDir, tiersOfDir,
43
+ contextWindowOfDir, excludedSkillsOfDir, gatesOfDir, sharedTierOfDir, tiersOfDir, learnOfDir,
44
44
  footprintOfDir, modeOfDir, postureOfDir,
45
45
  trustOfDir,
46
46
  readJsonMaybe, readMaybe, renderedTier, themeOfDir,
@@ -280,6 +280,8 @@ export function diffCollect({
280
280
  contextWindow: contextWindowOfDir(dir, host),
281
281
  // The tier routing, or an install built `--tiers auto` reads its `Model tiers: auto` line and every tiered agent as drift.
282
282
  tiers: tiersOfDir(dir, host),
283
+ // The learn model, or an install built `--learn off` reads its `Learn model: off` line as drift.
284
+ learn: learnOfDir(dir, host),
283
285
  // The user's own overrides file (pins and the tiers map): a render input like every axis above, so it is
284
286
  // part of the memo key, and `null` (no file) leaves the emit to seed its stub as before.
285
287
  overridesText: readMaybe(path.join(dir, 'agent-overrides.json')),
@@ -20,7 +20,7 @@
20
20
  * and there is no in-process equivalent — `vm.Script` compiles as a SCRIPT and every plugin is
21
21
  * ESM (`import { promises as fs } from "node:fs"`), which `node --check` accepts through
22
22
  * module-syntax detection and `vm.Script` rejects with a SyntaxError of its own. So the ban is
23
- * an ALLOW-LIST of exactly the shape the hook entry already carries for `$GENESEED_LLM`: one
23
+ * an ALLOW-LIST of exactly the shape the hook entry carries for `$GENESEED_LLM` (and, since ADR 0002's 2026-11-18 amendment, for its detached `learn-worker`): one
24
24
  * binding, one call site, and a test that names the argv. What the ban actually protects —
25
25
  * that this tool never shells back to the generator — is asserted directly instead.
26
26
  *
@@ -30,6 +30,7 @@
30
30
  * four lines of accumulator that keep the Doctor page's per-check cards a parameter rather
31
31
  * than a rewrite.
32
32
  */
33
+ import { existsSync } from 'node:fs';
33
34
  import path from 'node:path';
34
35
  import { emitGlobalInto, emitProjectInto, main as driverMain } from '../build/driver.mjs';
35
36
  import { ROOT } from '../build/source.mjs';
@@ -40,8 +41,10 @@ import {
40
41
  import { installProfile } from '../build/profile.mjs';
41
42
  import { providerWarning } from '../maintain/kit-migration.mjs';
42
43
  import { validateIsVendored } from '../hosts/native.mjs';
43
- import { learnState } from '../hosts/memory-files.mjs';
44
+ import { learnState, readLearnLast } from '../hosts/memory-files.mjs';
45
+ import { learnInstalls } from './status.mjs';
44
46
  import { printErr, printOut } from '../lib/fs.mjs';
47
+ import { resolveCommand } from '../lib/proc.mjs';
45
48
  import { authoringProblems, factoryProblems, loopProblems } from './checks-authoring.mjs';
46
49
  import { gateProbe, guardProbe } from './checks-probe.mjs';
47
50
  import {
@@ -69,6 +72,35 @@ export function themesToCheck(theme, allThemes, detected, available) {
69
72
  return [...available].sort();
70
73
  }
71
74
 
75
+ /**
76
+ * Whether `word` (a command's first word) is something `learn`'s spawn can run (`resolveCommand`).
77
+ * Pure over `exists`, so a test names every row.
78
+ */
79
+ export function commandOnPath(word, env = process.env, exists = existsSync, platform = process.platform) {
80
+ // The spawn's own resolver (`resolveCommand`, F5): on Windows a `claude.cmd` shim counts, a `.ps1` does not.
81
+ return resolveCommand(word, env, exists, platform) !== null;
82
+ }
83
+
84
+ /**
85
+ * D9: the one case where `active` would lie. An install whose learn command (`$GENESEED_LLM`, from its
86
+ * settings or the shell) names a first word the hook's PATH does not hold learns nothing. A NOTE and never a
87
+ * problem: doctor runs in a terminal whose PATH may differ from the one the host app hands its hooks.
88
+ */
89
+ export function learnCommandNotes(installs, env = process.env, onPath = commandOnPath) {
90
+ const seen = new Set();
91
+ const notes = [];
92
+ for (const { host, settingsEnv = [] } of installs) {
93
+ if (host === 'opencode' || host === 'bob') continue;
94
+ const llm = [...settingsEnv].reverse().find((e) => e && typeof e === 'object' && e.GENESEED_LLM)?.GENESEED_LLM || env.GENESEED_LLM || '';
95
+ const word = String(llm).trim().split(/\s+/)[0];
96
+ if (!word || seen.has(`${host} ${word}`) || onPath(word, env)) continue;
97
+ seen.add(`${host} ${word}`);
98
+ notes.push(`${NOTE}learn: ${host}'s model command '${word}' is not on PATH here, so its hook may learn `
99
+ + 'nothing. Install it, or put it on the PATH the host app starts hooks with.');
100
+ }
101
+ return notes;
102
+ }
103
+
72
104
  /**
73
105
  * Host-compat I1: one `[note]`-prefixed line per root `openclaudeDualHarnessRoots` finds —
74
106
  * extracted to its own function (rather than inlined in `doctorCollect`) so a test can pin the
@@ -291,7 +323,9 @@ export function doctorCollect({
291
323
  problems = problems.concat(ran('shared_paths', 'Rendered shared paths', renderedPathNotes()));
292
324
  problems = problems.concat(ran('providers', 'Workflow provider', providerNotes()));
293
325
  problems = problems.concat(ran('tier_env', 'Model tier aliases', tierEnvNotes()));
294
- problems = problems.concat(ran('learn', 'Memory learning', [`${NOTE}learn: ${learnState()}`]));
326
+ const learning = learnInstalls();
327
+ problems = problems.concat(ran('learn', 'Memory learning',
328
+ [`${NOTE}learn: ${learnState(process.env, learning, readLearnLast())}`, ...learnCommandNotes(learning)]));
295
329
  problems = problems.concat(ran('map', 'Module map', moduleMapProblems()));
296
330
  problems = problems.concat(ran('host_matrix', 'Host tables', hostMatrixProblems()));
297
331
  problems = problems.concat(ran('host_claims', 'Host claims',
@@ -36,7 +36,7 @@
36
36
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
37
37
  import path from 'node:path';
38
38
 
39
- import { DEFAULT_CONTEXT_WINDOW, GATE_SWITCHES, THEMES, ROOT, loadKits, makeCfg } from '../build/source.mjs';
39
+ import { DEFAULT_CONTEXT_WINDOW, DEFAULT_LEARN, GATE_SWITCHES, THEMES, ROOT, loadKits, makeCfg } from '../build/source.mjs';
40
40
  import { tuiInventory } from './inventory.mjs';
41
41
  import { sourceGeneration } from '../build/render.mjs';
42
42
  import { readVersion, sourceFingerprint } from '../build/version.mjs';
@@ -48,14 +48,14 @@ import {
48
48
  // the deployed theme and footprint, and `rebuild-all` re-emits in the deployed everything, so
49
49
  // three verbs read them.
50
50
  import {
51
- claudeCfg, defaultTheme, hookShellProblems, installedDefaults, installState, installTargets,
52
- installsReferencingShim, openclaudeDualHarnessRoots, themeOfDir, readJsonMaybe, readMaybe,
51
+ claudeCfg, claudeReadManifest, defaultTheme, hookShellProblems, installedDefaults, installState, installTargets,
52
+ installsReferencingShim, learnOfDir, openclaudeDualHarnessRoots, themeOfDir, readJsonMaybe, readMaybe,
53
53
  } from '../hosts/installs.mjs';
54
54
  import { installProfile, rebuildCommand } from '../build/generate.mjs';
55
55
  import { providerWarning } from '../maintain/kit-migration.mjs';
56
56
  import { isDoctorNote } from './scan.mjs';
57
57
  import { pendingDrafts } from '../hosts/hooks-context.mjs';
58
- import { factCount, learnState } from '../hosts/memory-files.mjs';
58
+ import { factCount, learnState, readLearnLast } from '../hosts/memory-files.mjs';
59
59
  import { lastStoreReport } from '../hosts/store-watch.mjs';
60
60
  import { hookShimPath, shimDead } from '../hosts/shim.mjs';
61
61
  import { printErr, printOut } from '../lib/fs.mjs';
@@ -272,6 +272,37 @@ export function keptKitFiles(host, scope, root, active) {
272
272
  return Object.keys(kept).length ? kept : null;
273
273
  }
274
274
 
275
+ /**
276
+ * The installs present, each with the settings `"env"` objects its hook runs under, for
277
+ * `learnState` (D12). A Claude-shaped hook gets its env from the shell and from the settings
278
+ * files: the host's user settings always, plus the project's two for a project install. Not on
279
+ * the hook path; an unreadable file is simply no env.
280
+ */
281
+ export function learnInstalls(targets = installTargets()) {
282
+ const envOf = (file) => readJsonMaybe(file)?.env ?? null;
283
+ const out = [];
284
+ for (const [host, scope, root] of targets) {
285
+ let state;
286
+ try { state = installState(root, host, scope); } catch { continue; }
287
+ if (state !== 'active') continue;
288
+ if (!CLAUDE_STYLE.includes(host) || host === 'bob') { out.push({ host }); continue; }
289
+ const spec = HOSTS.find((h) => h.host === host);
290
+ const files = [];
291
+ try { files.push(path.join(spec.configDir(), 'settings.json')); } catch { /* no host dir */ }
292
+ if (scope !== 'global') {
293
+ const dir = path.join(root, spec.projectMarker);
294
+ files.push(path.join(dir, 'settings.json'), path.join(dir, 'settings.local.json'));
295
+ }
296
+ // What the manifest recorded Geneseed wrote (D5): a value equal to it is Geneseed's, any other is the user's.
297
+ const cfg = claudeCfg(root, scope, host);
298
+ const recorded = claudeReadManifest(cfg).managed?.settings_env?.GENESEED_LLM;
299
+ let learn = null;
300
+ try { learn = learnOfDir(cfg, host); } catch { /* no carrier: the default */ }
301
+ out.push({ host, settingsEnv: files.map(envOf), recorded: typeof recorded === 'string' ? recorded : null, learn });
302
+ }
303
+ return out;
304
+ }
305
+
275
306
  /**
276
307
  * The `[host, scope, root]` of `targets` the user chose as the default, or null: no pick, or a pick
277
308
  * that no longer names an ACTIVE install (removed, disabled, or not seen from here). A stale pick
@@ -365,7 +396,7 @@ export function statusData() {
365
396
  agent_md_present: Boolean(agentMd && existsSync(agentMd)),
366
397
  gates: gateSummary([...(cfgDir ? [cfgDir] : []), ...otherCfg]),
367
398
  drafts_pending: pendingDrafts(),
368
- learn: learnState(),
399
+ learn: learnState(process.env, learnInstalls(), readLearnLast()),
369
400
  store_report: lastStoreReport(),
370
401
  opencode_shadow: opencodeShadowedInstall(),
371
402
  openclaude_dual_harness: openclaudeDualHarnessRoots(),
@@ -516,6 +547,8 @@ export function statusLines(d, color = false, boxed = true) {
516
547
  // Elided at the default, like the shared tier, so a default row prints what it did.
517
548
  ...(p.contextWindow && p.contextWindow !== DEFAULT_CONTEXT_WINDOW ? [`context window: ${p.contextWindow}`] : []),
518
549
  ...(p.tiers && p.tiers !== 'off' ? [`model tiers: ${p.tiers}`] : []),
550
+ // The learn model, elided at its default (`light`) like the tiers: a default row prints what it did.
551
+ ...(p.learn && p.learn !== DEFAULT_LEARN ? [`learn model: ${p.learn}`] : []),
519
552
  // Each elided when armed. The law's text still binds; only its tool-boundary gate is off.
520
553
  ...GATE_SWITCHES.filter((g) => p[g.key] === false)
521
554
  .map((g) => `${g.marker.toLowerCase()}: off${g.law ? ` (Law ${g.law} text still binds)` : ''}`)]
@@ -155,7 +155,7 @@ export function cmdValidate(args) {
155
155
  theme: args.theme, footprint: args.footprint, posture: args.posture, mode: args.mode,
156
156
  trust: args.trust, doctrines: args.doctrines, excludeRules: args.excludeRules,
157
157
  excludeSkills: args.excludeSkills, kits: args.kits, sharedTier: args.sharedTier === 'on',
158
- contextWindow: args.contextWindow, tiers: args.tiers,
158
+ contextWindow: args.contextWindow, tiers: args.tiers, learn: args.learn,
159
159
  ...Object.fromEntries(GATE_SWITCHES.map((g) => [g.key, args[g.arg] ? false : null])),
160
160
  };
161
161
  let scanDirs;
package/js/lib/proc.mjs CHANGED
@@ -27,4 +27,40 @@
27
27
  * `js/maintain/update.mjs`) and are correct — `tests/unit/spawn_hygiene.test.mjs` explains why
28
28
  * it asserts no inverse rule.
29
29
  */
30
+ import { existsSync } from 'node:fs';
31
+ import path from 'node:path';
32
+
30
33
  export const NO_WINDOW = { windowsHide: process.platform === 'win32' };
34
+
35
+ /** The extensions the model spawn can run on Windows: an executable, or a `cmd.exe` batch shim. */
36
+ const WIN_RUNNABLE = ['.exe', '.com', '.cmd', '.bat'];
37
+
38
+ /**
39
+ * The file `word` names as a command, or null: what a spawn of it can actually run, and the one answer
40
+ * `learn`'s spawn and `doctor`'s PATH note share (spec 2026-11-18-learn-model-row, F5).
41
+ *
42
+ * On Windows `CreateProcess` finds only `.exe` on PATH, so an npm-installed CLI (`claude.cmd`,
43
+ * `openclaude.cmd`) is "not found" to a plain `spawn`: the word is resolved here against `PATH` and
44
+ * `PATHEXT`, and only `.exe`, `.com`, `.cmd` and `.bat` count (a `.ps1` or `.vbs` in PATHEXT cannot be
45
+ * run by this spawn). Elsewhere the OS resolves the word at spawn time, so this only reports whether a
46
+ * file of that name sits on `PATH`. `exists` and `platform` are parameters so a table can state every row.
47
+ */
48
+ export function resolveCommand(word, env = process.env, exists = existsSync, platform = process.platform) {
49
+ if (!word) return null;
50
+ const win = platform === 'win32';
51
+ const sep = win ? /[\\/]/ : /\//;
52
+ const dirs = sep.test(word) ? [''] : String(env.PATH ?? env.Path ?? '').split(win ? ';' : ':').filter(Boolean);
53
+ let exts = [''];
54
+ if (win) {
55
+ const listed = String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').map((e) => e.toLowerCase());
56
+ const has = WIN_RUNNABLE.find((e) => word.toLowerCase().endsWith(e));
57
+ exts = has ? [''] : listed.filter((e) => WIN_RUNNABLE.includes(e));
58
+ }
59
+ for (const dir of dirs) {
60
+ for (const ext of exts) {
61
+ const file = dir ? path.join(dir, word + ext) : word + ext;
62
+ if (exists(file)) return file;
63
+ }
64
+ }
65
+ return null;
66
+ }
@@ -27,7 +27,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from
27
27
  import path from 'node:path';
28
28
 
29
29
  import {
30
- CONTEXT_WINDOWS, DEFAULT_CONTEXT_WINDOW, DEFAULT_TIERS, TIERS_CHOICES, discoverNames, GATE_SWITCHES, knownRuleIds, knownSkillIds, linkedSkillIds, loadKits, PACK_ORDER, ROOT,
30
+ CONTEXT_WINDOWS, DEFAULT_CONTEXT_WINDOW, DEFAULT_LEARN, DEFAULT_TIERS, LEARN_CHOICES, TIERS_CHOICES, discoverNames, GATE_SWITCHES, knownRuleIds, knownSkillIds, linkedSkillIds, loadKits, PACK_ORDER, ROOT,
31
31
  } from '../build/source.mjs';
32
32
  import { installProfile, setupBuildArgs } from '../build/profile.mjs';
33
33
  import { PRESETS } from '../loop/score.mjs';
@@ -70,9 +70,11 @@ export const BASE_PROFILE = 'starter';
70
70
  * `tiers` (`--tiers`) is optional and means "the profile sets it" only when present: absent keeps the
71
71
  * install's own recorded value (`profileBuildArgs`' `current`), `off` on a fresh install. No shipped
72
72
  * profile turns it on.
73
+ * `learn` (`--learn`) is optional the same way: absent keeps the install's own recorded value
74
+ * (`profileBuildArgs`' `currentLearn`), `light` on a fresh install.
73
75
  */
74
76
  export const PROFILE_KEYS = ['description', 'hosts', 'theme', 'footprint', 'posture', 'mode', 'trust',
75
- 'doctrines', 'excludeRules', 'excludeSkills', 'kits', 'kitsByDetection', 'sharedTier', 'contextWindow', 'tiers', 'gates', 'login'];
77
+ 'doctrines', 'excludeRules', 'excludeSkills', 'kits', 'kitsByDetection', 'sharedTier', 'contextWindow', 'tiers', 'learn', 'gates', 'login'];
76
78
 
77
79
  /** A profile name: a file stem, never a path. */
78
80
  const NAME_RE = /^[a-z0-9][a-z0-9._-]*$/i;
@@ -144,6 +146,7 @@ export function profileProblems(p) {
144
146
  choice('trust', Object.keys(PRESETS));
145
147
  choice('contextWindow', Object.keys(CONTEXT_WINDOWS));
146
148
  choice('tiers', [...TIERS_CHOICES]);
149
+ choice('learn', [...LEARN_CHOICES]);
147
150
  const packs = discoverNames('doctrines', PACK_ORDER[0]);
148
151
  if (p.doctrines !== undefined && p.doctrines !== 'all') {
149
152
  if (!stringList(p.doctrines)) errs.push(`'doctrines' must be 'all' or a list of: ${list(packs)}`);
@@ -258,7 +261,7 @@ export function profileKits(p, host, project = null, detectRoots = {}) {
258
261
  * here; posture and mode elide only at the value the driver would take anyway. `--reset` last,
259
262
  * as the wizard does: a profile is a whole selection and wins over the install it lands on (D14).
260
263
  */
261
- export function profileBuildArgs(p, host, project = null, current = null, detectRoots = {}) {
264
+ export function profileBuildArgs(p, host, project = null, current = null, detectRoots = {}, currentLearn = null) {
262
265
  // A stated selection, never null: `'all'` resolves to the packs, a list is the list.
263
266
  const doctrines = PACK_ORDER.filter((d) => profileDoctrines(p).includes(d));
264
267
  // PROJECT SCOPE (spec D32, D37): `--emit <host> --out <dir> --root <dir>`, and only here the
@@ -269,7 +272,9 @@ export function profileBuildArgs(p, host, project = null, current = null, detect
269
272
  p.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
270
273
  // The profile's own value, else the install's recorded one (`current`), else off: a profile
271
274
  // without the key never turns a routed install back off by being applied over it.
272
- p.tiers ?? current ?? DEFAULT_TIERS);
275
+ p.tiers ?? current ?? DEFAULT_TIERS,
276
+ // The same for the learn model: a profile without the key never resets a recorded choice.
277
+ p.learn ?? currentLearn ?? DEFAULT_LEARN);
273
278
  if (!p.excludeSkills?.length) argv.push('--exclude-skills', 'none');
274
279
  argv.push('--reset');
275
280
  return argv;
@@ -303,6 +308,7 @@ export function profileFromInstall(info, description = '') {
303
308
  contextWindow: info.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
304
309
  // Written only when on, so a saved profile of a default install is what it always was.
305
310
  ...(info.tiers && info.tiers !== DEFAULT_TIERS ? { tiers: info.tiers } : {}),
311
+ ...(info.learn && info.learn !== DEFAULT_LEARN ? { learn: info.learn } : {}),
306
312
  gates,
307
313
  login: true,
308
314
  };
@@ -343,6 +349,11 @@ export function profileDiff(p, base) {
343
349
  if (w(p) !== w(base)) out.push({ key, base: w(base), now: w(p) });
344
350
  continue;
345
351
  }
352
+ if (key === 'learn') {
353
+ const w = (prof) => prof.learn ?? DEFAULT_LEARN;
354
+ if (w(p) !== w(base)) out.push({ key, base: w(base), now: w(p) });
355
+ continue;
356
+ }
346
357
  if (key === 'contextWindow') {
347
358
  const w = (prof) => prof.contextWindow ?? DEFAULT_CONTEXT_WINDOW;
348
359
  if (w(p) !== w(base)) out.push({ key, base: w(base), now: w(p) });