lean-agent-harness 0.0.0-stage → 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.
Files changed (45) hide show
  1. package/AGENTS.md +34 -0
  2. package/CHANGELOG.md +54 -0
  3. package/CLAUDE.md +12 -0
  4. package/GLOSSARY.md +53 -0
  5. package/LICENSE +21 -0
  6. package/README.md +92 -2
  7. package/adapters/opencode/commands/audit-code.md +5 -0
  8. package/adapters/opencode/commands/commit.md +5 -0
  9. package/adapters/opencode/commands/orchestrate.md +5 -0
  10. package/adapters/opencode/commands/plan-flow.md +5 -0
  11. package/adapters/opencode/commands/review.md +5 -0
  12. package/bin/cli.js +310 -0
  13. package/guard/claude/hook.json +7 -0
  14. package/guard/claude/lah-guard/core.js +101 -0
  15. package/guard/claude/lah-guard/index.js +76 -0
  16. package/guard/claude/lah-guard/policy.json +33 -0
  17. package/guard/claude/merge-settings.js +70 -0
  18. package/guard/codex/lah.rules +74 -0
  19. package/guard/pi/lah-guard/core.js +101 -0
  20. package/guard/pi/lah-guard/index.js +49 -0
  21. package/guard/pi/lah-guard/policy.json +33 -0
  22. package/install.sh +263 -0
  23. package/manifest.tsv +31 -0
  24. package/package.json +54 -4
  25. package/profile-extras.txt +6 -0
  26. package/skills/audit-code/SKILL.md +14 -0
  27. package/skills/audit-code/agents/openai.yaml +2 -0
  28. package/skills/code-review/SKILL.md +42 -0
  29. package/skills/commit/SKILL.md +15 -0
  30. package/skills/commit/agents/openai.yaml +2 -0
  31. package/skills/db-migration/SKILL.md +40 -0
  32. package/skills/diagnosing-bugs/SKILL.md +32 -0
  33. package/skills/diagram-design/SKILL.md +43 -0
  34. package/skills/diagram-design/references/template.md +33 -0
  35. package/skills/humanizer/SKILL.md +30 -0
  36. package/skills/impeccable/SKILL.md +36 -0
  37. package/skills/orchestrate/SKILL.md +38 -0
  38. package/skills/orchestrate/agents/openai.yaml +2 -0
  39. package/skills/plan-flow/SKILL.md +37 -0
  40. package/skills/plan-flow/agents/openai.yaml +2 -0
  41. package/skills/review/SKILL.md +22 -0
  42. package/skills/review/agents/openai.yaml +2 -0
  43. package/skills/security-audit/SKILL.md +32 -0
  44. package/skills/testing/SKILL.md +28 -0
  45. package/templates/GLOSSARY.md +11 -0
