geneseed 4.32.0 → 5.0.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 +85 -0
- package/DESIGN.md +2 -2
- package/README.md +6 -5
- package/SHIPPED.md +4 -3
- package/adapters/bob/README.md +6 -5
- package/adapters/claude-code/README.md +4 -3
- package/adapters/claude-code/skills/geneseed/SKILL.md +1 -1
- package/adapters/openclaude/README.md +4 -3
- package/adapters/opencode/GLOBAL-HARNESS-SPEC.md +3 -1
- package/adapters/opencode/HOW-OPENCODE-LOADS.md +2 -1
- package/adapters/opencode/README.md +18 -18
- package/adapters/opencode/plugins/geneseed-activity.js +57 -1
- package/adapters/opencode/plugins/geneseed-context.js +85 -18
- package/adapters/opencode/plugins/geneseed-guard.js +437 -76
- package/adapters/opencode/plugins/geneseed-learn.js +97 -23
- package/bin/geneseed-cli.mjs +17 -25
- package/bin/geneseed-hook.mjs +23 -8
- package/docs/DESIGN.md +175 -0
- package/docs/PRD.md +111 -0
- package/docs/README.md +3 -2
- package/docs/architecture.md +145 -0
- package/docs/concepts/agents.md +1 -1
- package/docs/concepts/collaboration.md +1 -1
- package/docs/concepts/enforcement-table.md +1 -1
- package/docs/concepts/exclusions.md +5 -5
- package/docs/concepts/footprint.md +1 -1
- package/docs/concepts/foreman-mode.md +2 -2
- package/docs/concepts/hooks.md +22 -8
- package/docs/concepts/host-matrix.md +2 -2
- package/docs/concepts/hosts.md +1 -1
- package/docs/concepts/kits.md +3 -1
- package/docs/concepts/ownership.md +1 -1
- package/docs/concepts/rules.md +15 -2
- package/docs/concepts/shared-tier.md +73 -0
- package/docs/concepts/skills.md +2 -2
- package/docs/concepts/themes.md +1 -1
- package/docs/extending.md +13 -12
- package/docs/guides/install-claude-code.md +1 -1
- package/docs/guides/install-opencode.md +1 -1
- package/docs/guides/migrate.md +4 -2
- package/docs/guides/project-context.md +2 -2
- package/docs/guides/setup-footprint.md +1 -1
- package/docs/guides/uninstall.md +2 -1
- package/docs/guides/upgrade-to-5.md +116 -0
- package/docs/guides/upgrade.md +21 -9
- package/docs/guides/wiki.md +3 -3
- package/docs/reference/env-context.md +5 -3
- package/docs/reference/environment.md +1 -1
- package/docs/reference/glossary.md +2 -0
- package/docs/reference/opencode-plugins.md +3 -3
- package/docs/reference/plugin-activity.md +1 -1
- package/docs/reference/plugin-context.md +1 -0
- package/docs/reference/plugin-guard.md +14 -6
- package/docs/reference/plugin-learn.md +13 -6
- package/docs/reference/troubleshoot-hooks.md +3 -3
- package/docs/reference/troubleshoot-update.md +14 -0
- package/docs/token-footprint.md +4 -3
- package/docs/understand/a-day.md +2 -2
- package/docs/understand/design-choices-install.md +2 -1
- package/docs/understand/enforced-vs-asked.md +1 -1
- package/docs/understand/machine-bob.md +2 -0
- package/docs/understand/machine-claude.md +7 -5
- package/docs/understand/machine-opencode.md +7 -5
- package/docs/understand/on-your-machine.md +4 -0
- package/docs/understand/take-it-out.md +1 -1
- package/docs/web-ui.md +126 -68
- package/harness.config.json +1 -1
- package/js/README.md +10 -6
- package/js/build/args.mjs +10 -8
- package/js/build/bundle.mjs +11 -13
- package/js/build/driver.mjs +66 -65
- package/js/build/emit-claude.mjs +22 -16
- package/js/build/emit-common.mjs +4 -5
- package/js/build/emit-opencode.mjs +22 -22
- package/js/build/fold.mjs +515 -0
- package/js/build/generate.mjs +41 -52
- package/js/build/render.mjs +115 -29
- package/js/build/source.mjs +4 -1
- package/js/build/stubs.mjs +70 -9
- package/js/build/version.mjs +10 -10
- package/js/cli-table.json +23 -83
- package/js/hosts/activity.mjs +2 -2
- package/js/hosts/geneseed-dir.mjs +1 -1
- package/js/hosts/hooks-context.mjs +389 -99
- package/js/hosts/hooks-learn.mjs +38 -7
- package/js/hosts/hooks-prims.mjs +4 -2
- package/js/hosts/hooks.mjs +114 -39
- package/js/hosts/hosts.mjs +150 -51
- package/js/hosts/installs.mjs +55 -167
- package/js/hosts/link.mjs +3 -5
- package/js/hosts/mcp.mjs +1 -1
- package/js/hosts/memory-files.mjs +219 -17
- package/js/hosts/ownership-gate.mjs +1 -1
- package/js/hosts/settings.mjs +18 -13
- package/js/hosts/shim.mjs +4 -33
- package/js/hosts/store-watch.mjs +189 -0
- package/js/inspect/checks-authoring.mjs +3 -3
- package/js/inspect/checks-build.mjs +45 -18
- package/js/inspect/checks-counts.mjs +4 -4
- package/js/inspect/checks-repo.mjs +13 -14
- package/js/inspect/cost.mjs +24 -2
- package/js/inspect/diff.mjs +123 -123
- package/js/inspect/doctor.mjs +22 -27
- package/js/inspect/excludes.mjs +181 -62
- package/js/inspect/inventory.mjs +22 -27
- package/js/inspect/registry.mjs +106 -30
- package/js/inspect/scan.mjs +5 -5
- package/js/inspect/status.mjs +141 -119
- package/js/inspect/validate.mjs +22 -24
- package/js/lib/fs.mjs +47 -50
- package/js/lib/json.mjs +10 -17
- package/js/lib/machine-dir.mjs +73 -0
- package/js/lib/paths.mjs +22 -33
- package/js/lib/proc.mjs +1 -1
- package/js/lib/prompt.mjs +19 -27
- package/js/lib/text.mjs +8 -12
- package/js/lib/udiff.mjs +11 -15
- package/js/loop/catalog.mjs +2 -3
- package/js/maintain/memory.mjs +17 -17
- package/js/maintain/migrate.mjs +79 -89
- package/js/maintain/setup.mjs +43 -32
- package/js/maintain/uninstall.mjs +43 -61
- package/js/maintain/update.mjs +200 -93
- package/js/ui/anim.mjs +21 -35
- package/js/ui/cli.mjs +36 -58
- package/js/ui/menu.mjs +22 -45
- package/js/ui/tui.mjs +27 -67
- package/js/web/actions.mjs +34 -34
- package/js/web/api.mjs +130 -74
- package/js/web/catalog.mjs +175 -46
- package/js/web/docs.mjs +33 -12
- package/js/web/doctor-worker.mjs +14 -0
- package/js/web/handler.mjs +14 -5
- package/js/web/routes.mjs +17 -19
- package/js/web/state.mjs +78 -19
- package/js/web/update-check.mjs +25 -10
- package/js/web/user-files.mjs +50 -105
- package/package.json +7 -4
- package/registry.json +48 -55
- package/src/AGENT.md.tmpl +13 -14
- package/src/agents/_self-improvement.md +1 -1
- package/src/agents/_template.md +1 -1
- package/src/agents/advocate.md +1 -1
- package/src/agents/architect.md +1 -1
- package/src/agents/developer.md +1 -1
- 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 +1 -1
- 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 +2 -2
- 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 +1 -1
- 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 +1 -1
- package/src/agents/user-advocate.md +1 -1
- package/src/agents/visionary.md +1 -1
- package/src/memory/README.md +1 -1
- package/src/skills/_self-improvement.md +2 -2
- package/src/skills/daydream/SKILL.md +2 -2
- package/src/skills/daydream/instructions.md +1 -1
- package/src/skills/geneseed.md +1 -1
- package/src/skills/learn-mode.md +1 -2
- package/src/skills/profile.md +2 -2
- package/src/skills/rule/approve.md +69 -0
- package/src/skills/rule/consolidate.md +3 -3
- package/src/skills/rule.md +13 -5
- package/src/skills/skill-forge.md +1 -1
- package/src/skills/teach.md +29 -12
- package/src/skills/wiki.md +1 -1
- package/themes/_TEMPLATE.json +1 -2
- package/themes/biker.json +1 -2
- package/themes/commentator.json +1 -2
- package/themes/cyberpunk.json +1 -2
- package/themes/gamer.json +1 -2
- package/themes/imperial.json +1 -2
- package/themes/joker.json +1 -2
- package/themes/marvin.json +1 -2
- package/themes/mean.json +1 -2
- package/themes/military.json +1 -2
- package/themes/neutral.json +1 -2
- package/themes/pirate.json +1 -2
- package/themes/sports.json +1 -2
- package/themes/verstappen.json +1 -2
- package/themes/wizard.json +1 -2
- package/web/dist/assets/Activity-D8G4eClY.js +1 -0
- package/web/dist/assets/ActivityDetail-BtOBYk3M.js +1 -0
- package/web/dist/assets/AgentGlyph-k6o3gCM1.js +1 -0
- package/web/dist/assets/Bonsai-B_y20b3i.js +1 -0
- package/web/dist/assets/{CopyButton-C5Li6awl.js → CopyButton-CHQte7Ap.js} +1 -1
- package/web/dist/assets/Dashboard-B8uXeJZ_.js +2 -0
- package/web/dist/assets/Docs-Dgv_MWfT.js +5 -0
- package/web/dist/assets/GreenhouseView-CSzTMSl_.js +1 -0
- package/web/dist/assets/Installs-BDk9lqBI.js +3 -0
- package/web/dist/assets/JournalView-CvRk1-m5.js +1 -0
- package/web/dist/assets/Kits-CoITzxWM.js +1 -0
- package/web/dist/assets/Laws-Ctf5r9rE.js +3 -0
- package/web/dist/assets/Library-DNwHYVXt.js +3 -0
- package/web/dist/assets/{Loops-CzitjxGV.js → Loops-S85PMQ8m.js} +2 -2
- package/web/dist/assets/{Markdown-C4S4tTA7.js → Markdown-0ORz7tAc.js} +21 -21
- package/web/dist/assets/OperatorHudView-DuGz_sTk.js +1 -0
- package/web/dist/assets/Personal-afJNwvRS.js +2 -0
- package/web/dist/assets/{RailCats-D5weYPCS.js → RailCats-AW92uhsX.js} +1 -1
- package/web/dist/assets/Settings-CGDFz-6j.js +1 -0
- package/web/dist/assets/Tabs-1qLrnqmn.js +1 -0
- package/web/dist/assets/api-C46vAuqp.js +1 -0
- package/web/dist/assets/controls-D4wmg_pl.js +1 -0
- package/web/dist/assets/index-COTd4TRZ.js +3 -0
- package/web/dist/assets/index-CtorA7uK.css +1 -0
- package/web/dist/assets/motion-RlUl1osO.js +1 -0
- package/web/dist/assets/{sections-ChwaobfW.js → sections-CtFz7HFH.js} +1 -1
- package/web/dist/index.html +5 -5
- package/src/skills/quiz.md +0 -44
- package/web/dist/assets/Activity-Bjy64wHC.js +0 -1
- package/web/dist/assets/ActivityDetail-B0AaipP8.js +0 -1
- package/web/dist/assets/Bonsai-CJniRqaH.js +0 -1
- package/web/dist/assets/Dashboard-B-6DTmae.js +0 -2
- package/web/dist/assets/Docs-LRc30XL9.js +0 -5
- package/web/dist/assets/GreenhouseView-CcoYlaWo.js +0 -1
- package/web/dist/assets/Installs-dp1epTcE.js +0 -3
- package/web/dist/assets/JournalView-nFP4poCf.js +0 -1
- package/web/dist/assets/KitApply-DwyZUj57.js +0 -1
- package/web/dist/assets/Kits-C0IEdZXe.js +0 -1
- package/web/dist/assets/Laws-CkykmQWu.js +0 -3
- package/web/dist/assets/Library-Guh9HBZU.js +0 -2
- package/web/dist/assets/OperatorHudView-DLGNulIY.js +0 -1
- package/web/dist/assets/Personal-BMtberL8.js +0 -2
- package/web/dist/assets/Tabs-uYJqfuQt.js +0 -1
- package/web/dist/assets/api-BxjLd7Qd.js +0 -1
- package/web/dist/assets/index-DA7BiaE5.js +0 -3
- package/web/dist/assets/index-dbbDGFDq.css +0 -1
- package/web/dist/assets/motion-Bccx3zE8.js +0 -1
|
@@ -9,11 +9,18 @@
|
|
|
9
9
|
* closure (the generator now imports this file too, and its spawn ban greps for that literal)
|
|
10
10
|
* and made the hook module a row in `tests/unit/hook_cli.test.mjs`'s spawn allow-list for a
|
|
11
11
|
* spawn the CLI never makes. Everything here is fs-only; `hooks-learn.mjs` is the one spawner.
|
|
12
|
+
*
|
|
13
|
+
* `user-rules.md`'s parser lives here too, and the draft's format and the fold's ledger reader: the
|
|
14
|
+
* web console edits or shows through them and the fold writes through them, and the build may not
|
|
15
|
+
* import `js/web` (spec C20).
|
|
12
16
|
*/
|
|
13
|
-
import {
|
|
17
|
+
import { isUtf8 } from 'node:buffer';
|
|
18
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync } from 'node:fs';
|
|
14
19
|
import path from 'node:path';
|
|
15
|
-
import { readText, writeText } from '../lib/fs.mjs';
|
|
20
|
+
import { readText, writeText, writeTextAtomic } from '../lib/fs.mjs';
|
|
21
|
+
import { isDict } from '../lib/json.mjs';
|
|
16
22
|
import { normcase } from '../lib/paths.mjs';
|
|
23
|
+
import { WHITESPACE, stripWhitespace } from '../lib/text.mjs';
|
|
17
24
|
import { isFile, listDir, sortPaths, splitLines, splitWords } from './hooks-prims.mjs';
|
|
18
25
|
|
|
19
26
|
const FRONTMATTER_RE = /^\s*---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/;
|
|
@@ -44,13 +51,24 @@ const MAP_HINT = 'Each topic file lists its facts; open the one the task needs.'
|
|
|
44
51
|
const FACT_LINE_RE = /^- \[([^\]]*)\]\((?:\.\.\/)?([^/)]+)\.md\)(.*)$/;
|
|
45
52
|
const MAP_LINE_RE = /^- \[[^\]]*\]\(topics\/[^)]+\.md\)/;
|
|
46
53
|
|
|
47
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* `append_agent_lesson` — one dated bullet, capped at the newest MAX_AGENT_BULLETS.
|
|
56
|
+
*
|
|
57
|
+
* A FILE THAT IS NOT UTF-8 IS LEFT WHOLE, the fold's rule (`foldRules` in js/build/fold.mjs): the
|
|
58
|
+
* read below replaces each bad byte, so rewriting the file would change a line nobody touched.
|
|
59
|
+
* The lesson is dropped and the answer is null; the caller says so. The tier's agent files are
|
|
60
|
+
* the ones that can be hand-edited in another encoding.
|
|
61
|
+
*/
|
|
48
62
|
export function appendAgentLesson(memDir, agent, lesson) {
|
|
49
63
|
const d = path.join(memDir, 'agents');
|
|
50
64
|
mkdirSync(d, { recursive: true });
|
|
51
65
|
const f = path.join(d, `${agent}.md`);
|
|
52
66
|
let bullets = [];
|
|
53
|
-
if (existsSync(f))
|
|
67
|
+
if (existsSync(f)) {
|
|
68
|
+
const raw = readFileSync(f);
|
|
69
|
+
if (!isUtf8(raw)) return null;
|
|
70
|
+
bullets = splitLines(raw.toString('utf8')).filter((l) => l.startsWith('- '));
|
|
71
|
+
}
|
|
54
72
|
const now = new Date();
|
|
55
73
|
const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-`
|
|
56
74
|
+ `${String(now.getDate()).padStart(2, '0')}`;
|
|
@@ -95,7 +113,7 @@ function globMd(dir) {
|
|
|
95
113
|
}
|
|
96
114
|
|
|
97
115
|
/** Stems that name the store's own files, never a fact — `MEMORY` is the index itself. */
|
|
98
|
-
const RESERVED_STEMS = new Set(['memory', 'readme']);
|
|
116
|
+
export const RESERVED_STEMS = new Set(['memory', 'readme']);
|
|
99
117
|
|
|
100
118
|
/**
|
|
101
119
|
* `_existing_slugs` — slugs already stored. learn never CREATES one of these; it may only
|
|
@@ -105,6 +123,16 @@ export function existingSlugs(memDir) {
|
|
|
105
123
|
return new Set(globMd(memDir).map(stem).filter((s) => !RESERVED_STEMS.has(s.toLowerCase())));
|
|
106
124
|
}
|
|
107
125
|
|
|
126
|
+
/**
|
|
127
|
+
* How many facts a store holds, by the same test the console's list uses. No folder is no facts
|
|
128
|
+
* (0); a folder that cannot be listed is null, so a row says "not read" rather than "no facts".
|
|
129
|
+
* The first listing is only for that answer: `existingSlugs` reads a failure as empty.
|
|
130
|
+
*/
|
|
131
|
+
export function factCount(store) {
|
|
132
|
+
try { readdirSync(store); } catch (e) { return e?.code === 'ENOENT' ? 0 : null; }
|
|
133
|
+
return existingSlugs(store).size;
|
|
134
|
+
}
|
|
135
|
+
|
|
108
136
|
/** Lines of a text file, or null when it cannot be read. */
|
|
109
137
|
function readLines(p) {
|
|
110
138
|
try { return splitLines(readText(p)); } catch { return null; }
|
|
@@ -117,7 +145,7 @@ function readLines(p) {
|
|
|
117
145
|
function writeIfChanged(p, text) {
|
|
118
146
|
const old = readLines(p);
|
|
119
147
|
if (old && `${old.join('\n')}\n` === text) return;
|
|
120
|
-
|
|
148
|
+
writeTextAtomic(p, text);
|
|
121
149
|
}
|
|
122
150
|
|
|
123
151
|
/** A topic name as a file stem: `[a-z0-9-]`, any other run becomes `-`, empty becomes `misc`. */
|
|
@@ -167,6 +195,19 @@ function indexedFacts(memDir) {
|
|
|
167
195
|
return found;
|
|
168
196
|
}
|
|
169
197
|
|
|
198
|
+
/**
|
|
199
|
+
* What MEMORY.md holds that no index writer generated: the lines a person wrote.
|
|
200
|
+
* `generated(slug)` says whether a flat pointer to that slug counts as generated too.
|
|
201
|
+
*/
|
|
202
|
+
export function indexNotes(memDir, generated) {
|
|
203
|
+
return (readLines(path.join(memDir, 'MEMORY.md')) ?? []).filter((l) => {
|
|
204
|
+
const t = l.trim();
|
|
205
|
+
const flat = FACT_LINE_RE.exec(t);
|
|
206
|
+
return t && t !== MEMORY_SEED.trim() && t !== MAP_HINT && !MAP_LINE_RE.test(t)
|
|
207
|
+
&& !(flat && generated(flat[2]));
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
170
211
|
/**
|
|
171
212
|
* Rewrite MEMORY.md as the map: one line per topic file with its fact count.
|
|
172
213
|
*
|
|
@@ -177,11 +218,7 @@ function indexedFacts(memDir) {
|
|
|
177
218
|
*/
|
|
178
219
|
function writeMap(memDir, dropFlat) {
|
|
179
220
|
const idx = path.join(memDir, 'MEMORY.md');
|
|
180
|
-
const carried = (
|
|
181
|
-
const t = l.trim();
|
|
182
|
-
return t && t !== MEMORY_SEED.trim() && t !== MAP_HINT && !MAP_LINE_RE.test(t)
|
|
183
|
-
&& !(dropFlat && FACT_LINE_RE.test(t));
|
|
184
|
-
});
|
|
221
|
+
const carried = indexNotes(memDir, () => dropFlat);
|
|
185
222
|
const tdir = path.join(memDir, TOPICS);
|
|
186
223
|
const topics = globMd(tdir).map(stem).sort().map((t) => {
|
|
187
224
|
const n = (readLines(path.join(tdir, `${t}.md`)) ?? [])
|
|
@@ -341,7 +378,7 @@ export function writeMemories(modelOutput, memDir, existing) {
|
|
|
341
378
|
}
|
|
342
379
|
|
|
343
380
|
/**
|
|
344
|
-
*
|
|
381
|
+
* Remove the index line(s) naming `<name>.md`.
|
|
345
382
|
*
|
|
346
383
|
* ITS PYTHON HOME IS THE TUI, and it is here because this is where its SIBLINGS' twins are:
|
|
347
384
|
* `appendAgentLesson` writes the index lines this deletes and `consolidateMemory` rebuilds
|
|
@@ -352,7 +389,7 @@ export function writeMemories(modelOutput, memDir, existing) {
|
|
|
352
389
|
* nothing in `js/` referenced it — which is the third time a plan's "already ported" column
|
|
353
390
|
* was answered by reading rather than by trusting.
|
|
354
391
|
*
|
|
355
|
-
* SUBSTRING, NOT PARSE
|
|
392
|
+
* SUBSTRING, NOT PARSE: any line containing `(<name>.md)` goes,
|
|
356
393
|
* so a hand-written index in a different shape still loses its entry. And the file is only
|
|
357
394
|
* REWRITTEN when something actually changed, which keeps a delete of an unindexed fact from
|
|
358
395
|
* touching the user's mtime.
|
|
@@ -377,21 +414,50 @@ export function memoryDropIndex(memDir, name) {
|
|
|
377
414
|
}
|
|
378
415
|
if (!touched) return;
|
|
379
416
|
pruneTopicsDir(memDir);
|
|
380
|
-
try { writeMap(memDir, false); } catch { /*
|
|
417
|
+
try { writeMap(memDir, false); } catch { /* best-effort */ }
|
|
381
418
|
}
|
|
382
419
|
|
|
383
420
|
/** Drop every line holding `needle`; the kept lines when something went, else null. */
|
|
384
421
|
function dropLines(p, needle) {
|
|
385
422
|
const lines = readLines(p);
|
|
386
|
-
if (!lines) return null; //
|
|
423
|
+
if (!lines) return null; // unreadable: nothing to drop
|
|
387
424
|
const keep = lines.filter((ln) => !ln.includes(needle));
|
|
388
425
|
if (keep.length === lines.length) return null;
|
|
389
426
|
try {
|
|
390
|
-
|
|
391
|
-
} catch { /*
|
|
427
|
+
writeTextAtomic(p, `${keep.join('\n')}\n`);
|
|
428
|
+
} catch { /* best-effort */ }
|
|
392
429
|
return keep;
|
|
393
430
|
}
|
|
394
431
|
|
|
432
|
+
/**
|
|
433
|
+
* Move a runtime store aside to a sibling
|
|
434
|
+
* `archived-<name>/<timestamp>/`.
|
|
435
|
+
*
|
|
436
|
+
* NEVER a delete. Memory is the one thing in this system a user cannot rebuild, so the
|
|
437
|
+
* destructive verb's most destructive option is still a move.
|
|
438
|
+
*
|
|
439
|
+
* `renameSync` rather than a copy-then-delete: the destination is a SIBLING of the source, so
|
|
440
|
+
* it is the same device by construction and a cross-device fallback has nothing to do.
|
|
441
|
+
* shortcut: rename only, and the day a store can live on another volume this needs a copy path.
|
|
442
|
+
*
|
|
443
|
+
* `move` is `copyFileSync` for a file that must stay readable until its replacement lands.
|
|
444
|
+
*/
|
|
445
|
+
export function archiveStore(store, move = renameSync) {
|
|
446
|
+
// `toLocaleString('sv-SE')` — LOCAL time, matching the old hand-rolled stamp
|
|
447
|
+
// (`getHours()`/`getMinutes()`/`getSeconds()` are all local-time getters, unlike
|
|
448
|
+
// `toISOString()`'s UTC). sv-SE's default format is already zero-padded
|
|
449
|
+
// "YYYY-MM-DD HH:MM:SS"; stripping the punctuation and reinserting one dash reproduces
|
|
450
|
+
// the exact `YYYYMMDD-HHMMSS` shape the padStart version built by hand.
|
|
451
|
+
const stamp = new Date().toLocaleString('sv-SE').replace(/\D/g, '').replace(/^(\d{8})/, '$1-');
|
|
452
|
+
const parent = path.join(path.dirname(store), `archived-${path.basename(store)}`);
|
|
453
|
+
// A taken name gets `-2`, …: two moves in one second must not fail the second.
|
|
454
|
+
let dest = path.join(parent, stamp);
|
|
455
|
+
for (let n = 2; existsSync(dest); n += 1) dest = path.join(parent, `${stamp}-${n}`);
|
|
456
|
+
mkdirSync(parent, { recursive: true });
|
|
457
|
+
move(store, dest);
|
|
458
|
+
return dest;
|
|
459
|
+
}
|
|
460
|
+
|
|
395
461
|
/**
|
|
396
462
|
* `consolidate_memory` — rebuild both index levels from the fact files actually on disk:
|
|
397
463
|
* index orphans, prune dead lines, refresh each line from its fact's description, report
|
|
@@ -411,3 +477,139 @@ export function consolidateMemory(memDir) {
|
|
|
411
477
|
const pruned = [...old.keys()].filter((s) => !facts.has(s)).sort();
|
|
412
478
|
return { added, pruned, duplicates: dups };
|
|
413
479
|
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* `## R<n> — Title`, anchored at column 0 so a rule body's fenced code and the stub's
|
|
483
|
+
* indented format example never parse as rules.
|
|
484
|
+
*
|
|
485
|
+
* The whitespace classes are `WHITESPACE`, not `\s`: this pattern runs over a HAND-EDITED
|
|
486
|
+
* file, which is where a non-breaking space actually turns up. `\S` is its complement for
|
|
487
|
+
* the same reason.
|
|
488
|
+
*
|
|
489
|
+
* `\d` IS LEFT ASCII, and that is a declared divergence rather than an oversight, unlike
|
|
490
|
+
* `ruleFields` (`js/web/user-files.mjs`), which uses `\p{Nd}`. No theme seeds a non-ASCII rule id, no build
|
|
491
|
+
* writes one, and the web editor cannot produce one either — it writes `R<n>` itself from
|
|
492
|
+
* `max(ids) + 1`. Widening this to match would only move the gap one line down, to whatever
|
|
493
|
+
* parses the captured digits back into a number.
|
|
494
|
+
*/
|
|
495
|
+
const RULE_HEAD_RE = new RegExp(
|
|
496
|
+
`^##[${WHITESPACE}]+R(\\d+)[${WHITESPACE}]*[—–-]+[${WHITESPACE}]*`
|
|
497
|
+
+ `([^${WHITESPACE}].*?)[${WHITESPACE}]*$`,
|
|
498
|
+
);
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* A line `parseRules` reads as the edge of a rule: `## ` ends the current block, and a
|
|
502
|
+
* `RULE_HEAD_RE` line opens one (a non-breaking space after `##` does the second, not the first).
|
|
503
|
+
* ONE predicate for both the parser and `ruleFields`, so a body the writer accepts can never
|
|
504
|
+
* split or forge a rule when read back.
|
|
505
|
+
*/
|
|
506
|
+
export const isRuleEdge = (line) => line.startsWith('## ') || RULE_HEAD_RE.test(line);
|
|
507
|
+
|
|
508
|
+
const META_RE = new RegExp(`^\\((.+)\\)[${WHITESPACE}]*$`);
|
|
509
|
+
|
|
510
|
+
/** `{}` when the line is body rather than metadata. */
|
|
511
|
+
function parseRuleMeta(line) {
|
|
512
|
+
const m = META_RE.exec(stripWhitespace(line));
|
|
513
|
+
if (!m) return {};
|
|
514
|
+
const meta = {};
|
|
515
|
+
for (const part of m[1].split('|')) {
|
|
516
|
+
const at = part.indexOf(':');
|
|
517
|
+
if (at < 0) continue; // `partition` with no separator — not a pair
|
|
518
|
+
const key = stripWhitespace(part.slice(0, at)).toLowerCase().replaceAll(' ', '_');
|
|
519
|
+
if (['scope', 'source', 'trial_until'].includes(key)) {
|
|
520
|
+
meta[key] = stripWhitespace(part.slice(at + 1));
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return meta;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* `user-rules.md` parsed to `[rules, warnings]`.
|
|
528
|
+
*
|
|
529
|
+
* Every rule carries its `start`/`end` LINE INDICES, which is what lets `apiRulesMutate`
|
|
530
|
+
* splice exactly one block and leave every other byte of the user's file — prose,
|
|
531
|
+
* formatting, hand-written sections — untouched.
|
|
532
|
+
* @returns {[Array<{id: number, start: number, end: number} & Record<string, any>>, string[]]}
|
|
533
|
+
*/
|
|
534
|
+
export function parseRules(text) {
|
|
535
|
+
const lines = splitLines(text);
|
|
536
|
+
const rules = [];
|
|
537
|
+
const warnings = [];
|
|
538
|
+
const seen = new Set();
|
|
539
|
+
for (let idx = 0; idx < lines.length; idx += 1) {
|
|
540
|
+
const m = RULE_HEAD_RE.exec(lines[idx]);
|
|
541
|
+
if (!m) continue;
|
|
542
|
+
let end = lines.length;
|
|
543
|
+
for (let j = idx + 1; j < lines.length; j += 1) {
|
|
544
|
+
if (isRuleEdge(lines[j])) { end = j; break; }
|
|
545
|
+
}
|
|
546
|
+
const rid = Number(m[1]);
|
|
547
|
+
if (seen.has(rid)) warnings.push(`duplicate rule id R${rid}`);
|
|
548
|
+
seen.add(rid);
|
|
549
|
+
let k = idx + 1;
|
|
550
|
+
while (k < end && !stripWhitespace(lines[k])) k += 1;
|
|
551
|
+
const meta = k < end ? parseRuleMeta(lines[k]) : {};
|
|
552
|
+
if (Object.keys(meta).length) k += 1;
|
|
553
|
+
rules.push({
|
|
554
|
+
id: rid,
|
|
555
|
+
title: m[2],
|
|
556
|
+
scope: Object.hasOwn(meta, 'scope') ? meta.scope : 'project',
|
|
557
|
+
source: Object.hasOwn(meta, 'source') ? meta.source : '',
|
|
558
|
+
trial_until: Object.hasOwn(meta, 'trial_until') ? meta.trial_until : '',
|
|
559
|
+
body: stripWhitespace(lines.slice(k, end).join('\n')),
|
|
560
|
+
start: idx,
|
|
561
|
+
end,
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
return [rules, warnings];
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// The draft's block headings: the fold writes them, `parseDraft` reads them, and the rule Rite's
|
|
568
|
+
// approval flow (src/skills/rule/approve.md) names them, so a change here changes that file too.
|
|
569
|
+
export const draftRuleHead = (host, title) => `## Rule from ${host}: ${title}`;
|
|
570
|
+
export const draftChoiceHead = (file) => `## Choose: ${file}`;
|
|
571
|
+
const DRAFT_RULE_RE = /^## Rule from ([^:]+): (.+)$/;
|
|
572
|
+
const DRAFT_CHOICE = draftChoiceHead('');
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* The blocks of `user-rules.draft.md`, as `{title, host, key, body}`, in file order. A
|
|
576
|
+
* `## Rule from <host>: <title>` block is a pointer line, then the rule. A `## Choose: <file>` block
|
|
577
|
+
* is a question about two files, so it keeps its title alone. Every other heading (`## Renumbered`,
|
|
578
|
+
* the file's record of past decisions) ends the block before it and adds none. `key` is the
|
|
579
|
+
* pointer line's `sha256`, the block's row in the ledger.
|
|
580
|
+
*/
|
|
581
|
+
export function parseDraft(text) {
|
|
582
|
+
const out = [];
|
|
583
|
+
let open = null;
|
|
584
|
+
for (const line of splitLines(text)) {
|
|
585
|
+
if (line.startsWith('## ')) {
|
|
586
|
+
const rule = DRAFT_RULE_RE.exec(line);
|
|
587
|
+
open = rule ? { title: rule[2], host: rule[1], lines: [] }
|
|
588
|
+
: line.startsWith(DRAFT_CHOICE) ? { title: line.slice(3), host: null, lines: [] } : null;
|
|
589
|
+
if (open) out.push(open);
|
|
590
|
+
} else open?.lines.push(line);
|
|
591
|
+
}
|
|
592
|
+
return out.map(({ title, host, lines }) => ({
|
|
593
|
+
title, host, key: /sha256: (\w+)/.exec(lines[0] ?? '')?.[1],
|
|
594
|
+
body: host ? stripWhitespace(lines.slice(1).join('\n')) : '',
|
|
595
|
+
}));
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* The ledger, or an empty one. One that holds nothing counts as empty and is written whole by the
|
|
600
|
+
* next item, because a key set on `[]` never reaches the file and the item would be reported on
|
|
601
|
+
* every emit. Anything else that is no ledger throws: treating it as empty would draft every
|
|
602
|
+
* decided item again, and the failed step is what the user should see.
|
|
603
|
+
*/
|
|
604
|
+
export function readFoldState(shared) {
|
|
605
|
+
const blank = (v) => v === null || v === undefined || (Array.isArray(v) && !v.length);
|
|
606
|
+
if (!existsSync(shared.foldState)) return { version: 1, items: {} };
|
|
607
|
+
const text = readFileSync(shared.foldState, 'utf8');
|
|
608
|
+
const state = text.trim() ? JSON.parse(text) : null;
|
|
609
|
+
if (blank(state)) return { version: 1, items: {} };
|
|
610
|
+
if (!isDict(state) || !(blank(state.items) || isDict(state.items))) {
|
|
611
|
+
throw new Error(`${shared.foldState} is not a ledger`);
|
|
612
|
+
}
|
|
613
|
+
if (blank(state.items)) state.items = {};
|
|
614
|
+
return state;
|
|
615
|
+
}
|
|
@@ -37,7 +37,7 @@ const MANAGED_BLOCK_RE = /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/g
|
|
|
37
37
|
const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
|
|
38
38
|
|
|
39
39
|
// Write-shaped tool names (Bob's `tool-gate` also routes reads here: `read_file` carries a path).
|
|
40
|
-
export const WRITE_NAME_RE = /write|edit|diff|replace|insert/i;
|
|
40
|
+
export const WRITE_NAME_RE = /write|edit|diff|replace|insert|move|rename|delete|remove|trash|copy/i;
|
|
41
41
|
|
|
42
42
|
// js/hosts/activity.mjs `safeStem`, copied (that module is not on the gate path): a hostile
|
|
43
43
|
// session id can never steer the marker join out of its directory.
|
package/js/hosts/settings.mjs
CHANGED
|
@@ -22,9 +22,8 @@
|
|
|
22
22
|
*
|
|
23
23
|
* HOOKS ARE APPEND-ONLY AND FAIL-CLOSED. Nothing here rewrites a hook group in place:
|
|
24
24
|
* `mergeClaudeSettings` appends what is missing and removes only groups the manifest
|
|
25
|
-
* recorded, and cleanup goes through `GENESEED_HOOK_SNIFF`, which
|
|
26
|
-
*
|
|
27
|
-
* strands live hooks in every config emitted before the change.
|
|
25
|
+
* recorded, and cleanup goes through `GENESEED_HOOK_SNIFF`, which recognises the shim form. A
|
|
26
|
+
* 1.x install, wired before the shim, must rebuild first.
|
|
28
27
|
*
|
|
29
28
|
* ONE KNOWN DIVERGENCE, recorded rather than reproduced. JS objects order integer-like
|
|
30
29
|
* keys first, so a settings.json carrying a `"1"` or `"2"` at any level comes back from
|
|
@@ -405,9 +404,14 @@ function reconcileOpencodeSkillPermission(perm, names, staleNames = [], added =
|
|
|
405
404
|
export function opencodeEditAsks(cfgDir, global, agentRel = null) {
|
|
406
405
|
const cfg = path.basename(cfgDir);
|
|
407
406
|
const tails = ['opencode.json', 'opencode.jsonc', ...['excludes.json', GLOBAL_MANIFEST, '.geneseed-emit',
|
|
408
|
-
'plugins
|
|
407
|
+
'plugins/*', 'plugin/*', 'agents/*.md', 'agent/*.md', 'mode/*.md', 'modes/*.md', 'tool/*', 'tools/*',
|
|
408
|
+
...(global ? ['AGENT.md', 'config.json'] : [])].map((f) => `${cfg}/${f}`),
|
|
409
409
|
...['.claude', '.openclaude', '.bob'].flatMap((m) => [`${m}/settings.json`, `${m}/settings.local.json`]),
|
|
410
|
-
'.bob/settings/settings.json'
|
|
410
|
+
'.bob/settings/settings.json',
|
|
411
|
+
// Persist Insight: the rule and memory stores, which the guard no longer releases on a re-issue.
|
|
412
|
+
// The coined names match anywhere, as the guard and Claude's rule gate match them; the memory
|
|
413
|
+
// folders by their last segments, so a project's unrelated `memory/` is never asked about.
|
|
414
|
+
'user-rules.md', 'user-rules.draft.md', 'MEMORY.md', `${cfg}/memory/*.md`, 'geneseed/memory/*.md'];
|
|
411
415
|
const keys = [];
|
|
412
416
|
if (agentRel) {
|
|
413
417
|
const abs = path.resolve(path.dirname(cfgDir), agentRel);
|
|
@@ -415,6 +419,10 @@ export function opencodeEditAsks(cfgDir, global, agentRel = null) {
|
|
|
415
419
|
const gitRel = git ? path.relative(git, abs).split(path.sep).join('/') : agentRel;
|
|
416
420
|
keys.push(...new Set([agentRel, gitRel, `*../${agentRel}`,
|
|
417
421
|
...(agentRel.includes('/') ? [`*/${agentRel}`] : [])]));
|
|
422
|
+
// The store sits beside the carrier (`<out>/memory`, js/build/bundle.mjs), the same four shapes.
|
|
423
|
+
const beside = (rel) => path.posix.join(path.posix.dirname(rel), 'memory/*.md');
|
|
424
|
+
keys.push(...new Set([beside(agentRel), beside(gitRel), `*../${beside(agentRel)}`,
|
|
425
|
+
...(agentRel.includes('/') ? [`*/${beside(agentRel)}`] : [])]));
|
|
418
426
|
}
|
|
419
427
|
try {
|
|
420
428
|
const home = shimHome();
|
|
@@ -582,7 +590,7 @@ export function atomicWriteJson(p, config) {
|
|
|
582
590
|
|
|
583
591
|
/** `_build_settings._merge_opencode_json`. Returns the resolved target path.
|
|
584
592
|
*
|
|
585
|
-
* Zero runtime callers — re-measured this phase and still true.
|
|
593
|
+
* Zero runtime callers — re-measured this phase and still true. The MCP module
|
|
586
594
|
* re-implements the inverse itself rather than inherit this one's permission/lsp side
|
|
587
595
|
* effects, so the only crossings are the two emit-tree ones (`_build_emit.emit_opencode`,
|
|
588
596
|
* `_build_global.emit_opencode_global`).
|
|
@@ -1138,13 +1146,10 @@ export function unwireClaudeExcludes(p, excludes) {
|
|
|
1138
1146
|
}
|
|
1139
1147
|
|
|
1140
1148
|
// ---- Settings integrity check -----------------------------------------------------
|
|
1141
|
-
// Substrings that mark a hook command as Geneseed's.
|
|
1142
|
-
//
|
|
1143
|
-
//
|
|
1144
|
-
|
|
1145
|
-
// to the orphan scan — the one place a stranded hook can still surface — so cleanup would
|
|
1146
|
-
// silently leave live hooks behind in every config emitted before the shim landed.
|
|
1147
|
-
export const GENESEED_HOOK_SNIFF = ['harness.py', SHIM_MARK];
|
|
1149
|
+
// Substrings that mark a hook command as Geneseed's. Every install since the shim names it; the
|
|
1150
|
+
// floor is stated, not guessed at: a 1.x install, wired to an interpreter and a checkout, must
|
|
1151
|
+
// rebuild first, or its hooks read as the user's own.
|
|
1152
|
+
export const GENESEED_HOOK_SNIFF = [SHIM_MARK];
|
|
1148
1153
|
|
|
1149
1154
|
/** `_build_settings._settings_hook_groups` — flatten `hooks` to [event, group] pairs. */
|
|
1150
1155
|
function settingsHookGroups(loaded) {
|
package/js/hosts/shim.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The machine-wide HOOK SHIM — where it lives, what it says, whether it still resolves — and
|
|
3
|
-
* the
|
|
3
|
+
* the shim-shaped reader `migrate` needs (the autostart scan).
|
|
4
4
|
*
|
|
5
5
|
* SPLIT OUT OF `js/hosts/settings.mjs` (2026-10) for its cheapest caller. Every CLI run asks
|
|
6
6
|
* `shimDead()` (the dead-shim warning in `bin/geneseed-cli.mjs`), and that used to load the
|
|
@@ -361,37 +361,6 @@ export function hookRunnerEntry() {
|
|
|
361
361
|
return { runner: process.execPath, entry: path.join(ROOT, 'bin', 'geneseed-hook.mjs') };
|
|
362
362
|
}
|
|
363
363
|
|
|
364
|
-
// P10d. `GENESEED_HOOK_SNIFF` answers "is this hook Geneseed's?". A MIGRATION needs the other
|
|
365
|
-
// question — "is this Geneseed's OLD one?" — and the two are not the same sniff.
|
|
366
|
-
//
|
|
367
|
-
// THREE SHAPES ARE IN THE WILD, AND TWO OF THEM ARE IDENTICAL IN THE SETTINGS FILE:
|
|
368
|
-
// 1. legacy-direct the command itself names `harness.py` (pre-shim, P0 and earlier)
|
|
369
|
-
// 2. shim-python the command names the shim; the shim BODY runs python + harness.py
|
|
370
|
-
// 3. shim-node the command names the shim; the shim BODY runs node + the .mjs entry
|
|
371
|
-
//
|
|
372
|
-
// 2 and 3 differ ONLY inside the shim body. A classifier reading the host config alone would
|
|
373
|
-
// call a fully-unmigrated machine "already migrated" — silently — and `migrate` would no-op on
|
|
374
|
-
// exactly the installs it exists for. The shim body is a REQUIRED input, not a refinement.
|
|
375
|
-
const SHIM_ENTRY_MARK = 'geneseed-hook.mjs';
|
|
376
|
-
|
|
377
|
-
/**
|
|
378
|
-
* `_build_settings._migrate_shape` — 'legacy' | 'current' | 'none'.
|
|
379
|
-
*
|
|
380
|
-
* PURE — and currently reached only END TO END, by the `migrate/a-node-baked-shim-reads-as-current`
|
|
381
|
-
* cell. No unit corpus drives it directly, which is worth knowing before trusting it.
|
|
382
|
-
* 'none' is not a fault: a user's own settings.json may carry three hand-written hooks
|
|
383
|
-
* and no Geneseed entry. That must read as
|
|
384
|
-
* "nothing to migrate" rather than "unrecognised", or `migrate` refuses on the commonest
|
|
385
|
-
* config on any machine.
|
|
386
|
-
*/
|
|
387
|
-
export function migrateShape(commands, shimBody) {
|
|
388
|
-
if (commands.some((c) => c.includes('harness.py'))) return 'legacy';
|
|
389
|
-
if (commands.some((c) => c.includes(SHIM_MARK))) {
|
|
390
|
-
return shimBody.includes(SHIM_ENTRY_MARK) ? 'current' : 'legacy';
|
|
391
|
-
}
|
|
392
|
-
return 'none';
|
|
393
|
-
}
|
|
394
|
-
|
|
395
364
|
/**
|
|
396
365
|
* `_build_settings._autostart_paths` — where a hand-written web-daemon autostart entry lives.
|
|
397
366
|
*
|
|
@@ -403,9 +372,11 @@ export function migrateShape(commands, shimBody) {
|
|
|
403
372
|
* Both platforms' paths on both platforms, deliberately — the scan is a read that misses
|
|
404
373
|
* harmlessly, and returning only the host platform's would make the macOS arm unreachable
|
|
405
374
|
* from the Windows machine this port is developed on: an ungated branch dressed as a fork.
|
|
375
|
+
* With no home directory there is nowhere to look, and the same read misses: `[]`, not a throw.
|
|
406
376
|
*/
|
|
407
377
|
export function autostartPaths() {
|
|
408
|
-
|
|
378
|
+
let home;
|
|
379
|
+
try { home = os.homedir(); } catch { return []; }
|
|
409
380
|
return [
|
|
410
381
|
path.join(home, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu',
|
|
411
382
|
'Programs', 'Startup', 'geneseed-web.vbs'),
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE CHANGE REPORT: tells the user that a rule, profile, wiki manifest or memory file changed in
|
|
3
|
+
* a session with no approval. It detects; it prevents nothing. Shell is no boundary (the gates read
|
|
4
|
+
* only parsed forms), so this is what still catches a write they never saw, at the end of the turn.
|
|
5
|
+
*
|
|
6
|
+
* OFF THE PER-CALL PATH. Nothing here loads on a tool call. The hook entry takes the baseline after
|
|
7
|
+
* `context` has answered, once per session, and `learn` compares on Stop. Both are stats, no reads.
|
|
8
|
+
*
|
|
9
|
+
* WHAT COUNTS AS APPROVED, per host. Claude and OpenClaude: a Write, Edit or NotebookEdit the
|
|
10
|
+
* transcript shows ran, because a gated tool runs only past the host's prompt. The transcript is read
|
|
11
|
+
* only when a file changed, which keeps the common Stop to the stats. Bob has no transcript and no
|
|
12
|
+
* file-tool write passes its gate, so every change there is reported. OpenCode has this logic in
|
|
13
|
+
* the guard plugin, with the baseline in memory and approval from `tool.execute.after`.
|
|
14
|
+
*
|
|
15
|
+
* GENESEED'S OWN WRITES. `learn`, a memory removal and the fold run inside `recordOwnWrites`, which
|
|
16
|
+
* snapshots the store around the run and logs what moved to `memory/.own-writes.json`, as an exact
|
|
17
|
+
* size and mtime. A change matching the log is not reported. Limits: a write by anything else during
|
|
18
|
+
* that window is excused too, and the log is a plain file an agent could edit. The web console's
|
|
19
|
+
* edits are not logged, so one made during a session is reported.
|
|
20
|
+
*
|
|
21
|
+
* WHAT IT CANNOT TELL. Approval is per session, and the tier is shared: another session's approved
|
|
22
|
+
* write reads as a change here, so the line says so rather than call it unapproved. A Claude
|
|
23
|
+
* sub-agent's write sits in its own transcript and reads the same way. shortcut: a false alarm, the
|
|
24
|
+
* safe direction; read the sidechain files here if that proves noisy.
|
|
25
|
+
*
|
|
26
|
+
* WHAT IT CANNOT RESIST. The baseline, like the own-writes log, is a plain file in the install, and
|
|
27
|
+
* an agent that can write there can edit it, or set a file's size and time back. The report is
|
|
28
|
+
* evidence against a careless or a weak agent, not a control against a determined one.
|
|
29
|
+
*
|
|
30
|
+
* Every entry swallows its errors: a report that cannot be made must never change a hook's verdict.
|
|
31
|
+
* Nothing here prints. The caller decides where the line goes, because a Stop's stdout is one document.
|
|
32
|
+
*/
|
|
33
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
34
|
+
import path from 'node:path';
|
|
35
|
+
|
|
36
|
+
import { machineDir } from '../lib/machine-dir.mjs';
|
|
37
|
+
import { normcase } from '../lib/paths.mjs';
|
|
38
|
+
import { sovereignBypass } from './hosts.mjs';
|
|
39
|
+
|
|
40
|
+
const STATE_DIR = path.join('notebook', 'store-baseline');
|
|
41
|
+
const OWN_LOG = '.own-writes.json';
|
|
42
|
+
const OWN_LOG_CAP = 2000;
|
|
43
|
+
const STALE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
44
|
+
const NAMES_SHOWN = 5;
|
|
45
|
+
|
|
46
|
+
/** The store files under one home, as `path -> "size:mtime"`. The guard's `storeScan` is its twin. */
|
|
47
|
+
export function storeScan(home, found = {}) {
|
|
48
|
+
const stamp = (f) => {
|
|
49
|
+
try { const s = statSync(f); if (s.isFile()) found[f] = `${s.size}:${Math.trunc(s.mtimeMs)}`; } catch { /* absent */ }
|
|
50
|
+
};
|
|
51
|
+
for (const n of ['user-rules.md', 'PROFILE.md', 'geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json']) stamp(path.join(home, n));
|
|
52
|
+
const walk = (dir) => {
|
|
53
|
+
let items = [];
|
|
54
|
+
try { items = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
55
|
+
for (const e of items) {
|
|
56
|
+
if (e.isDirectory()) { if (e.name !== 'archive' && !e.name.startsWith('archived-')) walk(path.join(dir, e.name)); }
|
|
57
|
+
else if (e.name.endsWith('.md')) stamp(path.join(dir, e.name));
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
walk(path.join(home, 'memory'));
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const homesOf = (root) => [...new Set([root, machineDir()])];
|
|
65
|
+
const scanAll = (root) => homesOf(root).reduce((found, h) => storeScan(h, found), {});
|
|
66
|
+
const stateFile = (root, sid) => path.join(root, STATE_DIR, `${String(sid).replace(/[^\w.-]/g, '_').slice(0, 120)}.json`);
|
|
67
|
+
const readJson = (f) => { try { return JSON.parse(readFileSync(f, 'utf8')); } catch { return null; } };
|
|
68
|
+
|
|
69
|
+
function saveBaseline(root, sid, stamps) {
|
|
70
|
+
const f = stateFile(root, sid);
|
|
71
|
+
mkdirSync(path.dirname(f), { recursive: true });
|
|
72
|
+
writeFileSync(f, JSON.stringify(stamps));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The session's baseline, written once. SessionStart fires again on resume and compact: keeping the
|
|
77
|
+
* first one means those cannot launder a change made before them. Old sessions' files are dropped.
|
|
78
|
+
*/
|
|
79
|
+
export function writeBaseline(root, sid) {
|
|
80
|
+
try {
|
|
81
|
+
if (typeof sid !== 'string' || !sid || sovereignBypass(root)) return;
|
|
82
|
+
const f = stateFile(root, sid);
|
|
83
|
+
if (existsSync(f)) return;
|
|
84
|
+
saveBaseline(root, sid, scanAll(root));
|
|
85
|
+
const dir = path.dirname(f);
|
|
86
|
+
for (const n of readdirSync(dir)) {
|
|
87
|
+
const old = path.join(dir, n);
|
|
88
|
+
if (Date.now() - statSync(old).mtimeMs > STALE_MS) unlinkSync(old);
|
|
89
|
+
}
|
|
90
|
+
} catch { /* no notebook, or a read-only install: no report */ }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** What differs between two scans, sorted. */
|
|
94
|
+
export function changedFiles(before, now) {
|
|
95
|
+
return [...new Set([...Object.keys(before), ...Object.keys(now)])].filter((f) => before[f] !== now[f]).sort();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Run `fn`, Geneseed's own writer, and log what it moved under `home`. A throw from `fn` still logs
|
|
100
|
+
* and still propagates. `home` is the folder holding `memory/`.
|
|
101
|
+
*/
|
|
102
|
+
export function recordOwnWrites(home, fn) {
|
|
103
|
+
let before = null;
|
|
104
|
+
try { before = storeScan(home); } catch { /* the write still runs */ }
|
|
105
|
+
try { return fn(); } finally {
|
|
106
|
+
try {
|
|
107
|
+
if (before) {
|
|
108
|
+
const now = storeScan(home);
|
|
109
|
+
const moved = changedFiles(before, now);
|
|
110
|
+
if (moved.length) {
|
|
111
|
+
const f = path.join(home, 'memory', OWN_LOG);
|
|
112
|
+
const log = { ...readJson(f) };
|
|
113
|
+
for (const p of moved) { delete log[p]; log[p] = now[p] ?? 'gone'; }
|
|
114
|
+
const kept = Object.entries(log).slice(-OWN_LOG_CAP);
|
|
115
|
+
mkdirSync(path.dirname(f), { recursive: true });
|
|
116
|
+
writeFileSync(f, JSON.stringify(Object.fromEntries(kept)));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
} catch { /* the log never fails a write */ }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The files the transcript shows a file tool really wrote: a tool_use whose result was no error. */
|
|
124
|
+
export function approvedInTranscript(file, cwd) {
|
|
125
|
+
const asked = new Map();
|
|
126
|
+
const failed = new Set();
|
|
127
|
+
let text = '';
|
|
128
|
+
try { text = readFileSync(file, 'utf8'); } catch { return new Set(); }
|
|
129
|
+
for (const line of text.split('\n')) {
|
|
130
|
+
if (!line.includes('"tool_use"') && !line.includes('"tool_result"')) continue;
|
|
131
|
+
let row;
|
|
132
|
+
try { row = JSON.parse(line); } catch { continue; }
|
|
133
|
+
const blocks = row?.message?.content;
|
|
134
|
+
for (const b of Array.isArray(blocks) ? blocks : []) {
|
|
135
|
+
if (b?.type === 'tool_use' && /^(?:Write|Edit|MultiEdit|NotebookEdit)$/.test(b.name)) {
|
|
136
|
+
const p = b.input?.file_path ?? b.input?.notebook_path;
|
|
137
|
+
if (typeof p === 'string') asked.set(b.id, normcase(path.resolve(cwd || process.cwd(), p)));
|
|
138
|
+
} else if (b?.type === 'tool_result' && b.is_error) failed.add(b.tool_use_id);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return new Set([...asked].filter(([id]) => !failed.has(id)).map(([, p]) => p));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The line the user reads. The guard's `storeLine` is its twin, same words. */
|
|
145
|
+
export function storeLine(files) {
|
|
146
|
+
const shown = files.slice(0, NAMES_SHOWN).map((f) => f.split(/[\\/]/).slice(-2).join('/')).join(', ');
|
|
147
|
+
const more = files.length > NAMES_SHOWN ? ` (+${files.length - NAMES_SHOWN} more)` : '';
|
|
148
|
+
return `Geneseed change report: ${files.length} rule or memory file${files.length === 1 ? '' : 's'} `
|
|
149
|
+
+ `changed outside this session's approved writes (another session may have made it): ${shown}${more}. `
|
|
150
|
+
+ 'This detects a change; it prevented nothing.';
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** What `geneseed status` shows: the last report, machine-wide, written only where the tier exists. */
|
|
154
|
+
function noteForStatus(files, host) {
|
|
155
|
+
try {
|
|
156
|
+
const dir = machineDir();
|
|
157
|
+
if (existsSync(dir)) writeFileSync(path.join(dir, '.store-report.json'), JSON.stringify({ at: new Date().toISOString(), host, files }));
|
|
158
|
+
} catch { /* an unwritable status file must not swallow the report */ }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The last report within the stale window, or null. For `geneseed status`. */
|
|
162
|
+
export function lastStoreReport() {
|
|
163
|
+
try {
|
|
164
|
+
const r = readJson(path.join(machineDir(), '.store-report.json'));
|
|
165
|
+
return r && Array.isArray(r.files) && Date.now() - Date.parse(r.at) < STALE_MS ? r : null;
|
|
166
|
+
} catch { return null; } // no home directory: `status` must still answer
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Compare at a turn's end: the line to show, or null. Rolls the baseline, so a change is said once,
|
|
171
|
+
* and a session with no baseline (installed mid-session) starts one here. `transcript` is null on Bob.
|
|
172
|
+
*/
|
|
173
|
+
export function storeReport(root, sid, { transcript = null, cwd = null, host = 'claude' } = {}) {
|
|
174
|
+
try {
|
|
175
|
+
if (typeof sid !== 'string' || !sid) return null;
|
|
176
|
+
const before = readJson(stateFile(root, sid));
|
|
177
|
+
if (!before) { writeBaseline(root, sid); return null; }
|
|
178
|
+
const now = scanAll(root);
|
|
179
|
+
const changed = changedFiles(before, now);
|
|
180
|
+
if (!changed.length) return null;
|
|
181
|
+
saveBaseline(root, sid, now);
|
|
182
|
+
const own = homesOf(root).reduce((log, h) => ({ ...log, ...readJson(path.join(h, 'memory', OWN_LOG)) }), {});
|
|
183
|
+
const approved = typeof transcript === 'string' ? approvedInTranscript(transcript, cwd) : new Set();
|
|
184
|
+
const files = changed.filter((f) => own[f] !== (now[f] ?? 'gone') && !approved.has(normcase(f)));
|
|
185
|
+
if (!files.length) return null;
|
|
186
|
+
noteForStatus(files, host);
|
|
187
|
+
return storeLine(files);
|
|
188
|
+
} catch { return null; }
|
|
189
|
+
}
|