From f3112ae63f3c2fb123d789d39cea6dcf09358c44 Mon Sep 17 00:00:00 2001 From: done6666 Date: Fri, 30 Oct 2026 04:49:51 +0300 Subject: [PATCH 1/2] feat: resume sessions from a roadmap checkpoint - The current roadmap step carries a checkpoint (next, done, open) that brief shows first and keeps when the budget is tight. - check --diff fails when the current step's paths change but its checkpoint does not, so every commit leaves a resume point (ADR-0018). - hook install --platform claude adds a SessionStart hook that runs brief in every new, resumed, cleared or compacted session; platforms without such a hook are refused (ADR-0019). - Skill, AGENTS.md contract and README now describe repository memory. Co-Authored-By: Claude Opus 5.5 --- .opencode/skills/steadfast/SKILL.md | 21 ++-- .steadfast/decisions/ADR-0002.yaml | 2 +- .steadfast/decisions/ADR-0007.yaml | 2 +- .steadfast/decisions/ADR-0008.yaml | 2 +- .steadfast/decisions/ADR-0009.yaml | 2 +- .steadfast/decisions/ADR-0010.yaml | 2 +- .steadfast/decisions/ADR-0014.yaml | 2 +- .steadfast/decisions/ADR-0016.yaml | 2 +- .steadfast/decisions/ADR-0017.yaml | 2 +- .steadfast/decisions/ADR-0018.yaml | 20 ++++ .steadfast/decisions/ADR-0019.yaml | 16 +++ .steadfast/roadmap.yaml | 11 +- AGENTS.md | 3 +- README.md | 47 ++++++--- schema/roadmap.schema.json | 26 +++++ skills/steadfast/SKILL.md | 21 ++-- src/commands/brief.ts | 24 ++++- src/commands/check.ts | 45 +++++++- src/commands/hook.ts | 150 +++++++++++++++++++++++++-- src/commands/init.ts | 3 +- src/commands/mcp.ts | 2 +- src/core/roadmap.ts | 58 ++++++++++- src/types.ts | 7 ++ test/checkpoint.test.ts | 155 ++++++++++++++++++++++++++++ test/hook.test.ts | 66 ++++++++++++ test/validate.test.ts | 9 +- 26 files changed, 631 insertions(+), 69 deletions(-) create mode 100644 .steadfast/decisions/ADR-0018.yaml create mode 100644 .steadfast/decisions/ADR-0019.yaml create mode 100644 test/checkpoint.test.ts diff --git a/.opencode/skills/steadfast/SKILL.md b/.opencode/skills/steadfast/SKILL.md index f630b26..9b11451 100644 --- a/.opencode/skills/steadfast/SKILL.md +++ b/.opencode/skills/steadfast/SKILL.md @@ -5,9 +5,7 @@ description: Use when a repository has .steadfast/ or AGENTS.md mentions steadfa # Steadfast Memory -## Trigger - -Use this skill when `.steadfast/` exists or `AGENTS.md` mentions steadfast. +## Tools With MCP connected, call its `brief`, `context`, `check`, `verify`, `new`, `finding` and `supersede` tools instead of the CLI below; clients prefix the @@ -15,9 +13,9 @@ names (`steadfast_*` in OpenCode, `mcp__steadfast__*` in Claude). ## 0. Recover state -Run `npx steadfast-docs brief` first. It prints the current roadmap step, next -steps, blockers, recent commits and worktrees. Do not open -`.steadfast/roadmap.yaml` directly; edit it only to update status and evidence. +Run `npx steadfast-docs brief` first, unless the session already shows it. +Resume from the current step's `checkpoint.next`. Edit +`.steadfast/roadmap.yaml` only for status, evidence and checkpoint. ## 1. Plan the path set @@ -97,9 +95,8 @@ Then set `status: active` and run `verify`. - If a rule changes, run `steadfast supersede --decision ""`. - If you learn a fact code cannot prove yet, record it with `steadfast finding new`; retire it when a test proves it. - Unenforceable rules are advisory and expire. -- When a roadmap step is finished, set `status: done` and `evidence: ` in `.steadfast/roadmap.yaml`, then make the next unblocked step - `current`. +- When a step is finished, set `status: done`, `evidence: `, + drop its checkpoint, and make the next unblocked step `current`. ## 7. Hand off @@ -109,8 +106,10 @@ Tell the human only: - decisions that need approval, one line each - any guard that blocked a path -Leave a durable handoff in the commit body or an issue: `Finding:`, `Decision:`, -`Next:`. Update README `Status` on release changes. +Before each commit and before you stop, rewrite the current step's +`checkpoint`: `next` (one action), `done` (max 3), `open` (max 2); `check +--diff` fails if step paths changed but it did not. Update README `Status` on +release changes. ## Stop conditions diff --git a/.steadfast/decisions/ADR-0002.yaml b/.steadfast/decisions/ADR-0002.yaml index b4770ed..e11f151 100644 --- a/.steadfast/decisions/ADR-0002.yaml +++ b/.steadfast/decisions/ADR-0002.yaml @@ -9,5 +9,5 @@ decision: Decision records are YAML; Markdown is reserved for agent contracts an why: - Prose budgets cannot be enforced; data can. enforced_by: test/validate.test.ts -verified_by: h1:f751be4b1e95bc479b70138a5a7b576232dd6bff0d9fe1fbe85cb4e4326caaca +verified_by: h1:f4bae5285a62401270d8b8ece0d35bf16f1e6488bf073ff7d305a8ba067a01e7 by: agent diff --git a/.steadfast/decisions/ADR-0007.yaml b/.steadfast/decisions/ADR-0007.yaml index 2c2c99e..c7443c8 100644 --- a/.steadfast/decisions/ADR-0007.yaml +++ b/.steadfast/decisions/ADR-0007.yaml @@ -10,7 +10,7 @@ decision: The canonical skill is budgeted, and every project copy is verified ag why: - Global copies are user-managed; project copies are enforced. enforced_by: test/skill.test.ts -verified_by: h1:19c49b970bd9e616aa6976151bc1374a34600f44246f9810118e78944c18f061 +verified_by: h1:806e39cb49f2b5381b9059240f86c23514831f67c0a32c6b774d42e63bc7eb4b supersedes: - ADR-0006 by: agent diff --git a/.steadfast/decisions/ADR-0008.yaml b/.steadfast/decisions/ADR-0008.yaml index 6419a14..bec365c 100644 --- a/.steadfast/decisions/ADR-0008.yaml +++ b/.steadfast/decisions/ADR-0008.yaml @@ -11,5 +11,5 @@ decision: Legacy documentation is deleted after migration; check fails if a reti why: - The pack is the only context; stale docs are the drift this replaces. enforced_by: test/retire.test.ts -verified_by: h1:11cbf5ccd00b71880ac07bcbb3eaefb98523dcd9fef0921ccc026b399cb80006 +verified_by: h1:1a0d070f7ce565ab916cdeed819bffdd9766892a657c0cf9de2d75bf2f84fed8 by: agent diff --git a/.steadfast/decisions/ADR-0009.yaml b/.steadfast/decisions/ADR-0009.yaml index b865f63..a9c0e6f 100644 --- a/.steadfast/decisions/ADR-0009.yaml +++ b/.steadfast/decisions/ADR-0009.yaml @@ -13,5 +13,5 @@ decision: The MCP server wraps the CLI, so every command has one implementation why: - A second implementation would drift and double the test burden. enforced_by: test/mcp.test.ts -verified_by: h1:cea336eb4526c6ee4382f4e434dde4722873b2fb7fbc27e0c1f11f9b512d98d6 +verified_by: h1:f74039e2802c8aad252e83ca1383e4b97326a6f4929ae8980146646636392e16 by: agent diff --git a/.steadfast/decisions/ADR-0010.yaml b/.steadfast/decisions/ADR-0010.yaml index 1186210..6e80da6 100644 --- a/.steadfast/decisions/ADR-0010.yaml +++ b/.steadfast/decisions/ADR-0010.yaml @@ -11,5 +11,5 @@ decision: The pre-commit hook validates the index, and refuses when governed fil why: - A hook that reads only the working tree can approve a different commit. enforced_by: test/hook.test.ts -verified_by: h1:bc7ffd28919212f071e8fc157061bd0a34361ba507986b2c0ded5e209cd8d868 +verified_by: h1:b870406ba14ecc656dbedb6d41e4f18efc669c23adf0523440cbb3255ea0d099 by: agent diff --git a/.steadfast/decisions/ADR-0014.yaml b/.steadfast/decisions/ADR-0014.yaml index adb9485..94871da 100644 --- a/.steadfast/decisions/ADR-0014.yaml +++ b/.steadfast/decisions/ADR-0014.yaml @@ -10,5 +10,5 @@ decision: A config change that only updates retired_docs is not decision debt. why: - retire records the retirement itself; a second record would be noise. enforced_by: test/retire.test.ts -verified_by: h1:c5753d9f2a65d774cda525b362d2936241ac6c90303a43284ef8e2ff6cf7262d +verified_by: h1:9644a79fba2791a41064779c81ed3f872aa5d0c39c24c76c61c8e86f69367954 by: agent diff --git a/.steadfast/decisions/ADR-0016.yaml b/.steadfast/decisions/ADR-0016.yaml index 214cf08..c5e8c25 100644 --- a/.steadfast/decisions/ADR-0016.yaml +++ b/.steadfast/decisions/ADR-0016.yaml @@ -15,5 +15,5 @@ decision: Execution state lives in a mutable, token-budgeted roadmap; decisions why: - Session handoff needs a current step, but a second normative store would drift. enforced_by: test/roadmap.test.ts -verified_by: h1:795e400d27e8e719d8de0bd22ccbdedc8b48e1389197500d512264639664c036 +verified_by: h1:56030221ddd95bbcd5f34402dfb6ece921aed6c2f04fc54228c8be4f87a9cf34 by: agent diff --git a/.steadfast/decisions/ADR-0017.yaml b/.steadfast/decisions/ADR-0017.yaml index f4fe6d0..8715a15 100644 --- a/.steadfast/decisions/ADR-0017.yaml +++ b/.steadfast/decisions/ADR-0017.yaml @@ -16,5 +16,5 @@ decision: Findings are append-only, target-versioned observations; they enter co why: - Facts code cannot prove yet are lost between sessions, but a second decision store would drift. enforced_by: test/finding.test.ts -verified_by: h1:83994bc5706a9a709258a4e4933f6257c195c5e9e92aa890feb9de155aa8b044 +verified_by: h1:773140bd04fd73c0684c19225324665a999dee2ada7e0fbafc065a6165860165 by: agent diff --git a/.steadfast/decisions/ADR-0018.yaml b/.steadfast/decisions/ADR-0018.yaml new file mode 100644 index 0000000..1052ab2 --- /dev/null +++ b/.steadfast/decisions/ADR-0018.yaml @@ -0,0 +1,20 @@ +id: ADR-0018 +topic: session-checkpoint +scope: global +status: active +created: 2026-10-30 +applies_to: + - src/core/roadmap.ts + - src/commands/brief.ts + - src/commands/check.ts + - schema/roadmap.schema.json + - test/checkpoint.test.ts +decision: The current roadmap step carries a checkpoint rewritten in place; check --diff fails when the step's paths change but the checkpoint does not. +why: + - A context reset loses in-progress state; binding the resume point to commits saves it without predicting when context runs out. +rejected: + - "Appended session log: grows without bound and becomes the docs that rot." + - "Date-based staleness: an old date says nothing about whether the work moved." +enforced_by: test/checkpoint.test.ts +by: agent +verified_by: h1:bc4b3504b62cf4de1d660149180b7b92fb065af552bd060a9424df7093207c29 diff --git a/.steadfast/decisions/ADR-0019.yaml b/.steadfast/decisions/ADR-0019.yaml new file mode 100644 index 0000000..a868e74 --- /dev/null +++ b/.steadfast/decisions/ADR-0019.yaml @@ -0,0 +1,16 @@ +id: ADR-0019 +topic: session-start +scope: global +status: active +created: 2026-10-30 +applies_to: + - src/commands/hook.ts + - test/hook.test.ts +decision: hook install --platform claude adds a SessionStart hook that runs brief; platforms without a session-start context hook are refused. +why: + - Memory the agent must pull gets skipped; a harness hook pushes it into every new, resumed or compacted session. +rejected: + - "OpenCode compaction plugin: experimental API and it fires only on compaction, not at session start." +enforced_by: test/hook.test.ts +by: agent +verified_by: h1:49a9e159038fb341ba42dfdf702e0de6bc99fc1ac67ca88d69f1a8640164f8fe diff --git a/.steadfast/roadmap.yaml b/.steadfast/roadmap.yaml index 327ac84..4e94841 100644 --- a/.steadfast/roadmap.yaml +++ b/.steadfast/roadmap.yaml @@ -1,3 +1,12 @@ # Execution state: mutable. One current step. Decisions stay in .steadfast/decisions/. version: 1 -steps: [] +updated: 2026-10-30 +steps: + - id: STEP-001 + goal: Make a new session resume where the last one stopped + why: Context resets lose the in-progress state, and agents skip memory they must pull. + paths: [src/**, schema/roadmap.schema.json, test/**, skills/steadfast/SKILL.md, README.md] + acceptance: npm test and steadfast check --strict pass + status: done + evidence: test/checkpoint.test.ts + decisions: [ADR-0018, ADR-0019] diff --git a/AGENTS.md b/AGENTS.md index 394e534..9f43706 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,8 @@ After `steadfast new`, fill the record you just created. If the steadfast MCP server is connected, call `steadfast_context` (OpenCode) or `mcp__steadfast__context` (Claude) with the paths you will touch; otherwise run `npx steadfast-docs context --for `. Use only that output for context. If context fails, narrow the paths or ask the human before raising the budget; do not pass `--allow-partial`. Records are not reading material: do not load other records, legacy docs or architecture notes. The pack is the only context. -At session start, run `npx steadfast-docs brief` to recover the current roadmap step. Update `.steadfast/roadmap.yaml` when a step starts or finishes. +At session start, run `npx steadfast-docs brief` to recover the current roadmap step and its checkpoint. Update `.steadfast/roadmap.yaml` when a step starts or finishes. +Before each commit and before the session ends, rewrite the current step's `checkpoint` (`next`, `done`, `open`) so the next session resumes where this one stopped. If you discover a fact code cannot prove yet, record a finding; retire it when a test proves it. After a new record, fill the record you just created. Never edit an active record; supersede it. diff --git a/README.md b/README.md index 33996ef..75a612c 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,24 @@ # steadfast-docs -**Normative project memory for AI coding agents.** +**Repository memory for AI coding agents.** -Documentation that only agents read. Humans ask; agents remember; CI keeps the memory honest. +Documentation that only agents read. A new session resumes where the last one stopped; humans ask, agents remember, and CI keeps the memory honest. [![npm](https://img.shields.io/npm/v/steadfast-docs?color=black&label=npm)](https://www.npmjs.com/package/steadfast-docs) [![ci](https://github.com/done6666/steadfast-docs/actions/workflows/ci.yml/badge.svg)](https://github.com/done6666/steadfast-docs/actions/workflows/ci.yml) -[![tests](https://img.shields.io/badge/tests-172-black)](https://github.com/done6666/steadfast-docs/tree/main/test) +[![tests](https://img.shields.io/badge/tests-184-black)](https://github.com/done6666/steadfast-docs/tree/main/test) [![node](https://img.shields.io/badge/node-%3E%3D20.11-black)](https://github.com/done6666/steadfast-docs/blob/main/package.json) [![license](https://img.shields.io/badge/license-MIT-black)](https://github.com/done6666/steadfast-docs/blob/main/LICENSE) ## Why -Agent-written documentation fails in two ways: +Large projects outlive a context window. Agent-written documentation fails in three ways: -1. **It rots.** A decision changes in conversation but not in the file. Copies multiply, and the agent follows the wrong one. -2. **It floods the context.** A project with 40 ADRs is roughly 50K tokens. Accuracy drops as input grows, so the agent pays more and reasons worse. +1. **It forgets.** The context fills, a new session starts, and the in-progress state (what is done, what is next, what is still a guess) is gone. +2. **It rots.** A decision changes in conversation but not in the file. Copies multiply, and the agent follows the wrong one. +3. **It floods the context.** A project with 40 ADRs is roughly 50K tokens. Accuracy drops as input grows, so the agent pays more and reasons worse, and skips docs it was told to read. -Adding more documentation makes both worse. +Adding more documentation makes all three worse. ## The idea @@ -28,6 +29,7 @@ Store only what code cannot prove: the rule, the reason, and the alternatives al | **Invariants** | 10–25 laws, always loaded | ~400 tokens | | **Decisions** | append-only YAML, never edited | ≤160 tokens each | | **Guards** | `deny` / `instead` / `check` | ≤3 per decision | +| **Checkpoint** | where the last session stopped, rewritten in place | 1 next, ≤3 done, ≤2 open | | **Context pack** | compiled per task, only matching records | hard token cap | No compiled state is committed. The pack is generated on demand, so there is no second copy to go stale. @@ -52,15 +54,15 @@ One-time setup. After this, you do not run the loop; the agent does. ```bash npx steadfast-docs init npx steadfast-docs mcp install --platform opencode # or --platform claude -npx steadfast-docs hook install +npx steadfast-docs hook install # add --platform claude for a session-start brief npx steadfast-docs skill install --platform opencode ``` -`init` writes `.steadfast/` and appends the contract to `AGENTS.md`. `mcp install` gives the agent native tools, `hook install` gates commits, and the skill teaches the loop. From then on, you talk to the agent: +`init` writes `.steadfast/` and appends the contract to `AGENTS.md`. `mcp install` gives the agent native tools, `hook install` gates commits (and with `--platform claude` starts every session with the brief), and the skill teaches the loop. From then on, you talk to the agent: > “Add a refund endpoint.” -The agent plans the paths, calls `context`, reads only the pack, implements, runs the tests, calls `check` and `verify`, and appends a decision when it made a non-obvious choice. You see a short summary and the decisions that need approval — never a document to review. +The agent reads the brief, resumes from the checkpoint, plans the paths, calls `context`, reads only the pack, implements, runs the tests, calls `check` and `verify`, rewrites the checkpoint, and appends a decision when it made a non-obvious choice. You see a short summary and the decisions that need approval — never a document to review. `context --for` accepts files, directories or globs. A directory expands to the files beneath it, and a glob expands to the files it matches, so `src/core` finds a rule declared for `src/core/pack.ts`. A selector that matches no decision is called out in the pack; `--strict` turns that into a failure. @@ -75,7 +77,9 @@ The agent plans the paths, calls `context`, reads only the pack, implements, run The server exposes `brief`, `context`, `check`, `verify`, `new`, `finding`, `explain`, `supersede` and `doctor`. It is a JSON-RPC wrapper over the same CLI, so there is one implementation and two entry points. `--print` shows the config without writing it; `--check` verifies an existing install. -`hook install` adds a managed block to the real git hooks directory (respecting a repo-local `core.hooksPath`, worktrees and submodules) that runs `check --strict --staged --diff HEAD`. `--staged` refuses to validate a working tree that differs from the index, so what the hook approves is what the commit contains. An existing hook is chained as `pre-commit.steadfast-original` (non-shell hooks included), runs before the check, and is restored by `hook remove`. A hooks directory shared outside the repository is refused, because a project-specific hook would run in every repo. `doctor` then reports the contract, skill copy, MCP config, hook, freshness, advisory rules and retired docs in one pass. +`hook install` adds a managed block to the real git hooks directory (respecting a repo-local `core.hooksPath`, worktrees and submodules) that runs `check --strict --staged --diff HEAD`. `--staged` refuses to validate a working tree that differs from the index, so what the hook approves is what the commit contains. An existing hook is chained as `pre-commit.steadfast-original` (non-shell hooks included), runs before the check, and is restored by `hook remove`. A hooks directory shared outside the repository is refused, because a project-specific hook would run in every repo. + +`hook install --platform claude` also adds a `SessionStart` hook to `.claude/settings.json` that runs `brief`. Every new, resumed, cleared or compacted Claude Code session starts with the current step and its checkpoint, so the agent never has to remember to ask. Other hooks and settings are preserved, and `hook remove --platform claude` takes out only this entry. OpenCode has no documented session-start context hook; there the `AGENTS.md` contract tells the agent to run `brief`. `doctor` then reports the contract, skill copy, MCP config, hook, freshness, advisory rules and retired docs in one pass. ## What a decision looks like @@ -113,12 +117,23 @@ steps: acceptance: pnpm test --filter worker status: current decisions: [ADR-0017] + checkpoint: + next: Wire the cleanup job into the scheduler + done: ["Migration and handler"] + open: ["Retention window of 90 days is a guess"] ``` One step is `current`; `done` requires evidence (a test or commit). `brief` -compiles a ≤300-token session view — current step, next steps, blockers, recent -commits, worktrees and memory stats — and stores nothing. The full roadmap is -never loaded into context. +compiles a ≤300-token session view — current step and checkpoint, next steps, +blockers, recent commits, worktrees and memory stats — and stores nothing. The +full roadmap is never loaded into context. + +The checkpoint is where the last session stopped: the next concrete action, +what is done, and what is still open. It is rewritten in place, never +appended. `check --diff` fails when the current step's paths change but its +checkpoint does not, so every commit leaves a resume point even if the context +runs out mid-task. Done steps carry none; lasting facts move into findings or +decisions. ## What a finding is @@ -149,6 +164,7 @@ append-only: correct one by appending a successor with `supersedes`. - **Append-only.** Change a rule by appending a record with `supersedes: [ADR-0012]`. `superseded` is derived, never written. Two active records cannot share a `(scope, topic)`. - **Content fingerprints.** `verified_by` hashes the files matched by `applies_to`, not a commit sha. Verify before committing; rebases cannot invalidate it. - **Declared enforcement.** `enforced_by` is a test path or a `!command`. `check` verifies that a test path exists but never runs it; `verify --assume` is an explicit assertion that the test passed. Rules without one are advisory and are flagged after `advisory_ttl_days` (a failure under `--strict`). +- **Resume points move with the work.** A commit that touches the current step without rewriting its checkpoint fails `check --strict`. - **Hard budgets.** Per record, per pack, per invariant list, enforced against a conservative token estimate. `context` exits 2 with the token or guard count needed, so the agent can ask before raising the budget; `--budget` may only lower the configured cap, and `--allow-partial` is the explicit escape hatch. - **Negative memory.** Rejected proposals are first-class records, so the agent does not re-litigate dead ends. - **Retired docs stay retired.** `retire` deletes the old documentation and records the glob; `check` fails if it reappears. In a git worktree it stages the deletion and the config update, so `check` sees the retired state immediately; `--no-stage` leaves both for selective staging. Git history is the archive. @@ -170,7 +186,7 @@ append-only: correct one by appending a successor with `supersedes`. | `npx steadfast-docs verify --assume` | Recompute fingerprints after the tests pass | | `npx steadfast-docs retire --apply [--no-stage]` | Delete legacy docs, stage the change and enforce `retired_docs` | | `npx steadfast-docs mcp install` | Register the MCP server (or run `mcp` to start it) | -| `npx steadfast-docs hook install` | Add the managed pre-commit `check` | +| `npx steadfast-docs hook install [--platform claude]` | Add the managed pre-commit `check` and the session-start brief | | `npx steadfast-docs doctor` | Diagnose contract, skill, MCP, hook, freshness and advisories | | `npx steadfast-docs skill install --platform opencode` | Install the agent loop (or `claude`) | @@ -247,6 +263,7 @@ node dist/src/cli.js check --strict ## Status 0.5.0 published. The agent-native slice is complete: `init`, `brief`, `new`, `finding`, `explain`, `supersede`, `context`, `check`, `verify`, `retire`, `skill`, `mcp`, `hook`, `doctor`. +Unreleased: roadmap checkpoints that a commit must move, and a Claude Code session-start brief. A real-project pilot has completed and is kept as a lab branch, not adopted. Next is a new adoption pilot; task-scope contracts (`start` / `check` / `end`) only if real use needs them. ## License diff --git a/schema/roadmap.schema.json b/schema/roadmap.schema.json index 7ba9779..b13abc0 100644 --- a/schema/roadmap.schema.json +++ b/schema/roadmap.schema.json @@ -42,6 +42,10 @@ { "if": { "properties": { "status": { "const": "blocked" } }, "required": ["status"] }, "then": { "required": ["blocked_by"] } + }, + { + "if": { "properties": { "status": { "enum": ["done", "dropped"] } }, "required": ["status"] }, + "then": { "not": { "required": ["checkpoint"] } } } ], "properties": { @@ -84,6 +88,28 @@ "type": "array", "maxItems": 8, "items": { "type": "string", "pattern": "^FIND-[0-9]{4,}$", "maxLength": 32 } + }, + "checkpoint": { "$ref": "#/$defs/checkpoint" } + } + }, + "checkpoint": { + "type": "object", + "additionalProperties": false, + "required": ["next"], + "description": "Where the last session stopped. Rewritten in place; brief shows it, and a diff that touches the step's paths must move it. Done and dropped steps carry none.", + "properties": { + "next": { "type": "string", "minLength": 1, "maxLength": 160, "pattern": "\\S", "description": "The next concrete action." }, + "done": { + "type": "array", + "maxItems": 3, + "items": { "type": "string", "minLength": 1, "maxLength": 100, "pattern": "\\S" }, + "description": "What this step already finished." + }, + "open": { + "type": "array", + "maxItems": 2, + "items": { "type": "string", "minLength": 1, "maxLength": 100, "pattern": "\\S" }, + "description": "Unresolved questions or working assumptions." } } } diff --git a/skills/steadfast/SKILL.md b/skills/steadfast/SKILL.md index f630b26..9b11451 100644 --- a/skills/steadfast/SKILL.md +++ b/skills/steadfast/SKILL.md @@ -5,9 +5,7 @@ description: Use when a repository has .steadfast/ or AGENTS.md mentions steadfa # Steadfast Memory -## Trigger - -Use this skill when `.steadfast/` exists or `AGENTS.md` mentions steadfast. +## Tools With MCP connected, call its `brief`, `context`, `check`, `verify`, `new`, `finding` and `supersede` tools instead of the CLI below; clients prefix the @@ -15,9 +13,9 @@ names (`steadfast_*` in OpenCode, `mcp__steadfast__*` in Claude). ## 0. Recover state -Run `npx steadfast-docs brief` first. It prints the current roadmap step, next -steps, blockers, recent commits and worktrees. Do not open -`.steadfast/roadmap.yaml` directly; edit it only to update status and evidence. +Run `npx steadfast-docs brief` first, unless the session already shows it. +Resume from the current step's `checkpoint.next`. Edit +`.steadfast/roadmap.yaml` only for status, evidence and checkpoint. ## 1. Plan the path set @@ -97,9 +95,8 @@ Then set `status: active` and run `verify`. - If a rule changes, run `steadfast supersede --decision ""`. - If you learn a fact code cannot prove yet, record it with `steadfast finding new`; retire it when a test proves it. - Unenforceable rules are advisory and expire. -- When a roadmap step is finished, set `status: done` and `evidence: ` in `.steadfast/roadmap.yaml`, then make the next unblocked step - `current`. +- When a step is finished, set `status: done`, `evidence: `, + drop its checkpoint, and make the next unblocked step `current`. ## 7. Hand off @@ -109,8 +106,10 @@ Tell the human only: - decisions that need approval, one line each - any guard that blocked a path -Leave a durable handoff in the commit body or an issue: `Finding:`, `Decision:`, -`Next:`. Update README `Status` on release changes. +Before each commit and before you stop, rewrite the current step's +`checkpoint`: `next` (one action), `done` (max 3), `open` (max 2); `check +--diff` fails if step paths changed but it did not. Update README `Status` on +release changes. ## Stop conditions diff --git a/src/commands/brief.ts b/src/commands/brief.ts index 27cb822..c2680d8 100644 --- a/src/commands/brief.ts +++ b/src/commands/brief.ts @@ -4,7 +4,7 @@ import { parseArgs } from "node:util"; import { buildFindingGraph, findingTokens, staleFindingAge } from "../core/finding.js"; import { tryGit } from "../core/git.js"; import { buildGraph } from "../core/graph.js"; -import { loadRoadmap, stepTokens } from "../core/roadmap.js"; +import { checkpointLines, loadRoadmap, stepTokens } from "../core/roadmap.js"; import { loadProject } from "../core/store.js"; import { estimateTokens, recordTokens } from "../core/tokens.js"; import { write, writeError } from "../output.js"; @@ -84,6 +84,7 @@ function stepDetail(step: Step): string[] { function roadmapSections(roadmap: Roadmap | undefined): { summary: string[]; current: Section; + checkpoint: Section; next: Section; blocked: Section; } { @@ -91,6 +92,7 @@ function roadmapSections(roadmap: Roadmap | undefined): { return { summary: ["roadmap: none (create .steadfast/roadmap.yaml)"], current: { name: "current", lines: [], optional: false }, + checkpoint: { name: "checkpoint", lines: [], optional: false }, next: { name: "next", lines: [], optional: true }, blocked: { name: "blocked", lines: [], optional: true }, }; @@ -107,6 +109,16 @@ function roadmapSections(roadmap: Roadmap | undefined): { currentStep === undefined ? { name: "current", lines: ["current: none"], optional: false } : { name: "current", lines: ["current:", ...stepDetail(currentStep).map((line) => ` ${line}`)], optional: false }; + const checkpoint: Section = { + name: "checkpoint", + lines: + currentStep === undefined + ? [] + : currentStep.checkpoint === undefined + ? ["checkpoint: none (write checkpoint.next before the session ends)"] + : ["checkpoint:", ...checkpointLines(currentStep.checkpoint).map((line) => ` ${line}`)], + optional: false, + }; const nextSteps = roadmap.steps.filter((step) => step.status === "todo").slice(0, 2); const next = @@ -127,7 +139,7 @@ function roadmapSections(roadmap: Roadmap | undefined): { optional: true, }; - return { summary, current, next, blocked }; + return { summary, current, checkpoint, next, blocked }; } function memoryLine( @@ -192,6 +204,7 @@ function render( } if (count() > bodyBudget) { const current = present.find((section) => section.name === "current"); + const checkpoint = present.find((section) => section.name === "checkpoint"); const summary = present.filter((section) => ["memory", "git", "roadmap"].includes(section.name), ); @@ -199,6 +212,7 @@ function render( current === undefined ? summary : [...summary, { ...current, lines: current.lines.slice(0, 2).map((line) => truncate(line, 60)) }]; + if (checkpoint !== undefined) fallback.push(checkpoint); present = fallback; omitted.push("detail"); } @@ -241,8 +255,8 @@ export async function briefCommand(argv: string[]): Promise { if (values.help) { write("steadfast brief [--json] [--budget ]"); write(""); - write(" Prints the current roadmap step, next steps, blockers, recent commits,"); - write(" worktrees and memory stats. Run at the start of a session."); + write(" Prints the current roadmap step and its checkpoint, next steps, blockers,"); + write(" recent commits, worktrees and memory stats. Run at the start of a session."); write(" --budget may only lower budgets.brief_tokens."); return 0; } @@ -337,6 +351,7 @@ export async function briefCommand(argv: string[]): Promise { { name: "worktrees", lines: worktreeLine, optional: true }, { name: "roadmap", lines: sections.summary, optional: false }, sections.current, + sections.checkpoint, { name: "warnings", lines: @@ -396,6 +411,7 @@ export async function briefCommand(argv: string[]): Promise { budget: cap, omitted: output.omitted, current: currentStep?.id ?? null, + checkpoint: currentStep?.checkpoint ?? null, next: next.map((step) => step.id), blocked: blocked.map((step) => step.id), memory: { tokens: memory.tokens }, diff --git a/src/commands/check.ts b/src/commands/check.ts index aa15f1c..e4b9dcf 100644 --- a/src/commands/check.ts +++ b/src/commands/check.ts @@ -21,13 +21,13 @@ import { matchesAny } from "../core/glob.js"; import type { Change } from "../core/git.js"; import { buildGraph } from "../core/graph.js"; import { safeFile } from "../core/paths.js"; -import { loadRoadmap } from "../core/roadmap.js"; +import { checkpointKey, loadRoadmap, ROADMAP_FILE, validateRoadmap } from "../core/roadmap.js"; import { installedSkillTargets, readCanonicalSkill } from "../core/skill.js"; import { loadProject } from "../core/store.js"; import { estimateTokens, recordTokens } from "../core/tokens.js"; import { validateConfig, validateDecision } from "../core/validate.js"; import { paint, write, writeError } from "../output.js"; -import type { Config, Decision, Finding, Issue } from "../types.js"; +import type { Checkpoint, Config, Decision, Finding, Issue, Step } from "../types.js"; import { resolveExistingRoot } from "./shared.js"; const DEBT_TRIGGERS: RegExp[] = [ @@ -119,6 +119,24 @@ function canonical(decision: Decision): string { }); } +function underStep(path: string, step: Step): boolean { + return ( + matchesAny(path, step.paths) || + step.paths.some((selector) => path.startsWith(`${selector.replace(/\/+$/, "")}/`)) + ); +} + +function checkpointAtRef(root: string, ref: string, id: string): Checkpoint | undefined { + const text = fileAtRef(root, ref, ROADMAP_FILE); + if (text === undefined) return undefined; + try { + return validateRoadmap(parse(text), ROADMAP_FILE).value?.steps.find((step) => step.id === id) + ?.checkpoint; + } catch { + return undefined; + } +} + export async function checkCommand(argv: string[]): Promise { const { values } = parseArgs({ args: argv, @@ -583,6 +601,29 @@ export async function checkCommand(argv: string[]): Promise { }); } + if (roadmapCurrent !== undefined) { + const touched = changed.filter( + (path) => path !== ROADMAP_FILE && underStep(path, roadmapCurrent), + ); + if ( + touched.length > 0 && + (roadmapCurrent.checkpoint === undefined || + checkpointKey(roadmapCurrent.checkpoint) === + checkpointKey(checkpointAtRef(root, ref, roadmapCurrent.id))) + ) { + issues.push({ + severity: "warning", + code: "roadmap/checkpoint-stale", + message: `${roadmapCurrent.id} paths changed but its checkpoint did not: ${touched + .slice(0, 3) + .join(", ")}${touched.length > 3 ? ` +${touched.length - 3}` : ""}`, + file: ROADMAP_FILE, + id: roadmapCurrent.id, + fix: "rewrite checkpoint.next (and done, open) so the next session can resume", + }); + } + } + const readRecord = (file: string): Decision | undefined => { const text = fileAtRef(root, ref, file); if (text === undefined) return undefined; diff --git a/src/commands/hook.ts b/src/commands/hook.ts index 793569b..94929d3 100644 --- a/src/commands/hook.ts +++ b/src/commands/hook.ts @@ -12,8 +12,9 @@ import { basename, dirname, join, relative } from "node:path"; import { parseArgs } from "node:util"; import { gitCommonDir, gitPath, gitRoot } from "../core/git.js"; import { relativeInside } from "../core/paths.js"; -import { toPosix } from "../util.js"; +import { isObject, toPosix } from "../util.js"; import { paint, write, writeError } from "../output.js"; +import { writeConfig } from "./mcp.js"; import { resolveExistingRoot } from "./shared.js"; const BEGIN = "# steadfast:begin"; @@ -74,6 +75,102 @@ ${END} `; } +export function sessionSettingsPath(root: string): string { + return join(root, ".claude", "settings.json"); +} + +function briefCommandFor(root: string): string { + if (existsSync(join(root, "node_modules", ".bin", "steadfast"))) { + return "./node_modules/.bin/steadfast brief"; + } + const running = process.argv[1] === undefined ? undefined : realPath(process.argv[1]); + const rootReal = realPath(root); + const local = + running === undefined || rootReal === undefined ? undefined : relativeInside(rootReal, running); + if (local !== undefined && !local.startsWith("node_modules/")) return `node ${local} brief`; + return "npx -y steadfast-docs brief"; +} + +function isSessionEntry(entry: unknown): boolean { + if (!isObject(entry) || !Array.isArray(entry.hooks)) return false; + return entry.hooks.some( + (hook) => + isObject(hook) && + typeof hook.command === "string" && + /steadfast/.test(hook.command) && + / brief\b/.test(hook.command), + ); +} + +function readSettings(path: string): Record | string { + if (!existsSync(path)) return {}; + try { + const parsed: unknown = JSON.parse(readFileSync(path, "utf8")); + return isObject(parsed) ? parsed : `error: ${path} must hold a JSON object`; + } catch (error) { + return `error: ${path} is not plain JSON (${(error as Error).message})`; + } +} + +function sessionEntries(settings: Record): unknown[] { + const hooks = isObject(settings.hooks) ? settings.hooks : {}; + return Array.isArray(hooks.SessionStart) ? hooks.SessionStart : []; +} + +export function sessionHookInstalled(root: string): boolean { + const settings = readSettings(sessionSettingsPath(root)); + return typeof settings !== "string" && sessionEntries(settings).some(isSessionEntry); +} + +function installSession(root: string): number { + const path = sessionSettingsPath(root); + const settings = readSettings(path); + if (typeof settings === "string") { + writeError(settings); + return 2; + } + const hooks = isObject(settings.hooks) ? settings.hooks : {}; + hooks.SessionStart = [ + ...sessionEntries(settings).filter((entry) => !isSessionEntry(entry)), + { hooks: [{ type: "command", command: briefCommandFor(root) }] }, + ]; + settings.hooks = hooks; + const written = writeConfig(root, path, settings); + if (written.startsWith("error:")) { + writeError(written); + return 2; + } + write(`${paint.green("installed")} SessionStart brief in ${written}`); + write("every new, resumed, cleared or compacted Claude Code session starts with the brief"); + return 0; +} + +function removeSession(root: string): number { + const path = sessionSettingsPath(root); + const settings = readSettings(path); + if (typeof settings === "string") { + writeError(settings); + return 2; + } + const entries = sessionEntries(settings); + if (!entries.some(isSessionEntry)) { + write("no SessionStart brief found; left untouched"); + return 0; + } + const hooks = settings.hooks as Record; + const rest = entries.filter((entry) => !isSessionEntry(entry)); + if (rest.length > 0) hooks.SessionStart = rest; + else delete hooks.SessionStart; + if (Object.keys(hooks).length === 0) delete settings.hooks; + const written = writeConfig(root, path, settings); + if (written.startsWith("error:")) { + writeError(written); + return 2; + } + write(`removed SessionStart brief from ${written}`); + return 0; +} + function writeHook(hookPath: string, content: string): void { mkdirSync(dirname(hookPath), { recursive: true }); writeFileSync(hookPath, `${content.trimEnd()}\n`); @@ -174,6 +271,7 @@ export async function hookCommand(argv: string[]): Promise { options: { root: { type: "string" }, check: { type: "boolean", default: false }, + platform: { type: "string" }, help: { type: "boolean", short: "h", default: false }, }, allowPositionals: true, @@ -181,11 +279,12 @@ export async function hookCommand(argv: string[]): Promise { }); if (values.help || positionals.length === 0) { - write("steadfast hook install|remove [--check] [--root ]"); + write("steadfast hook install|remove [--platform claude] [--check] [--root ]"); write(""); - write(" install add a managed check --strict block to the git pre-commit hook"); - write(" remove remove only the steadfast block, restoring any chained hook"); - write(" --check report whether the hook is installed"); + write(" install add a managed check --strict block to the git pre-commit hook"); + write(" remove remove only the steadfast block, restoring any chained hook"); + write(" --platform claude: also run brief at every session start (.claude/settings.json)"); + write(" --check report whether the hooks are installed"); return 0; } @@ -194,6 +293,15 @@ export async function hookCommand(argv: string[]): Promise { writeError("error: usage: steadfast hook install|remove"); return 2; } + if (values.platform === "opencode") { + writeError("error: opencode has no session-start context hook; AGENTS.md tells the agent to run brief"); + return 2; + } + if (values.platform !== undefined && values.platform !== "claude") { + writeError(`error: unsupported platform "${values.platform}"; use claude`); + return 2; + } + const session = values.platform === "claude"; const root = resolveExistingRoot(values.root); if (root === undefined) { @@ -240,19 +348,39 @@ export async function hookCommand(argv: string[]): Promise { } if (values.check) { + let status = 0; const installed = existsSync(hookPath) && readFileSync(hookPath, "utf8").includes(BEGIN); if (installed) { write(`${paint.green("ok")} ${hookPath}`); - return 0; + } else { + writeError("missing: pre-commit hook"); + writeError("fix: steadfast hook install"); + status = 1; } - writeError("missing: pre-commit hook"); - writeError("fix: steadfast hook install"); - return 1; + if (session) { + if (sessionHookInstalled(root)) { + write(`${paint.green("ok")} SessionStart brief in ${sessionSettingsPath(root)}`); + } else { + writeError("missing: SessionStart brief"); + writeError("fix: steadfast hook install --platform claude"); + status = 1; + } + } + return status; } if (action === "remove") { - return remove(hookPath); + const status = remove(hookPath); + return status !== 0 || !session ? status : removeSession(root); } - return install(root, git, hookPath); + if (session) { + const settings = readSettings(sessionSettingsPath(root)); + if (typeof settings === "string") { + writeError(settings); + return 2; + } + } + const status = install(root, git, hookPath); + return status !== 0 || !session ? status : installSession(root); } diff --git a/src/commands/init.ts b/src/commands/init.ts index fbfbeae..1d80733 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -15,7 +15,8 @@ const AGENTS_BLOCK = `${BEGIN} If the steadfast MCP server is connected, call \`steadfast_context\` (OpenCode) or \`mcp__steadfast__context\` (Claude) with the paths you will touch; otherwise run \`npx steadfast-docs context --for \`. Use only that output for context. If context fails, narrow the paths or ask the human before raising the budget; do not pass \`--allow-partial\`. Records are not reading material: do not load other records, legacy docs or architecture notes. The pack is the only context. -At session start, run \`npx steadfast-docs brief\` to recover the current roadmap step. Update \`.steadfast/roadmap.yaml\` when a step starts or finishes. +At session start, run \`npx steadfast-docs brief\` to recover the current roadmap step and its checkpoint. Update \`.steadfast/roadmap.yaml\` when a step starts or finishes. +Before each commit and before the session ends, rewrite the current step's \`checkpoint\` (\`next\`, \`done\`, \`open\`) so the next session resumes where this one stopped. If you discover a fact code cannot prove yet, record a finding; retire it when a test proves it. After a new record, fill the record you just created. Never edit an active record; supersede it. diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index 5d8a376..4700854 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -65,7 +65,7 @@ function targetProblem( } } -function writeConfig( +export function writeConfig( root: string, path: string, config: Record, diff --git a/src/core/roadmap.ts b/src/core/roadmap.ts index e87d5b0..b74af81 100644 --- a/src/core/roadmap.ts +++ b/src/core/roadmap.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { parse } from "yaml"; -import type { Issue, Roadmap, Severity, Step, StepStatus } from "../types.js"; +import type { Checkpoint, Issue, Roadmap, Severity, Step, StepStatus } from "../types.js"; import { estimateTokens } from "./tokens.js"; import { safeFile } from "./paths.js"; import { isObject } from "../util.js"; @@ -18,7 +18,9 @@ export const STEP_FIELDS = [ "blocked_by", "decisions", "findings", + "checkpoint", ] as const; +export const CHECKPOINT_FIELDS = ["next", "done", "open"] as const; const STEP_ID_RE = /^STEP-[0-9]{3,}$/; const DECISION_ID_RE = /^ADR-[0-9]{4,}$/; @@ -161,6 +163,33 @@ function readArray( return out; } +function readCheckpoint( + raw: Record, + issues: Issue[], + file: string, + id: string | undefined, +): Checkpoint | undefined { + const value = raw.checkpoint; + if (value === undefined) return undefined; + if (!isObject(value)) { + error(issues, "schema/type", `"checkpoint" must be a mapping`, file, id); + return undefined; + } + for (const key of Object.keys(value)) { + if (!CHECKPOINT_FIELDS.includes(key as (typeof CHECKPOINT_FIELDS)[number])) { + error(issues, "schema/unknown-field", `unknown field "checkpoint.${key}"`, file, id, `remove "${key}"`); + } + } + const next = readString(value, "next", 160, issues, file, id, true); + const done = readArray(value, "done", 3, 100, issues, file, id, false); + const open = readArray(value, "open", 2, 100, issues, file, id, false); + if (next === undefined) return undefined; + const checkpoint: Checkpoint = { next }; + if (done && done.length > 0) checkpoint.done = done; + if (open && open.length > 0) checkpoint.open = open; + return checkpoint; +} + export function validateRoadmap( raw: unknown, file: string, @@ -276,6 +305,17 @@ export function validateRoadmap( if (status === "blocked" && blockedBy === undefined) { error(issues, "roadmap/blocked-by", "blocked steps require blocked_by: a step id or the reason", file, id); } + const checkpoint = readCheckpoint(entry, issues, file, id); + if (entry.checkpoint !== undefined && (status === "done" || status === "dropped")) { + error( + issues, + "roadmap/checkpoint-closed", + `${status} steps carry no checkpoint`, + file, + id, + "record lasting facts as findings or decisions, then remove the checkpoint", + ); + } if (id === undefined || goal === undefined || why === undefined || acceptance === undefined || paths === undefined || status === undefined) { continue; @@ -285,6 +325,7 @@ export function validateRoadmap( if (blockedBy !== undefined) value.blocked_by = blockedBy; if (decisions && decisions.length > 0) value.decisions = decisions; if (findings && findings.length > 0) value.findings = findings; + if (checkpoint !== undefined) value.checkpoint = checkpoint; steps.push(value); } @@ -413,6 +454,21 @@ export function stepTokens(step: Step): number { paths: step.paths, decisions: step.decisions ?? [], findings: step.findings ?? [], + checkpoint: step.checkpoint ?? {}, }), ); } + +export function checkpointLines(checkpoint: Checkpoint): string[] { + return [ + `next: ${checkpoint.next}`, + ...(checkpoint.done ?? []).map((item) => `done: ${item}`), + ...(checkpoint.open ?? []).map((item) => `open: ${item}`), + ]; +} + +/** Stable identity of a checkpoint, so a diff can tell whether it moved. */ +export function checkpointKey(checkpoint: Checkpoint | undefined): string { + if (checkpoint === undefined) return ""; + return JSON.stringify([checkpoint.next, checkpoint.done ?? [], checkpoint.open ?? []]); +} diff --git a/src/types.ts b/src/types.ts index f0201a0..e03e2d2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -103,6 +103,13 @@ export interface Step { blocked_by?: string; decisions?: string[]; findings?: string[]; + checkpoint?: Checkpoint; +} + +export interface Checkpoint { + next: string; + done?: string[]; + open?: string[]; } export interface Roadmap { diff --git a/test/checkpoint.test.ts b/test/checkpoint.test.ts new file mode 100644 index 0000000..ce618f5 --- /dev/null +++ b/test/checkpoint.test.ts @@ -0,0 +1,155 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import test from "node:test"; +import { cli, tempDir, write } from "./helpers.js"; + +const TODAY = new Date().toISOString().slice(0, 10); + +function git(root: string, args: string[]): string { + return execFileSync("git", args, { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); +} + +function project(): string { + const root = tempDir(); + write(root, "src/a.ts", "export const a = 1;\n"); + write(root, "docs/notes.txt", "notes\n"); + write(root, "test/a.test.ts", "export {};\n"); + assert.equal(cli(["init"], root).status, 0); + return root; +} + +function repo(): string { + const root = project(); + git(root, ["init", "-q"]); + git(root, ["config", "user.email", "test@example.com"]); + git(root, ["config", "user.name", "test"]); + return root; +} + +function commitAll(root: string, message: string): void { + git(root, ["add", "-A"]); + git(root, ["commit", "-q", "-m", message]); +} + +function roadmap(root: string, checkpoint: string, status = "current"): void { + write( + root, + ".steadfast/roadmap.yaml", + `version: 1 +updated: ${TODAY} +steps: + - id: STEP-001 + goal: Add the cleanup job + why: Inactive users keep rows forever. + paths: [src] + acceptance: run test/a.test.ts + status: ${status} +${status === "done" ? " evidence: test/a.test.ts\n" : ""}${checkpoint}`, + ); +} + +const CHECKPOINT = ` checkpoint: + next: Wire the job into the scheduler + done: ["Migration and handler"] + open: ["Retention window is a guess"] +`; + +test("brief shows where the last session stopped", () => { + const root = project(); + roadmap(root, CHECKPOINT); + + const result = cli(["brief"], root); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /checkpoint:\n {2}next: Wire the job into the scheduler\n {2}done: Migration and handler\n {2}open: Retention window is a guess/); + + const json = JSON.parse(cli(["brief", "--json"], root).stdout) as { + checkpoint: { next: string; done: string[] }; + }; + assert.equal(json.checkpoint.next, "Wire the job into the scheduler"); + assert.deepEqual(json.checkpoint.done, ["Migration and handler"]); +}); + +test("brief asks for a checkpoint when the current step has none", () => { + const root = project(); + roadmap(root, ""); + + const result = cli(["brief"], root); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /checkpoint: none \(write checkpoint\.next/); +}); + +test("brief keeps the checkpoint when the budget forces the fallback", () => { + const root = project(); + roadmap(root, CHECKPOINT); + + const result = cli(["brief", "--budget", "120"], root); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /next: Wire the job/); +}); + +test("checkpoints are bounded and need a next action", () => { + const cases: Array<[string, RegExp]> = [ + [" checkpoint:\n done: [\"a\"]\n", /missing required field "next"/], + [" checkpoint:\n next: x\n later: y\n", /unknown field "checkpoint\.later"/], + [" checkpoint:\n next: x\n done: [a, b, c, d]\n", /"done" has 4 items; limit is 3/], + [` checkpoint:\n next: ${"x".repeat(161)}\n`, /"next" is 161 chars; limit is 160/], + [" checkpoint: resume later\n", /"checkpoint" must be a mapping/], + ]; + for (const [checkpoint, expected] of cases) { + const root = project(); + roadmap(root, checkpoint); + const result = cli(["check"], root); + assert.equal(result.status, 1, checkpoint); + assert.match(result.stdout + result.stderr, expected); + } +}); + +test("done steps carry no checkpoint", () => { + const root = project(); + roadmap(root, CHECKPOINT, "done"); + + const result = cli(["check"], root); + assert.equal(result.status, 1); + assert.match(result.stdout + result.stderr, /roadmap\/checkpoint-closed/); +}); + +test("check --diff flags step work that left the checkpoint behind", () => { + const root = repo(); + roadmap(root, CHECKPOINT); + commitAll(root, "base"); + + write(root, "src/a.ts", "export const a = 2;\n"); + const stale = cli(["check", "--strict", "--diff", "HEAD"], root); + assert.equal(stale.status, 1); + assert.match(stale.stdout + stale.stderr, /roadmap\/checkpoint-stale/); + assert.match(stale.stdout + stale.stderr, /src\/a\.ts/); + + roadmap(root, CHECKPOINT.replace("Wire the job into the scheduler", "Add the retention test")); + const fresh = cli(["check", "--strict", "--diff", "HEAD"], root); + assert.doesNotMatch(fresh.stdout + fresh.stderr, /checkpoint-stale/); +}); + +test("check --diff requires a checkpoint once step work starts", () => { + const root = repo(); + roadmap(root, ""); + commitAll(root, "base"); + + write(root, "src/a.ts", "export const a = 2;\n"); + const result = cli(["check", "--strict", "--diff", "HEAD"], root); + assert.equal(result.status, 1); + assert.match(result.stdout + result.stderr, /roadmap\/checkpoint-stale/); +}); + +test("check --diff ignores changes outside the current step", () => { + const root = repo(); + roadmap(root, CHECKPOINT); + commitAll(root, "base"); + + write(root, "docs/notes.txt", "more notes\n"); + const result = cli(["check", "--strict", "--diff", "HEAD"], root); + assert.doesNotMatch(result.stdout + result.stderr, /checkpoint-stale/); +}); diff --git a/test/hook.test.ts b/test/hook.test.ts index 0c96e80..b819ad9 100644 --- a/test/hook.test.ts +++ b/test/hook.test.ts @@ -402,3 +402,69 @@ test("the hook works when the project is below the git root", () => { }); assert.equal(passed.status, 0, `${passed.stdout}${passed.stderr}`); }); + +test("hook install --platform claude runs brief at every session start", () => { + const root = project(); + write( + root, + ".claude/settings.json", + JSON.stringify({ + permissions: { allow: ["Bash(ls)"] }, + hooks: { SessionStart: [{ hooks: [{ type: "command", command: "echo hi" }] }] }, + }), + ); + + assert.equal(cli(["hook", "install", "--platform", "claude"], root).status, 0); + assert.equal(cli(["hook", "install", "--platform", "claude"], root).status, 0); + const settings = JSON.parse(readFileSync(join(root, ".claude", "settings.json"), "utf8")) as { + permissions: unknown; + hooks: { SessionStart: Array<{ matcher?: string; hooks: Array<{ command: string }> }> }; + }; + assert.deepEqual(settings.permissions, { allow: ["Bash(ls)"] }); + const commands = settings.hooks.SessionStart.flatMap((entry) => entry.hooks.map((hook) => hook.command)); + assert.deepEqual(commands, ["echo hi", "npx -y steadfast-docs brief"]); + assert.ok(settings.hooks.SessionStart.every((entry) => entry.matcher === undefined)); + + const check = cli(["hook", "install", "--platform", "claude", "--check"], root); + assert.equal(check.status, 0, check.stderr); + assert.match(check.stdout, /SessionStart brief/); + + assert.equal(cli(["hook", "remove", "--platform", "claude"], root).status, 0); + const after = JSON.parse(readFileSync(join(root, ".claude", "settings.json"), "utf8")) as { + hooks: { SessionStart: Array<{ hooks: Array<{ command: string }> }> }; + }; + assert.deepEqual( + after.hooks.SessionStart.flatMap((entry) => entry.hooks.map((hook) => hook.command)), + ["echo hi"], + ); + const missing = cli(["hook", "install", "--platform", "claude", "--check"], root); + assert.equal(missing.status, 1); + assert.match(missing.stderr, /missing: SessionStart brief/); +}); + +test("hook install --platform prefers a locally installed CLI", () => { + const root = project(); + write(root, "node_modules/.bin/steadfast", "#!/bin/sh\n"); + assert.equal(cli(["hook", "install", "--platform", "claude"], root).status, 0); + const text = readFileSync(join(root, ".claude", "settings.json"), "utf8"); + assert.match(text, /\.\/node_modules\/\.bin\/steadfast brief/); +}); + +test("hook install refuses platforms without a session-start hook", () => { + const root = project(); + const opencode = cli(["hook", "install", "--platform", "opencode"], root); + assert.equal(opencode.status, 2); + assert.match(opencode.stderr, /no session-start context hook/); + assert.equal(existsSync(join(root, ".git", "hooks", "pre-commit")), false); + assert.equal(cli(["hook", "install", "--platform", "cursor"], root).status, 2); +}); + +test("hook install --platform claude refuses malformed settings", () => { + const root = project(); + write(root, ".claude/settings.json", "{ not json"); + const result = cli(["hook", "install", "--platform", "claude"], root); + assert.equal(result.status, 2); + assert.match(result.stderr, /not plain JSON/); + assert.equal(readFileSync(join(root, ".claude", "settings.json"), "utf8"), "{ not json"); + assert.equal(existsSync(join(root, ".git", "hooks", "pre-commit")), false); +}); diff --git a/test/validate.test.ts b/test/validate.test.ts index cb2d4eb..175ba3f 100644 --- a/test/validate.test.ts +++ b/test/validate.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import test from "node:test"; import { FINDING_FIELDS } from "../src/core/finding.js"; -import { ROADMAP_FIELDS, STEP_FIELDS } from "../src/core/roadmap.js"; +import { CHECKPOINT_FIELDS, ROADMAP_FIELDS, STEP_FIELDS } from "../src/core/roadmap.js"; import { CONFIG_BUDGET_FIELDS, CONFIG_FIELDS, @@ -195,12 +195,17 @@ test("json schemas stay in sync with the validator", () => { decisions: { items: { maxLength?: number } }; }; }; + checkpoint: { properties: Record }; }; }; assert.deepEqual(Object.keys(roadmap.properties).sort(), [...ROADMAP_FIELDS].sort()); assert.deepEqual(Object.keys(roadmap.$defs.step.properties).sort(), [...STEP_FIELDS].sort()); assert.equal(roadmap.allOf.length, 1); - assert.equal(roadmap.$defs.step.allOf.length, 2); + assert.equal(roadmap.$defs.step.allOf.length, 3); + assert.deepEqual( + Object.keys(roadmap.$defs.checkpoint.properties).sort(), + [...CHECKPOINT_FIELDS].sort(), + ); assert.equal(roadmap.$defs.step.properties.id.maxLength, 32); assert.equal(roadmap.$defs.step.properties.decisions.items.maxLength, 32); assert.ok(roadmap.$defs.step.properties.paths.items.pattern?.includes("\\.")); From f478ed9ceed3f6ea9497f1930a64f93a29ffec95 Mon Sep 17 00:00:00 2001 From: done6666 Date: Fri, 30 Oct 2026 04:57:04 +0300 Subject: [PATCH 2/2] feat(hook): push the brief into every OpenCode compaction `hook install --platform opencode` now writes a managed .opencode/plugins/steadfast-brief.js on OpenCode's experimental.session.compacting hook. The plugin runs the project's own brief and pushes it into output.context, so the summary a compacted session continues from carries the current step and its checkpoint; if brief fails it tells the agent to run it. `hook remove --platform opencode` deletes only that file, `--check` reports it, and a plugin file steadfast did not write is never overwritten or removed. ADR-0020 supersedes ADR-0019 with the OpenCode rule. Co-Authored-By: Claude Opus 5.5 --- .steadfast/decisions/ADR-0009.yaml | 2 +- .steadfast/decisions/ADR-0010.yaml | 2 +- .steadfast/decisions/ADR-0020.yaml | 18 ++++ .steadfast/roadmap.yaml | 8 ++ README.md | 10 ++- src/commands/hook.ts | 136 ++++++++++++++++++++++++++--- src/commands/mcp.ts | 17 +++- test/hook.test.ts | 116 ++++++++++++++++++++++-- 8 files changed, 280 insertions(+), 29 deletions(-) create mode 100644 .steadfast/decisions/ADR-0020.yaml diff --git a/.steadfast/decisions/ADR-0009.yaml b/.steadfast/decisions/ADR-0009.yaml index a9c0e6f..9a348f8 100644 --- a/.steadfast/decisions/ADR-0009.yaml +++ b/.steadfast/decisions/ADR-0009.yaml @@ -13,5 +13,5 @@ decision: The MCP server wraps the CLI, so every command has one implementation why: - A second implementation would drift and double the test burden. enforced_by: test/mcp.test.ts -verified_by: h1:f74039e2802c8aad252e83ca1383e4b97326a6f4929ae8980146646636392e16 +verified_by: h1:d309321c91f8d88ca63ee8392f1986074d0d002b03fad93861f014c8ae3e7caa by: agent diff --git a/.steadfast/decisions/ADR-0010.yaml b/.steadfast/decisions/ADR-0010.yaml index 6e80da6..0fee1eb 100644 --- a/.steadfast/decisions/ADR-0010.yaml +++ b/.steadfast/decisions/ADR-0010.yaml @@ -11,5 +11,5 @@ decision: The pre-commit hook validates the index, and refuses when governed fil why: - A hook that reads only the working tree can approve a different commit. enforced_by: test/hook.test.ts -verified_by: h1:b870406ba14ecc656dbedb6d41e4f18efc669c23adf0523440cbb3255ea0d099 +verified_by: h1:d25df35a4e112b7dd104ffd44707150645862e21ab0dbe5904ae6853dc47ae18 by: agent diff --git a/.steadfast/decisions/ADR-0020.yaml b/.steadfast/decisions/ADR-0020.yaml new file mode 100644 index 0000000..4946d33 --- /dev/null +++ b/.steadfast/decisions/ADR-0020.yaml @@ -0,0 +1,18 @@ +id: ADR-0020 +topic: session-start +scope: global +status: active +created: 2026-10-30 +applies_to: + - src/commands/hook.ts + - test/hook.test.ts +decision: hook install --platform claude adds a SessionStart brief; --platform opencode writes a managed .opencode/plugins/steadfast-brief.js pushing brief into compaction context. +why: + - Agents skip memory they must pull; harness hooks push it at Claude session start and into every OpenCode compaction. +rejected: + - "Setting output.prompt: it replaces OpenCode's own compaction prompt instead of adding to it." +enforced_by: test/hook.test.ts +verified_by: h1:c1bafd596bfa9c6895d6fbdcc960533022f286c3fa36190ffdb5bb2e19106ad5 +supersedes: + - ADR-0019 +by: agent diff --git a/.steadfast/roadmap.yaml b/.steadfast/roadmap.yaml index 4e94841..660e6d1 100644 --- a/.steadfast/roadmap.yaml +++ b/.steadfast/roadmap.yaml @@ -10,3 +10,11 @@ steps: status: done evidence: test/checkpoint.test.ts decisions: [ADR-0018, ADR-0019] + - id: STEP-002 + goal: Push the brief into every OpenCode compaction + why: OpenCode has no session-start hook, so a compacted session loses the step unless the summary carries it. + paths: [src/commands/hook.ts, src/commands/mcp.ts, test/hook.test.ts, README.md] + acceptance: npm test and steadfast check --strict pass + status: done + evidence: test/hook.test.ts + decisions: [ADR-0020] diff --git a/README.md b/README.md index 75a612c..3354ea1 100644 --- a/README.md +++ b/README.md @@ -54,11 +54,11 @@ One-time setup. After this, you do not run the loop; the agent does. ```bash npx steadfast-docs init npx steadfast-docs mcp install --platform opencode # or --platform claude -npx steadfast-docs hook install # add --platform claude for a session-start brief +npx steadfast-docs hook install --platform opencode # or claude: pushes the brief into new or compacted sessions npx steadfast-docs skill install --platform opencode ``` -`init` writes `.steadfast/` and appends the contract to `AGENTS.md`. `mcp install` gives the agent native tools, `hook install` gates commits (and with `--platform claude` starts every session with the brief), and the skill teaches the loop. From then on, you talk to the agent: +`init` writes `.steadfast/` and appends the contract to `AGENTS.md`. `mcp install` gives the agent native tools, `hook install` gates commits (and with `--platform` pushes the brief into new or compacted sessions), and the skill teaches the loop. From then on, you talk to the agent: > “Add a refund endpoint.” @@ -79,7 +79,9 @@ The server exposes `brief`, `context`, `check`, `verify`, `new`, `finding`, `exp `hook install` adds a managed block to the real git hooks directory (respecting a repo-local `core.hooksPath`, worktrees and submodules) that runs `check --strict --staged --diff HEAD`. `--staged` refuses to validate a working tree that differs from the index, so what the hook approves is what the commit contains. An existing hook is chained as `pre-commit.steadfast-original` (non-shell hooks included), runs before the check, and is restored by `hook remove`. A hooks directory shared outside the repository is refused, because a project-specific hook would run in every repo. -`hook install --platform claude` also adds a `SessionStart` hook to `.claude/settings.json` that runs `brief`. Every new, resumed, cleared or compacted Claude Code session starts with the current step and its checkpoint, so the agent never has to remember to ask. Other hooks and settings are preserved, and `hook remove --platform claude` takes out only this entry. OpenCode has no documented session-start context hook; there the `AGENTS.md` contract tells the agent to run `brief`. `doctor` then reports the contract, skill copy, MCP config, hook, freshness, advisory rules and retired docs in one pass. +`hook install --platform claude` also adds a `SessionStart` hook to `.claude/settings.json` that runs `brief`. Every new, resumed, cleared or compacted Claude Code session starts with the current step and its checkpoint, so the agent never has to remember to ask. Other hooks and settings are preserved, and `hook remove --platform claude` takes out only this entry. + +`hook install --platform opencode` writes a managed plugin, `.opencode/plugins/steadfast-brief.js`, for OpenCode's `experimental.session.compacting` hook (experimental upstream, so it may change). When a session fills up and compacts, the plugin runs the project's own `brief` (the CLI in `node_modules`, the local build, or `npx`) and adds it to the compaction context, so the summary the session continues from carries the current step and its checkpoint. If `brief` fails, the plugin tells the agent to run it instead. OpenCode documents no session-start context hook, so a brand-new session still relies on the `AGENTS.md` contract to run `brief`. `hook remove --platform opencode` deletes only that file, and a plugin file steadfast did not write is never overwritten or removed. `doctor` then reports the contract, skill copy, MCP config, hook, freshness, advisory rules and retired docs in one pass. ## What a decision looks like @@ -186,7 +188,7 @@ append-only: correct one by appending a successor with `supersedes`. | `npx steadfast-docs verify --assume` | Recompute fingerprints after the tests pass | | `npx steadfast-docs retire --apply [--no-stage]` | Delete legacy docs, stage the change and enforce `retired_docs` | | `npx steadfast-docs mcp install` | Register the MCP server (or run `mcp` to start it) | -| `npx steadfast-docs hook install [--platform claude]` | Add the managed pre-commit `check` and the session-start brief | +| `npx steadfast-docs hook install [--platform claude\|opencode]` | Add the managed pre-commit `check` and the session-start or compaction brief | | `npx steadfast-docs doctor` | Diagnose contract, skill, MCP, hook, freshness and advisories | | `npx steadfast-docs skill install --platform opencode` | Install the agent loop (or `claude`) | diff --git a/src/commands/hook.ts b/src/commands/hook.ts index 94929d3..eab4b47 100644 --- a/src/commands/hook.ts +++ b/src/commands/hook.ts @@ -14,12 +14,13 @@ import { gitCommonDir, gitPath, gitRoot } from "../core/git.js"; import { relativeInside } from "../core/paths.js"; import { isObject, toPosix } from "../util.js"; import { paint, write, writeError } from "../output.js"; -import { writeConfig } from "./mcp.js"; +import { targetProblem, writeConfig, writeText } from "./mcp.js"; import { resolveExistingRoot } from "./shared.js"; const BEGIN = "# steadfast:begin"; const END = "# steadfast:end"; const ORIGINAL = "steadfast-original"; +const PLUGIN_MARKER = "// steadfast:managed"; export function hookPathFor(root: string): string | undefined { if (gitRoot(root) === undefined) return undefined; @@ -79,16 +80,20 @@ export function sessionSettingsPath(root: string): string { return join(root, ".claude", "settings.json"); } -function briefCommandFor(root: string): string { +function briefArgvFor(root: string): string[] { if (existsSync(join(root, "node_modules", ".bin", "steadfast"))) { - return "./node_modules/.bin/steadfast brief"; + return ["./node_modules/.bin/steadfast", "brief"]; } const running = process.argv[1] === undefined ? undefined : realPath(process.argv[1]); const rootReal = realPath(root); const local = running === undefined || rootReal === undefined ? undefined : relativeInside(rootReal, running); - if (local !== undefined && !local.startsWith("node_modules/")) return `node ${local} brief`; - return "npx -y steadfast-docs brief"; + if (local !== undefined && !local.startsWith("node_modules/")) return ["node", local, "brief"]; + return ["npx", "-y", "steadfast-docs", "brief"]; +} + +function briefCommandFor(root: string): string { + return briefArgvFor(root).join(" "); } function isSessionEntry(entry: unknown): boolean { @@ -171,6 +176,85 @@ function removeSession(root: string): number { return 0; } +export function compactionPluginPath(root: string): string { + return join(root, ".opencode", "plugins", "steadfast-brief.js"); +} + +function compactionPlugin(root: string): string { + return `${PLUGIN_MARKER}: written by \`steadfast hook install --platform opencode\`; \`hook remove --platform opencode\` deletes it. +import { execFile } from "node:child_process"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = fileURLToPath(new URL("../..", import.meta.url)); +const [file, ...args] = ${JSON.stringify(briefArgvFor(root))}; +const command = file.includes("/") ? join(root, file) : file; + +function brief() { + return new Promise((resolve) => { + execFile(command, args, { cwd: root, timeout: 30000 }, (error, stdout) => { + resolve(error ? "" : stdout.trim()); + }); + }); +} + +export const SteadfastBrief = async () => ({ + "experimental.session.compacting": async (_input, output) => { + const text = await brief(); + output.context.push( + text + ? "Keep this steadfast brief (current roadmap step and checkpoint) in the summary; the next turn resumes from it.\\n\\n" + text + : "steadfast brief failed during compaction; run it first to recover the current roadmap step.", + ); + }, +}); +`; +} + +function pluginManaged(path: string): boolean { + return existsSync(path) && readFileSync(path, "utf8").startsWith(PLUGIN_MARKER); +} + +export function compactionHookInstalled(root: string): boolean { + return pluginManaged(compactionPluginPath(root)); +} + +function compactionProblem(root: string): string | undefined { + const path = compactionPluginPath(root); + const problem = targetProblem(root, path); + if (problem !== undefined) return problem; + if (existsSync(path) && !pluginManaged(path)) { + return `error: ${path} exists and is not managed by steadfast; move it before installing`; + } + return undefined; +} + +function installCompaction(root: string): number { + const written = writeText(root, compactionPluginPath(root), compactionPlugin(root)); + if (written.startsWith("error:")) { + writeError(written); + return 2; + } + write(`${paint.green("installed")} compaction brief in ${written}`); + write("every OpenCode compaction carries the brief into the summary"); + return 0; +} + +function removeCompaction(root: string): number { + const path = compactionPluginPath(root); + if (!existsSync(path)) { + write("no compaction brief found; left untouched"); + return 0; + } + if (!pluginManaged(path)) { + write(`${path} is not managed by steadfast; left untouched`); + return 0; + } + unlinkSync(path); + write(`removed compaction brief ${path}`); + return 0; +} + function writeHook(hookPath: string, content: string): void { mkdirSync(dirname(hookPath), { recursive: true }); writeFileSync(hookPath, `${content.trimEnd()}\n`); @@ -279,11 +363,12 @@ export async function hookCommand(argv: string[]): Promise { }); if (values.help || positionals.length === 0) { - write("steadfast hook install|remove [--platform claude] [--check] [--root ]"); + write("steadfast hook install|remove [--platform claude|opencode] [--check] [--root ]"); write(""); write(" install add a managed check --strict block to the git pre-commit hook"); write(" remove remove only the steadfast block, restoring any chained hook"); write(" --platform claude: also run brief at every session start (.claude/settings.json)"); + write(" opencode: also push brief into every compaction (.opencode/plugins/)"); write(" --check report whether the hooks are installed"); return 0; } @@ -293,15 +378,16 @@ export async function hookCommand(argv: string[]): Promise { writeError("error: usage: steadfast hook install|remove"); return 2; } - if (values.platform === "opencode") { - writeError("error: opencode has no session-start context hook; AGENTS.md tells the agent to run brief"); - return 2; - } - if (values.platform !== undefined && values.platform !== "claude") { - writeError(`error: unsupported platform "${values.platform}"; use claude`); + if ( + values.platform !== undefined && + values.platform !== "claude" && + values.platform !== "opencode" + ) { + writeError(`error: unsupported platform "${values.platform}"; use claude or opencode`); return 2; } const session = values.platform === "claude"; + const compaction = values.platform === "opencode"; const root = resolveExistingRoot(values.root); if (root === undefined) { @@ -366,12 +452,24 @@ export async function hookCommand(argv: string[]): Promise { status = 1; } } + if (compaction) { + if (compactionHookInstalled(root)) { + write(`${paint.green("ok")} compaction brief in ${compactionPluginPath(root)}`); + } else { + writeError("missing: OpenCode compaction brief"); + writeError("fix: steadfast hook install --platform opencode"); + status = 1; + } + } return status; } if (action === "remove") { const status = remove(hookPath); - return status !== 0 || !session ? status : removeSession(root); + if (status !== 0) return status; + if (session) return removeSession(root); + if (compaction) return removeCompaction(root); + return status; } if (session) { @@ -381,6 +479,16 @@ export async function hookCommand(argv: string[]): Promise { return 2; } } + if (compaction) { + const problem = compactionProblem(root); + if (problem !== undefined) { + writeError(problem); + return 2; + } + } const status = install(root, git, hookPath); - return status !== 0 || !session ? status : installSession(root); + if (status !== 0) return status; + if (session) return installSession(root); + if (compaction) return installCompaction(root); + return status; } diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index 4700854..9986afa 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -38,7 +38,7 @@ function commandExists(name: string): boolean { return spawnSync(finder, [name], { stdio: "ignore" }).status === 0; } -function targetProblem( +export function targetProblem( root: string, path: string, allowOutside = false, @@ -65,10 +65,10 @@ function targetProblem( } } -export function writeConfig( +export function writeText( root: string, path: string, - config: Record, + content: string, allowOutside = false, ): string { const problem = targetProblem(root, path, allowOutside); @@ -76,11 +76,20 @@ export function writeConfig( mkdirSync(dirname(path), { recursive: true }); const temporary = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`); - writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`); + writeFileSync(temporary, content); renameSync(temporary, path); return path; } +export function writeConfig( + root: string, + path: string, + config: Record, + allowOutside = false, +): string { + return writeText(root, path, `${JSON.stringify(config, null, 2)}\n`, allowOutside); +} + function opencodeConfigPaths(root: string, global: boolean): string[] { if (global) { const base = join(homedir(), ".config", "opencode"); diff --git a/test/hook.test.ts b/test/hook.test.ts index b819ad9..de4385b 100644 --- a/test/hook.test.ts +++ b/test/hook.test.ts @@ -11,6 +11,7 @@ import { } from "node:fs"; import { join } from "node:path"; import test from "node:test"; +import { pathToFileURL } from "node:url"; import { CLI, cli, tempDir, write } from "./helpers.js"; const BEGIN = "# steadfast:begin"; @@ -450,13 +451,118 @@ test("hook install --platform prefers a locally installed CLI", () => { assert.match(text, /\.\/node_modules\/\.bin\/steadfast brief/); }); -test("hook install refuses platforms without a session-start hook", () => { +test("hook install refuses unknown platforms", () => { const root = project(); - const opencode = cli(["hook", "install", "--platform", "opencode"], root); - assert.equal(opencode.status, 2); - assert.match(opencode.stderr, /no session-start context hook/); + const cursor = cli(["hook", "install", "--platform", "cursor"], root); + assert.equal(cursor.status, 2); + assert.match(cursor.stderr, /use claude or opencode/); assert.equal(existsSync(join(root, ".git", "hooks", "pre-commit")), false); - assert.equal(cli(["hook", "install", "--platform", "cursor"], root).status, 2); +}); + +type CompactingHook = ( + input: { sessionID: string }, + output: { context: string[]; prompt?: string }, +) => Promise; + +async function compact(pluginPath: string): Promise { + const copy = pluginPath.replace(/\.js$/, ".mjs"); + writeFileSync(copy, readFileSync(pluginPath, "utf8")); + const module = (await import(pathToFileURL(copy).href)) as Record; + assert.deepEqual(Object.keys(module), ["SteadfastBrief"]); + const plugin = module.SteadfastBrief as () => Promise>; + const hooks = await plugin(); + const output: { context: string[]; prompt?: string } = { context: [] }; + const compacting = hooks["experimental.session.compacting"]; + assert.ok(compacting); + await compacting({ sessionID: "s" }, output); + assert.equal(output.prompt, undefined); + return output.context; +} + +test("hook install --platform opencode pushes brief into every compaction", async () => { + const root = project(); + const bin = join(root, "node_modules", ".bin"); + mkdirSync(bin, { recursive: true }); + const shim = join(bin, "steadfast"); + writeFileSync(shim, `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(CLI)} "$@"\n`); + chmodSync(shim, 0o755); + write( + root, + ".steadfast/roadmap.yaml", + `version: 1 +updated: 2026-10-30 +steps: + - id: STEP-001 + goal: Add the cleanup job + why: Inactive users keep rows forever. + paths: [src] + acceptance: run test/a.test.ts + status: current + checkpoint: + next: Wire the job into the scheduler +`, + ); + write(root, ".opencode/plugins/other.js", "export const Other = async () => ({});\n"); + + assert.equal(cli(["hook", "install", "--platform", "opencode"], root).status, 0); + const installed = cli(["hook", "install", "--platform", "opencode"], root); + assert.equal(installed.status, 0, installed.stderr); + assert.match(installed.stdout, /compaction brief/); + assert.ok(existsSync(join(root, ".git", "hooks", "pre-commit"))); + const pluginPath = join(root, ".opencode", "plugins", "steadfast-brief.js"); + const plugin = readFileSync(pluginPath, "utf8"); + assert.match(plugin, /^\/\/ steadfast:managed/); + assert.match(plugin, /"experimental\.session\.compacting"/); + assert.match(plugin, /\["\.\/node_modules\/\.bin\/steadfast","brief"\]/); + + const context = await compact(pluginPath); + assert.equal(context.length, 1); + const pushed = context.join("\n"); + assert.match(pushed, /# steadfast brief v1/); + assert.match(pushed, /STEP-001 Add the cleanup job/); + assert.match(pushed, /next: Wire the job into the scheduler/); + + const check = cli(["hook", "install", "--platform", "opencode", "--check"], root); + assert.equal(check.status, 0, check.stderr); + assert.match(check.stdout, /compaction brief/); + + assert.equal(cli(["hook", "remove", "--platform", "opencode"], root).status, 0); + assert.equal(existsSync(pluginPath), false); + assert.equal(existsSync(join(root, ".git", "hooks", "pre-commit")), false); + assert.ok(existsSync(join(root, ".opencode", "plugins", "other.js"))); + const missing = cli(["hook", "install", "--platform", "opencode", "--check"], root); + assert.equal(missing.status, 1); + assert.match(missing.stderr, /missing: OpenCode compaction brief/); +}); + +test("the compaction plugin tells the agent to run brief when brief fails", async () => { + const root = project(); + write(root, "node_modules/.bin/steadfast", "#!/bin/sh\nexit 1\n"); + chmodSync(join(root, "node_modules", ".bin", "steadfast"), 0o755); + assert.equal(cli(["hook", "install", "--platform", "opencode"], root).status, 0); + + const context = await compact(join(root, ".opencode", "plugins", "steadfast-brief.js")); + assert.deepEqual(context, [ + "steadfast brief failed during compaction; run it first to recover the current roadmap step.", + ]); +}); + +test("hook --platform opencode never touches a plugin it did not write", () => { + const root = project(); + const pluginPath = join(root, ".opencode", "plugins", "steadfast-brief.js"); + write(root, ".opencode/plugins/steadfast-brief.js", "export const Mine = async () => ({});\n"); + + const refused = cli(["hook", "install", "--platform", "opencode"], root); + assert.equal(refused.status, 2); + assert.match(refused.stderr, /not managed by steadfast/); + assert.equal(existsSync(join(root, ".git", "hooks", "pre-commit")), false); + assert.equal(cli(["hook", "install", "--platform", "opencode", "--check"], root).status, 1); + + assert.equal(cli(["hook", "install"], root).status, 0); + const removed = cli(["hook", "remove", "--platform", "opencode"], root); + assert.equal(removed.status, 0, removed.stderr); + assert.match(removed.stdout, /not managed by steadfast; left untouched/); + assert.equal(readFileSync(pluginPath, "utf8"), "export const Mine = async () => ({});\n"); }); test("hook install --platform claude refuses malformed settings", () => {