lean-agent-harness 1.3.1 → 1.4.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 CHANGED
@@ -4,6 +4,22 @@ All notable changes to this project are documented here. Format based on [Keep a
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.4.0] - 2026-11-04
8
+
9
+ ### Added
10
+
11
+ - A divergent user `AGENTS.md`/`CLAUDE.md` is now merged instead of only backed up: the original is still saved as `.bak` (`.bak.1`, ...), and its rules survive in the agent's context as a `## Project Rules` section delimited by `lah:project-rules` comments. Reinstalls over a merged file are a no-op; payload upgrades replace only the harness part and keep the section. Files the harness itself deployed (the `lean-agent-harness` marker or the 1.x signature lines — `Single source of truth for all coding agents`, `# Claude Code Project Configuration`) are replaced without absorbing the old harness text. The affected `manifest.tsv` rows carry the new `merge` mode, and installer parity now runs the merge through both installers.
12
+
13
+ ## [1.3.2] - 2026-10-31
14
+
15
+ ### Added
16
+
17
+ - OpenCode guard: `--global --guard` also merges permission rules into `~/.config/opencode/opencode.json`, generated from `guard/policy.json`: secret files denied for `read` and `edit` (`.env.example` allowed), destructive commands set to `ask` with the flag before or after other arguments. Your own rules are kept; ours are moved last because OpenCode applies the last matching rule. A previous file is saved as `.bak`, a second run changes nothing, and an `opencode.json` that is not a JSON object is never touched. Follows the documented format; not yet run against a live OpenCode.
18
+
19
+ ### Changed
20
+
21
+ - The read, validate and backup logic for user JSON files moved to `guard/json-config.js`, shared by the Claude Code and OpenCode merges.
22
+
7
23
  ## [1.3.1] - 2026-10-31
8
24
 
9
25
  ### Fixed
package/CLAUDE.md CHANGED
@@ -1,3 +1,4 @@
1
+ <!-- Managed by lean-agent-harness. -->
1
2
  # Claude Code Project Configuration
2
3
 
3
4
  Single source of truth is defined in `AGENTS.md`. All directives, subagents, skills, and lifecycle commands apply here.
package/GLOSSARY.md CHANGED
@@ -14,7 +14,8 @@ Single source of truth for the domain vocabulary of this project. Both human eng
14
14
  | **Target** | One deployment destination with its native layout. `agents` is the cross-tool `.agents/skills` location read by Pi, OpenCode, Codex, Copilot and Cursor; `claude` uses `.claude/skills`. | `target` column of `manifest.tsv` | Declared only in `manifest.tsv`; both installers read it. |
15
15
  | **Manifest** | Tab-separated table mapping package sources to destinations per scope (local/global). | `manifest.tsv` | Single source for `bin/cli.js` and `install.sh`; `test/cli.test.js` asserts identical output trees. |
16
16
  | **Adapter** | A static file that bridges one agent's native mechanism to a skill (OpenCode command stubs). | `adapters/` | Contains no rules, only a pointer to the skill. |
17
- | **Instruction Stub** | A file that makes an agent read the shared rules (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`). | `file` rows in `manifest.tsv` | Content must derive from the package `AGENTS.md`; installed once per scope where the agent reads `AGENTS.md` natively; user customizations are kept as `.bak`, or the next free `.bak.N`, on overwrite; an existing backup is never overwritten. |
17
+ | **Instruction Stub** | A file that makes an agent read the shared rules (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`). | `file` rows in `manifest.tsv` | Content must derive from the package `AGENTS.md`; installed once per scope where the agent reads `AGENTS.md` natively; user customizations are kept as `.bak`, or the next free `.bak.N`, and in `merge` mode also survive in context as the Project Rules Section; an existing backup is never overwritten. |
18
+ | **Project Rules Section** | The `## Project Rules` block, delimited by `lah:project-rules:start`/`:end` comments, that a `merge`-mode instruction file appends to hold the rules of the user's previous file. | Delimited block at the end of a deployed Instruction Stub | Preserved verbatim across reinstalls and payload upgrades; a file the harness itself deployed (identity marker or the 1.x signature lines) is replaced bare and never absorbed into it. |
18
19
  | **ODD (Organic Driven Development)** | Decomposition style: complex work becomes small, feature-complete, reviewable milestone slices chained across PRs. | `plan-flow` output in `.tasks/current.md` | A slice must satisfy its DoD before the next starts. |
19
20
  | **Slice** | One feature-complete ODD unit (e.g., migration + model + service + tests). | `- [ ] Slice N:` checklist item | No fragmented single-line micro-slices. |
20
21
  | **DoD (Definition of Done)** | Verification gate: 0 linter/compiler errors, passing tests with cited terminal output, no debug residue, glossary-aligned naming, isolated `git status`. | `orchestrate` skill DoD; `commit` skill step 1 | Evidence without raw terminal output is invalid. |
@@ -29,9 +30,10 @@ Single source of truth for the domain vocabulary of this project. Both human eng
29
30
  | **Seed Glossary** | Minimal domain-glossary template deployed to client projects when they have none. | `templates/GLOSSARY.md` | At most 1500 bytes (token budget test); never overwrites an existing `GLOSSARY.md`. |
