geneseed 5.3.1 → 5.5.0
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.
- package/CHANGELOG.md +102 -0
- package/README.md +51 -18
- package/SHIPPED.md +7 -7
- package/adapters/bob/README.md +12 -1
- package/adapters/opencode/README.md +5 -3
- package/adapters/opencode/plugins/geneseed-context.js +77 -10
- package/adapters/opencode/plugins/geneseed-guard.js +106 -22
- package/adapters/opencode/plugins/geneseed-learn.js +641 -6
- package/bin/geneseed-cli.mjs +10 -0
- package/bin/geneseed-hook.mjs +5 -4
- package/docs/PRD.md +1 -1
- package/docs/README.md +1 -0
- package/docs/concepts/agents.md +14 -2
- package/docs/concepts/collaboration.md +2 -2
- package/docs/concepts/enforcement-table.md +5 -2
- package/docs/concepts/exclusions.md +16 -2
- package/docs/concepts/footprint.md +1 -1
- package/docs/concepts/foreman-mode.md +23 -4
- package/docs/concepts/hook-gates.md +4 -4
- package/docs/concepts/hooks.md +25 -7
- package/docs/concepts/host-matrix.md +4 -4
- package/docs/concepts/hosts.md +1 -1
- package/docs/concepts/kits.md +12 -2
- package/docs/concepts/loop-bricks.md +3 -3
- package/docs/concepts/loops.md +6 -4
- package/docs/concepts/ownership.md +1 -1
- package/docs/concepts/rules.md +2 -2
- package/docs/concepts/shared-tier.md +1 -1
- package/docs/concepts/skills.md +21 -1
- package/docs/concepts/themes.md +1 -1
- package/docs/extending.md +73 -29
- package/docs/guides/auto-merge.md +100 -0
- package/docs/guides/choose-your-setup.md +1 -1
- package/docs/guides/headless.md +1 -1
- package/docs/guides/install-clone.md +19 -1
- package/docs/guides/install-scripted.md +8 -2
- package/docs/guides/install.md +20 -2
- package/docs/guides/loop-finish.md +3 -3
- package/docs/guides/loop-running.md +4 -4
- package/docs/guides/project-context.md +1 -1
- package/docs/guides/run-a-factory.md +2 -2
- package/docs/guides/setup-doctrines.md +2 -2
- package/docs/guides/setup-footprint.md +1 -1
- package/docs/guides/uninstall.md +3 -3
- package/docs/guides/upgrade.md +2 -2
- package/docs/guides/worktree.md +1 -1
- package/docs/reference/env-context.md +1 -1
- package/docs/reference/environment.md +4 -2
- package/docs/reference/plugin-activity.md +1 -1
- package/docs/reference/plugin-guard.md +1 -1
- package/docs/reference/plugin-learn.md +5 -1
- package/docs/reference/plugin-workflow.md +1 -1
- package/docs/reference/profiles.md +142 -0
- package/docs/reference/troubleshoot-doctor.md +1 -1
- package/docs/reference/troubleshoot-hooks.md +2 -2
- package/docs/reference/troubleshoot-install.md +3 -3
- package/docs/reference/troubleshoot-tools.md +1 -1
- package/docs/token-footprint.md +11 -6
- package/docs/understand/design-choices-engineering.md +1 -1
- package/docs/understand/enforced-vs-asked.md +1 -1
- package/docs/understand/machine-claude.md +2 -2
- package/docs/understand/on-your-machine.md +1 -1
- package/docs/web-ui.md +8 -6
- package/harness.config.json +1 -1
- package/js/README.md +11 -3
- package/js/build/args.mjs +16 -4
- package/js/build/catalog.mjs +11 -1
- package/js/build/driver.mjs +74 -16
- package/js/build/emit-claude.mjs +32 -5
- package/js/build/emit-opencode.mjs +16 -9
- package/js/build/export.mjs +1 -1
- package/js/build/generate.mjs +12 -157
- package/js/build/notes-migrate.mjs +99 -0
- package/js/build/profile.mjs +326 -0
- package/js/build/render.mjs +110 -8
- package/js/build/retired-skills.mjs +60 -13
- package/js/build/source.mjs +100 -3
- package/js/build/stubs.mjs +4 -1
- package/js/cli-table.json +212 -7
- package/js/hosts/agent-runs.mjs +205 -0
- package/js/hosts/done-checks.mjs +3 -1
- package/js/hosts/hooks-done.mjs +428 -63
- package/js/hosts/hooks-learn.mjs +89 -3
- package/js/hosts/hooks-prims.mjs +44 -4
- package/js/hosts/hooks.mjs +159 -9
- package/js/hosts/hosts.mjs +10 -0
- package/js/hosts/installs.mjs +44 -2
- package/js/hosts/link.mjs +45 -10
- package/js/hosts/native.mjs +61 -7
- package/js/hosts/opencode.mjs +1 -1
- package/js/hosts/settings.mjs +101 -3
- package/js/hosts/spec-feedback.mjs +538 -0
- package/js/hosts/usage.mjs +67 -8
- package/js/inspect/agent-scores.mjs +118 -0
- package/js/inspect/checks-authoring.mjs +2 -1
- package/js/inspect/checks-build.mjs +20 -4
- package/js/inspect/checks-constitution.mjs +32 -0
- package/js/inspect/checks-repo.mjs +27 -2
- package/js/inspect/cost.mjs +6 -5
- package/js/inspect/diff.mjs +46 -8
- package/js/inspect/doctor.mjs +4 -0
- package/js/inspect/inventory.mjs +1 -1
- package/js/inspect/status.mjs +3 -1
- package/js/inspect/validate.mjs +1 -0
- package/js/lib/machine-dir.mjs +8 -0
- package/js/lib/paths.mjs +4 -1
- package/js/maintain/profile-scope.mjs +145 -0
- package/js/maintain/profiles.mjs +486 -0
- package/js/maintain/setup.mjs +413 -15
- package/js/maintain/uninstall.mjs +4 -1
- package/js/maintain/update.mjs +4 -2
- package/js/web/actions.mjs +44 -41
- package/js/web/api.mjs +13 -3
- package/js/web/handler.mjs +8 -0
- package/js/web/jobs.mjs +5 -4
- package/js/web/profiles-api.mjs +201 -0
- package/js/web/routes.mjs +5 -0
- package/package.json +2 -1
- package/profiles/guillaume-claude-global.json +16 -0
- package/profiles/starter.json +14 -0
- package/registry.json +14 -0
- package/src/AGENT.md.tmpl +16 -18
- package/src/agents/_self-improvement.md +15 -7
- package/src/agents/_template.md +4 -2
- package/src/agents/advocate.md +1 -1
- package/src/agents/architect.md +1 -1
- package/src/agents/developer.md +10 -3
- package/src/agents/devops-engineer.md +1 -1
- package/src/agents/docker-expert.md +1 -1
- package/src/agents/docs.md +1 -1
- package/src/agents/empiricist.md +1 -1
- package/src/agents/explorer.md +4 -2
- package/src/agents/framer.md +1 -1
- package/src/agents/historian.md +1 -1
- package/src/agents/kubernetes-specialist.md +1 -1
- package/src/agents/memory-curator.md +1 -1
- package/src/agents/operator.md +1 -1
- package/src/agents/performance.md +1 -1
- package/src/agents/pragmatist.md +1 -1
- package/src/agents/react-engineer.md +1 -1
- package/src/agents/react-reviewer.md +1 -1
- package/src/agents/researcher.md +1 -1
- package/src/agents/reviewer.md +10 -3
- package/src/agents/security.md +1 -1
- package/src/agents/skeptic.md +1 -1
- package/src/agents/spring-boot-engineer.md +1 -1
- package/src/agents/spring-reviewer.md +1 -1
- package/src/agents/spring-security.md +1 -1
- package/src/agents/steward.md +1 -1
- package/src/agents/tester.md +4 -2
- package/src/agents/user-advocate.md +1 -1
- package/src/agents/visionary.md +1 -1
- package/src/bricks/pr-open.md +3 -2
- package/src/doctrines/ops.md +2 -2
- package/src/doctrines/process.md +40 -36
- package/src/factories/analysis-to-build.json +1 -1
- package/src/factories/bug-report-to-fix.json +1 -1
- package/src/factories/issue-to-pr.json +1 -1
- package/src/kits/terminal-tools/rules.md +10 -0
- package/src/kits/terminal-tools.json +13 -0
- package/src/licenses/herdr.txt +201 -0
- package/src/memory/README.md +12 -2
- package/src/modes/foreman.md +25 -9
- package/src/skill-descriptions.json +63 -0
- package/src/skills/_self-improvement.md +42 -24
- package/src/skills/_template.md +3 -1
- package/src/skills/brainstorm.md +35 -22
- package/src/skills/commit.md +17 -17
- package/src/skills/daydream/VENDOR.md +6 -0
- package/src/skills/debug/ci.md +1 -1
- package/src/skills/dependencies.md +3 -3
- package/src/skills/diagram-design/VENDOR.md +4 -0
- package/src/skills/document-project.md +3 -2
- package/src/skills/explain-changes/VENDOR.md +5 -1
- package/src/skills/factory.md +13 -4
- package/src/skills/geneseed.md +4 -2
- package/src/skills/git-history.md +5 -7
- package/src/skills/herdr.md +135 -0
- package/src/skills/loop.md +3 -2
- package/src/skills/opencode-cli.md +84 -0
- package/src/skills/parallel-agents.md +11 -0
- package/src/skills/pipeline.md +3 -3
- package/src/skills/plan.md +5 -4
- package/src/skills/react-view-transitions/VENDOR.md +7 -1
- package/src/skills/release.md +11 -9
- package/src/skills/review-response.md +4 -2
- package/src/skills/rule/approve.md +2 -1
- package/src/skills/rule.md +27 -1
- package/src/skills/ship.md +54 -7
- package/src/skills/skill-forge.md +5 -3
- package/src/skills/token-report/VENDOR.md +5 -1
- package/src/skills/worktree.md +2 -2
- package/src/upstreams.json +9 -2
- package/themes/README.md +3 -1
- package/themes/_TEMPLATE.json +2 -0
- package/themes/biker.json +2 -0
- package/themes/commentator.json +2 -0
- package/themes/cyberpunk.json +2 -0
- package/themes/gamer.json +2 -0
- package/themes/imperial.json +2 -0
- package/themes/joker.json +2 -0
- package/themes/marvin.json +2 -0
- package/themes/mean.json +2 -0
- package/themes/military.json +2 -0
- package/themes/neutral.json +2 -0
- package/themes/pirate.json +2 -0
- package/themes/sports.json +2 -0
- package/themes/verstappen.json +2 -0
- package/themes/wizard.json +2 -0
- package/web/dist/assets/{ActiveLoops-BJJN3P-V.js → ActiveLoops-DOJCPPPc.js} +1 -1
- package/web/dist/assets/Activity-LKsDzsnK.js +1 -0
- package/web/dist/assets/ActivityDetail-DhwTfPm6.js +1 -0
- package/web/dist/assets/{Bonsai-BBl4XXqs.js → Bonsai-CePMLrpr.js} +1 -1
- package/web/dist/assets/{CopyButton-Beven8yn.js → CopyButton-CuoaJ6k7.js} +1 -1
- package/web/dist/assets/Dashboard-D1VKuvLe.js +2 -0
- package/web/dist/assets/Docs-CUrHJKaU.js +5 -0
- package/web/dist/assets/Factories-Ci1XfmSy.js +1 -0
- package/web/dist/assets/{GreenhouseView-Bce212qd.js → GreenhouseView-CNfH2lPK.js} +1 -1
- package/web/dist/assets/Installs-ZHQZM1iS.js +3 -0
- package/web/dist/assets/{JournalView-CV4omyww.js → JournalView-CMsWahkS.js} +1 -1
- package/web/dist/assets/Kits-CkliyK0n.js +1 -0
- package/web/dist/assets/Laws-hh4O3HZ4.js +4 -0
- package/web/dist/assets/{LibRows-Dag1s0ZX.js → LibRows-Brv0Hmkr.js} +1 -1
- package/web/dist/assets/Library-BYmiLjJr.js +3 -0
- package/web/dist/assets/Loops-ytm-xJ68.js +2 -0
- package/web/dist/assets/{OperatorHudView-JmYY1pBR.js → OperatorHudView-KaqCx_HP.js} +1 -1
- package/web/dist/assets/Personal-CmcnRKYE.js +2 -0
- package/web/dist/assets/Settings-tUrpdOfq.js +1 -0
- package/web/dist/assets/{Tabs-8zsyEPSK.js → Tabs-CD7etcGD.js} +1 -1
- package/web/dist/assets/api-CZ-x0iWG.js +1 -0
- package/web/dist/assets/{controls-D4wmg_pl.js → controls-CK7qHA8H.js} +1 -1
- package/web/dist/assets/{index-CRWqKxfY.css → index-Ba_Kg3Af.css} +1 -1
- package/web/dist/assets/index-COKbhFNo.js +6 -0
- package/web/dist/index.html +3 -3
- package/web/dist/assets/Activity-WQ3ykgxU.js +0 -1
- package/web/dist/assets/ActivityDetail-7rt04SkS.js +0 -1
- package/web/dist/assets/Dashboard-BgLArtgu.js +0 -2
- package/web/dist/assets/Docs-B5aHp86J.js +0 -5
- package/web/dist/assets/Factories-BjqzXAw8.js +0 -1
- package/web/dist/assets/Installs-B1OsrHXF.js +0 -3
- package/web/dist/assets/Kits-CW1e7xNa.js +0 -1
- package/web/dist/assets/Laws-1Ckf1lbs.js +0 -4
- package/web/dist/assets/Library-B3FuFLel.js +0 -3
- package/web/dist/assets/Loops-CwqgnLNw.js +0 -2
- package/web/dist/assets/Personal-DKLgLa7Z.js +0 -2
- package/web/dist/assets/Settings-BwErnh-R.js +0 -1
- package/web/dist/assets/api-DLDVY3K-.js +0 -1
- package/web/dist/assets/index-Ce6qF2nG.js +0 -6
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agents' self-improvement loop, captured by the hook: every `spec-feedback:` line a sub-agent
|
|
3
|
+
* ends its report with (src/agents/_self-improvement.md) goes into the notes the agent reads at its
|
|
4
|
+
* next dispatch, `<notes>/agent-notes/<agent>.md`, or for a `general` one `_general.md`, which every agent reads.
|
|
5
|
+
* The skills' loop is the same line tagged `[skill:<name>]` (src/skills/_self-improvement.md),
|
|
6
|
+
* read off the main session's final reply on Stop (`turnReply`) and off a sub-agent's report on
|
|
7
|
+
* SubagentStop, into `<notes>/skill-notes/<name>.md` or `skill-notes/_general.md`: the skills'
|
|
8
|
+
* notes stayed empty the same way (73 runs in 30 days, 20 with friction, no note written).
|
|
9
|
+
* Each line also names its scope: the machine notes (the tier) or this project's
|
|
10
|
+
* (`<project>/notebook`), `PROJECT_NOTES_DIR` below.
|
|
11
|
+
*
|
|
12
|
+
* WHY A HOOK AND NOT THE CALLER. The include used to tell the caller to write the line down. That
|
|
13
|
+
* is model discipline, and it never happened: the tier's `agent-notes/` stayed empty for weeks
|
|
14
|
+
* while sub-agents kept emitting the lines. So the capture is mechanical, on SubagentStop, and it
|
|
15
|
+
* needs no model: it copies what the agent wrote, it does not judge it. `$GENESEED_LLM` decides
|
|
16
|
+
* only the separate lesson distil into `memory/agents/` (`./hooks-learn.mjs`).
|
|
17
|
+
*
|
|
18
|
+
* Builtins and `./hooks-prims.mjs` only, no spawn: `learn` imports this on every Stop and SubagentStop.
|
|
19
|
+
* Nothing here prints. The caller swallows a throw, so a bad file never fails a hook.
|
|
20
|
+
*/
|
|
21
|
+
import { isUtf8 } from 'node:buffer';
|
|
22
|
+
import {
|
|
23
|
+
closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync,
|
|
24
|
+
} from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { SECRET_RE, splitLines } from './hooks-prims.mjs';
|
|
27
|
+
import { gitCommonDirOf, gitRootOf, mainWorktreeOf } from './gitref.mjs';
|
|
28
|
+
|
|
29
|
+
// ---- spec-feedback twin: BEGIN — adapters/opencode/plugins/geneseed-learn.js carries everything down
|
|
30
|
+
// to the END marker verbatim, with `export ` dropped (`node tests/twins.mjs --write` after a change).
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* One report line: `spec-feedback: [agent|general] <fix> [— situation: …] — seen: …`, at the start
|
|
34
|
+
* of the line after an optional list marker, and optionally wrapped in backticks or bold. A line
|
|
35
|
+
* that only names the protocol ("No spec-feedback.", "The reviewer's spec-feedback: …") does not
|
|
36
|
+
* start with it, so it is no feedback; nor is a quoted (`>`) line or one inside a code fence: both
|
|
37
|
+
* show someone else's line. Real reports write the scope four ways (`[agent]`, `agent`,
|
|
38
|
+
* `agent —`, none), and some copy the template's `[agent|general]`; a missing or unchosen scope
|
|
39
|
+
* reads as `agent`.
|
|
40
|
+
*/
|
|
41
|
+
const FEEDBACK_LINE_RE = /^[ \t]*(?:[-*+][ \t]+)*(\*\*|`)?spec-feedback[ \t]*:(\*\*|`)?[ \t]*(.*)$/i;
|
|
42
|
+
const FENCE_RE = /^[ \t]*(?:```|~~~)/;
|
|
43
|
+
// A bare scope word stands alone: `agent-notes/…` and `general-purpose …` open a body, not a scope.
|
|
44
|
+
// `[agent:project]` (or bare `agent:project`) is the agent's own line kept for this repo only, and
|
|
45
|
+
// `[general:project]` (or bare `general:project`) the line every agent reads in this repo only.
|
|
46
|
+
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;
|
|
47
|
+
// What opens an agent's tag at all, parsed or not: `[project]`, `[agent project]`, `[agent:local]`
|
|
48
|
+
// do not parse, and are dropped rather than filed, tag and all, in the machine notes.
|
|
49
|
+
const AGENT_OPENING_RE = /^\[[ \t]*(?:agent|general|project)\b/i;
|
|
50
|
+
/**
|
|
51
|
+
* A skill's scope, which always names the skill: `[skill:<name>]` for that skill's own notes,
|
|
52
|
+
* `[skill:<name>:general]` (or `, general` / ` general`) for the notes every skill shares, and
|
|
53
|
+
* `[skill:<name>:project]` for its own notes in this repo only, and `[skill:<name>:general:project]`
|
|
54
|
+
* for the notes every skill shares in this repo only. The
|
|
55
|
+
* name is required because the main session's reply, where a skill's line is read, also relays
|
|
56
|
+
* sub-agents' `[agent]` and `[general]` lines: only a line naming a skill is a skill's. A `|`
|
|
57
|
+
* before `general` is the template's unchosen alternative, as `[agent|general]` is: own notes.
|
|
58
|
+
* The bracket's content is taken whole, and a name that is no slug (the template's `<name>`, a
|
|
59
|
+
* path) drops the line rather than letting `[skill:…]` fall through into an agent's notes. The
|
|
60
|
+
* brackets may be dropped (`skill:debug — …`), as reports drop them around `agent`, scope and all (`skill:debug:project — …`).
|
|
61
|
+
*/
|
|
62
|
+
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;
|
|
63
|
+
const SKILL_NAME_RE = /^[a-z][a-z0-9-]{0,63}$/;
|
|
64
|
+
// What opens a skill's tag at all, parsed or not.
|
|
65
|
+
const SKILL_OPENING_RE = /^(?:\[[ \t]*skill\b|skill[ \t]*:)/i;
|
|
66
|
+
// "none" as the whole answer, or before punctuation or a dash; "none of the proof commands…" is feedback.
|
|
67
|
+
const FEEDBACK_NONE_RE = /^(?:none|n\/a|nothing|no friction)[ \t]*(?:$|[.,;:!—–-])/i;
|
|
68
|
+
/** The include's own template, which a report may quote: never a note. */
|
|
69
|
+
export const FEEDBACK_PLACEHOLDER = '<the one-line fix>';
|
|
70
|
+
/**
|
|
71
|
+
* The step-0 footprint: every dispatch reads its own notes and `_general.md`. Past the bullet cap,
|
|
72
|
+
* or past the character budget, the oldest of the HOOK'S bullets drop (a hand-written line is
|
|
73
|
+
* never dropped). An agent's own file keeps 100, as `memory/agents/` does; the general file 30.
|
|
74
|
+
*/
|
|
75
|
+
export const MAX_FEEDBACK_BULLETS = 100;
|
|
76
|
+
export const MAX_GENERAL_BULLETS = 30;
|
|
77
|
+
export const MAX_NOTE_FILE_CHARS = 8000;
|
|
78
|
+
/** A body past this many characters is cut, so one runaway line cannot fill the file. */
|
|
79
|
+
export const MAX_FEEDBACK_CHARS = 500;
|
|
80
|
+
/** The general file's name. `_` keeps it apart from every agent: an agent name starts with a letter. */
|
|
81
|
+
export const GENERAL_NOTES = '_general.md';
|
|
82
|
+
/**
|
|
83
|
+
* TWO SCOPES, chosen by the line, never by the install (the owner's ruling, 2026-11-15). A flaw of
|
|
84
|
+
* the spec is true in every repo: `[agent]`, `[general]`, `[skill:<id>]`, `[skill:<id>:general]` go
|
|
85
|
+
* to the MACHINE notes, the tier's `notes/`. A fact true only in this repo, `[agent:project]`,
|
|
86
|
+
* `[general:project]`, `[skill:<id>:project]` or `[skill:<id>:general:project]`, goes to the
|
|
87
|
+
* PROJECT notes, `<project root>/notebook/`, one folder for every host, with its own `_general.md`
|
|
88
|
+
* files. The render names this folder relative to the project root (`{{PATH_PROJECT_NOTES}}`).
|
|
89
|
+
*/
|
|
90
|
+
export const PROJECT_NOTES_DIR = 'notebook';
|
|
91
|
+
/**
|
|
92
|
+
* THE PROJECT NOTES NEVER REACH A COMMIT, and Geneseed writes no file into the user's tree to say so
|
|
93
|
+
* (the owner's ruling, 2026-11-15): the ignore entries go into the clone's own `.git/info/exclude`,
|
|
94
|
+
* per clone and never committed. That covers a fresh repo, a repo whose `notebook/` is tracked, and an
|
|
95
|
+
* unrelated `notebook/` folder alike, since only the notes folders and the migration's archives are
|
|
96
|
+
* named. `rel` is the notebook's path from the git root, `/`-separated. The exclude file's new text,
|
|
97
|
+
* or null when every entry is already there: the block is added once, and only its missing lines after.
|
|
98
|
+
*/
|
|
99
|
+
export const EXCLUDE_HEAD = '# Geneseed: the project notes stay on this clone, never committed';
|
|
100
|
+
export function excludeWithNotes(text, rel) {
|
|
101
|
+
const lines = String(text || '').replace(/\r\n?/g, '\n').split('\n').map((l) => l.trim());
|
|
102
|
+
const want = ['agent-notes', 'skill-notes', 'archived-agent-notes', 'archived-skill-notes'].map((sub) => `/${rel}/${sub}/`);
|
|
103
|
+
const missing = want.filter((w) => !lines.includes(w));
|
|
104
|
+
if (!missing.length) return null;
|
|
105
|
+
const old = String(text || '').replace(/\r\n?/g, '\n');
|
|
106
|
+
const add = [...(lines.includes(EXCLUDE_HEAD) ? [] : [EXCLUDE_HEAD]), ...missing];
|
|
107
|
+
return `${old}${old && !old.endsWith('\n') ? '\n' : ''}${add.join('\n')}\n`;
|
|
108
|
+
}
|
|
109
|
+
// A bullet's dated tail, `(2026-11-14)` or `(tester, 2026-11-14)`: not part of what it says.
|
|
110
|
+
const DATED_TAIL_RE = /[ \t]*\((?:[a-z][a-z0-9-]*, )?\d{4}-\d{2}-\d{2}\)[ \t]*$/;
|
|
111
|
+
// A bullet in the shape this capture writes: the only kind the caps may drop.
|
|
112
|
+
// Every bullet the hook writes names its writer beside the date, `(<agent or skill>, date)`: that
|
|
113
|
+
// is what tells it from a line written by hand (the notes were hand-written as `- [skill] … (date)`
|
|
114
|
+
// before the hook), and a hand-written line is never dropped (the owner's ruling, 2026-11-15).
|
|
115
|
+
// `[agent]` bullets written before the name was added read as hand lines now: kept, never pruned.
|
|
116
|
+
const HOOK_BULLET_RE = /^- \[(?:agent|general|skill)\] .*\([a-z][a-z0-9-]*, \d{4}-\d{2}-\d{2}\)[ \t]*$/;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Every feedback line in `text` as `{ scope, body }`, in order, each body once. `secret` is Law
|
|
120
|
+
* I's pattern: a line that carries a credential is dropped whole, never written to a note. An
|
|
121
|
+
* agent's scope is `agent`, `general`, `project` or `project-general`. A skill's line also carries
|
|
122
|
+
* `skill: <name>`, its scope `skill` (own notes), `general`, `project` or `project-general`.
|
|
123
|
+
*/
|
|
124
|
+
export function specFeedbackOf(text, secret) {
|
|
125
|
+
const found = [];
|
|
126
|
+
let fenced = false;
|
|
127
|
+
for (const line of String(text || '').split(/\r?\n/)) {
|
|
128
|
+
if (FENCE_RE.test(line)) { fenced = !fenced; continue; }
|
|
129
|
+
if (fenced) continue;
|
|
130
|
+
const m = FEEDBACK_LINE_RE.exec(line);
|
|
131
|
+
if (!m) continue;
|
|
132
|
+
let body = m[3].trim();
|
|
133
|
+
// `**spec-feedback:** …` closed its wrapper at the colon; `` `spec-feedback: …` `` closes it at the end.
|
|
134
|
+
if (m[1] && !m[2] && body.endsWith(m[1])) body = body.slice(0, -m[1].length).trim();
|
|
135
|
+
let scope = 'agent';
|
|
136
|
+
let skill = null;
|
|
137
|
+
const k = SKILL_SCOPE_RE.exec(body);
|
|
138
|
+
if (k) {
|
|
139
|
+
skill = (k[1] ?? k[4]).toLowerCase();
|
|
140
|
+
if (!SKILL_NAME_RE.test(skill)) continue;
|
|
141
|
+
// A skill line wrapped in inline code is an example the reply quotes (a summary of this very
|
|
142
|
+
// format), not the reply's own line: the main session discusses the format, an agent's
|
|
143
|
+
// report does not. A whole-line `spec-feedback:` in backticks stays an agent's line.
|
|
144
|
+
if (m[1] === '`') continue;
|
|
145
|
+
const tag = (k[3] && k[2] !== '|' ? k[3] : k[5] ?? '').toLowerCase().replace(/[ \t]/g, '');
|
|
146
|
+
scope = tag === 'general:project' ? 'project-general' : tag || 'skill';
|
|
147
|
+
body = body.slice(k[0].length);
|
|
148
|
+
} else if (SKILL_OPENING_RE.test(body)) {
|
|
149
|
+
continue; // a skill tag that does not parse (`[skill:a:b]`, `[skill:a, b]`) is no agent's line
|
|
150
|
+
} else {
|
|
151
|
+
const s = FEEDBACK_SCOPE_RE.exec(body);
|
|
152
|
+
if (!s && AGENT_OPENING_RE.test(body)) continue;
|
|
153
|
+
const g = s ? s.groups : {};
|
|
154
|
+
const projectTag = g.pw || g.pb;
|
|
155
|
+
if (projectTag) scope = projectTag.toLowerCase() === 'general' ? 'project-general' : 'project';
|
|
156
|
+
else if (g.own || g.bare) scope = (g.own || g.bare).toLowerCase();
|
|
157
|
+
if (s) body = body.slice(s[0].length);
|
|
158
|
+
}
|
|
159
|
+
body = body.replace(/\s+/g, ' ').trim();
|
|
160
|
+
if (body.length < 10 || FEEDBACK_NONE_RE.test(body) || body.includes(FEEDBACK_PLACEHOLDER)) continue;
|
|
161
|
+
if (secret && secret.test(body)) continue;
|
|
162
|
+
if (body.length > MAX_FEEDBACK_CHARS) body = `${body.slice(0, MAX_FEEDBACK_CHARS).trimEnd()}…`;
|
|
163
|
+
if (found.some((f) => f.body === body && (f.skill ?? null) === skill)) continue;
|
|
164
|
+
found.push(skill ? { scope, skill, body } : { scope, body });
|
|
165
|
+
}
|
|
166
|
+
return found;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The note bullets for one report: an `agent` line goes to the agent's own file, a `general` line
|
|
171
|
+
* to `_general.md` only (with the agent's name), which every agent reads too. One home each. A
|
|
172
|
+
* skill's line is not the agent's: `skillBullets` takes it.
|
|
173
|
+
*/
|
|
174
|
+
export function feedbackBullets(items, agent, day) {
|
|
175
|
+
const mine = items.filter((f) => !f.skill);
|
|
176
|
+
const own = (scope) => mine.filter((f) => f.scope === scope).map((f) => `- [agent] ${f.body} (${agent}, ${day})`);
|
|
177
|
+
const general = (scope) => mine.filter((f) => f.scope === scope).map((f) => `- [general] ${f.body} (${agent}, ${day})`);
|
|
178
|
+
return {
|
|
179
|
+
own: own('agent'),
|
|
180
|
+
general: general('general'),
|
|
181
|
+
// The same bullet shapes in the project's files: where a bullet sits says its scope.
|
|
182
|
+
project: own('project'),
|
|
183
|
+
projectGeneral: general('project-general'),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The same for the skills' lines, into `skill-notes/`: `own` maps each skill to its bullets,
|
|
189
|
+
* `- [skill] … (<skill>, date)`; a general line goes to `skill-notes/_general.md`, which every
|
|
190
|
+
* skill reads, in the same shape as `[general]`. The name beside the date is what tells a hook
|
|
191
|
+
* bullet from the `- [skill] … (date)` lines written by hand before the hook: those are never
|
|
192
|
+
* dropped, and the duplicate check reads past both tails, so the same words are one note.
|
|
193
|
+
*/
|
|
194
|
+
export function skillBullets(items, day) {
|
|
195
|
+
const own = new Map();
|
|
196
|
+
const project = new Map();
|
|
197
|
+
const general = [];
|
|
198
|
+
const projectGeneral = [];
|
|
199
|
+
for (const f of items) {
|
|
200
|
+
if (!f.skill) continue;
|
|
201
|
+
if (f.scope === 'general' || f.scope === 'project-general') {
|
|
202
|
+
(f.scope === 'general' ? general : projectGeneral).push(`- [general] ${f.body} (${f.skill}, ${day})`);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
const into = f.scope === 'project' ? project : own;
|
|
206
|
+
if (!into.has(f.skill)) into.set(f.skill, []);
|
|
207
|
+
into.get(f.skill).push(`- [skill] ${f.body} (${f.skill}, ${day})`);
|
|
208
|
+
}
|
|
209
|
+
return { own, general, project, projectGeneral };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Every file one report writes, `{ root, sub, name, bullets, cap }` in the order the capture
|
|
214
|
+
* writes them: `root` is `machine` (the tier's notes) or `project` (`<project>/notebook`). A Stop
|
|
215
|
+
* passes no agent, so an agent's line there (relayed from a sub-agent) has no target. The one
|
|
216
|
+
* routing table: the hook and the OpenCode plugin both write what this returns.
|
|
217
|
+
*/
|
|
218
|
+
export function feedbackTargets(items, agent, day) {
|
|
219
|
+
const targets = [];
|
|
220
|
+
const put = (root, sub, name, bullets, cap) => { if (bullets.length) targets.push({ root, sub, name, bullets, cap }); };
|
|
221
|
+
if (agent) {
|
|
222
|
+
const { own, general, project, projectGeneral } = feedbackBullets(items, agent, day);
|
|
223
|
+
put('machine', 'agent-notes', `${agent}.md`, own, MAX_FEEDBACK_BULLETS);
|
|
224
|
+
put('machine', 'agent-notes', GENERAL_NOTES, general, MAX_GENERAL_BULLETS);
|
|
225
|
+
put('project', 'agent-notes', `${agent}.md`, project, MAX_FEEDBACK_BULLETS);
|
|
226
|
+
put('project', 'agent-notes', GENERAL_NOTES, projectGeneral, MAX_GENERAL_BULLETS);
|
|
227
|
+
}
|
|
228
|
+
const skills = skillBullets(items, day);
|
|
229
|
+
for (const [skill, bullets] of skills.own) put('machine', 'skill-notes', `${skill}.md`, bullets, MAX_FEEDBACK_BULLETS);
|
|
230
|
+
put('machine', 'skill-notes', GENERAL_NOTES, skills.general, MAX_GENERAL_BULLETS);
|
|
231
|
+
for (const [skill, bullets] of skills.project) put('project', 'skill-notes', `${skill}.md`, bullets, MAX_FEEDBACK_BULLETS);
|
|
232
|
+
put('project', 'skill-notes', GENERAL_NOTES, skills.projectGeneral, MAX_GENERAL_BULLETS);
|
|
233
|
+
return targets;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** What a bullet says, for the duplicate check: its date and agent off, spacing and case folded. */
|
|
237
|
+
export const feedbackKey = (bullet) => bullet.replace(DATED_TAIL_RE, '').replace(/\s+/g, ' ').trim().toLowerCase();
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* A notes file's new text with `bullets` appended, or null when every one is already there (a
|
|
241
|
+
* second run on the same report writes nothing). The old text is kept as it was, line endings
|
|
242
|
+
* folded to LF; past `cap` bullets of the hook's own shape, or past `budget` characters, the
|
|
243
|
+
* oldest hook bullets drop. A hand-written line is never moved or dropped, and neither is a bullet
|
|
244
|
+
* this call adds: when hand-written text alone fills the budget, the file goes over it rather
|
|
245
|
+
* than lose the note just written.
|
|
246
|
+
*/
|
|
247
|
+
export function mergeFeedback(old, bullets, cap = MAX_FEEDBACK_BULLETS, budget = MAX_NOTE_FILE_CHARS) {
|
|
248
|
+
const text = String(old || '').replace(/\r\n?/g, '\n');
|
|
249
|
+
const lines = text ? text.replace(/\n$/, '').split('\n') : [];
|
|
250
|
+
let oldCount = lines.length;
|
|
251
|
+
const seen = new Set(lines.filter((l) => l.startsWith('- ')).map(feedbackKey));
|
|
252
|
+
let added = 0;
|
|
253
|
+
for (const b of bullets) {
|
|
254
|
+
const k = feedbackKey(b);
|
|
255
|
+
if (seen.has(k)) continue;
|
|
256
|
+
seen.add(k);
|
|
257
|
+
lines.push(b);
|
|
258
|
+
added += 1;
|
|
259
|
+
}
|
|
260
|
+
if (!added) return null;
|
|
261
|
+
const size = () => lines.reduce((n, l) => n + l.length + 1, 0);
|
|
262
|
+
let hooks = lines.filter((l) => HOOK_BULLET_RE.test(l)).length;
|
|
263
|
+
while (hooks > cap || size() > budget) {
|
|
264
|
+
const i = lines.slice(0, oldCount).findIndex((l) => HOOK_BULLET_RE.test(l));
|
|
265
|
+
if (i < 0) break;
|
|
266
|
+
lines.splice(i, 1);
|
|
267
|
+
oldCount -= 1;
|
|
268
|
+
hooks -= 1;
|
|
269
|
+
}
|
|
270
|
+
return `${lines.join('\n')}\n`;
|
|
271
|
+
}
|
|
272
|
+
// ---- spec-feedback twin: END
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The text of a sub-agent's FINAL message in a Claude-Code JSONL transcript, or null when the
|
|
276
|
+
* text holds no assistant line (the tail reader then reads further back). The host writes one
|
|
277
|
+
* message as one line per content block, all under one `message.id`, so every line of the last
|
|
278
|
+
* id counts. Its text blocks count, and so does a tool call's `input.message`: an Agent-SDK
|
|
279
|
+
* sub-agent ends with `SubagentHandback({ message })`, and its report lives there, not in a text
|
|
280
|
+
* block (seen in 330 of 500 sub-agent transcripts here, 2026-11).
|
|
281
|
+
*/
|
|
282
|
+
export function finalAssistantText(raw) {
|
|
283
|
+
const entries = [];
|
|
284
|
+
for (const line of splitLines(raw)) {
|
|
285
|
+
if (!line.trim()) continue;
|
|
286
|
+
try { entries.push(JSON.parse(line)); } catch { /* a torn line is no message */ }
|
|
287
|
+
}
|
|
288
|
+
const isAssistant = (o) => o && (o.type === 'assistant' || (o.message && o.message.role === 'assistant'));
|
|
289
|
+
let last = -1;
|
|
290
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) if (isAssistant(entries[i])) { last = i; break; }
|
|
291
|
+
if (last < 0) return null;
|
|
292
|
+
const id = entries[last].message && entries[last].message.id;
|
|
293
|
+
const lines = id ? entries.filter((o) => isAssistant(o) && o.message && o.message.id === id) : [entries[last]];
|
|
294
|
+
const parts = [];
|
|
295
|
+
for (const o of lines) {
|
|
296
|
+
const c = o.message ? o.message.content : o.content;
|
|
297
|
+
if (typeof c === 'string') parts.push(c);
|
|
298
|
+
else if (Array.isArray(c)) {
|
|
299
|
+
for (const b of c) {
|
|
300
|
+
if (!b || typeof b !== 'object') continue;
|
|
301
|
+
if (b.type === 'text' && typeof b.text === 'string') parts.push(b.text);
|
|
302
|
+
else if (b.type === 'tool_use' && b.input && typeof b.input.message === 'string') parts.push(b.input.message);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return parts.join('\n');
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The final report a SubagentStop payload points at: the sub-agent's own transcript
|
|
311
|
+
* (`agent_transcript_path`), read through the Stop's shared reader, plus the host's
|
|
312
|
+
* `last_assistant_message` when the transcript does not hold it. THE UNION, never one of the two:
|
|
313
|
+
* the host copy may be the newer message (a lagging transcript), or an OLDER text one (the final
|
|
314
|
+
* message is a hand-back tool call with no text block). A stray earlier line costs at most a
|
|
315
|
+
* deduplicated bullet; dropping the side that holds the report would lose the whole note.
|
|
316
|
+
*
|
|
317
|
+
* `field` names the transcript: a Stop's reply is the main session's, `transcript_path`
|
|
318
|
+
* (`turnReply`). The same union holds there: the host copy covers a transcript that lags.
|
|
319
|
+
*/
|
|
320
|
+
export function subagentReport(meta, read, field = 'agent_transcript_path') {
|
|
321
|
+
let text = '';
|
|
322
|
+
const tp = typeof meta[field] === 'string' ? meta[field] : null;
|
|
323
|
+
if (tp) {
|
|
324
|
+
try { text = read(tp, (raw, whole) => finalAssistantText(raw) ?? (whole ? '' : null)) || ''; } catch { text = ''; }
|
|
325
|
+
}
|
|
326
|
+
const last = typeof meta.last_assistant_message === 'string' ? meta.last_assistant_message.trim() : '';
|
|
327
|
+
if (!last || text.includes(last)) return text;
|
|
328
|
+
return text ? `${text}\n${last}` : last;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* The main session's final reply at a Stop, where a skill's `spec-feedback:` line is read (a skill
|
|
333
|
+
* runs in the main context, so no SubagentStop sees it). The host's `last_assistant_message` is
|
|
334
|
+
* that reply's text: when it holds no `spec-feedback` at all, the turn has nothing to capture and
|
|
335
|
+
* the transcript is never read, so the common Stop costs one substring test. Otherwise, or with no
|
|
336
|
+
* host copy (an older host; Bob sends neither), the transcript's final message is read too.
|
|
337
|
+
*/
|
|
338
|
+
export function turnReply(meta, read) {
|
|
339
|
+
const last = meta.last_assistant_message;
|
|
340
|
+
if (typeof last === 'string' && !/spec-feedback/i.test(last)) return '';
|
|
341
|
+
return subagentReport(meta, read, 'transcript_path');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Today as `YYYY-MM-DD`, local time, as `appendAgentLesson` dates a lesson. */
|
|
345
|
+
export function today(now = new Date()) {
|
|
346
|
+
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* THE FILE LOCK. Parallel sub-agents end together, and their hooks read-merge-write one notes file:
|
|
351
|
+
* without a lock the last writer drops the others' bullets (7 of 12 kept, measured). `<file>.lock`
|
|
352
|
+
* is created exclusively and holds its owner's token (pid and a nonce). The wait is bounded
|
|
353
|
+
* (LOCK_TRIES x LOCK_WAIT_MS, one second) and a hook that never gets the lock gives up silently: a
|
|
354
|
+
* note is worth less than a stalled SubagentStop.
|
|
355
|
+
*
|
|
356
|
+
* A STALE LOCK (older than LOCK_STALE_MS: a dead hook) is broken by RENAMING it to a name only this
|
|
357
|
+
* hook uses, so of two waiters that both saw it stale only one rename succeeds. The one that
|
|
358
|
+
* renamed checks what it took: a fresh lock (another waiter broke the stale one and took the file
|
|
359
|
+
* between this hook's stat and its rename) is put back with a link that cannot overwrite. On
|
|
360
|
+
* release a hook removes the lock only when it still holds its own token, so a holder that outlived
|
|
361
|
+
* the stale age never removes the next holder's lock.
|
|
362
|
+
*/
|
|
363
|
+
const LOCK_TRIES = 100;
|
|
364
|
+
const LOCK_WAIT_MS = 10;
|
|
365
|
+
const LOCK_STALE_MS = 10000;
|
|
366
|
+
const SLEEPER = new Int32Array(new SharedArrayBuffer(4));
|
|
367
|
+
const lockToken = () => `${process.pid}.${Math.random().toString(36).slice(2)}`;
|
|
368
|
+
function breakStale(lock) {
|
|
369
|
+
const taken = `${lock}.${lockToken()}.stale`;
|
|
370
|
+
try { renameSync(lock, taken); } catch { return; /* another waiter broke it first, or it was released */ }
|
|
371
|
+
try {
|
|
372
|
+
if (Date.now() - statSync(taken).mtimeMs <= LOCK_STALE_MS) linkSync(taken, lock); // a live lock: put it back
|
|
373
|
+
} catch { /* the slot is taken again: the live holder's token is in the new lock */ }
|
|
374
|
+
try { unlinkSync(taken); } catch { /* gone */ }
|
|
375
|
+
}
|
|
376
|
+
/** Exported for the unit tier: ownership on release is invisible through `captureSpecFeedback`. */
|
|
377
|
+
export function withLock(file, fn) {
|
|
378
|
+
const lock = `${file}.lock`;
|
|
379
|
+
const token = lockToken();
|
|
380
|
+
for (let i = 0; i < LOCK_TRIES; i += 1) {
|
|
381
|
+
let fd;
|
|
382
|
+
try {
|
|
383
|
+
fd = openSync(lock, 'wx');
|
|
384
|
+
} catch (e) {
|
|
385
|
+
const code = /** @type {NodeJS.ErrnoException} */ (e).code;
|
|
386
|
+
// Windows refuses to create a file whose last holder just unlinked it while a handle was
|
|
387
|
+
// still open (delete pending): EPERM or EACCES, not EEXIST. That is a busy lock, not a fault.
|
|
388
|
+
if (code === 'EPERM' || code === 'EACCES' || code === 'EBUSY') { Atomics.wait(SLEEPER, 0, 0, LOCK_WAIT_MS); continue; }
|
|
389
|
+
if (code !== 'EEXIST') return false;
|
|
390
|
+
let stale = false;
|
|
391
|
+
try { stale = Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS; } catch { continue; /* released */ }
|
|
392
|
+
if (stale) { breakStale(lock); continue; }
|
|
393
|
+
Atomics.wait(SLEEPER, 0, 0, LOCK_WAIT_MS);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
try { writeFileSync(fd, token); } finally { closeSync(fd); }
|
|
398
|
+
return fn();
|
|
399
|
+
} finally {
|
|
400
|
+
try { if (readFileSync(lock, 'utf8') === token) unlinkSync(lock); } catch { /* broken as stale */ }
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** LF on every platform: the tier's file is shared with the OpenCode plugin, which writes LF. */
|
|
407
|
+
function writeAtomic(file, text) {
|
|
408
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
409
|
+
writeFileSync(tmp, text, 'utf8');
|
|
410
|
+
// A rename onto a file a reader (an agent at step 0, a scanner) holds open fails EPERM on
|
|
411
|
+
// Windows for a moment: three tries, 10 ms apart, then the error.
|
|
412
|
+
for (let i = 0; ; i += 1) {
|
|
413
|
+
try { renameSync(tmp, file); return; } catch (e) {
|
|
414
|
+
if (i < 2 && /** @type {NodeJS.ErrnoException} */ (e).code === 'EPERM') { Atomics.wait(SLEEPER, 0, 0, LOCK_WAIT_MS); continue; }
|
|
415
|
+
try { unlinkSync(tmp); } catch { /* gone */ }
|
|
416
|
+
throw e;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Add `bullets` to one notes file, under its lock. A file that is not UTF-8 is left whole (the fold's rule). */
|
|
422
|
+
function addTo(file, bullets, cap) {
|
|
423
|
+
if (!bullets.length) return false;
|
|
424
|
+
return withLock(file, () => {
|
|
425
|
+
let old = '';
|
|
426
|
+
if (existsSync(file)) {
|
|
427
|
+
const raw = readFileSync(file);
|
|
428
|
+
if (!isUtf8(raw)) return false;
|
|
429
|
+
old = raw.toString('utf8');
|
|
430
|
+
}
|
|
431
|
+
const next = mergeFeedback(old, bullets, cap);
|
|
432
|
+
if (next === null) return false;
|
|
433
|
+
writeAtomic(file, next);
|
|
434
|
+
return true;
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* A skill this install serves under that name: `<skillsDir>/<name>/SKILL.md` names its OWN notes
|
|
440
|
+
* file, `skill-notes/<name>.md`, which the render writes from the skill's id
|
|
441
|
+
* (`{{SKILL_NAME}}`, src/skills/_self-improvement.md). An alias folder an older build rendered
|
|
442
|
+
* (`deps-audit/`, whose body is `dependencies`'), a skill rendered before the id was, or any folder
|
|
443
|
+
* that is not a Geneseed skill names another file or `<name>`, so no note is kept for it: nothing
|
|
444
|
+
* would read it. Read only when a line names a skill, which is rare.
|
|
445
|
+
*/
|
|
446
|
+
export function liveSkill(skillsDir, name) {
|
|
447
|
+
if (!skillsDir) return false;
|
|
448
|
+
try {
|
|
449
|
+
return readFileSync(path.join(skillsDir, name, 'SKILL.md'), 'utf8').includes(`skill-notes/${name}.md`);
|
|
450
|
+
} catch { return false; }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* THE ONE RESOLVER of a project's notes folder, for the hook, the migration and `diff`:
|
|
455
|
+
* `<base>/notebook`, where a `base` inside a linked git worktree is mapped to the same place in
|
|
456
|
+
* the main checkout, since a worktree and its notes go when it is removed. Read off disk, never
|
|
457
|
+
* by spawning git. The OpenCode learn plugin keeps an async hand twin (`notesRootsOf`).
|
|
458
|
+
*/
|
|
459
|
+
export function projectNotesDir(base) {
|
|
460
|
+
if (!base) return null;
|
|
461
|
+
let at = base;
|
|
462
|
+
try {
|
|
463
|
+
const main = mainWorktreeOf(at);
|
|
464
|
+
if (main) at = path.join(main, path.relative(gitRootOf(at), at));
|
|
465
|
+
} catch { at = base; }
|
|
466
|
+
return path.join(at, PROJECT_NOTES_DIR);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The project notes, kept out of every commit: their entries in the clone's own `.git/info/exclude`
|
|
471
|
+
* (`excludeWithNotes`). A linked worktree's notes are the main checkout's, whose `.git` is the shared
|
|
472
|
+
* one; a submodule's gitdir is named by its `.git` file. Outside a git repo nothing is written. Never
|
|
473
|
+
* throws: an exclude that cannot be written costs only the ignore line, never the note.
|
|
474
|
+
*/
|
|
475
|
+
export function excludeProjectNotes(notebookDir) {
|
|
476
|
+
try {
|
|
477
|
+
const root = gitRootOf(path.dirname(notebookDir));
|
|
478
|
+
if (!root) return false;
|
|
479
|
+
const rel = path.relative(root, notebookDir).split(path.sep).join('/');
|
|
480
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return false;
|
|
481
|
+
const file = path.join(gitCommonDirOf(root), 'info', 'exclude');
|
|
482
|
+
const next = excludeWithNotes(existsSync(file) ? readFileSync(file, 'utf8') : '', rel);
|
|
483
|
+
if (next === null) return false;
|
|
484
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
485
|
+
writeAtomic(file, next);
|
|
486
|
+
return true;
|
|
487
|
+
} catch { return false; }
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* The capture: the feedback lines in `report` into the notes `feedbackTargets` names. `roots` is
|
|
492
|
+
* `{ machine, project }`, each a notes root or null (that scope writes nothing), or one string for
|
|
493
|
+
* both. An agent's lines are kept when `agent` names one (a SubagentStop); a skill's either way, a
|
|
494
|
+
* sub-agent's or the main session's (a Stop passes no agent, so a relayed `[agent]` or `[general]`
|
|
495
|
+
* line there is no note). A skill line is kept only for a `liveSkill` of `skillsDir`, the install's
|
|
496
|
+
* own `skills/`, so an invented or misspelt name, an alias, or a skill another install serves
|
|
497
|
+
* writes no file nobody reads. A root whose parent does not exist (no tier, no project there)
|
|
498
|
+
* writes nothing. Returns the files it changed.
|
|
499
|
+
*/
|
|
500
|
+
export function captureSpecFeedback(agent, report, roots, day = today(), skillsDir = null) {
|
|
501
|
+
const at = typeof roots === 'string' ? { machine: roots, project: roots } : (roots || {});
|
|
502
|
+
const usable = (dir) => Boolean(dir) && existsSync(path.dirname(dir));
|
|
503
|
+
if (!usable(at.machine) && !usable(at.project)) return [];
|
|
504
|
+
const items = specFeedbackOf(report, SECRET_RE)
|
|
505
|
+
.filter((f) => (f.skill ? liveSkill(skillsDir, f.skill) : Boolean(agent)));
|
|
506
|
+
if (!items.length) return [];
|
|
507
|
+
const written = [];
|
|
508
|
+
for (const t of feedbackTargets(items, agent, day)) {
|
|
509
|
+
const root = at[t.root];
|
|
510
|
+
if (!usable(root)) continue;
|
|
511
|
+
if (t.root === 'project' && typeof roots !== 'string') excludeProjectNotes(root);
|
|
512
|
+
const dir = path.join(root, t.sub);
|
|
513
|
+
mkdirSync(dir, { recursive: true });
|
|
514
|
+
const file = path.join(dir, t.name);
|
|
515
|
+
if (addTo(file, t.bullets, t.cap)) written.push(file);
|
|
516
|
+
}
|
|
517
|
+
return written;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* The migration's merge (`js/build/notes-migrate.mjs`): `source`'s lines appended after `target`'s.
|
|
522
|
+
* A source line is left out only when the target already holds that EXACT line (a trailing CR
|
|
523
|
+
* aside): case and inner spacing are never folded, and two equal lines inside the source both stay,
|
|
524
|
+
* since the user may have written them so. Blank lines travel with the lines they sit between. NO cap
|
|
525
|
+
* and no budget: a moved note is never dropped. null when the target already holds every line.
|
|
526
|
+
* (The capture's own duplicate check, `feedbackKey` in `mergeFeedback`, folds case and spacing for
|
|
527
|
+
* the hook's bullets; it did so before the two scopes, and this merge does not use it.)
|
|
528
|
+
*/
|
|
529
|
+
export function mergeNotesText(target, source) {
|
|
530
|
+
const text = String(target || '').replace(/\r\n?/g, '\n').replace(/\n+$/, '');
|
|
531
|
+
const lines = text ? text.split('\n') : [];
|
|
532
|
+
const have = new Set(lines);
|
|
533
|
+
const src = String(source || '').replace(/\r\n?/g, '\n').replace(/\n+$/, '');
|
|
534
|
+
const add = (src ? src.split('\n') : []).filter((l) => !l.trim() || !have.has(l));
|
|
535
|
+
if (!add.some((l) => l.trim())) return null;
|
|
536
|
+
while (add.length && !add[0].trim()) add.shift();
|
|
537
|
+
return `${[...lines, ...add].join('\n')}\n`;
|
|
538
|
+
}
|
package/js/hosts/usage.mjs
CHANGED
|
@@ -10,10 +10,31 @@
|
|
|
10
10
|
* printed byte would turn a gate permissive), and swallows every error — a counter that fails
|
|
11
11
|
* must never block, slow or change a tool call. It rides `tool-gate`, the verb Bob already runs
|
|
12
12
|
* on every tool and Claude/OpenClaude route their `Skill|Agent|Task` matcher to, so no host pays
|
|
13
|
-
* an extra process for it
|
|
13
|
+
* an extra process for it; the slash counter rides `activity`, already wired to UserPromptSubmit
|
|
14
|
+
* on all three, and loads this module only for a prompt that starts with `/`. The OpenCode guard plugin carries the same rules inline (a plugin
|
|
14
15
|
* cannot import from here): `NAME_RE` by `tests/twins.mjs`, `usageOf` by hand, since it reads
|
|
15
16
|
* no Bob shape. `tests/unit/usage.test.mjs` holds both to one table.
|
|
16
17
|
*
|
|
18
|
+
* A SKILL TYPED AS `/name` is a second source (`recordSlash`): Claude Code hands UserPromptSubmit
|
|
19
|
+
* the prompt as typed, and a slash-invoked skill makes no Skill tool call (2026-11 transcripts: 1
|
|
20
|
+
* Skill call after ~300 skill slash lines), so the tool counter never sees it. Its line carries
|
|
21
|
+
* `via: "slash"`; a Skill-tool line stays byte-identical. Only a name that resolves to an installed
|
|
22
|
+
* `SKILL.md` counts — a built-in (`/clear`, `/model`) or a path never does, and the prompt's
|
|
23
|
+
* arguments are never read. A namespaced plugin skill (`/plugin:skill`) is not counted that way:
|
|
24
|
+
* its folder is the host's plugin cache, which this reads nowhere else.
|
|
25
|
+
*
|
|
26
|
+
* NOT COUNTED, ON PURPOSE:
|
|
27
|
+
* * a session in an EXCLUDED folder (`sovereignBypass`): the install is dormant there, and its
|
|
28
|
+
* hooks write nothing — the counter included. So a repo excluded for a time shows fewer calls
|
|
29
|
+
* in the ledger than its transcripts hold, and that is the switch working.
|
|
30
|
+
* * the GLOBAL install's copy when a live project install of the same host sits in the session's
|
|
31
|
+
* project dir (`globalHookStandingDown`): both hooks run, both would append, and the console
|
|
32
|
+
* sums every install's ledger, so each call read twice. The caller passes that test in as
|
|
33
|
+
* `standingDown`, evaluated only for a call that counts: this module stays builtins-only.
|
|
34
|
+
* UNVERIFIED ON BOB: with no project variable, its project dir is the payload's `cwd`. If that
|
|
35
|
+
* follows a `cd` into another repo whose Bob project install Bob never loaded, the global
|
|
36
|
+
* stands down and the call is counted by neither (adapters/bob/README.md).
|
|
37
|
+
*
|
|
17
38
|
* Off when `GENESEED_NO_USAGE` is set or the install holds a `.usage-off` marker.
|
|
18
39
|
*/
|
|
19
40
|
import { appendFileSync, existsSync } from 'node:fs';
|
|
@@ -21,6 +42,11 @@ import path from 'node:path';
|
|
|
21
42
|
|
|
22
43
|
export const USAGE_LEDGER = path.join('notebook', 'usage.jsonl');
|
|
23
44
|
export const USAGE_OFF = '.usage-off';
|
|
45
|
+
/**
|
|
46
|
+
* The agent outcome ledger beside it (./agent-runs.mjs writes it, under the same switch). Here, not
|
|
47
|
+
* there, so the CLI's reader (js/inspect/agent-scores.mjs) never loads the done gate's module tree.
|
|
48
|
+
*/
|
|
49
|
+
export const RUNS_LEDGER = path.join('notebook', 'agent-runs.jsonl');
|
|
24
50
|
|
|
25
51
|
const NAME_RE = /^[A-Za-z0-9][\w.:@/-]{0,99}$/;
|
|
26
52
|
|
|
@@ -54,16 +80,49 @@ export function usageOf(payload) {
|
|
|
54
80
|
return NAME_RE.test(name) ? { kind, name } : null;
|
|
55
81
|
}
|
|
56
82
|
|
|
57
|
-
/**
|
|
58
|
-
|
|
83
|
+
/** The tail both counters share: the switches, the stand-down, then one appended line. */
|
|
84
|
+
function appendUse(root, use, now, standingDown) {
|
|
85
|
+
if (existsSync(path.join(root, USAGE_OFF))) return;
|
|
86
|
+
if (!existsSync(path.join(root, 'notebook'))) return;
|
|
87
|
+
if (standingDown && standingDown()) return;
|
|
88
|
+
appendFileSync(path.join(root, USAGE_LEDGER),
|
|
89
|
+
`${JSON.stringify({ ts: now.toISOString().slice(0, 10), ...use })}\n`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Append one line for `payload` under `root`, if it is a counted call. Never throws.
|
|
94
|
+
* `standingDown`: a thunk, true when another install's hook counts this call (see the header).
|
|
95
|
+
*/
|
|
96
|
+
export function recordUse(root, payload, now = new Date(), standingDown = null) {
|
|
59
97
|
try {
|
|
60
98
|
if (!root || process.env.GENESEED_NO_USAGE) return;
|
|
61
99
|
const use = usageOf(payload);
|
|
62
100
|
if (!use) return;
|
|
63
|
-
|
|
64
|
-
const dir = path.join(root, 'notebook');
|
|
65
|
-
if (!existsSync(dir)) return;
|
|
66
|
-
appendFileSync(path.join(root, USAGE_LEDGER),
|
|
67
|
-
`${JSON.stringify({ ts: now.toISOString().slice(0, 10), ...use })}\n`);
|
|
101
|
+
appendUse(root, use, now, standingDown);
|
|
68
102
|
} catch { /* a counter never fails a tool call */ }
|
|
69
103
|
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The skill a prompt typed as `/name …` names, else null. The first token only, and never one
|
|
107
|
+
* holding a path separator, `..` or a plugin's `:` — it is about to become a folder name.
|
|
108
|
+
*/
|
|
109
|
+
export function slashSkillOf(prompt) {
|
|
110
|
+
if (typeof prompt !== 'string') return null;
|
|
111
|
+
const m = /^\s*\/(\S+)/.exec(prompt);
|
|
112
|
+
if (!m || /[/\\:]|\.\./.test(m[1])) return null;
|
|
113
|
+
return NAME_RE.test(m[1]) ? m[1] : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* One `via: "slash"` line for a UserPromptSubmit `payload` whose prompt runs an installed skill:
|
|
118
|
+
* `<dir>/<name>/SKILL.md` exists in one of `skillDirs`. Same switches and stand-down as
|
|
119
|
+
* `recordUse`. Never throws.
|
|
120
|
+
*/
|
|
121
|
+
export function recordSlash(root, payload, { skillDirs = [], now = new Date(), standingDown = null } = {}) {
|
|
122
|
+
try {
|
|
123
|
+
if (!root || process.env.GENESEED_NO_USAGE) return;
|
|
124
|
+
const name = slashSkillOf(payload && payload.prompt);
|
|
125
|
+
if (!name || !skillDirs.some((d) => d && existsSync(path.join(d, name, 'SKILL.md')))) return;
|
|
126
|
+
appendUse(root, { kind: 'skill', name, via: 'slash' }, now, standingDown);
|
|
127
|
+
} catch { /* a counter never fails a prompt */ }
|
|
128
|
+
}
|