geneseed 5.4.0 → 5.5.1

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 (191) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +31 -1
  3. package/SHIPPED.md +1 -1
  4. package/adapters/bob/README.md +12 -1
  5. package/adapters/opencode/README.md +2 -1
  6. package/adapters/opencode/plugins/geneseed-context.js +71 -10
  7. package/adapters/opencode/plugins/geneseed-guard.js +101 -19
  8. package/adapters/opencode/plugins/geneseed-learn.js +641 -6
  9. package/bin/geneseed-cli.mjs +3 -0
  10. package/bin/geneseed-hook.mjs +2 -1
  11. package/docs/concepts/agents.md +13 -1
  12. package/docs/concepts/enforcement-table.md +1 -1
  13. package/docs/concepts/foreman-mode.md +22 -3
  14. package/docs/concepts/hook-gates.md +1 -1
  15. package/docs/concepts/hooks.md +22 -5
  16. package/docs/concepts/host-matrix.md +2 -2
  17. package/docs/concepts/hosts.md +1 -1
  18. package/docs/concepts/shared-tier.md +1 -1
  19. package/docs/concepts/skills.md +21 -1
  20. package/docs/concepts/themes.md +1 -1
  21. package/docs/extending.md +11 -2
  22. package/docs/guides/install-clone.md +18 -0
  23. package/docs/guides/install-scripted.md +8 -2
  24. package/docs/guides/install.md +19 -1
  25. package/docs/guides/upgrade.md +1 -1
  26. package/docs/reference/env-context.md +1 -1
  27. package/docs/reference/environment.md +1 -1
  28. package/docs/reference/plugin-learn.md +4 -0
  29. package/docs/reference/profiles.md +226 -0
  30. package/docs/token-footprint.md +9 -4
  31. package/docs/understand/design-choices-engineering.md +1 -1
  32. package/docs/web-ui.md +3 -1
  33. package/harness.config.json +1 -1
  34. package/js/README.md +9 -2
  35. package/js/build/args.mjs +4 -3
  36. package/js/build/catalog.mjs +11 -1
  37. package/js/build/driver.mjs +42 -11
  38. package/js/build/emit-claude.mjs +24 -1
  39. package/js/build/emit-opencode.mjs +3 -0
  40. package/js/build/export.mjs +12 -17
  41. package/js/build/generate.mjs +2 -1
  42. package/js/build/notes-migrate.mjs +99 -0
  43. package/js/build/profile.mjs +14 -6
  44. package/js/build/render.mjs +34 -10
  45. package/js/build/source.mjs +85 -2
  46. package/js/cli-table.json +164 -4
  47. package/js/hosts/agent-runs.mjs +205 -0
  48. package/js/hosts/done-checks.mjs +3 -1
  49. package/js/hosts/hooks-done.mjs +91 -16
  50. package/js/hosts/hooks-learn.mjs +85 -0
  51. package/js/hosts/hooks-prims.mjs +39 -1
  52. package/js/hosts/hooks.mjs +10 -4
  53. package/js/hosts/hosts.mjs +10 -0
  54. package/js/hosts/installs.mjs +25 -1
  55. package/js/hosts/link.mjs +45 -10
  56. package/js/hosts/native.mjs +42 -5
  57. package/js/hosts/opencode.mjs +1 -1
  58. package/js/hosts/settings.mjs +72 -0
  59. package/js/hosts/spec-feedback.mjs +538 -0
  60. package/js/hosts/usage.mjs +67 -8
  61. package/js/inspect/agent-scores.mjs +118 -0
  62. package/js/inspect/checks-authoring.mjs +2 -1
  63. package/js/inspect/checks-build.mjs +20 -4
  64. package/js/inspect/checks-repo.mjs +27 -2
  65. package/js/inspect/cost.mjs +6 -5
  66. package/js/inspect/diff.mjs +25 -5
  67. package/js/inspect/doctor.mjs +4 -0
  68. package/js/inspect/status.mjs +3 -1
  69. package/js/inspect/validate.mjs +1 -0
  70. package/js/lib/machine-dir.mjs +8 -0
  71. package/js/lib/paths.mjs +4 -1
  72. package/js/maintain/profile-scope.mjs +145 -0
  73. package/js/maintain/profiles.mjs +486 -0
  74. package/js/maintain/setup.mjs +409 -15
  75. package/js/maintain/uninstall.mjs +4 -1
  76. package/js/maintain/update.mjs +1 -1
  77. package/js/web/actions.mjs +28 -38
  78. package/js/web/api.mjs +7 -2
  79. package/js/web/handler.mjs +8 -0
  80. package/js/web/jobs.mjs +5 -4
  81. package/js/web/profiles-api.mjs +201 -0
  82. package/js/web/routes.mjs +5 -0
  83. package/package.json +2 -1
  84. package/profiles/autonomous.json +14 -0
  85. package/profiles/corporate.json +14 -0
  86. package/profiles/guillaume-claude-global.json +16 -0
  87. package/profiles/mentor.json +13 -0
  88. package/profiles/minimal.json +15 -0
  89. package/profiles/starter.json +14 -0
  90. package/src/AGENT.md.tmpl +1 -1
  91. package/src/agents/_self-improvement.md +15 -7
  92. package/src/agents/_template.md +4 -2
  93. package/src/agents/advocate.md +1 -1
  94. package/src/agents/architect.md +1 -1
  95. package/src/agents/developer.md +10 -3
  96. package/src/agents/devops-engineer.md +7 -6
  97. package/src/agents/docker-expert.md +1 -1
  98. package/src/agents/docs.md +1 -1
  99. package/src/agents/empiricist.md +1 -1
  100. package/src/agents/explorer.md +4 -2
  101. package/src/agents/framer.md +1 -1
  102. package/src/agents/historian.md +1 -1
  103. package/src/agents/kubernetes-specialist.md +4 -2
  104. package/src/agents/memory-curator.md +1 -1
  105. package/src/agents/operator.md +1 -1
  106. package/src/agents/performance.md +1 -1
  107. package/src/agents/pragmatist.md +1 -1
  108. package/src/agents/react-engineer.md +1 -1
  109. package/src/agents/react-reviewer.md +1 -1
  110. package/src/agents/researcher.md +1 -1
  111. package/src/agents/reviewer.md +10 -3
  112. package/src/agents/security.md +1 -1
  113. package/src/agents/skeptic.md +1 -1
  114. package/src/agents/spring-boot-engineer.md +4 -4
  115. package/src/agents/spring-reviewer.md +5 -3
  116. package/src/agents/spring-security.md +1 -1
  117. package/src/agents/steward.md +1 -1
  118. package/src/agents/tester.md +4 -2
  119. package/src/agents/user-advocate.md +1 -1
  120. package/src/agents/visionary.md +1 -1
  121. package/src/memory/README.md +12 -2
  122. package/src/modes/foreman.md +23 -10
  123. package/src/skill-descriptions.json +63 -0
  124. package/src/skills/_self-improvement.md +42 -26
  125. package/src/skills/_template.md +3 -1
  126. package/src/skills/brainstorm.md +35 -22
  127. package/src/skills/codebase-design.md +2 -2
  128. package/src/skills/daydream/VENDOR.md +6 -0
  129. package/src/skills/diagram-design/SKILL.md +12 -7
  130. package/src/skills/diagram-design/VENDOR.md +23 -14
  131. package/src/skills/diagram-design/references/layout-budget.md +7 -1
  132. package/src/skills/diagram-design/references/onboarding.md +1 -1
  133. package/src/skills/diagram-design/references/primitives-core.md +1 -1
  134. package/src/skills/diagram-design/references/semantic-patterns.md +1 -1
  135. package/src/skills/diagram-design/references/style-guide.md +1 -1
  136. package/src/skills/diagram-design/references/type-dependency.md +69 -0
  137. package/src/skills/diagram-design/references/type-event-modeling.md +36 -0
  138. package/src/skills/diagram-design/references/type-requirement-traceability.md +45 -0
  139. package/src/skills/diagram-design/references/type-sbgn.md +80 -0
  140. package/src/skills/diagram-design/references/type-scatter.md +1 -1
  141. package/src/skills/diagram-design/references/type-steps.md +180 -0
  142. package/src/skills/diagram-design/references/type-unit-grid.md +63 -0
  143. package/src/skills/explain-changes/VENDOR.md +5 -1
  144. package/src/skills/geneseed-code-review.md +2 -1
  145. package/src/skills/parallel-agents.md +12 -1
  146. package/src/skills/pipeline.md +3 -3
  147. package/src/skills/plan.md +5 -4
  148. package/src/skills/react-view-transitions/AGENTS.md +26 -26
  149. package/src/skills/react-view-transitions/SKILL.md +1 -1
  150. package/src/skills/react-view-transitions/VENDOR.md +19 -4
  151. package/src/skills/release.md +7 -2
  152. package/src/skills/rule/approve.md +2 -1
  153. package/src/skills/skill-forge.md +5 -3
  154. package/src/skills/spring-boot/cloud.md +19 -1
  155. package/src/skills/spring-boot/logging.md +5 -3
  156. package/src/skills/spring-boot/web.md +27 -2
  157. package/src/skills/spring-boot.md +4 -2
  158. package/src/skills/spring-data-jpa.md +18 -4
  159. package/src/skills/spring-testing.md +4 -0
  160. package/src/skills/token-report/VENDOR.md +5 -1
  161. package/src/upstreams.json +6 -6
  162. package/themes/README.md +3 -1
  163. package/web/dist/assets/{ActiveLoops-BJJN3P-V.js → ActiveLoops-DOJCPPPc.js} +1 -1
  164. package/web/dist/assets/{Activity-D2kOc3yi.js → Activity-bUSPM3Dl.js} +1 -1
  165. package/web/dist/assets/{ActivityDetail-By3xOr21.js → ActivityDetail-AHRoXeFN.js} +1 -1
  166. package/web/dist/assets/{Bonsai-CBWDTBA4.js → Bonsai-B5XY9pid.js} +1 -1
  167. package/web/dist/assets/{CopyButton-BVbpriMB.js → CopyButton-C0wwRR9H.js} +1 -1
  168. package/web/dist/assets/{Dashboard-CIJLPHM9.js → Dashboard-DPAA96EI.js} +2 -2
  169. package/web/dist/assets/{Docs-CiRRIELs.js → Docs-CpGDq165.js} +1 -1
  170. package/web/dist/assets/{Factories-DhyK0O8d.js → Factories-cNhETa5Q.js} +1 -1
  171. package/web/dist/assets/{GreenhouseView-DW3PgTPy.js → GreenhouseView-DO3ADmT9.js} +1 -1
  172. package/web/dist/assets/Installs-D3dDyq10.js +3 -0
  173. package/web/dist/assets/{JournalView-O65qEWfp.js → JournalView--W-Lw_V9.js} +1 -1
  174. package/web/dist/assets/{Kits-C5U-yT6Z.js → Kits-ChfehxY6.js} +1 -1
  175. package/web/dist/assets/Laws-CNxYmV36.js +4 -0
  176. package/web/dist/assets/{LibRows-D6-CVa3K.js → LibRows-CiPvsRYB.js} +1 -1
  177. package/web/dist/assets/{Library-CzPlerd6.js → Library-BxQvbwVU.js} +1 -1
  178. package/web/dist/assets/{Loops-CqNF_-nS.js → Loops-DAblKkyq.js} +1 -1
  179. package/web/dist/assets/{OperatorHudView-BNr8K5qj.js → OperatorHudView-QtSaSyYm.js} +1 -1
  180. package/web/dist/assets/{Personal-DeDb9e8O.js → Personal-DxSGv638.js} +1 -1
  181. package/web/dist/assets/{Settings-B8MPN_AD.js → Settings-CgTbhvRv.js} +1 -1
  182. package/web/dist/assets/{Tabs-DJzAez4h.js → Tabs-Cf4X1hdz.js} +1 -1
  183. package/web/dist/assets/api-CZ-x0iWG.js +1 -0
  184. package/web/dist/assets/{controls-D4wmg_pl.js → controls-CK7qHA8H.js} +1 -1
  185. package/web/dist/assets/{index-BL3P-9Rg.js → index-B_pTwZra.js} +4 -4
  186. package/web/dist/assets/index-CzfImiYb.css +1 -0
  187. package/web/dist/index.html +3 -3
  188. package/web/dist/assets/Installs-B6nlo-Ly.js +0 -3
  189. package/web/dist/assets/Laws-CuTw_XNf.js +0 -4
  190. package/web/dist/assets/api-DLDVY3K-.js +0 -1
  191. package/web/dist/assets/index-CRWqKxfY.css +0 -1
