geneseed 6.0.2 → 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 (99) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/DESIGN.md +1 -1
  3. package/SHIPPED.md +1 -1
  4. package/adapters/opencode/plugins/geneseed-context.js +11 -10
  5. package/adapters/opencode/plugins/geneseed-learn.js +24 -8
  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 +27 -2
  15. package/harness.config.json +1 -1
  16. package/js/build/args.mjs +4 -3
  17. package/js/build/bundle.mjs +2 -11
  18. package/js/build/driver.mjs +8 -8
  19. package/js/build/emit-claude.mjs +59 -4
  20. package/js/build/fold.mjs +3 -20
  21. package/js/build/generate.mjs +11 -2
  22. package/js/build/profile.mjs +10 -5
  23. package/js/build/render.mjs +3 -1
  24. package/js/build/source.mjs +12 -1
  25. package/js/build/stubs.mjs +42 -5
  26. package/js/cli-table.json +37 -0
  27. package/js/hosts/hooks-context.mjs +9 -8
  28. package/js/hosts/hooks-learn.mjs +435 -55
  29. package/js/hosts/installs.mjs +22 -2
  30. package/js/hosts/memory-files.mjs +249 -13
  31. package/js/hosts/native.mjs +23 -1
  32. package/js/hosts/settings.mjs +77 -4
  33. package/js/inspect/diff.mjs +3 -1
  34. package/js/inspect/doctor.mjs +37 -1
  35. package/js/inspect/status.mjs +40 -4
  36. package/js/inspect/validate.mjs +1 -1
  37. package/js/lib/proc.mjs +36 -0
  38. package/js/maintain/memory.mjs +2 -2
  39. package/js/maintain/profiles.mjs +15 -4
  40. package/js/maintain/setup.mjs +31 -7
  41. package/js/maintain/update.mjs +1 -1
  42. package/js/web/actions.mjs +5 -3
  43. package/js/web/api.mjs +2 -2
  44. package/js/web/catalog.mjs +5 -3
  45. package/js/web/profiles-api.mjs +2 -2
  46. package/js/web/state.mjs +13 -2
  47. package/package.json +1 -1
  48. package/src/AGENT.md.tmpl +1 -1
  49. package/src/agents/memory-curator.md +4 -1
  50. package/src/doctrines/process.md +2 -2
  51. package/src/memory/README.md +45 -6
  52. package/src/skills/rule/approve.md +3 -1
  53. package/src/skills/rule/consolidate.md +1 -1
  54. package/src/skills/rule.md +9 -5
  55. package/web/dist/assets/ActiveLoops-paFbiZyt.js +1 -0
  56. package/web/dist/assets/Activity-BsMFA5Aa.js +1 -0
  57. package/web/dist/assets/ActivityDetail-C66n3oul.js +1 -0
  58. package/web/dist/assets/{Bonsai-Bry-kOFb.js → Bonsai-BCd-qt7W.js} +1 -1
  59. package/web/dist/assets/{CopyButton-Cnnvjgkg.js → CopyButton-Dpl0PFja.js} +1 -1
  60. package/web/dist/assets/Dashboard-CQxdiv7F.js +2 -0
  61. package/web/dist/assets/{Docs-BJ23-fIx.js → Docs-D0XlXuiA.js} +2 -2
  62. package/web/dist/assets/Factories-CPVBoWoA.js +1 -0
  63. package/web/dist/assets/{GreenhouseView-VL_ZKJUR.js → GreenhouseView-C_2auUA8.js} +1 -1
  64. package/web/dist/assets/Installs-CXqjmqms.js +3 -0
  65. package/web/dist/assets/JournalView-S-igd-Nv.js +1 -0
  66. package/web/dist/assets/{Kits-DDSerkJk.js → Kits-K6mu91rm.js} +1 -1
  67. package/web/dist/assets/Laws-j5vKNwLT.js +4 -0
  68. package/web/dist/assets/{LibRows-QsUBjOF7.js → LibRows-1yTY0Kwn.js} +1 -1
  69. package/web/dist/assets/Library-BQZnFdWs.js +3 -0
  70. package/web/dist/assets/Loops-B5DgxpLm.js +2 -0
  71. package/web/dist/assets/Models-C-4Y4jvx.js +1 -0
  72. package/web/dist/assets/{OperatorHudView-Bdupodlc.js → OperatorHudView-_8NBAvkd.js} +1 -1
  73. package/web/dist/assets/Personal-Bf7zHDc6.js +2 -0
  74. package/web/dist/assets/Settings-BTrA6MXv.js +1 -0
  75. package/web/dist/assets/Tabs-BDhZImxa.js +1 -0
  76. package/web/dist/assets/controls-CREglcUF.js +1 -0
  77. package/web/dist/assets/index-9iBqq7i2.css +1 -0
  78. package/web/dist/assets/index-BiKWWv7Z.js +6 -0
  79. package/web/dist/assets/router-1EhRJy1C.js +1 -0
  80. package/web/dist/assets/useLocalStorage-54tkqXN7.js +1 -0
  81. package/web/dist/index.html +4 -2
  82. package/web/dist/assets/ActiveLoops-BWkImeYa.js +0 -1
  83. package/web/dist/assets/Activity-DJlPhk8q.js +0 -1
  84. package/web/dist/assets/ActivityDetail-Dk7UPnE_.js +0 -1
  85. package/web/dist/assets/Dashboard-CWhh_GSc.js +0 -2
  86. package/web/dist/assets/Factories-CjsIACyi.js +0 -1
  87. package/web/dist/assets/Installs-qcfOZNzF.js +0 -3
  88. package/web/dist/assets/JournalView-KrmFUC-X.js +0 -1
  89. package/web/dist/assets/Laws-DDffPs6O.js +0 -4
  90. package/web/dist/assets/Library-DzT3Mebh.js +0 -3
  91. package/web/dist/assets/Loops-CjsX3brz.js +0 -2
  92. package/web/dist/assets/Models-DPrAv3FG.js +0 -1
  93. package/web/dist/assets/Personal-D-dpCUU5.js +0 -2
  94. package/web/dist/assets/Settings-Dz33_Sys.js +0 -1
  95. package/web/dist/assets/Tabs-qY40S34V.js +0 -1
  96. package/web/dist/assets/controls-CK7qHA8H.js +0 -1
  97. package/web/dist/assets/index-BhT94v2q.js +0 -6
  98. package/web/dist/assets/index-DcusoHzF.css +0 -1
  99. package/web/dist/assets/usePoll-D5c_qIFZ.js +0 -1
