Skip to content
Back to search

ballast

Builds up to a goal in a field you have no expertise in: splits it into the foundations that goal actually needs, mobilizes what you already hold, learns what is missing, and leaves every solved path behind for the next goal. Nothing is called done until a check passes.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/svy04--ballast/badge.svg)](/listings/svy04--ballast)

HTML

<a href="/listings/svy04--ballast"><img src="/api/listings/svy04--ballast/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

/plugin marketplace add svy04/ballast
/plugin install ballast@ballast

Two lines in Claude Code and you are done. The hook runs on the `node` (≥ 18) already on your PATH; the other sixteen pieces are markdown skills. (The install id reads `plugin@marketplace` — both happen to be named ballast here.) For a guided first setup — no JSON in sight — say "set up ballast" or call `/ballast:setup`.

Pairing it with a style skill? ballast shapes what the model remembers and what counts as done, not how it talks, so terse-reply skills such as caveman sit beside it without conflict. The one place they meet is `memory/`: keep compression tools away from the ledger and knowledge files — the `memory-compress-guard` example rule guards exactly that. For plain-language replies, copy the example catalog's `reader-first` rule.

Using Codex instead? The same repository installs as a Codex plugin — `codex plugin marketplace add svy04/ballast`, then `codex plugin add ballast@ballast` — and the same hook runs there: Codex loads `hooks/hooks.json` once you trust it in `/hooks`. Without the plugin, a project-level `.codex/hooks.json` does the same, and the bundled `codex exec` wrapper stays for builds without hooks: [docs/CODEX.md](docs/CODEX.md).

<p align="center"> </p>

<p align="center"> <a href="#how-it-runs">How it runs</a> · <a href="#the-pieces">Pieces</a> · <a href="#quick-start">Quick start</a> · <a href="#philosophy">Philosophy</a> </p>

<details> <summary><strong>Specs</strong> — dependencies, what is enforced, what ships empty</summary>

- **Zero dependencies, zero network** — the hook is one script, imports only `fs`/`os`/`path`; it reads local files and prints. ballast itself sends nothing anywhere (the optional verifier/researcher commands are local CLIs you configure, and the separate verify script only spawns `node` to re-run the hook) - **One hook (four events) + sixteen skills** — only the hook is code-enforced, and the docs label which is which - **Ships empty, and says so** — every session opens with one line, `[ballast] hook live — N rules loaded`, zero at first; on messages the hook stays silent until a rule matches. [Quick start](#quick-start) is how rules get there. Standing cost: the sixteen skill descriptions are about 665 words; skill bodies load only when a skill is invoked - **Delivery log, ids only** — each delivery appends one JSON line (timestamp, rule ids, sizes — never prompt or tool text) to `~/.claude/ballast/log.jsonl`, rotated past ~512 KB; `--report` aggregates it into fires per rule and names the rules that never fired; `BALLAST_NO_LOG=1` turns it off - **[Hook verified on 20 cases](hooks/scripts/verify-hook.mjs)**, in five groups — delivery (keyword inject, silence on no match, block, legacy input fields) · failure (a broken catalog says so, and still never blocks; the manifest is in the shape Claude Code loads) · status line (with rules, without a catalog, with a broken one, after compaction) · log (ids only, never text; `BALLAST_NO_LOG` writes nothing) · tool layer and modes (injects, denies, silent for unnamed tools, out of prompts; the compaction reminder; `--report`/`--check` naming fired, dead and broken rules). The harness checks what the hook emits, not whether the model obeys; run `node hooks/scripts/verify-hook.mjs` in a clone to re-check - **MIT** — the whole mechanism is readable in an afternoon

</details>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 14 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "ballast",
  3. "description": "Builds up to a goal in a field you have no expertise in — learns the foundations it needs and keeps every solved path for the next goal.",
  4. "owner": {
  5. "name": "svy04"
  6. },
  7. "plugins": [
  8. {
  9. "name": "ballast",
  10. "source": "./",
  11. "description": "Builds up to a goal in a field you have no expertise in: splits it into the foundations that goal actually needs, mobilizes what you already hold, learns what is missing, and leaves every solved path behind for the next goal. Nothing is called done until a check passes."
  12. }
  13. ]
  14. }