@@ -39,7 +39,8 @@ import { promises as fs, realpathSync } from "node:fs"
39
39
  import * as path from "node:path"
40
40
  import { fileURLToPath } from "node:url"
41
41
  import { homedir } from "node:os"
42
- import { readdirSync, statSync, writeFileSync as writeLogSync, mkdirSync, readFileSync as readLogSync } from "node:fs"
42
+ import { createHash } from "node:crypto"
43
+ import { readdirSync, statSync, existsSync, writeFileSync as writeLogSync, mkdirSync, readFileSync as readLogSync } from "node:fs"
43
44
 
44
45
  // OpenCode 1.x paints a plugin's stderr over its TUI input box (in red); its own log API
45
46
  // writes to the log file instead. The V1 entry sets LOG_CLIENT; V2 and tests have no
@@ -122,6 +123,41 @@ async function readsTier(dir) {
122
123
  try { if ((await fs.readFile(path.join(dir, ".geneseed-emit"), "utf8")).trim().endsWith("-global")) return true } catch { /* no marker */ }
123
124
  return isHostConfigDir(dir)
124
125
  }
126
+ // Where the install's notebook is, and which loaded copy records: geneseed-guard.js is their home
127
+ // and carries the reasons (`node tests/twins.mjs --write` keeps these copies).
128
+ function notebookHome(cfg = path.dirname(PLUGIN_DIR)) {
129
+ const isDirSync = (p) => { try { return statSync(p).isDirectory() } catch { return false } }
130
+ if (isDirSync(path.join(cfg, "notebook"))) return cfg
131
+ if (path.basename(cfg) === ".opencode" && isDirSync(path.join(path.dirname(cfg), "notebook"))) return path.dirname(cfg)
132
+ return null
133
+ }
134
+ function usageHome(cfg = path.dirname(PLUGIN_DIR)) {
135
+ const home = notebookHome(cfg)
136
+ return home && !existsSync(path.join(home, ".usage-off")) ? home : null
137
+ }
138
+ function countingCopy(here) {
139
+ const [directory, worktree] = here || []
140
+ if (!directory) return null
141
+ const start = path.resolve(directory)
142
+ const top = worktree ? path.resolve(worktree) : start
143
+ const rel = path.relative(top, start)
144
+ // Nearest first. `directory` not under `worktree`: test the two and walk nothing.
145
+ const dirs = [start]
146
+ if (rel.startsWith("..") || path.isAbsolute(rel)) dirs.push(top)
147
+ else for (let d = start; norm(d) !== norm(top) && path.dirname(d) !== d;) { d = path.dirname(d); dirs.push(d) }
148
+ for (const dir of dirs) {
149
+ const plugins = path.join(dir, ".opencode", "plugins")
150
+ if (existsSync(path.join(plugins, "geneseed-guard.js")) && usageHome(path.join(dir, ".opencode"))) return norm(plugins)
151
+ }
152
+ return null
153
+ }
154
+ function anotherCopyCounts(here) {
155
+ if (process.env.GENESEED_STACK_GLOBAL) return false
156
+ try {
157
+ const winner = countingCopy(here)
158
+ return winner !== null && winner !== norm(PLUGIN_DIR)
159
+ } catch { return false /* cannot tell: count */ }
160
+ }
125
161
  async function sovereignBypass(cwd) {
126
162
  try {
127
163
  const cfg = path.dirname(PLUGIN_DIR) // plugins/ sits directly in <cfg>
@@ -280,6 +316,558 @@ async function appendAgentLesson(memDir, agent, lesson) {
280
316
  return file
281
317
  }
282
318
 
319
+ // ---- spec-feedback notes (agent-notes/<name>.md, skill-notes/<name>.md) ----------
320
+ // The `spec-feedback:` lines a subagent ends its report with go into the notes its next dispatch
321
+ // reads, and a skill's `[skill:<name>]` line into the notes that skill reads, with no model call:
322
+ // the twin of js/hosts/spec-feedback.mjs `captureSpecFeedback`, which the Claude hook runs on
323
+ // SubagentStop and Stop. The pure part below is a tool-kept copy.
324
+ // ---- spec-feedback twin: BEGIN — adapters/opencode/plugins/geneseed-learn.js carries everything down
325
+ // to the END marker verbatim, with `export ` dropped (`node tests/twins.mjs --write` after a change).
326
+
327
+ /**
328
+ * One report line: `spec-feedback: [agent|general] <fix> [— situation: …] — seen: …`, at the start
329
+ * of the line after an optional list marker, and optionally wrapped in backticks or bold. A line
330
+ * that only names the protocol ("No spec-feedback.", "The reviewer's spec-feedback: …") does not
331
+ * start with it, so it is no feedback; nor is a quoted (`>`) line or one inside a code fence: both
332
+ * show someone else's line. Real reports write the scope four ways (`[agent]`, `agent`,
333
+ * `agent —`, none), and some copy the template's `[agent|general]`; a missing or unchosen scope
334
+ * reads as `agent`.
335
+ */
336
+ const FEEDBACK_LINE_RE = /^[ \t]*(?:[-*+][ \t]+)*(\*\*|`)?spec-feedback[ \t]*:(\*\*|`)?[ \t]*(.*)$/i;
337
+ const FENCE_RE = /^[ \t]*(?:```|~~~)/;
338
+ // A bare scope word stands alone: `agent-notes/…` and `general-purpose …` open a body, not a scope.
339
+ // `[agent:project]` (or bare `agent:project`) is the agent's own line kept for this repo only, and
340
+ // `[general:project]` (or bare `general:project`) the line every agent reads in this repo only.
341
+ const FEEDBACK_SCOPE_RE = /^(?:\[[ \t]*(?<own>agent|general)[ \t]*\]|\[[ \t]*agent[ \t]*\|[ \t]*general[ \t]*\]|\[[ \t]*(?<pw>agent|general)[ \t]*:[ \t]*project[ \t]*\]|(?<pb>agent|general):project(?![\w-])|(?<bare>agent|general)(?![\w-]))[ \t]*(?:[—–:-][ \t]*)?/i;
342
+ // What opens an agent's tag at all, parsed or not: `[project]`, `[agent project]`, `[agent:local]`
343
+ // do not parse, and are dropped rather than filed, tag and all, in the machine notes.
344
+ const AGENT_OPENING_RE = /^\[[ \t]*(?:agent|general|project)\b/i;
345
+ /**
346
+ * A skill's scope, which always names the skill: `[skill:<name>]` for that skill's own notes,
347
+ * `[skill:<name>:general]` (or `, general` / ` general`) for the notes every skill shares, and
348
+ * `[skill:<name>:project]` for its own notes in this repo only, and `[skill:<name>:general:project]`
349
+ * for the notes every skill shares in this repo only. The
350
+ * name is required because the main session's reply, where a skill's line is read, also relays
351
+ * sub-agents' `[agent]` and `[general]` lines: only a line naming a skill is a skill's. A `|`
352
+ * before `general` is the template's unchosen alternative, as `[agent|general]` is: own notes.
353
+ * The bracket's content is taken whole, and a name that is no slug (the template's `<name>`, a
354
+ * path) drops the line rather than letting `[skill:…]` fall through into an agent's notes. The
355
+ * brackets may be dropped (`skill:debug — …`), as reports drop them around `agent`, scope and all (`skill:debug:project — …`).
356
+ */
357
+ const SKILL_SCOPE_RE = /^(?:\[[ \t]*skill[ \t]*:[ \t]*([^\]|,; \t:]*)[ \t]*(?:([|,;:]|[ \t])[ \t]*(general[ \t]*:[ \t]*project|general|project)[ \t]*)?\]|skill:([a-z][a-z0-9-]*)(?::(general:project|general|project))?(?![\w-]))[ \t]*(?:[—–:-][ \t]*)?/i;
358
+ const SKILL_NAME_RE = /^[a-z][a-z0-9-]{0,63}$/;
359
+ // What opens a skill's tag at all, parsed or not.
360
+ const SKILL_OPENING_RE = /^(?:\[[ \t]*skill\b|skill[ \t]*:)/i;
361
+ // "none" as the whole answer, or before punctuation or a dash; "none of the proof commands…" is feedback.
362
+ const FEEDBACK_NONE_RE = /^(?:none|n\/a|nothing|no friction)[ \t]*(?:$|[.,;:!—–-])/i;
363
+ /** The include's own template, which a report may quote: never a note. */
364
+ const FEEDBACK_PLACEHOLDER = '<the one-line fix>';
365
+ /**
366
+ * The step-0 footprint: every dispatch reads its own notes and `_general.md`. Past the bullet cap,
367
+ * or past the character budget, the oldest of the HOOK'S bullets drop (a hand-written line is
368
+ * never dropped). An agent's own file keeps 100, as `memory/agents/` does; the general file 30.
369
+ */
370
+ const MAX_FEEDBACK_BULLETS = 100;
371
+ const MAX_GENERAL_BULLETS = 30;
372
+ const MAX_NOTE_FILE_CHARS = 8000;
373
+ /** A body past this many characters is cut, so one runaway line cannot fill the file. */
374
+ const MAX_FEEDBACK_CHARS = 500;
375
+ /** The general file's name. `_` keeps it apart from every agent: an agent name starts with a letter. */
376
+ const GENERAL_NOTES = '_general.md';
377
+ /**
378
+ * TWO SCOPES, chosen by the line, never by the install (the owner's ruling, 2026-11-15). A flaw of
379
+ * the spec is true in every repo: `[agent]`, `[general]`, `[skill:<id>]`, `[skill:<id>:general]` go
380
+ * to the MACHINE notes, the tier's `notes/`. A fact true only in this repo, `[agent:project]`,
381
+ * `[general:project]`, `[skill:<id>:project]` or `[skill:<id>:general:project]`, goes to the
382
+ * PROJECT notes, `<project root>/notebook/`, one folder for every host, with its own `_general.md`
383
+ * files. The render names this folder relative to the project root (`{{PATH_PROJECT_NOTES}}`).
384
+ */
385
+ const PROJECT_NOTES_DIR = 'notebook';
386
+ /**
387
+ * THE PROJECT NOTES NEVER REACH A COMMIT, and Geneseed writes no file into the user's tree to say so
388
+ * (the owner's ruling, 2026-11-15): the ignore entries go into the clone's own `.git/info/exclude`,
389
+ * per clone and never committed. That covers a fresh repo, a repo whose `notebook/` is tracked, and an
390
+ * unrelated `notebook/` folder alike, since only the notes folders and the migration's archives are
391
+ * named. `rel` is the notebook's path from the git root, `/`-separated. The exclude file's new text,
392
+ * or null when every entry is already there: the block is added once, and only its missing lines after.
393
+ */
394
+ const EXCLUDE_HEAD = '# Geneseed: the project notes stay on this clone, never committed';
395
+ function excludeWithNotes(text, rel) {
396
+ const lines = String(text || '').replace(/\r\n?/g, '\n').split('\n').map((l) => l.trim());
397
+ const want = ['agent-notes', 'skill-notes', 'archived-agent-notes', 'archived-skill-notes'].map((sub) => `/${rel}/${sub}/`);
398
+ const missing = want.filter((w) => !lines.includes(w));
399
+ if (!missing.length) return null;
400
+ const old = String(text || '').replace(/\r\n?/g, '\n');
401
+ const add = [...(lines.includes(EXCLUDE_HEAD) ? [] : [EXCLUDE_HEAD]), ...missing];
402
+ return `${old}${old && !old.endsWith('\n') ? '\n' : ''}${add.join('\n')}\n`;
403
+ }
404
+ // A bullet's dated tail, `(2026-11-14)` or `(tester, 2026-11-14)`: not part of what it says.
405
+ const DATED_TAIL_RE = /[ \t]*\((?:[a-z][a-z0-9-]*, )?\d{4}-\d{2}-\d{2}\)[ \t]*$/;
406
+ // A bullet in the shape this capture writes: the only kind the caps may drop.
407
+ // Every bullet the hook writes names its writer beside the date, `(<agent or skill>, date)`: that
408
+ // is what tells it from a line written by hand (the notes were hand-written as `- [skill] … (date)`
409
+ // before the hook), and a hand-written line is never dropped (the owner's ruling, 2026-11-15).
410
+ // `[agent]` bullets written before the name was added read as hand lines now: kept, never pruned.
411
+ const HOOK_BULLET_RE = /^- \[(?:agent|general|skill)\] .*\([a-z][a-z0-9-]*, \d{4}-\d{2}-\d{2}\)[ \t]*$/;
412
+
413
+ /**
414
+ * Every feedback line in `text` as `{ scope, body }`, in order, each body once. `secret` is Law
415
+ * I's pattern: a line that carries a credential is dropped whole, never written to a note. An
416
+ * agent's scope is `agent`, `general`, `project` or `project-general`. A skill's line also carries
417
+ * `skill: <name>`, its scope `skill` (own notes), `general`, `project` or `project-general`.
418
+ */
419
+ function specFeedbackOf(text, secret) {
420
+ const found = [];
421
+ let fenced = false;
422
+ for (const line of String(text || '').split(/\r?\n/)) {
423
+ if (FENCE_RE.test(line)) { fenced = !fenced; continue; }
424
+ if (fenced) continue;
425
+ const m = FEEDBACK_LINE_RE.exec(line);
426
+ if (!m) continue;
427
+ let body = m[3].trim();
428
+ // `**spec-feedback:** …` closed its wrapper at the colon; `` `spec-feedback: …` `` closes it at the end.
429
+ if (m[1] && !m[2] && body.endsWith(m[1])) body = body.slice(0, -m[1].length).trim();
430
+ let scope = 'agent';
431
+ let skill = null;
432
+ const k = SKILL_SCOPE_RE.exec(body);
433
+ if (k) {
434
+ skill = (k[1] ?? k[4]).toLowerCase();
435
+ if (!SKILL_NAME_RE.test(skill)) continue;
436
+ // A skill line wrapped in inline code is an example the reply quotes (a summary of this very
437
+ // format), not the reply's own line: the main session discusses the format, an agent's
438
+ // report does not. A whole-line `spec-feedback:` in backticks stays an agent's line.
439
+ if (m[1] === '`') continue;
440
+ const tag = (k[3] && k[2] !== '|' ? k[3] : k[5] ?? '').toLowerCase().replace(/[ \t]/g, '');
441
+ scope = tag === 'general:project' ? 'project-general' : tag || 'skill';
442
+ body = body.slice(k[0].length);
443
+ } else if (SKILL_OPENING_RE.test(body)) {
444
+ continue; // a skill tag that does not parse (`[skill:a:b]`, `[skill:a, b]`) is no agent's line
445
+ } else {
446
+ const s = FEEDBACK_SCOPE_RE.exec(body);
447
+ if (!s && AGENT_OPENING_RE.test(body)) continue;
448
+ const g = s ? s.groups : {};
449
+ const projectTag = g.pw || g.pb;
450
+ if (projectTag) scope = projectTag.toLowerCase() === 'general' ? 'project-general' : 'project';
451
+ else if (g.own || g.bare) scope = (g.own || g.bare).toLowerCase();
452
+ if (s) body = body.slice(s[0].length);
453
+ }
454
+ body = body.replace(/\s+/g, ' ').trim();
455
+ if (body.length < 10 || FEEDBACK_NONE_RE.test(body) || body.includes(FEEDBACK_PLACEHOLDER)) continue;
456
+ if (secret && secret.test(body)) continue;
457
+ if (body.length > MAX_FEEDBACK_CHARS) body = `${body.slice(0, MAX_FEEDBACK_CHARS).trimEnd()}…`;
458
+ if (found.some((f) => f.body === body && (f.skill ?? null) === skill)) continue;
459
+ found.push(skill ? { scope, skill, body } : { scope, body });
460
+ }
461
+ return found;
462
+ }
463
+
464
+ /**
465
+ * The note bullets for one report: an `agent` line goes to the agent's own file, a `general` line
466
+ * to `_general.md` only (with the agent's name), which every agent reads too. One home each. A
467
+ * skill's line is not the agent's: `skillBullets` takes it.
468
+ */
469
+ function feedbackBullets(items, agent, day) {
470
+ const mine = items.filter((f) => !f.skill);
471
+ const own = (scope) => mine.filter((f) => f.scope === scope).map((f) => `- [agent] ${f.body} (${agent}, ${day})`);
472
+ const general = (scope) => mine.filter((f) => f.scope === scope).map((f) => `- [general] ${f.body} (${agent}, ${day})`);
473
+ return {
474
+ own: own('agent'),
475
+ general: general('general'),
476
+ // The same bullet shapes in the project's files: where a bullet sits says its scope.
477
+ project: own('project'),
478
+ projectGeneral: general('project-general'),
479
+ };
480
+ }
481
+
482
+ /**
483
+ * The same for the skills' lines, into `skill-notes/`: `own` maps each skill to its bullets,
484
+ * `- [skill] … (<skill>, date)`; a general line goes to `skill-notes/_general.md`, which every
485
+ * skill reads, in the same shape as `[general]`. The name beside the date is what tells a hook
486
+ * bullet from the `- [skill] … (date)` lines written by hand before the hook: those are never
487
+ * dropped, and the duplicate check reads past both tails, so the same words are one note.
488
+ */
489
+ function skillBullets(items, day) {
490
+ const own = new Map();
491
+ const project = new Map();
492
+ const general = [];
493
+ const projectGeneral = [];
494
+ for (const f of items) {
495
+ if (!f.skill) continue;
496
+ if (f.scope === 'general' || f.scope === 'project-general') {
497
+ (f.scope === 'general' ? general : projectGeneral).push(`- [general] ${f.body} (${f.skill}, ${day})`);
498
+ continue;
499
+ }
500
+ const into = f.scope === 'project' ? project : own;
501
+ if (!into.has(f.skill)) into.set(f.skill, []);
502
+ into.get(f.skill).push(`- [skill] ${f.body} (${f.skill}, ${day})`);
503
+ }
504
+ return { own, general, project, projectGeneral };
505
+ }
506
+
507
+ /**
508
+ * Every file one report writes, `{ root, sub, name, bullets, cap }` in the order the capture
509
+ * writes them: `root` is `machine` (the tier's notes) or `project` (`<project>/notebook`). A Stop
510
+ * passes no agent, so an agent's line there (relayed from a sub-agent) has no target. The one
511
+ * routing table: the hook and the OpenCode plugin both write what this returns.
512
+ */
513
+ function feedbackTargets(items, agent, day) {
514
+ const targets = [];
515
+ const put = (root, sub, name, bullets, cap) => { if (bullets.length) targets.push({ root, sub, name, bullets, cap }); };
516
+ if (agent) {
517
+ const { own, general, project, projectGeneral } = feedbackBullets(items, agent, day);
518
+ put('machine', 'agent-notes', `${agent}.md`, own, MAX_FEEDBACK_BULLETS);
519
+ put('machine', 'agent-notes', GENERAL_NOTES, general, MAX_GENERAL_BULLETS);
520
+ put('project', 'agent-notes', `${agent}.md`, project, MAX_FEEDBACK_BULLETS);
521
+ put('project', 'agent-notes', GENERAL_NOTES, projectGeneral, MAX_GENERAL_BULLETS);
522
+ }
523
+ const skills = skillBullets(items, day);
524
+ for (const [skill, bullets] of skills.own) put('machine', 'skill-notes', `${skill}.md`, bullets, MAX_FEEDBACK_BULLETS);
525
+ put('machine', 'skill-notes', GENERAL_NOTES, skills.general, MAX_GENERAL_BULLETS);
526
+ for (const [skill, bullets] of skills.project) put('project', 'skill-notes', `${skill}.md`, bullets, MAX_FEEDBACK_BULLETS);
527
+ put('project', 'skill-notes', GENERAL_NOTES, skills.projectGeneral, MAX_GENERAL_BULLETS);
528
+ return targets;
529
+ }
530
+
531
+ /** What a bullet says, for the duplicate check: its date and agent off, spacing and case folded. */
532
+ const feedbackKey = (bullet) => bullet.replace(DATED_TAIL_RE, '').replace(/\s+/g, ' ').trim().toLowerCase();
533
+
534
+ /**
535
+ * A notes file's new text with `bullets` appended, or null when every one is already there (a
536
+ * second run on the same report writes nothing). The old text is kept as it was, line endings
537
+ * folded to LF; past `cap` bullets of the hook's own shape, or past `budget` characters, the
538
+ * oldest hook bullets drop. A hand-written line is never moved or dropped, and neither is a bullet
539
+ * this call adds: when hand-written text alone fills the budget, the file goes over it rather
540
+ * than lose the note just written.
541
+ */
542
+ function mergeFeedback(old, bullets, cap = MAX_FEEDBACK_BULLETS, budget = MAX_NOTE_FILE_CHARS) {
543
+ const text = String(old || '').replace(/\r\n?/g, '\n');
544
+ const lines = text ? text.replace(/\n$/, '').split('\n') : [];
545
+ let oldCount = lines.length;
546
+ const seen = new Set(lines.filter((l) => l.startsWith('- ')).map(feedbackKey));
547
+ let added = 0;
548
+ for (const b of bullets) {
549
+ const k = feedbackKey(b);
550
+ if (seen.has(k)) continue;
551
+ seen.add(k);
552
+ lines.push(b);
553
+ added += 1;
554
+ }
555
+ if (!added) return null;
556
+ const size = () => lines.reduce((n, l) => n + l.length + 1, 0);
557
+ let hooks = lines.filter((l) => HOOK_BULLET_RE.test(l)).length;
558
+ while (hooks > cap || size() > budget) {
559
+ const i = lines.slice(0, oldCount).findIndex((l) => HOOK_BULLET_RE.test(l));
560
+ if (i < 0) break;
561
+ lines.splice(i, 1);
562
+ oldCount -= 1;
563
+ hooks -= 1;
564
+ }
565
+ return `${lines.join('\n')}\n`;
566
+ }
567
+ // ---- spec-feedback twin: END
568
+
569
+ // Law I's credential pattern: a hand twin of js/hosts/hooks-prims.mjs SECRET_RE (two lines there,
570
+ // so no tool-kept line twin); tests/plugins/learn.test.mjs holds the two sources equal.
571
+ const FEEDBACK_SECRET_RE =
572
+ /\b(?:AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|sk-ant-[A-Za-z0-9_-]{20,}|xox[abprs]-[0-9A-Za-z-]{10,})\b|-----BEGIN [A-Z ]*PRIVATE KEY-----/
573
+
574
+ // The two notes roots, `{ machine, project }`: the twin of js/hosts/hooks-learn.mjs `notesRootsOf`,
575
+ // which says why. MACHINE is the tier's notes/ for every install. PROJECT is <project>/notebook:
576
+ // the install's parent for a project install (plugins in <repo>/.opencode/plugins), the git root
577
+ // of the session `root` for a global one, a linked worktree's main checkout either way; null for a
578
+ // global session outside any repo.
579
+ async function gitRootOf(dir) {
580
+ for (let d = path.resolve(dir); ;) {
581
+ try { await fs.stat(path.join(d, ".git")); return d } catch { /* walk up */ }
582
+ const up = path.dirname(d)
583
+ if (up === d) return null
584
+ d = up
585
+ }
586
+ }
587
+ // The project notes' entries in the clone's own `.git/info/exclude`: the hand twin of
588
+ // js/hosts/spec-feedback.mjs `excludeProjectNotes` (the block's text is the tool-kept
589
+ // `excludeWithNotes`). Outside a git repo nothing is written; never throws.
590
+ async function excludeProjectNotes(notebookDir) {
591
+ try {
592
+ const top = await gitRootOf(path.dirname(notebookDir))
593
+ if (!top) return false
594
+ const rel = path.relative(top, notebookDir).split(path.sep).join("/")
595
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false
596
+ let gitdir = path.join(top, ".git")
597
+ if (!(await isDir(gitdir))) {
598
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(await fs.readFile(gitdir, "utf8"))
599
+ if (!m) return false
600
+ gitdir = path.resolve(top, m[1])
601
+ try { gitdir = path.resolve(gitdir, (await fs.readFile(path.join(gitdir, "commondir"), "utf8")).trim()) } catch { /* no commondir: a submodule's own gitdir */ }
602
+ }
603
+ const file = path.join(gitdir, "info", "exclude")
604
+ const next = excludeWithNotes(await fs.readFile(file, "utf8").catch(() => ""), rel)
605
+ if (next === null) return false
606
+ await fs.mkdir(path.dirname(file), { recursive: true })
607
+ await fs.writeFile(file, next, "utf8")
608
+ return true
609
+ } catch { return false }
610
+ }
611
+ async function notesRootsOf(pluginDir = PLUGIN_DIR, root = null) {
612
+ const own = path.resolve(pluginDir, "..")
613
+ let base = null
614
+ try {
615
+ base = (await readsTier(own)) ? (root ? await gitRootOf(root) : null) : path.dirname(own)
616
+ const main = base ? await mainWorktreeOf(base) : null
617
+ if (main) base = path.join(main, path.relative(await gitRootOf(base), base))
618
+ } catch { base = null }
619
+ return { machine: path.join(machineDir(), "notes"), project: base ? path.join(base, PROJECT_NOTES_DIR) : null }
620
+ }
621
+
622
+ // The file lock, a twin of js/hosts/spec-feedback.mjs `withLock` (async here): `<file>.lock` made
623
+ // exclusively and holding its owner's token, at most 100 waits of 10 ms, then give up silently.
624
+ // Parallel child sessions end together and would otherwise lose bullets. A lock older than 10 s
625
+ // is a dead holder's: it is broken by renaming it to a name only this caller uses (one of two
626
+ // waiters wins), a fresh lock taken that way is linked back, and a holder removes the lock on
627
+ // release only while it still holds its own token.
628
+ const feedbackLockToken = () => `${process.pid}.${Math.random().toString(36).slice(2)}`
629
+ async function breakStaleFeedbackLock(lock) {
630
+ const taken = `${lock}.${feedbackLockToken()}.stale`
631
+ try { await fs.rename(lock, taken) } catch { return }
632
+ try {
633
+ if (Date.now() - (await fs.stat(taken)).mtimeMs <= 10000) await fs.link(taken, lock) // a live lock: put it back
634
+ } catch { /* the slot is taken again */ }
635
+ await fs.unlink(taken).catch(() => {})
636
+ }
637
+ async function withFeedbackLock(file, fn) {
638
+ const lock = `${file}.lock`
639
+ const token = feedbackLockToken()
640
+ for (let i = 0; i < 100; i += 1) {
641
+ let handle
642
+ try {
643
+ handle = await fs.open(lock, "wx")
644
+ } catch (e) {
645
+ // Windows: a lock unlinked while a handle is still open is "delete pending", and creating it
646
+ // again fails EPERM/EACCES, not EEXIST. A busy lock, not a fault: wait and retry.
647
+ if (["EPERM", "EACCES", "EBUSY"].includes(e?.code)) { await new Promise((r) => setTimeout(r, 10)); continue }
648
+ if (e?.code !== "EEXIST") return false
649
+ let stale = false
650
+ try { stale = Date.now() - (await fs.stat(lock)).mtimeMs > 10000 } catch { continue }
651
+ if (stale) { await breakStaleFeedbackLock(lock); continue }
652
+ await new Promise((r) => setTimeout(r, 10))
653
+ continue
654
+ }
655
+ try {
656
+ try { await handle.writeFile(token) } finally { await handle.close() }
657
+ return await fn()
658
+ } finally {
659
+ try { if ((await fs.readFile(lock, "utf8")) === token) await fs.unlink(lock) } catch { /* broken as stale */ }
660
+ }
661
+ }
662
+ return false
663
+ }
664
+
665
+ async function addFeedback(file, bullets, cap) {
666
+ if (!bullets.length) return false
667
+ return withFeedbackLock(file, async () => {
668
+ let old = ""
669
+ try {
670
+ const raw = await fs.readFile(file)
671
+ if (!raw.equals(Buffer.from(raw.toString("utf8")))) return false // not UTF-8: left whole
672
+ old = raw.toString("utf8")
673
+ } catch { /* the first note */ }
674
+ const next = mergeFeedback(old, bullets, cap)
675
+ if (next === null) return false
676
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
677
+ await fs.writeFile(tmp, next, "utf8")
678
+ // A rename onto a file a reader holds open fails EPERM on Windows for a moment: three tries.
679
+ for (let i = 0; ; i += 1) {
680
+ try { await fs.rename(tmp, file); break } catch (e) {
681
+ if (i < 2 && e?.code === "EPERM") { await new Promise((r) => setTimeout(r, 10)); continue }
682
+ await fs.unlink(tmp).catch(() => {})
683
+ throw e
684
+ }
685
+ }
686
+ return true
687
+ })
688
+ }
689
+
690
+ // A skill this install serves under that name: its SKILL.md names its own notes file. The twin of
691
+ // js/hosts/spec-feedback.mjs `liveSkill`, which says why (an alias folder or an older render does not).
692
+ async function liveSkill(skillsDir, name) {
693
+ if (!skillsDir) return false
694
+ try { return (await fs.readFile(path.join(skillsDir, name, "SKILL.md"), "utf8")).includes(`skill-notes/${name}.md`) } catch { return false }
695
+ }
696
+
697
+ // `report` is a child session's final assistant text (`agent` named), or a session's last reply
698
+ // at a turn's end (`agent` null: only `[skill:<name>]` lines count there). A skill line is kept
699
+ // only for a `liveSkill` of `skillsDir`. The twin of js/hosts/spec-feedback.mjs
700
+ // `captureSpecFeedback`, which says why. Never throws.
701
+ async function captureSpecFeedback(agent, report, roots, day = new Date().toISOString().slice(0, 10), skillsDir = null) {
702
+ try {
703
+ const at = typeof roots === "string" ? { machine: roots, project: roots } : (roots || {})
704
+ const usable = async (dir) => Boolean(dir) && (await isDir(path.dirname(dir)))
705
+ if (!(await usable(at.machine)) && !(await usable(at.project))) return []
706
+ const items = []
707
+ for (const f of specFeedbackOf(report, FEEDBACK_SECRET_RE)) {
708
+ if (f.skill ? await liveSkill(skillsDir, f.skill) : agent) items.push(f)
709
+ }
710
+ if (!items.length) return []
711
+ const written = []
712
+ for (const t of feedbackTargets(items, agent, day)) {
713
+ const root = at[t.root]
714
+ if (!(await usable(root))) continue
715
+ if (t.root === "project" && typeof roots !== "string") await excludeProjectNotes(root)
716
+ const dir = path.join(root, t.sub)
717
+ await fs.mkdir(dir, { recursive: true })
718
+ if (await addFeedback(path.join(dir, t.name), t.bullets, t.cap)) written.push(path.join(dir, t.name))
719
+ }
720
+ if (written.length) say(`spec-feedback -> ${written.join(", ")}`, "info")
721
+ return written
722
+ } catch (err) {
723
+ say(`spec-feedback skipped: ${err?.message ?? err}`)
724
+ return []
725
+ }
726
+ }
727
+
728
+ // This install's skills (`<cfg>/skills`, `<repo>/.opencode/skills`): the ones whose rendered
729
+ // machine notes are `notesRootsOf().machine`.
730
+ const SKILLS_DIR = path.join(path.dirname(PLUGIN_DIR), "skills")
731
+
732
+ // A skill runs in the main context, so its `[skill:<name>]` line is read off a session's last reply
733
+ // at EVERY turn's end (V1 `session.idle`, V2 `session.execution.succeeded`), not after the
734
+ // debounce: a skill runs mid-session, and a process closed inside the quiet window would lose the
735
+ // line. The twin of the Stop hook's capture (js/hosts/hooks-learn.mjs). One message fetch per
736
+ // turn, and none for an install that ships no skills or in an excluded folder. A child session's
737
+ // lines are read here too; the child capture writes the same bullets, which are not added twice.
738
+ // `fetchMessages` is the host's own read. Never throws.
739
+ async function captureTurn(fetchMessages, root) {
740
+ try {
741
+ if (!(await isDir(SKILLS_DIR)) || (await sovereignBypass(root))) return []
742
+ return await captureSpecFeedback(null, finalAssistantText(await fetchMessages()), await notesRootsOf(PLUGIN_DIR, root), undefined, SKILLS_DIR)
743
+ } catch (err) {
744
+ say(`spec-feedback skipped: ${err?.message ?? err}`)
745
+ return []
746
+ }
747
+ }
748
+
749
+ // The last assistant message's text, V1 (`{ info: { role }, parts }`) or V2 (`{ type, content }`).
750
+ function finalAssistantText(messages) {
751
+ for (let i = (messages || []).length - 1; i >= 0; i -= 1) {
752
+ const m = messages[i]
753
+ if (m?.info?.role === "assistant") return partsText(m.parts)
754
+ if (m?.type === "assistant") return partsText(m.content)
755
+ }
756
+ return ""
757
+ }
758
+
759
+ // ---- agent outcome ledger (notebook/agent-runs.jsonl) ---------------------------------------
760
+ // One line per finished child session that names its agent: the twin of js/hosts/agent-runs.mjs
761
+ // `recordAgentRun`. The marker table, the spec hash and the line are tool-kept below; the walk is
762
+ // by hand, since a session's messages are not a JSONL transcript.
763
+ // ---- agent-runs twin: BEGIN — adapters/opencode/plugins/geneseed-learn.js carries everything down
764
+ // to the END marker verbatim, with `export ` dropped (`node tests/twins.mjs --write` after a change).
765
+
766
+ /**
767
+ * A refused tool call: the result text a host or a gate gives a call it did not run. Only the
768
+ * result's FIRST line is read, and every marker is anchored at its start (a host prefix of at most
769
+ * 80 characters allowed for Geneseed's own words): a red test or a search that QUOTES a gate's text
770
+ * further down its output is an error, not a refusal. One row each, with where its text comes from:
771
+ * - Geneseed's own refusal (`gateText` mode `refused`, js/hosts/hooks-prims.mjs), and the text
772
+ * said when that text fails (`GATE_UNSAID`), behind a host's prefix ("PreToolUse:Bash hook …").
773
+ * - The OpenCode guard: V1 throws `[geneseed-guard] blocked: …`; V2 renames the call, and core
774
+ * answers `No tool named "BLOCKED, not a missing tool: …"` (geneseed-guard.js, seen on 2.2.6).
775
+ * - Claude Code's auto-mode classifier, seen live 2026-11-14: "Permission for this action was
776
+ * denied by the Claude Code auto mode classifier."
777
+ * - Claude Code's worktree isolation, seen live 2026-11-14: "This agent is isolated in the
778
+ * worktree …, but this command … Refusing to run it — …".
779
+ * - Claude Code's permission rule deny and a user's "no" to an ask: UNVERIFIED wording.
780
+ */
781
+ const REFUSAL_MARKERS = [
782
+ /^.{0,80}?Tell the user this, word for word:/,
783
+ /^.{0,80}?Geneseed could not describe this call\./,
784
+ /^\[geneseed-guard\] blocked:/,
785
+ /^No tool named "BLOCKED, not a missing tool:/,
786
+ /^Permission for this action was denied\b/,
787
+ /^This agent is isolated in the worktree .{1,600}? Refusing to run it\b/,
788
+ /^Permission to use \S.{0,300}? has been denied\b/,
789
+ /^The user doesn't want to (?:proceed with|take) this/,
790
+ ];
791
+
792
+ /**
793
+ * True when the first line of `text` (a tool result) says the call was refused. Each marker is
794
+ * anchored with `^` (no `m` flag) and its `.` never crosses a line break, so a marker can only
795
+ * match on the first line.
796
+ */
797
+ function isRefusal(text) {
798
+ const t = String(text ?? '').trimStart();
799
+ return REFUSAL_MARKERS.some((re) => re.test(t));
800
+ }
801
+
802
+ /** The short hash of a rendered spec: sha256 of its text with line endings folded to LF, 12 hex. */
803
+ function specHashOf(text) {
804
+ return createHash('sha256').update(String(text).replace(/\r\n?/g, '\n'), 'utf8').digest('hex').slice(0, 12);
805
+ }
806
+
807
+ /** The ledger line, field order fixed. `ts` is the UTC day, as `usage.jsonl` stamps it. */
808
+ function agentRunLine(run, now = new Date()) {
809
+ return `${JSON.stringify({
810
+ ts: now.toISOString().slice(0, 10), agent: run.agent, spec: run.spec ?? null, done: run.done ?? null,
811
+ blocks: run.blocks ?? null, tools: run.tools ?? null, refused: run.refused ?? null,
812
+ feedback: run.feedback ?? 0, report: Boolean(run.report),
813
+ })}\n`;
814
+ }
815
+ // ---- agent-runs twin: END
816
+
817
+ // The child's tool calls are its `tool` parts that name their tool: V1's `{ tool, state: { status,
818
+ // error } }` (seen), and on V2 `{ name, state? }` in `session.context()`, a shape UNVERIFIED against a
819
+ // live OpenCode 2. With no such part at all the counts are null, never a confident 0: an unknown
820
+ // shape must not read as "used no tools". A refusal is an errored part whose error text
821
+ // `isRefusal` reads as one: V1's `[geneseed-guard] blocked:`, V2 core's `No tool named "BLOCKED…`.
822
+ function toolCounts(messages) {
823
+ let tools = 0
824
+ let refused = 0
825
+ for (const m of messages || []) {
826
+ for (const p of m?.parts ?? m?.content ?? []) {
827
+ if (p?.type !== "tool" || typeof (p.tool ?? p.name) !== "string") continue
828
+ tools += 1
829
+ const state = p.state ?? {}
830
+ const e = state.error ?? p.error
831
+ const said = typeof e === "string" ? e : e?.message ?? e?.data?.message ?? ""
832
+ if ((state.status ?? p.status) === "error" && isRefusal(said)) refused += 1
833
+ }
834
+ }
835
+ return tools ? { tools, refused } : { tools: null, refused: null }
836
+ }
837
+
838
+ // The agent's rendered spec hash when this install's manifest owns `agents/<name>.md`, else null.
839
+ async function ownedSpec(cfg, agent) {
840
+ try {
841
+ const owned = JSON.parse(await fs.readFile(path.join(cfg, ".geneseed-manifest.json"), "utf8")).owned
842
+ if (!Array.isArray(owned) || !owned.includes(`agents/${agent}.md`)) return null
843
+ return specHashOf(await fs.readFile(path.join(cfg, "agents", `${agent}.md`), "utf8"))
844
+ } catch { return null }
845
+ }
846
+
847
+ // `done` and `blocks` are null here: this host's done gate is geneseed-context.js, whose verdict
848
+ // this plugin cannot read. Into the install's notebook, as usage.jsonl (`usageHome`: <cfg> for a
849
+ // global install, <repo> for a project one) and off as it is (GENESEED_NO_USAGE, `.usage-off`);
850
+ // the spec hash still comes from the plugin's own layer, `cfg` (<repo>/.opencode holds a project
851
+ // install's manifest and agents/). Beside a live project install the global copy sees the child
852
+ // too: one copy records it, the one `countingCopy` names (`here` is [directory, worktree]). Once
853
+ // per child per process: a child idles more than once. Never throws.
854
+ const recordedRuns = new Set()
855
+ async function recordAgentRun(sid, agent, messages, cfg = path.dirname(PLUGIN_DIR), here = null) {
856
+ try {
857
+ if (!agent || recordedRuns.has(sid) || process.env.GENESEED_NO_USAGE) return null
858
+ const home = usageHome(cfg)
859
+ if (!home || anotherCopyCounts(here)) return null
860
+ recordedRuns.add(sid)
861
+ const report = finalAssistantText(messages)
862
+ const line = agentRunLine({
863
+ agent, spec: await ownedSpec(cfg, agent), done: null, blocks: null, ...toolCounts(messages),
864
+ feedback: specFeedbackOf(report, FEEDBACK_SECRET_RE).filter((f) => !f.skill).length, report: Boolean(report.trim()),
865
+ })
866
+ const file = path.join(home, "notebook", "agent-runs.jsonl")
867
+ return (await withFeedbackLock(file, async () => { await fs.appendFile(file, line); return line })) || null
868
+ } catch { return null }
869
+ }
870
+
283
871
  // Flatten a session's messages into "role: text" notes, and pick the model the