30
31
  | **Source Override** | Testability hook: installers use `LAH_SOURCE` (shell) or `LAH_FAKE_HOME`/`LAH_FAKE_CWD` (CLI exports) in tests. | `install.sh`, `bin/cli.js` | Must never alter default behavior when unset. |
31
32
  | **Pinned Download** | A `curl` install fixed to a release and verified: `LAH_VERSION` selects the tag `vX.Y.Z` (default: the branch), `LAH_SHA256` makes `install.sh` abort before deploying when the archive differs, `LAH_ARCHIVE_URL` replaces the download URL (mirrors, tests). | `install.sh` | Without `LAH_SHA256` the archive is installed unverified and the installer says so. GitHub archives are not guaranteed byte-stable: recompute a stale checksum from a trusted copy before assuming tampering. |
32
- | **Guard** | Opt-in enforcement of the `AGENTS.md` Hard Rules that a tool can check mechanically (secret files, destructive commands): a Claude Code `PreToolUse` hook, a Pi extension and Codex command rules. Deployed only by `--global --guard`. | `guard/`, `global-guard` rows in `manifest.tsv` | Executes code inside the agent, so it is never on by default and never project-local (Pi loads project extensions only after the project is trusted). Best effort, not a sandbox: it does not see commands built through an interpreter. |
33
+ | **Guard** | Opt-in enforcement of the `AGENTS.md` Hard Rules that a tool can check mechanically (secret files, destructive commands): a Claude Code `PreToolUse` hook, OpenCode permission rules, a Pi extension and Codex command rules. Deployed only by `--global --guard`. | `guard/`, `global-guard` rows in `manifest.tsv` | Executes code inside the agent, so it is never on by default and never project-local (Pi loads project extensions only after the project is trusted). Best effort, not a sandbox: it does not see commands built through an interpreter. |
33
34
  | **Guard Policy** | The single list of protected secret files and destructive commands, each with a decision: `ask` (human confirms; blocked when nobody can answer) or `deny`. | `guard/policy.json` | Every guard artifact is generated from it by `guard/build.js` (including the `core.js` matcher copied beside the Pi and Claude Code guards); a test fails when a committed artifact drifts. |
34
35
  | **Guard Matcher** | The shared logic that decides whether a path is a secret and which shell rule a command hits, built from the Guard Policy. Names, directories and the executable (`/bin/CAT` is `cat`) compare case-insensitively (the default macOS and Windows file systems open `.ENV` as `.env`), and brace patterns (`*.{env,pem}`) are expanded. | `guard/core.js` | One source, copied by `guard/build.js` beside each guard because each deploys on its own. |
36
+ | **OpenCode Permission** | A manifest row of kind `opencode-permission`: merges the rules generated from the Guard Policy into the `permission` of `~/.config/opencode/opencode.json`. | `manifest.tsv`, `guard/opencode/permission.json`, `guard/opencode/merge-permission.js` | OpenCode applies the last matching rule, so each pattern is moved to the end and replaces a user rule with the same pattern; a text value (`"allow"`) is kept as `{"*": "allow"}`. Same backup and invalid-JSON rules as the Settings Hook (`guard/json-config.js`). |
35
37
  | **Settings Hook** | A manifest row of kind `settings-hook`: registers the Claude Code guard hook in `~/.claude/settings.json` by merge instead of copying a file. | `manifest.tsv`, `guard/claude/hook.json`, `guard/claude/merge-settings.js` | Idempotent. Keeps every other key, saves the previous file as `.bak` (or `.bak.N`) when it changes, and never touches a `settings.json` that is not valid JSON. |
36
38
 
37
39
  ---
package/README.md CHANGED
@@ -41,12 +41,12 @@ curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/ins
41
41
  curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/install.sh | bash -s -- --global --auto
42
42
  ```
43
43
 
44
- `install.sh` accepts `--global`, `--local`, `--all`, `--auto`, `--profile core|full`, auto-detects existing environments and never blocks without a TTY. An existing `AGENTS.md`/`CLAUDE.md` that differs is saved as `.bak` before it is replaced; if a `.bak` already exists, the next one is `.bak.1`, `.bak.2`, and so on, so no version is lost. An existing `GLOSSARY.md` is never touched; a missing one is seeded from `templates/GLOSSARY.md`.
44
+ `install.sh` accepts `--global`, `--local`, `--all`, `--auto`, `--profile core|full`, auto-detects existing environments and never blocks without a TTY. An existing `AGENTS.md`/`CLAUDE.md` that differs is never lost: the original is saved as `.bak` (then `.bak.1`, `.bak.2`, ...), and its rules are merged into the deployed file under a `## Project Rules` section delimited by `lah:project-rules` comments, so they stay in the agent's context. Reinstalls change nothing over a merged file; upgrades replace only the harness part and keep the section. A file the harness itself deployed (the `lean-agent-harness` marker, the 1.x `Single source of truth` line or the 1.x `# Claude Code Project Configuration` heading) is replaced without absorbing the old harness text. An existing `GLOSSARY.md` is never touched; a missing one is seeded from `templates/GLOSSARY.md`.
45
45
 
