diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000..33ede4d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,22 @@ +--- +name: Bug +about: The megaplan skill or validator did not work as documented +labels: "" +--- + +**What was run** + + +**Host** (name and version) + +**Megaplan version** + + +**Expected** + +**Actual** + +**Output excerpt** + + + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..df320ec --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/Gamebreack/megaplan/security/advisories/new + about: Report security problems privately, not as a public issue. diff --git a/.github/ISSUE_TEMPLATE/idea.md b/.github/ISSUE_TEMPLATE/idea.md new file mode 100644 index 0000000..16e1f7c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/idea.md @@ -0,0 +1,15 @@ +--- +name: Idea +about: Propose a change or improvement +labels: "" +--- + +**Problem** + + +**Proposed change** + + +--- + +Changes should keep Megaplan portable and simple: plain instructions, no runner, no host adapters. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..d3212af --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,12 @@ +## What and why + + + +## Hosts tested in + + + +## Checklist + +- [ ] Follows the rules in AGENTS.md +- [ ] The [pre-PR checklist](https://github.com/Gamebreack/megaplan/blob/main/CONTRIBUTING.md#before-you-open-a-pull-request) is done diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..f65cf83 --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,34 @@ +name: Validate + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: "3.12" + - name: Run gitleaks secret scan + run: | + curl -fsSL -o /tmp/gitleaks.tar.gz https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz + echo "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb /tmp/gitleaks.tar.gz" | sha256sum -c - + mkdir -p /tmp/gitleaks + tar -xzf /tmp/gitleaks.tar.gz -C /tmp/gitleaks gitleaks + /tmp/gitleaks/gitleaks dir --no-banner --redact . + - name: Run repository guards + run: MEGAPLAN_PRE_PUSH_GUARDS_ONLY=1 scripts/hooks/pre_push.sh + - name: Check doc line limits + run: scripts/check-doc-length.sh + - name: Validate skill + run: python3 scripts/validate.py + - name: Run tests + run: python3 -m unittest discover -s tests -v diff --git a/.gitignore b/.gitignore index 8931864..a906a11 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,22 @@ .slim/ + +# Local secrets +.env +.env.* + +# Python bytecode, caches, and virtualenvs +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.venv/ + +# Logs, temporary files, backups, and editor/OS metadata +*.log +*.tmp +*.bak +*~ +*.swp +*.swo +.DS_Store +Thumbs.db diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..747499a --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,79 @@ +# Git hooks (pre-commit framework). Install once per clone: `pre-commit install` (installs the commit and push hooks). +# Run all commit-stage hooks: `pre-commit run --all-files`. Never bypass with --no-verify. +default_install_hook_types: [pre-commit, pre-push] +default_stages: [pre-commit] + +repos: + - repo: https://github.com/gitleaks/gitleaks + rev: v8.30.1 + hooks: + - id: gitleaks + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + # stages pinned: these hooks' manifests also declare other stages; all are pinned for consistency. + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + stages: [pre-commit] + - id: end-of-file-fixer + stages: [pre-commit] + - id: check-yaml + stages: [pre-commit] + - id: check-merge-conflict + args: [--assume-in-merge] + stages: [pre-commit] + - id: check-added-large-files + stages: [pre-commit] + + - repo: local + hooks: + # Limit lives in AGENTS.md (Hard rules); the script holds the numbers and the exempt list. + - id: doc-length + name: doc line limits (CONTEXT.md < 80, other Markdown < 200) + entry: scripts/check-doc-length.sh + language: system + pass_filenames: false + always_run: true + stages: [pre-commit] + + - id: validate + name: validator (megaplan frontmatter, links, sections, templates) + entry: python3 scripts/validate.py + language: system + pass_filenames: false + always_run: true + stages: [pre-commit] + + # The lookbehind skips URL paths (https://host/home/x). This config is excluded because the regex text itself contains the prefixes. + - id: no-absolute-home-path + name: portability guard (no absolute home paths) + description: Machine-specific paths never enter this repo (see AGENTS.md). + entry: '(?/megaplan.git` | +| 2. Install the hooks (once per clone) | `cd megaplan`, then `pre-commit install` (needs [pre-commit](https://pre-commit.com)) | +| 3. Make the change | on a feature branch | +| 4. Run the checks | the [required checks](#required-checks) | +| 5. Propose it | open a pull request against `main` (maintainers from `dev`, contributors from their fork) | + +## Required checks + +CI runs these commands. They must pass before merge and before release. Python 3.9 or later. + +```bash +gitleaks dir --no-banner --redact . +MEGAPLAN_PRE_PUSH_GUARDS_ONLY=1 scripts/hooks/pre_push.sh +scripts/check-doc-length.sh +python3 scripts/validate.py +python3 -m unittest discover -s tests +``` + +## How a change flows + +The diagram shows the maintainer path. Solid lines are every change; the dashed box is a release. + +```mermaid +%%{init: {"theme":"base","themeVariables":{"fontFamily":"system-ui, -apple-system, Segoe UI, sans-serif","fontSize":"15px","primaryTextColor":"#1b221e","lineColor":"#8a968f","clusterBkg":"transparent","clusterBorder":"#b7c0ba","titleColor":"#5d6962","edgeLabelBackground":"#ffffff"},"flowchart":{"curve":"basis","nodeSpacing":22,"rankSpacing":30,"padding":14,"htmlLabels":true}}}%% +flowchart LR + F["Feature branch
local only"] + H["Commit hooks
secrets, limits, validator"] + D["dev
the one pushed branch"] + P["Pull request
CI + review"] + M["main"] + R["Release
tag + GitHub release"] + + F --> H + H -->|"merge"| D + D -->|"push hook, PR"| P + P -->|"merge"| M + M -.->|"when releasing"| R + + classDef p1 fill:#dbe8f6,stroke:#4a7fb5,color:#1b221e + classDef p2 fill:#fbefd2,stroke:#c3962c,color:#1b221e + classDef p3 fill:#d8eee2,stroke:#3f8f68,color:#1b221e + classDef side fill:#f5f6f5,stroke:#a9b4ad,color:#5d6962,stroke-dasharray:4 3 + class F,H p1 + class D,P p2 + class M p3 + class R side + linkStyle 4 stroke:#8a968f,stroke-width:1.5px,stroke-dasharray:2 3 +``` + +**Branches:** the branch rule is in [AGENTS.md](AGENTS.md#hard-rules). + +## Before you open a pull request + +- [ ] All [required checks](#required-checks) pass +- [ ] `pre-commit run --all-files` passes, without bypassing hooks ([hard rules](AGENTS.md#hard-rules)) +- [ ] `CHANGELOG.md` has an entry under `[Unreleased]`, or the change is not user-facing +- [ ] The [hard rules in AGENTS.md](AGENTS.md#hard-rules) hold (including the flow-map rule) + +## What the hooks check + +Hooks run on commit and on push. Fix what they report. + +| Hook | When | What it does | +|---|---|---| +| Secret scan (gitleaks) | commit | blocks credentials and tokens | +| `.env`, `CONTEXT.md`, and `docs/megaplan/` guards | commit | keeps environment files and local planning out of git | +| Hygiene | commit | trailing whitespace, end of file, YAML, merge markers, large files | +| Line limits | commit | doc line limits (see AGENTS.md) | +| Portability guard | commit | no absolute home paths | +| Validator | commit | frontmatter, links and the skill's content check | +| `scripts/hooks/pre_push.sh` | push | checks the checkout and pushed files for forbidden paths, then runs checks and tests | + +## Versioning + +Versions are SemVer tags only (for example `v2.0.0`), applied to the skill's behavior: + +| Bump | When | +|---|---| +| Patch | wording and template fixes that do not change what the skill asks of an agent | +| Minor | new or changed workflow or structure rules | +| Major | a breaking change to how Megaplan tracks plans or items | + +## Releasing + +For maintainers. Work through the steps in order; each one gates the next. + +1. In a pull request, move the `[Unreleased]` entries in `CHANGELOG.md` under `## [X.Y.Z] - YYYY-MM-DD` and update the compare links. +2. Run pre-release verification on that pull request while it is up to date with `main`: a fresh verifier run plus an independent review panel. Merge only with no open blocker findings. +3. Only with operator approval: after the pull request merges, create the annotated tag `vX.Y.Z` on the merge commit and push it. +4. Create the GitHub release with that version's changelog section as its notes: `gh release create vX.Y.Z --verify-tag --title "vX.Y.Z — " --notes-file
`. diff --git a/README.md b/README.md index c7b9bef..44eaab9 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,106 @@ -# Megaplan +# Megaplan — plan-tracking methodology for AI coding agents -A plan-tracking methodology for working with AI coding agents across sessions. +[![Latest release](https://img.shields.io/github/v/release/Gamebreack/megaplan)](https://github.com/Gamebreack/megaplan/releases) +[![License: MIT](https://img.shields.io/github/license/Gamebreack/megaplan)](LICENSE) +[![Validate](https://github.com/Gamebreack/megaplan/actions/workflows/validate.yml/badge.svg)](https://github.com/Gamebreack/megaplan/actions/workflows/validate.yml) -An agent starts every session with no memory of the last one. Megaplan's answer is to agree the -scope of a piece of work out loud, write the agreement down, and keep it somewhere small enough that -the next session actually reads it. +Megaplan provides a plan-tracking methodology for AI coding agents with two-tier visibility (durable ADRs committed in `docs/adr/`, ephemeral backlog & resumable logs in `docs/megaplan/`), supporting conversational or spec-first scoping and zero runtime. Documents, not machinery—built to keep shared context clear across sessions. -There is no installer and nothing to run. It is a skill and five markdown templates. +> **Status:** see the latest release badge above and [CHANGELOG.md](CHANGELOG.md). -## How it works +## What you get -You ask for a feature. The agent interviews you — what outcome, what already exists that this -touches, what's out, and what it cut from what you asked for. It restates the scope as the things it -will *not* touch. You confirm. Then it writes the backlog. +- **Durable boundaries**: architectural decisions live as version-controlled ADRs (`docs/adr/`). +- **Clean remotes**: process logs and backlogs stay ephemeral (`docs/megaplan/`), tracked locally or excluded on team repos. +- **Resumable work**: backlog items have explicit outcome, scope, non-touching constraints, verification criteria, and dated logs. +- **Spec-first entry**: start from an interactive interview or an existing OpenSpec/ticket proposal. +- **Zero runtime**: plain Markdown and templates. No runner, server, or database required. +- **Portable**: host-agnostic skill (`skills/megaplan/SKILL.md`). -From there the backlog is the guidance: one index of live work, and one file per item holding the -agreed scope, what it touches, and a dated log of what actually happened. You can ask for an -adversarial review of an item before any code is written, or of the implementation afterwards. +## What an item looks like -## The five files +A sample backlog item file (`docs/megaplan/backlog-items/b01.md`). The exact format lives in [SKILL.md](skills/megaplan/SKILL.md#the-item-file). -| File | Holds | -|---|---| -| `docs/megaplan/backlog.md` | Index of live work, one row per item | -| `docs/megaplan/backlog-items/.md` | One file per item, for items that need one | -| `docs/megaplan/megaplan.md` | What the project is, and what already exists in it | -| `docs/megaplan/done.md` | What you have confirmed finished | -| `docs/megaplan/glossary.md` | The project's domain terms | +```markdown +# b01: Add export validator + +Spec: docs/proposals/export-spec.md + +## Outcome +Validator checks export JSON schema before saving. -Finished items leave the index. You write one line in `done.md` confirming what you verified; the -agent then updates `megaplan.md` if the item changed what exists, and deletes both the row and the -item file — so the index stays a picture of live work rather than a growing archive. +## Scope +- [x] Parse JSON file +- [ ] Add schema check and error path reporting -## Adopting it +## Touches +- `scripts/validator.py:45` — add schema check + +## Not touching +- CLI entrypoint or logging config + +## Acceptance +- [ ] Invalid schema raises `ValueError` with the failing field path + +## Log +- **2026-11-29** — parser added, schema check pending (`a1b2c3d`) +``` -Give your agent this repo's URL and tell it to install the megaplan skill: +## How it works +The agent scopes the work, maintains the backlog and item logs, and graduates boundaries to ADRs. Full flow: [flow-map.md](flow-map.md). Exact behavior: [SKILL.md](skills/megaplan/SKILL.md). + +```mermaid +%%{init: {"theme":"base","themeVariables":{"fontFamily":"system-ui, -apple-system, Segoe UI, sans-serif","fontSize":"15px","primaryTextColor":"#1b221e","lineColor":"#8a968f","clusterBkg":"transparent","clusterBorder":"#b7c0ba","titleColor":"#5d6962","edgeLabelBackground":"#ffffff"},"flowchart":{"curve":"basis","nodeSpacing":22,"rankSpacing":30,"padding":14,"htmlLabels":true}}}%% +flowchart LR + I["Scope item
interview or spec"] + B["Backlog index
docs/megaplan/backlog.md"] + F["Item file
scope, log, acceptance"] + A["ADR graduation
docs/adr/"] + D["Done ledger
docs/megaplan/done.md"] + + I -->|"create row"| B + B -.->|"when needed"| F + F -->|"boundary needed"| A + F -->|"review & finish"| D + D -->|"remove row"| B + + classDef p1 fill:#dbe8f6,stroke:#4a7fb5,color:#1b221e + classDef p2 fill:#fbefd2,stroke:#c3962c,color:#1b221e + classDef p3 fill:#d8eee2,stroke:#3f8f68,color:#1b221e + classDef p4 fill:#e7def4,stroke:#7a5aa6,color:#1b221e + class I p1 + class B,F p2 + class A p3 + class D p4 ``` -https://github.com/Gamebreack/megaplan + +## Install + +The skill follows the [Agent Skills](https://agentskills.io) format: a folder with a `SKILL.md`. Copy `skills/megaplan/` into your host's skills directory. + +```bash +git clone --branch v2.0.0 --depth 1 https://github.com/Gamebreack/megaplan.git +# then copy or symlink megaplan/skills/megaplan into your host's skills directory ``` -It reads the repo, works out where your harness keeps skills, and puts it there. The repo is public, -so nothing needs authenticating. +### With MAO -Then, in the repo you want to use it in, tell the agent to use the megaplan skill. It runs the -interview and writes the documents into `docs/megaplan/`. +[multi-agent-orchestration](https://github.com/Gamebreack/multi-agent-orchestration) (MAO) `mao-setup` offers `megaplan` as an optional y/N install. -This works the same whether the repo is empty or already has months of work in it. In a repo with -existing work the backlog still starts empty — what is already built gets described in -`megaplan.md`, and only work you intend to do next becomes an item. +## Works well with + +Pairs with [OpenSpec](https://github.com/Fission-AI/OpenSpec) for drafting proposals, [agent-verification](https://github.com/Gamebreack/agent-verification) (`verify`) for independent verification, and [flow-map](https://github.com/Gamebreack/flow-map) for system maps. None of them is required. + +## Repository layout + +| Path | What | +|---|---| +| `skills/megaplan/SKILL.md` | the core skill instruction file | +| `skills/megaplan/templates/` | item, backlog, done, ADR, glossary and megaplan templates | +| `scripts/validate.py`, `tests/` | standard-library validator and its tests | +| `flow-map.md` | end-to-end flow diagrams | -## Where the details are +## Contributing, security, license -`skills/megaplan/SKILL.md` is the methodology, and it is the product. Read it for the exact rules the -agent follows. Everything else here is either a template or megaplan's own backlog, kept because it -uses itself. +[CONTRIBUTING.md](CONTRIBUTING.md) covers checks, hooks and releases; changes are listed in [CHANGELOG.md](CHANGELOG.md). Report vulnerabilities privately via [SECURITY.md](SECURITY.md). Licensed under [MIT](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..8b09d0d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,48 @@ +# Security policy + +## Contents + +| Question | Answer | +|---|---| +| Which versions get fixes? | [Supported versions](#supported-versions) | +| Where do I report? | [How to report](#how-to-report) | +| When will I hear back, and how is it fixed? | [What to expect](#what-to-expect) | + +## Supported versions + +Only the latest minor release gets fixes. + +| Version | Supported | +|---|---| +| 2.0.x | yes | +| < 2.0 | no | + +## How to report + +1. Open a private report on [Gamebreack/megaplan](https://github.com/Gamebreack/megaplan/security/advisories/new): **Security → Report a vulnerability**. +2. Include the skill version, the host you ran it in, the inputs that trigger the problem (with secrets and private paths redacted), and what happened. + +> Do not describe a security problem in a public issue or pull request. + +## What to expect + +1. An acknowledgement within 7 days. +2. A patch release with the fix. +3. Credit in the changelog, unless you ask otherwise. + +## What counts + +Megaplan (the `megaplan` skill) is instructions, not code. It runs only through the agent and harness that load it, so a security issue is wording that leads a compliant agent to an unsafe action. + +| Counts: report privately | Does not count: use the normal channel | +|---|---| +| Guidance that makes the agent print secrets or private paths | An ordinary bug with no security effect: use the [bug issue](https://github.com/Gamebreack/megaplan/issues/new?template=bug.md) | +| Guidance that makes the agent act beyond its approved scope | A suggestion: use the [idea issue](https://github.com/Gamebreack/megaplan/issues/new?template=idea.md) | +| Guidance that makes the agent skip approval steps | A host, harness or model behaving badly: see [Out of scope](#out-of-scope) | +| Guidance that makes the agent claim results without evidence | | + +`scripts/validate.py` runs `git ls-files` read-only in the repository and reads Markdown; it executes no content from the skill. + +## Out of scope + +Vulnerabilities in a host, harness or model. Report those to the relevant vendor. diff --git a/docs/megaplan/backlog-items/b01.md b/docs/megaplan/backlog-items/b01.md deleted file mode 100644 index d863504..0000000 --- a/docs/megaplan/backlog-items/b01.md +++ /dev/null @@ -1,84 +0,0 @@ -# b01: Megaplan as a skill and five documents - -## Outcome - -Megaplan is a skill plus five markdown files, and adopting it is copying templates rather than -running an installer. Known when a fresh repo can be set up by invoking the skill, with no script -executed at any point. - -## Scope - -- [x] `SKILL.md` carries the methodology inline — interview, item shape, finish rule, attack modes -- [x] Five templates as real files under `skills/megaplan/templates/` -- [x] The skill installs from this repo's URL -- [x] Enforcement layer removed -- [x] This repo's own four files rewritten to describe what exists -- [x] `README.md` rewritten as a front page - -## Touches - -- `skills/megaplan/SKILL.md` — carries the methodology inline -- `skills/megaplan/templates/` — five files; replaced two tracked symlinks -- `docs/megaplan/` — this repo's own backlog, rewritten -- `README.md` — the front page - -Deleted, 107 files: `docs/megaplan/` (52 — 43 item files, 5 ADRs, 2 cycle files, -`.workflow-state.json`, `V1-PLAN.md`), `examples/` (12), `contrib/wiki/` (12), `tests/` (10), -`scripts/` (9), `templates/` (5, moved into the skill), the two tracked symlinks under -`skills/megaplan/` (2), and `AGENTS.md`, `docs/methodology.md`, `pyproject.toml`, `.gitignore`, -`.ignore`. - -## Not touching - -- `LICENSE` -- Git history — the previous version stays reachable at tag `pre-v2`, local-only until pushed - -## Cut - -Enforcement went entirely, not partially. An agent can write any status and nothing stops it. The -commit-time gate that used to stop that did work; keeping it meant keeping the 11,217 lines of -machinery built around it. What is lost is that a status is now a claim rather than a checked fact — -`done.md` is a record, and records can be neglected. - -Also cut: the size caps, and the check that the documents stay small. Nothing runs now, so there is -nothing left to run a cap. - -## Log - -- **2026-08-20** — `2cc2961` skill and templates. Two tracked symlinks in `skills/megaplan/` pointed - at root `templates/` and `docs/`; writing through them wrote to the old location and `git add` - refused the path. Removed both first. -- **2026-08-20** — `5cf3b6e` machinery deleted. Two installed git hooks had to be removed before any - commit: pre-commit ran a validator that this commit deletes, so it would have blocked its own - removal. Backed up outside the repo first. -- **2026-08-20** — `82cc5ae` narrative deleted: 8,371 → 608 tracked lines. Across all three - deletions, 19,564 → 608. -- **2026-08-20** — `539cebb` this repo's own documents rewritten. -- **2026-08-20** — `5bdae14` README rewritten; `.gitignore` and `.ignore` deleted outright rather - than trimmed. -- **2026-08-20** — a cold read by an agent given no history found the docs unusable on first - contact: the front page documented an installer that no longer existed, the status table was - duplicated across three files, the glossary broke its own "domain terms only" rule, and "operator" - was never defined despite being the pivotal role. A sweep for the same defect found one more: a - section in the item-file template whose only content compared itself to the old version, which no - adopter can see. It would have shipped into every adopting repo. -- **2026-08-20** — five further reviews found nine rules an adopter could not follow. Those are - `b02`, not amendments here. Tracked lines at this point: 401. -- **2026-08-20** — `0544abb` corrected this file's `## Touches`, `## Not touching`, the enforcement - cost and the line counts. -- **2026-08-20** — `c5d5cb8` corrected them again. Two verifiers found three of the twelve claims - `b02` verified in its first round were false, and one was that this file had gained four wrong - file counts in the commit titled "correct the record". The counts now match - `git diff --diff-filter=D pre-v2..HEAD`. - -## Attack - -Three rounds of subagent review ran against the plan before execution. What changed as a result: - -- Enforcement dropped. The gate worked, but its cost was the machinery around it. -- `## Log` added: two items in the previous version had invented a dated section by hand, at - `E-B2.md:51` and `E-B8.md:36`, because none existed. -- `## Scope` is rewritten rather than appended to. Eleven items in the previous version carried a - `done` status beside unchecked scope boxes. -- Item files made optional. 27 of the previous version's 42 items — 64% — arrived in five commits - that each created two or more, rather than being written as they were worked. diff --git a/docs/megaplan/backlog-items/b02.md b/docs/megaplan/backlog-items/b02.md deleted file mode 100644 index 02debd2..0000000 --- a/docs/megaplan/backlog-items/b02.md +++ /dev/null @@ -1,117 +0,0 @@ -# b02: Correct the defects found reviewing b01 - -## Outcome - -The shipped skill and templates carry no rule an adopter cannot follow, and `b01` describes what -actually happened. Done when a reader can adopt megaplan from the repo URL alone and every claim in -`docs/megaplan/` checks out against git. - -## Scope - -- [x] Adoption is pasting the repo URL to an agent — no clone, no symlink, no path -- [x] `done` stops being a status; the ledger is the only thing that means finished -- [x] `Depends on` column deleted -- [x] "operator" defined in the template that lands in an adopting repo -- [x] ID allocation rule stated, and every ID that leaves the backlog stays in `done.md` -- [x] The fileless-item path has somewhere to write its outcome -- [x] One rule for when the interview runs -- [x] The pronoun rule holds for all four questions, not just question 4 -- [x] `## Picking up where you left off` added -- [x] Templates ship no dangling link and no `b01` -- [x] The skill description stops promising a file per item -- [x] The `## Statuses` section that restated what it forbade restating is gone -- [x] `glossary.md` and `done.md` restored to their templates' wording -- [x] `superseded` has an exit that does not orphan its ID -- [x] The first-item bootstrap case is stated, so the finish rule is reachable -- [x] The finish rule says the same thing in all four files that state it -- [x] `## Touches` asks for what a document can actually provide -- [x] A finding against unfinished work is fixed in place; against a finished item it becomes a new item -- [x] `## Cut` holds only subtractions, with their costs named -- [x] `SKILL.md` says when the agent moves a status -- [x] `b01` rewritten to match what the commits did, and its log attributes them -- [x] `.pytest_cache/` and `.ruff_cache/` deleted - -## Touches - -Line numbers are omitted deliberately: every edit below moves the lines the others sit on, and a -stale pointer in the file the next session works from is worse than none. - -- `skills/megaplan/SKILL.md` — the frontmatter description, the pronoun rule and question 4, the ID - format, the two competing rules for when the interview runs, the fileless-item outcome, the - `## Statuses` section, the missing resume procedure, `superseded`'s lack of an exit, and this - repo's own item ID inside the canonical file tree -- `skills/megaplan/templates/backlog.md` — `done` as a status, the `Depends on` column, the example - row's link, and "operator" used undefined -- `skills/megaplan/templates/done.md` — "operator" used undefined; boilerplate reworded in the copy -- `skills/megaplan/templates/megaplan.md`, `glossary.md`, `backlog-item.md` — unmarked example rows - and rules buried inside placeholders -- `docs/megaplan/glossary.md` — dropped the "not of the methodology" clause the template carries -- `docs/megaplan/megaplan.md` — a harness-specific install path, and a `## History` section the - template does not have -- `docs/megaplan/backlog-items/b01.md` — `Touches`, `Not touching`, the enforcement cost, the line - counts, missing SHAs, and review numbers wrong in both directions -- `README.md` — the clone-and-symlink model, `b01` shown as fixed layout, and the append-not-edit - description of finishing - -## Not touching - -- The interview's four questions, the item-file sections, or the finish rule. The defects are in how - they are written down, not in the design. -- `LICENSE` -- Git history. `pre-v2` stays where it is. -- `## Scope` keeps its name; attack, adversarial review and review keep theirs; `megaplan.md` keeps - its filename. Reviewers argued for all three and none of them would bite anyone using this. - -## Cut - -Cut: no check that the shipped templates and this repo's copies of them stay in sync. They drifted -twice, silently — the glossary's rule sentence and `done.md`'s — and nothing runs here to catch the -third. What is lost is that the only worked example can contradict the thing it is an example of, -and only a reader diffing them by hand will notice. - -Also cut: line numbers in `## Touches`. What is lost is the ability to jump straight to a defect; -paths alone mean the next reader has to search the file. Kept anyway, because a pointer that has -rotted is worse than one that was never offered. - -Also cut: the three reviewer suggestions listed under `## Not touching`. What is lost is a tidier -vocabulary — `## Steps` instead of `## Scope`, one word for attack, a project-named `megaplan.md`. -None of them changes what an adopter can do. - -## Log - -- **2026-08-20** — five subagents reviewed the repo across documentation, template conformity, - terminology, clarity, and claims. Every defect they found was introduced by the five commits from - `pre-v2` to `5bdae14`, not inherited: the only genuine leftovers were two tool cache directories. - Nine findings would bite a user; the rest was polish and is listed under Not touching. -- **2026-08-20** — the reviewers disagreed once, about whether `.pytest_cache/` and `.ruff_cache/` - exist. They do. `git status` misses them because each writes a self-ignoring `.gitignore` inside - itself. -- **2026-08-20** — `7d492e1` adoption by URL. `19d7750` the nine rules. `0544abb` b01 corrected. - `5f5e79e` cache directories deleted. No `.gitignore` came back — nothing here generates anything. -- **2026-08-20** — two verifiers found three of the twelve claims this item made in its first - round were false. See `## Attack`. -- **2026-08-20** — a second pair of verifiers found five more defects and four places where the rule - itself was wrong rather than the repo. The rule changes: `## Touches` asks for paths and wants a - line number only for code; a finding against unfinished work is fixed in place; `## Cut` holds - only subtractions; `SKILL.md` says when a status moves. `## Scope` above was rewritten rather than - appended to this time — appending it last round was what broke the three claim counts. - Fixed in this item rather than a new one: they are defects in this item's own work, not new - findings against a finished one. - -## Attack - -Two verifiers attacked this item's work after the four fix commits. Three of the twelve claims it -made in its first round came back false: - -- The backlog template still shipped `[b01](backlog-items/b01.md)` — the box said the link was gone, - but the fix had only added a comment above the row. It was the only link under `skills/`, and it - resolved nowhere. -- The pronoun rule was moved, not fixed. The new rule said all four questions are in the operator's - voice, while the same commit rewrote question 4 into the agent's — the same contradiction from the - other side. -- The commit titled "correct the record" put four fresh wrong file counts into `b01`, and - overcorrected one review figure past the true value. - -Also found: `~/.claude/skills/megaplan` survived in two files the URL commit never touched, the -README still described appending to `megaplan.md` after the rule changed to editing, and the -`## Statuses` fix left the finish rule stated three ways across three files. diff --git a/docs/megaplan/backlog.md b/docs/megaplan/backlog.md deleted file mode 100644 index 847a474..0000000 --- a/docs/megaplan/backlog.md +++ /dev/null @@ -1,24 +0,0 @@ -# Backlog — Megaplan - -The **operator** is the human who owns this project: they answer the interview, confirm scope, and -write `done.md`. The agent does everything else, including maintaining this file. - -## Statuses - -| Status | Meaning | -|---|---| -| `pending` | Defined, not started | -| `in-progress` | Being worked now | -| `review` | Believed complete, waiting on the operator | -| `superseded` | Replaced by another item, and not delivered | - -An item leaves this file when the operator writes its line in `done.md` — whether it was finished or -superseded. The agent then edits `megaplan.md` under "what already exists" if the item changed what -exists, and deletes both the row here and the item file. This file is live work only. - -## Index - -| ID | Title | Status | Item file | -|---|---|---|---| -| b01 | Megaplan as a skill and five documents | review | [b01](backlog-items/b01.md) | -| b02 | Correct the defects found reviewing b01 | review | [b02](backlog-items/b02.md) | diff --git a/docs/megaplan/done.md b/docs/megaplan/done.md deleted file mode 100644 index 8127b43..0000000 --- a/docs/megaplan/done.md +++ /dev/null @@ -1,7 +0,0 @@ -# Done - -Only the operator writes in this file. One line per item that leaves the backlog, whether it was -finished or superseded; append only. An item is not finished until its line is here. - -| ID | Date | Verified | -|---|---|---| diff --git a/docs/megaplan/glossary.md b/docs/megaplan/glossary.md deleted file mode 100644 index 5339a0b..0000000 --- a/docs/megaplan/glossary.md +++ /dev/null @@ -1,11 +0,0 @@ -# Glossary - -Domain terms only — the vocabulary of the problem, not of the methodology. - -A rename edits the existing row. If a term's code pointer no longer resolves, delete the row. - -Empty: this project's vocabulary *is* the methodology, and that is defined in -`skills/megaplan/SKILL.md`. A project with a real domain fills this in. - -| Term | Meaning | Lives in | -|---|---|---| diff --git a/docs/megaplan/megaplan.md b/docs/megaplan/megaplan.md deleted file mode 100644 index c0a0625..0000000 --- a/docs/megaplan/megaplan.md +++ /dev/null @@ -1,26 +0,0 @@ -# Megaplan - -## What this is - -A plan-tracking methodology for driving AI coding agents across sessions. You ask for a feature, -the agent interviews you until the scope is actually agreed, and the agreement is written down as a -backlog the next session can pick up. It is documents and a naming convention. Nothing in it runs. - -The methodology itself lives in `skills/megaplan/SKILL.md`. That file is the product. - -## What already exists - -- `skills/megaplan/SKILL.md` — the methodology: the interview, the item-file shape, the finish rule, - the two attack modes. -- `skills/megaplan/templates/` — five templates copied into a project on adoption: `backlog.md`, - `backlog-item.md`, `megaplan.md`, `done.md`, `glossary.md`. -- `README.md` — the front page: what this is and how to adopt it. -- This repo uses itself. `docs/megaplan/` is megaplan's own backlog. - -There is no installer and nothing to run. - -Nothing here is pushed. The public URL still serves the version before this work — 110 files with a -bootstrap script and a test suite. An earlier and much larger version is in git history at tag -`pre-v2`, local-only until pushed. - -When an item changes what exists, edit the line it affects rather than appending a new one. diff --git a/flow-map.md b/flow-map.md new file mode 100644 index 0000000..ed16e61 --- /dev/null +++ b/flow-map.md @@ -0,0 +1,109 @@ +# Flow map — from agent scoping to finished work + +The path through the `megaplan` skill, from A (agent starting a task) to B (operator reviewing completion). Source: `skills/megaplan/SKILL.md`. + +> **Status:** verified against skill behavior. Releases: see [CHANGELOG.md](CHANGELOG.md). + +## 1. Scoping and entry paths + +> Shows how an item enters the backlog via conversational interview or an existing spec, and when boundaries graduate to ADRs. + +```mermaid +%%{init: {"theme":"base","themeVariables":{"fontFamily":"system-ui, -apple-system, Segoe UI, sans-serif","fontSize":"15px","primaryTextColor":"#1b221e","lineColor":"#8a968f","clusterBkg":"transparent","clusterBorder":"#b7c0ba","titleColor":"#5d6962","edgeLabelBackground":"#ffffff"},"flowchart":{"curve":"basis","nodeSpacing":22,"rankSpacing":30,"padding":14,"htmlLabels":true}}}%% +flowchart TD + S["New work request"] + P1["Path 1: Conversational
4 questions, restate non-touching"] + P2["Path 2: Existing spec
link spec, verify acceptance"] + R["Backlog row
docs/megaplan/backlog.md"] + F["Item file
docs/megaplan/backlog-items/"] + ADR["ADR graduation
docs/adr/"] + + S --> P1 + S --> P2 + P1 --> R + P2 --> R + R -.->|"when needed (optional)"| F + F -->|"boundary needed"| ADR + + classDef p1 fill:#dbe8f6,stroke:#4a7fb5,color:#1b221e + classDef p2 fill:#fbefd2,stroke:#c3962c,color:#1b221e + classDef p3 fill:#d8eee2,stroke:#3f8f68,color:#1b221e + class S p1 + class P1,P2,R,F p2 + class ADR p3 +``` + +| Phase | In one line | +|---|---| +| Entry | Choose conversational interview or spec-first path based on whether a formal proposal exists. | +| Item setup | Add a backlog row (small work stays fileless with `—`), or also create an item file when needed for outcome, scope, constraints, and acceptance criteria. | +| ADRs | Graduate architectural boundaries and invariants into version-controlled ADR files. | + +## 2. Execution and pickup + +> Shows how an active item is loaded from the backlog and how progress is tracked via resumable logs. + +```mermaid +%%{init: {"theme":"base","themeVariables":{"fontFamily":"system-ui, -apple-system, Segoe UI, sans-serif","fontSize":"15px","primaryTextColor":"#1b221e","lineColor":"#8a968f","clusterBkg":"transparent","clusterBorder":"#b7c0ba","titleColor":"#5d6962","edgeLabelBackground":"#ffffff"},"flowchart":{"curve":"basis","nodeSpacing":22,"rankSpacing":30,"padding":14,"htmlLabels":true}}}%% +flowchart TD + B["Backlog index
docs/megaplan/backlog.md"] + IT["Active item file
load single item"] + LG["Log appends
dated events, commit SHAs"] + SC["Scope updates
rewrite scope if shift occurs"] + + B -->|"status: in-progress"| IT + IT -->|"work and errors"| LG + IT -->|"scope changes"| SC + LG -->|"outranks scope"| IT + + classDef p1 fill:#dbe8f6,stroke:#4a7fb5,color:#1b221e + classDef p2 fill:#fbefd2,stroke:#c3962c,color:#1b221e + class B p1 + class IT,LG,SC p2 +``` + +| Phase | In one line | +|---|---| +| Pickup | Read `backlog.md` and load only the active item file; never load all item files. | +| Logs | Append dated entries to `## Log` for every event, error, and commit SHA; log outranks checkboxes. | + +## 3. Finish and visibility split + +> Shows how items transition to review, receive operator sign-off in `done.md`, and get cleaned up based on visibility. + +```mermaid +%%{init: {"theme":"base","themeVariables":{"fontFamily":"system-ui, -apple-system, Segoe UI, sans-serif","fontSize":"15px","primaryTextColor":"#1b221e","lineColor":"#8a968f","clusterBkg":"transparent","clusterBorder":"#b7c0ba","titleColor":"#5d6962","edgeLabelBackground":"#ffffff"},"flowchart":{"curve":"basis","nodeSpacing":22,"rankSpacing":30,"padding":14,"htmlLabels":true}}}%% +flowchart TD + W["Implementation complete"] + REV["Status: review"] + DON["Operator done.md line
written by operator"] + DEL["Delete file
if git-tracked"] + ARC["Archive file
if git-excluded"] + + W --> REV + REV --> DON + DON --> DEL + DON --> ARC + + classDef p1 fill:#dbe8f6,stroke:#4a7fb5,color:#1b221e + classDef p2 fill:#fbefd2,stroke:#c3962c,color:#1b221e + classDef p3 fill:#d8eee2,stroke:#3f8f68,color:#1b221e + class W p1 + class REV,DON p2 + class DEL,ARC p3 +``` + +| Phase | In one line | +|---|---| +| Sign-off | Set backlog row to `review` and prompt operator for a one-line entry in `done.md`. | +| Cleanup | Remove backlog row; delete item file if git-tracked or move to archive if git-excluded. | + +## Where it lives + +| Phase | Path | +|---|---| +| Methodology & Rules | `skills/megaplan/SKILL.md` | +| Templates | `skills/megaplan/templates/` | +| Checks & Tests | `scripts/validate.py`, `tests/` | + +Updated 2026-11-29 · See [CHANGELOG.md](CHANGELOG.md) for releases diff --git a/scripts/check-doc-length.sh b/scripts/check-doc-length.sh new file mode 100755 index 0000000..2adf6dd --- /dev/null +++ b/scripts/check-doc-length.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Enforces the line limits in AGENTS.md (Hard rules): every CONTEXT.md under +# CONTEXT_LIMIT lines, every other tracked Markdown file under DOC_LIMIT lines. +# Append-only records in EXEMPT are skipped. +set -euo pipefail + +CONTEXT_LIMIT=80 +DOC_LIMIT=200 +EXEMPT="CHANGELOG.md" + +git rev-parse --git-dir >/dev/null + +status=0 +while IFS= read -r -d '' file; do + case " $EXEMPT " in *" $file "*) continue ;; esac + [ -f "$file" ] || continue # tracked but deleted in the working tree + case "$file" in + CONTEXT.md | */CONTEXT.md) limit=$CONTEXT_LIMIT ;; + *) limit=$DOC_LIMIT ;; + esac + # awk counts a final line without a newline; wc -l would not. + lines=$(awk 'END { print NR }' < "$file") + if [ "$lines" -ge "$limit" ]; then + echo "$file: $lines lines (must be under $limit)" + status=1 + fi +done < <(git ls-files -z '*.md') + +exit "$status" diff --git a/scripts/hooks/guard_scan.py b/scripts/hooks/guard_scan.py new file mode 100755 index 0000000..4260e15 --- /dev/null +++ b/scripts/hooks/guard_scan.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Matching helper for scripts/hooks/pre_push.sh (standard library only). + +All regex and NUL handling lives here so the hook needs only git and Python 3: +no PCRE and no GNU-only grep. Input is read from stdin as bytes. +Inputs come from plumbing (`git ls-files -z`, `git grep -z`, `git rev-list | git diff-tree`), +never porcelain `git log`: its output depends on user config (for example log.showSignature +prints signature text into the stream), which would corrupt parsing. + +Modes (exit 0 = hit, printed to stdout; 1 = no hit; 2 = usage error or any crash, fail closed): + paths NUL-separated paths (`git ls-files -z`, or `git diff-tree --name-only -z`): print the + forbidden ones (a .env file anywhere, a root CONTEXT.md, or docs/megaplan/). + grep `git grep -n -I -z -E ` output (path NUL line NUL text LF): + print hits where the home-path lookbehind also holds. + added `git diff-tree -p --cc` patch text: print added lines that hold a home path. + In a combined (merge) diff a line counts as added only when it is added + against every parent (all '+' columns), i.e. introduced by the merge itself. +""" +import re +import sys + +# Same rule as the no-absolute-home-path hook in .pre-commit-config.yaml. +HOME = re.compile( + r"(?= cols and line[:cols] == b"+" * cols: + if HOME.search(line[cols:].decode("utf-8", errors="surrogateescape")): + hits.append(line) + return hits + + +def main(argv): + modes = {"paths": forbidden_paths, "grep": grep_hits, "added": added_hits} + if len(argv) != 2 or argv[1] not in modes: + sys.stderr.write("usage: guard_scan.py paths|grep|added < input\n") + return 2 + try: + hits = modes[argv[1]](sys.stdin.buffer.read()) + for h in hits: + sys.stdout.buffer.write(h + b"\n") + sys.stdout.buffer.flush() + except BaseException as exc: # an uncaught exception would exit 1 = "no hit" + sys.stderr.write("guard_scan.py: %s: %s\n" % (type(exc).__name__, exc)) + return 2 + return 0 if hits else 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/hooks/pre_push.sh b/scripts/hooks/pre_push.sh new file mode 100755 index 0000000..0f96c55 --- /dev/null +++ b/scripts/hooks/pre_push.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# Pre-push checks: the same gates CI runs, plus whole-repo guards that the commit +# hooks (staged files only) cannot see. Does not call pre-commit (avoids recursion). +# +# Guards run on the current checkout and, when pre-commit exports the pushed range +# (PRE_COMMIT_FROM_REF and PRE_COMMIT_TO_REF, pre-commit 4.x, pre-push stage), also on +# the commits being pushed: .env paths, a root CONTEXT.md, docs/megaplan/ and added home-path lines +# anywhere in that range. +# A new branch has no usable from-ref, so the range is the commits not reachable from +# the destination remote's tracking refs (or any remote-tracking ref when PRE_COMMIT_REMOTE_NAME +# is unset). Without the variables (manual run) only the checkout is checked. +# Merge commits are included (--cc: changes made by the merge itself, e.g. conflict +# resolution; --cc rather than -m so lines merely brought in from another parent, which +# are scanned as their own commits or already on the remote, are not re-flagged). +# Every git call whose output is parsed passes --no-color (forced colour would break parsing). +# The range scans use plumbing (rev-list | diff-tree), not porcelain log: its output depends on +# user config (log.showSignature prints signature text into the stream). +# All regex and NUL-separated path matching lives in guard_scan.py (git + Python 3 only, +# no PCRE, no GNU grep), so quoted (core.quotePath) names match too and macOS works. +# +# MEGAPLAN_PRE_PUSH_GUARDS_ONLY=1 stops after the guards (the hook tests use it so they +# do not recurse into the real suite). Unset, the full run happens. +set -euo pipefail + +# Resolve the helper before the cd so manual runs from any directory work. +SCAN="$(CDPATH= cd -- "$(dirname -- "$0")" >/dev/null && pwd)/guard_scan.py" +cd "$(git rev-parse --show-toplevel)" + +# Same exclusions as the no-absolute-home-path hook in .pre-commit-config.yaml. +EXCLUDES=(':!.pre-commit-config.yaml' ':!scripts/hooks/pre_push.sh') + +tmp=$(mktemp) +trap 'rm -f "$tmp"' EXIT + +# Feeds "$tmp" to the Python helper in the given mode and prints its hits. +# Helper exit codes: 0 hit, 1 no hit, 2 or other = error (a crash exits 2, never 1). +# Returns 0 on hit, 1 on no hit, exits on any other result (fail closed). +scan() { + local rc=0 + python3 "$SCAN" "$1" <"$tmp" || rc=$? + case "$rc" in + 0) return 0 ;; + 1) return 1 ;; + *) echo "guard_scan.py $1 failed (rc=$rc)" >&2; exit 1 ;; + esac +} + +# Range of commits being pushed, as rev-list arguments; empty when unknown. +RANGE=() +from="${PRE_COMMIT_FROM_REF:-}" +to="${PRE_COMMIT_TO_REF:-}" +if [ -n "$from" ] && [ -n "$to" ] && ! [[ "$to" =~ ^0+$ ]]; then + if [[ "$from" =~ ^0+$ ]] || ! git rev-parse --verify --quiet "${from}^{commit}" >/dev/null; then + if [ -n "${PRE_COMMIT_REMOTE_NAME:-}" ]; then + RANGE=("$to" --not "--remotes=${PRE_COMMIT_REMOTE_NAME}") + else + RANGE=("$to" --not --remotes) + fi + else + RANGE=("${from}..${to}") + fi +elif [ -z "$from" ] && [ -z "$to" ] && [ -n "${PRE_COMMIT_REMOTE_NAME:-}" ]; then + RANGE=("HEAD" --not "--remotes=${PRE_COMMIT_REMOTE_NAME}") +fi + +echo "== tracked .env files, root CONTEXT.md, and docs/megaplan/ ==" +git ls-files -z >"$tmp" +if scan paths; then + echo ".env files, root CONTEXT.md, and docs/megaplan/ must not be tracked" >&2 + exit 1 +fi + +if [ "${#RANGE[@]}" -gt 0 ]; then + echo "== .env files, root CONTEXT.md, and docs/megaplan/ in pushed commits ==" + git rev-list "${RANGE[@]}" | + git diff-tree --stdin --root -r -z --no-commit-id --name-only --no-renames --cc --diff-filter=ACMRT --no-color >"$tmp" + if scan paths; then + echo ".env files, root CONTEXT.md, and docs/megaplan/ must not be pushed (present in the pushed commits)" >&2 + exit 1 + fi +fi + +echo "== absolute home paths ==" +# git grep only pre-filters (POSIX ERE); the lookbehind is applied by the helper. +rc=0 +git grep --no-color -n -I -z -E '(/home/|/Users/|[A-Za-z]:[/\\]Users[/\\])' -- . "${EXCLUDES[@]}" >"$tmp" || rc=$? +case "$rc" in + 0|1) ;; + *) echo "home-path check could not run (git grep rc=$rc)" >&2; exit 1 ;; +esac +if scan grep; then + echo "absolute home paths found" >&2 + exit 1 +fi + +if [ "${#RANGE[@]}" -gt 0 ]; then + echo "== absolute home paths in pushed commits ==" + git rev-list "${RANGE[@]}" | + git diff-tree --stdin --root -r --no-commit-id -p --cc -U0 --no-renames --no-ext-diff --no-textconv --no-color -- . "${EXCLUDES[@]}" >"$tmp" + # Added lines only; merge commits are scanned with --cc (see guard_scan.py). + if scan added; then + echo "absolute home paths found in the pushed commits" >&2 + exit 1 + fi +fi + +if [ "${MEGAPLAN_PRE_PUSH_GUARDS_ONLY:-}" = "1" ]; then + exit 0 +fi + +echo "== doc line limits ==" +scripts/check-doc-length.sh + +echo "== validator ==" +python3 scripts/validate.py + +echo "== tests ==" +python3 -m unittest discover -s tests diff --git a/scripts/validate.py b/scripts/validate.py new file mode 100755 index 0000000..4827e61 --- /dev/null +++ b/scripts/validate.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +"""Validate the skill repository. Standard library only. + +Checks: + frontmatter SKILL.md has a name equal to its folder and a description; values are strict YAML + (a plain scalar may not contain ": " or start with an indicator character). + links every relative Markdown link in tracked files resolves. + sections the skill keeps its six required level-2 headings in order. + templates all required template files exist with required headings/statuses and no regressions. + +Usage: python3 scripts/validate.py [--root PATH] +Exit status is 0 when every check passes, 1 otherwise. +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from pathlib import Path + +SKILL_DIR = Path("skills/megaplan") +SKILL = SKILL_DIR / "SKILL.md" +TEMPLATES_DIR = SKILL_DIR / "templates" + +LINK_RE = re.compile(r"\[[^\]]*\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+[^)]*)?\)") +REF_LINK_RE = re.compile(r"^\s*\[[^\]]+\]:\s*\n]+?)>?(?:\s+[\"'(].*)?$", re.M) + + +def read(root: Path, rel: Path) -> str: + return (root / rel).read_text(encoding="utf-8") + + +def tracked_markdown(root: Path) -> list[Path]: + """Tracked .md files, or every .md file outside hidden and docs dirs without git.""" + try: + out = subprocess.run( + ["git", "ls-files", "-z", "*.md"], cwd=root, capture_output=True, check=True + ).stdout.decode() + files = [Path(p) for p in out.split("\0") if p] + if files: + return files + except (OSError, subprocess.CalledProcessError): + pass + skip = {".git", "docs"} + return [ + p.relative_to(root) + for p in root.rglob("*.md") + if not any(part in skip or part.startswith(".") for part in p.relative_to(root).parts[:-1]) + ] + + +INDICATORS = set("[]{}#&*!|>%@`,?:") +KEY_RE = re.compile(r"^([A-Za-z][A-Za-z0-9_-]*):(?: (.*))?$") + + +def scalar_error(value: str) -> str | None: + """Why a frontmatter value is not a safe YAML scalar, or None when it is.""" + if not value: + return "empty value" + if value[0] == '"': + try: + parsed = json.loads(value) + except ValueError: + return "unterminated or badly escaped double-quoted string" + return None if isinstance(parsed, str) else "not a string" + if value[0] == "'": + inner = value[1:-1].replace("''", "") + if len(value) < 2 or value[-1] != "'" or "'" in inner: + return "unterminated or badly escaped single-quoted string" + return None + if value[0] in INDICATORS or value.startswith("- "): + return f"plain value starts with the YAML indicator {value[0]!r}; quote it" + if ": " in value or value.endswith(":"): + return 'plain value contains ": "; wrap the value in double quotes' + if " #" in value: + return 'plain value contains " #"; wrap the value in double quotes' + return None + + +def unquote(value: str) -> str: + if value.startswith('"'): + return json.loads(value) + if value.startswith("'"): + return value[1:-1].replace("''", "'") + return value + + +def check_frontmatter(root: Path) -> list[str]: + text = read(root, SKILL) + match = re.match(r"---\n(.*?)\n---\n", text, re.DOTALL) + if not match: + return [f"{SKILL}: missing YAML frontmatter"] + errors = [] + fields: dict[str, str] = {} + bad: set[str] = set() + for line in match.group(1).splitlines(): + if not line.strip(): + continue + parsed = KEY_RE.match(line) + if not parsed: + errors.append(f"{SKILL}: unsupported frontmatter line {line!r} (use `key: value`)") + continue + key, value = parsed.group(1), (parsed.group(2) or "").strip() + if key in fields: + errors.append(f"{SKILL}: duplicate key {key!r}") + continue + problem = scalar_error(value) + if problem: + errors.append(f"{SKILL}: {key}: {problem}") + bad.add(key) + continue + fields[key] = unquote(value) + for key in ("name", "description"): + if key not in fields and key not in bad: + errors.append(f"{SKILL}: missing {key}") + if "name" in fields and fields["name"] != SKILL_DIR.name: + errors.append(f"{SKILL}: name is {fields['name']!r}, expected {SKILL_DIR.name!r}") + if "description" in fields: + desc_len = len(fields["description"].strip()) + if desc_len < 40: + errors.append(f"{SKILL}: description is too short") + elif desc_len > 1024: + errors.append(f"{SKILL}: description is too long ({desc_len} chars, max 1024)") + return errors + + +def check_links(root: Path) -> list[str]: + errors = [] + for rel in tracked_markdown(root): + path = root / rel + if not path.is_file(): + continue + text = path.read_text(encoding="utf-8") + targets = [a or b for a, b in LINK_RE.findall(text)] + REF_LINK_RE.findall(text) + for target in targets: + if re.match(r"^[a-z]+:", target) or target.startswith("#"): + continue + file_part = target.split("#", 1)[0] + if not (path.parent / file_part).exists(): + errors.append(f"{rel}: broken link {target}") + return errors + + +REQUIRED_HEADINGS = [ + "## Files and visibility", + "## Scoping an item", + "## The item file", + "## ADRs", + "## When an item finishes", + "## Picking up where you left off", +] + + +def check_sections(root: Path) -> list[str]: + """The skill keeps its six required level-2 headings in order.""" + text = read(root, SKILL) + errors = [] + positions = [ + m.start() if (m := re.search("^" + re.escape(h) + "$", text, re.M)) else -1 + for h in REQUIRED_HEADINGS + ] + for heading, pos in zip(REQUIRED_HEADINGS, positions): + if pos < 0: + errors.append(f"{SKILL}: missing heading {heading!r}") + found = [p for p in positions if p >= 0] + if found != sorted(found): + errors.append(f"{SKILL}: sections are out of order") + return errors + + +REQUIRED_TEMPLATES = [ + "backlog.md", + "backlog-item.md", + "adr.md", + "done.md", + "glossary.md", + "megaplan.md", +] +BACKLOG_ITEM_HEADINGS = [ + "## Outcome", + "## Scope", + "## Touches", + "## Not touching", + "## Acceptance", + "## Log", +] +BACKLOG_STATUSES = [ + "pending", + "in-progress", + "blocked", + "review", + "superseded", +] +ADR_HEADINGS = [ + "## Context", + "## Decision", + "## Boundaries", + "## Consequences", +] +MEGAPLAN_HEADINGS = [ + "## What this is", + "## What already exists", +] +TEMPLATE_HEADINGS = ( + ("backlog-item.md", BACKLOG_ITEM_HEADINGS), + ("adr.md", ADR_HEADINGS), + ("megaplan.md", MEGAPLAN_HEADINGS), +) +TEMPLATE_TABLES = ( + ("done.md", "| ID | Date | Verified |"), + ("glossary.md", "| Term | Meaning | Lives in |"), +) +B01_RE = re.compile(r"\[b01\]|backlog-items/b01\.md") + + +def check_templates(root: Path) -> list[str]: + """Template files exist and enforce the v2 structure without regressions.""" + errors = [] + texts: dict[str, str] = {} + for name in REQUIRED_TEMPLATES: + rel = TEMPLATES_DIR / name + path = root / rel + if not path.is_file(): + errors.append(f"{rel}: missing template") + continue + texts[name] = path.read_text(encoding="utf-8") + + for name, headings in TEMPLATE_HEADINGS: + if name in texts: + rel = TEMPLATES_DIR / name + text = texts[name] + for heading in headings: + if not re.search("^" + re.escape(heading) + "$", text, re.M): + errors.append(f"{rel}: missing heading {heading!r}") + + if "backlog-item.md" in texts and "## Attack" in texts["backlog-item.md"]: + errors.append(f"{TEMPLATES_DIR / 'backlog-item.md'}: must not contain '## Attack'") + + if "backlog.md" in texts: + rel = TEMPLATES_DIR / "backlog.md" + text = texts["backlog.md"] + for status in BACKLOG_STATUSES: + if f"`{status}`" not in text: + errors.append(f"{rel}: missing status `{status}`") + + for name, header in TEMPLATE_TABLES: + if name in texts and header not in texts[name]: + errors.append(f"{TEMPLATES_DIR / name}: missing table header {header!r}") + + templates_dir = root / TEMPLATES_DIR + if templates_dir.is_dir(): + for path in sorted(templates_dir.glob("*.md")): + if B01_RE.search(path.read_text(encoding="utf-8")): + errors.append(f"{TEMPLATES_DIR / path.name}: template must not contain b01 link") + + return errors + + +CHECKS = [ + ("frontmatter", check_frontmatter), + ("links", check_links), + ("sections", check_sections), + ("templates", check_templates), +] + + +def validate(root: Path) -> list[str]: + errors = [] + for name, check in CHECKS: + try: + found = check(root) + except (OSError, KeyError, ValueError, TypeError) as exc: + found = [f"{name}: {type(exc).__name__}: {exc}"] + errors.extend(found) + print(f"{'FAIL' if found else 'ok '} {name}") + return errors + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent) + args = parser.parse_args(argv) + errors = validate(args.root.resolve()) + for error in errors: + print(f" - {error}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/megaplan/SKILL.md b/skills/megaplan/SKILL.md index 02f8d89..27e71b7 100644 --- a/skills/megaplan/SKILL.md +++ b/skills/megaplan/SKILL.md @@ -1,159 +1,136 @@ --- name: megaplan -description: Plan-tracking methodology for software projects. Use when starting work in a repo, scoping a feature, or picking up a project after time away — interviews the operator to agree scope, then writes a backlog of items, each with its own file where it needs one. +description: "Plan-tracking methodology for software projects: scoping items, durable ADRs, a live backlog, and resumable logs." --- # Megaplan -Documents, not machinery. Nothing here runs. The value is an agreed scope written down where the -next session can find it. +Documents, not machinery. Nothing here executes. The value is an agreed scope and decision trail +written down where the next session can find it without re-litigating old choices. -Two roles. The **operator** is the human who owns the project: they answer the interview, confirm -scope, and decide when something is finished. The **agent** does everything else — running the -interview, writing and updating every file here, and running attacks when asked. +## Files and visibility -Below, "you" is the agent. In each numbered interview question, the **bolded** part is what you say -to the operator — inside it "you" is the operator and "I" is you. Everything else, including the -notes under a question, is addressed to you. +Two-tier visibility keeps architectural decisions durable while letting process logs stay clean: -## Files +- **Durable boundaries (committed to git):** `docs/adr/-.md` for architectural + boundaries, plus an optional shared `docs/glossary.md` for domain vocabulary. +- **Ephemeral work** (committed on solo private repos, or excluded via `.git/info/exclude` on public + and team repos so remotes stay clean of process logs). When switching an existing repo from + tracked to local-only `docs/megaplan/`, untrack the existing files from the git index + (`git rm -r --cached docs/megaplan/`) before relying on `.git/info/exclude`, otherwise git keeps + committing changes to them: + - `docs/megaplan/backlog.md` — live work index only, one row per item + - `docs/megaplan/backlog-items/.md` — one file per item, when the item needs one + - `docs/megaplan/done.md` — append-only ledger of finished and superseded items + - `docs/megaplan/megaplan.md` — optional as-built snapshot; skip when `README.md`, `CONTEXT.md`, + or a flow map already describes what exists + - `docs/megaplan/glossary.md` — optional local glossary when not shared in the repo -``` -docs/megaplan/backlog.md index — live work only, one row per item -docs/megaplan/backlog-items/.md one file per item, when the item needs one -docs/megaplan/megaplan.md what this project is, and what already exists -docs/megaplan/done.md ledger — what got finished, append-only -docs/megaplan/glossary.md domain terms — the naming authority -``` - -Templates for all five are in `templates/`. Copy them out, then fill in the angle-bracket -placeholders and delete any row marked as an example. Don't redesign the sections or drop one. - -Read `backlog.md` to find the item, then load that item's file and work from it. Never load every -item file to work on one. +Templates for all files live in `templates/`. Copy them out, fill in angle-bracket placeholders, +and delete example rows. Keep sections intact unless marked optional. -A `superseded` item leaves the backlog the same way a finished one does: ask the operator for its -`done.md` line, saying what replaced it, then delete the row and the file. +Two roles: the **operator** owns the project, confirms scope, and writes `done.md`; the **agent** +runs scoping, maintains `backlog.md`, item files, and ADRs, and updates `megaplan.md` when used. -IDs are a `b` and a zero-padded number: `b01`, `b02`. The next one is one past the highest that -appears in either `backlog.md` or `done.md`. Every item that leaves the backlog leaves its ID in -`done.md`, so an ID is never reused. +IDs are `b` plus a zero-padded number (`b01`, `b02`) — one past the highest ID in `backlog.md` or +`done.md`. Because every exiting item records its ID in `done.md`, IDs are never reused. -Set the row to `in-progress` when you start work on it, `review` when you believe it is complete, -and `superseded` when something replaces it. The operator decides what is finished. +Statuses in `backlog.md`: `pending`, `in-progress`, `blocked`, `review`, `superseded`. Set `in-progress` +when work starts, `blocked` when waiting on an external dependency or decision, `review` when ready +for the operator, and `superseded` when another item replaces it. -## Setting up a repo +Setting up an empty or existing repo follows the same rule: existing work gets no backlog rows. +Only work the operator intends to do becomes an item. If you keep a `glossary.md`, limit it to +domain terms (name, one-line meaning, code pointer), edit existing rows on rename, and delete rows +whose code pointer no longer resolves. -Same in an empty repo and one with work already in it: run the interview, then write the files. +## Scoping an item -`## What already exists` in `megaplan.md` is as-built prose: real artifacts, and the negatives — the -things deliberately absent, like "no migrations" or "no auth layer". Describe what the code does now, -not what it was once meant to do. When an item changes what exists, edit the line it affects rather -than appending a new one; the section describes the current build, not its history. +Run scoping before creating item files or writing code. Skip it only for unambiguous trivial edits +such as a typo or a verbatim rename. -**Existing work gets no backlog rows.** Work the operator intends to do becomes an item. Everything -else is a line under "what already exists", or nothing. - -## The interview - -Run this before writing any of these files and before any code. Skip it only when the scope is -already unambiguous — a typo, or a rename handed to you verbatim. - -Keep asking until every answer names something checkable: a file, a path, an observable behaviour. -"It should work better" is not an answer. +**Path 1 — Conversational interview** (default when starting from an idea). In the numbered +questions below, the **bolded** text is what the agent says to the operator; keep asking until +every answer names something checkable (a path, symbol, or observable behaviour): 1. **What outcome, and how will you know it happened?** -2. **What already exists that this touches?** Take the answer in prose, then go find where it lives - — `file:line` for code, the section for a document — and read it back to confirm. Include the - negatives — "no new tables", "not touching the migration path". +2. **What already exists that this touches?** Verify the named paths in the repo (`file:line` for + code, section for docs), read them back to confirm, and capture the negatives ("no new tables", + "no migration changes"). 3. **What's out?** -4. **What did I cut from what you asked for, and what do you lose?** Ask this of yourself and - answer it yourself, about your own proposal. Not a rejected alternative — a subtraction from what - was actually asked for, with the cost named. +4. **What did I cut from what you asked for, and what do you lose?** The agent answers this about + its own proposal — an actual subtraction from what was requested, with its cost named. -Then restate the scope as **what you will not touch** — the paths, the systems, the behaviours that -stay as they are. Not a prose summary: a wrong clause in prose reads fine, a wrong entry in "not -touching `migrations/`" is obviously wrong at a glance. Get confirmation, then write. +Then restate the scope as **what you will not touch** — concrete paths, systems, and behaviours +staying untouched. Confirm before writing anything. If the operator corrects the restatement twice +and it is still wrong, stop and write nothing; the feature is not ready to be an item. -If the operator corrects your restatement twice and it is still wrong, the scope is not agreed. Tell -them the feature isn't ready to be an item, write nothing, and stop. +**Path 2 — From an existing spec** (when a spec, proposal, OpenSpec change, or ticket already +exists). Link it in `Spec:` at the top of the item file, skip interview questions already answered +by the spec, and confirm only `## Not touching`, checkable `## Acceptance` criteria, and any new +ADRs before writing. -**The item file is optional.** Small work gets a row only: put the outcome in the `Title` cell and -`—` where the link would go. The moment it needs a log, an attack section, or a second sentence, -create the file and move the detail into it. +**Fileless rows remain valid for small work:** put the outcome in the `Title` cell and `—` in the +`Item file` cell. Create the item file the moment the item needs a log, an acceptance list, or a +second sentence. ## The item file ``` # : -## Outcome what, and how the operator will know -## Scope checkbox list — always rewritten to current truth -## Touches question 2's answer — paths, plus file:line where it is code -## Not touching question 2's negatives, plus question 3, plus the restatement -## Cut question 4's answer, in your voice -## Log dated appends: what happened, what broke, the commit SHA where there was one -## Attack review findings, when the operator asks for one +Spec: <link to spec/proposal/ticket, or omit> +## Outcome what changes and how the operator will know +## Scope checkbox list — rewritten to current truth, never appended +## Touches paths; add :<line> only where it points at code +## Not touching what stays as it is +## Acceptance checkable criteria for verification +## Cut optional — only when something asked for was subtracted, with cost named +## Log dated appends: what happened, what broke, commit SHA ``` -**`## Touches` names paths.** Add a line number only where it points at code and the line is the -point. A pointer into a document goes stale the moment the document is edited, which is usually the -same commit. - -**`## Scope` is never appended to.** Rewrite it to say what is true now, and put every change in the -`## Log` as one dated line. Keep each fact in one place: a second copy never gets updated, and that -is how an item ends up claiming finished and unfinished at the same time. +- **`## Scope` is rewritten, never appended.** Replace it to reflect current truth whenever scope + shifts, and record the change as a dated entry in `## Log`. Never keep two copies of truth. +- **`## Touches` adds `:line` only for code.** Document line numbers go stale on the next edit. +- **`## Acceptance` holds checkable verification criteria**, not vague wishes. +- **`## Cut` is optional.** Include it only when something requested was subtracted, naming the cost. +- **`## Log` is what makes an item resumable.** Record what actually happened, errors hit, and + commit SHAs — checkboxes alone cannot distinguish unstarted work from unlogged progress. -**`## Log` is what makes an item resumable.** A ticked box tells you only that someone typed an `x`. -An unticked one cannot tell you whether the work never started or finished and was never ticked. -Record what happened, not what was intended. +Do not add an `Attack` section. Independent review and verification belong to dedicated reviewers +or verifiers; record findings against open work in `## Log` and fix them in place. Findings +against finished items become new backlog items. -An attack finding against a finished item becomes a new item. A finding against work still in -progress is fixed where it is and recorded in that item's `## Log`. +## ADRs -## When an item finishes - -When you believe an item is complete, set its row to `review` and ask the operator for one line in -`done.md` — ID, date, one sentence on what they verified. Never write that line yourself. Until it -exists the item is not finished; it is the record of what got done, and the cheapest answer to "is -this already done" without reading every item file. - -Once it is there, do the rest in one commit: edit `megaplan.md` under "what already exists" if the -item changed what exists, delete the row from `backlog.md`, and delete the item file. The deleted -file stays reachable in git history. - -The first item in a repo is the exception: it creates these files, so its own output lands in -`megaplan.md` as it is written rather than at finish. +Durable architectural boundaries live in `docs/adr/<NNNN>-<slug>.md` (created from +`templates/adr.md`) and are committed to git even when `docs/megaplan/` is git-excluded. -## The glossary +**Graduation rule:** whenever scoping or implementation establishes a boundary that future work +must respect — an invariant, interface contract, data boundary, or explicit non-goal, not a +temporary execution detail — write an ADR and link it from the item file. -Domain terms only — the vocabulary of the problem, not of the methodology. Term, one-line meaning, -where it lives in the code. Fill it from the answers to question 2; don't add an interview question -for vocabulary. - -Two rules keep it honest: - -- **A rename edits the existing row.** Never add a second row for the same concept. -- **If a term's code pointer no longer resolves, delete the row.** A stale row is worse than a - missing one: the glossary is the naming authority, so a dead term keeps pulling new code toward a - dead name. - -## Adversarial review +## When an item finishes -Two modes. The operator asks for one by name; neither runs on its own. +When implementation and checks are complete, set the row in `backlog.md` to `review` and ask the +operator for one line in `done.md` — ID, date, and one sentence on what they verified. Never write +that `done.md` line yourself unless explicitly authorized. -**Attack the item** — before code. Is the scope right, is the premise wrong, what is missing, what -will this collide with. +Once the `done.md` line exists: -**Attack the implementation** — after code. Does it do what the item said, what did it do that the -item never mentioned, and does the code use the glossary's terms or invent its own. +1. Update `docs/megaplan/megaplan.md` if present and affected by what changed. +2. Remove the item's row from `docs/megaplan/backlog.md`. +3. Handle the item file according to visibility: + - **If `docs/megaplan/` is git-tracked:** delete the item file (git history preserves it). + - **If `docs/megaplan/` is git-excluded:** move the item file to `docs/megaplan/archive/` (or an + external backup) so history is not silently lost. -Spawn subagents with the item file as their brief — plus the diff and the glossary for an -implementation attack, since the item file holds no code. Findings go under `## Attack`. +`superseded` items exit the exact same way: the operator writes the `done.md` line naming what +replaced the item, then the row and item file leave the live backlog. ## Picking up where you left off -Read `backlog.md` first and find the row you are resuming. Then open only that item's file. +Read `docs/megaplan/backlog.md` first and load only the active item file — never load every item +file to work on one. -`## Log` outranks `## Scope`. If the checkboxes say one thing and the log says another, the log is -what happened. If the log's last entry does not match the working tree, say so before writing any -code. +`## Log` outranks `## Scope`. If the checkboxes and log disagree, trust the log. If the last log +entry does not match the working tree, state the mismatch before writing any code. diff --git a/skills/megaplan/templates/adr.md b/skills/megaplan/templates/adr.md new file mode 100644 index 0000000..fb1fcfe --- /dev/null +++ b/skills/megaplan/templates/adr.md @@ -0,0 +1,27 @@ +# ADR-<NNNN>: <title> + +Status: Proposed | Accepted | Superseded by ADR-<NNNN> +Date: <YYYY-MM-DD> + +<!-- Durable architectural boundary committed in docs/adr/, even when docs/megaplan/ is git-excluded. --> + +## Context + +<!-- Why this decision is needed now and what constraints apply. --> +<context and problem forces> + +## Decision + +<!-- The architectural choice made. --> +<what we decided> + +## Boundaries + +<!-- What this rules in and rules out for future work. --> +- **In:** <what future changes must follow or build on> +- **Out:** <what is explicitly forbidden or kept separate> + +## Consequences + +<!-- Trade-offs, costs, and follow-up obligations accepted by this decision. --> +<positive and negative consequences> diff --git a/skills/megaplan/templates/backlog-item.md b/skills/megaplan/templates/backlog-item.md index 372300d..659f057 100644 --- a/skills/megaplan/templates/backlog-item.md +++ b/skills/megaplan/templates/backlog-item.md @@ -1,31 +1,38 @@ # <id>: <title> +Spec: <link to spec/proposal/ticket, or delete this line> + ## Outcome -<What changes, in one sentence — and how you will know it happened.> +<!-- One sentence: what changes and how the operator will know it happened. --> +<what changes, and how you will know> ## Scope -- [ ] <one step> - -Rewrite this whole list to current truth whenever scope changes; never append an amendment here. +<!-- Rewrite this list to current truth whenever scope changes; never append amendments here. --> +- [ ] <one concrete step> ## Touches -- `<path>` — <why; add `:<line>` where it points at code> +<!-- Paths only for docs; add :<line> only where pointing at code. --> +- `<path>` — <why> ## Not touching +<!-- Concrete paths, systems, and behaviours that stay unchanged. --> - `<path>` — <stays as it is> +## Acceptance + +<!-- Checkable criteria for independent verification; no vague wishes. --> +- [ ] <observable check or command that must pass> + ## Cut -<What was removed from what was asked for, and what that costs. The agent's answer.> +<!-- Optional: delete section unless something asked for was subtracted, with its cost named. --> +<what was subtracted from the request, and what is lost> ## Log +<!-- Dated appends only: what actually happened, what broke, commit SHA, or review findings. Outranks Scope. --> - **<YYYY-MM-DD>** — <what happened, what broke, commit SHA> - -## Attack - -<Review findings, when asked for. A finding needing its own work becomes a new item.> diff --git a/skills/megaplan/templates/backlog.md b/skills/megaplan/templates/backlog.md index 03262fc..0f07afb 100644 --- a/skills/megaplan/templates/backlog.md +++ b/skills/megaplan/templates/backlog.md @@ -1,24 +1,23 @@ # Backlog — <project> -The **operator** is the human who owns this project: they answer the interview, confirm scope, and -write `done.md`. The agent does everything else, including maintaining this file. +<!-- Roles: the operator confirms scope and writes done.md; the agent maintains this file and item files. --> +<!-- IDs: b01, b02 — one past highest in backlog.md or done.md, never reused. --> ## Statuses | Status | Meaning | |---|---| -| `pending` | Defined, not started | -| `in-progress` | Being worked now | -| `review` | Believed complete, waiting on the operator | -| `superseded` | Replaced by another item, and not delivered | +| `pending` | Scoped, not started | +| `in-progress` | Actively being worked | +| `blocked` | Waiting on an external dependency or decision | +| `review` | Implementation and checks done, waiting on operator | +| `superseded` | Replaced by another item, not delivered | -An item leaves this file when the operator writes its line in `done.md` — whether it was finished or -superseded. The agent then edits `megaplan.md` under "what already exists" if the item changed what -exists, and deletes both the row here and the item file. This file is live work only. +<!-- Finish rule: once the operator writes the done.md line, update megaplan.md if present, remove the row here, and either delete the item file (if git-tracked) or move it to docs/megaplan/archive/ (if git-excluded). --> ## Index | ID | Title | Status | Item file | |---|---|---|---| -<!-- example row, delete this line on adoption --> -| <id> | <title, or the whole outcome when there is no item file> | pending | <link to the item file, or —> | +<!-- example row, delete on adoption --> +| `<id>` | <title, or full outcome when fileless> | pending | <path to item file, or —> | diff --git a/skills/megaplan/templates/done.md b/skills/megaplan/templates/done.md index 1814a6b..84025cf 100644 --- a/skills/megaplan/templates/done.md +++ b/skills/megaplan/templates/done.md @@ -1,9 +1,9 @@ # Done -Only the operator writes in this file. One line per item that leaves the backlog, whether it was -finished or superseded; append only. An item is not finished until its line is here. +<!-- Operator-only append-only ledger: agent must never write here unless explicitly authorized. --> +<!-- An item is not finished (or retired as superseded) until its row appears here. --> | ID | Date | Verified | |---|---|---| -<!-- example row, delete this line on adoption --> -| <id> | <YYYY-MM-DD> | <one sentence on what you verified> | +<!-- example row, delete on adoption --> +| `<id>` | `<YYYY-MM-DD>` | <one sentence on what was verified, or what superseded it> | diff --git a/skills/megaplan/templates/glossary.md b/skills/megaplan/templates/glossary.md index 86d255c..6d0439f 100644 --- a/skills/megaplan/templates/glossary.md +++ b/skills/megaplan/templates/glossary.md @@ -1,10 +1,9 @@ # Glossary -Domain terms only — the vocabulary of the problem, not of the methodology. - -A rename edits the existing row. If a term's code pointer no longer resolves, delete the row. +<!-- Optional: domain terms only (the vocabulary of the problem, not methodology). --> +<!-- Rules: a rename edits the existing row; if a term's code pointer no longer resolves, delete the row. --> | Term | Meaning | Lives in | |---|---|---| -<!-- example row, delete this line on adoption --> -| <term> | <one-line meaning> | `<path>:<line>` | +<!-- example row, delete on adoption --> +| <term> | <one-line domain meaning> | `<path>:<line>` | diff --git a/skills/megaplan/templates/megaplan.md b/skills/megaplan/templates/megaplan.md index 20d969c..4baac5e 100644 --- a/skills/megaplan/templates/megaplan.md +++ b/skills/megaplan/templates/megaplan.md @@ -1,12 +1,13 @@ # <project> +<!-- Optional as-built snapshot: skip this file if README.md, CONTEXT.md, or a flow map already covers what exists. --> + ## What this is -<One paragraph: the problem, and who has it.> +<One paragraph: the problem and who has it.> ## What already exists -<As-built. Name real artifacts, and the negatives — "no new tables", "no new migrations". -Describe what the code does now, not what it was once meant to do.> - -When an item changes what exists, edit the line it affects rather than appending a new one. +<!-- Edit affected lines in place when an item changes reality; never append history here. --> +<!-- Name real artifacts and deliberate negatives (e.g. "no migrations", "no auth layer"). --> +<as-built summary of what the code does now> diff --git a/tests/test_content.py b/tests/test_content.py new file mode 100644 index 0000000..e61c16a --- /dev/null +++ b/tests/test_content.py @@ -0,0 +1,202 @@ +"""Tests for skill sections and template checks in scripts/validate.py.""" + +import contextlib +import io +import shutil +import tempfile +import unittest +from pathlib import Path + +import test_validate as tv + +validate = tv.validate +SKILL = validate.SKILL +TEMPLATES_DIR = validate.TEMPLATES_DIR + + +VALID_TEMPLATES = { + "backlog.md": ( + "# Backlog — <project>\n\n" + "## Statuses\n\n" + "| Status | Meaning |\n" + "|---|---|\n" + "| `pending` | Defined, not started |\n" + "| `in-progress` | Being worked now |\n" + "| `blocked` | Waiting on external input |\n" + "| `review` | Believed complete, waiting on the operator |\n" + "| `superseded` | Replaced by another item |\n" + ), + "backlog-item.md": ( + "# <id>: <title>\n\n" + "## Outcome\n\n<outcome>\n\n" + "## Scope\n\n- [ ] <step>\n\n" + "## Touches\n\n- `<path>`\n\n" + "## Not touching\n\n- `<path>`\n\n" + "## Acceptance\n\n- <criterion>\n\n" + "## Log\n\n- **<YYYY-MM-DD>** — <note>\n" + ), + "adr.md": ( + "# <NNNN>: <title>\n\n" + "## Context\n\n<context>\n\n" + "## Decision\n\n<decision>\n\n" + "## Boundaries\n\n<boundaries>\n\n" + "## Consequences\n\n<consequences>\n" + ), + "done.md": "# Done\n\n| ID | Date | Verified |\n|---|---|---|\n| <id> | <YYYY-MM-DD> | <note> |\n", + "glossary.md": "# Glossary\n\n| Term | Meaning | Lives in |\n|---|---|---|\n| <term> | <meaning> | `<path>:<line>` |\n", + "megaplan.md": "# <project>\n\n## What this is\n\n<summary>\n\n## What already exists\n\n<state>\n", +} + + +class SectionTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + for rel in tv.tracked_files(): + if (tv.ROOT / rel).is_file(): + (self.root / rel).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(tv.ROOT / rel, self.root / rel) + + def tearDown(self): + self._tmp.cleanup() + + def edit(self, rel, old, new): + path = self.root / rel + text = path.read_text(encoding="utf-8") + self.assertIn(old, text, f"fixture text not found in {rel}") + path.write_text(text.replace(old, new, 1), encoding="utf-8") + + def errors(self, check): + with contextlib.redirect_stdout(io.StringIO()): + return check(self.root) + + def assertReports(self, check, fragment): + errors = self.errors(check) + self.assertTrue(any(fragment in e for e in errors), errors) + + def test_sections_pass(self): + self.assertEqual([], self.errors(validate.check_sections)) + + def test_missing_section_fails(self): + self.edit(SKILL, "## ADRs", "## Decisions") + self.assertReports(validate.check_sections, "missing heading") + + def test_out_of_order_fails(self): + self.edit(SKILL, "## Files and visibility", "## Placeholder") + self.edit(SKILL, "## Picking up where you left off", + "## Picking up where you left off\n\n## Files and visibility") + self.assertReports(validate.check_sections, "out of order") + + def test_demoted_heading_fails(self): + self.edit(SKILL, "## Scoping an item", "### Scoping an item") + self.assertReports(validate.check_sections, "missing heading") + + +class TemplateTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + tdir = self.root / TEMPLATES_DIR + tdir.mkdir(parents=True) + for name, content in VALID_TEMPLATES.items(): + (tdir / name).write_text(content, encoding="utf-8") + + def tearDown(self): + self._tmp.cleanup() + + def errors(self): + with contextlib.redirect_stdout(io.StringIO()): + return validate.check_templates(self.root) + + def assertReports(self, fragment): + errors = self.errors() + self.assertTrue(any(fragment in e for e in errors), errors) + + def test_valid_templates_pass(self): + self.assertEqual([], self.errors()) + + def test_missing_template_fails(self): + for name in VALID_TEMPLATES: + with self.subTest(template=name): + path = self.root / TEMPLATES_DIR / name + saved = path.read_text(encoding="utf-8") + path.unlink() + try: + self.assertReports("missing template") + finally: + path.write_text(saved, encoding="utf-8") + + def test_backlog_item_missing_heading_fails(self): + path = self.root / TEMPLATES_DIR / "backlog-item.md" + saved = path.read_text(encoding="utf-8") + for heading in validate.BACKLOG_ITEM_HEADINGS: + with self.subTest(heading=heading): + path.write_text(saved.replace(heading, "## Replaced", 1), encoding="utf-8") + self.assertReports(f"missing heading {heading!r}") + path.write_text(saved, encoding="utf-8") + + def test_backlog_item_demoted_heading_fails(self): + path = self.root / TEMPLATES_DIR / "backlog-item.md" + text = path.read_text(encoding="utf-8") + path.write_text(text.replace("## Acceptance", "### Acceptance", 1), encoding="utf-8") + self.assertReports("missing heading '## Acceptance'") + + def test_backlog_item_attack_regression_fails(self): + path = self.root / TEMPLATES_DIR / "backlog-item.md" + text = path.read_text(encoding="utf-8") + path.write_text(text + "\n## Attack\n\n<findings>\n", encoding="utf-8") + self.assertReports("## Attack") + + def test_backlog_missing_status_fails(self): + path = self.root / TEMPLATES_DIR / "backlog.md" + saved = path.read_text(encoding="utf-8") + for status in validate.BACKLOG_STATUSES: + with self.subTest(status=status): + path.write_text(saved.replace(f"`{status}`", "removed", 1), encoding="utf-8") + self.assertReports(f"missing status `{status}`") + path.write_text(saved, encoding="utf-8") + + def test_adr_missing_heading_fails(self): + path = self.root / TEMPLATES_DIR / "adr.md" + saved = path.read_text(encoding="utf-8") + for heading in validate.ADR_HEADINGS: + with self.subTest(heading=heading): + path.write_text(saved.replace(heading, "## Replaced", 1), encoding="utf-8") + self.assertReports(f"missing heading {heading!r}") + path.write_text(saved, encoding="utf-8") + + def test_done_missing_table_header_fails(self): + path = self.root / TEMPLATES_DIR / "done.md" + text = path.read_text(encoding="utf-8") + path.write_text(text.replace("| ID | Date | Verified |", "| ID | Date |", 1), encoding="utf-8") + self.assertReports("| ID | Date | Verified |") + + def test_glossary_missing_table_header_fails(self): + path = self.root / TEMPLATES_DIR / "glossary.md" + text = path.read_text(encoding="utf-8") + path.write_text(text.replace("| Term | Meaning | Lives in |", "| Term | Meaning |", 1), + encoding="utf-8") + self.assertReports("| Term | Meaning | Lives in |") + + def test_megaplan_missing_heading_fails(self): + path = self.root / TEMPLATES_DIR / "megaplan.md" + saved = path.read_text(encoding="utf-8") + for heading in validate.MEGAPLAN_HEADINGS: + with self.subTest(heading=heading): + path.write_text(saved.replace(heading, "## Replaced", 1), encoding="utf-8") + self.assertReports(f"missing heading {heading!r}") + path.write_text(saved, encoding="utf-8") + + def test_template_b01_bracket_link_fails(self): + path = self.root / TEMPLATES_DIR / "backlog.md" + path.write_text(path.read_text(encoding="utf-8") + "\n| [b01] | example |\n", encoding="utf-8") + self.assertReports("b01") + + def test_template_b01_path_link_fails(self): + path = self.root / TEMPLATES_DIR / "done.md" + path.write_text(path.read_text(encoding="utf-8") + "\nSee backlog-items/b01.md\n", encoding="utf-8") + self.assertReports("b01") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pre_push.py b/tests/test_pre_push.py new file mode 100644 index 0000000..0a39d47 --- /dev/null +++ b/tests/test_pre_push.py @@ -0,0 +1,578 @@ +"""Tests for scripts/hooks/pre_push.sh guards (standard library only). + +Each test builds a throwaway git repo and runs the script with +MEGAPLAN_PRE_PUSH_GUARDS_ONLY=1, so only the guard section runs (no recursion into +the real suite). The hook must not depend on PCRE or GNU grep (see PortabilityTests). +""" +import atexit +import functools +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "hooks" / "pre_push.sh" +HELPER = SCRIPT.with_name("guard_scan.py") +HOME_LINE = "see /" + "home/someone/project\n" # split so the repo guard ignores this file +WIN_WSL_LINES = ( + ("win_bs", "see C:\\" + "Users\\alice\\proj\n"), + ("win_fwd", "see C:/" + "Users/alice/proj\n"), + ("wsl", "see /mnt/c/" + "Users/alice/proj\n"), +) +UNICODE_HOME_LINES = ( + ("unix_unicode", "see /" + "home/élise/project\n"), + ("win_unicode", "see C:\\" + "Users\\李\\project\n"), +) + + +# Isolated HOME/XDG so user config is never read, even by git older than 2.32 +# (which ignores GIT_CONFIG_GLOBAL). +_HOME = tempfile.mkdtemp(prefix="megaplan-home-") +atexit.register(shutil.rmtree, _HOME, ignore_errors=True) + + +# A python3 that is the interpreter running these tests, first on PATH: a version-manager shim +# (asdf, mise, pyenv) cannot find its config under the isolated HOME and would make the +# hook's `python3` calls fail. +_BIN = tempfile.mkdtemp(prefix="megaplan-bin-") +atexit.register(shutil.rmtree, _BIN, ignore_errors=True) +os.symlink(sys.executable, os.path.join(_BIN, "python3")) + + +def _env(**extra): + env = {k: v for k, v in os.environ.items() + if not k.startswith("GIT_") and not k.startswith("PRE_COMMIT_")} + env.update(HOME=_HOME, XDG_CONFIG_HOME=_HOME, GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, + GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid", + MEGAPLAN_PRE_PUSH_GUARDS_ONLY="1") + env["PATH"] = _BIN + os.pathsep + env.get("PATH", "") + env.update(extra) + return env + + +def _configure_ssh_signing(repo, workdir): + """Configure ssh commit signing in repo with a throwaway key; returns False on failure.""" + key = Path(workdir) / "key" + r = subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)], + capture_output=True) + if r.returncode != 0: + return False + pub = key.with_suffix(".pub").read_text().split() + allowed = Path(workdir) / "allowed" + allowed.write_text("t@example.invalid " + pub[0] + " " + pub[1] + "\n") + for k, v in (("gpg.format", "ssh"), ("user.signingkey", str(key)), + ("commit.gpgSign", "true"), ("gpg.ssh.allowedSignersFile", str(allowed))): + if subprocess.run(["git", "config", k, v], cwd=repo, env=_env(), + capture_output=True).returncode != 0: + return False + return True + + +@functools.lru_cache(maxsize=None) +def ssh_signing_available(): + """True if this machine can make an ssh-signed commit (needs ssh-keygen and git >= 2.34).""" + if not shutil.which("ssh-keygen"): + return False + with tempfile.TemporaryDirectory() as d: + repo = Path(d) / "r" + repo.mkdir() + try: + def run(*a): + return subprocess.run(["git", *a], cwd=repo, env=_env(), capture_output=True) + if run("init", "-q").returncode != 0 or not _configure_ssh_signing(repo, d): + return False + (repo / "f").write_text("x\n") + return (run("add", "f").returncode == 0 + and run("commit", "-q", "-m", "probe").returncode == 0) + except OSError: + return False + + +class PrePushGuards(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.repo = Path(self._tmp.name) + self.git("init", "-q") + self.commit({"README.md": "hello\n"}, "base") + + def git(self, *args): + r = subprocess.run(["git", *args], cwd=self.repo, env=_env(), + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + return r.stdout.strip() + + def commit(self, files, msg): + for name, content in files.items(): + p = self.repo / name + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(content) + self.git("add", "-A") + self.git("commit", "-q", "-m", msg) + return self.git("rev-parse", "HEAD") + + def remove(self, name, msg): + self.git("rm", "-q", name) + self.git("commit", "-q", "-m", msg) + return self.git("rev-parse", "HEAD") + + def run_hook(self, script=SCRIPT, cwd=None, **extra): + return self.run_hook_full(script, cwd, **extra).returncode + + def run_hook_full(self, script=SCRIPT, cwd=None, **extra): + return subprocess.run(["bash", str(script)], cwd=cwd or self.repo, env=_env(**extra), + capture_output=True, text=True) + + def run_range(self, base): + return self.run_hook(PRE_COMMIT_FROM_REF=base, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")) + + # checkout checks (no range variables) + def test_clean(self): + self.assertEqual(self.run_hook(), 0) + + def test_tracked_env(self): + self.commit({".env": "X=1\n"}, "env") + r = self.run_hook_full() + self.assertEqual(r.returncode, 1) + self.assertIn("must not be tracked", r.stderr) + + def test_nested_env_local(self): + self.commit({"sub/.env.local": "X=1\n"}, "env") + self.assertEqual(self.run_hook(), 1) + + def test_lookalike_names_pass(self): + self.commit({"envoy.md": "x\n", "config.env.md": "x\n"}, "ok") + self.assertEqual(self.run_hook(), 0) + + def test_non_ascii_dir_env(self): + self.commit({"données/.env": "X=1\n"}, "env") + self.assertEqual(self.run_hook(), 1) + + def test_root_context_md_tracked(self): + self.commit({"CONTEXT.md": "x\n"}, "ctx") + self.assertEqual(self.run_hook(), 1) + + def test_nested_context_md_passes(self): + self.commit({"docs/CONTEXT.md": "x\n"}, "ctx") + self.assertEqual(self.run_hook(), 0) + + def test_root_context_md_added_then_removed_in_range(self): + base = self.git("rev-parse", "HEAD") + self.commit({"CONTEXT.md": "x\n"}, "add") + self.remove("CONTEXT.md", "rm") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_docs_megaplan_tracked(self): + self.commit({"docs/megaplan/backlog.md": "# Backlog\n"}, "megaplan") + r = self.run_hook_full() + self.assertEqual(r.returncode, 1) + self.assertIn("must not be tracked", r.stderr) + + def test_docs_megaplan_added_then_removed_in_range(self): + base = self.git("rev-parse", "HEAD") + self.commit({"docs/megaplan/backlog.md": "# Backlog\n"}, "add") + self.remove("docs/megaplan/backlog.md", "rm") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_url_path_passes(self): + self.commit({"a.md": "https://host/home/x\nhttps://example.com/home/u\n"}, "url") + self.assertEqual(self.run_hook(), 0) + + def test_home_path_in_checkout(self): + self.commit({"a.md": HOME_LINE}, "home") + r = self.run_hook_full() + self.assertEqual(r.returncode, 1) + self.assertIn("absolute home paths found", r.stderr) + self.assertNotIn("failed", r.stderr) + + def test_windows_and_wsl_home_paths_in_checkout_and_range(self): + for name, line in WIN_WSL_LINES: + with self.subTest(name=name): + base = self.git("rev-parse", "HEAD") + self.commit({"a.md": line}, "add " + name) + self.assertEqual(self.run_hook(), 1) + self.remove("a.md", "rm " + name) + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_unicode_home_paths_in_checkout_and_range(self): + for name, line in UNICODE_HOME_LINES: + with self.subTest(name=name): + base = self.git("rev-parse", "HEAD") + self.commit({"a.md": line}, "add " + name) + self.assertEqual(self.run_hook(), 1) + self.remove("a.md", "rm " + name) + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + # pushed-range checks + def test_range_clean(self): + base = self.git("rev-parse", "HEAD") + self.commit({"b.md": "fine\n"}, "b") + self.assertEqual(self.run_range(base), 0) + + def test_env_added_then_removed_in_range(self): + base = self.git("rev-parse", "HEAD") + self.commit({".env": "X=1\n"}, "add env") + self.remove(".env", "rm env") + self.assertEqual(self.run_hook(), 0) # checkout alone is clean + r = self.run_hook_full(PRE_COMMIT_FROM_REF=base, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")) + self.assertEqual(r.returncode, 1) + self.assertIn("must not be pushed", r.stderr) + self.assertNotIn("failed", r.stderr) + + def test_non_ascii_env_added_then_removed_in_range(self): + base = self.git("rev-parse", "HEAD") + self.commit({"données/.env": "X=1\n"}, "add env") + self.remove("données/.env", "rm env") + self.assertEqual(self.run_range(base), 1) + + def test_home_path_added_then_removed_in_range(self): + base = self.git("rev-parse", "HEAD") + self.commit({"a.md": HOME_LINE}, "add") + self.remove("a.md", "rm") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_url_in_range_passes(self): + base = self.git("rev-parse", "HEAD") + self.commit({"a.md": "https://host/home/x\n"}, "url") + self.assertEqual(self.run_range(base), 0) + + def test_bad_commit_before_range_is_ignored(self): + self.commit({".env": "X=1\n"}, "add env") + self.remove(".env", "rm env") + base = self.git("rev-parse", "HEAD") + self.commit({"b.md": "fine\n"}, "b") + self.assertEqual(self.run_range(base), 0) + + def test_new_branch_uses_commits_not_on_remotes(self): + # Zero from-ref (new branch): range is everything not reachable from a remote ref. + self.git("update-ref", "refs/remotes/origin/main", "HEAD") + self.commit({".env": "X=1\n"}, "add env") + self.remove(".env", "rm env") + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")), 1) + + def test_new_branch_ignores_commits_already_on_remote(self): + self.commit({".env": "X=1\n"}, "add env") + self.remove(".env", "rm env") + self.git("update-ref", "refs/remotes/origin/main", "HEAD") + self.commit({"b.md": "fine\n"}, "b") + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")), 0) + + def test_new_branch_scopes_exclusion_to_destination_remote(self): + self.git("update-ref", "refs/remotes/origin/main", "HEAD") + self.commit({".env": "X=1\n"}, "add env") + self.remove(".env", "rm env") + self.git("update-ref", "refs/remotes/private/feat", "HEAD") + head = self.git("rev-parse", "HEAD") + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=head, + PRE_COMMIT_REMOTE_NAME="private"), 0) + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=head, + PRE_COMMIT_REMOTE_NAME="origin"), 1) + + def test_cleanup_push_deleting_remote_bad_content_is_allowed(self): + self.commit({".env": "X=1\n", "a.md": HOME_LINE}, "bad, already on the remote") + remote = self.git("rev-parse", "HEAD") + self.git("update-ref", "refs/remotes/origin/main", remote) + self.git("rm", "-q", ".env") + self.commit({"a.md": "clean\n"}, "cleanup") + self.assertEqual(self.run_range(remote), 0) + + def test_home_path_introduced_by_merge_resolution_then_removed(self): + self.commit({"a.md": "base\n"}, "a") + base = self.git("rev-parse", "HEAD") + branch = self.git("rev-parse", "--abbrev-ref", "HEAD") + self.git("checkout", "-q", "-b", "side") + self.commit({"a.md": "side\n"}, "side") + self.git("checkout", "-q", branch) + self.commit({"a.md": "main\n"}, "main") + merge = subprocess.run(["git", "merge", "side"], cwd=self.repo, env=_env(), + capture_output=True, text=True) + self.assertNotEqual(merge.returncode, 0) # conflict + (self.repo / "a.md").write_text(HOME_LINE) + self.git("add", "a.md") + self.git("commit", "-q", "-m", "merge with bad resolution") + self.commit({"a.md": "clean\n"}, "fix after merge") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_merge_bringing_in_lines_is_not_reflagged(self): + # New branch (zero from-ref). A remote-only parent carries a home-path line; a clean + # merge of it must not be attributed to the merge commit (-m would flag it). + branch = self.git("rev-parse", "--abbrev-ref", "HEAD") + self.git("checkout", "-q", "-b", "remote-only") + self.commit({"legacy.md": HOME_LINE}, "legacy, already on the remote") + self.git("update-ref", "refs/remotes/origin/remote-only", "HEAD") + self.git("checkout", "-q", branch) + self.commit({"c.md": "main\n"}, "main") + self.git("merge", "-q", "--no-edit", "remote-only") + # The merged file is tracked, so the checkout scan would flag it; deleting it from the + # working tree only (git grep skips missing files) isolates the pushed-range scan. + (self.repo / "legacy.md").unlink() + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")), 0) + + def test_forced_colour_does_not_hide_home_path(self): + self.git("config", "color.ui", "always") + self.git("config", "color.grep", "always") + base = self.git("rev-parse", "HEAD") + self.commit({"a.md": HOME_LINE}, "home") + self.assertEqual(self.run_hook(), 1) + self.remove("a.md", "rm") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_forced_colour_does_not_hide_env_in_range(self): + self.git("config", "color.ui", "always") + base = self.git("rev-parse", "HEAD") + self.commit({".env": "X=1\n"}, "env") + self.remove(".env", "rm") + self.assertEqual(self.run_range(base), 1) + + def _hook_copy(self, helper_text=None): + d = Path(self._tmp.name + "-hook") + d.mkdir() + self.addCleanup(shutil.rmtree, d, ignore_errors=True) + shutil.copy(SCRIPT, d / "pre_push.sh") + if helper_text is not None: + (d / "guard_scan.py").write_text(helper_text) + return d / "pre_push.sh" + + def test_helper_crash_fails_closed(self): + text = HELPER.read_text().replace( + "def forbidden_paths(data):", "def forbidden_paths(data):\n raise RuntimeError('boom')") + r = self.run_hook_full(self._hook_copy(text)) + self.assertEqual(r.returncode, 1) + self.assertIn("failed", r.stderr) + + def test_missing_helper_fails_closed(self): + r = self.run_hook_full(self._hook_copy()) + self.assertEqual(r.returncode, 1) + self.assertIn("failed", r.stderr) + + def test_run_from_subdirectory_with_relative_path(self): + # The hook and helper are copied into the repo, so a helper path resolved after the + # cd (relative to the repo top level) would not be found from the subdirectory. + hooks = self.repo / "scripts" / "hooks" + hooks.mkdir(parents=True) + shutil.copy(SCRIPT, hooks / "pre_push.sh") + shutil.copy(HELPER, hooks / "guard_scan.py") + sub = self.repo / "sub" / "dir" + sub.mkdir(parents=True) + rel = os.path.relpath(hooks / "pre_push.sh", sub) + self.assertEqual(self.run_hook(script=rel, cwd=sub), 0) + self.commit({".env": "X=1\n"}, "env") + self.assertEqual(self.run_hook(script=rel, cwd=sub), 1) + + def test_cdpath_does_not_break_helper_lookup(self): + # A decoy directory on CDPATH has scripts/hooks/ but no helper; a plain `cd` to the + # relative hook directory would land there. + hooks = self.repo / "scripts" / "hooks" + hooks.mkdir(parents=True) + shutil.copy(SCRIPT, hooks / "pre_push.sh") + shutil.copy(HELPER, hooks / "guard_scan.py") + decoy = Path(self._tmp.name + "-decoy") + (decoy / "scripts" / "hooks").mkdir(parents=True) + self.addCleanup(shutil.rmtree, decoy, ignore_errors=True) + self.assertEqual(self.run_hook(script="scripts/hooks/pre_push.sh", CDPATH=str(decoy)), 0) + + def test_root_commit_env_added_then_removed(self): + # --root: a root commit in the range must be scanned (no remote refs, zero from-ref). + self.git("checkout", "-q", "--orphan", "fresh") + self.git("rm", "-rq", "--cached", ".") + (self.repo / "README.md").unlink() + self.commit({".env": "X=1\n"}, "root adds env") + self.remove(".env", "rm env") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")), 1) + + def test_root_commit_home_path_added_then_removed(self): + self.git("checkout", "-q", "--orphan", "fresh") + self.git("rm", "-rq", "--cached", ".") + (self.repo / "README.md").unlink() + self.commit({"a.md": HOME_LINE}, "root adds home path") + self.remove("a.md", "rm") + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF="0" * 40, + PRE_COMMIT_TO_REF=self.git("rev-parse", "HEAD")), 1) + + def test_initial_push_with_remote_name_only_scans_root_history(self): + self.git("checkout", "-q", "--orphan", "fresh") + self.git("rm", "-rq", "--cached", ".") + (self.repo / "README.md").unlink() + self.commit({".env": "X=1\n"}, "root adds env") + self.remove(".env", "rm env") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_hook(PRE_COMMIT_REMOTE_NAME="origin"), 1) + + def test_symlink_env_changed_to_file_then_deleted(self): + os.symlink("target", self.repo / ".env") + self.git("add", "-A") + self.git("commit", "-q", "-m", "env symlink, already on the remote") + remote = self.git("rev-parse", "HEAD") + (self.repo / ".env").unlink() + self.commit({".env": "X=1\n"}, "symlink becomes a regular file (type change)") + self.remove(".env", "rm env") + self.assertEqual(self.run_range(remote), 1) + + def test_hook_python_is_the_test_interpreter_not_a_shim(self): + path = _env()["PATH"].split(os.pathsep) + self.assertEqual(os.path.realpath(os.path.join(path[0], "python3")), + os.path.realpath(sys.executable)) + # A stand-in shim later on PATH that fails without a tool-versions file in HOME. + fake = Path(self._tmp.name + "-shim") + fake.mkdir() + self.addCleanup(shutil.rmtree, fake, ignore_errors=True) + (fake / "python3").write_text('#!/bin/sh\n[ -f "$HOME/.tool-versions" ] || exit 3\n') + (fake / "python3").chmod(0o755) + path.insert(1, str(fake)) + self.assertEqual(self.run_hook(PATH=os.pathsep.join(path)), 0) + + def test_range_scans_use_plumbing_not_log(self): + text = SCRIPT.read_text() + self.assertNotIn("git log", text) + self.assertEqual(len(re.findall(r"git rev-list \"\$\{RANGE\[@\]\}\" \|\s*\n\s*git diff-tree --stdin", + text)), 2) + + def _signed_repo(self): + wd = Path(self._tmp.name + "-key") + wd.mkdir() + self.addCleanup(shutil.rmtree, wd, ignore_errors=True) + self.assertTrue(_configure_ssh_signing(self.repo, wd)) + self.git("config", "log.showSignature", "true") + + @unittest.skipUnless(ssh_signing_available(), "ssh commit signing unavailable (needs git >= 2.34 and ssh-keygen)") + def test_show_signature_does_not_hide_env_in_range(self): + self._signed_repo() + base = self.git("rev-parse", "HEAD") + self.commit({".env": "X=1\n"}, "add env") + self.remove(".env", "rm env") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + @unittest.skipUnless(ssh_signing_available(), "ssh commit signing unavailable (needs git >= 2.34 and ssh-keygen)") + def test_show_signature_does_not_hide_home_path_in_range(self): + self._signed_repo() + base = self.git("rev-parse", "HEAD") + self.commit({"a.md": HOME_LINE}, "add") + self.remove("a.md", "rm") + self.assertEqual(self.run_range(base), 1) + + def test_env_added_only_in_merge_resolution_then_removed(self): + self.commit({"a.md": "base\n"}, "a") + base = self.git("rev-parse", "HEAD") + branch = self.git("rev-parse", "--abbrev-ref", "HEAD") + self.git("checkout", "-q", "-b", "side") + self.commit({"a.md": "side\n"}, "side") + self.git("checkout", "-q", branch) + self.commit({"a.md": "main\n"}, "main") + subprocess.run(["git", "merge", "side"], cwd=self.repo, env=_env(), capture_output=True) + (self.repo / "a.md").write_text("resolved\n") + (self.repo / ".env").write_text("X=1\n") + self.git("add", "-A") + self.git("commit", "-q", "-m", "merge adding .env") + self.remove(".env", "rm env") + self.assertEqual(self.run_hook(), 0) + self.assertEqual(self.run_range(base), 1) + + def test_ref_deletion_skips_range_scan(self): + base = self.git("rev-parse", "HEAD") + self.assertEqual(self.run_hook(PRE_COMMIT_FROM_REF=base, PRE_COMMIT_TO_REF="0" * 40), 0) + + +class HelperTests(unittest.TestCase): + def scan(self, mode, data): + r = subprocess.run(["python3", str(HELPER), mode], input=data, capture_output=True) + return r.returncode + + def test_added_lookbehind_cases(self): + home = "/" + "home/u" + users = "/" + "Users/u" + win_bs = "C:\\" + "Users\\alice\\proj" + win_fwd = "C:/" + "Users/alice/proj" + wsl = "/mnt/c/" + "Users/alice/proj" + hit = lambda text: self.scan("added", ("@@ -0,0 +1 @@\n+" + text + "\n").encode()) + self.assertEqual(hit("cd " + home), 0) + self.assertEqual(hit(users + "/x"), 0) + self.assertEqual(hit("(" + home + ")"), 0) + self.assertEqual(hit(win_bs), 0) + self.assertEqual(hit("cd " + win_fwd), 0) + self.assertEqual(hit("cd " + wsl), 0) + self.assertEqual(hit("(" + wsl + ")"), 0) + self.assertEqual(hit("https://host" + home + "/x"), 1) + self.assertEqual(hit("https://example.com" + home), 1) + self.assertEqual(hit("https://example.com" + wsl), 1) + self.assertEqual(hit("foo" + win_bs), 1) + self.assertEqual(hit("pre" + home), 1) + self.assertEqual(hit("a-" + home), 1) + self.assertEqual(hit("~" + home), 1) + + def test_added_ignores_headers_context_and_removals(self): + home = "/" + "home/u" + patch = ("diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n-" + home + "\n context " + home + "\n") + self.assertEqual(self.scan("added", patch.encode()), 1) + + def test_combined_diff_needs_all_plus_columns(self): + home = "/" + "home/u" + # added against only the first parent: not a hit + self.assertEqual(self.scan("added", ("@@@ -1 -1 +1 @@@\n+ " + home + "\n").encode()), 1) + self.assertEqual(self.scan("added", ("@@@ -1 -1 +1 @@@\n +" + home + "\n").encode()), 1) + self.assertEqual(self.scan("added", ("@@@ -1 -1 +1 @@@\n++" + home + "\n").encode()), 0) + + def test_paths(self): + self.assertEqual(self.scan("paths", b"a/.env\0b.md\0"), 0) + self.assertEqual(self.scan("paths", b"CONTEXT.md\0"), 0) + self.assertEqual(self.scan("paths", b"docs/megaplan/backlog.md\0"), 0) + self.assertEqual(self.scan("paths", b"docs/CONTEXT.md\0docs/megaplan-other/a.md\0envoy.md\0config.env.md\0"), 1) + + def test_grep_mode(self): + home = "/" + "home/u" + win_bs = "C:\\" + "Users\\alice\\proj" + win_fwd = "C:/" + "Users/alice/proj" + wsl = "/mnt/c/" + "Users/alice/proj" + self.assertEqual(self.scan("grep", ("f\0" + "1\0see " + home + "\n").encode()), 0) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see " + win_bs + "\n").encode()), 0) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see " + win_fwd + "\n").encode()), 0) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see " + wsl + "\n").encode()), 0) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see https://h" + home + "\n").encode()), 1) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see https://example.com" + home + "\n").encode()), 1) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see https://example.com" + wsl + "\n").encode()), 1) + + def test_unicode_home_paths_in_helper(self): + unix_u = "/" + "home/élise/project" + win_u = "C:\\" + "Users\\李\\project" + self.assertEqual(self.scan("added", ("@@ -0,0 +1 @@\n+see " + unix_u + "\n").encode()), 0) + self.assertEqual(self.scan("added", ("@@ -0,0 +1 @@\n+see " + win_u + "\n").encode()), 0) + self.assertEqual(self.scan("added", ("@@ -0,0 +1 @@\n+https://host" + unix_u + "\n").encode()), 1) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see " + unix_u + "\n").encode()), 0) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see " + win_u + "\n").encode()), 0) + self.assertEqual(self.scan("grep", ("f\0" + "1\0see https://host" + unix_u + "\n").encode()), 1) + + def test_bad_usage_fails(self): + self.assertEqual(self.scan("nope", b""), 2) + + +class PortabilityTests(unittest.TestCase): + def test_no_pcre_dependency(self): + text = SCRIPT.read_text() + self.assertIsNone(re.search(r"grep\b.*\s-[a-zA-Z]*P", text)) + self.assertNotIn("perl-regexp", text) + self.assertNotIn("patternType", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_validate.py b/tests/test_validate.py new file mode 100644 index 0000000..5eff62c --- /dev/null +++ b/tests/test_validate.py @@ -0,0 +1,192 @@ +"""Tests for scripts/validate.py. Each test breaks one property in a temporary copy of the repository.""" + +import contextlib +import io +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "scripts")) + +import validate # noqa: E402 + +SKILL = validate.SKILL +NAME = validate.SKILL_DIR.name + + +def tracked_files(): + """Tracked files of the repository, or every file outside .git and docs without git.""" + try: + out = subprocess.run(["git", "ls-files", "-z"], cwd=ROOT, capture_output=True, + check=True).stdout.decode() + files = [Path(p) for p in out.split("\0") if p] + if files: + return files + except (OSError, subprocess.CalledProcessError): + pass + return [p.relative_to(ROOT) for p in ROOT.rglob("*") + if p.is_file() and not {".git", "docs", "__pycache__"} & set(p.relative_to(ROOT).parts)] + + +class ValidateTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + for rel in tracked_files(): + if (ROOT / rel).is_file(): + (self.root / rel).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(ROOT / rel, self.root / rel) + + def tearDown(self): + self._tmp.cleanup() + + def edit(self, rel, old, new): + path = self.root / rel + text = path.read_text(encoding="utf-8") + self.assertIn(old, text, f"fixture text not found in {rel}") + path.write_text(text.replace(old, new, 1), encoding="utf-8") + + def errors(self, check): + with contextlib.redirect_stdout(io.StringIO()): + return check(self.root) + + def set_description(self, value): + path = self.root / SKILL + text = path.read_text(encoding="utf-8") + start = text.index("description:") + end = text.index("\n", start) + path.write_text(text[:start] + "description: " + value + text[end:], encoding="utf-8") + + def assertReports(self, check, fragment): + errors = self.errors(check) + self.assertTrue(any(fragment in e for e in errors), errors) + + def test_repository_passes(self): + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual([], validate.validate(self.root)) + + def test_main_exits_zero_on_success(self): + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(0, validate.main(["--root", str(self.root)])) + + def test_main_exits_nonzero_on_failure(self): + self.edit(SKILL, f"name: {NAME}", "name: other") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(1, validate.main(["--root", str(self.root)])) + + def test_check_exception_fails_validation(self): + def broken(root): + raise OSError("unreadable") + + saved = validate.CHECKS + validate.CHECKS = [("broken", broken)] + try: + with contextlib.redirect_stdout(io.StringIO()): + errors = validate.validate(self.root) + finally: + validate.CHECKS = saved + self.assertEqual(["broken: OSError: unreadable"], errors) + + def test_missing_frontmatter(self): + text = (self.root / SKILL).read_text(encoding="utf-8") + (self.root / SKILL).write_text(text.replace("---\n", "", 2), encoding="utf-8") + self.assertReports(validate.check_frontmatter, "missing YAML frontmatter") + + def test_wrong_skill_name(self): + self.edit(SKILL, f"name: {NAME}", f"name: {NAME.upper()}") + self.assertReports(validate.check_frontmatter, "name is") + + def test_short_description(self): + self.set_description('"Too short."') + self.assertReports(validate.check_frontmatter, "description") + + def test_max_length_description_passes(self): + self.set_description('"' + ("a" * 1024) + '"') + self.assertEqual([], self.errors(validate.check_frontmatter)) + + def test_overlong_description_fails(self): + self.set_description('"' + ("a" * 1025) + '"') + self.assertReports(validate.check_frontmatter, "too long") + + def test_unquoted_colon_space_fails(self): + self.set_description("Does a thing: and then another thing, long enough to pass.") + self.assertReports(validate.check_frontmatter, 'contains ": "') + + def test_quoted_colon_space_passes(self): + self.set_description('"Does a thing: and then another thing, long enough to pass."') + self.assertEqual([], self.errors(validate.check_frontmatter)) + + def test_single_quoted_passes(self): + self.set_description("'Does a thing: and then another, long enough to pass here.'") + self.assertEqual([], self.errors(validate.check_frontmatter)) + + def test_unquoted_plain_without_colon_passes(self): + self.set_description("Does a thing and then another thing, long enough to pass") + self.assertEqual([], self.errors(validate.check_frontmatter)) + + def test_leading_indicator_fails(self): + self.set_description("[stub] does a thing and then another thing, long enough") + self.assertReports(validate.check_frontmatter, "indicator") + + def test_unterminated_quote_fails(self): + self.set_description('"Does a thing and then another thing, long enough to pass') + self.assertReports(validate.check_frontmatter, "unterminated") + + def test_missing_description(self): + path = self.root / SKILL + text = path.read_text(encoding="utf-8") + start = text.index("description:") + end = text.index("\n", start) + path.write_text(text[:start] + text[end + 1:], encoding="utf-8") + self.assertReports(validate.check_frontmatter, "missing description") + + def test_missing_name(self): + self.edit(SKILL, f"name: {NAME}\n", "") + self.assertReports(validate.check_frontmatter, "missing name") + + def test_broken_link(self): + (self.root / SKILL).write_text((self.root / SKILL).read_text(encoding="utf-8") + + "\n[x](missing.md)\n", encoding="utf-8") + self.assertReports(validate.check_links, "broken link") + + def test_valid_link_with_title_passes(self): + path = self.root / "CONTRIBUTING.md" + path.write_text(path.read_text(encoding="utf-8") + '\n[guide](README.md "Guide")\n', + encoding="utf-8") + self.assertEqual([], self.errors(validate.check_links)) + + def test_broken_link_with_title_fails(self): + (self.root / SKILL).write_text((self.root / SKILL).read_text(encoding="utf-8") + + '\n[guide](missing.md "Guide")\n', encoding="utf-8") + self.assertReports(validate.check_links, "broken link missing.md") + + def test_valid_reference_link_passes(self): + path = self.root / "CONTRIBUTING.md" + path.write_text(path.read_text(encoding="utf-8") + "\n[guide][docs]\n\n[docs]: README.md\n", + encoding="utf-8") + self.assertEqual([], self.errors(validate.check_links)) + + def test_broken_reference_link_fails(self): + (self.root / SKILL).write_text((self.root / SKILL).read_text(encoding="utf-8") + + "\n[guide][docs]\n\n[docs]: missing.md\n", encoding="utf-8") + self.assertReports(validate.check_links, "broken link missing.md") + + def test_valid_angle_bracket_link_with_spaces_passes(self): + (self.root / "guide file.md").write_text("# Guide\n", encoding="utf-8") + path = self.root / "CONTRIBUTING.md" + path.write_text(path.read_text(encoding="utf-8") + "\n[guide](<guide file.md>)\n", + encoding="utf-8") + self.assertEqual([], self.errors(validate.check_links)) + + def test_broken_angle_bracket_link_with_spaces_fails(self): + (self.root / SKILL).write_text((self.root / SKILL).read_text(encoding="utf-8") + + "\n[guide](<missing file.md>)\n", encoding="utf-8") + self.assertReports(validate.check_links, "broken link missing file.md") + + +if __name__ == "__main__": + unittest.main()