package/AGENTS.md ADDED
@@ -0,0 +1,34 @@
1
+ # Agent Configuration
2
+
3
+ Single source of truth for all coding agents. Engineering rigor, deterministic execution, zero-compromise delivery.
4
+
5
+ ## 1. Core Principles
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.
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.
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.
10
+ * **Deep Modules:** High functional depth behind minimal interfaces. No shallow wrappers, anemic layers, or premature fragmentation.
11
+ * **One Question at a Time:** When scope is ambiguous, ask exactly ONE question on the current decision, with a default answerable in one word. Never list questions.
12
+ * **Manifest Pre-flight:** Never assume signatures, versions, or test commands. Read the active manifest (`package.json`, `go.mod`, `pyproject.toml`, `Cargo.toml`, `composer.json`, `Makefile`) first.
13
+ * **Test-First:** Write and run the test before the implementation: RED, then GREEN, then REFACTOR. Never claim a passing test you did not run.
14
+ * **Evidence:** Verification claims must quote the exact terminal summary line (e.g. `Tests: 28 passed, 28 total`).
15
+ * **Stubborn bugs:** use the `diagnosing-bugs` skill instead of blind patching.
16
+
17
+ ## 2. Work Sizing
18
+
19
+ * **Inline:** ≤ 1 file, cosmetic, < 30 lines, auditable via `git diff`. Execute immediately.
20
+ * **Tracked:** architectural uncertainty, multi-step work, or **high-risk** change (auth/authz, data migration or deletion, secrets/config, public interface, concurrency). Use the workflow below, grouping cohesive feature-complete slices (migration + model + service + tests), never micro-slices.
21
+ * **State:** the plan and `- [ ]` checklist live in `.tasks/current.md` so a compacted session resumes without re-asking. Delete it after a clean `commit`.
22
+ * **Branch:** tracked work happens on `feature/<task-slug>`, never `main`/`master`.
23
+
24
+ Workflow skills (explicit invocation only): `plan-flow <task>` → `orchestrate` → `review` → `commit [hint]`; plus `audit-code [path]`. Skills are referenced by name; each agent resolves them from its own skills directory.
25
+
26
+ ## 3. Hard Rules
27
+
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.
29
+ * **Zero-Hang:** Never block on stdin: use non-interactive flags (`-y`, `--no-interaction`, `-m "<msg>"`); no interactive editors or `sudo`.
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`).
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.
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.
33
+ * **Destructive commands** (`rm -rf`, DB drops/truncation, `git reset --hard`, `git push --force`) require explicit human confirmation.
34
+ * **Slice rollback:** a slice that fails its Definition of Done is reverted to the last clean passing state.
package/CHANGELOG.md ADDED
@@ -0,0 +1,54 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
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
+
28
+ ## [1.2.0]
29
+
30
+ ### Added
31
+
32
+ - `--profile core|full` in both installers. `core` skips the skills listed in `profile-extras.txt`.
33
+ - Risk tiers (`low` | `high`) on every planned slice, with a fresh-context verifier for high-risk slices.
34
+ - 400 changed-lines budget per slice, defined in `orchestrate` and enforced at `commit`.
35
+ - Verification evidence bound to a hash of the working diff, so it goes stale after any edit.
36
+ - `install.sh` env vars: `LAH_VERSION` pins a release tag, `LAH_SHA256` verifies the downloaded archive and aborts on mismatch.
37
+
38
+ ### Changed
39
+
40
+ - Standing token cost reduced; each `SKILL.md` capped at 3000 bytes, with detail moved to `references/`.
41
+ - `diagram-design` split into a skill and `references/template.md`.
42
+
43
+ ### Fixed
44
+
45
+ - `install.sh --auto` selects the detected environments.
46
+ - Corrected the `curl` install URL.
47
+ - A divergent `AGENTS.md`/`CLAUDE.md` no longer overwrites an earlier `.bak`; later backups become `.bak.1`, `.bak.2`, and so on.
48
+ - `manifest.tsv` rows with the wrong column count now fail with the offending line number.
49
+
50
+ ## [1.1.0]
51
+
52
+ ### Changed
53
+
54
+ - `bin/cli.js` reworked and package metadata prepared for the first npm release.
package/CLAUDE.md ADDED
@@ -0,0 +1,12 @@
1
+ # Claude Code Project Configuration
2
+
3
+ Single source of truth is defined in `AGENTS.md`. All directives, subagents, skills, and lifecycle commands apply here.
4
+
5
+ Read and adhere strictly to:
6
+ @AGENTS.md
7
+
8
+ ## Fast Command Reference
9
+ - `/plan-flow <task>`: Read-only architecture analysis & ODD milestone checklist.
10
+ - `/orchestrate <task>`: Step-by-step implementation, RED-GREEN loop, and DoD validation.
11
+ - `/review [target]`: Risk-based git diff audit against SonarQube quality gates.
12
+ - `/commit [hint]`: Quality gate verification and atomic Conventional Commit.
package/GLOSSARY.md ADDED
@@ -0,0 +1,53 @@
1
+ # Domain Glossary & Ubiquitous Language
2
+
3
+ Single source of truth for the domain vocabulary of this project. Both human engineers and coding agents must align terminology here to prevent conceptual divergence and verbose circumlocution.
4
+
5
+ > **For client projects installed via this harness:** replace the harness terms below with your business domain vocabulary, keeping the table format. The installed `GLOSSARY.md` is your project's glossary, not this repo's.
6
+
7
+ ---
8
+
9
+ ## Harness Core Entities & Concepts
10
+
11
+ | Term | Ubiquitous Definition | Canonical Representation | Constraints / Invariants |
12
+ | :--- | :--- | :--- | :--- |
13
+ | **Harness** | The portable rule + command + skill bundle deployed across coding agents. | `lean-agent-harness` root | Deployed files are package-derived; never hand-edit a deployed copy without syncing upstream. |
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
+ | **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
+ | **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. |
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
+ | **Slice** | One feature-complete ODD unit (e.g., migration + model + service + tests). | `- [ ] Slice N:` checklist item | No fragmented single-line micro-slices. |
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. |
21
+ | **RED / GREEN / REFACTOR** | Test-first cycle: prove the gap with a failing test, implement minimally to pass, refactor for SOLID. | `testing` skill | Never assert GREEN without running the runner. |
22
+ | **Workflow Skill** | A skill invoked explicitly (`plan-flow`, `orchestrate`, `review`, `audit-code`, `commit`). It carries `disable-model-invocation: true`, so its description costs no standing tokens. | `skills/<name>/SKILL.md` | Role instructions (Planner, Orchestrator) live inside the skill; no separate agent or command files. |
23
+ | **Skill** | A self-contained Agent Skills playbook (`name` + `description` frontmatter) loaded on demand. | `skills/<name>/SKILL.md` | `name` equals the folder; keep each around 70 lines or fewer. |
24
+ | **Inline Task** | Work small enough to skip planning ceremony (≤ 1 file, < 30 lines, cosmetic). | `AGENTS.md` § 2 | Auditable through `git diff` alone. |
25
+ | **Risk Tier** | `low` or `high` tag on each planned slice. `high` = a high-risk item named in `AGENTS.md` § 2 (auth/authz, data migration or deletion, secrets/config, public interface, concurrency). | `Risk:` field in `plan-flow` output | High-risk slices get a fresh-context verifier (`orchestrate`) and review (`review`); low-risk slices keep the single DoD gate. |
26
+ | **Change Budget** | Limit of 400 changed lines per work unit. | `orchestrate` § Change budget (enforced by `commit`) | Rule text lives only in `orchestrate`. |
27
+ | **Blocker** | A review finding (Blocker or Critical) that blocks `commit` until fixed. | `review` verdict | WARNING and SUGGESTION never block and never trigger fixes. |
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
+ | **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
+ | **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. |
34
+
35
+ ---
36
+
37
+ ## Architectural Seams & Boundaries
38
+
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.
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.
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.
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.
43
+
44
+ ---
45
+
46
+ ## Deprecated / Forbidden Jargon
47
+
48
+ * *Do not say:* "the installer script things".
49
+ *Use instead:* "the shell installer (`install.sh`)" or "the CLI (`bin/cli.js`)".
50
+ * *Do not say:* "the md file with the rules".
51
+ *Use instead:* "`AGENTS.md` (SSOT)".
52
+ * *Do not say:* "the todo file".
53
+ *Use instead:* "`.tasks/current.md` (ephemeral execution state)".
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lnardev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ # Lean Agent Harness (`lah`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
+
7
+ ## How it works
8
+
9
+ Everything ships as [Agent Skills](https://agentskills.io) (`skills/<name>/SKILL.md`, with `name` and `description` frontmatter) plus a single `AGENTS.md`. There are no separate command or subagent files, so there is nothing to translate per tool.
10
+
11
+ * **Domain skills** (`testing`, `security-audit`, `db-migration`, `diagnosing-bugs`, `code-review`, `impeccable`, `humanizer`, `diagram-design`) load on demand when the task matches their description.
12
+ * **Workflow skills** (`plan-flow`, `orchestrate`, `review`, `audit-code`, `commit`) set `disable-model-invocation: true` (plus `agents/openai.yaml` for Codex). Claude Code, Pi, Cursor and Codex never offer them to the model, so their descriptions cost no tokens until you call them. OpenCode and Copilot ignore the flag and list them (one short line each). The Planner and Orchestrator roles live inside `plan-flow` and `orchestrate`. Slices tagged `Risk: high` are verified and reviewed in a fresh context; every `SKILL.md` stays under 3000 bytes and long detail loads from `references/`.
13
+
14
+ ```text
15
+ plan-flow <task> → orchestrate → review [target] → commit [hint] audit-code [path]
16
+ (read-only plan) (RED-GREEN, DoD) (audit git diff) (atomic commit) (security scan)
17
+ ```
18
+
19
+ How you invoke a workflow skill depends on the tool: `/plan-flow` in Claude Code, Cursor and OpenCode (through a command stub in `adapters/`), `/skill:plan-flow` in Pi, `$plan-flow` in Codex.
20
+
21
+ ## Where files go
22
+
23
+ | Scope | Files |
24
+ | :--- | :--- |
25
+ | Project | `AGENTS.md`, `CLAUDE.md` (imports `@AGENTS.md`), `GLOSSARY.md` (only if missing) at the root; skills in `.claude/skills/` and `.agents/skills/`; OpenCode command stubs in `.opencode/commands/` |
26
+ | User (`--global`) | `~/.claude/{CLAUDE.md,AGENTS.md,skills}`, `~/.agents/skills`, `~/.pi/agent/AGENTS.md`, `~/.config/opencode/{AGENTS.md,commands}`, `~/.codex/AGENTS.md`, `~/.copilot/copilot-instructions.md`, `~/.commandcode/{AGENTS.md,skills}` |
27
+
28
+ `.agents/skills` is read natively by Pi, OpenCode, Codex, Copilot and Cursor. Claude Code reads `.claude/skills`. Every destination is a row in `manifest.tsv`, which both installers read.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npx lean-agent-harness # into the current project
34
+ npx lean-agent-harness --global # into your home directory
35
+ ```
36
+
37
+ Without Node.js:
38
+
39
+ ```bash
40
+ curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/install.sh | bash
41
+ curl -fsSL https://raw.githubusercontent.com/lnardev/lean-agent-harness/main/install.sh | bash -s -- --global --auto
42
+ ```
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`.
45
+
46
+ **Pinning and verifying the `curl` install.** The one-liner runs the `main` branch unless you pin it:
47
+
48
+ ```bash
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
+ ```
51
+
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.
53
+
54
+ **Profiles.** `--profile core` skips the skills listed in `profile-extras.txt` (`impeccable`, `humanizer`, `diagram-design`, `db-migration`), whose descriptions cost standing tokens in every project. `full` is the default. Both installers read the same file.
55
+
56
+ ```bash
57
+ npx lean-agent-harness --global --profile core
58
+ ```
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
+
66
+ ```bash
67
+ npm test # installs with both installers and asserts identical output trees
68
+ ```
69
+
70
+ ## Repository layout
71
+
72
+ ```text
73
+ AGENTS.md Single source of rules
74
+ CLAUDE.md Imports AGENTS.md for Claude Code
75
+ GLOSSARY.md Harness vocabulary (this repo only)
76
+ templates/ GLOSSARY.md seed deployed to client projects when missing
77
+ manifest.tsv Destinations per target and scope (read by both installers)
78
+ profile-extras.txt Skills omitted by --profile core (read by both installers)
79
+ skills/ Domain and workflow skills
80
+ adapters/opencode/ Command stubs that point OpenCode slash commands at skills
81
+ bin/cli.js npx installer
82
+ install.sh curl installer
83
+ ```
84
+
85
+ ## Principles
86
+
87
+ * **Token economy:** short standing rules, on-demand skills, explicit-only workflows.
88
+ * **Slices (ODD):** complex work becomes small, feature-complete, reviewable slices tracked in `.tasks/current.md`.
89
+ * **Strict typing, no placeholders, dependency lockdown, confirmation before destructive commands.** Full text in `AGENTS.md`.
90
+
91
+ ## License
92
+
93
+ MIT © [lnardev](https://github.com/lnardev)
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Deep static security audit of a path or the whole workspace. Invoke explicitly.
3
+ argument-hint: "[path]"
4
+ ---
5
+ Load the `audit-code` skill and follow it. Arguments: $ARGUMENTS
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Verifies quality gates and creates an atomic Conventional Commit. Invoke explicitly.
3
+ argument-hint: "[hint]"
4
+ ---
5
+ Load the `commit` skill and follow it. Arguments: $ARGUMENTS
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Executes the .tasks/current.md checklist slice by slice with RED-GREEN-REFACTOR and the DoD gate. Invoke explicitly after a plan exists.
3
+ argument-hint: "[task or slice]"
4
+ ---
5
+ Load the `orchestrate` skill and follow it. Arguments: $ARGUMENTS
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Read-only analysis that produces an ODD slice plan in .tasks/current.md. Invoke explicitly before non-trivial implementation.
3
+ argument-hint: "<task>"
4
+ ---
5
+ Load the `plan-flow` skill and follow it. Arguments: $ARGUMENTS
@@ -0,0 +1,5 @@
1
+ ---
2
+ description: Risk-based audit of uncommitted changes against quality gates before committing. Invoke explicitly.
3
+ argument-hint: "[target]"
4
+ ---
5
+ Load the `review` skill and follow it. Arguments: $ARGUMENTS
package/bin/cli.js ADDED
@@ -0,0 +1,310 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ /**
5
+ * Lean Agent Harness — deployment CLI (npx).
6
+ *
7
+ * Manifest-driven installer: every supported environment is declared once in a
8
+ * declarative table and deployed by a single engine. No per-platform copy-paste.
9
+ *
10
+ * Modes:
11
+ * (default) deploy into the current project
12
+ * --global deploy into the user home (~/.claude, ~/.pi, ~/.config/opencode, ...)
13
+ *
14
+ * Flags: --help | -h | --version | -v | --global | -g | --local | -l | --guard (with --global)
15
+ */
16
+
17
+ const fs = require("fs");
18
+ const os = require("os");
19
+ const path = require("path");
20
+
21
+ const { version } = require("../package.json");
22
+ const { mergeHook } = require("../guard/claude/merge-settings.js");
23
+
24
+ const PKG_ROOT = path.resolve(__dirname, "..");
25
+
26
+ /**
27
+ * @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
30
+ * @property {string} src Path relative to the package root
31
+ * @property {string} dest Path relative to the target base
32
+ * @property {string} mode "" or "if-missing" (file kind: never overwrite an existing dest)
33
+ *
34
+ * @typedef {Object} Target
35
+ * @property {string} name Human-readable label
36
+ * @property {string} base Destination base directory (project root or home)
37
+ * @property {Entry[]} entries
38
+ */
39
+
40
+ const LABELS = {
41
+ core: "Core",
42
+ claude: "Claude Code",
43
+ agents: "Agent Skills (.agents: Pi · OpenCode · Codex · Copilot · Cursor)",
44
+ pi: "Pi",
45
+ opencode: "OpenCode",
46
+ codex: "Codex",
47
+ copilot: "Copilot",
48
+ commandcode: "CommandCode",
49
+ "pi-guard": "Pi guard",
50
+ "claude-guard": "Claude Code guard",
51
+ "codex-guard": "Codex guard",
52
+ };
53
+
54
+ /**
55
+ * Parse manifest.tsv (shared with install.sh).
56
+ * @param {string} text
57
+ * @returns {{scope: string, target: string, entry: Entry}[]}
58
+ */
59
+ function parseManifest(text) {
60
+ return text
61
+ .replace(/\r/g, "")
62
+ .split("\n")
63
+ .map((line, index) => ({ line, lineNumber: index + 1 }))
64
+ .filter(({ line }) => line.trim() !== "" && !line.startsWith("#"))
65
+ .map(({ line, lineNumber }) => {
66
+ const columns = line.split("\t");
67
+ if (columns.length !== 5 && columns.length !== 6) {
68
+ throw new Error(`manifest.tsv line ${lineNumber}: expected 5 or 6 columns, got ${columns.length}`);
69
+ }
70
+ const [scope, target, kind, src, dest, mode = ""] = columns;
71
+ return {
72
+ scope,
73
+ target,
74
+ entry: {
75
+ kind,
76
+ src,
77
+ dest,
78
+ mode: mode.trim(),
79
+ },
80
+ };
81
+ });
82
+ }
83
+
84
+ /**
85
+ * @param {string} scope
86
+ * @param {string} base
87
+ * @returns {Target[]}
88
+ */
89
+ function targetsFor(scope, base) {
90
+ const rows = parseManifest(fs.readFileSync(path.join(PKG_ROOT, "manifest.tsv"), "utf8"));
91
+ /** @type {Map<string, Target>} */
92
+ const byId = new Map();
93
+ for (const row of rows.filter((r) => r.scope === scope)) {
94
+ if (!byId.has(row.target)) {
95
+ byId.set(row.target, { name: LABELS[row.target] || row.target, base, entries: [] });
96
+ }
97
+ byId.get(row.target).entries.push(row.entry);
98
+ }
99
+ return [...byId.values()];
100
+ }
101
+
102
+ /** Declarative deployment manifest, resolved against the current environment. */
103
+ const TARGETS = {
104
+ local: () => targetsFor("local", process.env.LAH_FAKE_CWD || process.cwd()),
105
+ global: (home) => targetsFor("global", home),
106
+ "global-guard": (home) => targetsFor("global-guard", home),
107
+ };
108
+
109
+ const c = process.stdout.isTTY
110
+ ? { reset: "\x1b[0m", bold: "\x1b[1m", green: "\x1b[32m", cyan: "\x1b[36m", dim: "\x1b[2m" }
111
+ : { reset: "", bold: "", green: "", cyan: "", dim: "" };
112
+
113
+ const PROFILES = ["core", "full"];
114
+
115
+ /**
116
+ * Skill folders omitted by the "core" profile (profile-extras.txt, shared with install.sh).
117
+ * @param {string} profile
118
+ * @returns {Set<string>}
119
+ */
120
+ function excludedSkills(profile) {
121
+ if (profile !== "core") return new Set();
122
+ const text = fs.readFileSync(path.join(PKG_ROOT, "profile-extras.txt"), "utf8");
123
+ return new Set(
124
+ text
125
+ .replace(/\r/g, "")
126
+ .split("\n")
127
+ .filter((line) => line.trim() !== "" && !line.startsWith("#")),
128
+ );
129
+ }
130
+
131
+ /**
132
+ * @param {string} src
133
+ * @param {string} dest
134
+ * @param {Set<string>} [exclude] top-level entries of src to skip (dotfiles are always skipped)
135
+ */
136
+ function copyDir(src, dest, exclude = new Set()) {
137
+ fs.cpSync(src, dest, {
138
+ recursive: true,
139
+ force: true,
140
+ filter: (from) => {
141
+ if (path.dirname(from) !== src) return true;
142
+ const name = path.basename(from);
143
+ return !name.startsWith(".") && !exclude.has(name);
144
+ },
145
+ });
146
+ }
147
+
148
+ /**
149
+ * First free backup name: "<name>.bak", then "<name>.bak.1", "<name>.bak.2", ...
150
+ * Existing backups are never overwritten.
151
+ *
152
+ * @param {string} destPath
153
+ * @returns {string}
154
+ */
155
+ function backupPath(destPath) {
156
+ let candidate = `${destPath}.bak`;
157
+ for (let n = 1; fs.existsSync(candidate); n++) candidate = `${destPath}.bak.${n}`;
158
+ return candidate;
159
+ }
160
+
161
+ /**
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).
165
+ *
166
+ * @param {string} srcPath
167
+ * @param {string} destPath
168
+ * @param {string} [mode]
169
+ */
170
+ function writeInstruction(srcPath, destPath, mode = "") {
171
+ if (mode === "if-missing" && fs.existsSync(destPath)) return;
172
+ fs.mkdirSync(path.dirname(destPath), { recursive: true });
173
+ try {
174
+ const current = fs.readFileSync(destPath, "utf8");
175
+ if (current !== fs.readFileSync(srcPath, "utf8")) {
176
+ fs.copyFileSync(destPath, backupPath(destPath));
177
+ }
178
+ } catch (err) {
179
+ if (err.code !== "ENOENT") {
180
+ throw err;
181
+ }
182
+ }
183
+ fs.copyFileSync(srcPath, destPath);
184
+ }
185
+
186
+ /**
187
+ * @param {Target} t
188
+ * @param {Set<string>} [exclude] skill folders to skip (profile)
189
+ * @returns {boolean} success
190
+ */
191
+ function deployTarget(t, exclude = new Set()) {
192
+ try {
193
+ for (const { kind, src, dest, mode } of t.entries) {
194
+ const from = path.join(PKG_ROOT, src);
195
+ const to = path.join(t.base, dest);
196
+ if (kind === "file") writeInstruction(from, to, mode);
197
+ else if (kind === "settings-hook") mergeHook(from, to);
198
+ else copyDir(from, to, src === "skills" ? exclude : new Set());
199
+ }
200
+ const label = t.base.replace(process.env.LAH_FAKE_HOME || os.homedir(), "~");
201
+ console.log(` ${c.green}✔${c.reset} ${label} (${t.name})`);
202
+ return true;
203
+ } catch (err) {
204
+ console.error(` ${c.bold}\x1b[31m✖${c.reset} ${t.name}: ${err.message}`);
205
+ return false;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * @param {Target[]} targets
211
+ * @param {string} profile
212
+ * @returns {{ok: number, failed: number}}
213
+ */
214
+ function deployAll(targets, profile) {
215
+ const exclude = excludedSkills(profile);
216
+ let ok = 0;
217
+ let failed = 0;
218
+ for (const t of targets) (deployTarget(t, exclude) ? ok++ : failed++);
219
+ return { ok, failed };
220
+ }
221
+
222
+ function deployLocal(profile = "full") {
223
+ console.log(`\nModo: ${c.bold}Local${c.reset} (${c.dim}${process.env.LAH_FAKE_CWD || process.cwd()}${c.reset})`);
224
+ return deployAll(TARGETS.local(), profile);
225
+ }
226
+
227
+ function deployGlobal(profile = "full", guard = false) {
228
+ const home = process.env.LAH_FAKE_HOME || os.homedir();
229
+ console.log(`\nModo: ${c.bold}Global${c.reset} (${c.dim}${home}${c.reset})`);
230
+ return deployAll([...TARGETS.global(home), ...(guard ? TARGETS["global-guard"](home) : [])], profile);
231
+ }
232
+
233
+ const HELP = `Lean Agent Harness v${version}
234
+ Despliegue multi-plataforma de reglas, comandos y skills para agentes de código.
235
+
236
+ Uso:
237
+ npx lean-agent-harness Instalar en el proyecto actual (local)
238
+ npx lean-agent-harness --global Instalar en el home del usuario (~/.claude, ...)
239
+ lean | lah Alias si se instaló globalmente
240
+
241
+ Flags:
242
+ -l, --local Desplegar en el proyecto actual (comportamiento por defecto)
243
+ -g, --global Desplegar en carpetas de usuario (~/)
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
247
+ -h, --help Mostrar esta ayuda
248
+ -v, --version Mostrar versión
249
+
250
+ Entornos: Claude Code · Pi · CommandCode · OpenCode · Cursor · Codex · Copilot (destinos en manifest.tsv)
251
+ `;
252
+
253
+ /** @returns {number} exit code */
254
+ function main(argv) {
255
+ if (argv.includes("--help") || argv.includes("-h")) {
256
+ console.log(HELP);
257
+ return 0;
258
+ }
259
+ if (argv.includes("--version") || argv.includes("-v")) {
260
+ console.log(version);
261
+ return 0;
262
+ }
263
+
264
+ let profile = "full";
265
+ const rest = [...argv];
266
+ const at = rest.indexOf("--profile");
267
+ if (at !== -1) {
268
+ profile = rest[at + 1] ?? "";
269
+ rest.splice(at, 2);
270
+ if (!PROFILES.includes(profile)) {
271
+ console.error(`Perfil desconocido: "${profile}". Usa: ${PROFILES.join(" | ")}`);
272
+ return 1;
273
+ }
274
+ }
275
+
276
+ const validFlags = new Set(["--global", "-g", "--local", "-l", "--guard"]);
277
+ const unknownArgs = rest.filter((a) => !validFlags.has(a));
278
+
279
+ if (unknownArgs.length > 0) {
280
+ console.error(`Flag desconocido: ${unknownArgs.join(" ")}\n\n${HELP}`);
281
+ return 1;
282
+ }
283
+
284
+ const isGlobal = argv.includes("--global") || argv.includes("-g");
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);
291
+
292
+ if (failed > 0) return 1;
293
+ console.log(`\n${c.green}${c.bold}Done!${c.reset} Arnés desplegado correctamente.\n`);
294
+ return 0;
295
+ }
296
+
297
+ if (require.main === module) {
298
+ process.exit(main(process.argv.slice(2)));
299
+ }
300
+
301
+ module.exports = {
302
+ TARGETS,
303
+ parseManifest,
304
+ deployTarget,
305
+ deployLocal,
306
+ deployGlobal,
307
+ writeInstruction,
308
+ PKG_ROOT,
309
+ version,
310
+ };
@@ -0,0 +1,7 @@
1
+ {
2
+ "event": "PreToolUse",
3
+ "entry": {
4
+ "matcher": "Read|Edit|Write|MultiEdit|NotebookEdit|Grep|Bash",
5
+ "hooks": [{ "type": "command", "command": "node \"$HOME/.claude/hooks/lah-guard/index.js\"" }]
6
+ }
7
+ }