46
46
  **Pinning and verifying the `curl` install.** The one-liner runs the `main` branch unless you pin it:
47
47
 
48
48
  ```bash
49
- curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/install.sh | LAH_VERSION=1.3.1 LAH_SHA256=<sha256-of-the-archive> bash -s -- --global --auto
49
+ curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/install.sh | LAH_VERSION=1.4.0 LAH_SHA256=<sha256-of-the-archive> bash -s -- --global --auto
50
50
  ```
51
51
 
52
52
  `LAH_VERSION` downloads that release tag. `LAH_SHA256` makes the installer abort, before deploying anything, if the archive does not match. Without it the installer says that the checksum is not verified. GitHub does not publish archive checksums, so compute the value once from a copy you trust, for example `shasum -a 256` on the archive of that tag. GitHub's generated archives are not guaranteed to stay byte-identical over time, so if a previously valid checksum stops matching, recompute it from a trusted copy before assuming tampering.
@@ -57,7 +57,7 @@ curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/ins
57
57
  npx lean-agent-harness --global --profile core
58
58
  ```
59
59
 
60
- **Guard (opt-in).** `AGENTS.md` is advice the model may ignore. `--global --guard` adds enforcement where the tool supports it, all generated from `guard/policy.json`: a `PreToolUse` hook for Claude Code (registered in `~/.claude/settings.json` by merge, with a `.bak` of the previous file), an extension for Pi and command rules for Codex. Secret files (`.env*`, `*.pem`, `*.key`, `.ssh/`) are denied; `rm -r`, `git reset --hard`, `git push --force` and `sudo` ask first. Best effort, not a sandbox: commands built through an interpreter (`python -c`) are not seen, and a `Grep` aimed at a whole directory can still reach a secret file inside it. Cursor, OpenCode, Copilot and CommandCode have no guard. `install.sh --guard` needs `node`.
60
+ **Guard (opt-in).** `AGENTS.md` is advice the model may ignore. `--global --guard` adds enforcement where the tool supports it, all generated from `guard/policy.json`: a `PreToolUse` hook for Claude Code (registered in `~/.claude/settings.json` by merge, with a `.bak` of the previous file), permission rules for OpenCode (merged into `~/.config/opencode/opencode.json`, your own rules kept), an extension for Pi and command rules for Codex. Secret files (`.env*`, `*.pem`, `*.key`, `.ssh/`) are denied; `rm -r`, `git reset --hard`, `git push --force` and `sudo` ask first. Best effort, not a sandbox: commands built through an interpreter (`python -c`) are not seen, and a `Grep` aimed at a whole directory can still reach a secret file inside it. The OpenCode rules follow its documented permission format but have not been run against a live OpenCode. Cursor, Copilot and CommandCode have no guard. `install.sh --guard` needs `node`.
61
61
 
62
62
  ```bash
63
63
  npx lean-agent-harness --global --guard
package/bin/cli.js CHANGED
@@ -20,16 +20,21 @@ const path = require("path");
20
20
 
21
21
  const { version } = require("../package.json");
22
22
  const { mergeHook } = require("../guard/claude/merge-settings.js");
23
+ const { mergePermission } = require("../guard/opencode/merge-permission.js");
23
24
 
24
25
  const PKG_ROOT = path.resolve(__dirname, "..");
25
26
 