@@ -15,11 +15,13 @@
15
15
  * import `js/web` (spec C20).
16
16
  */
17
17
  import { isUtf8 } from 'node:buffer';
18
+ import { createHash } from 'node:crypto';
18
19
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync } from 'node:fs';
19
20
  import path from 'node:path';
20
21
  import { readText, writeText, writeTextAtomic } from '../lib/fs.mjs';
21
- import { isDict } from '../lib/json.mjs';
22
+ import { isDict, jsonDumpsIndent } from '../lib/json.mjs';
22
23
  import { normcase } from '../lib/paths.mjs';
24
+ import { sharedPaths } from '../lib/machine-dir.mjs';
23
25
  import { WHITESPACE, stripWhitespace } from '../lib/text.mjs';
24
26
  import { isFile, listDir, sortPaths, splitLines, splitWords } from './hooks-prims.mjs';
25
27
 
@@ -115,12 +117,25 @@ function globMd(dir) {
115
117
  /** Stems that name the store's own files, never a fact — `MEMORY` is the index itself. */
116
118
  export const RESERVED_STEMS = new Set(['memory', 'readme']);
117
119
 
120
+ /**
121
+ * IS THIS TOP-LEVEL STEM A STORE DOCUMENT RATHER THAN A FACT? (D2) `memory` and `readme` in any case,
122
+ * and any stem written wholly in capitals: `MEMORY`, `README`, `ARCHIVE-INDEX`. A person names the
123
+ * documents that describe a store in capitals, and a fact is a lower-case slug. Without
124
+ * this a hand-written `ARCHIVE-INDEX.md` was indexed as a fact under `misc`, listed to `learn`, and
125
+ * counted by the curation nudge. A stem with no letter in it (`2026`) is no document: it has no case.
126
+ *
127
+ * ONE PREDICATE, EVERY READER: the plugins carry a twin (`geneseed-learn.js`), the console's
128
+ * `isFurniture` and `geneseed memory rm` call this one, so a list and its count cannot disagree.
129
+ */
130
+ export const isReservedStem = (stem) => RESERVED_STEMS.has(stem.toLowerCase())
131
+ || (stem === stem.toUpperCase() && stem !== stem.toLowerCase());
132
+
118
133
  /**
119
134
  * `_existing_slugs` — slugs already stored. learn never CREATES one of these; it may only
120
135
  * update or archive it by name (`writeMemories`).
121
136
  */
122
137
  export function existingSlugs(memDir) {
123
- return new Set(globMd(memDir).map(stem).filter((s) => !RESERVED_STEMS.has(s.toLowerCase())));
138
+ return new Set(globMd(memDir).map(stem).filter((s) => !isReservedStem(s)));
124
139
  }
125
140
 
126
141
  /**
@@ -169,7 +184,7 @@ export function readFacts(memDir) {
169
184
  const facts = new Map();
170
185
  for (const name of sortPaths(globMd(memDir))) {
171
186
  const s = stem(name);
172
- if (RESERVED_STEMS.has(s.toLowerCase())) continue;
187
+ if (isReservedStem(s)) continue;
173
188
  try {
174
189
  const [fm] = frontmatter(readText(path.join(memDir, name)));
175
190
  facts.set(s, { desc: fmGet(fm, 'description').trim(), topic: topicOf(fm) });
@@ -212,13 +227,14 @@ export function indexNotes(memDir, generated) {
212
227
  * Rewrite MEMORY.md as the map: one line per topic file with its fact count.
213
228
  *
214
229
  * LINES THE MAP DID NOT GENERATE ARE CARRIED, so a note the user wrote into the index
215
- * survives. `dropFlat` also drops legacy flat fact pointers; a rebuild passes it because it
216
- * has just moved them into topic files. With no topic and nothing carried, the file goes
217
- * back to the seed.
230
+ * survives. `generated(slug)` says which legacy flat fact pointers a rebuild has just moved into
231
+ * topic files, and only those are dropped (D4): a pointer to a store document (`ARCHIVE-INDEX`) or
232
+ * to a fact that is not on disk is no fact line, so it stays like any other line a person wrote.
233
+ * With no topic and nothing carried, the file goes back to the seed.
218
234
  */
219
- function writeMap(memDir, dropFlat) {
235
+ function writeMap(memDir, generated) {
220
236
  const idx = path.join(memDir, 'MEMORY.md');
221
- const carried = indexNotes(memDir, () => dropFlat);
237
+ const carried = indexNotes(memDir, generated);
222
238
  const tdir = path.join(memDir, TOPICS);
223
239
  const topics = globMd(tdir).map(stem).sort().map((t) => {
224
240
  const n = (readLines(path.join(tdir, `${t}.md`)) ?? [])
@@ -264,7 +280,12 @@ function rebuildIndex(memDir, refresh, fresh = new Set()) {
264
280
  writeIfChanged(path.join(tdir, `${topic}.md`), `# ${topic}\n\n${lines.join('\n')}\n`);
265
281
  }
266
282
  if (!byTopic.size) pruneTopicsDir(memDir);
267
- writeMap(memDir, true);
283
+ // A flat pointer is generated, and so dropped, unless it names a STORE DOCUMENT (`ARCHIVE-INDEX.md`):
284
+ // a fact's pointer has moved into a topic file, a dead one (no such file) is the old rule's, and
285
+ // a document is no fact, so its line is one a person wrote and stays (D4).
286
+ const known = new Set([...facts.keys()].map((slug) => slug.toLowerCase()));
287
+ const documents = new Set(globMd(memDir).map((n) => stem(n).toLowerCase()).filter((s) => !known.has(s)));
288
+ writeMap(memDir, (slug) => !documents.has(slug.toLowerCase()));
268
289
  return { facts, old };
269
290
  }
270
291
 
@@ -276,12 +297,27 @@ function rebuildIndex(memDir, refresh, fresh = new Set()) {
276
297
  * `topics/*.md` only, never a fact file, and it keeps each pointer's own title and hook.
277
298
  */
278
299
  export function migrateMemoryIndex(memDir) {
279
- const lines = readLines(path.join(memDir, 'MEMORY.md'));
280
- if (!lines?.some((l) => FACT_LINE_RE.test(l.trim())) || !existingSlugs(memDir).size) return false;
300
+ if (!holdsFlatFacts(memDir)) return false;
281
301
  rebuildIndex(memDir, false);
282
302
  return true;
283
303
  }
284
304
 
305
+ /**
306
+ * Does MEMORY.md still hold a flat pointer to a STORED fact? The one test of "this index is flat",
307
+ * for the migration and for the pick of always-on candidates (`alwaysOnCandidates`). A pointer to a
308
+ * store document or to a fact that is gone is carried by the migration (D4) and is no fact to move,
309
+ * so a migrated index that carries one is not flat, and the next emit finds nothing to do.
310
+ */
311
+ export function holdsFlatFacts(memDir) {
312
+ const lines = readLines(path.join(memDir, 'MEMORY.md'));
313
+ if (!lines) return false;
314
+ const slugs = new Set([...existingSlugs(memDir)].map((s) => s.toLowerCase()));
315
+ return lines.some((l) => {
316
+ const m = FACT_LINE_RE.exec(l.trim());
317
+ return m !== null && slugs.has(m[2].toLowerCase());
318
+ });
319
+ }
320
+
285
321
  /** The chunk without its frontmatter `action:` line, which is an instruction, not the fact. */
286
322
  function stripAction(chunk) {
287
323
  const lines = chunk.split('\n');
@@ -350,7 +386,7 @@ export function writeMemories(modelOutput, memDir, existing) {
350
386
  const name = fmGet(fm, 'name').trim();
351
387
  const key = name.toLowerCase();
352
388
  const action = fmGet(fm, 'action').trim().toLowerCase() || 'create';
353
- if (!MEMORY_SLUG_RE.test(name) || RESERVED_STEMS.has(key) || done.has(key)) continue;
389
+ if (!MEMORY_SLUG_RE.test(name) || isReservedStem(name) || done.has(key)) continue;
354
390
  const slug = stored.get(key);
355
391
  if (slug && action !== 'create' && hasForce(memDir, slug)) continue;
356
392
  const body = `${stripAction(chunk).replace(/\n+$/, '')}\n`;
@@ -414,7 +450,7 @@ export function memoryDropIndex(memDir, name) {
414
450
  }
415
451
  if (!touched) return;
416
452
  pruneTopicsDir(memDir);
417
- try { writeMap(memDir, false); } catch { /* best-effort */ }
453
+ try { writeMap(memDir, () => false); } catch { /* best-effort */ }
418
454
  }
419
455
 
420
456
  /** Drop every line holding `needle`; the kept lines when something went, else null. */
@@ -618,3 +654,203 @@ export function readFoldState(shared) {
618
654
  if (blank(state.items)) state.items = {};
619
655
  return state;
620
656
  }
657
+
658
+ export const itemKey = (kind, host, bytes) => createHash('sha256').update(`${kind}\0${host}\0`).update(bytes).digest('hex');
659
+
660
+ const DRAFT_HEAD = '# User rules — draft\n\nNot active. The rule Rite or the console applies decisions.\n';
661
+
662
+ /**
663
+ * A block in the draft and a C7 record. The key names the host too, so two hosts holding the same
664
+ * text are two decisions. Draft first: a stop between the writes leaves a block the next run
665
+ * recognises, not a lost one. `extra` rides on the ledger row (`fact`, for a memory candidate).
666
+ *
667
+ * HERE, NOT IN THE FOLD, since D31: the tier's memory step (`ensureSharedTier`, `stubs.mjs`) drafts too,
668
+ * and `fold.mjs` imports `stubs.mjs` for its seeds, so the fold's home for this would be a cycle.
669
+ */
670
+ export function draftItem(kind, key, block, tally, { host, shared, dryRun, report }, extra = {}) {
671
+ const state = readFoldState(shared);
672
+ if (state.items[key]) return;
673
+ report[tally] += 1;
674
+ if (dryRun) return;
675
+ const text = existsSync(shared.draft) ? readText(shared.draft) : DRAFT_HEAD;
676
+ if (!text.includes(`sha256: ${key}`)) writeTextAtomic(shared.draft, `${text}\n${block}`);
677
+ state.items[key] = { kind, host, state: 'pending', ...extra };
678
+ writeTextAtomic(shared.foldState, `${jsonDumpsIndent(state)}\n`);
679
+ }
680
+
681
+ /**
682
+ * The part of a flat MEMORY.md the session hook used to inject, in characters. Memory was the 4th
683
+ * of 5 session files, and what the 9 000-character payload left after the rules, profile and
684
+ * wiki was cut by position (`capToRoom`): 3 072 of 8 509 characters on the machine this was
685
+ * measured on (2026-11-18). A rule whose pointer sat inside that part was in force by ACCIDENT of
686
+ * its line number, which is exactly what a draft asks the user to turn into a decision.
687
+ */
688
+ export const LEGACY_INJECT_CHARS = 3072;
689
+ /** At most this many candidates are drafted at one migration: a console of 100 drafts is noise. */
690
+ export const MAX_ALWAYS_ON = 30;
691
+ const ALWAYS_WORDS_RE = /\b(?:always|never|toujours|jamais)\b/i;
692
+ const DRAFT_BODY_MAX = 1500;
693
+ const DRAFT_TITLE_MAX = 100;
694
+ export const MEMORY_DRAFT_HOST = 'memory';
695
+
696
+ const LEARN_UNSET = 'dormant ($GENESEED_LLM unset)';
697
+
698
+ /**
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.
702
+ */
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
+ }
784
+
785
+ const oneLine = (text, max) => {
786
+ const t = text.replace(/\s+/g, ' ').trim();
787
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
788
+ };
789
+
790
+ /**
791
+ * A fact's text as a rule body. A `## ` line would end the draft's block and open another, so it
792
+ * is demoted to `### `; a long fact is cut and says where the rest is. The description stands in
793
+ * for an empty body.
794
+ */
795
+ function draftBody(body, desc) {
796
+ const text = stripWhitespace(body.replace(/^## /gm, '### ')) || desc;
797
+ return text.length > DRAFT_BODY_MAX ? `${text.slice(0, DRAFT_BODY_MAX)}…\n(cut: the whole fact is in memory/)` : text;
798
+ }
799
+
800
+ /**
801
+ * The facts a FLAT index would have loaded at every session and that read as standing rules (D31),
802
+ * picked without a model: `force: constraint`, or a `feedback` fact whose pointer sat in the
803
+ * injected part (`LEGACY_INJECT_CHARS`), or a `feedback` fact whose description says always,
804
+ * never (or toujours, jamais). Priority in that order, then slug; `[]` for a store that is
805
+ * not flat, so a second emit picks nothing. Read BEFORE `migrateMemoryIndex`, which erases the
806
+ * flat index. Each is `{ slug, title, body, reason }`.
807
+ */
808
+ export function alwaysOnCandidates(memDir) {
809
+ if (!holdsFlatFacts(memDir)) return [];
810
+ const lines = readLines(path.join(memDir, 'MEMORY.md'));
811
+ const injected = new Set();
812
+ let at = 0;
813
+ for (const line of lines) {
814
+ at += line.length + 1;
815
+ const m = FACT_LINE_RE.exec(line.trim());
816
+ if (m && at <= LEGACY_INJECT_CHARS) injected.add(m[2].toLowerCase());
817
+ }
818
+ const rank = { constraint: 0, injected: 1, described: 2 };
819
+ const found = [];
820
+ for (const slug of [...existingSlugs(memDir)].sort()) {
821
+ let fm; let body;
822
+ try { [fm, body] = frontmatter(readText(path.join(memDir, `${slug}.md`))); } catch { continue; }
823
+ const desc = fmGet(fm, 'description').trim();
824
+ // The TYPE, not the topic: `topic:` only files the fact, and a `type: feedback` fact filed under
825
+ // `topic: git` is still a rule about how to work. (A nested `metadata: type:` reads as `type`.)
826
+ const feedback = topicSlug(fmGet(fm, 'type')) === 'feedback';
827
+ const reason = fmGet(fm, 'force').trim().toLowerCase() === 'constraint' ? 'constraint'
828
+ : feedback && injected.has(slug.toLowerCase()) ? 'injected'
829
+ : feedback && ALWAYS_WORDS_RE.test(desc) ? 'described' : null;
830
+ if (!reason) continue;
831
+ found.push({ slug, reason, title: oneLine(desc || slug, DRAFT_TITLE_MAX), body: draftBody(body, desc) });
832
+ }
833
+ return found.sort((a, b) => rank[a.reason] - rank[b.reason]).slice(0, MAX_ALWAYS_ON);
834
+ }
835
+
836
+ /**
837
+ * Write each candidate as a draft through the fold's own path, one block and one ledger row, with
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,
840
+ * decided or not. Never touches `user-rules.md`; approval is the console's or the Rite's.
841
+ */
842
+ export function draftAlwaysOn(shared, candidates) {
843
+ const ctx = { host: MEMORY_DRAFT_HOST, shared, dryRun: false, report: { rules: 0 } };
844
+ let n = 0;
845
+ for (const c of candidates) {
846
+ // The key is the text the way `rule-decide.mjs` re-reads it, so the block can be decided.
847
+ const [rules] = parseRules(`## R0 — ${c.title}\n${c.body}\n`);
848
+ if (rules.length !== 1) continue;
849
+ n += 1;
850
+ const key = itemKey('rule', MEMORY_DRAFT_HOST, `${rules[0].title}\n${rules[0].body}`);
851
+ draftItem('rule', key, `${draftRuleHead(MEMORY_DRAFT_HOST, c.title)}\n`
852
+ + `(source: ${path.join(shared.memory, `${c.slug}.md`)} | old: R${n} | sha256: ${key})\n`
853
+ + `${c.body}\n`, 'rules', ctx, { fact: c.slug });
854
+ }
855
+ return ctx.report.rules;
856
+ }
@@ -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,7 +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';
44
+ import { learnState, readLearnLast } from '../hosts/memory-files.mjs';
45
+ import { learnInstalls } from './status.mjs';
43
46
  import { printErr, printOut } from '../lib/fs.mjs';
47
+ import { resolveCommand } from '../lib/proc.mjs';
44
48
  import { authoringProblems, factoryProblems, loopProblems } from './checks-authoring.mjs';
45
49
  import { gateProbe, guardProbe } from './checks-probe.mjs';
46
50
  import {
@@ -68,6 +72,35 @@ export function themesToCheck(theme, allThemes, detected, available) {
68
72
  return [...available].sort();
69
73
  }
70
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
+
71
104
  /**
72
105
  * Host-compat I1: one `[note]`-prefixed line per root `openclaudeDualHarnessRoots` finds —
73
106
  * extracted to its own function (rather than inlined in `doctorCollect`) so a test can pin the
@@ -290,6 +323,9 @@ export function doctorCollect({
290
323
  problems = problems.concat(ran('shared_paths', 'Rendered shared paths', renderedPathNotes()));
291
324
  problems = problems.concat(ran('providers', 'Workflow provider', providerNotes()));
292
325
  problems = problems.concat(ran('tier_env', 'Model tier aliases', tierEnvNotes()));
326
+ const learning = learnInstalls();
327
+ problems = problems.concat(ran('learn', 'Memory learning',
328
+ [`${NOTE}learn: ${learnState(process.env, learning, readLearnLast())}`, ...learnCommandNotes(learning)]));
293
329
  problems = problems.concat(ran('map', 'Module map', moduleMapProblems()));
294
330
  problems = problems.concat(ran('host_matrix', 'Host tables', hostMatrixProblems()));
295
331
  problems = problems.concat(ran('host_claims', 'Host claims',