README.md · README · 261 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # ballast
  2. **[한국어 문서 →](README.ko.md) · [简体中文 →](README.zh-CN.md)**
  3. ![ballast — a ship that holds steady because of the weight riding low in its hull](assets/banner.png)
  4. **ballast is a Claude Code and Codex plugin that takes a goal you have no expertise in, builds it up from the foundations, and carries it through — then keeps every solved path so the next goal starts further along.**
  5. A few weeks into working with Claude, this piles up:
  6. - **You give the same correction again next month**
  7. - **A settled decision reopens, or quietly changes**
  8. - **You act on an unsourced answer, and find out later**
  9. - **Your copy names a feature nobody built yet**
  10. - **"Done" turns out to mean Claude said so**
  11. - **What you shipped stalls its first reader**
  12. - **Another model's tidy summary lands as fact**
  13. - **You re-research what the project already wrote down**
  14. All eight have one cause: the weight sits in the conversation and nowhere else. Ships fix this by loading weight low in the hull, under everything else — that weight is called ballast. Here, it is rules, decisions, and verified facts riding in files, under the conversation.
  15. And it accumulates. A method you only found after dead ends, a fact that survived checking, a vague problem finally cut into pieces — each one stays, and the next goal starts on top of it. You do not dig the same hole twice.
  16. The smallest piece of that, live in a session — the first symptom on the list, with a rule you set once, weeks ago:
  17. ```
  18. > add a setup script — npm install and we're done
  19. [ballast] Standing rules that apply to this request:
  20. - Use pnpm here: This repo uses pnpm. npm install has broken the
  21. lockfile twice; write scripts and commands with pnpm.
  22. Claude: Using pnpm — your rule says npm broke the lockfile twice.
  23. The setup script runs pnpm install.
  24. ```
  25. The `[ballast]` block is the guaranteed part: "npm" matched your rule, so its full text arrived with this message. The reply line is illustrative — the hook guarantees delivery, not obedience.
  26. ## At a glance
  27. - **What it is**: a Claude Code / Codex CLI plugin — one hook script (node, zero dependencies, zero network) on four events (`UserPromptSubmit`, `PreToolUse`, `PreCompact`, `SessionStart`), plus sixteen markdown skills.
  28. - **What the hook does**: delivers the full text of your own standing rules from a JSON catalog into the request they match — at the prompt, at the tool call a rule names, and just before context compaction. Every delivery is logged as rule ids and counts, never as prompt text.
  29. - **What the skills cover**: an append-only decision ledger, verification labels for claims, a proof standard for external claims, goal decomposition, checkpoints, recall, corrections-into-rules (pin), rehearsal, delegated research, a knowledge base, memory scaffolding, skill authoring, an agent-owned schedule (fixed dates, event triggers, launch bundles), and three operations skills (setup, doctor, report).
  30. - **What it is not**: not multi-agent orchestration, not automatic memory collection or summarization, not provider switching or routing, not a style pack. You write the rules; the plugin delivers them.
  31. ## Install
  32. ```
  33. /plugin marketplace add svy04/ballast
  34. /plugin install ballast@ballast
  35. ```
  36. Two lines in Claude Code and you are done. The hook runs on the `node` (≥ 18) already on your PATH; the other sixteen pieces are markdown skills. (The install id reads `plugin@marketplace` — both happen to be named ballast here.) For a guided first setup — no JSON in sight — say "set up ballast" or call `/ballast:setup`.
  37. Pairing it with a style skill? ballast shapes what the model remembers and what counts as done, not how it talks, so terse-reply skills such as caveman sit beside it without conflict. The one place they meet is `memory/`: keep compression tools away from the ledger and knowledge files — the `memory-compress-guard` example rule guards exactly that. For plain-language replies, copy the example catalog's `reader-first` rule.
  38. Using Codex instead? The same repository installs as a Codex plugin — `codex plugin marketplace add svy04/ballast`, then `codex plugin add ballast@ballast` — and the same hook runs there: Codex loads `hooks/hooks.json` once you trust it in `/hooks`. Without the plugin, a project-level `.codex/hooks.json` does the same, and the bundled `codex exec` wrapper stays for builds without hooks: [docs/CODEX.md](docs/CODEX.md).
  39. <p align="center">
  40. <a href="CHANGELOG.md"><img src="https://img.shields.io/badge/version-0.11.0-blue" alt="Version 0.11.0"></a>
  41. <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
  42. </p>
  43. <p align="center">
  44. <a href="#how-it-runs">How it runs</a> ·
  45. <a href="#the-pieces">Pieces</a> ·
  46. <a href="#quick-start">Quick start</a> ·
  47. <a href="#philosophy">Philosophy</a>
  48. </p>
  49. <details>
  50. <summary><strong>Specs</strong> — dependencies, what is enforced, what ships empty</summary>
  51. - **Zero dependencies, zero network** — the hook is one script, imports only `fs`/`os`/`path`; it reads local files and prints. ballast itself sends nothing anywhere (the optional verifier/researcher commands are local CLIs you configure, and the separate verify script only spawns `node` to re-run the hook)
  52. - **One hook (four events) + sixteen skills** — only the hook is code-enforced, and the docs label which is which
  53. - **Ships empty, and says so** — every session opens with one line, `[ballast] hook live — N rules loaded`, zero at first; on messages the hook stays silent until a rule matches. [Quick start](#quick-start) is how rules get there. Standing cost: the sixteen skill descriptions are about 665 words; skill bodies load only when a skill is invoked
  54. - **Delivery log, ids only** — each delivery appends one JSON line (timestamp, rule ids, sizes — never prompt or tool text) to `~/.claude/ballast/log.jsonl`, rotated past ~512 KB; `--report` aggregates it into fires per rule and names the rules that never fired; `BALLAST_NO_LOG=1` turns it off
  55. - **[Hook verified on 20 cases](hooks/scripts/verify-hook.mjs)**, in five groups — delivery (keyword inject, silence on no match, block, legacy input fields) · failure (a broken catalog says so, and still never blocks; the manifest is in the shape Claude Code loads) · status line (with rules, without a catalog, with a broken one, after compaction) · log (ids only, never text; `BALLAST_NO_LOG` writes nothing) · tool layer and modes (injects, denies, silent for unnamed tools, out of prompts; the compaction reminder; `--report`/`--check` naming fired, dead and broken rules). The harness checks what the hook emits, not whether the model obeys; run `node hooks/scripts/verify-hook.mjs` in a clone to re-check
  56. - **MIT** — the whole mechanism is readable in an afternoon
  57. </details>
  58. ## How it runs
  59. Hand it something big — `/ballast:goal ship the pricing page` — and every piece attaches to that one goal, in order.
  60. **It starts from what is already held.** At the session's first reply, the recall skill has swept the files brain-init scaffolded on day one — index, knowledge, decisions, rules, skills, all five, past the first hit. The goal skill then splits the objective into branches and judges each one against that inventory.
  61. A covered branch must use its file: the pricing rule already in the catalog and the brand facts in `memory/knowledge/` come along as they are, and nothing already held gets re-researched. A bare branch makes learning its first task.
  62. **A bare branch starts with questions, not answers.** In a field you have never worked in, your sense of what matters is the least reliable thing you have. So the terrain scan collects what is argued, what is settled, and where beginners get burned, and lays them out as a map.
  63. Then the branch is cut top-down into a pyramid of atomic pieces: no overlaps, nothing missing, each leaf small enough to verify on its own. A sub-field exposed mid-work is registered by name the moment it appears. Unfilled is allowed; unnamed is not.
  64. **Leaves fill bottom-up, and nothing bears weight unverified.** Collection can be handed to a second CLI (researcher), whose findings arrive `hearsay` — it can fetch, but it cannot rule. Every leaf faces the verify gate — refuted first, sourced, labeled — and what survives lands in `memory/knowledge/`.
  65. The skeleton itself lives in `memory/goal/pricing-page.md`: the tree, its gaps, the next leaf. Tomorrow's session resumes from that file.
  66. **The work runs on prepared ground.** Quality is set before the work, not patched after it. Mid-work you correct Claude once — "prices include VAT" — and pin writes that into the rule catalog; the hook delivers it with every message that matches, and only those. A standing rule rides along just when its keywords appear.
  67. Anything said about the product outside the repo passes proof-standard first. External claims come from a truth file — a record of what verifiably works, evidence attached. No entry, no claim.
  68. **Done is a claim, so done passes a check.** A zero-context reader walks the deliverable cold (rehearsal); the check passes when a round comes back stall-free, and that round's log is the evidence. A passed check is a file that exists, a test that runs, an output actually inspected.
  69. What the goal solved then stays. Decisions go to the ledger, changed only by supersede — and only what the user actually said goes in; a reading of their silence stays in open questions.
  70. A procedure that will recur becomes a skill (skill-forge), and a pause becomes a thirty-second return (checkpoint). Next quarter's pricing page opens on the solved path.
  71. The same loop, drawn — boxes are pieces, cylinders are files that outlive the session:
  72. ```mermaid
  73. flowchart TD
  74. G["a goal arrives — /ballast:goal"] --> M{"mobilize:<br/>already held in rules,<br/>knowledge, skills?"}
  75. M -- "held → using it is mandatory" --> W["the work"]
  76. M -- "gap → learn first" --> L["terrain scan → top-down skeleton →<br/>bottom-up leaves, each verified"]
  77. L -. "collection delegated<br/>(optional) — returns hearsay" .-> X["researcher"] -.-> L
  78. L --> V["verify gate — refute first,<br/>a second model may argue back"] --> K[("memory/knowledge/<br/>labeled, sourced")]
  79. K --> W
  80. W -- "you correct Claude once" --> P["pin"] --> R[("rule catalog")]
  81. R -- "hook delivers on every<br/>matching message" --> W
  82. W -- "a solved path recurs" --> S["skill-forge →<br/>a skill file"] --> W
  83. W -- "pause" --> C[("CHECKPOINT.md")] -- "30-second return" --> W
  84. W --> RH["rehearsal — a zero-context<br/>reader executes it"] --> D["done = a check passed"]
  85. ```
  86. Only the hook in all of this is code: a script that runs on every prompt and every tool call it watches, whether Claude cooperates or not. The sixteen skills are conventions — markdown instructions that hold exactly as well as Claude follows them. Conventions drift: `CLAUDE.md` is read once and recedes as the work goes on, and a convention recedes the same way.
  87. The route from convention to enforcement is **pin**: when a convention slips, you correct it once, pin writes the correction into the rule catalog, and the hook delivers it from then on. Whether each rule then actually fires is a recorded fact, not a feeling — the delivery log counts every arrival, and the **report** skill names the rules that never fired.
  88. ## The pieces
  89. | Piece | Kind | Role |
  90. |---|---|---|
  91. | **rules hook** | code — script on every prompt, watched tool call, and compaction | Delivers each matching rule's full text with the message — and, for rules that name tools (`when.tools`), with the tool call itself — up to a per-message cap fixed in the source (at most 12 rules / ~6,000 chars); `block` rules stop the prompt (exit 2) or deny the tool call; before compaction it delivers one checkpoint reminder; every delivery lands in the log as ids and counts |
  92. | **decision-ledger** | convention — markdown skill | Append-only `DECISIONS.md`; changed minds get supersede links, never silent edits; a non-answer is not a decision — readings the user never confirmed stay in open questions as `assumed` |
  93. | **verify-gate** | convention — markdown skill | Research and model knowledge stay drafts until refuted-and-survived, sourced, and labeled |
  94. | **knowledge-base** | convention — markdown skill | Gate-passed findings land in `memory/knowledge/`; every new question reads there before researching |
  95. | **researcher** | convention — markdown skill | Hands collection to a configured second CLI — findings arrive `hearsay` and still face the gate |
  96. | **proof-standard** | convention — markdown skill | No external claim without evidence in a truth file; copy may not blur code states |
  97. | **brain-init** | convention — markdown skill | Scaffolds memory: index, ledger, open questions, session log, product truth; appends a session-start block to `CLAUDE.md` (on Codex, `AGENTS.md`) |
  98. | **goal** | convention — markdown skill | Mobilizes what you already hold, maps the field, splits the goal top-down into a pyramid of atomic pieces — no overlaps, no gaps — and fills them bottom-up, each verified before it bears weight; the skeleton persists in `memory/goal/<slug>.md` |
  99. | **rehearsal** | convention — markdown skill | A zero-context reader executes the deliverable before it ships; the round log becomes the done-check's evidence |
  100. | **checkpoint** | convention — markdown skill | `CHECKPOINT.md` keeps a thirty-second return point; `HANDOFF.md` carries orders read once, then deleted |
  101. | **pin** | convention — markdown skill | Turns the correction you just made into a permanent rule in the hook's catalog, in one step |
  102. | **recall** | convention — markdown skill | At a session's first reply and at every subject shift, sweeps index, knowledge, decisions, rules, and skills before answering — and does not stop at the first hit |
  103. | **skill-forge** | convention — markdown skill | A procedure that recurred and passed its check becomes a skill file; the next run starts from the solved path |
  104. | **schedule** | convention — markdown skill | `memory/SCHEDULE.md` holds fixed dates, event entries with freshness limits, and launch bundles that fire all-staged or not at all — the agent notices, judges, and prepares; the human fires anything outward |
  105. | **setup** | convention — markdown skill | First-time setup as a conversation — proves the hook is alive first, then builds the first catalog from choices; four questions or fewer, no JSON shown |
  106. | **doctor** | convention — markdown skill | Health check in four states (healthy / off / broken / unchecked) — live-fires the status line, runs `--check` on the catalogs, and never hides what it could not verify |
  107. | **report** | convention — markdown skill | Reads the delivery log via `--report`: fires per rule, never-fired rules as symptoms (wrong-language keywords / safe-by-default / dead weight), pruning proposed one rule at a time |
  108. verify-gate's labels: `confirmed` / `observed` / `assumed` / `hearsay` / `unknown`. proof-standard tracks code in four states — implemented, wired, operational, verified.
  109. Reference: [skills/](skills/) — each skill file's front matter says when it fires. Every skill is also callable as `/ballast:<name>`.
  110. ## Quick start
  111. ### First session
  112. 0. **Smoke-test in 60 seconds.** Create `<project>/.claude/ballast.rules.json` from the example catalog: [`rules/ballast.rules.example.json`](rules/ballast.rules.example.json). If you installed from the marketplace, ask Claude to copy the example catalog out of the ballast plugin, or paste the JSON from [Write the catalog by hand](#write-the-catalog-by-hand). Then send any message containing "generate": a `[ballast]` block above the reply means the hook is live.
  113. 1. **Pin your first rule.** Correct Claude about anything once — a correction is the **pin** skill's cue: Claude drafts the rule entry, shows it to you, and writes it to the catalog on your OK. If no draft appears, call `/ballast:pin` directly.
  114. 2. **`/ballast:brain-init`** scaffolds the memory files in your project — index, ledger, open questions, session log, product truth — and appends a session-start block to your `CLAUDE.md`, so expect that file to change.
  115. 3. **`/ballast:goal <something big>`** runs the full pipeline — in an unfamiliar field it maps the debates, the settled ground, and the beginner traps before producing a single answer.
  116. Before any rule exists, your message arrives alone. With the example catalog from step 0 in place, "generate" trips its `cost-gate` rule and the message arrives like this:
  117. ```
  118. > generate 40 images for the launch batch
  119. [ballast] Standing rules that apply to this request:
  120. - Estimate before spending: Anything that spends money or credits:
  121. present an estimate and get explicit approval BEFORE executing.
  122. No exceptions for small amounts — the habit is the point.
  123. ```
  124. ### Write the catalog by hand
  125. Rules live in `<project>/.claude/ballast.rules.json` and `~/.claude/ballast.rules.json` (project wins on duplicate `id`). The `version`/`rules` wrapper is required — a file holding a bare rule object loads as zero rules, silently:
  126. ```json
  127. {
  128. "version": 1,
  129. "rules": [
  130. {
  131. "id": "cost-gate",
  132. "title": "Estimate before spending",
  133. "when": { "keywords": ["generate", "credits"], "patterns": ["\\bbatch\\b"] },
  134. "action": "inject",
  135. "body": "Anything that spends money or credits: present an estimate and get explicit approval BEFORE executing. No exceptions for small amounts — the habit is the point."
  136. }
  137. ]
  138. }
  139. ```
  140. - `keywords` — case-insensitive substring match; the string must appear verbatim in the message, so add keywords in the language you chat in. Short keywords match inside longer words — `npm` also fires on `pnpm`
  141. - `patterns` — regex match
  142. - `always: true` — fires on every message; keep to 1–2 rules
  143. - `tools` — moves the rule to the action layer: `"when": {"tools": ["Bash"], "patterns": ["\\bnpm (install|add)\\b"]}` fires when the named tool's command or file path matches, instead of on the prompt. `"tools": true` watches every tool; with `always: true` it fires on each call of those tools
  144. - `action: "block"` — stops the prompt and shows `body` as the reason; on a tool rule it denies that tool call instead
  145. - `BALLAST_DISABLE=1` — turns the hook off (set env vars in the environment you launch Claude Code from)
  146. - `BALLAST_DEBUG=1` — prints load failures and bad patterns to stderr; the hook otherwise swallows them
  147. - `BALLAST_NO_LOG=1` — turns the delivery log off
  148. Start from [`rules/ballast.rules.example.json`](rules/ballast.rules.example.json), or let **pin** write entries for you.
  149. ### Know the limits
  150. Four design choices to keep in mind:
  151. - **Fail-silent, with two exceptions** — a bad regex or an internal error never breaks your session and says nothing. The exceptions exist because dropped and dead both look exactly like quiet: a catalog that exists but will not parse gets one line back to you, and every session opens with one status line.
  152. - **Fail-open** — if the hook cannot run at all (`node` missing from PATH, catalog unreadable), `block` rules do not fire either — at the prompt or at the tool call. Treat blocks as a guardrail, not a sandbox.
  153. - **Install changes one thing you can see** — the line at session start (`[ballast] hook live — no rule catalog yet`, until your catalog has a rule). Everything else waits for its cue: a correction cues pin, a session's first reply cues recall (which, before `/ballast:brain-init`, has no memory files to sweep). `BALLAST_DISABLE=1` turns the hook off, `BALLAST_QUIET=1` only the status line; the skills leave with the plugin.
  154. - **A project catalog travels with its repo** — a cloned project's `.claude/ballast.rules.json` is someone else's standing instructions. The status line counts them, and how many are always-on; read it when you open an unfamiliar repo.
  155. Fail-open has no error screen — the symptoms are a missing `[ballast] hook live` line at session start and a missing `[ballast]` block on a message that should match. When you see either, check these three in order.
  156. 1. Check that `node --version` prints 18+ — install Node if it doesn't
  157. 2. Restart Claude Code if the plugin was installed this session
  158. 3. Rerun with `BALLAST_DEBUG=1` for the specific failure
  159. Before a Claude-operated repo's first push, walk [docs/PUBLISH-CHECKLIST.md](docs/PUBLISH-CHECKLIST.md) — these workspaces accumulate secrets in files you stopped looking at.
  160. <details>
  161. <summary><b>Optional — put a second model on verification or collection duty</b></summary>
  162. To put a second model on verification duty, create `<project>/.claude/ballast.verifier.json` — the whole file is `{ "command": "your-verifier-cli --check" }` ([example](rules/ballast.verifier.example.json)).
  163. Point `command` at any CLI that will argue against a claim — the verify-gate skill runs it with the claim as the final argument and weighs the refutation before labeling anything `confirmed`. Without the file — or when the command fails, which gets reported once — the gate still runs on primary sources alone, labeled `(self-gated)`.
  164. To delegate collection the same way, create `<project>/.claude/ballast.researcher.json` — same shape, `{ "command": "your-researcher-cli --search" }` ([example](rules/ballast.researcher.example.json)); the researcher skill runs it with the question as the final argument.
  165. Collection is delegated, judgment is not: findings arrive `hearsay` and must still pass the gate. Without the file Claude collects as before; a failing command is reported once, then Claude collects directly.
  166. </details>
  167. ## Philosophy
  168. ballast starts from a plain situation: one person with no development background runs an entire job through Claude Code, across fields they were never trained in. What carries that is not knowing more up front — it is building up to each goal from the foundations that goal actually needs, and keeping every path already solved so the next goal starts further along.
  169. What breaks it is memory and overconfidence. So rules live in files and arrive with the message that needs them.
  170. Decisions live in a ledger that cannot be quietly rewritten. Claims carry labels until they earn `confirmed`.
  171. The pieces share one arrangement: the check stands before the mistake. That order came from months of fixing accidents after they shipped — months you cannot inspect, which is why the first disclosure below reads `hearsay`. ballast is built to leave those accidents no room to happen.
  172. By those labels, this README owes you two disclosures:
  173. - **The track record is `hearsay`.** Those months of daily use happened in a private company workspace, and this public repo dates from August 2026 — there is no public history here to open.
  174. - **The novelty claim is `unknown`.** Injecting context on prompt submit is a documented Claude Code hook pattern, and append-only records long predate software. "We have not seen the whole loop elsewhere" is the most ballast can say.
  175. What you can check is the mechanism: the hook, the sixteen skills, and the rule format are all in this repo. If you know prior art for the loop, [open an issue](https://github.com/svy04/ballast/issues) and we'll link it.
  176. ## Maintenance
  177. Version history lives in [CHANGELOG.md](CHANGELOG.md) — each release records what changed and what was corrected. Ask anything in [an issue](https://github.com/svy04/ballast/issues); answers that belonged in this README get written into it.
  178. Pull requests start at [CONTRIBUTING.md](CONTRIBUTING.md) — the short version: the hook stays zero-dependency and fail-silent, and docs must match behavior.
  179. ---
  180. MIT
hooks/scripts/verify-hook.mjs · Bundled script · 432 lines · 2 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * ballast — hook verification harness
  4. *
  5. * Runs ballast-rules.mjs as a child process against twenty cases and checks
  6. * the observable contract (stdout / stderr / exit code / log file), plus the
  7. * shape of the plugin's hook manifest:
  8. *
  9. * 1. keyword match -> injects matching rule bodies as additionalContext
  10. * 2. no match -> stays silent (no stdout, exit 0)
  11. * 3. action: "block" -> blocks the prompt (exit 2, reason on stderr)
  12. * 4. legacy input field -> accepts "prompt" as well as "prompt_text"
  13. * 5. broken catalog -> says so, and delivers no rules
  14. * 6. broken catalog -> still never blocks the session (exit 0)
  15. * 7. hooks/hooks.json -> every event entry wraps its commands in a nested
  16. * "hooks" array (the shape Claude Code and Codex load;
  17. * the flat shape fails plugin load — fixed in 0.8.1)
  18. * 8. SessionStart -> status line says the hook is live and counts the rules
  19. * 9. SessionStart -> with no catalog at all, the line still appears ("no rule catalog yet")
  20. * 10. SessionStart -> with a broken catalog, the line appears and names the failure
  21. * 11. delivery log -> one JSON line per delivery: rule ids and sizes, never prompt text
  22. * 12. BALLAST_NO_LOG=1 -> writes nothing
  23. * 13. tools-scoped rule -> stays out of prompt matching (action layer is opt-in)
  24. * 14. PreToolUse -> injects a rule whose "when.tools" names the tool
  25. * 15. PreToolUse block -> denies the call (permissionDecision, exit 0 — not exit 2)
  26. * 16. PreToolUse -> a tool the rule does not name stays silent
  27. * 17. PreCompact -> emits the checkpoint reminder
  28. * 18. SessionStart -> after compaction (source: "compact") the line says so
  29. * 19. --report -> names fired rules and never-fired rules from the log
  30. * 20. --check -> flags a rule that can never fire and a pattern that
  31. * does not compile
  32. *
  33. * Self-contained: builds its own temp catalogs, isolates the child's home
  34. * and project directories from the real machine, and cleans up after itself.
  35. * No dependencies beyond node built-ins.
  36. *
  37. * Run: node hooks/scripts/verify-hook.mjs
  38. */
  39. import { spawnSync } from "node:child_process";
  40. import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from "node:fs";
  41. import { tmpdir } from "node:os";
  42. import { join, dirname } from "node:path";
  43. import { fileURLToPath } from "node:url";
  44. const HOOK = join(dirname(fileURLToPath(import.meta.url)), "ballast-rules.mjs");
  45. const MANIFEST = join(dirname(fileURLToPath(import.meta.url)), "..", "hooks.json");
  46. const CATALOG = {
  47. rules: [
  48. {
  49. id: "test-inject",
  50. title: "deploy checklist",
  51. when: { keywords: ["deploy"] },
  52. body: "Run the release checklist before any deploy.",
  53. },
  54. {
  55. id: "test-block",
  56. title: "no force push",
  57. when: { keywords: ["force push"] },
  58. action: "block",
  59. body: "Force pushes to shared branches are not allowed.",
  60. },
  61. {
  62. id: "tool-inject",
  63. title: "pnpm only",
  64. when: { tools: ["Bash"], keywords: ["npm install"] },
  65. body: "This repo uses pnpm; npm install has broken the lockfile before.",
  66. },
  67. {
  68. id: "tool-block",
  69. title: "no recursive root delete",
  70. when: { tools: ["Bash"], patterns: ["rm -rf /"] },
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 73 on GitHub
  71. action: "block",
  72. body: "Recursive deletion from the filesystem root is not allowed.",
  73. },
  74. ],
  75. };
  76. /**
  77. * Run the hook once with an isolated home + project dir and a given catalog.
  78. * opts.args — extra argv (e.g. ["--report"])
  79. * opts.env — extra environment entries
  80. * opts.seedLog — JSONL text written to <home>/.claude/ballast/log.jsonl first
  81. * Returns stdout/stderr/status plus logText (the isolated delivery log, "" if absent).
  82. */
  83. function runHook(stdinObj, catalogText, opts = {}) {
  84. const root = mkdtempSync(join(tmpdir(), "ballast-verify-"));
  85. try {
  86. const home = join(root, "home");
  87. const project = join(root, "project");
  88. mkdirSync(join(home, ".claude"), { recursive: true });
  89. mkdirSync(join(project, ".claude"), { recursive: true });
  90. if (catalogText !== undefined) {
  91. writeFileSync(join(project, ".claude", "ballast.rules.json"), catalogText);
  92. }
  93. if (opts.seedLog !== undefined) {
  94. mkdirSync(join(home, ".claude", "ballast"), { recursive: true });
  95. writeFileSync(join(home, ".claude", "ballast", "log.jsonl"), opts.seedLog);
  96. }
  97. const res = spawnSync(process.execPath, [HOOK, ...(opts.args || [])], {
  98. input: stdinObj === undefined ? "" : JSON.stringify(stdinObj),
  99. encoding: "utf8",
  100. timeout: 10_000,
  101. env: {
  102. ...process.env,
  103. HOME: home, // POSIX homedir()
  104. USERPROFILE: home, // Windows homedir()
  105. CLAUDE_PROJECT_DIR: project,
  106. BALLAST_DISABLE: "",
  107. BALLAST_DEBUG: "",
  108. BALLAST_NO_LOG: "",
  109. ...(opts.env || {}),
  110. },
  111. });
  112. if (res.error) throw res.error;
  113. const logFile = join(home, ".claude", "ballast", "log.jsonl");
  114. const logText = existsSync(logFile) ? readFileSync(logFile, "utf8") : "";
  115. return { status: res.status, stdout: res.stdout || "", stderr: res.stderr || "", logText };
  116. } finally {
  117. rmSync(root, { recursive: true, force: true });
  118. }
  119. }
  120. function parseContext(stdout) {
  121. try {
  122. return JSON.parse(stdout).hookSpecificOutput.additionalContext;
  123. } catch {
  124. return null;
  125. }
  126. }
  127. const goodCatalog = JSON.stringify(CATALOG);
  128. const cases = [
  129. {
  130. name: "keyword match injects matching rules",
  131. run: () => runHook({ prompt_text: "please deploy the new build" }, goodCatalog),
  132. check: (r) => {
  133. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  134. const ctx = parseContext(r.stdout);
  135. if (!ctx) return `expected hookSpecificOutput JSON on stdout, got: ${r.stdout || "(empty)"}`;
  136. if (!ctx.includes("Run the release checklist")) return "matched rule body missing from context";
  137. if (ctx.includes("Force pushes")) return "unmatched rule leaked into context";
  138. return null;
  139. },
  140. },
  141. {
  142. name: "no match stays silent",
  143. run: () => runHook({ prompt_text: "write a haiku about rivers" }, goodCatalog),
  144. check: (r) => {
  145. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  146. if (r.stdout.trim() !== "") return `expected empty stdout, got: ${r.stdout}`;
  147. return null;
  148. },
  149. },
  150. {
  151. name: 'action "block" blocks with exit 2',
  152. run: () => runHook({ prompt_text: "just force push it to main" }, goodCatalog),
  153. check: (r) => {
  154. if (r.status !== 2) return `expected exit 2, got ${r.status}`;
  155. if (!r.stderr.includes("Force pushes")) return "block reason missing from stderr";
  156. return null;
  157. },
  158. },
  159. {
  160. name: 'legacy "prompt" field still works',
  161. run: () => runHook({ prompt: "time to deploy again" }, goodCatalog),
  162. check: (r) => {
  163. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  164. const ctx = parseContext(r.stdout);
  165. if (!ctx || !ctx.includes("Run the release checklist")) return "legacy field was not accepted";
  166. return null;
  167. },
  168. },
  169. {
  170. name: "broken catalog says so instead of failing silently",
  171. run: () => runHook({ prompt_text: "deploy something" }, "{ this is not valid JSON"),
  172. check: (r) => {
  173. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  174. const ctx = parseContext(r.stdout);
  175. if (!ctx) return "expected a notice on stdout, got nothing";
  176. if (!ctx.includes("could not be read")) return `notice did not name the failure: ${ctx}`;
  177. if (ctx.includes("Standing rules that apply"))
  178. return "a broken catalog must not deliver rules";
  179. return null;
  180. },
  181. },
  182. {
  183. name: "a broken catalog never blocks the session",
  184. run: () => runHook({ prompt_text: "deploy something" }, "{ this is not valid JSON"),
  185. check: (r) => {
  186. if (r.status === 2) return "a parse failure must not block the prompt";
  187. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  188. return null;
  189. },
  190. },
  191. {
  192. name: "hooks.json wraps every command in a nested hooks array",
  193. run: () => JSON.parse(readFileSync(MANIFEST, "utf8")),
  194. check: (manifest) => {
  195. const events = manifest && manifest.hooks;
  196. if (!events || typeof events !== "object") return "manifest has no top-level hooks object";
  197. const names = Object.keys(events);
  198. if (names.length === 0) return "manifest declares no events";
  199. for (const name of names) {
  200. const entries = events[name];
  201. if (!Array.isArray(entries) || entries.length === 0) return `${name}: expected a non-empty array of entries`;
  202. entries.forEach((entry, i) => {
  203. if (!entry || !Array.isArray(entry.hooks) || entry.hooks.length === 0)
  204. throw new Error(`${name}[${i}]: expected a nested "hooks" array (flat type/command entries fail to load)`);
  205. entry.hooks.forEach((h, j) => {
  206. if (!h || h.type !== "command" || typeof h.command !== "string" || !h.command)
  207. throw new Error(`${name}[${i}].hooks[${j}]: expected { type: "command", command: "..." }`);
  208. if (!h.command.includes("ballast-rules.mjs")) throw new Error(`${name}[${i}].hooks[${j}]: command does not run ballast-rules.mjs`);
  209. });
  210. });
  211. }
  212. return null;
  213. },
  214. },
  215. {
  216. name: "session start: status line counts the loaded rules",
  217. run: () => runHook({ hook_event_name: "SessionStart", source: "startup" }, goodCatalog),
  218. check: (r) => {
  219. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  220. let out;
  221. try { out = JSON.parse(r.stdout); } catch { return `expected JSON on stdout, got: ${r.stdout || "(empty)"}`; }
  222. const ctx = out.hookSpecificOutput && out.hookSpecificOutput.additionalContext;
  223. if (!ctx) return "expected hookSpecificOutput.additionalContext";
  224. if (out.hookSpecificOutput.hookEventName !== "SessionStart") return "hookEventName should be SessionStart";
  225. if (!ctx.includes("hook live")) return `status line missing: ${ctx}`;
  226. if (!ctx.includes("4 rules")) return `expected the 4 catalog rules to be counted: ${ctx}`;
  227. if (!ctx.includes("project catalog")) return `expected the project catalog to be named: ${ctx}`;
  228. if (typeof out.systemMessage !== "string" || !out.systemMessage.includes("hook live")) return "systemMessage (the user-visible copy) missing";
  229. if (ctx.includes("Standing rules that apply")) return "status mode must not deliver rules";
  230. return null;
  231. },
  232. },
  233. {
  234. name: "session start: no catalog at all still prints the line",
  235. run: () => runHook({ hook_event_name: "SessionStart", source: "startup" }, undefined),
  236. check: (r) => {
  237. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  238. const ctx = parseContext(r.stdout);
  239. if (!ctx) return `expected a status line, got: ${r.stdout || "(empty)"}`;
  240. if (!ctx.includes("no rule catalog yet")) return `expected "no rule catalog yet": ${ctx}`;
  241. return null;
  242. },
  243. },
  244. {
  245. name: "session start: a broken catalog is named in the status line",
  246. run: () => runHook({ hook_event_name: "SessionStart", source: "startup" }, "{ this is not valid JSON"),
  247. check: (r) => {
  248. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  249. const ctx = parseContext(r.stdout);
  250. if (!ctx) return "expected a status line";
  251. if (!ctx.includes("hook live")) return `status line missing: ${ctx}`;
  252. if (!ctx.includes("could not be read")) return `broken catalog not named: ${ctx}`;
  253. return null;
  254. },
  255. },
  256. {
  257. name: "delivery log: rule ids and sizes, never prompt text",
  258. run: () => runHook({ prompt_text: "please deploy the new build" }, goodCatalog),
  259. check: (r) => {
  260. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  261. const lines = r.logText.trim().split("\n").filter(Boolean);
  262. if (lines.length !== 1) return `expected exactly 1 log line, got ${lines.length}`;
  263. let e;
  264. try { e = JSON.parse(lines[0]); } catch { return `log line is not JSON: ${lines[0]}`; }
  265. if (e.ev !== "prompt") return `expected ev "prompt", got ${e.ev}`;
  266. if (!Array.isArray(e.rules) || !e.rules.includes("test-inject")) return "fired rule id missing from log";
  267. if (typeof e.chars !== "number") return "delivered size missing from log";
  268. if (r.logText.includes("deploy the new build")) return "PROMPT TEXT LEAKED INTO THE LOG";
  269. return null;
  270. },
  271. },
  272. {
  273. name: "BALLAST_NO_LOG=1 writes nothing",
  274. run: () => runHook({ prompt_text: "please deploy the new build" }, goodCatalog, { env: { BALLAST_NO_LOG: "1" } }),
  275. check: (r) => {
  276. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  277. if (r.logText !== "") return `expected no log file, got: ${r.logText}`;
  278. const ctx = parseContext(r.stdout);
  279. if (!ctx || !ctx.includes("Run the release checklist")) return "delivery itself must still work with logging off";
  280. return null;
  281. },
  282. },
  283. {
  284. name: "tools-scoped rule stays out of prompt matching",
  285. run: () => runHook({ prompt_text: "should I run npm install here?" }, goodCatalog),
  286. check: (r) => {
  287. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  288. if (r.stdout.trim() !== "") return `a when.tools rule fired on a prompt: ${r.stdout}`;
  289. return null;
  290. },
  291. },
  292. {
  293. name: "PreToolUse injects a rule that names the tool",
  294. run: () =>
  295. runHook(
  296. { hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command: "npm install express" } },
  297. goodCatalog
  298. ),
  299. check: (r) => {
  300. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  301. let out;
  302. try { out = JSON.parse(r.stdout); } catch { return `expected JSON on stdout, got: ${r.stdout || "(empty)"}`; }
  303. if (out.hookSpecificOutput.hookEventName !== "PreToolUse") return "hookEventName should be PreToolUse";
  304. const ctx = out.hookSpecificOutput.additionalContext;
  305. if (!ctx || !ctx.includes("pnpm")) return `tool rule body missing: ${ctx}`;
  306. if (ctx.includes("release checklist")) return "a prompt-layer rule leaked into the tool layer";
  307. const e = JSON.parse(r.logText.trim());
  308. if (e.ev !== "tool" || e.tool !== "Bash") return "tool delivery not logged";
  309. if (r.logText.includes("express")) return "TOOL INPUT TEXT LEAKED INTO THE LOG";
  310. return null;
  311. },
  312. },
  313. {
  314. name: "PreToolUse block denies the call without breaking the session",
  315. run: () =>
  316. runHook(
  317. { hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command: "rm -rf / --no-preserve-root" } },
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 324 on GitHub
  318. goodCatalog
  319. ),
  320. check: (r) => {
  321. if (r.status !== 0) return `expected exit 0 (deny is JSON, not exit 2), got ${r.status}`;
  322. let out;
  323. try { out = JSON.parse(r.stdout); } catch { return `expected JSON on stdout, got: ${r.stdout || "(empty)"}`; }
  324. if (out.hookSpecificOutput.permissionDecision !== "deny") return "expected permissionDecision deny";
  325. if (!String(out.hookSpecificOutput.permissionDecisionReason).includes("Recursive deletion"))
  326. return "deny reason missing the rule body";
  327. return null;
  328. },
  329. },
  330. {
  331. name: "PreToolUse: a tool the rule does not name stays silent",
  332. run: () =>
  333. runHook(
  334. { hook_event_name: "PreToolUse", tool_name: "Write", tool_input: { file_path: "npm install notes.md" } },
  335. goodCatalog
  336. ),
  337. check: (r) => {
  338. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  339. if (r.stdout.trim() !== "") return `rule fired for a tool it does not name: ${r.stdout}`;
  340. return null;
  341. },
  342. },
  343. {
  344. name: "PreCompact emits the checkpoint reminder",
  345. run: () => runHook({ hook_event_name: "PreCompact", trigger: "auto" }, goodCatalog),
  346. check: (r) => {
  347. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  348. let out;
  349. try { out = JSON.parse(r.stdout); } catch { return `expected JSON on stdout, got: ${r.stdout || "(empty)"}`; }
  350. if (out.hookSpecificOutput.hookEventName !== "PreCompact") return "hookEventName should be PreCompact";
  351. const ctx = out.hookSpecificOutput.additionalContext;
  352. if (!ctx || !ctx.includes("CHECKPOINT")) return `checkpoint reminder missing: ${ctx}`;
  353. if (typeof out.systemMessage !== "string") return "user-visible line missing";
  354. return null;
  355. },
  356. },
  357. {
  358. name: 'session start after compaction (source: "compact") says so',
  359. run: () => runHook({ hook_event_name: "SessionStart", source: "compact" }, goodCatalog),
  360. check: (r) => {
  361. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  362. const ctx = parseContext(r.stdout);
  363. if (!ctx) return "expected a status line";
  364. if (!ctx.includes("context compacted")) return `expected the compaction variant: ${ctx}`;
  365. if (!ctx.includes("4 rules")) return `rule count missing from the compaction line: ${ctx}`;
  366. return null;
  367. },
  368. },
  369. {
  370. name: "--report names fired and never-fired rules",
  371. run: () =>
  372. runHook(undefined, goodCatalog, {
  373. args: ["--report"],
  374. seedLog:
  375. JSON.stringify({ ts: "2026-08-20T10:00:00Z", ev: "prompt", dir: "proj", rules: ["test-inject"], chars: 50 }) +
  376. "\n" +
  377. JSON.stringify({ ts: "2026-08-21T10:00:00Z", ev: "tool", dir: "proj", tool: "Bash", rules: ["tool-inject"], chars: 40 }) +
  378. "\n",
  379. }),
  380. check: (r) => {
  381. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  382. if (!r.stdout.includes("delivery report")) return `report header missing: ${r.stdout}`;
  383. if (!r.stdout.includes("test-inject")) return "fired rule missing from report";
  384. if (!r.stdout.includes("never fired")) return "never-fired section missing";
  385. if (!r.stdout.includes("test-block")) return "dead rule not named";
  386. return null;
  387. },
  388. },
  389. {
  390. name: "--check flags a rule that can never fire and a bad regex",
  391. run: () =>
  392. runHook(undefined, JSON.stringify({
  393. rules: [
  394. { id: "no-trigger", body: "x", when: {} },
  395. { id: "bad-regex", body: "y", when: { patterns: ["("] } },
  396. ],
  397. }), { args: ["--check"] }),
  398. check: (r) => {
  399. if (r.status !== 0) return `expected exit 0, got ${r.status}`;
  400. if (!r.stdout.includes("can never fire")) return `never-fires warning missing: ${r.stdout}`;
  401. if (!r.stdout.includes("does not compile")) return `bad-regex warning missing: ${r.stdout}`;
  402. return null;
  403. },
  404. },
  405. ];
  406. let failed = 0;
  407. for (const c of cases) {
  408. let reason;
  409. try {
  410. reason = c.check(c.run());
  411. } catch (e) {
  412. reason = `harness error: ${e && e.message}`;
  413. }
  414. if (reason) {
  415. failed++;
  416. console.log(`FAIL ${c.name}`);
  417. console.log(` ${reason}`);
  418. } else {
  419. console.log(`PASS ${c.name}`);
  420. }
  421. }
  422. console.log(`\n${cases.length - failed}/${cases.length} passed`);
  423. process.exit(failed === 0 ? 0 : 1);

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.