26
27
  /**
27
28
  * @typedef {Object} Entry
28
- * @property {"file"|"dir"|"settings-hook"} kind file = instruction file (.bak on divergence); dir = mirrored directory;
29
- * settings-hook = merge a hook into a Claude Code settings.json
29
+ * @property {"file"|"dir"|"settings-hook"|"opencode-permission"} kind
30
+ * file = instruction file (.bak on divergence); dir = mirrored directory;
31
+ * settings-hook = merge a hook into a Claude Code settings.json;
32
+ * opencode-permission = merge permission rules into an OpenCode opencode.json
30
33
  * @property {string} src Path relative to the package root
31
34
  * @property {string} dest Path relative to the target base
32
- * @property {string} mode "" or "if-missing" (file kind: never overwrite an existing dest)
35
+ * @property {string} mode "" | "if-missing" (file kind: never overwrite an existing dest)
36
+ * | "merge" (file kind: back up a divergent dest and merge its rules into the
37
+ * deployed file as a "Project Rules" section)
33
38
  *
34
39
  * @typedef {Object} Target
35
40
  * @property {string} name Human-readable label
@@ -48,6 +53,7 @@ const LABELS = {
48
53
  commandcode: "CommandCode",
49
54
  "pi-guard": "Pi guard",
50
55
  "claude-guard": "Claude Code guard",
56
+ "opencode-guard": "OpenCode guard",
51
57
  "codex-guard": "Codex guard",
52
58
  };
53
59
 
@@ -158,10 +164,40 @@ function backupPath(destPath) {
158
164
  return candidate;
159
165
  }
160
166
 
167
+ /** Merge mode: markers delimiting the user's rules inside a deployed instruction file. */
168
+ const MERGE_START = "<!-- lah:project-rules:start -->";
169
+ const MERGE_END = "<!-- lah:project-rules:end -->";
170
+ const MERGE_HEADING = "## Project Rules\n\n";
171
+ /** Strings identifying a file the harness itself deployed (any version): replaced bare, never absorbed. */
172
+ const HARNESS_MARKS = [
173
+ "lean-agent-harness",
174
+ "Single source of truth for all coding agents",
175
+ "# Claude Code Project Configuration",
176
+ ];
177
+
161
178
  /**
162
- * Write an instruction file. If the destination exists and differs from the
163
- * package payload, the user's file is preserved as "<name>.bak" (or the next free
164
- * "<name>.bak.N") first. With mode "if-missing" an existing destination is left untouched (seed files).
179
+ * The user's section inside a managed instruction file (between the markers, trimmed),
180
+ * or null when the file carries no markers.
181
+ * @param {string} text
182
+ * @returns {string | null}
183
+ */
184
+ function sectionOf(text) {
185
+ const at = text.indexOf(MERGE_START);
186
+ if (at === -1) return null;
187
+ let body = text.slice(at + MERGE_START.length);
188
+ const end = body.indexOf(MERGE_END);
189
+ if (end !== -1) body = body.slice(0, end);
190
+ return body.trim();
191
+ }
192
+
193
+ /**
194
+ * Write an instruction file. A destination that differs from the package payload is
195
+ * preserved as "<name>.bak" (or the next free "<name>.bak.N") first. With mode
196
+ * "if-missing" an existing destination is left untouched (seed files). With mode
197
+ * "merge" the divergent destination's rules also survive in context: a user file is
198
+ * merged as a "Project Rules" section, a managed file keeps its section across
199
+ * payload upgrades, and a file the harness itself deployed is replaced bare.
200
+ * Writing a byte-identical result is a no-op, so reinstalling is stable.
165
201
  *
166
202
  * @param {string} srcPath
167
203
  * @param {string} destPath
@@ -169,18 +205,32 @@ function backupPath(destPath) {
169
205
  */
170
206
  function writeInstruction(srcPath, destPath, mode = "") {
171
207
  if (mode === "if-missing" && fs.existsSync(destPath)) return;
208
+ const payload = fs.readFileSync(srcPath, "utf8");
172
209
  fs.mkdirSync(path.dirname(destPath), { recursive: true });
210
+ let current = null;
173
211
  try {
174
- const current = fs.readFileSync(destPath, "utf8");
175
- if (current !== fs.readFileSync(srcPath, "utf8")) {
176
- fs.copyFileSync(destPath, backupPath(destPath));
177
- }
212
+ current = fs.readFileSync(destPath, "utf8");
178
213
  } catch (err) {
179
214
  if (err.code !== "ENOENT") {
180
215
  throw err;
181
216
  }
182
217
  }
183
- fs.copyFileSync(srcPath, destPath);
218
+ if (current === null) {
219
+ fs.copyFileSync(srcPath, destPath);
220
+ return;
221
+ }
222
+ if (current === payload) return;
223
+ let next = null;
224
+ if (mode === "merge") {
225
+ const marked = sectionOf(current);
226
+ const userRules = marked === null && !HARNESS_MARKS.some((m) => current.includes(m)) ? current.trim() : "";
227
+ const body = marked ?? (userRules ? MERGE_HEADING + userRules : "");
228
+ next = body ? `${payload.replace(/\s+$/, "")}\n\n${MERGE_START}\n${body}\n${MERGE_END}\n` : payload;
229
+ }
230
+ if (next !== null && next === current) return;
231
+ fs.copyFileSync(destPath, backupPath(destPath));
232
+ if (next !== null) fs.writeFileSync(destPath, next);
233
+ else fs.copyFileSync(srcPath, destPath);
184
234
  }
185
235
 
186
236
  /**
@@ -195,6 +245,7 @@ function deployTarget(t, exclude = new Set()) {
195
245
  const to = path.join(t.base, dest);
196
246
  if (kind === "file") writeInstruction(from, to, mode);
197
247
  else if (kind === "settings-hook") mergeHook(from, to);
248
+ else if (kind === "opencode-permission") mergePermission(from, to);
198
249
  else copyDir(from, to, src === "skills" ? exclude : new Set());
199
250
  }
200
251
  const label = t.base.replace(process.env.LAH_FAKE_HOME || os.homedir(), "~");
@@ -242,7 +293,7 @@ Flags:
242
293
  -l, --local Desplegar en el proyecto actual (comportamiento por defecto)
243
294
  -g, --global Desplegar en carpetas de usuario (~/)
244
295
  --profile <p> core = sin skills extra (ver profile-extras.txt) | full (por defecto)
245
- --guard Con --global: instala el guard (hook de Claude Code, extensión de Pi y reglas de Codex) que bloquea
296
+ --guard Con --global: instala el guard (hook de Claude Code, permisos de OpenCode, extensión de Pi y reglas de Codex) que bloquea
246
297
  secretos y comandos destructivos. Ejecuta código en el agente: es opt-in
247
298
  -h, --help Mostrar esta ayuda
248
299
  -v, --version Mostrar versión
@@ -5,45 +5,12 @@
5
5
  * Registers the lah guard hook in a Claude Code settings.json without touching anything else.
6
6
  * Used by bin/cli.js (require) and install.sh (`node merge-settings.js <hook.json> <settings.json>`).
7
7
  *
8
- * A settings.json that is not valid JSON, or whose `hooks` have an unexpected shape, is never
9
- * modified. When the file changes, the previous one is kept as "<name>.bak" (or the next free .bak.N).
8
+ * A settings.json whose `hooks` have an unexpected shape is never modified (see json-config.js for
9
+ * the invalid-JSON and backup rules).
10
10
  */
