geneseed 4.31.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 +107 -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 +220 -18
- package/adapters/opencode/plugins/geneseed-guard.js +578 -74
- 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 +6 -6
- package/docs/concepts/footprint.md +1 -1
- package/docs/concepts/foreman-mode.md +2 -2
- package/docs/concepts/hook-gates.md +1 -1
- package/docs/concepts/hooks.md +27 -11
- package/docs/concepts/host-matrix.md +3 -3
- package/docs/concepts/hosts.md +1 -1
- package/docs/concepts/kits.md +3 -1
- package/docs/concepts/loop-bricks.md +1 -1
- package/docs/concepts/loop-notes.md +4 -2
- package/docs/concepts/loop-templates.md +7 -4
- package/docs/concepts/loops.md +3 -0
- package/docs/concepts/ownership.md +2 -2
- 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/run-a-loop.md +1 -1
- package/docs/guides/set-up-ownership.md +1 -1
- 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/loop-actions.md +1 -1
- package/docs/reference/opencode-plugins.md +3 -3
- package/docs/reference/plugin-activity.md +1 -1
- package/docs/reference/plugin-context.md +5 -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 +4 -3
- package/docs/understand/machine-bob.md +3 -1
- 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 +141 -73
- 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 +410 -99
- package/js/hosts/hooks-done.mjs +97 -31
- package/js/hosts/hooks-learn.mjs +38 -7
- package/js/hosts/hooks-prims.mjs +69 -2
- package/js/hosts/hooks.mjs +300 -64
- 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/loop/state.mjs +15 -5
- 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 +38 -38
- package/js/web/api.mjs +132 -76
- 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 +4 -1
- package/src/agents/advocate.md +1 -1
- package/src/agents/architect.md +1 -1
- package/src/agents/developer.md +6 -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 +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 +5 -2
- package/src/agents/user-advocate.md +1 -1
- package/src/agents/visionary.md +1 -1
- package/src/bricks/apply.md +3 -0
- package/src/bricks/test.md +6 -4
- package/src/loops/bugfix.json +11 -5
- package/src/loops/feature.json +7 -4
- 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/loop.md +1 -0
- 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/ship.md +9 -1
- 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-IXnXzH4Y.js → CopyButton-CHQte7Ap.js} +1 -1
- package/web/dist/assets/Dashboard-B8uXeJZ_.js +2 -0
- package/web/dist/assets/{DataTable-BWbUx4bY.js → DataTable-b9zTShqJ.js} +1 -1
- package/web/dist/assets/Docs-Dgv_MWfT.js +5 -0
- package/web/dist/assets/{EmptyState-1sPNleqv.js → EmptyState-CY5Pm2xy.js} +1 -1
- package/web/dist/assets/FilterInput-qGKNSlxv.js +1 -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-C5u7fQOR.js → Loops-S85PMQ8m.js} +2 -2
- package/web/dist/assets/Markdown-0ORz7tAc.js +69 -0
- package/web/dist/assets/OperatorHudView-DuGz_sTk.js +1 -0
- package/web/dist/assets/Personal-afJNwvRS.js +2 -0
- package/web/dist/assets/RailCats-AW92uhsX.js +1 -0
- 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/react-C1iE8mnY.js +9 -0
- package/web/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/web/dist/assets/{sections-ChwaobfW.js → sections-CtFz7HFH.js} +1 -1
- package/web/dist/assets/{usePoll-bDFN-Hr6.js → usePoll-o8ul-Sog.js} +1 -1
- package/web/dist/index.html +7 -7
- package/src/skills/quiz.md +0 -44
- package/web/dist/assets/Activity-B7cFtS00.js +0 -1
- package/web/dist/assets/ActivityDetail-C-GbMmuW.js +0 -1
- package/web/dist/assets/Bonsai-_YyexVC5.js +0 -1
- package/web/dist/assets/Dashboard-sCfEjowQ.js +0 -2
- package/web/dist/assets/Docs-w3Y7M5Ts.js +0 -5
- package/web/dist/assets/FilterInput-CZREvrjX.js +0 -1
- package/web/dist/assets/GreenhouseView-BWWbMKmg.js +0 -1
- package/web/dist/assets/Installs-CnkdJ-VA.js +0 -3
- package/web/dist/assets/JournalView-C7bPD3fZ.js +0 -1
- package/web/dist/assets/KitApply-CQQbnThf.js +0 -1
- package/web/dist/assets/Kits-aj07N7mT.js +0 -1
- package/web/dist/assets/Laws-DZ38nl_H.js +0 -3
- package/web/dist/assets/Library-QCGXPV5h.js +0 -2
- package/web/dist/assets/Markdown-DpmmtW2Y.js +0 -65
- package/web/dist/assets/OperatorHudView-Blu1lqiZ.js +0 -1
- package/web/dist/assets/Personal-ox_MktWO.js +0 -2
- package/web/dist/assets/RailCats-BuJD4Jou.js +0 -1
- package/web/dist/assets/Tabs-CIPyMAX-.js +0 -1
- package/web/dist/assets/api-BxjLd7Qd.js +0 -1
- package/web/dist/assets/index-0GCxkY7m.css +0 -1
- package/web/dist/assets/index-CzDi9JpF.js +0 -3
- package/web/dist/assets/motion-CXaUMNkg.js +0 -1
- package/web/dist/assets/react-DlYQp10C.js +0 -9
- package/web/dist/assets/rolldown-runtime-hePW80VL.js +0 -1
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
// - Deletion Is Deliberate: block catastrophic shell commands, and every command that would
|
|
10
10
|
// really lose data, judged against the repository's state (`lossReason`, below).
|
|
11
11
|
// - Commands Must Return: block a recursive scan rooted at a whole filesystem (find /).
|
|
12
|
-
// - Persist Insight (rule vs memory):
|
|
13
|
-
//
|
|
12
|
+
// - Persist Insight (rule vs memory): a write to user-rules.md or a memory file needs the
|
|
13
|
+
// HOST's own prompt (`permission.edit`; on V2 the `evaluate` hook too); with none, it is refused.
|
|
14
14
|
// - Wiki (AGENT.md §8): block mutations under a declared wiki's `protected`
|
|
15
15
|
// folders — the user's knowledge base sets its own no-go zones in geneseed-wiki.jsonc.
|
|
16
16
|
// - Ownership: in an application repo whose root AGENTS.md has no `## Ownership` section,
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
// upgrade path there is still a session-level `permission` ruleset set by the loop launcher
|
|
52
52
|
// when it creates the loop session (`session.create` accepts one).
|
|
53
53
|
|
|
54
|
-
import { promises as fs, realpathSync, existsSync, readFileSync, readdirSync, statSync, lstatSync } from "node:fs"
|
|
54
|
+
import { promises as fs, realpathSync, existsSync, readFileSync, readdirSync, readlinkSync, statSync, lstatSync, writeFileSync } from "node:fs"
|
|
55
55
|
import { spawnSync } from "node:child_process"
|
|
56
56
|
import * as path from "node:path"
|
|
57
57
|
import { fileURLToPath } from "node:url"
|
|
@@ -114,8 +114,13 @@ async function mainWorktreeOf(dir) {
|
|
|
114
114
|
async function sovereignBypass(cwd) {
|
|
115
115
|
try {
|
|
116
116
|
const cfg = path.dirname(PLUGIN_DIR) // plugins/ sits directly in <cfg>
|
|
117
|
-
const
|
|
118
|
-
|
|
117
|
+
const listOf = async (file) => {
|
|
118
|
+
try { const l = JSON.parse(await fs.readFile(file, "utf8")).excludes; return Array.isArray(l) ? l : [] } catch { return [] }
|
|
119
|
+
}
|
|
120
|
+
const entries = await listOf(path.join(cfg, "excludes.json"))
|
|
121
|
+
// Shared list (<machineDir>/excludes.json): a GLOBAL install adds it, a project install never does.
|
|
122
|
+
const shared = await listOf(path.join(machineDir(), "excludes.json"))
|
|
123
|
+
if (shared.length && await readsTier(cfg)) entries.push(...shared)
|
|
119
124
|
const here = norm(cwd || process.cwd())
|
|
120
125
|
const main = await mainWorktreeOf(cwd || process.cwd())
|
|
121
126
|
const heres = main ? [here, norm(main)] : [here]
|
|
@@ -1106,22 +1111,22 @@ function parsePatchPaths(patchText) {
|
|
|
1106
1111
|
return patchSections(patchText).flatMap((s) => [s.from, s.path]).filter(Boolean)
|
|
1107
1112
|
}
|
|
1108
1113
|
|
|
1109
|
-
//
|
|
1110
|
-
//
|
|
1111
|
-
//
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
+
// The argument keys that can name a target. Every one is read, never the first found: a call that
|
|
1115
|
+
// carried a decoy `patchText` or a harmless `path` beside the real `filePath` once hid the target
|
|
1116
|
+
// from every gate, a hard refusal such as `.ssh/id_rsa` included.
|
|
1117
|
+
const PATH_KEYS = ["filePath", "file_path", "path", "file", "target", "filename", "destination", "dest"]
|
|
1118
|
+
function plainPaths(args) {
|
|
1119
|
+
// Normalize Windows backslashes to `/` so the secret-path patterns (which use `/`
|
|
1120
|
+
// as the segment separator) match `C:\Users\me\.ssh\id_rsa` the same as a POSIX path.
|
|
1121
|
+
return PATH_KEYS.map((k) => args?.[k]).filter((v) => typeof v === "string" && v).map((v) => v.replace(/\\/g, "/"))
|
|
1122
|
+
}
|
|
1123
|
+
// Returns every candidate path for this call, normalized (backslashes -> `/`): every path key, and
|
|
1124
|
+
// every patch marker resolved against `cwd` (the session's `ctx.directory` — the same root
|
|
1125
|
+
// `apply_patch.ts:72` resolves against upstream) since a patch marker is worktree-relative.
|
|
1114
1126
|
function pickPath(args, cwd) {
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
}
|
|
1119
|
-
for (const k of ["filePath", "path", "file", "target", "filename"]) {
|
|
1120
|
-
// Normalize Windows backslashes to `/` so the secret-path patterns (which use `/`
|
|
1121
|
-
// as the segment separator) match `C:\Users\me\.ssh\id_rsa` the same as a POSIX path.
|
|
1122
|
-
if (args && typeof args[k] === "string") return [args[k].replace(/\\/g, "/")]
|
|
1123
|
-
}
|
|
1124
|
-
return []
|
|
1127
|
+
const marked = args && typeof args.patchText === "string" ? parsePatchPaths(args.patchText)
|
|
1128
|
+
.map((p) => path.resolve(cwd || process.cwd(), p).replace(/\\/g, "/")) : []
|
|
1129
|
+
return [...new Set([...marked, ...plainPaths(args)])]
|
|
1125
1130
|
}
|
|
1126
1131
|
// Per-FILE added content for an `apply_patch` call: `parsePatchPaths` flattens every marker
|
|
1127
1132
|
// path into one list (right for the path-only gates, which must catch a secret/protected name
|
|
@@ -1169,19 +1174,17 @@ function patchSections(patchText) {
|
|
|
1169
1174
|
// NEW content — a `-` line is text being REMOVED, so a secret there is leaving the file, not
|
|
1170
1175
|
// landing in it, and must not block the call.
|
|
1171
1176
|
function pickAddedContentByPath(args, cwd) {
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
.
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
if (
|
|
1182
|
-
|
|
1183
|
-
if (typeof args.newString === "string") return [{ path: p, content: args.newString }]
|
|
1184
|
-
return []
|
|
1177
|
+
const found = args && typeof args.patchText === "string" ? parsePatchSections(args.patchText)
|
|
1178
|
+
.filter((s) => s.added.length)
|
|
1179
|
+
.map((s) => ({
|
|
1180
|
+
path: path.resolve(cwd || process.cwd(), s.path).replace(/\\/g, "/"),
|
|
1181
|
+
content: s.added.join("\n"),
|
|
1182
|
+
})) : []
|
|
1183
|
+
// Beside a patch too: a decoy `patchText` must not hide the content a call also carries.
|
|
1184
|
+
const [p] = plainPaths(args)
|
|
1185
|
+
if (!p) return found
|
|
1186
|
+
for (const text of [args.content, args.newString]) if (typeof text === "string") found.push({ path: p, content: text })
|
|
1187
|
+
return found
|
|
1185
1188
|
}
|
|
1186
1189
|
function pickCommand(args) {
|
|
1187
1190
|
for (const k of ["command", "cmd", "script"]) {
|
|
@@ -1253,20 +1256,48 @@ function stripJsonc(text) {
|
|
|
1253
1256
|
return res
|
|
1254
1257
|
}
|
|
1255
1258
|
|
|
1256
|
-
|
|
1259
|
+
// The machine tier: machineDir() in js/lib/machine-dir.mjs, which a plugin cannot import.
|
|
1260
|
+
function machineDir() {
|
|
1261
|
+
return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "geneseed")
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
// The wiki manifest's names, newest first: WIKI_NAMES in js/lib/machine-dir.mjs.
|
|
1265
|
+
const WIKI_NAMES = ["geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]
|
|
1266
|
+
|
|
1267
|
+
// The host's own config dir counts as global too, whatever its marker says (the hook's
|
|
1268
|
+
// isHostGlobalDir accepts both): OPENCODE_CONFIG_DIR, else <XDG config>/opencode.
|
|
1269
|
+
const hostConfigDir = () => process.env.OPENCODE_CONFIG_DIR || path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "opencode")
|
|
1270
|
+
async function isHostConfigDir(dir) {
|
|
1271
|
+
const real = async (d) => { const r = await fs.realpath(path.resolve(d)).catch(() => path.resolve(d)); return process.platform === "win32" ? r.toLowerCase() : r }
|
|
1272
|
+
return (await real(dir)) === (await real(hostConfigDir()))
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
// Whether this install reads the machine tier: its .geneseed-emit names a -global emit, or it IS
|
|
1276
|
+
// the host's own config dir (the two tests of the hook's isHostGlobalDir).
|
|
1277
|
+
async function readsTier(dir) {
|
|
1278
|
+
try { if ((await fs.readFile(path.join(dir, ".geneseed-emit"), "utf8")).trim().endsWith("-global")) return true } catch { /* no marker */ }
|
|
1279
|
+
return isHostConfigDir(dir)
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
// Every manifest in force: $GENESEED_WIKI alone when set, else the host layer's and, for a global
|
|
1283
|
+
// install, the shared one. Protection only widens, so both are read; the context plugin's
|
|
1284
|
+
// seed-or-real choice would need seed hashes this plugin does not carry.
|
|
1285
|
+
async function wikiFiles() {
|
|
1257
1286
|
const explicit = process.env.GENESEED_WIKI
|
|
1258
|
-
if (explicit && (await isFile(explicit))) return explicit
|
|
1287
|
+
if (explicit && (await isFile(explicit))) return [explicit]
|
|
1259
1288
|
const bases = []
|
|
1260
1289
|
if (process.env.GENESEED_HARNESS) bases.push(process.env.GENESEED_HARNESS)
|
|
1261
1290
|
bases.push(path.resolve(PLUGIN_DIR, ".."))
|
|
1291
|
+
if (await readsTier(path.dirname(PLUGIN_DIR))) bases.push(machineDir())
|
|
1292
|
+
const found = []
|
|
1262
1293
|
for (const base of bases) {
|
|
1263
1294
|
// wiki.jsonc and wiki.json are the legacy names from earlier seeds — still honoured.
|
|
1264
|
-
for (const name of
|
|
1295
|
+
for (const name of WIKI_NAMES) {
|
|
1265
1296
|
const p = path.join(base, name)
|
|
1266
|
-
if (await isFile(p))
|
|
1297
|
+
if (await isFile(p)) { found.push(p); break }
|
|
1267
1298
|
}
|
|
1268
1299
|
}
|
|
1269
|
-
return
|
|
1300
|
+
return found
|
|
1270
1301
|
}
|
|
1271
1302
|
|
|
1272
1303
|
// Cached absolute prefixes, refreshed on a short TTL so a manifest edit lands
|
|
@@ -1280,9 +1311,9 @@ async function protectedPrefixes() {
|
|
|
1280
1311
|
if (now - _prot.at < PROT_TTL_MS) return _prot.prefixes
|
|
1281
1312
|
const prefixes = []
|
|
1282
1313
|
try {
|
|
1283
|
-
const file
|
|
1284
|
-
|
|
1285
|
-
|
|
1314
|
+
for (const file of await wikiFiles()) {
|
|
1315
|
+
let data
|
|
1316
|
+
try { data = JSON.parse(stripJsonc(await fs.readFile(file, "utf8"))) } catch { continue } // one bad manifest hides no other
|
|
1286
1317
|
for (const w of Array.isArray(data?.wikis) ? data.wikis : []) {
|
|
1287
1318
|
if (!w?.path || !Array.isArray(w.protected)) continue
|
|
1288
1319
|
for (const d of w.protected) {
|
|
@@ -1299,32 +1330,156 @@ async function protectedPrefixes() {
|
|
|
1299
1330
|
}
|
|
1300
1331
|
|
|
1301
1332
|
// ---- the rule / memory stores (Persist Insight) --------------------------------
|
|
1302
|
-
// Whether something the user wants kept is a standing rule or a durable fact is THEIR
|
|
1303
|
-
//
|
|
1304
|
-
//
|
|
1305
|
-
//
|
|
1306
|
-
//
|
|
1307
|
-
//
|
|
1333
|
+
// Whether something the user wants kept is a standing rule or a durable fact is THEIR call, and
|
|
1334
|
+
// the HOST asks it, never the agent (External Gate). This was a speed bump: the first write was
|
|
1335
|
+
// refused and any re-issue passed, so an agent could release itself by claiming the user's
|
|
1336
|
+
// authorization, and one did (2026-11). `tool.execute.before` can only allow or throw, so the
|
|
1337
|
+
// prompt comes from what runs AFTER it, inside the host's own edit tools:
|
|
1338
|
+
// - V1: `permission.edit` "ask" keys (`opencodeEditAsks`, js/hosts/settings.mjs). V1 calls no
|
|
1339
|
+
// plugin hook on an ask, so the guard passes a native edit only when the merged config really
|
|
1340
|
+
// asks for that path and no "always" has switched that off (`hostPrompts`), and refuses it otherwise.
|
|
1341
|
+
// - V2: the same keys, and `permission.hook("evaluate")` (`setupV2`), which also asks over a saved
|
|
1342
|
+
// approval and a config that drifted.
|
|
1343
|
+
// A tool outside those never reaches either prompt, so a write the guard can see there is refused. A
|
|
1344
|
+
// refusal has no release: a re-issue meets the same answer. Shell is not a boundary: only the parsed
|
|
1345
|
+
// forms `shellWriteTargets` reads are seen, V2 asks on them through `evaluate`, V1 refuses them, and
|
|
1346
|
+
// everything else in a command is the host's own command permission's business.
|
|
1308
1347
|
//
|
|
1309
1348
|
// Install folder and file names are theme-independent by design, so the match is on
|
|
1310
1349
|
// literal names. `user-rules.md` / `MEMORY.md` are Geneseed's own coinage and match
|
|
1311
1350
|
// anywhere; other markdown matches only inside this install's own memory/ dir, so a
|
|
1312
1351
|
// project's unrelated memory/ folder is never caught.
|
|
1313
|
-
const RULE_STORE_BUMPED = new Set()
|
|
1314
1352
|
const nocase = (s) => (process.platform === "win32" ? s.toLowerCase() : s)
|
|
1315
|
-
//
|
|
1316
|
-
//
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1353
|
+
// The host's own edit tools, the only ones its `edit` permission covers (V1 `edit`, `write`,
|
|
1354
|
+
// `apply_patch`; V2 `patch`). The guard's WRITE_TOOLS is a wider substring class, which also
|
|
1355
|
+
// catches an MCP server's writer: that one gets no prompt.
|
|
1356
|
+
const NATIVE_EDIT_TOOLS = new Set(["write", "edit", "apply_patch", "patch"])
|
|
1357
|
+
// A weak model once took a refusal as leave to write the same file through a shell command, so
|
|
1358
|
+
// each text names the one way forward. Neither invites a re-issue: nothing here releases one.
|
|
1359
|
+
const PERSIST_EDIT_TOOL = "Stop and ask the user now (the rule skill). Only the host's own edit tool " +
|
|
1360
|
+
"reaches its prompt, so make this write with it and the host asks the user; re-issuing this " +
|
|
1361
|
+
"call changes nothing, and never write it another way (for example through a shell command)."
|
|
1362
|
+
const PERSIST_NO_PROMPT = "Stop and ask the user now (the rule skill). The host has no prompt wired for " +
|
|
1363
|
+
"this file, so this write stays refused and re-issuing it changes nothing: leave it for the user " +
|
|
1364
|
+
"to write themself, and never write it another way (for example through a shell command)."
|
|
1365
|
+
// Whether the merged `permission.edit` makes V1 ask about `rel`, a path from the worktree: its own
|
|
1366
|
+
// evaluation, the LAST matching rule, with `Wildcard.match`'s pattern (util/wildcard.ts, 1.19.5).
|
|
1367
|
+
function editRuleAsks(edit, rel) {
|
|
1368
|
+
if (typeof edit === "string") return edit === "ask"
|
|
1369
|
+
return Object.entries(edit ?? {}).findLast(([k]) => wildMatch(k, rel))?.[1] === "ask"
|
|
1370
|
+
}
|
|
1371
|
+
// Whether one agent's own ruleset (`client.app.agents()`, config and frontmatter merged) leaves the
|
|
1372
|
+
// write to a prompt: its last rule for `edit` on `rel`. A deny is fine, the host refuses that itself.
|
|
1373
|
+
const agentMayAsk = (rules, rel) => (Array.isArray(rules) ? rules : [])
|
|
1374
|
+
.findLast((r) => wildMatch(r?.permission ?? "", "edit") && wildMatch(r?.pattern ?? "", rel))?.action !== "allow"
|
|
1375
|
+
// The coined names, with their label. Exact case outside a store: `docs/concepts/memory.md` is another
|
|
1376
|
+
// file, on Windows too, and a fold would refuse it for ever. A file that EXISTS under a coined name
|
|
1377
|
+
// comes back in its true case through `landsOn`'s link-followed form, on NTFS and APFS alike; a
|
|
1378
|
+
// differently cased spelling of one that does not exist yet is not caught. Inside a store every .md
|
|
1379
|
+
// counts, whatever its case.
|
|
1380
|
+
const COINED_NAMES = [["user-rules.md", "user-rules.md"], ["MEMORY.md", "the memory index"], ["user-rules.draft.md", "the rule draft"]]
|
|
1381
|
+
const coined = (name) => COINED_NAMES.find(([n]) => n === name)?.[1] ?? null
|
|
1382
|
+
const foldPath = (s) => nocase(s.replace(/\\/g, "/"))
|
|
1383
|
+
// A path with a colon past its drive names an NTFS stream, which writes through to the real file.
|
|
1384
|
+
const namesStream = (p) => process.platform === "win32"
|
|
1385
|
+
&& String(p).replace(/^(?:[\\/]{2}[?.][\\/])?[a-zA-Z]:/, "").includes(":")
|
|
1386
|
+
// What a path lands on: spelled out against `base`, as written and with links followed, the two forms
|
|
1387
|
+
// `protectedCheck` reads, because a link from outside into a store and a store that links out are both
|
|
1388
|
+
// real. `path.resolve` folds `..`, `//` and `.`. Windows also drops a stream and trailing dots and spaces
|
|
1389
|
+
// from each segment, and its `realpath` turns an existing `~1` short name long. A short name of a file
|
|
1390
|
+
// that does not exist yet does not exist either.
|
|
1391
|
+
function landsOn(p, base) {
|
|
1392
|
+
let raw = String(p)
|
|
1393
|
+
if (/^~(?=[\\/]|$)/.test(raw)) raw = homedir() + raw.slice(1)
|
|
1394
|
+
// A Git Bash `/c/…`, a device path, and this machine's admin share all name the drive path.
|
|
1395
|
+
if (process.platform === "win32") {
|
|
1396
|
+
raw = raw.replace(/^\/([a-zA-Z])(?=\/|$)/, "$1:").replace(/^[\\/]{2}[?.][\\/](?=[a-zA-Z]:)/, "")
|
|
1397
|
+
.replace(/^[\\/]{2}(?:localhost|127\.0\.0\.1|\[?::1\]?)[\\/]([a-zA-Z])\$(?=[\\/]|$)/i, "$1:")
|
|
1398
|
+
}
|
|
1399
|
+
let abs = path.resolve(base || process.cwd(), raw)
|
|
1400
|
+
if (process.platform === "win32") {
|
|
1401
|
+
const drive = /^[a-zA-Z]:|^\\\\[^\\]+\\[^\\]+/.exec(abs)?.[0] ?? ""
|
|
1402
|
+
abs = drive + abs.slice(drive.length).split("\\").map((s) => s.replace(/:.*$/, "").replace(/[. ]+$/, "")).join("\\")
|
|
1403
|
+
}
|
|
1404
|
+
// A dangling link has no realpath, and a write through it creates its target: follow it by hand,
|
|
1405
|
+
// each hop through `resolvePath`, because a hop may pass a folder link. Bounded: links can loop.
|
|
1406
|
+
const forms = [abs, resolvePath(abs)]
|
|
1407
|
+
for (let cur = forms[1], hop = 0; hop < 8; hop += 1) {
|
|
1408
|
+
try { cur = resolvePath(path.resolve(path.dirname(cur), readlinkSync(cur))); forms.push(cur) } catch { break }
|
|
1409
|
+
}
|
|
1410
|
+
return forms
|
|
1411
|
+
}
|
|
1412
|
+
// Every memory store this install writes, folded. Not only `<plugin dir>/../memory`: a project install
|
|
1413
|
+
// keeps its store beside its AGENT.md, `<out>/memory`, by default `<root>/Harness/memory`
|
|
1414
|
+
// (js/build/bundle.mjs). A carrier counts only when it holds an AGENT.md, so a project's unrelated
|
|
1415
|
+
// `memory/` is not caught. `$GENESEED_HARNESS` and `$GENESEED_MEMORY` are read live, as `machineDir` is.
|
|
1416
|
+
let wiredHomes = null
|
|
1417
|
+
function storeHomes() {
|
|
1418
|
+
const cfg = path.dirname(PLUGIN_DIR)
|
|
1419
|
+
const root = path.dirname(cfg)
|
|
1420
|
+
wiredHomes ??= agentAskTails(cfg).map((t) => path.resolve(root, path.dirname(t)))
|
|
1421
|
+
const homes = [cfg, machineDir(), path.join(root, "Harness"), ...wiredHomes,
|
|
1422
|
+
...CARRIER_DIRS.filter((d) => existsSync(path.join(d, "AGENT.md")))]
|
|
1423
|
+
if (process.env.GENESEED_HARNESS) homes.push(process.env.GENESEED_HARNESS)
|
|
1424
|
+
return [...new Set(homes.map((h) => path.resolve(h)))]
|
|
1425
|
+
}
|
|
1426
|
+
function storeDirs() {
|
|
1427
|
+
const dirs = storeHomes().map((h) => path.join(h, "memory"))
|
|
1428
|
+
if (process.env.GENESEED_MEMORY) dirs.push(process.env.GENESEED_MEMORY)
|
|
1429
|
+
return [...new Set(dirs.flatMap((d) => [path.resolve(d), resolvePath(d)]).map(foldPath))]
|
|
1430
|
+
}
|
|
1431
|
+
// The store files under one home, as `path -> "size:mtime"`: stats, no reads. Twin of
|
|
1432
|
+
// js/hosts/store-watch.mjs `storeScan`; the plugins' copies are held equal by helper_parity.
|
|
1433
|
+
function storeScan(home, found = {}) {
|
|
1434
|
+
const stamp = (f) => {
|
|
1435
|
+
try { const s = statSync(f); if (s.isFile()) found[f] = `${s.size}:${Math.trunc(s.mtimeMs)}` } catch { /* absent */ }
|
|
1436
|
+
}
|
|
1437
|
+
for (const n of ["user-rules.md", "PROFILE.md", "geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]) stamp(path.join(home, n))
|
|
1438
|
+
const walk = (dir) => {
|
|
1439
|
+
let items = []
|
|
1440
|
+
try { items = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
1441
|
+
for (const e of items) {
|
|
1442
|
+
if (e.isDirectory()) { if (e.name !== "archive" && !e.name.startsWith("archived-")) walk(path.join(dir, e.name)) }
|
|
1443
|
+
else if (e.name.endsWith(".md")) stamp(path.join(dir, e.name))
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
walk(path.join(home, "memory"))
|
|
1447
|
+
return found
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// ---- the change report (twin of js/hosts/store-watch.mjs, whose header says why) ---------------
|
|
1451
|
+
// It detects; it prevents nothing. Here the baseline lives in memory, for as long as the plugin does.
|
|
1452
|
+
const scanAllStores = () => storeHomes().reduce((found, h) => storeScan(h, found), {})
|
|
1453
|
+
const ownWrites = () => storeHomes().reduce((log, h) => {
|
|
1454
|
+
try { return { ...log, ...JSON.parse(readFileSync(path.join(h, "memory", ".own-writes.json"), "utf8")) } } catch { return log }
|
|
1455
|
+
}, {})
|
|
1456
|
+
const storeLine = (files) => {
|
|
1457
|
+
const shown = files.slice(0, 5).map((f) => f.split(/[\\/]/).slice(-2).join("/")).join(", ")
|
|
1458
|
+
const more = files.length > 5 ? ` (+${files.length - 5} more)` : ""
|
|
1459
|
+
return `Geneseed change report: ${files.length} rule or memory file${files.length === 1 ? "" : "s"} ` +
|
|
1460
|
+
`changed outside this session's approved writes (another session may have made it): ${shown}${more}. This detects a change; it prevented nothing.`
|
|
1461
|
+
}
|
|
1462
|
+
function noteForStatus(files) {
|
|
1463
|
+
try {
|
|
1464
|
+
if (existsSync(machineDir())) writeFileSync(path.join(machineDir(), ".store-report.json"), JSON.stringify({ at: new Date().toISOString(), host: "opencode", files }))
|
|
1465
|
+
} catch { /* a status line never fails a turn */ }
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// The store a write would land in, or null. `base` is the session's directory: a relative path is
|
|
1469
|
+
// the tool's, never this process's.
|
|
1470
|
+
function ruleStoreTarget(p, base) {
|
|
1471
|
+
const stores = storeDirs()
|
|
1472
|
+
for (const abs of landsOn(p, base)) {
|
|
1473
|
+
const hit = coined(path.basename(abs))
|
|
1474
|
+
if (hit) return hit
|
|
1475
|
+
const t = foldPath(abs)
|
|
1476
|
+
if (nocase(t).endsWith(".md") && stores.some((d) => t.startsWith(`${d}/`))) return "memory"
|
|
1477
|
+
}
|
|
1478
|
+
return null
|
|
1327
1479
|
}
|
|
1480
|
+
// Whether the merged `permission.edit`'s pattern `k` matches `rel`: V1's `Wildcard.match` (1.19.5).
|
|
1481
|
+
const wildMatch = (k, s) => new RegExp(`^${k.replace(/\\/g, "/").replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
1482
|
+
.replace(/\*/g, ".*").replace(/\?/g, ".")}$`, process.platform === "win32" ? "si" : "s").test(s)
|
|
1328
1483
|
|
|
1329
1484
|
// ---- protected checks (External Gate) ------------------------------------------
|
|
1330
1485
|
// Twin of js/hosts/hooks.mjs's `protectedCheck` — keep in step. A project lists the checks its agent
|
|
@@ -1380,6 +1535,7 @@ function gateConfig(p) {
|
|
|
1380
1535
|
for (const target of [path.resolve(p), resolvePath(p)]) {
|
|
1381
1536
|
const t = fold(target)
|
|
1382
1537
|
if (carriers.includes(t)) return true
|
|
1538
|
+
if (fold(path.join(machineDir(), "excludes.json")) === t) return true // the shared exclude list
|
|
1383
1539
|
const dir = path.dirname(target)
|
|
1384
1540
|
if (GATE_CONFIG_MARKERS.some((m) => nocase(m) === nocase(path.basename(dir)))
|
|
1385
1541
|
&& GATE_CONFIG_FILES.some((f) => fold(path.join(dir, f)) === t)) return true
|
|
@@ -1388,6 +1544,149 @@ function gateConfig(p) {
|
|
|
1388
1544
|
return false
|
|
1389
1545
|
}
|
|
1390
1546
|
|
|
1547
|
+
// The files `gateConfig` leaves to OpenCode's native `permission.edit` ask (`opencodeEditAsks` in
|
|
1548
|
+
// js/hosts/settings.mjs). That ask covers edit tools only: a shell command never reaches it, and
|
|
1549
|
+
// this tool hook has no ask tier, so for a SHELL write these are refused. The agent can still
|
|
1550
|
+
// make the edit through an edit tool, where the user gets the prompt. The key shapes are the emit's,
|
|
1551
|
+
// matched as a path tail; tests/plugins/guard.test.mjs walks `opencodeEditAsks`'s own output.
|
|
1552
|
+
// A project `AGENT.md` in a subfolder has no fixed name, so its keys are read back from the
|
|
1553
|
+
// opencode.json the emit wrote beside the install, only when a shell write names a target at all.
|
|
1554
|
+
function agentAskTails(cfg) {
|
|
1555
|
+
const tails = []
|
|
1556
|
+
for (const f of ["opencode.json", "opencode.jsonc"]) {
|
|
1557
|
+
try {
|
|
1558
|
+
const edit = JSON.parse(stripJsonc(readFileSync(path.join(path.dirname(cfg), f), "utf8")))?.permission?.edit
|
|
1559
|
+
for (const k of Object.keys(edit ?? {})) {
|
|
1560
|
+
const tail = k.replace(/^\*(?:\.\.)?\/?/, "")
|
|
1561
|
+
if (/\/AGENT\.md$/i.test(tail)) tails.push(tail)
|
|
1562
|
+
}
|
|
1563
|
+
} catch { /* none, or unreadable: the fixed names below still hold */ }
|
|
1564
|
+
}
|
|
1565
|
+
return tails
|
|
1566
|
+
}
|
|
1567
|
+
function nativeAskFile(p) {
|
|
1568
|
+
try {
|
|
1569
|
+
const cfg = path.dirname(PLUGIN_DIR)
|
|
1570
|
+
const name = path.basename(cfg)
|
|
1571
|
+
const tails = ["opencode.json", "opencode.jsonc", ...[".claude", ".openclaude", ".bob"].flatMap((m) =>
|
|
1572
|
+
[`${m}/settings.json`, `${m}/settings.local.json`]), ".bob/settings/settings.json", ".geneseed/bin/*",
|
|
1573
|
+
...["excludes.json", ".geneseed-manifest.json", ".geneseed-emit", "plugins/*", "plugin/*", "agents/*.md", "agent/*.md",
|
|
1574
|
+
"mode/*.md", "modes/*.md", "tool/*", "tools/*", "AGENT.md", "config.json"]
|
|
1575
|
+
.map((f) => `${name}/${f}`), ...agentAskTails(cfg)]
|
|
1576
|
+
const fold = (s) => nocase(s.replace(/\\/g, "/"))
|
|
1577
|
+
const asked = tails.map((t) => new RegExp(`(?:^|/)${fold(t).replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`))
|
|
1578
|
+
// Its own try: a home that cannot be read costs the shim dir, never the entries above.
|
|
1579
|
+
let bin = null
|
|
1580
|
+
try { bin = fold(path.join(resolvePath(process.env.GENESEED_HOME || "~/.geneseed"), "bin")) } catch { /* no shim dir */ }
|
|
1581
|
+
const agents = [cfg, path.dirname(cfg)].map((d) => fold(path.join(d, "AGENT.md")))
|
|
1582
|
+
for (const target of [path.resolve(p), resolvePath(p)]) {
|
|
1583
|
+
const t = fold(target)
|
|
1584
|
+
if (asked.some((re) => re.test(t)) || agents.includes(t) || (bin && t.startsWith(`${bin}/`))) return true
|
|
1585
|
+
}
|
|
1586
|
+
} catch { /* an unresolvable path is no hit, like `protectedIn` */ }
|
|
1587
|
+
return false
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// ---- shell-write twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js carries everything down
|
|
1591
|
+
// to the END marker verbatim, with `export ` dropped (tests/plugins/guard.test.mjs diffs the two).
|
|
1592
|
+
|
|
1593
|
+
// The cheap prefilter, a superset of what the parse acts on: a `>`, or one of the programs as a word.
|
|
1594
|
+
const SHELL_WRITE_RE = />|(?:^|[\s;&|("'`\\/])(?:tee|sed|cp|mv|rm)(?:\.exe)?(?=[\s;&|)"'`]|$)/im;
|
|
1595
|
+
// One pass over a segment: a quoted run (kept: its `>` is data), or a redirection with its optional
|
|
1596
|
+
// fd, operator, `&` (a dup such as `2>&1`, which writes no file) and target word. `<` forms match
|
|
1597
|
+
// too, so that their words never read as operands. A backslash is no escape here, as in
|
|
1598
|
+
// `SCAN_SPLIT_RE`: `echo "say \"hi > f\""` closes its quote early, reads a target, and asks (on Bob, blocks).
|
|
1599
|
+
const REDIRECT_RE = /"[^"]*"?|'[^']*'?|(?:(?<!\S)\d+|&)?(<<?<?-?|>>?)[ \t]*(&?)((?:[^\s"';|&<>()]|"[^"]*"?|'[^']*'?)*)/g;
|
|
1600
|
+
const SHELL_CD = new Set(['cd', 'pushd', 'chdir', 'set-location', 'sl']);
|
|
1601
|
+
|
|
1602
|
+
/** `t` as an absolute path from `dir`, `~/…` as it stands, or null for what the shell rewrites. */
|
|
1603
|
+
function writePath(dir, t) {
|
|
1604
|
+
if (/[$`*?{}\0]/.test(t) || /^~[^\\/]/.test(t) || /^(?:\/dev\/|nul$)/i.test(t)) return null;
|
|
1605
|
+
if (t[0] === '~') return t;
|
|
1606
|
+
// A Git Bash `/c/…` path, as `resolveIn` reads it.
|
|
1607
|
+
const q = process.platform === 'win32' ? t.replace(/^\/([a-zA-Z])(?=\/|$)/, '$1:') : t;
|
|
1608
|
+
if (path.isAbsolute(q)) return path.resolve(q);
|
|
1609
|
+
return dir ? path.resolve(dir, q) : null;
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
/** The files `sed` edits in place: none without `-i`; else its operands, past the script if inline. */
|
|
1613
|
+
function sedFiles(args) {
|
|
1614
|
+
const ops = [];
|
|
1615
|
+
let inPlace = false; let script = false; let flags = true;
|
|
1616
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
1617
|
+
const a = args[i];
|
|
1618
|
+
if (flags && a === '--') flags = false;
|
|
1619
|
+
else if (flags && /^--in-place(?:=|$)/.test(a)) inPlace = true;
|
|
1620
|
+
else if (flags && (a === '--expression' || a === '--file')) { script = true; i += 1; }
|
|
1621
|
+
else if (flags && /^--(?:expression|file)=/.test(a)) script = true;
|
|
1622
|
+
else if (flags && /^-[a-zA-Z]*i/.test(a)) inPlace = true;
|
|
1623
|
+
else if (flags && /^-[a-zA-Z]*[ef]$/.test(a)) { script = true; i += 1; }
|
|
1624
|
+
else if (!flags || !a.startsWith('-') || a === '-') { if (a) ops.push(a); }
|
|
1625
|
+
}
|
|
1626
|
+
return inPlace ? ops.slice(script ? 0 : 1) : [];
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
/**
|
|
1630
|
+
* The files `command` would write, as absolute paths: redirect targets (`>`, `>>`, `&>`), `tee`
|
|
1631
|
+
* and `rm` operands, `sed -i` files, the destination of `cp` and `mv`, and the sources of `mv`, which
|
|
1632
|
+
* it removes. A destination may be a folder, so `cp a tests/` also names `tests/a`. Read like
|
|
1633
|
+
* `rootScan`: quotes, comments and heredoc bodies are data. A `cd` is followed; one it cannot read
|
|
1634
|
+
* leaves later relative paths unseen. What it cannot read, it leaves out: this reader fails OPEN.
|
|
1635
|
+
*
|
|
1636
|
+
* shortcut: KNOWN UNSEEN FORMS, all of them still a write. An interpreter (inline code,
|
|
1637
|
+
* `bash -c`, `eval`, `xargs`), a script or `npm run`, a `$(…)` or subshell trick, `>|`, a path with a
|
|
1638
|
+
* variable, glob or brace in it, a wrapper with flags (`sudo -u x`) or outside `SCAN_WRAPPERS` (`env rm`,
|
|
1639
|
+
* `nohup rm`, `timeout 5 rm`, `exec rm`), `echo x >& file` (read as a dup), a `popd` (not followed, so
|
|
1640
|
+
* relative paths after a `pushd`/`popd` pair resolve from the wrong folder), `cp -t`, any other writer
|
|
1641
|
+
* (`dd`, `ln`, `install`, `git mv`, `git checkout`, `Set-Content`), and a folder removed above a
|
|
1642
|
+
* listed file (`rm -r tests` when only `tests/a.test.js` is listed). CI running the checks is the
|
|
1643
|
+
* boundary that holds against those.
|
|
1644
|
+
*/
|
|
1645
|
+
function shellWriteTargets(command, cwd) {
|
|
1646
|
+
if (!SHELL_WRITE_RE.test(command)) return [];
|
|
1647
|
+
const found = new Set();
|
|
1648
|
+
let dir = cwd;
|
|
1649
|
+
const add = (t) => { const p = writePath(dir, t); if (p) found.add(p); };
|
|
1650
|
+
const bare = (t) => t.replace(/["']/g, '');
|
|
1651
|
+
for (const seg of scanSegments(command)) {
|
|
1652
|
+
const outs = [];
|
|
1653
|
+
const body = seg.replace(REDIRECT_RE, (m, op, dup, target) => {
|
|
1654
|
+
if (op === undefined) return m;
|
|
1655
|
+
if (op[0] === '>' && !dup && target) outs.push(bare(target));
|
|
1656
|
+
return ' ';
|
|
1657
|
+
});
|
|
1658
|
+
let toks = stripStructure(body.match(SCAN_TOKEN_RE) || []);
|
|
1659
|
+
while (toks.length && (/^\w+=/.test(toks[0]) || SCAN_WRAPPERS.has(bare(toks[0])))) toks = toks.slice(1);
|
|
1660
|
+
const prog = toks.length ? bare(toks[0]).split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') : '';
|
|
1661
|
+
const args = toks.slice(1).map(bare);
|
|
1662
|
+
const dashes = args.indexOf('--');
|
|
1663
|
+
const ops = args.filter((a, i) => a && (a === '-' || !a.startsWith('-') || (dashes >= 0 && i > dashes)));
|
|
1664
|
+
if (SHELL_CD.has(prog)) {
|
|
1665
|
+
const to = ops.find((a) => !/^\/d$/i.test(a));
|
|
1666
|
+
dir = to && to !== '-' ? writePath(dir, to) : null;
|
|
1667
|
+
} else if (prog === 'rm' || prog === 'tee') ops.forEach(add);
|
|
1668
|
+
else if (prog === 'sed') sedFiles(args).forEach(add);
|
|
1669
|
+
else if ((prog === 'cp' || prog === 'mv') && ops.length > 1) {
|
|
1670
|
+
const dest = ops[ops.length - 1];
|
|
1671
|
+
const sources = ops.slice(0, -1);
|
|
1672
|
+
add(dest);
|
|
1673
|
+
for (const s of sources) {
|
|
1674
|
+
add(`${dest.replace(/[\\/]+$/, '')}/${s.split(/[\\/]/).pop()}`);
|
|
1675
|
+
if (prog === 'mv') add(s);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
outs.forEach(add);
|
|
1679
|
+
}
|
|
1680
|
+
return [...found];
|
|
1681
|
+
}
|
|
1682
|
+
// ---- shell-write twin: END
|
|
1683
|
+
|
|
1684
|
+
// A segment that is only a redirect: `> f`, or `A=1 > f`. V2's shell tool asserts only when its parser
|
|
1685
|
+
// finds a command, so no `evaluate` runs for one, and the guard refuses it as it does on V1.
|
|
1686
|
+
const noProgramWord = (command) => scanSegments(command).some((seg) => seg.includes(">")
|
|
1687
|
+
&& !stripStructure(seg.replace(REDIRECT_RE, (m, op) => (op === undefined ? m : " ")).match(SCAN_TOKEN_RE) || [])
|
|
1688
|
+
.some((t) => !/^\w+=/.test(t)))
|
|
1689
|
+
|
|
1391
1690
|
// ---- the ownership first-write gate --------------------------------------------
|
|
1392
1691
|
// Twin of js/hosts/ownership-gate.mjs's `ownershipBlock` — keep in step (same manifests, same
|
|
1393
1692
|
// managed-block strip, same section match, same reason). In an application repo (a git root
|
|
@@ -1457,6 +1756,33 @@ function ownershipBlock(p, sessionID) {
|
|
|
1457
1756
|
// renaming, or deleting a protected note is as destructive as overwriting it. Same
|
|
1458
1757
|
// substring stance: over-matching the class is harmless (see WRITE_TOOLS note).
|
|
1459
1758
|
const WIKI_MUTATE_TOOLS = [...WRITE_TOOLS, "delete", "remove", "rename", "move", "trash"]
|
|
1759
|
+
// The rule-store walk reads EVERY tool the host's prompt does not cover, except a named read set: a
|
|
1760
|
+
// list of writers can only ever be short of the next MCP server (`append`, `put`, `download`). Host
|
|
1761
|
+
// tools by exact name, an MCP tool by a read verb among the words of its name, unless a writer verb
|
|
1762
|
+
// is there too.
|
|
1763
|
+
const HOST_READ_TOOLS = new Set(["read", "grep", "glob", "list", "webfetch", "websearch", "codesearch", "lsp", "skill",
|
|
1764
|
+
"todoread", "todowrite", "task", "subagent", "question", "workflow"])
|
|
1765
|
+
const READ_WORDS = new Set(["read", "get", "list", "search", "find", "grep", "glob", "view", "query", "stat", "describe", "show", "exists"])
|
|
1766
|
+
const readsOnly = (tool) => HOST_READ_TOOLS.has(tool)
|
|
1767
|
+
|| (tool.split(/[^a-z0-9]+/).some((w) => READ_WORDS.has(w))
|
|
1768
|
+
&& !hasAny(tool, [...WIKI_MUTATE_TOOLS, "copy", "append", "put", "download", "update", "set", "sync", "upload"]))
|
|
1769
|
+
// The strings a call carries that name a path, nested ones too: an MCP writer spells its target as it
|
|
1770
|
+
// likes. A string counts by its key, or by a separator with no whitespace, or by a `file:` URL. A title
|
|
1771
|
+
// or a comment that happens to read MEMORY.md is text, and another scheme's URL is not a path here.
|
|
1772
|
+
// Nesting past the bound sets `overflow`: what cannot be read is refused, not passed.
|
|
1773
|
+
const PATH_KEY_RE = /path|file|dest|target|out|dir|ur[il]|where|src|source|^to$|^from$/i
|
|
1774
|
+
const TEXT_KEY_RE = /^(?:title|name|content|text|body|data|description|summary|message|newString|oldString|new_string|old_string|patchText)$/i
|
|
1775
|
+
const ARG_DEPTH = 32
|
|
1776
|
+
function argPaths(v, key = "", out = [], depth = 0) {
|
|
1777
|
+
if (depth > ARG_DEPTH) { out.overflow = true; return out }
|
|
1778
|
+
if (typeof v === "string") {
|
|
1779
|
+
if (!v || v.includes("\n") || TEXT_KEY_RE.test(key)) return out
|
|
1780
|
+
if (/^file:/i.test(v)) { try { out.push(fileURLToPath(v)) } catch { /* no local file */ } }
|
|
1781
|
+
else if (!/^[a-z][a-z0-9+.-]+:\/\//i.test(v) && (PATH_KEY_RE.test(key) || (/[\\/]/.test(v) && !/\s/.test(v)))) out.push(v)
|
|
1782
|
+
} else if (Array.isArray(v)) v.forEach((x) => argPaths(x, key, out, depth + 1))
|
|
1783
|
+
else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) argPaths(x, k, out, depth + 1)
|
|
1784
|
+
return out
|
|
1785
|
+
}
|
|
1460
1786
|
|
|
1461
1787
|
// Usage counting: the same rules as js/hosts/usage.mjs, inline because a plugin cannot import
|
|
1462
1788
|
// from the repo (V2 loads every .js in plugins/ as a plugin). One line per skill or subagent
|
|
@@ -1503,7 +1829,88 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1503
1829
|
return Boolean(meta?.parentID ?? meta?.parentId)
|
|
1504
1830
|
} catch { return false }
|
|
1505
1831
|
}
|
|
1832
|
+
// Whether the host itself will ask the user about this write once this hook lets it run. V2
|
|
1833
|
+
// hands in `hostAsks` once its `evaluate` hook is registered; V1 is read from the merged config,
|
|
1834
|
+
// every source included, and a failed read is no prompt. Read only on a rule-store write.
|
|
1835
|
+
// V1's edit tools ask with `always: ["*"]`, so one "always" approves every edit of this instance
|
|
1836
|
+
// and the rule above stops asking: from then on nothing here can pass to a prompt.
|
|
1837
|
+
// What this can see of an "always": a reply this plugin heard, in this instance, since it loaded.
|
|
1838
|
+
// What it cannot: the hook names no agent, so every agent's ruleset must leave the prompt in place.
|
|
1839
|
+
const editAsks = new Set()
|
|
1840
|
+
let everyEditApproved = false
|
|
1841
|
+
const hostPrompts = async (tool, p, cwd) => {
|
|
1842
|
+
if (!NATIVE_EDIT_TOOLS.has(tool)) return false
|
|
1843
|
+
if (ctx?.hostAsks) return true
|
|
1844
|
+
if (everyEditApproved) return false
|
|
1845
|
+
try {
|
|
1846
|
+
const got = await ctx?.client?.config?.get?.()
|
|
1847
|
+
const edit = (got?.data ?? got)?.permission?.edit
|
|
1848
|
+
if (edit === undefined) return false
|
|
1849
|
+
const rel = path.relative(root(), path.resolve(cwd, p)).replace(/\\/g, "/")
|
|
1850
|
+
if (!editRuleAsks(edit, rel)) return false
|
|
1851
|
+
if (typeof ctx?.client?.app?.agents !== "function") return false
|
|
1852
|
+
const agents = await ctx.client.app.agents()
|
|
1853
|
+
return (agents?.data ?? agents ?? []).every((a) => agentMayAsk(a?.permission, rel))
|
|
1854
|
+
} catch { return false }
|
|
1855
|
+
}
|
|
1856
|
+
// The change report. One baseline per root session, in memory. V2 feeds this hook from its own
|
|
1857
|
+
// events (`setupV2`). `say` reaches the USER: a V1 toast, a V2 synthetic message.
|
|
1858
|
+
const watched = new Map()
|
|
1859
|
+
const say = ctx?.say ?? (async (_sid, line) => {
|
|
1860
|
+
await ctx?.client?.tui?.showToast?.({ body: { title: "Geneseed", message: line, variant: "warning" } })
|
|
1861
|
+
})
|
|
1862
|
+
const unwatched = new Set()
|
|
1863
|
+
const watch = async (sid) => {
|
|
1864
|
+
if (OFF || !sid || watched.has(sid) || unwatched.has(sid)) return
|
|
1865
|
+
if (await sovereignBypass(root()) || await isChildSession(sid)) { unwatched.add(sid); return }
|
|
1866
|
+
watched.set(sid, scanAllStores())
|
|
1867
|
+
}
|
|
1868
|
+
const compare = async (sid) => {
|
|
1869
|
+
const before = watched.get(sid)
|
|
1870
|
+
if (!before) return
|
|
1871
|
+
const now = scanAllStores()
|
|
1872
|
+
watched.set(sid, now)
|
|
1873
|
+
const changed = [...new Set([...Object.keys(before), ...Object.keys(now)])].filter((f) => before[f] !== now[f]).sort()
|
|
1874
|
+
if (!changed.length) return
|
|
1875
|
+
const own = ownWrites()
|
|
1876
|
+
const files = changed.filter((f) => own[f] !== (now[f] ?? "gone"))
|
|
1877
|
+
if (!files.length) return
|
|
1878
|
+
const line = storeLine(files)
|
|
1879
|
+
log(line)
|
|
1880
|
+
noteForStatus(files)
|
|
1881
|
+
await say(sid, line)
|
|
1882
|
+
}
|
|
1506
1883
|
return {
|
|
1884
|
+
// V1's `permission.asked` / `permission.replied` (1.19.5), and the older `permission.updated`
|
|
1885
|
+
// with `permissionID` and `response`. Never throws: an event has no one to catch it.
|
|
1886
|
+
event: async ({ event }) => {
|
|
1887
|
+
try {
|
|
1888
|
+
const e = event?.properties ?? {}
|
|
1889
|
+
if (event?.type === "permission.asked" || event?.type === "permission.updated") {
|
|
1890
|
+
if ((e.permission ?? e.type) === "edit") editAsks.add(e.id)
|
|
1891
|
+
} else if (event?.type === "permission.replied" && (e.reply ?? e.response) === "always"
|
|
1892
|
+
&& editAsks.has(e.requestID ?? e.permissionID)) everyEditApproved = true
|
|
1893
|
+
else if (event?.type === "session.created") await watch(e.info?.id)
|
|
1894
|
+
else if (event?.type === "session.idle") await compare(e.sessionID)
|
|
1895
|
+
} catch (err) { log(`change report error (ignored): ${err?.message ?? err}`) }
|
|
1896
|
+
},
|
|
1897
|
+
// A native edit that ran went past the host's prompt: approved, so its new stamp joins every
|
|
1898
|
+
// baseline here. Only those tools, and only with a session watched.
|
|
1899
|
+
"tool.execute.after": async (input) => {
|
|
1900
|
+
try {
|
|
1901
|
+
const tool = String(input?.tool ?? "").toLowerCase()
|
|
1902
|
+
if (!watched.size || !NATIVE_EDIT_TOOLS.has(tool)) return
|
|
1903
|
+
const cwd = ctx?.directory || process.cwd()
|
|
1904
|
+
for (const raw of pickPath(input?.args ?? {}, cwd)) {
|
|
1905
|
+
if (!ruleStoreTarget(raw, cwd)) continue
|
|
1906
|
+
// Only keys the scan itself names: a link's other spellings would read as files gone.
|
|
1907
|
+
const now = scanAllStores()
|
|
1908
|
+
for (const f of landsOn(raw, cwd)) {
|
|
1909
|
+
for (const base of watched.values()) { if (f in now) base[f] = now[f]; else delete base[f] }
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
} catch (err) { log(`change report error (ignored): ${err?.message ?? err}`) }
|
|
1913
|
+
},
|
|
1507
1914
|
"tool.execute.before": async (input, output) => {
|
|
1508
1915
|
// Bypass before counting, the order Claude's toolGate keeps: an excluded repo is
|
|
1509
1916
|
// dormant, so nothing is written there. GENESEED_GUARD=off still counts — Claude's
|
|
@@ -1511,6 +1918,8 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1511
1918
|
if (await sovereignBypass(root())) return
|
|
1512
1919
|
await recordUse(input?.tool || input?.name, output?.args || input?.args)
|
|
1513
1920
|
if (OFF) return
|
|
1921
|
+
// A session that predates this plugin never sent `session.created`. Once per session.
|
|
1922
|
+
try { await watch(input?.sessionID) } catch { /* the report never decides a tool call */ }
|
|
1514
1923
|
const tool = (input?.tool || input?.name || "").toLowerCase()
|
|
1515
1924
|
const args = output?.args || input?.args || {}
|
|
1516
1925
|
// `rule` is the ledger key, spelled as js/hosts/hooks.mjs spells it (`law-1`,
|
|
@@ -1536,18 +1945,22 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1536
1945
|
// one of them is a write target, so every one runs every gate; the first hit
|
|
1537
1946
|
// blocks the whole call (see `pickPath` for why this is not a single path).
|
|
1538
1947
|
const paths = pickPath(args, cwd)
|
|
1539
|
-
for (const
|
|
1948
|
+
for (const raw of paths) {
|
|
1949
|
+
if (namesStream(raw)) { await deny(`${raw} names an NTFS stream, which writes through to the file it hangs on — name the file itself (External Gate)`, "rigor-5"); return }
|
|
1950
|
+
// Once, here: under `opencode serve` this process's cwd is not the session's directory, and
|
|
1951
|
+
// every gate below resolves a relative path against it.
|
|
1952
|
+
const p = landsOn(raw, cwd)[0].replace(/\\/g, "/")
|
|
1540
1953
|
if (!SECRETS_GATE_OFF && SECRET_RE.some((re) => re.test(p))) { await deny(`write to secret/key file ${p} (Sealed Secrets)`, "law-1"); return }
|
|
1541
1954
|
if (SECRET_WARN_RE.some((re) => re.test(p))) log(`WARN: writing ${p} — keep secrets out of tracked files (Sealed Secrets)`)
|
|
1542
1955
|
const sensor = protectedCheck(p)
|
|
1543
1956
|
if (sensor) { await deny(`${p} is a protected check (${sensor === DONE_LIST ? "the done gate list itself" : `${sensor}, listed in ${SENSOR_LIST}`}) — a check the agent can edit is not a check (External Gate)`, "rigor-5"); return }
|
|
1544
1957
|
if (gateConfig(p)) { await deny(`${p} ${GATE_CONFIG_ASK} (External Gate)`, "rigor-5"); return }
|
|
1545
|
-
|
|
1546
|
-
if (
|
|
1547
|
-
|
|
1548
|
-
|
|
1958
|
+
// V1 after an "always": the `permission.edit` ask on these files is gone too.
|
|
1959
|
+
if (everyEditApproved && !ctx?.hostAsks && nativeAskFile(p)) { await deny(`${p} ${GATE_CONFIG_ASK} (External Gate)`, "rigor-5"); return }
|
|
1960
|
+
const store = ruleStoreTarget(raw, cwd)
|
|
1961
|
+
if (store && !(await hostPrompts(tool, raw, cwd))) {
|
|
1549
1962
|
await deny(`writing to ${store} — a standing rule, or a fact to remember? That ` +
|
|
1550
|
-
`choice is the user's (Persist Insight). ${
|
|
1963
|
+
`choice is the user's (Persist Insight). ${NATIVE_EDIT_TOOLS.has(tool) ? PERSIST_NO_PROMPT : PERSIST_EDIT_TOOL}`, "process-1")
|
|
1551
1964
|
return
|
|
1552
1965
|
}
|
|
1553
1966
|
}
|
|
@@ -1572,9 +1985,23 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1572
1985
|
}
|
|
1573
1986
|
}
|
|
1574
1987
|
}
|
|
1988
|
+
// Any tool the host's prompt does not cover, whatever it calls its arguments. `pickCommand`,
|
|
1989
|
+
// because SHELL_TOOLS is a substring class: `mcp_prune_write` holds "run".
|
|
1990
|
+
if (!NATIVE_EDIT_TOOLS.has(tool) && !readsOnly(tool) && !(hasAny(tool, SHELL_TOOLS) && pickCommand(args))) {
|
|
1991
|
+
const named = argPaths(args)
|
|
1992
|
+
if (named.overflow) { await deny(`${tool}'s arguments nest too deep to read, so a rule or memory write cannot be ruled out (Persist Insight)`, "process-1"); return }
|
|
1993
|
+
for (const v of named) {
|
|
1994
|
+
const store = ruleStoreTarget(v, cwd)
|
|
1995
|
+
if (store) {
|
|
1996
|
+
await deny(`writing to ${store} through ${tool} — a standing rule, or a fact to remember? That ` +
|
|
1997
|
+
`choice is the user's (Persist Insight). ${PERSIST_EDIT_TOOL}`, "process-1")
|
|
1998
|
+
return
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
1575
2002
|
if (hasAny(tool, WIKI_MUTATE_TOOLS)) {
|
|
1576
2003
|
for (const p of pickPath(args, cwd)) {
|
|
1577
|
-
const abs = (
|
|
2004
|
+
const abs = landsOn(p, cwd)[0].replace(/\\/g, "/").toLowerCase()
|
|
1578
2005
|
const hit = (await protectedPrefixes()).find(
|
|
1579
2006
|
(x) => abs.startsWith(x.prefix) || abs === x.prefix.slice(0, -1))
|
|
1580
2007
|
if (hit) { await deny(`mutation in protected wiki folder — ${hit.label} (AGENT.md §8)`, "wiki"); return }
|
|
@@ -1583,6 +2010,8 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1583
2010
|
// NOT else-if: a compound tool name (e.g. exec_and_save) can match both
|
|
1584
2011
|
// classes, and the shell check must still run after the write check.
|
|
1585
2012
|
if (hasAny(tool, SHELL_TOOLS)) {
|
|
2013
|
+
// OpenCode's bash tool may run in `workdir`, resolved against the session directory.
|
|
2014
|
+
const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
|
|
1586
2015
|
const c = pickCommand(args)
|
|
1587
2016
|
const cut = (t) => scanSegments(t).map((seg) => seg.match(SCAN_TOKEN_RE) || [])
|
|
1588
2017
|
if (c && (SHELL_BLOCK_RE.some((re) => re.test(c)) || catastrophic(c, cut))) { await deny(`catastrophic command (Deletion Is Deliberate): ${c.slice(0, 80)}`, "law-4"); return }
|
|
@@ -1593,11 +2022,25 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1593
2022
|
return
|
|
1594
2023
|
}
|
|
1595
2024
|
if (c && !DELETION_GATE_OFF && LOSS_CANDIDATE_RE.test(c)) {
|
|
1596
|
-
// OpenCode's bash tool may run in `workdir`, resolved against the session directory.
|
|
1597
|
-
const wd = typeof args.workdir === "string" && args.workdir ? path.resolve(cwd, args.workdir) : cwd
|
|
1598
2025
|
const loss = lossReason(cut(c), wd, { always: false, split: cut })
|
|
1599
2026
|
if (loss) { await deny(`${loss} (Deletion Is Deliberate) — confirm with the user first`, "law-4"); return }
|
|
1600
2027
|
}
|
|
2028
|
+
// External Gate over a shell write: the same paths as a write tool, no content scan. A
|
|
2029
|
+
// throw fails open through the catch below, as the twin's `shellWriteReason` does.
|
|
2030
|
+
for (const p of c ? shellWriteTargets(c, wd) : []) {
|
|
2031
|
+
const sensor = protectedCheck(p)
|
|
2032
|
+
if (sensor) { await deny(`${p} is a protected check (${sensor === DONE_LIST ? "the done gate list itself" : `${sensor}, listed in ${SENSOR_LIST}`}) — a check the agent can edit is not a check (External Gate)`, "rigor-5"); return }
|
|
2033
|
+
if (gateConfig(p) || nativeAskFile(p)) { await deny(`${p} ${GATE_CONFIG_ASK} (External Gate)`, "rigor-5"); return }
|
|
2034
|
+
// A parsed form that lands in a store. V2 can ask: `evaluate` runs for the shell tool's own
|
|
2035
|
+
// `permission.assert`, so the call is marked by its id and the host prompts. V1 cannot.
|
|
2036
|
+
const store = ruleStoreTarget(p, wd)
|
|
2037
|
+
if (store && ctx?.shellAsks && input?.callID && !noProgramWord(c)) { ctx.shellAsks.add(input.callID); continue }
|
|
2038
|
+
if (store) {
|
|
2039
|
+
await deny(`writing to ${store} through a shell command — a standing rule, or a fact to ` +
|
|
2040
|
+
`remember? That choice is the user's (Persist Insight). ${PERSIST_EDIT_TOOL}`, "process-1")
|
|
2041
|
+
return
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
1601
2044
|
}
|
|
1602
2045
|
} catch (err) {
|
|
1603
2046
|
// Our own deny must propagate; any inspection error must never break a tool call.
|
|
@@ -1621,25 +2064,86 @@ export const GeneseedGuard = async (ctx) => {
|
|
|
1621
2064
|
// original tool whatever the event's name says; every tool this guard gates requires
|
|
1622
2065
|
// arguments, so `{}` fails validation there before anything executes.
|
|
1623
2066
|
//
|
|
1624
|
-
//
|
|
1625
|
-
// resource list (the shell tool's is per sub-command), not the full input the content
|
|
1626
|
-
//
|
|
2067
|
+
// A deny stays here, not in `permission.hook("evaluate")`: that hook sees only the action and a
|
|
2068
|
+
// resource list (the shell tool's is per sub-command), not the full input the content scan and
|
|
2069
|
+
// the patch-path gates need. Its use is the ask this hook has no tier for. It runs after the
|
|
2070
|
+
// configured and saved rules, and for `edit` and `patch` a resource is relative to
|
|
2071
|
+
// `location.directory` or absolute, so a rule-store write becomes a real prompt whatever the config
|
|
2072
|
+
// and any saved "always" say (core/src/permission.ts, 2.2.5). A configured deny never reaches it,
|
|
2073
|
+
// and an unattended session turns the ask into a deny. A V2 without the domain has no `hostAsks`,
|
|
2074
|
+
// so the guard refuses those writes.
|
|
2075
|
+
async function askOnRuleStore(ctx, shellAsks) {
|
|
2076
|
+
const dir = ctx?.location?.directory || process.cwd()
|
|
2077
|
+
try {
|
|
2078
|
+
await ctx.permission.hook("evaluate", async (event) => {
|
|
2079
|
+
try {
|
|
2080
|
+
if (OFF || event.effect === "deny") return
|
|
2081
|
+
if (event.action === "shell") {
|
|
2082
|
+
// The shell tool's assert: action `shell`, one resource per parsed command, `source.id` the
|
|
2083
|
+
// call the tool hook marked. A command the host's parser finds no command in asserts nothing.
|
|
2084
|
+
if (!shellAsks.delete(event.source?.id)) return
|
|
2085
|
+
if (WARN_ONLY) { log("WARN (would ask): a shell write to a rule or memory file (Persist Insight)"); return }
|
|
2086
|
+
event.effect = "ask"
|
|
2087
|
+
event.message = "Geneseed (Persist Insight): this command writes a rule or memory file. A standing rule, or a fact to remember? That choice is yours."
|
|
2088
|
+
return
|
|
2089
|
+
}
|
|
2090
|
+
if (event.action !== "edit") return
|
|
2091
|
+
const store = event.resources.map((r) => ruleStoreTarget(r, dir)).find(Boolean)
|
|
2092
|
+
// The gate's own files have a static ask a saved "always" can outvote, so they are raised too.
|
|
2093
|
+
const gate = !store && event.resources.some((r) => nativeAskFile(path.resolve(dir, r)))
|
|
2094
|
+
if ((!store && !gate) || await sovereignBypass(ctx?.location?.project?.directory || dir)) return
|
|
2095
|
+
if (WARN_ONLY) { log(`WARN (would ask): writing to ${store || "a gate's configuration"} (Persist Insight)`); return }
|
|
2096
|
+
event.effect = "ask"
|
|
2097
|
+
event.message = store ? `Geneseed (Persist Insight): writing to ${store}. A standing rule, or a fact to remember? That choice is yours.`
|
|
2098
|
+
: "Geneseed (External Gate): this file is a gate's own configuration. Editing it could switch a check off."
|
|
2099
|
+
} catch {
|
|
2100
|
+
// An event this hook cannot read is asked about. A V2 callback never throws.
|
|
2101
|
+
try { if (event?.action === "edit") event.effect = "ask" } catch { /* a frozen event: the static key still asks */ }
|
|
2102
|
+
}
|
|
2103
|
+
})
|
|
2104
|
+
return true
|
|
2105
|
+
} catch { return false }
|
|
2106
|
+
}
|
|
2107
|
+
|
|
1627
2108
|
async function setupV2(ctx) {
|
|
2109
|
+
const shellAsks = new Set()
|
|
2110
|
+
const hostAsks = await askOnRuleStore(ctx, shellAsks)
|
|
1628
2111
|
const hooks = await GeneseedGuard({
|
|
1629
2112
|
worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory,
|
|
1630
2113
|
sessionMeta: (sessionID) => ctx.session.get({ sessionID }),
|
|
2114
|
+
hostAsks, shellAsks: hostAsks ? shellAsks : null,
|
|
2115
|
+
say: (sessionID, text) => ctx.session.synthetic({ sessionID, text, description: "Geneseed change report", resume: false }),
|
|
1631
2116
|
})
|
|
2117
|
+
const report = (type, properties) => hooks.event({ event: { type, properties } })
|
|
2118
|
+
// V2's turn edges, as geneseed-notify reads them. `say` above is the only way out to the user.
|
|
2119
|
+
const controller = new AbortController()
|
|
2120
|
+
try {
|
|
2121
|
+
await ctx.tool.hook("execute.after", async (event) => {
|
|
2122
|
+
if (event?.status === "completed") await hooks["tool.execute.after"]({ tool: event.tool, args: event.input })
|
|
2123
|
+
})
|
|
2124
|
+
if (ctx?.event?.subscribe) {
|
|
2125
|
+
void (async () => {
|
|
2126
|
+
for await (const ev of ctx.event.subscribe({ signal: controller.signal })) {
|
|
2127
|
+
const sessionID = ev?.data?.sessionID
|
|
2128
|
+
if (ev?.type === "session.execution.started") await report("session.created", { info: { id: sessionID } })
|
|
2129
|
+
else if (/^session\.execution\.(?:succeeded|failed|interrupted)$/.test(ev?.type ?? "")) await report("session.idle", { sessionID })
|
|
2130
|
+
}
|
|
2131
|
+
})().catch((err) => log(`change report stream ended: ${err?.message ?? err}`))
|
|
2132
|
+
}
|
|
2133
|
+
} catch (err) { log(`change report not wired: ${err?.message ?? err}`) }
|
|
1632
2134
|
await ctx.tool.hook("execute.before", async (event) => {
|
|
1633
2135
|
try {
|
|
1634
2136
|
// `sessionID` rides on every V2 execute.before event (@opencode/plugin 2.1.4 `ToolHooks`).
|
|
1635
|
-
await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID }, { args: event.input })
|
|
2137
|
+
await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID, callID: event.id }, { args: event.input })
|
|
1636
2138
|
} catch (err) {
|
|
1637
2139
|
const why = String(err?.message || "")
|
|
1638
2140
|
if (!why.startsWith("[geneseed-guard]")) return
|
|
1639
|
-
|
|
2141
|
+
// Core prints `No tool named "<this>"`, so the name must say first that nothing is missing.
|
|
2142
|
+
event.tool = `BLOCKED, not a missing tool: ${why}`
|
|
1640
2143
|
event.input = {}
|
|
1641
2144
|
}
|
|
1642
2145
|
})
|
|
2146
|
+
return () => controller.abort()
|
|
1643
2147
|
}
|
|
1644
2148
|
|
|
1645
2149
|
export default { id: "geneseed-guard", server: GeneseedGuard, setup: setupV2 }
|