284
872
  // session actually used so we distil with the user's own provider config.
285
873
  function flatten(messages) {
@@ -575,6 +1163,7 @@ export const GeneseedLearn = async (ctx) => {
575
1163
  const ours = new Set() // throwaway distil sessions — never mine our own output
576
1164
  const timers = new Map() // sid -> debounce timer, re-armed on each idle
577
1165
  const inFlight = new Set() // sid currently being distilled (guards against overlap)
1166
+ const lastReply = new Map() // sid -> id of its newest assistant message (captureTurn)
578
1167
  let warnedNoDir = false
579
1168
 
580
1169
  // The session root, as guard and context use it — not process.cwd(), which is the
@@ -596,6 +1185,19 @@ export const GeneseedLearn = async (ctx) => {
596
1185
  const agentName = isChild ? resolveAgentName(meta) : null
597
1186
  if (isChild && !agentName) return
598
1187
 
1188
+ const fetchMessages = async () => {
1189
+ const res = await client.session.messages({ path: { id: sid } })
1190
+ return Array.isArray(res) ? res : res?.data ?? []
1191
+ }
1192
+ // A child's report feedback first: it needs no store, no model and no minimum length. A
1193
+ // top-level session keeps the old order (no fetch before the store is known).
1194
+ let messages = null
1195
+ if (isChild) {
1196
+ messages = await fetchMessages()
1197
+ await captureSpecFeedback(agentName, finalAssistantText(messages), await notesRootsOf(PLUGIN_DIR, root), undefined, SKILLS_DIR)
1198
+ await recordAgentRun(sid, agentName, messages, undefined, [ctx?.directory, ctx?.worktree])
1199
+ }
1200
+
599
1201
  const memDir = await resolveMemoryDir()
600
1202
  if (!memDir) {
601
1203
  if (!warnedNoDir) {
@@ -607,9 +1209,7 @@ export const GeneseedLearn = async (ctx) => {
607
1209
  return
608
1210
  }
609
1211
 
610
- const res = await client.session.messages({ path: { id: sid } })
611
- const messages = Array.isArray(res) ? res : res?.data ?? []
612
- let { notes, model } = flatten(messages)
1212
+ let { notes, model } = flatten(messages ?? (await fetchMessages()))
613
1213
  if (notes.length < MIN_NOTES_CHARS) return
614
1214
  notes = notes.slice(-MAX_NOTES_CHARS)
615
1215
  model = model ?? envModel()
@@ -664,15 +1264,36 @@ export const GeneseedLearn = async (ctx) => {
664
1264
  event.payload?.info?.id
665
1265
  // A deleted session must not distil later from a stale timer (and its entry
666
1266
  // must not leak in the maps for the life of the process).
1267
+ // The newest assistant message per session, for the turn's capture (`message.updated`'s
1268
+ // `info` is the Message: `id`, `role`, `sessionID`).
1269
+ if (event.type === "message.updated") {
1270
+ const info = event.properties?.info
1271
+ if (info?.role === "assistant" && info.sessionID && info.id) lastReply.set(info.sessionID, info.id)
1272
+ return
1273
+ }
667
1274
  if (event.type === "session.deleted") {
668
1275
  const t = timers.get(sid)
669
1276
  if (t) clearTimeout(t)
670
1277
  timers.delete(sid)
671
1278
  ours.delete(sid)
1279
+ lastReply.delete(sid)
672
1280
  return
673
1281
  }
674
1282
  if (event.type !== "session.idle") return
675
1283
  if (!sid || ours.has(sid)) return
1284
+ // A skill's feedback line, now (captureTurn): not behind the debounce below.
1285
+ // One message, not the session: the newest assistant message `message.updated` named, read
1286
+ // by `session.message`. With none seen (a plugin loaded mid-turn), the whole history once.
1287
+ void captureTurn(async () => {
1288
+ const mid = lastReply.get(sid)
1289
+ if (mid && client.session.message) {
1290
+ const one = await client.session.message({ path: { id: sid, messageID: mid } })
1291
+ const m = one?.data ?? one
1292
+ return m ? [m] : []
1293
+ }
1294
+ const res = await client.session.messages({ path: { id: sid } })
1295
+ return Array.isArray(res) ? res : res?.data ?? []
1296
+ }, root)
676
1297
  // session.idle fires after every turn — debounce so we distil once, at the real
677
1298
  // end of the session (see header note). Each idle re-arms the timer.
678
1299
  const prev = timers.get(sid)
@@ -684,7 +1305,11 @@ export const GeneseedLearn = async (ctx) => {
684
1305
 
685
1306
  // OpenCode treats every export as a plugin and rejects non-functions; hang the test
686
1307
  // helpers off the factory instead — reachable via import, invisible to the loader.
687
- Object.assign(GeneseedLearn, { resolveMemoryDir, writeMemories, resolveAgentName, appendAgentLesson, flattenV2 })
1308
+ Object.assign(GeneseedLearn, {
1309
+ resolveMemoryDir, writeMemories, resolveAgentName, appendAgentLesson, flattenV2,
1310
+ captureSpecFeedback, captureTurn, finalAssistantText, notesRootsOf, FEEDBACK_SECRET_RE,
1311
+ recordAgentRun, toolCounts, isRefusal, specHashOf, agentRunLine,
1312
+ })
688
1313
 
689
1314
  // ---- OpenCode 2 ----------------------------------------------------------------
690
1315
  // `export default { id, server, setup }` serves V1 (>= 1.3.4) and V2 from one file — why, and
@@ -733,6 +1358,14 @@ async function setupV2(ctx) {
733
1358
  const agentName = isChild ? resolveAgentName(meta) : null
734
1359
  if (isChild && !agentName) return
735
1360
 
1361
+ // As on V1: a child is read first for its report feedback, a top-level session keeps the old order.
1362
+ let messages = null
1363
+ if (isChild) {
1364
+ messages = await ctx.session.context({ sessionID: sid })
1365
+ await captureSpecFeedback(agentName, finalAssistantText(messages), await notesRootsOf(PLUGIN_DIR, root), undefined, SKILLS_DIR)
1366
+ await recordAgentRun(sid, agentName, messages, undefined, [ctx?.location?.directory, ctx?.location?.project?.directory])
1367
+ }
1368
+
736
1369
  const memDir = await resolveMemoryDir()
737
1370
  if (!memDir) {
738
1371
  if (!warnedNoDir) {
@@ -742,7 +1375,7 @@ async function setupV2(ctx) {
742
1375
  return
743
1376
  }
744
1377
 
745
- let { notes, model } = flattenV2(await ctx.session.context({ sessionID: sid }))
1378
+ let { notes, model } = flattenV2(messages ?? (await ctx.session.context({ sessionID: sid })))
746
1379
  if (notes.length < MIN_NOTES_CHARS) return
747
1380
  notes = notes.slice(-MAX_NOTES_CHARS)
748
1381
  if (!model) {
@@ -781,6 +1414,8 @@ async function setupV2(ctx) {
781
1414
  continue
782
1415
  }
783
1416
  if (ev.type !== "session.execution.succeeded") continue
1417
+ // Fire and forget: an await here would hold the event stream the distil reads too.
1418
+ void captureTurn(() => ctx.session.context({ sessionID: sid }), root)
784
1419
  const prev = timers.get(sid)
785
1420
  if (prev) clearTimeout(prev)
786
1421
  timers.set(sid, setTimeout(() => { timers.delete(sid); runDistill(sid) }, DEBOUNCE_MS))