11
11
 
12
12
  const fs = require("node:fs");
13
- const path = require("node:path");
14
-
15
- /** @param {unknown} value @returns {value is Record<string, unknown>} */
16
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17
-
18
- /**
19
- * @param {string} settingsPath
20
- * @returns {{raw: string | null, settings: Record<string, unknown>}} raw is null when the file does not exist yet
21
- */
22
- function readSettings(settingsPath) {
23
- let raw = null;
24
- try {
25
- raw = fs.readFileSync(settingsPath, "utf8");
26
- } catch (err) {
27
- if (err.code !== "ENOENT") throw err;
28
- }
29
- if (raw === null) return { raw, settings: {} };
30
-
31
- let settings;
32
- try {
33
- settings = JSON.parse(raw);
34
- } catch (err) {
35
- throw new Error(`${settingsPath} is not valid JSON (${err.message}); fix it and run again`);
36
- }
37
- if (!isObject(settings)) throw new Error(`${settingsPath} is not a JSON object; fix it and run again`);
38
- return { raw, settings };
39
- }
40
-
41
- /** @param {string} settingsPath */
42
- function keepBackup(settingsPath) {
43
- let backup = `${settingsPath}.bak`;
44
- for (let n = 1; fs.existsSync(backup); n++) backup = `${settingsPath}.bak.${n}`;
45
- fs.copyFileSync(settingsPath, backup);
46
- }
13
+ const { isObject, readJsonObject, writeJsonObject } = require("../json-config.js");
47
14
 
48
15
  /**
49
16
  * @param {string} hookPath JSON file with {event, entry}
@@ -52,7 +19,7 @@ function keepBackup(settingsPath) {
52
19
  */
