lean-agent-harness 1.2.0 → 1.3.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/AGENTS.md +3 -2
- package/CHANGELOG.md +23 -0
- package/GLOSSARY.md +5 -2
- package/README.md +8 -2
- package/bin/cli.js +20 -6
- package/guard/claude/hook.json +7 -0
- package/guard/claude/lah-guard/core.js +101 -0
- package/guard/claude/lah-guard/index.js +76 -0
- package/guard/claude/lah-guard/policy.json +33 -0
- package/guard/claude/merge-settings.js +70 -0
- package/guard/codex/lah.rules +74 -0
- package/guard/pi/lah-guard/core.js +101 -0
- package/guard/pi/lah-guard/index.js +49 -0
- package/guard/pi/lah-guard/policy.json +33 -0
- package/install.sh +18 -2
- package/manifest.tsv +6 -0
- package/package.json +4 -1
- package/skills/orchestrate/SKILL.md +2 -1
- package/skills/plan-flow/SKILL.md +1 -1
- package/skills/review/SKILL.md +1 -1
package/AGENTS.md
CHANGED
|
@@ -4,6 +4,7 @@ Single source of truth for all coding agents. Engineering rigor, deterministic e
|
|
|
4
4
|
|
|
5
5
|
## 1. Core Principles
|
|
6
6
|
|
|
7
|
+
* **Scope:** A request that needs no file, code or command (a question, arithmetic, an explanation) gets a direct answer: no sizing, pre-flight, plan, verification or trade-off notes.
|
|
7
8
|
* **Communication:** Explain what you did, why, and the trade-offs, so the user can understand and decide. Offer an alternative only when it is a real option, with its cost. No filler or apologies.
|
|
8
9
|
* **Ubiquitous Language:** Read `GLOSSARY.md` (if present) before naming anything; keep business terms and code symbols 1:1. Register new domain entities and invariants there immediately.
|
|
9
10
|
* **Deep Modules:** High functional depth behind minimal interfaces. No shallow wrappers, anemic layers, or premature fragmentation.
|
|
@@ -24,10 +25,10 @@ Workflow skills (explicit invocation only): `plan-flow <task>` → `orchestrate`
|
|
|
24
25
|
|
|
25
26
|
## 3. Hard Rules
|
|
26
27
|
|
|
27
|
-
* **Circuit Breaker:** After 2 consecutive failed fixes on one error: STOP, revert (`git checkout -- <files
|
|
28
|
+
* **Circuit Breaker:** After 2 consecutive failed fixes on one error: STOP, revert (`git checkout -- <files>`, only files clean at slice start), re-read the full stack trace, state a new root-cause hypothesis before editing again.
|
|
28
29
|
* **Zero-Hang:** Never block on stdin: use non-interactive flags (`-y`, `--no-interaction`, `-m "<msg>"`); no interactive editors or `sudo`.
|
|
29
30
|
* **Strict Typing, no placeholders:** TypeScript: no `any`, explicit types. PHP: `declare(strict_types=1);` and typed signatures. Go: no bare `interface{}`, never discard errors with `_`. Python: full annotations/Pydantic. No stubs (`// ...`, `TODO: implement`), no dead or commented-out code, no AI attribution (`Co-Authored-By: Claude`).
|
|
30
|
-
* **Dependencies:** No
|
|
31
|
+
* **Dependencies:** No new packages (`npm i <pkg>`, `pip install <pkg>`, `go get`, `composer require`) unless the approved plan lists them; installing declared ones (`npm ci`) is fine.
|
|
31
32
|
* **Secrets:** Never read, print, or commit `.env*` (only `.env.example` for key names), SSH keys, `*.pem`/`*.key`, or `.git/*`. Define env vars as typed validated config.
|
|
32
33
|
* **Destructive commands** (`rm -rf`, DB drops/truncation, `git reset --hard`, `git push --force`) require explicit human confirmation.
|
|
33
34
|
* **Slice rollback:** a slice that fails its Definition of Done is reverted to the last clean passing state.
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,29 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented here. Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
4
4
|
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [1.3.0] - 2026-10-30
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Claude Code guard: `--global --guard` also installs a `PreToolUse` hook in `~/.claude/hooks/lah-guard/` and registers it in `~/.claude/settings.json` by merge (invalid JSON is never touched, the previous file is kept as `.bak`, a second run changes nothing). Secret files are denied; destructive commands go to Claude Code's own permission prompt. Input the hook cannot read blocks the call. `install.sh --guard` now requires `node`.
|
|
12
|
+
- Opt-in guard: `--global --guard` installs a Pi extension and Codex command rules that block secret files (`.env*`, `*.pem`, `*.key`, `.ssh/`) and ask before `rm -r`, `git reset --hard`, `git push --force` and `sudo`; without a UI to answer, those commands are blocked. Rules come from `guard/policy.json`. `--guard` without `--global` is rejected.
|
|
13
|
+
- `Scope` rule in `AGENTS.md`: a request that needs no file, code or command gets a direct answer, without the engineering workflow.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- The guard matcher moved to `guard/core.js`, copied by `guard/build.js` beside the Pi and Claude Code guards so both apply the same rules.
|
|
18
|
+
- `plan-flow` and `orchestrate` treat `db-migration` and `impeccable` as optional, so `--profile core` installs no longer reference missing skills.
|
|
19
|
+
- `GLOSSARY.md` registers `LAH_VERSION`, `LAH_SHA256`, `LAH_ARCHIVE_URL` and the `.bak.N` backup naming.
|
|
20
|
+
- Standing-context estimate updated to about 0.9k tokens; the `AGENTS.md` size cap in the test is now 3800 bytes.
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
|
|
24
|
+
- The Circuit Breaker revert can no longer discard the user's uncommitted edits: it only touches files that were clean when the slice began, and `orchestrate` asks the user to commit or stash otherwise.
|
|
25
|
+
- `review` no longer records a meaningless hash for committed work: `git diff HEAD` is empty there, so it hashes `git diff <base>...HEAD`.
|
|
26
|
+
- The dependency rule blocks new packages but no longer blocks installing the ones already declared (`npm ci`).
|
|
27
|
+
|
|
5
28
|
## [1.2.0]
|
|
6
29
|
|
|
7
30
|
### Added
|
package/GLOSSARY.md
CHANGED
|
@@ -14,7 +14,7 @@ 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
|
|
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. |
|
|
18
18
|
| **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
19
|
| **Slice** | One feature-complete ODD unit (e.g., migration + model + service + tests). | `- [ ] Slice N:` checklist item | No fragmented single-line micro-slices. |
|
|
20
20
|
| **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. |
|
|
@@ -28,6 +28,9 @@ Single source of truth for the domain vocabulary of this project. Both human eng
|
|
|
28
28
|
| **Profile** | Installation subset: `full` (default) deploys every skill; `core` omits the skills listed in `profile-extras.txt`. | `--profile core|full` | Only the `skills` directory is filtered; rules and workflow skills always install; both installers must produce identical trees. |
|
|
29
29
|
| **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
30
|
| **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
|
+
| **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 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. |
|
|
31
34
|
|
|
32
35
|
---
|
|
33
36
|
|
|
@@ -36,7 +39,7 @@ Single source of truth for the domain vocabulary of this project. Both human eng
|
|
|
36
39
|
* **Seam 1 (SSOT):** `AGENTS.md` is the only normative rule set. `CLAUDE.md` and the workflow skills reference it; duplication of normative rules across files is a defect.
|
|
37
40
|
* **Seam 2 (Installer Parity):** Any supported environment must be deployable from both installers (`bin/cli.js` and `install.sh`) with equivalent file placement. Adding a target requires only a `manifest.tsv` row; the parity test enforces it.
|
|
38
41
|
* **Seam 3 (Coupling):** Behavior of the harness must be declarative (`manifest.tsv` driven). No per-platform copy-paste blocks in either installer; there are no transforms; files are copied verbatim.
|
|
39
|
-
* **Seam 4 (Token Budget):** Standing rules (`AGENTS.md`) cost ~0.
|
|
42
|
+
* **Seam 4 (Token Budget):** Standing rules (`AGENTS.md`) cost ~0.9k tokens per session; skill descriptions add one line each, and workflow skills add none. Every rule added must earn its tokens by preventing a real, observed failure mode.
|
|
40
43
|
|
|
41
44
|
---
|
|
42
45
|
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Lean Agent Harness (`lah`)
|
|
2
2
|
|
|
3
|
-
One rule file and one skill format for **Claude Code**, **Pi**, **OpenCode**, **Codex**, **Cursor**, **Copilot** and **CommandCode**. Standing context is `AGENTS.md` (about 0.
|
|
3
|
+
One rule file and one skill format for **Claude Code**, **Pi**, **OpenCode**, **Codex**, **Cursor**, **Copilot** and **CommandCode**. Standing context is `AGENTS.md` (about 0.9k tokens) plus one line per skill.
|
|
4
4
|
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
|
|
@@ -46,7 +46,7 @@ curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/ins
|
|
|
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.
|
|
49
|
+
curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/install.sh | LAH_VERSION=1.3.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,6 +57,12 @@ 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`.
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
npx lean-agent-harness --global --guard
|
|
64
|
+
```
|
|
65
|
+
|
|
60
66
|
```bash
|
|
61
67
|
npm test # installs with both installers and asserts identical output trees
|
|
62
68
|
```
|
package/bin/cli.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* (default) deploy into the current project
|
|
12
12
|
* --global deploy into the user home (~/.claude, ~/.pi, ~/.config/opencode, ...)
|
|
13
13
|
*
|
|
14
|
-
* Flags: --help | -h | --version | -v | --global | -g | --local | -l
|
|
14
|
+
* Flags: --help | -h | --version | -v | --global | -g | --local | -l | --guard (with --global)
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
const fs = require("fs");
|
|
@@ -19,12 +19,14 @@ const os = require("os");
|
|
|
19
19
|
const path = require("path");
|
|
20
20
|
|
|
21
21
|
const { version } = require("../package.json");
|
|
22
|
+
const { mergeHook } = require("../guard/claude/merge-settings.js");
|
|
22
23
|
|
|
23
24
|
const PKG_ROOT = path.resolve(__dirname, "..");
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
27
|
* @typedef {Object} Entry
|
|
27
|
-
* @property {"file"|"dir"} kind file = instruction file (.bak on divergence); dir = mirrored directory
|
|
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
|
|
28
30
|
* @property {string} src Path relative to the package root
|
|
29
31
|
* @property {string} dest Path relative to the target base
|
|
30
32
|
* @property {string} mode "" or "if-missing" (file kind: never overwrite an existing dest)
|
|
@@ -44,6 +46,9 @@ const LABELS = {
|
|
|
44
46
|
codex: "Codex",
|
|
45
47
|
copilot: "Copilot",
|
|
46
48
|
commandcode: "CommandCode",
|
|
49
|
+
"pi-guard": "Pi guard",
|
|
50
|
+
"claude-guard": "Claude Code guard",
|
|
51
|
+
"codex-guard": "Codex guard",
|
|
47
52
|
};
|
|
48
53
|
|
|
49
54
|
/**
|
|
@@ -98,6 +103,7 @@ function targetsFor(scope, base) {
|
|
|
98
103
|
const TARGETS = {
|
|
99
104
|
local: () => targetsFor("local", process.env.LAH_FAKE_CWD || process.cwd()),
|
|
100
105
|
global: (home) => targetsFor("global", home),
|
|
106
|
+
"global-guard": (home) => targetsFor("global-guard", home),
|
|
101
107
|
};
|
|
102
108
|
|
|
103
109
|
const c = process.stdout.isTTY
|
|
@@ -188,6 +194,7 @@ function deployTarget(t, exclude = new Set()) {
|
|
|
188
194
|
const from = path.join(PKG_ROOT, src);
|
|
189
195
|
const to = path.join(t.base, dest);
|
|
190
196
|
if (kind === "file") writeInstruction(from, to, mode);
|
|
197
|
+
else if (kind === "settings-hook") mergeHook(from, to);
|
|
191
198
|
else copyDir(from, to, src === "skills" ? exclude : new Set());
|
|
192
199
|
}
|
|
193
200
|
const label = t.base.replace(process.env.LAH_FAKE_HOME || os.homedir(), "~");
|
|
@@ -217,10 +224,10 @@ function deployLocal(profile = "full") {
|
|
|
217
224
|
return deployAll(TARGETS.local(), profile);
|
|
218
225
|
}
|
|
219
226
|
|
|
220
|
-
function deployGlobal(profile = "full") {
|
|
227
|
+
function deployGlobal(profile = "full", guard = false) {
|
|
221
228
|
const home = process.env.LAH_FAKE_HOME || os.homedir();
|
|
222
229
|
console.log(`\nModo: ${c.bold}Global${c.reset} (${c.dim}${home}${c.reset})`);
|
|
223
|
-
return deployAll(TARGETS.global(home), profile);
|
|
230
|
+
return deployAll([...TARGETS.global(home), ...(guard ? TARGETS["global-guard"](home) : [])], profile);
|
|
224
231
|
}
|
|
225
232
|
|
|
226
233
|
const HELP = `Lean Agent Harness v${version}
|
|
@@ -235,6 +242,8 @@ Flags:
|
|
|
235
242
|
-l, --local Desplegar en el proyecto actual (comportamiento por defecto)
|
|
236
243
|
-g, --global Desplegar en carpetas de usuario (~/)
|
|
237
244
|
--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
|
|
246
|
+
secretos y comandos destructivos. Ejecuta código en el agente: es opt-in
|
|
238
247
|
-h, --help Mostrar esta ayuda
|
|
239
248
|
-v, --version Mostrar versión
|
|
240
249
|
|
|
@@ -264,7 +273,7 @@ function main(argv) {
|
|
|
264
273
|
}
|
|
265
274
|
}
|
|
266
275
|
|
|
267
|
-
const validFlags = new Set(["--global", "-g", "--local", "-l"]);
|
|
276
|
+
const validFlags = new Set(["--global", "-g", "--local", "-l", "--guard"]);
|
|
268
277
|
const unknownArgs = rest.filter((a) => !validFlags.has(a));
|
|
269
278
|
|
|
270
279
|
if (unknownArgs.length > 0) {
|
|
@@ -273,7 +282,12 @@ function main(argv) {
|
|
|
273
282
|
}
|
|
274
283
|
|
|
275
284
|
const isGlobal = argv.includes("--global") || argv.includes("-g");
|
|
276
|
-
const
|
|
285
|
+
const guard = argv.includes("--guard");
|
|
286
|
+
if (guard && !isGlobal) {
|
|
287
|
+
console.error("--guard requiere --global: las extensiones de proyecto solo cargan si el proyecto es de confianza.");
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
const { failed } = isGlobal ? deployGlobal(profile, guard) : deployLocal(profile);
|
|
277
291
|
|
|
278
292
|
if (failed > 0) return 1;
|
|
279
293
|
console.log(`\n${c.green}${c.bold}Done!${c.reset} Arnés desplegado correctamente.\n`);
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Policy matcher shared by every guard (Pi extension, Claude Code hook). guard/build.js copies this
|
|
5
|
+
* file beside each of them, because each is deployed on its own.
|
|
6
|
+
*
|
|
7
|
+
* Best effort, not a sandbox: a command built through an interpreter (`python -c`) is not seen.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const path = require("node:path");
|
|
11
|
+
|
|
12
|
+
const SEGMENT_SEPARATORS = /&&|\|\||[;|\n]/;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Case-insensitive: the default macOS and Windows file systems open `.ENV` as `.env`.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} pattern glob where `*` stands for any run of characters inside one path segment
|
|
18
|
+
* @returns {RegExp}
|
|
19
|
+
*/
|
|
20
|
+
function globToRegExp(pattern) {
|
|
21
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
|
|
22
|
+
return new RegExp(`^${escaped}$`, "i");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @param {string} word @returns {string} */
|
|
26
|
+
function unquote(word) {
|
|
27
|
+
return word.replace(/^['"]+|['"]+$/g, "");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Words of one shell segment, without leading VAR=value assignments.
|
|
32
|
+
* @param {string} segment
|
|
33
|
+
* @returns {string[]}
|
|
34
|
+
*/
|
|
35
|
+
function wordsOf(segment) {
|
|
36
|
+
const words = segment.trim().split(/\s+/).filter(Boolean).map(unquote);
|
|
37
|
+
while (words.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) words.shift();
|
|
38
|
+
return words;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {string} command @returns {string[][]} */
|
|
42
|
+
function segmentsOf(command) {
|
|
43
|
+
return command.split(SEGMENT_SEPARATORS).map(wordsOf).filter((words) => words.length > 0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {Object} ShellRule
|
|
48
|
+
* @property {string[]} command
|
|
49
|
+
* @property {string[]} [anyOf]
|
|
50
|
+
* @property {"ask" | "deny"} decision
|
|
51
|
+
* @property {string} reason
|
|
52
|
+
*
|
|
53
|
+
* @typedef {Object} Policy
|
|
54
|
+
* @property {{basenames: string[], except: string[], directories: string[], readers: string[]}} secrets
|
|
55
|
+
* @property {ShellRule[]} shell
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {Policy} policy
|
|
60
|
+
* @returns {{isSecretPath: (filePath: string) => boolean, readsSecret: (command: string) => boolean, ruleHit: (command: string) => ShellRule | undefined}}
|
|
61
|
+
*/
|
|
62
|
+
function createMatcher(policy) {
|
|
63
|
+
const secretBasenames = policy.secrets.basenames.map(globToRegExp);
|
|
64
|
+
const allowedBasenames = policy.secrets.except.map(globToRegExp);
|
|
65
|
+
const secretDirectories = policy.secrets.directories.map((name) => name.toLowerCase());
|
|
66
|
+
|
|
67
|
+
/** @param {string} filePath @returns {boolean} */
|
|
68
|
+
function isSecretPath(filePath) {
|
|
69
|
+
const base = path.basename(filePath);
|
|
70
|
+
if (allowedBasenames.some((pattern) => pattern.test(base))) return false;
|
|
71
|
+
if (secretBasenames.some((pattern) => pattern.test(base))) return true;
|
|
72
|
+
return filePath.split("/").some((part) => secretDirectories.includes(part.toLowerCase()));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {string} command @returns {boolean} */
|
|
76
|
+
function readsSecret(command) {
|
|
77
|
+
return segmentsOf(command).some(
|
|
78
|
+
([first, ...args]) => policy.secrets.readers.includes(first) && args.some(isSecretPath),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* @param {string} command
|
|
84
|
+
* @returns {ShellRule | undefined} the first policy rule the command hits
|
|
85
|
+
*/
|
|
86
|
+
function ruleHit(command) {
|
|
87
|
+
for (const words of segmentsOf(command)) {
|
|
88
|
+
for (const rule of policy.shell) {
|
|
89
|
+
const matchesCommand = rule.command.every((token, index) => words[index] === token);
|
|
90
|
+
if (!matchesCommand) continue;
|
|
91
|
+
const rest = words.slice(rule.command.length);
|
|
92
|
+
if (!rule.anyOf || rest.some((word) => rule.anyOf.includes(word))) return rule;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { isSecretPath, readsSecret, ruleHit };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = { createMatcher };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Lean Agent Harness guard for Claude Code (PreToolUse hook).
|
|
6
|
+
*
|
|
7
|
+
* Enforces the secret and destructive-command rules of AGENTS.md: secret files are denied outright,
|
|
8
|
+
* destructive shell commands go back to the user through Claude Code's own permission prompt.
|
|
9
|
+
* Rules live in policy.json and the matcher in core.js (both installed beside this file, generated
|
|
10
|
+
* by guard/build.js). Input it cannot read exits 2, which blocks the call: a broken guard fails closed.
|
|
11
|
+
*
|
|
12
|
+
* Best effort, not a sandbox: a command built through an interpreter (`python -c`) is not seen.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const { createMatcher } = require("./core.js");
|
|
16
|
+
const policy = require("./policy.json");
|
|
17
|
+
|
|
18
|
+
const { isSecretPath, readsSecret, ruleHit } = createMatcher(policy);
|
|
19
|
+
// Grep reads file contents through `path` (a file) and `glob` (a file name filter).
|
|
20
|
+
const FILE_PATH_KEYS = ["file_path", "notebook_path", "path", "glob"];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {string} toolName
|
|
24
|
+
* @param {Record<string, unknown>} toolInput
|
|
25
|
+
* @returns {{decision: "ask" | "deny", reason: string} | undefined}
|
|
26
|
+
*/
|
|
27
|
+
function decide(toolName, toolInput) {
|
|
28
|
+
if (toolName === "Bash") {
|
|
29
|
+
const command = toolInput.command;
|
|
30
|
+
if (typeof command !== "string") return undefined;
|
|
31
|
+
if (readsSecret(command)) {
|
|
32
|
+
return { decision: "deny", reason: "This command reads a secret file: AGENTS.md forbids it." };
|
|
33
|
+
}
|
|
34
|
+
const hit = ruleHit(command);
|
|
35
|
+
return hit ? { decision: hit.decision, reason: hit.reason } : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
for (const key of FILE_PATH_KEYS) {
|
|
39
|
+
const target = toolInput[key];
|
|
40
|
+
if (typeof target === "string" && isSecretPath(target)) {
|
|
41
|
+
return { decision: "deny", reason: `"${target}" is a secret file: AGENTS.md forbids reading, editing or writing it.` };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {string} raw @returns {string} the hook's stdout */
|
|
48
|
+
function run(raw) {
|
|
49
|
+
const event = JSON.parse(raw);
|
|
50
|
+
if (typeof event !== "object" || event === null || typeof event.tool_name !== "string" || typeof event.tool_input !== "object" || event.tool_input === null) {
|
|
51
|
+
throw new Error("expected {tool_name, tool_input}");
|
|
52
|
+
}
|
|
53
|
+
const verdict = decide(event.tool_name, event.tool_input);
|
|
54
|
+
if (!verdict) return "";
|
|
55
|
+
return JSON.stringify({
|
|
56
|
+
hookSpecificOutput: {
|
|
57
|
+
hookEventName: "PreToolUse",
|
|
58
|
+
permissionDecision: verdict.decision,
|
|
59
|
+
permissionDecisionReason: verdict.reason,
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let raw = "";
|
|
65
|
+
process.stdin.setEncoding("utf8");
|
|
66
|
+
process.stdin.on("data", (chunk) => {
|
|
67
|
+
raw += chunk;
|
|
68
|
+
});
|
|
69
|
+
process.stdin.on("end", () => {
|
|
70
|
+
try {
|
|
71
|
+
process.stdout.write(run(raw));
|
|
72
|
+
} catch (err) {
|
|
73
|
+
process.stderr.write(`lah-guard: cannot read the hook input (${err.message}); blocking the call.\n`);
|
|
74
|
+
process.exitCode = 2;
|
|
75
|
+
}
|
|
76
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"secrets": {
|
|
3
|
+
"basenames": [".env", ".env.*", "*.pem", "*.key", "id_rsa", "id_ed25519"],
|
|
4
|
+
"except": [".env.example"],
|
|
5
|
+
"directories": [".ssh"],
|
|
6
|
+
"readers": ["cat", "less", "more", "head", "tail", "grep", "rg", "sed", "awk", "cp", "mv", "scp", "base64", "xxd", "strings", "bat", "nl", "tac", "od", "hexdump", "source", "."]
|
|
7
|
+
},
|
|
8
|
+
"shell": [
|
|
9
|
+
{
|
|
10
|
+
"command": ["rm"],
|
|
11
|
+
"anyOf": ["-rf", "-fr", "-rF", "-Rf", "-fR", "-r", "-R", "--recursive"],
|
|
12
|
+
"decision": "ask",
|
|
13
|
+
"reason": "Recursive delete requires explicit human confirmation."
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"command": ["git", "reset"],
|
|
17
|
+
"anyOf": ["--hard"],
|
|
18
|
+
"decision": "ask",
|
|
19
|
+
"reason": "git reset --hard discards uncommitted work and requires explicit human confirmation."
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"command": ["git", "push"],
|
|
23
|
+
"anyOf": ["--force", "-f"],
|
|
24
|
+
"decision": "ask",
|
|
25
|
+
"reason": "Force push rewrites remote history and requires explicit human confirmation."
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"command": ["sudo"],
|
|
29
|
+
"decision": "ask",
|
|
30
|
+
"reason": "sudo is not allowed without explicit human confirmation."
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Registers the lah guard hook in a Claude Code settings.json without touching anything else.
|
|
6
|
+
* Used by bin/cli.js (require) and install.sh (`node merge-settings.js <hook.json> <settings.json>`).
|
|
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).
|
|
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} hookPath JSON file with {event, entry}
|
|
20
|
+
* @param {string} settingsPath
|
|
21
|
+
* @returns {boolean} true when settings.json was written
|
|
22
|
+
*/
|
|
23
|
+
function mergeHook(hookPath, settingsPath) {
|
|
24
|
+
const { event, entry } = JSON.parse(fs.readFileSync(hookPath, "utf8"));
|
|
25
|
+
|
|
26
|
+
let raw = null;
|
|
27
|
+
try {
|
|
28
|
+
raw = fs.readFileSync(settingsPath, "utf8");
|
|
29
|
+
} catch (err) {
|
|
30
|
+
if (err.code !== "ENOENT") throw err;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
let settings = {};
|
|
34
|
+
if (raw !== null) {
|
|
35
|
+
try {
|
|
36
|
+
settings = JSON.parse(raw);
|
|
37
|
+
} catch (err) {
|
|
38
|
+
throw new Error(`${settingsPath} is not valid JSON (${err.message}); fix it and run again`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const hooks = settings.hooks ?? {};
|
|
42
|
+
const entries = hooks[event] ?? [];
|
|
43
|
+
if (!isObject(settings) || !isObject(hooks) || !Array.isArray(entries)) {
|
|
44
|
+
throw new Error(`${settingsPath} has an unexpected "hooks" shape; fix it and run again`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const command = entry.hooks[0].command;
|
|
48
|
+
const registered = entries.some((existing) => Array.isArray(existing?.hooks) && existing.hooks.some((hook) => hook?.command === command));
|
|
49
|
+
if (registered) return false;
|
|
50
|
+
|
|
51
|
+
if (raw !== null) {
|
|
52
|
+
let backup = `${settingsPath}.bak`;
|
|
53
|
+
for (let n = 1; fs.existsSync(backup); n++) backup = `${settingsPath}.bak.${n}`;
|
|
54
|
+
fs.copyFileSync(settingsPath, backup);
|
|
55
|
+
}
|
|
56
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
57
|
+
fs.writeFileSync(settingsPath, `${JSON.stringify({ ...settings, hooks: { ...hooks, [event]: [...entries, entry] } }, null, 2)}\n`);
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (require.main === module) {
|
|
62
|
+
try {
|
|
63
|
+
mergeHook(process.argv[2], process.argv[3]);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
process.stderr.write(`${err.message}\n`);
|
|
66
|
+
process.exitCode = 1;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = { mergeHook };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Generated from guard/policy.json by guard/build.js. Do not edit.
|
|
2
|
+
# Codex rules match command prefixes only: a flag placed after other arguments is not seen.
|
|
3
|
+
|
|
4
|
+
prefix_rule(
|
|
5
|
+
pattern = ["rm", "-rf"],
|
|
6
|
+
decision = "prompt",
|
|
7
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
prefix_rule(
|
|
11
|
+
pattern = ["rm", "-fr"],
|
|
12
|
+
decision = "prompt",
|
|
13
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
prefix_rule(
|
|
17
|
+
pattern = ["rm", "-rF"],
|
|
18
|
+
decision = "prompt",
|
|
19
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
prefix_rule(
|
|
23
|
+
pattern = ["rm", "-Rf"],
|
|
24
|
+
decision = "prompt",
|
|
25
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
prefix_rule(
|
|
29
|
+
pattern = ["rm", "-fR"],
|
|
30
|
+
decision = "prompt",
|
|
31
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
prefix_rule(
|
|
35
|
+
pattern = ["rm", "-r"],
|
|
36
|
+
decision = "prompt",
|
|
37
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
prefix_rule(
|
|
41
|
+
pattern = ["rm", "-R"],
|
|
42
|
+
decision = "prompt",
|
|
43
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
prefix_rule(
|
|
47
|
+
pattern = ["rm", "--recursive"],
|
|
48
|
+
decision = "prompt",
|
|
49
|
+
justification = "Recursive delete requires explicit human confirmation.",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
prefix_rule(
|
|
53
|
+
pattern = ["git", "reset", "--hard"],
|
|
54
|
+
decision = "prompt",
|
|
55
|
+
justification = "git reset --hard discards uncommitted work and requires explicit human confirmation.",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
prefix_rule(
|
|
59
|
+
pattern = ["git", "push", "--force"],
|
|
60
|
+
decision = "prompt",
|
|
61
|
+
justification = "Force push rewrites remote history and requires explicit human confirmation.",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
prefix_rule(
|
|
65
|
+
pattern = ["git", "push", "-f"],
|
|
66
|
+
decision = "prompt",
|
|
67
|
+
justification = "Force push rewrites remote history and requires explicit human confirmation.",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
prefix_rule(
|
|
71
|
+
pattern = ["sudo"],
|
|
72
|
+
decision = "prompt",
|
|
73
|
+
justification = "sudo is not allowed without explicit human confirmation.",
|
|
74
|
+
)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Policy matcher shared by every guard (Pi extension, Claude Code hook). guard/build.js copies this
|
|
5
|
+
* file beside each of them, because each is deployed on its own.
|
|
6
|
+
*
|
|
7
|
+
* Best effort, not a sandbox: a command built through an interpreter (`python -c`) is not seen.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const path = require("node:path");
|
|
11
|
+
|
|
12
|
+
const SEGMENT_SEPARATORS = /&&|\|\||[;|\n]/;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Case-insensitive: the default macOS and Windows file systems open `.ENV` as `.env`.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} pattern glob where `*` stands for any run of characters inside one path segment
|
|
18
|
+
* @returns {RegExp}
|
|
19
|
+
*/
|
|
20
|
+
function globToRegExp(pattern) {
|
|
21
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
|
|
22
|
+
return new RegExp(`^${escaped}$`, "i");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @param {string} word @returns {string} */
|
|
26
|
+
function unquote(word) {
|
|
27
|
+
return word.replace(/^['"]+|['"]+$/g, "");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Words of one shell segment, without leading VAR=value assignments.
|
|
32
|
+
* @param {string} segment
|
|
33
|
+
* @returns {string[]}
|
|
34
|
+
*/
|
|
35
|
+
function wordsOf(segment) {
|
|
36
|
+
const words = segment.trim().split(/\s+/).filter(Boolean).map(unquote);
|
|
37
|
+
while (words.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) words.shift();
|
|
38
|
+
return words;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {string} command @returns {string[][]} */
|
|
42
|
+
function segmentsOf(command) {
|
|
43
|
+
return command.split(SEGMENT_SEPARATORS).map(wordsOf).filter((words) => words.length > 0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {Object} ShellRule
|
|
48
|
+
* @property {string[]} command
|
|
49
|
+
* @property {string[]} [anyOf]
|
|
50
|
+
* @property {"ask" | "deny"} decision
|
|
51
|
+
* @property {string} reason
|
|
52
|
+
*
|
|
53
|
+
* @typedef {Object} Policy
|
|
54
|
+
* @property {{basenames: string[], except: string[], directories: string[], readers: string[]}} secrets
|
|
55
|
+
* @property {ShellRule[]} shell
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {Policy} policy
|
|
60
|
+
* @returns {{isSecretPath: (filePath: string) => boolean, readsSecret: (command: string) => boolean, ruleHit: (command: string) => ShellRule | undefined}}
|
|
61
|
+
*/
|
|
62
|
+
function createMatcher(policy) {
|
|
63
|
+
const secretBasenames = policy.secrets.basenames.map(globToRegExp);
|
|
64
|
+
const allowedBasenames = policy.secrets.except.map(globToRegExp);
|
|
65
|
+
const secretDirectories = policy.secrets.directories.map((name) => name.toLowerCase());
|
|
66
|
+
|
|
67
|
+
/** @param {string} filePath @returns {boolean} */
|
|
68
|
+
function isSecretPath(filePath) {
|
|
69
|
+
const base = path.basename(filePath);
|
|
70
|
+
if (allowedBasenames.some((pattern) => pattern.test(base))) return false;
|
|
71
|
+
if (secretBasenames.some((pattern) => pattern.test(base))) return true;
|
|
72
|
+
return filePath.split("/").some((part) => secretDirectories.includes(part.toLowerCase()));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {string} command @returns {boolean} */
|
|
76
|
+
function readsSecret(command) {
|
|
77
|
+
return segmentsOf(command).some(
|
|
78
|
+
([first, ...args]) => policy.secrets.readers.includes(first) && args.some(isSecretPath),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* @param {string} command
|
|
84
|
+
* @returns {ShellRule | undefined} the first policy rule the command hits
|
|
85
|
+
*/
|
|
86
|
+
function ruleHit(command) {
|
|
87
|
+
for (const words of segmentsOf(command)) {
|
|
88
|
+
for (const rule of policy.shell) {
|
|
89
|
+
const matchesCommand = rule.command.every((token, index) => words[index] === token);
|
|
90
|
+
if (!matchesCommand) continue;
|
|
91
|
+
const rest = words.slice(rule.command.length);
|
|
92
|
+
if (!rule.anyOf || rest.some((word) => rule.anyOf.includes(word))) return rule;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { isSecretPath, readsSecret, ruleHit };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = { createMatcher };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Lean Agent Harness guard for Pi.
|
|
5
|
+
*
|
|
6
|
+
* Enforces the secret and destructive-command rules of AGENTS.md at the tool_call boundary:
|
|
7
|
+
* secret files are denied outright, destructive shell commands need a human answer, and without a
|
|
8
|
+
* UI to answer they are blocked. Rules live in policy.json and the matcher in core.js (both
|
|
9
|
+
* installed beside this file, generated by guard/build.js).
|
|
10
|
+
*
|
|
11
|
+
* Best effort, not a sandbox: a command built through an interpreter (`python -c`) is not seen.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const { createMatcher } = require("./core.js");
|
|
15
|
+
const policy = require("./policy.json");
|
|
16
|
+
|
|
17
|
+
const { isSecretPath, readsSecret, ruleHit } = createMatcher(policy);
|
|
18
|
+
const FILE_TOOLS = new Set(["read", "edit", "write"]);
|
|
19
|
+
|
|
20
|
+
/** @param {string} reason @returns {{block: true, reason: string}} */
|
|
21
|
+
const block = (reason) => ({ block: true, reason });
|
|
22
|
+
|
|
23
|
+
/** @param {{on: Function}} pi */
|
|
24
|
+
module.exports = function lahGuard(pi) {
|
|
25
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
26
|
+
const input = event.input || {};
|
|
27
|
+
|
|
28
|
+
if (FILE_TOOLS.has(event.toolName)) {
|
|
29
|
+
const target = input.path ?? input.file_path;
|
|
30
|
+
if (typeof target === "string" && isSecretPath(target)) {
|
|
31
|
+
return block(`"${target}" is a secret file: AGENTS.md forbids reading, editing or writing it.`);
|
|
32
|
+
}
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (event.toolName !== "bash" || typeof input.command !== "string") return undefined;
|
|
37
|
+
|
|
38
|
+
if (readsSecret(input.command)) {
|
|
39
|
+
return block("This command reads a secret file: AGENTS.md forbids it.");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const hit = ruleHit(input.command);
|
|
43
|
+
if (!hit) return undefined;
|
|
44
|
+
if (hit.decision === "deny") return block(hit.reason);
|
|
45
|
+
if (!ctx.hasUI) return block(`${hit.reason} Blocked: no UI for confirmation.`);
|
|
46
|
+
const confirmed = await ctx.ui.confirm("Confirm command", `${input.command}\n\n${hit.reason}`);
|
|
47
|
+
return confirmed ? undefined : block("Blocked by the user.");
|
|
48
|
+
});
|
|
49
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"secrets": {
|
|
3
|
+
"basenames": [".env", ".env.*", "*.pem", "*.key", "id_rsa", "id_ed25519"],
|
|
4
|
+
"except": [".env.example"],
|
|
5
|
+
"directories": [".ssh"],
|
|
6
|
+
"readers": ["cat", "less", "more", "head", "tail", "grep", "rg", "sed", "awk", "cp", "mv", "scp", "base64", "xxd", "strings", "bat", "nl", "tac", "od", "hexdump", "source", "."]
|
|
7
|
+
},
|
|
8
|
+
"shell": [
|
|
9
|
+
{
|
|
10
|
+
"command": ["rm"],
|
|
11
|
+
"anyOf": ["-rf", "-fr", "-rF", "-Rf", "-fR", "-r", "-R", "--recursive"],
|
|
12
|
+
"decision": "ask",
|
|
13
|
+
"reason": "Recursive delete requires explicit human confirmation."
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"command": ["git", "reset"],
|
|
17
|
+
"anyOf": ["--hard"],
|
|
18
|
+
"decision": "ask",
|
|
19
|
+
"reason": "git reset --hard discards uncommitted work and requires explicit human confirmation."
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"command": ["git", "push"],
|
|
23
|
+
"anyOf": ["--force", "-f"],
|
|
24
|
+
"decision": "ask",
|
|
25
|
+
"reason": "Force push rewrites remote history and requires explicit human confirmation."
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"command": ["sudo"],
|
|
29
|
+
"decision": "ask",
|
|
30
|
+
"reason": "sudo is not allowed without explicit human confirmation."
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|
package/install.sh
CHANGED
|
@@ -13,12 +13,14 @@ GREEN='\033[32m'; CYAN='\033[36m'; YELLOW='\033[33m'; BOLD='\033[1m'; DIM='\033[
|
|
|
13
13
|
TARGET_MODE=""
|
|
14
14
|
STRATEGY=""
|
|
15
15
|
PROFILE="full"
|
|
16
|
+
GUARD=false
|
|
16
17
|
while [ $# -gt 0 ]; do
|
|
17
18
|
case "$1" in
|
|
18
19
|
--global|-g) TARGET_MODE="global" ;;
|
|
19
20
|
--local|-l) TARGET_MODE="local" ;;
|
|
20
21
|
--all) STRATEGY="all" ;;
|
|
21
22
|
--auto) STRATEGY="auto" ;;
|
|
23
|
+
--guard) GUARD=true ;;
|
|
22
24
|
--profile)
|
|
23
25
|
PROFILE="${2:-}"
|
|
24
26
|
case "$PROFILE" in
|
|
@@ -26,11 +28,21 @@ while [ $# -gt 0 ]; do
|
|
|
26
28
|
*) echo "Perfil desconocido: \"$PROFILE\". Usa: core | full" >&2; exit 64 ;;
|
|
27
29
|
esac
|
|
28
30
|
;;
|
|
29
|
-
*) echo "Flag desconocido: $1 (solo: --global, --local, --all, --auto, --profile core|full)" >&2; exit 64 ;;
|
|
31
|
+
*) echo "Flag desconocido: $1 (solo: --global, --local, --all, --auto, --guard, --profile core|full)" >&2; exit 64 ;;
|
|
30
32
|
esac
|
|
31
33
|
shift
|
|
32
34
|
done
|
|
33
35
|
|
|
36
|
+
if [ "$GUARD" = true ] && [ "$TARGET_MODE" != "global" ]; then
|
|
37
|
+
echo "--guard requiere --global: las extensiones de proyecto solo cargan si el proyecto es de confianza." >&2
|
|
38
|
+
exit 64
|
|
39
|
+
fi
|
|
40
|
+
|
|
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
|
|
43
|
+
exit 1
|
|
44
|
+
fi
|
|
45
|
+
|
|
34
46
|
TTY_DEV=""
|
|
35
47
|
if [ -c /dev/tty ]; then TTY_DEV="/dev/tty"; fi
|
|
36
48
|
|
|
@@ -181,6 +193,9 @@ case "$STRATEGY" in
|
|
|
181
193
|
;;
|
|
182
194
|
esac
|
|
183
195
|
|
|
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
|
|
198
|
+
|
|
184
199
|
# 4. Deployment helpers (semantics mirror bin/cli.js: manifest.tsv is the SSOT)
|
|
185
200
|
MANIFEST="$SRC/manifest.tsv"
|
|
186
201
|
[ -f "$MANIFEST" ] || { echo "manifest.tsv no encontrado en $SRC" >&2; exit 1; }
|
|
@@ -232,10 +247,11 @@ TAB="$(printf '\t')"
|
|
|
232
247
|
DEPLOYED=""
|
|
233
248
|
while IFS="$TAB" read -r scope tgt kind src dest mode; do
|
|
234
249
|
case "$scope" in ""|\#*) continue ;; esac
|
|
235
|
-
[ "$scope" = "$TARGET_MODE" ]
|
|
250
|
+
if [ "$scope" != "$TARGET_MODE" ] && ! { [ "$GUARD" = true ] && [ "$scope" = "${TARGET_MODE}-guard" ]; }; then continue; fi
|
|
236
251
|
is_selected "$tgt" || continue
|
|
237
252
|
case "$kind" in
|
|
238
253
|
file) write_instruction "$SRC/$src" "$BASE_DIR/$dest" "${mode:-}" ;;
|
|
254
|
+
settings-hook) node "$SRC/guard/claude/merge-settings.js" "$SRC/$src" "$BASE_DIR/$dest" ;;
|
|
239
255
|
dir)
|
|
240
256
|
if [ "$src" = "skills" ]; then copy_dir "$SRC/$src" "$BASE_DIR/$dest" skip-extras
|
|
241
257
|
else copy_dir "$SRC/$src" "$BASE_DIR/$dest"; fi
|
package/manifest.tsv
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# Deployment manifest (SSOT for bin/cli.js and install.sh).
|
|
2
2
|
# Columns (tab-separated): scope target kind src dest [mode]
|
|
3
3
|
# scope: local (dest relative to project root) | global (dest relative to $HOME)
|
|
4
|
+
# | global-guard (dest relative to $HOME; deployed only with --global --guard)
|
|
4
5
|
# kind: file (instruction file; a divergent existing dest is saved as .bak) | dir (mirror directory)
|
|
6
|
+
# | settings-hook (merge the hook in src into the Claude Code settings.json at dest)
|
|
5
7
|
# mode: if-missing (file kind only: never overwrite an existing dest)
|
|
6
8
|
# Target "agents" = the cross-tool Agent Skills location (.agents/skills), read natively by
|
|
7
9
|
# Pi, OpenCode, Codex, Copilot and Cursor. Claude Code reads .claude/skills instead.
|
|
@@ -23,3 +25,7 @@ global codex file AGENTS.md .codex/AGENTS.md
|
|
|
23
25
|
global copilot file AGENTS.md .copilot/copilot-instructions.md
|
|
24
26
|
global commandcode file AGENTS.md .commandcode/AGENTS.md
|
|
25
27
|
global commandcode dir skills .commandcode/skills
|
|
28
|
+
global-guard pi-guard dir guard/pi/lah-guard .pi/agent/extensions/lah-guard
|
|
29
|
+
global-guard claude-guard dir guard/claude/lah-guard .claude/hooks/lah-guard
|
|
30
|
+
global-guard claude-guard settings-hook guard/claude/hook.json .claude/settings.json
|
|
31
|
+
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
|
+
"version": "1.3.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": {
|
|
@@ -23,6 +23,9 @@
|
|
|
23
23
|
"profile-extras.txt",
|
|
24
24
|
"adapters/",
|
|
25
25
|
"skills/",
|
|
26
|
+
"guard/claude/",
|
|
27
|
+
"guard/pi/",
|
|
28
|
+
"guard/codex/",
|
|
26
29
|
"AGENTS.md",
|
|
27
30
|
"CLAUDE.md",
|
|
28
31
|
"templates/",
|
|
@@ -12,12 +12,13 @@ Task: the arguments given with this invocation (default: the first pending slice
|
|
|
12
12
|
## Preconditions
|
|
13
13
|
1. `.tasks/current.md` has a `- [ ]` item. If not, halt and ask the user to run `plan-flow` first.
|
|
14
14
|
2. `git branch --show-current` is not `main`/`master`. If it is, run `git switch -c feature/<task-slug>` before touching any file.
|
|
15
|
+
3. Every file the slice will edit is clean in `git status --short`. If not, ask the user to commit or stash it first: the Circuit Breaker revert would discard their edits.
|
|
15
16
|
|
|
16
17
|
## Change budget
|
|
17
18
|
Before editing, forecast the slice's added + deleted lines. Above 400 changed lines, split the slice into smaller work units, or report the overage with its reason. Never shrink the diff by deleting tests, docs or comments, or by compressing code.
|
|
18
19
|
|
|
19
20
|
## Per slice (strictly sequential, only the slice's files)
|
|
20
|
-
1. Load the skills the slice names.
|
|
21
|
+
1. Load the skills the slice names; skip any that are not installed.
|
|
21
22
|
2. **Feature:** RED (write/run the test, log the failure) → GREEN (minimal implementation) → REFACTOR (strict typing, no dead code, names match `GLOSSARY.md`).
|
|
22
23
|
3. **Defect:** follow the `diagnosing-bugs` skill: reproduce (RED) → minimize → hypothesize in writing → instrument → fix → verify and remove instrumentation.
|
|
23
24
|
4. No package installs unless the plan lists them.
|
|
@@ -14,7 +14,7 @@ Task: the arguments given with this invocation. Read-only architect: inspect, de
|
|
|
14
14
|
2. **Size gate:** ≤ 1 file, cosmetic or < 30 lines → declare an **Inline Task** with a one-step guideline; skip slicing.
|
|
15
15
|
3. **Ground truth:** read `GLOSSARY.md` (if present) and the active manifest (`package.json`, `go.mod`, `Cargo.toml`, `pyproject.toml`, `Makefile`) for real test/lint commands. Verify paths, exports and signatures before citing them.
|
|
16
16
|
4. **Design:** deep modules, minimal public interfaces, no shallow pass-through layers.
|
|
17
|
-
5. **Slice:** feature-complete units (e.g. migration + model + service + tests). Each defines its RED state (failing test) first and names the skills it needs (`testing`, `security-audit`, `
|
|
17
|
+
5. **Slice:** feature-complete units (e.g. migration + model + service + tests). Each defines its RED state (failing test) first and names the skills it needs (`testing`, `security-audit`, `diagnosing-bugs`; `db-migration`, `impeccable` if installed).
|
|
18
18
|
6. **Persist** the plan to `.tasks/current.md`, then tell the user to run `orchestrate`.
|
|
19
19
|
|
|
20
20
|
## Output format
|
package/skills/review/SKILL.md
CHANGED
|
@@ -15,7 +15,7 @@ disable-model-invocation: true
|
|
|
15
15
|
* **Smells:** cyclomatic complexity > 10, functions > 30 lines, shallow wrappers, dead code.
|
|
16
16
|
4. Verify the diff fulfils the planned slice with no scope creep.
|
|
17
17
|
If any slice is `Risk: high`, run this review in a fresh context (subagent or new session) so it does not judge code it just wrote; if the host has neither, state that the review ran in the authoring context.
|
|
18
|
-
Record the hash of the diff you judged (`git add -N <new files>`, then `git diff HEAD | git hash-object --stdin`) in the verdict; a later change to that hash needs a new review.
|
|
18
|
+
Record the hash of the diff you judged (`git add -N <new files>`, then `git diff HEAD | git hash-object --stdin`) in the verdict; a later change to that hash needs a new review. If the work is already committed, `git diff HEAD` is empty and always hashes the same: hash `git diff <base>...HEAD` instead.
|
|
19
19
|
5. Verdict: any Blocker/Critical → list required fixes and block `commit`. Clean → approve and tell the user to run `commit`.
|
|
20
20
|
WARNING and SUGGESTION are listed once in the verdict. They never trigger fixes or another review round.
|
|
21
21
|
|