53
20
  function mergeHook(hookPath, settingsPath) {
54
21
  const { event, entry } = JSON.parse(fs.readFileSync(hookPath, "utf8"));
55
- const { raw, settings } = readSettings(settingsPath);
22
+ const { raw, value: settings } = readJsonObject(settingsPath);
56
23
 
57
24
  const hooks = settings.hooks ?? {};
58
25
  const entries = isObject(hooks) ? hooks[event] ?? [] : null;
@@ -64,9 +31,7 @@ function mergeHook(hookPath, settingsPath) {
64
31
  const registered = entries.some((existing) => Array.isArray(existing?.hooks) && existing.hooks.some((hook) => hook?.command === command));
65
32
  if (registered) return false;
66
33
 
67
- if (raw !== null) keepBackup(settingsPath);
68
- fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
69
- fs.writeFileSync(settingsPath, `${JSON.stringify({ ...settings, hooks: { ...hooks, [event]: [...entries, entry] } }, null, 2)}\n`);
34
+ writeJsonObject(settingsPath, raw, { ...settings, hooks: { ...hooks, [event]: [...entries, entry] } });
70
35
  return true;
71
36
  }
72
37
 
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Read and write a JSON config file that belongs to the user (Claude Code settings.json, OpenCode
5
+ * opencode.json) without ever damaging it. Shared by guard/claude/merge-settings.js and
6
+ * guard/opencode/merge-permission.js.
7
+ *
8
+ * A file that is not valid JSON, or not a JSON object, is never modified. When a write changes an
9
+ * existing file, the previous one is kept as "<name>.bak" (or the next free .bak.N).
10
+ */
11
+
12
+ const fs = require("node:fs");
13
+ const path = require("node:path");
14
+
15
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
16
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17
+
18
+ /**
19
+ * @param {string} filePath
20
+ * @returns {{raw: string | null, value: Record<string, unknown>}} raw is null when the file does not exist yet
21
+ */
22
+ function readJsonObject(filePath) {
23
+ let raw = null;
24
+ try {
25
+ raw = fs.readFileSync(filePath, "utf8");
26
+ } catch (err) {
27
+ if (err.code !== "ENOENT") throw err;
28
+ }
29
+ if (raw === null) return { raw, value: {} };
30
+
31
+ let value;
32
+ try {
33
+ value = JSON.parse(raw);
34
+ } catch (err) {
35
+ throw new Error(`${filePath} is not valid JSON (${err.message}); fix it and run again`);
36
+ }
37
+ if (!isObject(value)) throw new Error(`${filePath} is not a JSON object; fix it and run again`);
38
+ return { raw, value };
39
+ }
40
+
41
+ /**
42
+ * @param {string} filePath
43
+ * @param {string | null} raw what readJsonObject returned: null means there is nothing to back up
44
+ * @param {Record<string, unknown>} value
45
+ */
46
+ function writeJsonObject(filePath, raw, value) {
47
+ if (raw !== null) {
48
+ let backup = `${filePath}.bak`;
49
+ for (let n = 1; fs.existsSync(backup); n++) backup = `${filePath}.bak.${n}`;
50
+ fs.copyFileSync(filePath, backup);
51
+ }
52
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
53
+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
54
+ }
55
+
56
+ module.exports = { isObject, readJsonObject, writeJsonObject };
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ /**
5
+ * Merges the lah guard permissions into an OpenCode opencode.json without touching anything else.
6
+ * Used by bin/cli.js (require) and install.sh (`node merge-permission.js <permission.json> <opencode.json>`).
7
+ *
8
+ * OpenCode applies the last matching rule, so each of our patterns is moved to the end of its tool's
9
+ * rules: it replaces a user rule with the same pattern and wins over earlier, broader ones. A text
10
+ * value such as `"permission": "allow"` or `"read": "allow"` is kept as `{"*": "allow"}`.
11
+ * See json-config.js for the invalid-JSON and backup rules.
12
+ */
13
+
14
+ const fs = require("node:fs");
15
+ const { isObject, readJsonObject, writeJsonObject } = require("../json-config.js");
16
+
17
+ /**
18
+ * @param {unknown} value a `permission` or `permission.<tool>` value from the user's config
19
+ * @param {string} where for the error message
20
+ * @returns {Record<string, unknown>} the same rules as an object
21
+ */
22
+ function asRules(value, where) {
23
+ if (value === undefined) return {};
24
+ if (typeof value === "string") return { "*": value };
25
+ if (isObject(value)) return { ...value };
26
+ throw new Error(`${where} has an unexpected shape; fix it and run again`);
27
+ }
28
+
29
+ /**
30
+ * @param {string} fragmentPath JSON file with {permission: {<tool>: {<pattern>: <decision>}}}
31
+ * @param {string} configPath
32
+ * @returns {boolean} true when opencode.json was written
33
+ */
34
+ function mergePermission(fragmentPath, configPath) {
35
+ const { permission: ours } = JSON.parse(fs.readFileSync(fragmentPath, "utf8"));
36
+ const { raw, value: config } = readJsonObject(configPath);
37
+
38
+ const permission = asRules(config.permission, `${configPath} "permission"`);
39
+ for (const [tool, rules] of Object.entries(ours)) {
40
+ const merged = asRules(permission[tool], `${configPath} "permission.${tool}"`);
41
+ for (const [pattern, decision] of Object.entries(rules)) {
42
+ delete merged[pattern];
43
+ merged[pattern] = decision;
44
+ }
45
+ permission[tool] = merged;
46
+ }
47
+
48
+ const next = { ...config, permission };
49
+ if (JSON.stringify(next) === JSON.stringify(config)) return false;
50
+ writeJsonObject(configPath, raw, next);
51
+ return true;
52
+ }
53
+
54
+ if (require.main === module) {
55
+ try {
56
+ mergePermission(process.argv[2], process.argv[3]);
57
+ } catch (err) {
58
+ process.stderr.write(`${err.message}\n`);
59
+ process.exitCode = 1;
60
+ }
61
+ }
62
+
63
+ module.exports = { mergePermission };
@@ -0,0 +1,72 @@
1
+ {
2
+ "permission": {
3
+ "read": {
4
+ "*.env": "deny",
5
+ "*.env.*": "deny",
6
+ "*.pem": "deny",
7
+ "*.key": "deny",
8
+ "*id_rsa": "deny",
9
+ "*id_ed25519": "deny",
10
+ "*/.ssh/*": "deny",
11
+ "*.env.example": "allow"
12
+ },
13
+ "edit": {
14
+ "*.env": "deny",
15
+ "*.env.*": "deny",
16
+ "*.pem": "deny",
17
+ "*.key": "deny",
18
+ "*id_rsa": "deny",
19
+ "*id_ed25519": "deny",
20
+ "*/.ssh/*": "deny",
21
+ "*.env.example": "allow"
22
+ },
23
+ "bash": {
24
+ "rm -rf": "ask",
25
+ "rm -rf *": "ask",
26
+ "rm * -rf": "ask",
27
+ "rm * -rf *": "ask",
28
+ "rm -fr": "ask",
29
+ "rm -fr *": "ask",
30
+ "rm * -fr": "ask",
31
+ "rm * -fr *": "ask",
32
+ "rm -rF": "ask",
33
+ "rm -rF *": "ask",
34
+ "rm * -rF": "ask",
35
+ "rm * -rF *": "ask",
36
+ "rm -Rf": "ask",
37
+ "rm -Rf *": "ask",
38
+ "rm * -Rf": "ask",
39
+ "rm * -Rf *": "ask",
40
+ "rm -fR": "ask",
41
+ "rm -fR *": "ask",
42
+ "rm * -fR": "ask",
43
+ "rm * -fR *": "ask",
44
+ "rm -r": "ask",
45
+ "rm -r *": "ask",
46
+ "rm * -r": "ask",
47
+ "rm * -r *": "ask",
48
+ "rm -R": "ask",
49
+ "rm -R *": "ask",
50
+ "rm * -R": "ask",
51
+ "rm * -R *": "ask",
52
+ "rm --recursive": "ask",
53
+ "rm --recursive *": "ask",
54
+ "rm * --recursive": "ask",
55
+ "rm * --recursive *": "ask",
56
+ "git reset --hard": "ask",
57
+ "git reset --hard *": "ask",
58
+ "git reset * --hard": "ask",
59
+ "git reset * --hard *": "ask",
60
+ "git push --force": "ask",
61
+ "git push --force *": "ask",
62
+ "git push * --force": "ask",
63
+ "git push * --force *": "ask",
64
+ "git push -f": "ask",
65
+ "git push -f *": "ask",
66
+ "git push * -f": "ask",
67
+ "git push * -f *": "ask",
68
+ "sudo": "ask",
69
+ "sudo *": "ask"
70
+ }
71
+ }
72
+ }
package/install.sh CHANGED
@@ -39,7 +39,7 @@ if [ "$GUARD" = true ] && [ "$TARGET_MODE" != "global" ]; then
39
39
  fi
40
40
 
41
41
  if [ "$GUARD" = true ] && ! command -v node >/dev/null 2>&1; then
42
- echo "--guard necesita node para registrar el hook en ~/.claude/settings.json (y para que el hook funcione)." >&2
42
+ echo "--guard necesita node para registrar el hook de Claude Code y los permisos de OpenCode (y para que el hook funcione)." >&2
43
43
  exit 1
44
44
  fi
45
45
 
@@ -194,7 +194,7 @@ case "$STRATEGY" in
194
194
  esac
195
195
 
196
196
  # The guard is opt-in and independent of environment detection: --guard always deploys every guard target.
197
- if [ "$GUARD" = true ]; then SELECTED="$SELECTED pi-guard codex-guard claude-guard"; fi
197
+ if [ "$GUARD" = true ]; then SELECTED="$SELECTED pi-guard codex-guard claude-guard opencode-guard"; fi
198
198
 
199
199
  # 4. Deployment helpers (semantics mirror bin/cli.js: manifest.tsv is the SSOT)
200
200
  MANIFEST="$SRC/manifest.tsv"
@@ -207,14 +207,64 @@ backup_path() {
207
207
  printf '%s' "$candidate"
208
208
  }
209
209
 
210
+ # Merge mode: markers delimiting the user's rules inside a deployed instruction file,
211
+ # and the strings identifying a file the harness itself deployed (replaced bare, never absorbed).
212
+ MERGE_START='<!-- lah:project-rules:start -->'
213
+ MERGE_END='<!-- lah:project-rules:end -->'
214
+ MERGE_HEADING=$'## Project Rules\n\n'
215
+
216
+ # Leading and trailing whitespace (newlines included), matching the JS side's String.trim().
217
+ trim_ws() {
218
+ local t="$1"
219
+ t="${t#"${t%%[![:space:]]*}"}"
220
+ printf '%s' "${t%"${t##*[![:space:]]}"}"
221
+ }
222
+
210
223
  # Instruction file: a divergent existing destination is preserved as .bak (or the next free .bak.N).
211
224
  # mode "if-missing": an existing destination is left untouched (seed files).
225
+ # mode "merge": the divergent destination's rules also survive in context — a user file is merged
226
+ # as a "Project Rules" section, a managed file keeps its section across payload upgrades, and a
227
+ # file the harness itself deployed is replaced bare. Writing a byte-identical result is a no-op.
212
228
  write_instruction() {
213
229
  local src="$1" dest="$2" mode="${3:-}"
214
230
  if [ "$mode" = "if-missing" ] && [ -e "$dest" ]; then return 0; fi
215
231
  mkdir -p "$(dirname "$dest")"
216
- if [ -f "$dest" ] && ! cmp -s "$src" "$dest"; then cp "$dest" "$(backup_path "$dest")"; fi
232
+ if [ ! -e "$dest" ]; then cp "$src" "$dest"; return 0; fi
233
+ if cmp -s "$src" "$dest"; then return 0; fi
234
+ if [ "$mode" != "merge" ]; then
235
+ cp "$dest" "$(backup_path "$dest")"
236
+ cp "$src" "$dest"
237
+ return 0
238
+ fi
239
+ local current section composed payload
240
+ payload="$(cat "$src")"
241
+ payload="${payload%"${payload##*[![:space:]]}"}"
242
+ current="$(cat "$dest")"
243
+ case "$current" in
244
+ *"$MERGE_START"*)
245
+ section="$current"
246
+ section="${section#*"$MERGE_START"}"
247
+ section="${section%%"$MERGE_END"*}"
248
+ section="$(trim_ws "$section")"
249
+ ;;
250
+ *lean-agent-harness*|*"Single source of truth for all coding agents"*|*"# Claude Code Project Configuration"*)
251
+ section=""
252
+ ;;
253
+ *)
254
+ section="$(trim_ws "$current")"
255
+ if [ -n "$section" ]; then section="${MERGE_HEADING}${section}"; fi
256
+ ;;
257
+ esac
258
+ if [ -n "$section" ]; then
259
+ composed="$(printf '%s\n\n%s\n%s\n%s\n' "$payload" "$MERGE_START" "$section" "$MERGE_END")"
260
+ if printf '%s\n' "$composed" | cmp -s - "$dest"; then return 0; fi
261
+ cp "$dest" "$(backup_path "$dest")"
262
+ printf '%s\n' "$composed" > "$dest"
263
+ return 0
264
+ fi
265
+ cp "$dest" "$(backup_path "$dest")"
217
266
  cp "$src" "$dest"
267
+ return 0
218
268
  }
219
269
 
220
270
  # Skill folders omitted by --profile core (profile-extras.txt, shared with bin/cli.js).
@@ -252,6 +302,7 @@ while IFS="$TAB" read -r scope tgt kind src dest mode; do
252
302
  case "$kind" in
253
303
  file) write_instruction "$SRC/$src" "$BASE_DIR/$dest" "${mode:-}" ;;
254
304
  settings-hook) node "$SRC/guard/claude/merge-settings.js" "$SRC/$src" "$BASE_DIR/$dest" ;;
305
+ opencode-permission) node "$SRC/guard/opencode/merge-permission.js" "$SRC/$src" "$BASE_DIR/$dest" ;;
255
306
  dir)
256
307
  if [ "$src" = "skills" ]; then copy_dir "$SRC/$src" "$BASE_DIR/$dest" skip-extras
257
308
  else copy_dir "$SRC/$src" "$BASE_DIR/$dest"; fi
package/manifest.tsv CHANGED
@@ -4,28 +4,32 @@
4
4
  # | global-guard (dest relative to $HOME; deployed only with --global --guard)
5
5
  # kind: file (instruction file; a divergent existing dest is saved as .bak) | dir (mirror directory)
6
6
  # | settings-hook (merge the hook in src into the Claude Code settings.json at dest)
7
+ # | opencode-permission (merge the permission rules in src into the OpenCode opencode.json at dest)
7
8
  # mode: if-missing (file kind only: never overwrite an existing dest)
9
+ # merge (file kind only: back up a divergent dest and merge its rules into the deployed
10
+ # file as a "Project Rules" section; a dest the harness itself deployed is replaced bare)
8
11
  # Target "agents" = the cross-tool Agent Skills location (.agents/skills), read natively by
9
12
  # Pi, OpenCode, Codex, Copilot and Cursor. Claude Code reads .claude/skills instead.
10
- local core file AGENTS.md AGENTS.md
11
- local core file CLAUDE.md CLAUDE.md
13
+ local core file AGENTS.md AGENTS.md merge
14
+ local core file CLAUDE.md CLAUDE.md merge
12
15
  local core file templates/GLOSSARY.md GLOSSARY.md if-missing
13
16
  local claude dir skills .claude/skills
14
17
  local agents dir skills .agents/skills
15
18
  local opencode dir adapters/opencode/commands .opencode/commands
16
19
  local commandcode dir skills .commandcode/skills
17
- global claude file AGENTS.md .claude/AGENTS.md
18
- global claude file CLAUDE.md .claude/CLAUDE.md
20
+ global claude file AGENTS.md .claude/AGENTS.md merge
21
+ global claude file CLAUDE.md .claude/CLAUDE.md merge
19
22
  global claude dir skills .claude/skills
20
23
  global agents dir skills .agents/skills
21
- global pi file AGENTS.md .pi/agent/AGENTS.md
22
- global opencode file AGENTS.md .config/opencode/AGENTS.md
24
+ global pi file AGENTS.md .pi/agent/AGENTS.md merge
25
+ global opencode file AGENTS.md .config/opencode/AGENTS.md merge
23
26
  global opencode dir adapters/opencode/commands .config/opencode/commands
24
- global codex file AGENTS.md .codex/AGENTS.md
25
- global copilot file AGENTS.md .copilot/copilot-instructions.md
26
- global commandcode file AGENTS.md .commandcode/AGENTS.md
27
+ global codex file AGENTS.md .codex/AGENTS.md merge
28
+ global copilot file AGENTS.md .copilot/copilot-instructions.md merge
29
+ global commandcode file AGENTS.md .commandcode/AGENTS.md merge
27
30
  global commandcode dir skills .commandcode/skills
28
31
  global-guard pi-guard dir guard/pi/lah-guard .pi/agent/extensions/lah-guard
29
32
  global-guard claude-guard dir guard/claude/lah-guard .claude/hooks/lah-guard
30
33
  global-guard claude-guard settings-hook guard/claude/hook.json .claude/settings.json
34
+ global-guard opencode-guard opencode-permission guard/opencode/permission.json .config/opencode/opencode.json
31
35
  global-guard codex-guard file guard/codex/lah.rules .codex/rules/lah.rules
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lean-agent-harness",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "Zero-bloat, token-efficient agent harness for Claude Code, Cursor, OpenCode, Pi, Codex, and CommandCode.",
5
5
  "author": "lnardev",
6
6
  "bin": {
@@ -24,6 +24,8 @@
24
24
  "adapters/",
25
25
  "skills/",
26
26
  "guard/claude/",
27
+ "guard/json-config.js",
28
+ "guard/opencode/",
27
29
  "guard/pi/",
28
30
  "guard/codex/",
29
31
  "AGENTS.md",