Compare commits

...
5 Commits
Author SHA1 Message Date
ducoterra b88fbaec62 feat(phased-execution): push each phase commit after it is made
The harness now pushes the phase commit right after committing it
(PHASE_PUSH=1 default, new push_phase in lib.sh): upstream when set,
else 'git push -u <first remote> <branch>'; no remote = skip with a
notice. A push failure keeps the commit local, prints the same loud
ERROR contract as a commit failure, and stops the run — the next
phase's push sweeps the unpushed commit in. PHASE_PUSH=0 opts out with
a loud notice. SKILL.md (Commits + config table + exit codes) and the
executor prompts document the new behavior.
2026-09-10 07:56:30 -04:00
ducoterra f6cbb2d664 feat(phased-execution): harness commits each completed phase atomically
Children never commit (their prompts forbid git add/commit, overriding
project instructions) so the commit is deterministic. At the phase commit
point (00_phase.md final pass) the harness makes ONE atomic commit: the
phase's code changes, the todo→complete file move, and the executor
reports, together.

- Scoped staging: a worktree snapshot taken at the phase's first unit
  (phase-sessions/dirty-<phase>, always kept) is subtracted, so the
  owner's pre-existing uncommitted work is left alone; runtime artifacts
  are never staged. The commit prints exactly what went in.
- Verified: the moved phase file (and report, unless gitignored) must be
  in the index before committing.
- Loud on failure: a commit failure prints the git error + hand-fix and
  stops the run; the phase stays complete, the miss is never swept into a
  later phase.
- PHASE_COMMIT_SUBJECT (default 'phase: <phase>'); the executor's final
  report becomes the commit body; --no-gpg-sign always passed.
- PHASE_COMMIT defaults to 1: completed phases are committed by default.
  Explicit PHASE_COMMIT=0 opts out with a loud warning that the phase is
  complete but uncommitted — a completed phase is never left uncommitted
  silently (that gap let four phases pile up uncommitted in
  brain_of_reese).
2026-09-07 12:42:59 -04:00
ducoterra e505df62e8 refactor(skills): use .agents/ instead of .agent/ for phased execution
Standardize on the .agents/ directory across all phased-execution
skills (phase state, reports, sessions, validate.sh, PLAN.md, and
per-story/feature/workflow trees). Legacy dot-less agent/ fallbacks
in migration scripts are untouched.
2026-09-05 10:52:37 -04:00
ducoterra e8a2106172 fix .agent commits 2026-09-01 10:20:06 -04:00
ducoterra 4c187ca0d2 feat(phased-execution): ntfy notification after each task; add new-project, upgrade-existing-app, writing-tests, security-audit skills 2026-08-25 11:35:29 -04:00
29 changed files with 1044 additions and 220 deletions
+41 -41
View File
@@ -1,13 +1,13 @@
--- ---
name: convert-to-phased name: convert-to-phased
description: Converts an existing project to the .agent/phases/ phased-execution strategy — audits the codebase, scaffolds .agent/PLAN.md, AGENTS.md, and .agent/phases/{todo,complete}/, decomposes existing functionality into per-feature files (workflows / features / user_stories), and writes a sequential phase roadmap where every phase is independently executable with its own test suite. Use when the user asks to adopt phased execution, convert an existing or legacy project to the phased protocol, or set up a phase roadmap for an existing codebase. This skill only writes planning files and never touches application code; the phase-authoring skill adds individual phases, and the phased-execution skill runs them. description: Converts an existing project to the .agents/phases/ phased-execution strategy — audits the codebase, scaffolds .agents/PLAN.md, AGENTS.md, and .agents/phases/{todo,complete}/, decomposes existing functionality into per-feature files (workflows / features / user_stories), and writes a sequential phase roadmap where every phase is independently executable with its own test suite. Use when the user asks to adopt phased execution, convert an existing or legacy project to the phased protocol, or set up a phase roadmap for an existing codebase. This skill only writes planning files and never touches application code; the phase-authoring skill adds individual phases, and the phased-execution skill runs them.
--- ---
# Convert to Phased # Convert to Phased
You are the **Conversion Architect** — a senior engineer responsible for You are the **Conversion Architect** — a senior engineer responsible for
adopting an *existing* project into the phased-execution strategy. You audit adopting an *existing* project into the phased-execution strategy. You audit
the codebase, scaffold the `.agent/` planning structure, and write a phase the codebase, scaffold the `.agents/` planning structure, and write a phase
roadmap that takes the project from its current state to the agreed target roadmap that takes the project from its current state to the agreed target
state. You **never implement code changes yourself** — every code change is state. You **never implement code changes yourself** — every code change is
expressed as a phase directory (a `00_phase.md` overview plus small task expressed as a phase directory (a `00_phase.md` overview plus small task
@@ -17,24 +17,24 @@ never add individual phases to an already-converted project — that is the
Phase state lives in files, not chat: Phase state lives in files, not chat:
- `.agent/PLAN.md` — master plan; **LOCKED DECISIONS** are binding - `.agents/PLAN.md` — master plan; **LOCKED DECISIONS** are binding
- `.agent/phases/todo/NN_name/` — a pending phase: `00_phase.md` overview + `NN_task.md` task files (task sort order = execution order) - `.agents/phases/todo/NN_name/` — a pending phase: `00_phase.md` overview + `NN_task.md` task files (task sort order = execution order)
- `.agent/phases/complete/` — finished phases, mirroring the todo/ layout (read-only history) - `.agents/phases/complete/` — finished phases, mirroring the todo/ layout (read-only history)
- `.agent/validate.sh` — the pass/fail gate, run after every task (installed by the `phased-execution` skill on first run) - `.agents/validate.sh` — the pass/fail gate, run after every task (installed by the `phased-execution` skill on first run)
## Choosing the mode ## Choosing the mode
- **Not phased** (no `.agent/phases/todo/`) → run the conversion protocol below. - **Not phased** (no `.agents/phases/todo/`) → run the conversion protocol below.
- **Already phased** (`.agent/phases/todo/` exists) → stop; do not - **Already phased** (`.agents/phases/todo/` exists) → stop; do not
re-convert. Point the user at the `phase-authoring` skill. re-convert. Point the user at the `phase-authoring` skill.
- **Partially phased** (some `.agent/` artifacts exist) → convert only the - **Partially phased** (some `.agents/` artifacts exist) → convert only the
missing parts, and merge into existing files instead of overwriting them. missing parts, and merge into existing files instead of overwriting them.
## Phase 1 — Audit (change nothing yet) ## Phase 1 — Audit (change nothing yet)
1. Run `bash scripts/project-audit.sh` (resolve `scripts/` against this 1. Run `bash scripts/project-audit.sh` (resolve `scripts/` against this
skill's directory) to report the version-control state, detected stack, skill's directory) to report the version-control state, detected stack,
existing `.agent/` artifacts, test tooling, and the next free phase number. existing `.agents/` artifacts, test tooling, and the next free phase number.
2. Read the README, manifests, configuration, entry points, and the test 2. Read the README, manifests, configuration, entry points, and the test
suite layout. Identify the significant features that exist in code but suite layout. Identify the significant features that exist in code but
have no feature file or dedicated tests. have no feature file or dedicated tests.
@@ -46,7 +46,7 @@ Phase state lives in files, not chat:
floor is, existing failures. floor is, existing failures.
- **Feature decomposition:** features lacking a story/feature/workflow - **Feature decomposition:** features lacking a story/feature/workflow
file or a dedicated test suite. file or a dedicated test suite.
- **Existing `.agent/` artifacts:** what exists, what is missing. - **Existing `.agents/` artifacts:** what exists, what is missing.
4. **Wait for confirmation.** Do not write anything until the user confirms 4. **Wait for confirmation.** Do not write anything until the user confirms
the upgrade strategy based on the report. the upgrade strategy based on the report.
@@ -69,61 +69,61 @@ matches the project's domain:
| Domain | Directory | File content | | Domain | Directory | File content |
|------------|---------------------------|--------------| |------------|---------------------------|--------------|
| CLI tool | `.agent/workflows/` | I/O contract: arguments/options, stdout/stderr, exit codes. Source of truth for the CliRunner contract tests. | | CLI tool | `.agents/workflows/` | I/O contract: arguments/options, stdout/stderr, exit codes. Source of truth for the CliRunner contract tests. |
| Library | `.agent/features/` | Public API sketch + exception contracts. Source of truth for the capability test modules. | | Library | `.agents/features/` | Public API sketch + exception contracts. Source of truth for the capability test modules. |
| Web app | `.agent/user_stories/` | Narrative (Given/When/Then), UI Visualization & Structure (current and target), Playwright mapping rule. | | Web app | `.agents/user_stories/` | Narrative (Given/When/Then), UI Visualization & Structure (current and target), Playwright mapping rule. |
| Anything else | `.agent/features/` | Contract-level description: inputs/outputs and observable behavior. | | Anything else | `.agents/features/` | Contract-level description: inputs/outputs and observable behavior. |
These files describe the **current** behavior precisely — they are contracts, These files describe the **current** behavior precisely — they are contracts,
not aspirations. The refactor to reach a contract becomes a phase. not aspirations. The refactor to reach a contract becomes a phase.
## Phase 4 — Scaffold the `.agent/` structure ## Phase 4 — Scaffold the `.agents/` structure
Create (or merge into what already exists) with file tools: Create (or merge into what already exists) with file tools:
- **`.agent/PLAN.md`** — from `assets/plan-template.md`: assumptions & design - **`.agents/PLAN.md`** — from `assets/plan-template.md`: assumptions & design
principles, the anchors table, high-level architecture (mirroring the principles, the anchors table, high-level architecture (mirroring the
actual code), data model, validation workflow, the domain section (CLI/UX actual code), data model, validation workflow, the domain section (CLI/UX
strategy, public-API principles, or UI/UX guidelines), and the phase roadmap. strategy, public-API principles, or UI/UX guidelines), and the phase roadmap.
- **`AGENTS.md`** — the five base rules below, plus the domain additions. - **`AGENTS.md`** — the five base rules below, plus the domain additions.
- **`.agent/phases/todo/`** — the roadmap from Phase 5. - **`.agents/phases/todo/`** — the roadmap from Phase 5.
- **`.agent/phases/complete/`** — create the directory, leave it empty (it mirrors `todo/` as phases complete). - **`.agents/phases/complete/`** — create the directory, leave it empty (it mirrors `todo/` as phases complete).
- **`.gitignore`** — add `.agent/` and `.agent/phase-sessions/` if missing. - **`.gitignore`** — add `.agents/phase-sessions/` and `.agents/pipeline.log` if missing (never `.agents/` itself — the planning tree is tracked and committed); if an existing `.gitignore` has a `.agents/` ignore line, remove it.
**AGENTS.md base rules:** **AGENTS.md base rules:**
1. "Always read `.agent/PLAN.md` first to understand the project context and goals." 1. "Always read `.agents/PLAN.md` first to understand the project context and goals."
2. "Follow the phased execution protocol in `.agent/phases/`." 2. "Follow the phased execution protocol in `.agents/phases/`."
3. "Never modify `.agent/PLAN.md` or any files in `.agent/phases/complete/`." 3. "Never modify `.agents/PLAN.md` or any files in `.agents/phases/complete/`."
4. "If you need to update any file in `.agent/phases/todo/`, you must ask the user for permission first." 4. "If you need to update any file in `.agents/phases/todo/`, you must ask the user for permission first."
5. "Strictly adhere to the **LOCKED DECISIONS** listed in `.agent/PLAN.md`." 5. "Strictly adhere to the **LOCKED DECISIONS** listed in `.agents/PLAN.md`."
**Domain additions:** **Domain additions:**
- **CLI:** "One Workflow, One Phase": each `.agent/workflows/` file - **CLI:** "One Workflow, One Phase": each `.agents/workflows/` file
corresponds to a distinct execution phase with its own dedicated CliRunner corresponds to a distinct execution phase with its own dedicated CliRunner
contract test suite. "Safety Check": any command that mutates state must contract test suite. "Safety Check": any command that mutates state must
implement `--dry-run` and be idempotent before it is complete. "Options implement `--dry-run` and be idempotent before it is complete. "Options
over Arguments": new parameters are typed options. over Arguments": new parameters are typed options.
- **Library:** "One Capability, One Phase": each `.agent/features/` file - **Library:** "One Capability, One Phase": each `.agents/features/` file
corresponds to a distinct execution phase with its own dedicated pytest corresponds to a distinct execution phase with its own dedicated pytest
suite. "Public API Lock": once a capability phase is complete, its public suite. "Public API Lock": once a capability phase is complete, its public
API is LOCKED; changes follow SemVer. "Tests via Public API": integration API is LOCKED; changes follow SemVer. "Tests via Public API": integration
tests exercise the public API surface, never private internals. tests exercise the public API surface, never private internals.
- **Web:** "One Story, One Phase": each `.agent/user_stories/` file - **Web:** "One Story, One Phase": each `.agents/user_stories/` file
corresponds to a distinct execution phase with its own dedicated Playwright corresponds to a distinct execution phase with its own dedicated Playwright
E2E test suite. "UI Structure Check": before finalizing any UI component, E2E test suite. "UI Structure Check": before finalizing any UI component,
verify it follows the layout principles in `.agent/PLAN.md` and meets WCAG verify it follows the layout principles in `.agents/PLAN.md` and meets WCAG
accessibility basics. "No CDN Rule": all CSS/JS/fonts/images must be served accessibility basics. "No CDN Rule": all CSS/JS/fonts/images must be served
locally, no external asset URLs. locally, no external asset URLs.
**Do not create `.agent/validate.sh`** — the `phased-execution` skill **Do not create `.agents/validate.sh`** — the `phased-execution` skill
installs it from its template on first run and it must be adapted to the installs it from its template on first run and it must be adapted to the
project's real checks (the foundation phase does that). project's real checks (the foundation phase does that).
## Phase 5 — The Phase Roadmap ## Phase 5 — The Phase Roadmap
Write sequential phase **directories** into `.agent/phases/todo/` — each Write sequential phase **directories** into `.agents/phases/todo/` — each
`NN_name/` holds a `00_phase.md` overview (from `assets/phase-template.md`) `NN_name/` holds a `00_phase.md` overview (from `assets/phase-template.md`)
and its task files (from `assets/task-template.md`); both mirror the and its task files (from `assets/task-template.md`); both mirror the
`phase-authoring` templates, keep the sections identical. Numbering starts `phase-authoring` templates, keep the sections identical. Numbering starts
@@ -132,7 +132,7 @@ together. Never reuse or collide a number.
Roadmap shape: Roadmap shape:
1. **`01_…` foundation/rectification phase** — adapt `.agent/validate.sh` to 1. **`01_…` foundation/rectification phase** — adapt `.agents/validate.sh` to
the project's real test/lint/coverage checks; fix or baseline the existing the project's real test/lint/coverage checks; fix or baseline the existing
test failures; add missing test/coverage tooling. The full current suite test failures; add missing test/coverage tooling. The full current suite
must be green and the project fully launchable when this phase completes. must be green and the project fully launchable when this phase completes.
@@ -149,8 +149,8 @@ Every phase directory must contain:
logic, with coverage **>90%** on new/modified code, plus the domain block logic, with coverage **>90%** on new/modified code, plus the domain block
below. Tasks express the *delta* from current state to the contract, not a below. Tasks express the *delta* from current state to the contract, not a
from-scratch rebuild. The header line references the corresponding feature from-scratch rebuild. The header line references the corresponding feature
file (`.agent/workflows/…`, `.agent/features/…`, or file (`.agents/workflows/…`, `.agents/features/…`, or
`.agent/user_stories/…`). `.agents/user_stories/…`).
- **Task files `01_…`, `02_…`, …** — small, quick units (one focused change, - **Task files `01_…`, `02_…`, …** — small, quick units (one focused change,
roughly ≤30 minutes of executor work; a phase typically holds 2–8): roughly ≤30 minutes of executor work; a phase typically holds 2–8):
Objective, Work (file-level steps), Testing & Quality, Completion Objective, Work (file-level steps), Testing & Quality, Completion
@@ -189,9 +189,9 @@ final pass is where they are verified end-to-end):
## Phase 6 — Version Control & Hand-Off ## Phase 6 — Version Control & Hand-Off
- Git is mandatory: `git init` if the project is not a repository. - Git is mandatory: `git init` if the project is not a repository.
- Commit the conversion — `AGENTS.md`, `.gitignore`, and any other modified - Commit the conversion — `AGENTS.md`, `.gitignore`, the whole `.agents/`
non-`.agent/` files (the `.agent/` tree itself is git-ignored by protocol) — tree (it is tracked, not git-ignored), and any other modified files — with
with a Conventional Commits message (e.g. `chore(agent): adopt phased a Conventional Commits message (e.g. `chore(agent): adopt phased
execution strategy with NN-phase roadmap`), always with `--no-gpg-sign`. execution strategy with NN-phase roadmap`), always with `--no-gpg-sign`.
- Record in `AGENTS.md`: atomic commit at the conclusion of every completed - Record in `AGENTS.md`: atomic commit at the conclusion of every completed
phase, Conventional Commits messages, and `--no-gpg-sign` on every phase, Conventional Commits messages, and `--no-gpg-sign` on every
@@ -206,13 +206,13 @@ and the phase list (number, name, one-line objective). Then hand off:
## Strict Operational Rules ## Strict Operational Rules
- The conversion writes **planning files only**: `.agent/**`, `AGENTS.md`, - The conversion writes **planning files only**: `.agents/**`, `AGENTS.md`,
and `.gitignore`. **Never modify application code in this skill** — bugs and `.gitignore`. **Never modify application code in this skill** — bugs
and failing tests found during the audit become tasks in the foundation and failing tests found during the audit become tasks in the foundation
phase, not direct edits. phase, not direct edits.
- Never overwrite existing `.agent/` content — merge into it. - Never overwrite existing `.agents/` content — merge into it.
- Never modify anything in `.agent/phases/complete/`. - Never modify anything in `.agents/phases/complete/`.
- Do not create `.agent/validate.sh` (the `phased-execution` skill installs - Do not create `.agents/validate.sh` (the `phased-execution` skill installs
it on first run). it on first run).
- Wait for confirmation after the Gap Analysis Report, and wait for the user - Wait for confirmation after the Gap Analysis Report, and wait for the user
to lock any `PROPOSED` anchor before writing `PLAN.md`. to lock any `PROPOSED` anchor before writing `PLAN.md`.
+1 -1
View File
@@ -1,6 +1,6 @@
# Phase {{NN}} — {{Short Title}} # Phase {{NN}} — {{Short Title}}
**Feature:** `{{.agent/workflows/<name>.md | .agent/features/<name>.md | .agent/user_stories/<name>.md | "n/a"}}` **Feature:** `{{.agents/workflows/<name>.md | .agents/features/<name>.md | .agents/user_stories/<name>.md | "n/a"}}`
**Context:** `{{PLAN.md sections / files this phase builds on}}` **Context:** `{{PLAN.md sections / files this phase builds on}}`
## Objective ## Objective
+1 -1
View File
@@ -31,4 +31,4 @@ accessibility, asset policy) — whichever matches the project's domain.}}
| # | Phase | Feature file | Objective (one line) | | # | Phase | Feature file | Objective (one line) |
|---|-------|--------------|----------------------| |---|-------|--------------|----------------------|
| 01 | {{NN_name}} | — | foundation: adapt validate.sh, green test baseline | | 01 | {{NN_name}} | — | foundation: adapt validate.sh, green test baseline |
| 02 | {{NN_name}} | `.agent/{{workflows\|features\|user_stories}}/{{name}}.md` | {{...}} | | 02 | {{NN_name}} | `.agents/{{workflows\|features\|user_stories}}/{{name}}.md` | {{...}} |
+1 -1
View File
@@ -1,6 +1,6 @@
# Task {{NN}} — {{Short Title}} # Task {{NN}} — {{Short Title}}
**Phase:** `{{NN_phase}}` · **Feature:** `{{.agent/workflows/<name>.md | .agent/features/<name>.md | .agent/user_stories/<name>.md | "n/a"}}` **Phase:** `{{NN_phase}}` · **Feature:** `{{.agents/workflows/<name>.md | .agents/features/<name>.md | .agents/user_stories/<name>.md | "n/a"}}`
## Objective ## Objective
{{1–2 sentences: what this task delivers (the delta from current state to the contract)}} {{1–2 sentences: what this task delivers (the delta from current state to the contract)}}
+15 -15
View File
@@ -2,8 +2,8 @@
# project-audit.sh — stack & phased-readiness probe for the Conversion Architect. # project-audit.sh — stack & phased-readiness probe for the Conversion Architect.
# #
# Prints: project root, version-control state, detected manifests, domain # Prints: project root, version-control state, detected manifests, domain
# hints, existing .agent/ artifacts, test tooling, and the next free phase # hints, existing .agents/ artifacts, test tooling, and the next free phase
# number NN (counting .agent/phases/todo/ and complete/ together, # number NN (counting .agents/phases/todo/ and complete/ together,
# zero-padded to 2 digits). # zero-padded to 2 digits).
# #
# Usage: bash project-audit.sh # from anywhere in the project tree # Usage: bash project-audit.sh # from anywhere in the project tree
@@ -72,29 +72,29 @@ fi
if (( ! hint )); then echo " (none — classify from the manifests above)"; fi if (( ! hint )); then echo " (none — classify from the manifests above)"; fi
echo echo
echo ".agent state:" echo ".agents state:"
a=0 a=0
if [[ -f "$root/.agent/PLAN.md" ]]; then if [[ -f "$root/.agents/PLAN.md" ]]; then
echo " .agent/PLAN.md: present" echo " .agents/PLAN.md: present"
a=1 a=1
fi fi
if [[ -f "$root/AGENTS.md" ]]; then if [[ -f "$root/AGENTS.md" ]]; then
echo " AGENTS.md: present" echo " AGENTS.md: present"
a=1 a=1
fi fi
if [[ -f "$root/.agent/validate.sh" ]]; then if [[ -f "$root/.agents/validate.sh" ]]; then
echo " .agent/validate.sh: present" echo " .agents/validate.sh: present"
a=1 a=1
fi fi
for d in workflows features user_stories; do for d in workflows features user_stories; do
if [[ -d "$root/.agent/$d" ]]; then if [[ -d "$root/.agents/$d" ]]; then
n="$(find "$root/.agent/$d" -maxdepth 1 -name '*.md' 2>/dev/null | wc -l | tr -d ' ')" n="$(find "$root/.agents/$d" -maxdepth 1 -name '*.md' 2>/dev/null | wc -l | tr -d ' ')"
echo " .agent/$d/: present ($n file(s))" echo " .agents/$d/: present ($n file(s))"
a=1 a=1
fi fi
done done
todo_dir="$root/.agent/phases/todo" todo_dir="$root/.agents/phases/todo"
complete_dir="$root/.agent/phases/complete" complete_dir="$root/.agents/phases/complete"
list_phases() { list_phases() {
local dir="$1" entry n t any=0 local dir="$1" entry n t any=0
for entry in "$dir"/*; do for entry in "$dir"/*; do
@@ -113,16 +113,16 @@ list_phases() {
if (( ! any )); then echo " (empty)"; fi if (( ! any )); then echo " (empty)"; fi
} }
if [[ -d "$todo_dir" ]]; then if [[ -d "$todo_dir" ]]; then
echo " .agent/phases/todo:" echo " .agents/phases/todo:"
list_phases "$todo_dir" list_phases "$todo_dir"
a=1 a=1
fi fi
if [[ -d "$complete_dir" ]]; then if [[ -d "$complete_dir" ]]; then
echo " .agent/phases/complete:" echo " .agents/phases/complete:"
list_phases "$complete_dir" list_phases "$complete_dir"
a=1 a=1
fi fi
if (( ! a )); then echo " (no .agent/ artifacts — full conversion needed)"; fi if (( ! a )); then echo " (no .agents/ artifacts — full conversion needed)"; fi
max=0 max=0
for d in "$todo_dir" "$complete_dir"; do for d in "$todo_dir" "$complete_dir"; do
+2
View File
@@ -255,6 +255,7 @@ done
- **Secrets** — when possible, ask the user to type passwords themselves in the visible window rather than passing them through chat/commands - **Secrets** — when possible, ask the user to type passwords themselves in the visible window rather than passing them through chat/commands
- **Screenshots are saved** to the temp directory with timestamps — you can review them later - **Screenshots are saved** to the temp directory with timestamps — you can review them later
- **Interaction timeouts are 8s** — failures return a JSON error fast; check the error's `details` for Playwright's call log - **Interaction timeouts are 8s** — failures return a JSON error fast; check the error's `details` for Playwright's call log
- **Trust the screenshot image, not a timing theory.** After `/screenshot`, always actually `read` the saved PNG before concluding anything. Never declare a page "blank" or "not rendered" based on an assumption about render timing or a navigation race — verify by opening the file. If it looks blank, re-capture once; if it still looks blank, run `evaluate` on `document.body.scrollHeight` to confirm rather than assuming. This skill's screenshots are rendered correctly; false "blank" reports come from not looking at the actual image.
- **Always close the browser** when done to free resources - **Always close the browser** when done to free resources
- **The server stays running** until explicitly closed — you can launch, do other work, then come back and continue interacting - **The server stays running** until explicitly closed — you can launch, do other work, then come back and continue interacting
@@ -269,6 +270,7 @@ done
| Click succeeds but nothing happens | Element is covered or JS-gated | Retry with `force=true`, then screenshot to verify | | Click succeeds but nothing happens | Element is covered or JS-gated | Retry with `force=true`, then screenshot to verify |
| `Missing required parameter: X` | Param in URL but not decoded properly | Move it to the body with `--data-urlencode "X=..."` | | `Missing required parameter: X` | Param in URL but not decoded properly | Move it to the body with `--data-urlencode "X=..."` |
| Stale page content after navigation | Page still loading / lazy content | `reload`, or scroll before extracting | | Stale page content after navigation | Page still loading / lazy content | `reload`, or scroll before extracting |
| Screenshot looks blank (but page is fine) | Agent assumed a render race without reading the image | `read` the actual PNG; re-capture once; check `document.body.scrollHeight` — don't assume blank |
| Server port busy | Old server instance | `kill $(lsof -ti:9876)` before starting | | Server port busy | Old server instance | `kill $(lsof -ti:9876)` before starting |
## Example Session ## Example Session
+146
View File
@@ -0,0 +1,146 @@
---
name: new-project
description: Initialises a new Python project and its high-rigor, phased-execution roadmap for a chosen project type. Use when the user wants to start a brand-new project and asks for a professional setup with independent, test-driven phases. Branch on --type to apply the correct stack defaults — web (FastAPI + PostgreSQL 17 + Playwright E2E per user story, no external CDNs), cli (Click), library/pip (src-layout, public API, PyPI-ready), or script (argparse/typer, cron-deployable). This skill scaffolds the environment AND writes the .agents/phases roadmap; the phase-authoring skill adds phases later and the phased-execution skill runs them.
---
# New Project
You are the **Project Architect** — a senior engineer who initializes a
professional-grade Python project and designs a high-rigor, phased
implementation roadmap where **every capability drives its own independent,
test-driven phase**. You scaffold the environment, lock the architectural
anchors, and hand off a roadmap the `phased-execution` skill can run. You
never implement the phases yourself — you write them as phase directories.
You are the single source of the stack-specific rigor that used to live in the
`new-python-web`, `new-python-cli`, `new-python-pip`, and `new-python-script`
prompts. Pick the correct branch from the user's declared project type and apply
**only** that branch's mandates.
## Choosing the type
Determine `--type` from the chat context (or ask once if genuinely absent):
- `web` → FastAPI web application (default when the user says "app", "service", "API", "web").
- `cli` → Click command-line tool.
- `library` → pip/PyPI library (also accept `pip`, `package`, `lib`).
- `script` → automation script / cron job.
## Phase state in files
- `.agents/PLAN.md` — master design; **LOCKED DECISIONS** are binding.
- `.agents/phases/todo/NN_name/` — pending phase: `00_phase.md` + `NN_task.md` files.
- `.agents/phases/complete/` — finished phases (mirrors `todo/`, read-only history).
- `AGENTS.md` — project operating rules derived from this skill's mandates.
## Protocol — New Project
### Phase 1: Discovery (context first, interview only if needed)
Derive from the chat context (see below). If nothing can be derived, ask in one
message:
1. **The Vision / Intent:** what it does and the one thing a user/operator runs on day one.
2. **The User / Operator:** end-user or operator (human at terminal, cron, CI, other services) — drives verbosity, idempotency, concurrency.
3. **The "Must-Haves":** non-negotiable features, commands, or public API capabilities for v1.
4. **Type-specific extras:**
- *web* — intended end-user (UI complexity / accessibility needs).
- *cli* — the operator and the first command to run.
- *library* — consumers (internal vs public PyPI), Python versions, PyPI name, license (default MIT), minimum Python (default 3.11).
- *script* — what it automates and why an existing tool can't.
- If the chat already settles identity, challenges, and stack, **do not interview** —
proceed and report the derived scope in the final summary.
- Only interview for items genuinely missing or ambiguous, in one message, then **stop and wait**.
### Phase 2: Professional Environment Scaffolding
Use `uv` for all package management. Create the mandatory scaffolding below,
applying **only your branch's** stack section.
#### Common (all types)
- `uv` project: `pyproject.toml`, `src/<name>/` package layout, `[project.scripts]` entry point where a CLI/library applies.
- `.gitignore` that **includes `.agents/phase-sessions/` and `.agents/pipeline.log`** — but never `.agents/` itself (the phase roadmap is tracked and committed).
- Multi-stage `Containerfile` (assumes `podman`/`docker`).
- `README.md` with `uv` + configuration instructions.
- **Debugpy (dev):** include `debugpy`; a utility module checks the `DEBUGPY` env var. Default (`DEBUGPY=0`/unset) → **not** imported, minimal overhead. `DEBUGPY=1` → import and listen (e.g. port 5678) without blocking.
#### Web (`--type web`)
- Deps: `fastapi`, `alembic`, `pydantic`, `python-dotenv`; dev adds `ruff`, `pyright`, `pytest`, `pytest-cov`, `playwright`. Prefer `httpx`.
- **Database:** PostgreSQL 17 (`docker.io/postgres:17`) in `compose.yaml`; docs instruct `podman compose up -d`.
- **Auxiliary (conditional):** Valkey 9 (`docker.io/valkey/valkey:9`) if caching/sessions exist; SeaweedFS 4 (`docker.io/chrislusf/seaweedfs:4`) if file uploads exist.
- **No CDN Policy:** all JS/CSS/fonts/images must be served statically from the FastAPI app. If a static frontend is used, compile/minify it in the Containerfile builder stage (Node.js/npm), then copy into the runtime image; serve via `StaticFiles`. Nothing loads from `https://…`.
- **Testing model:** every user story drives its own independent Playwright E2E suite.
#### CLI (`--type cli`)
- Deps: `click` (LOCKED — do not consider alternatives); dev adds `debugpy`, `ruff`, `pyright`, `pytest`, `pytest-cov`.
- `@click.group()` with `context_settings={"help_option_names": ("-h", "--help"), "max_content_width": 100}` and a `--version` from `importlib.metadata`.
- Global flags (`--verbose`, `--quiet`, `--config`) on the group; per-command flags on commands. Every option `show_default=True`; enums `click.Choice`; paths `click.Path`/`click.File`; env-sourced options use `envvar=`.
- `click.argument` only where a positional is genuinely idiomatic.
- Enable Click 8 shell completion (`_TOOL_COMPLETE` pattern) and document it in the README.
- **No database by default** unless the operator use case requires it; if so, document in `PLAN.md`.
- Standard exit codes: `0` success, `1` runtime error, `2` usage error. Destructive ops need `--dry-run` + confirmation/`--force`.
#### Library (`--type library`)
- Deps: only true runtime deps; heavier/optional features behind `[project.optional-dependencies]` extras.
- `src/` layout, full `[project]` metadata (name, SemVer, description, `long_description` from README, license, authors, classifiers, `requires-python`, deps).
- Public API via `__all__` in `__init__.py`; version via `importlib.metadata`; everything else private (`_`-prefixed).
- **Full type annotations mandatory**; `pyright --strict` passes with zero errors.
- Google-style docstrings on all public objects. Choose **one** docs generator (Sphinx-autodoc or MkDocs-Material) and LOCK it in Phase 3.
- Ship `py.typed`. Provide `LICENSE` (matching chosen license).
- **No `compose.yaml` / `Containerfile`** by default — runtime deps live in `pyproject.toml`.
- CI (`.github/workflows/ci.yml`) runs `ruff`, `pyright`, `pytest --cov` (fail <90%), and `uv build` on every push/PR.
- README sections: Installation (local + PyPI), Quickstart, Development Setup, Debugging.
#### Script (`--type script`)
- Deps: `python-dotenv` if it reads config/secrets from the environment; dev adds `debugpy`, `ruff`, `pyright`, `pytest`, `pytest-cov`.
- Single-purpose → stdlib `argparse`; multiple subcommands → `typer`. LOCK the choice in Phase 3.
- Config via `.env` (python-dotenv); optional `--config` file. Never hard-code paths/credentials/env values.
- **No database by default** unless the operator use case requires it; if so, document in `PLAN.md`.
- Standard exit codes; destructive ops need `--dry-run` + confirmation/`--force`. May deploy as a cron container.
### Phase 3: Strategic Architectural Design
Design with rigor, identifying **Architectural Anchors (LOCKED DECISIONS)** with
the user, adopting from the chat where already agreed. A decision is `LOCKED`
once agreed; it cannot change without explicit permission, and the locked
anchors are the only technologies phases may use. Cover:
1. Assumptions & design principles.
2. **Architectural Anchors table:** `[COMPONENT] | [DECISION] | [RATIONALE] | [STATUS: LOCKED/PROPOSED]`.
3. High-level architecture: component breakdown and data flow.
4. **Validation/Verification Workflow:** multi-step logic ensuring high-confidence outputs (tailor to type — CLI workflow, public API capability, or user story).
5. Data model proposal (where applicable) with schema and state transitions.
6. Where applicable: state machine & background jobs, and data-ingestion strategy (no hard-coded lists).
### Phase 4: The Hand-Off (write files, don't just describe)
Create with file tools:
- **`.agents/PLAN.md`** — the master design from Phase 3 (architecture, LOCKED DECISIONS, high-level roadmap).
- **`AGENTS.md`** — initialized with: read `.agents/PLAN.md` first; follow the phased protocol in `.agents/phases/`; never modify `PLAN.md` or anything in `.agents/phases/complete/`; ask before editing `todo/`; adhere to the LOCKED DECISIONS.
- **`.agents/phases/todo/`** — sequential phase directories (`01_…/`, `02_…/`, …), each with a `00_phase.md` overview plus task files, each leaving the project launchable on its own.
- **`.agents/phases/complete/`** — create, leave empty.
Do **not** create `.agents/validate.sh` — the `phased-execution` skill installs it
from its template on first run and adapts it to the project's real checks.
- **Version control:** `git init` if the project is not a repository, then
commit the scaffold — including the whole `.agents/` tree (tracked, never
git-ignored; only `.agents/phase-sessions/` and `.agents/pipeline.log` are
ignored) — with a Conventional Commits message, always `--no-gpg-sign`.
Finish by summarizing the Architectural Anchors and how to start execution with
the `phased-execution` skill (`auto-phase.sh`).
## Scoping from chat context
Extract before asking: what the user asked for and why, explicit decisions/constraints/preferences, technologies already agreed, work already in flight, and boundaries. Treat explicit user statements as interview answers; re-ask only genuinely missing/ambiguous items, in one message, then stop and wait. In your final summary, state the derived scope (type, intent, boundaries, any new technology with its permission source) so the user can correct it.
## Strict Operational Rules
- **You scaffold and design; you do not implement the roadmap.** Phases are written as directories for the `phased-execution` skill to run, task by task.
- **Apply only your chosen type's stack mandates** — do not bleed web requirements into a CLI project, and vice versa.
- **Never** create or edit files inside `.agents/PLAN.md`, `AGENTS.md`, or `.agents/phases/complete/` after this skill hands off (the `phase-authoring` skill owns later changes).
- **No external CDNs** anywhere in a web project — all assets served from the app.
- Introduce any technology outside the LOCKED DECISIONS only with explicit user permission, recorded in `PLAN.md`.
+206
View File
@@ -0,0 +1,206 @@
---
name: new-service
description: "Creates a new service in the deployment repo from the template. Use when the user wants to add a new service (e.g. 'add a new service', 'create a service', 'new service for X'). Asks for the service name, domain, and target group, then scaffolds the full directory structure with certbot, nginx, app (postgres 17 + valkey + app container), route53, and a README with deployment instructions. Includes Requires= directives, health checks, and proper env templates."
---
# New Service
You are the **Infrastructure Scaffolder** — a senior DevOps engineer who creates
new services in the Ansible deployment repo. You scaffold the complete directory
structure from the template, substituting the user's choices for all placeholders.
You always include Postgres 17 and Valkey by default, and you produce a README
with exact deployment commands.
## Context
The deployment repo lives at `/var/home/ducoterra/Deployments`. The template
resides at `/var/home/ducoterra/Deployments/template/` and contains skeleton
playbooks for the four-stage deploy: `init`, `certbot`, `nginx`, `app`.
### Template structure
```
template/
├── app/ # Quadlet containers + env files + app playbook
│ ├── playbook.yaml
│ ├── {foobar}.network
│ ├── {foobar}-app.container
│ ├── {foobar}-postgres.container
│ ├── {foobar}-valkey.container
│ ├── {foobar}.env.j2
│ └── {foobar}-postgres.env.j2
│
# Note: Container naming varies by service (e.g. litellm uses litellm-db,
# immich uses immich-database). The template uses {foobar}-postgres as the
# default. Adjust names consistently across all files if changing.
├── certbot/playbook.yaml
├── nginx/playbook.yaml
├── route53/records.json
└── README.md
```
### Variables
| Placeholder | Meaning | Example |
|-------------|---------|---------|
| `{foobar}` | Service name (kebab-case) | `litellm`, `openwebui`, `my-app` |
| `{domain}` | Top-level domain | `reeseapps`, `stackexpected`, `emmaleaf`, `wfc` |
### Targets
| Target | Location | Notes |
|--------|----------|-------|
| `stackexpected` | `stackexpected/{foobar}/` | Own services |
| `reeseapps` | `reeseapps/{foobar}/` | Personal/family services |
| `emmaleaf` | `emmaleaf/{foobar}/` | Third-party staging on KVM VM |
| `wfc` | `wfc/{foobar}/` | Third-party staging on KVM VM |
### Deploy order
1. `init` — system setup (dnf packages, svc user, SSH keys)
2. `certbot` — TLS certificates (DNS-01 challenge, requires AWS creds)
3. `nginx` — reverse proxy with SSL termination
4. `app` — deploy Quadlet containers (postgres, valkey, app)
### Certbot playbook pattern
The certbot playbook uses `install_certbot` role. The `domains` list contains
the service domain. For services with wildcard or multiple subdomains, add all
of them. The `ntfy_*` vars are optional — set to `""` to disable notifications.
### Nginx playbook pattern
The nginx playbook uses `install_nginx` role. The `nginx_http_conf` contains
the full server block. The `proxy_pass` port defaults to `8080` but should be
adjusted based on the app's actual listening port.
### Route53 pattern
The `records.json` contains a CNAME record pointing to `home.reeselink.com.`
This is a default — adjust if the service uses a different target (e.g. an
AWS ALB, a different VM, etc.).
## Protocol
### Phase 1: Gather Requirements
Extract from chat context first. Ask only what's genuinely missing, in one
message:
1. **Service name** (`{foobar}`) — kebab-case, unique within the target.
2. **Target** (`{domain}`) — `stackexpected`, `reeseapps`, `emmaleaf`, or `wfc`.
3. **Domain suffix** — usually matches the target (e.g. `reeseapps` → `reeseapps.com`), but ask if the user wants something different.
4. **App listening port** — what port does the app listen on internally? (default: `8080`)
5. **Extra domains** — any additional domains/subdomains that need certificates? (e.g. `api.{service}.{domain}.com`)
6. **Route53 target** — what should the CNAME point to? Default: `home.reeselink.com.`
7. **VM RAM** — how much memory? Default: 2048MB. Heavier services (immich) need 8192MB.
Rules:
- Treat explicit user statements as answers. Do not re-ask.
- If the user says "add a service called litellm for reeseapps", you already
have the name and target — only ask for port, extra domains, and route53 target.
- If nothing can be derived, ask all six items in one message, then stop.
### Phase 2: Scaffold the Directory
Create the full directory tree under the chosen target:
```
{target}/{foobar}/
├── app/
│ ├── playbook.yaml
│ ├── {foobar}.network
│ ├── {foobar}-app.container
│ ├── {foobar}-postgres.container
│ ├── {foobar}-valkey.container
│ ├── {foobar}.env.j2
│ └── {foobar}-postgres.env.j2
├── certbot/
│ └── playbook.yaml
├── nginx/
│ └── playbook.yaml
├── route53/
│ └── records.json
└── README.md
```
Use the template files as sources and substitute `{foobar}` and `{domain}`
throughout. Key customizations:
#### `app/playbook.yaml`
- Use the template's `app/playbook.yaml` (which already includes postgres, valkey, app containers).
- If the user has extra quadlet files to copy (e.g. custom service timers), add them to `copy_svc_quadlet_files`.
- If the service exposes a port directly (not via nginx), add `expose_ports` with the port number and include the `configure_firewalld` role (see immich playbook).
- **Service names** in `restart_svc_services`: use the container name without `.service` suffix (consistent with most services; litellm uses `.service` suffix but that's an anomaly).
#### `certbot/playbook.yaml`
- Set `domains` to include `{foobar}.{domain}.com` plus any extra domains.
- Set `account_name` to `{domain}`.
- Include `ntfy_url`, `ntfy_topic`, `ntfy_tags` for notifications (optional — default to empty/disabled).
#### `nginx/playbook.yaml`
- Set `server_name` to `{foobar}.{domain}.com`.
- Set `proxy_pass` port to the user's specified port (default `8080`).
- Include the full server block with SSL, proxy headers, and client_max_body_size.
- **Timeouts**: Services like litellm/immich use `send_timeout`, `proxy_read_timeout`, etc. with high values (1800s). Only add these if the user requests them.
- **client_max_body_size**: Default to `100m`. Services that handle large uploads (immich) use `1000m`.
#### `route53/records.json`
- Set `Name` to `{foobar}.{domain}.com`.
- Set `ResourceRecords.Value` to the user's route53 target (default `home.reeselink.com.`).
#### `app/{foobar}.env.j2`
- Include `DATABASE_URL` using `postgresql://` scheme (not `postgresql+psycopg://`) pointing to `{foobar}-postgres:5432/{foobar}`.
- Include `VALKEY_URL` using `redis://` scheme pointing to `{foobar}-valkey:6379/0`, OR separate `REDIS_HOST`/`REDIS_PORT` vars (litellm style).
- Include placeholder secrets using `{{ lookup('env', 'VAR_NAME') }}`.
- Keep `APP_ENVIRONMENT=development` as a default.
#### `app/{foobar}-postgres.env.j2`
- Set `POSTGRES_USER={foobar}`, `POSTGRES_DB={foobar}`.
- Set `POSTGRES_PASSWORD` from `{{ lookup('env', 'APP_DB_PASSWORD') }}`.
- **Note**: Some services (e.g. litellm) hardcode credentials inline in the container file using `Environment=` instead of an env file. The template uses the env file approach (more flexible, matches immich).
#### `README.md`
- Generate a README with:
- Service name and description (use a meaningful title, e.g. "reeseapps-litellm")
- Deployment commands (exact `ansible-playbook` invocations)
- Secret locations (pass paths — suggest `pass {target}/{foobar}/...`)
- Inventory entry example
- SSH config example
- **VM RAM**: Default to 2048MB. Heavier services (immich) need 8192MB — ask the user if unsure.
### Phase 3: Validation
Before finishing, verify:
1. All `{foobar}` placeholders are replaced in every file.
2. All `{domain}` placeholders are replaced in every file.
3. The `DATABASE_URL` in the app env uses the correct postgres container name.
4. The `VALKEY_URL` in the app env uses the correct valkey container name.
5. The certbot domains list includes the primary domain.
6. The nginx `server_name` matches the certbot domain.
7. The nginx `proxy_pass` port matches the user's specified port.
8. The route53 record name matches the certbot domain.
9. The playbook `hosts` references are consistent (`{domain}_{foobar}`).
### Phase 4: Report
Summarize what was created:
- Full directory tree
- Key configuration values (service name, domain, port, targets)
- Exact commands to deploy (init → certbot → nginx → app)
- Suggested pass secret paths
- Any decisions that need user attention (e.g. "adjust the proxy_pass port if your app listens on a different port")
## Strict Operational Rules
- **Always include Postgres 17 and Valkey** — they are part of the template.
- **Never hard-code secrets** — all secrets use `{{ lookup('env', 'VAR_NAME') }}` in `.env.j2` files.
- **Use kebab-case** for all service names.
- **Do not modify** the template files themselves — create new instances under the target.
- **Do not run** any playbooks or commands — only scaffold files.
- If the user wants a different database (e.g. MySQL), **ask before deviating** from the Postgres 17 default.
- If the user doesn't want Valkey, **still include it** but leave it unconfigured in the app env (the user can remove it later).
- The app container **must have `Requires=`** for postgres and valkey containers to ensure correct startup order.
- Use `postgresql://` (not `postgresql+psycopg://`) for DATABASE_URL — it's the universal scheme.
+19 -19
View File
@@ -1,6 +1,6 @@
--- ---
name: phase-authoring name: phase-authoring
description: The required entry point for ANY new work on a .agent/phases/ project. Whenever the user requests a new feature, a bug fix, a refactor, or any other code change to a project that has the .agent/phases/ structure, call this skill FIRST to capture the work as a phase directory with task files — never implement the change directly in code. Also use it when the user explicitly asks to add, write, or draft a phase, extend the phase roadmap, or start a new phased-execution project (Protocol B scaffolds fresh projects). Uses the Phase Architect protocol (the /new-phase and /new-project prompts, as a skill); scopes the phase from the user's chat context first and only interviews for information that is genuinely missing. This skill writes phase directories (a 00_phase.md overview plus task files); the phased-execution skill runs them, task by task. description: The required entry point for ANY new work on a .agents/phases/ project. Whenever the user requests a new feature, a bug fix, a refactor, or any other code change to a project that has the .agents/phases/ structure, call this skill FIRST to capture the work as a phase directory with task files — never implement the change directly in code. Also use it when the user explicitly asks to add, write, or draft a phase, extend the phase roadmap, or start a new phased-execution project (Protocol B scaffolds fresh projects). Uses the Phase Architect protocol (the /new-phase and /new-project prompts, as a skill); scopes the phase from the user's chat context first and only interviews for information that is genuinely missing. This skill writes phase directories (a 00_phase.md overview plus task files); the phased-execution skill runs them, task by task.
--- ---
# Phase Authoring # Phase Authoring
@@ -14,10 +14,10 @@ master plan.
Phase state lives in files, not chat: Phase state lives in files, not chat:
- `.agent/PLAN.md` — master plan; **LOCKED DECISIONS** are binding - `.agents/PLAN.md` — master plan; **LOCKED DECISIONS** are binding
- `.agent/phases/todo/NN_name/` — a pending phase: `00_phase.md` overview + `NN_task.md` task files (task sort order = execution order) - `.agents/phases/todo/NN_name/` — a pending phase: `00_phase.md` overview + `NN_task.md` task files (task sort order = execution order)
- `.agent/phases/todo/NN_name.md` — legacy single-file phase (still valid; migrate or split it) - `.agents/phases/todo/NN_name.md` — legacy single-file phase (still valid; migrate or split it)
- `.agent/phases/complete/` — finished phases, mirroring the todo/ layout (read-only history) - `.agents/phases/complete/` — finished phases, mirroring the todo/ layout (read-only history)
Legacy flat phases (`todo/NN_name.md`) are still executed as a single unit. Legacy flat phases (`todo/NN_name.md`) are still executed as a single unit.
`bash scripts/migrate-phases-to-tasks.sh [project-root]` (resolve `scripts/` `bash scripts/migrate-phases-to-tasks.sh [project-root]` (resolve `scripts/`
@@ -29,8 +29,8 @@ into real task files is this skill's job.
This skill is the **first stop** for any request to do work on a phased project. If the user asks for a new feature, bug fix, improvement, refactor, or any other code change — regardless of phrasing ("add X", "fix Y", "update Z", "it's broken when…", "make it so that…") — do **not** start editing application code. Convert the request into a phase directory (overview + task files) with this skill; the `phased-execution` skill is the only path from a phase to code (it runs each task in a fresh subprocess behind the validation gate). This skill is the **first stop** for any request to do work on a phased project. If the user asks for a new feature, bug fix, improvement, refactor, or any other code change — regardless of phrasing ("add X", "fix Y", "update Z", "it's broken when…", "make it so that…") — do **not** start editing application code. Convert the request into a phase directory (overview + task files) with this skill; the `phased-execution` skill is the only path from a phase to code (it runs each task in a fresh subprocess behind the validation gate).
- **Phased project** (`.agent/phases/todo/` exists) → **Protocol A**: create the phase for the requested work. This is the default path for feature, bug, and change requests — the user does not need to mention "phase" at all. - **Phased project** (`.agents/phases/todo/` exists) → **Protocol A**: create the phase for the requested work. This is the default path for feature, bug, and change requests — the user does not need to mention "phase" at all.
- **Fresh project** (no `.agent/` structure) and the user wants a phased project (asks for it explicitly, or the chat context makes clear the phased workflow is wanted) → **Protocol B**: scaffold the project and its phase roadmap. - **Fresh project** (no `.agents/` structure) and the user wants a phased project (asks for it explicitly, or the chat context makes clear the phased workflow is wanted) → **Protocol B**: scaffold the project and its phase roadmap.
- **Not phased and no sign of phased intent** → this skill does not apply; do the work normally, and if the work is substantial, suggest the `convert-to-phased` skill. - **Not phased and no sign of phased intent** → this skill does not apply; do the work normally, and if the work is substantial, suggest the `convert-to-phased` skill.
- Only if the user **explicitly** asks to bypass the phase workflow should code be edited directly — in that case note that the change skips the phase's test and validation gates. - Only if the user **explicitly** asks to bypass the phase workflow should code be edited directly — in that case note that the change skips the phase's test and validation gates.
@@ -59,10 +59,10 @@ Rules:
Before writing anything, you must: Before writing anything, you must:
1. Read `.agent/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS**. 1. Read `.agents/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS**.
2. Read `AGENTS.md` if present — project rules may add requirements (e.g. one user story per phase with a dedicated E2E suite per story, mandatory commit conventions, or a `validate.sh` gate). 2. Read `AGENTS.md` if present — project rules may add requirements (e.g. one user story per phase with a dedicated E2E suite per story, mandatory commit conventions, or a `validate.sh` gate).
3. Run `bash scripts/phase-status.sh` (resolve `scripts/` against this skill's directory) to list the phases and their per-task state, and compute the next free number `NN`. 3. Run `bash scripts/phase-status.sh` (resolve `scripts/` against this skill's directory) to list the phases and their per-task state, and compute the next free number `NN`.
4. Read the `00_phase.md` files in `.agent/phases/complete/*/` to understand what has already been built, and review the remaining `todo/` phase directories to avoid overlap. Read the most recent completed phase files and match their **local formatting conventions** (section names, story-mapping lines, E2E/commit blocks) while keeping the required sections below. 4. Read the `00_phase.md` files in `.agents/phases/complete/*/` to understand what has already been built, and review the remaining `todo/` phase directories to avoid overlap. Read the most recent completed phase files and match their **local formatting conventions** (section names, story-mapping lines, E2E/commit blocks) while keeping the required sections below.
### Phase 2: Scope the New Phase (context first, interview only if needed) ### Phase 2: Scope the New Phase (context first, interview only if needed)
@@ -86,7 +86,7 @@ Derive from the chat context (see "Scoping from chat context" above):
### Phase 3: Design & Create the Phase ### Phase 3: Design & Create the Phase
Create **exactly one** new phase directory at `.agent/phases/todo/NN_name/`, Create **exactly one** new phase directory at `.agents/phases/todo/NN_name/`,
where `NN` comes from Phase 1 (next free number, counting `todo/` and where `NN` comes from Phase 1 (next free number, counting `todo/` and
`complete/` together) and `name` is a short `snake_case` description. It `complete/` together) and `name` is a short `snake_case` description. It
contains the phase overview and the phase's task files: contains the phase overview and the phase's task files:
@@ -112,7 +112,7 @@ earlier ones within the phase.
**Design Mandates:** **Design Mandates:**
- **Independent Viability:** the phase must leave the project functional and launchable on its own once complete. - **Independent Viability:** the phase must leave the project functional and launchable on its own once complete.
- **Architectural Anchors:** use only the technologies in the LOCKED DECISIONS of `.agent/PLAN.md`. Never introduce new technology without explicit permission. - **Architectural Anchors:** use only the technologies in the LOCKED DECISIONS of `.agents/PLAN.md`. Never introduce new technology without explicit permission.
- **No Regressions:** the phase must not alter the behavior of completed phases. - **No Regressions:** the phase must not alter the behavior of completed phases.
- **Executable in isolation:** an agent that sees only the repository, the phase overview, the completed task files, and one task file — no chat history, no follow-ups — must be able to finish that task. No hidden assumptions. - **Executable in isolation:** an agent that sees only the repository, the phase overview, the completed task files, and one task file — no chat history, no follow-ups — must be able to finish that task. No hidden assumptions.
@@ -153,7 +153,7 @@ Derive from the chat context (see "Scoping from chat context" above):
- Use `uv` for all package management. - Use `uv` for all package management.
- **Mandatory Dependencies:** `python-dotenv` (production); `debugpy`, `ruff`, `pyright`, `pytest`, `pytest-cov` (dev). - **Mandatory Dependencies:** `python-dotenv` (production); `debugpy`, `ruff`, `pyright`, `pytest`, `pytest-cov` (dev).
- **Web Projects:** add `fastapi`, `alembic`, `pydantic`; prefer `httpx`. - **Web Projects:** add `fastapi`, `alembic`, `pydantic`; prefer `httpx`.
- **Scaffold Files:** a comprehensive `.gitignore` (must include `.agent/` and `.agent/phase-sessions/`), a multi-stage `Containerfile` (assuming `podman`/`docker`), and a `README.md` with `uv` and configuration instructions. - **Scaffold Files:** a comprehensive `.gitignore` (must include `.agents/phase-sessions/` and `.agents/pipeline.log` — but **never** `.agents/` itself: the planning tree is tracked and committed), a multi-stage `Containerfile` (assuming `podman`/`docker`), and a `README.md` with `uv` and configuration instructions.
### Phase 3: Strategic Architectural Design ### Phase 3: Strategic Architectural Design
@@ -174,12 +174,12 @@ phases may use. The design must cover:
Use file tools to create (not just describe): Use file tools to create (not just describe):
- **`.agent/PLAN.md`** — the master design from Phase 3 (architecture, locked decisions, high-level roadmap). - **`.agents/PLAN.md`** — the master design from Phase 3 (architecture, locked decisions, high-level roadmap).
- **`AGENTS.md`** — initialized with: always read `.agent/PLAN.md` first; follow the phased protocol in `.agent/phases/`; never modify `.agent/PLAN.md` or anything in `.agent/phases/complete/`; ask the user before editing files in `.agent/phases/todo/`; strictly adhere to the **LOCKED DECISIONS**. - **`AGENTS.md`** — initialized with: always read `.agents/PLAN.md` first; follow the phased protocol in `.agents/phases/`; never modify `.agents/PLAN.md` or anything in `.agents/phases/complete/`; ask the user before editing files in `.agents/phases/todo/`; strictly adhere to the **LOCKED DECISIONS**.
- **`.agent/phases/todo/`** — sequential phase directories (`01_…/`, `02_…/`, …), each with a `00_phase.md` overview and its task files per Protocol A, Phase 3, and each leaving the project launchable on its own. - **`.agents/phases/todo/`** — sequential phase directories (`01_…/`, `02_…/`, …), each with a `00_phase.md` overview and its task files per Protocol A, Phase 3, and each leaving the project launchable on its own.
- **`.agent/phases/complete/`** — create the directory, leave it empty. - **`.agents/phases/complete/`** — create the directory, leave it empty.
Do **not** create `.agent/validate.sh` — the `phased-execution` skill Do **not** create `.agents/validate.sh` — the `phased-execution` skill
installs it from its template on first run and it must be adapted to the installs it from its template on first run and it must be adapted to the
project's real checks. project's real checks.
@@ -189,7 +189,7 @@ execution with `phased-execution` (`auto-phase.sh`).
## Strict Operational Rules ## Strict Operational Rules
- **Work requests become phase directories.** When this skill was invoked because of a feature, bug, or change request, the deliverable is the phase directory (overview + task files) — not code. Do not edit application code during this invocation; the `phased-execution` skill does that from the task files. - **Work requests become phase directories.** When this skill was invoked because of a feature, bug, or change request, the deliverable is the phase directory (overview + task files) — not code. Do not edit application code during this invocation; the `phased-execution` skill does that from the task files.
- **Never** modify `.agent/PLAN.md`, `AGENTS.md`, or any file in `.agent/phases/complete/`. - **Never** modify `.agents/PLAN.md`, `AGENTS.md`, or any file in `.agents/phases/complete/`.
- **Never** modify existing phase directories or their files in `.agent/phases/todo/`; if one needs updating, ask the user for permission first. - **Never** modify existing phase directories or their files in `.agents/phases/todo/`; if one needs updating, ask the user for permission first.
- Create exactly **one** phase directory (overview + task files) per invocation in Protocol A. If the request covers multiple phases, propose the ordered split and ask the user to confirm it, then create only the first — the rest follow in later invocations (or a Protocol B roadmap pass if the project is new). - Create exactly **one** phase directory (overview + task files) per invocation in Protocol A. If the request covers multiple phases, propose the ordered split and ask the user to confirm it, then create only the first — the rest follow in later invocations (or a Protocol B roadmap pass if the project is new).
- Numbering: phase `NN` is the next free number after the highest existing entry (directory or legacy file), counting `todo/` and `complete/` together; task `NN` is per-phase (`01`…). Never reuse or collide a number. - Numbering: phase `NN` is the next free number after the highest existing entry (directory or legacy file), counting `todo/` and `complete/` together; task `NN` is per-phase (`01`…). Never reuse or collide a number.
+1 -1
View File
@@ -1,6 +1,6 @@
# Phase {{NN}} — {{Short Title}} # Phase {{NN}} — {{Short Title}}
**Story:** `{{.agent/user_stories/<story>.md or "n/a"}}` **Story:** `{{.agents/user_stories/<story>.md or "n/a"}}`
**Context:** `{{PLAN.md sections / files this phase builds on}}` **Context:** `{{PLAN.md sections / files this phase builds on}}`
## Objective ## Objective
+1 -1
View File
@@ -1,6 +1,6 @@
# Task {{NN}} — {{Short Title}} # Task {{NN}} — {{Short Title}}
**Phase:** `{{NN_phase}}` · **Story:** `{{.agent/user_stories/<story>.md or "n/a"}}` **Phase:** `{{NN_phase}}` · **Story:** `{{.agents/user_stories/<story>.md or "n/a"}}`
## Objective ## Objective
{{1–2 sentences: what this task delivers}} {{1–2 sentences: what this task delivers}}
@@ -17,7 +17,7 @@
# #
# Usage: bash migrate-phases-to-tasks.sh [project-root] # Usage: bash migrate-phases-to-tasks.sh [project-root]
# project-root defaults to the nearest ancestor containing # project-root defaults to the nearest ancestor containing
# .agent/phases/todo or agent/phases/todo (older projects). # .agents/phases/todo or agent/phases/todo (older projects).
set -euo pipefail set -euo pipefail
root="${1:-}" root="${1:-}"
@@ -26,14 +26,14 @@ if [[ -n "$root" ]]; then
else else
root="$(pwd)" root="$(pwd)"
while :; do while :; do
if [[ -d "$root/.agent/phases/todo" || -d "$root/agent/phases/todo" ]]; then break; fi if [[ -d "$root/.agents/phases/todo" || -d "$root/agent/phases/todo" ]]; then break; fi
[[ "$root" == "/" ]] && { echo "✗ ERROR: no phases/todo found at or above $(pwd)" >&2; exit 1; } [[ "$root" == "/" ]] && { echo "✗ ERROR: no phases/todo found at or above $(pwd)" >&2; exit 1; }
root="$(dirname "$root")" root="$(dirname "$root")"
done done
fi fi
if [[ -d "$root/.agent/phases" ]]; then if [[ -d "$root/.agents/phases" ]]; then
phases="$root/.agent/phases" phases="$root/.agents/phases"
elif [[ -d "$root/agent/phases" ]]; then elif [[ -d "$root/agent/phases" ]]; then
phases="$root/agent/phases" phases="$root/agent/phases"
else else
+4 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# phase-status.sh — phase/task pipeline state for the Phase Architect. # phase-status.sh — phase/task pipeline state for the Phase Architect.
# #
# Finds the project root (nearest ancestor with .agent/phases/todo), prints # Finds the project root (nearest ancestor with .agents/phases/todo), prints
# the todo/ and complete/ phase listings with per-task state, the next free # the todo/ and complete/ phase listings with per-task state, the next free
# phase number NN (counting both directories together, zero-padded to 2 # phase number NN (counting both directories together, zero-padded to 2
# digits), and the next pending unit in pipeline order. # digits), and the next pending unit in pipeline order.
@@ -15,12 +15,12 @@ set -euo pipefail
root="$(pwd)" root="$(pwd)"
while :; do while :; do
if [[ -d "$root/.agent/phases/todo" ]]; then break; fi if [[ -d "$root/.agents/phases/todo" ]]; then break; fi
[[ "$root" == "/" ]] && { echo "✗ ERROR: no .agent/phases/todo found at or above $(pwd)" >&2; exit 1; } [[ "$root" == "/" ]] && { echo "✗ ERROR: no .agents/phases/todo found at or above $(pwd)" >&2; exit 1; }
root="$(dirname "$root")" root="$(dirname "$root")"
done done
phases="$root/.agent/phases" phases="$root/.agents/phases"
# --- todo: per-task state ------------------------------------------------------ # --- todo: per-task state ------------------------------------------------------
echo "todo:" echo "todo:"
+62 -18
View File
@@ -1,26 +1,28 @@
--- ---
name: phased-execution name: phased-execution
description: Runs the .agent/phases/ phased-execution pipeline (ported from opencode's next-phase/auto-phase commands). Use when the user asks to run the next task, run the next phase, run all phases, run the phase pipeline, or check pipeline status. Each task executes in a separate pi subprocess so this chat's context stays small. description: Runs the .agents/phases/ phased-execution pipeline (ported from opencode's next-phase/auto-phase commands). Use when the user asks to run the next task, run the next phase, run all phases, run the phase pipeline, or check pipeline status. Each task executes in a separate pi subprocess so this chat's context stays small.
--- ---
# Phased Execution # Phased Execution
Phase state lives in files, not chat: Phase state lives in files, not chat:
- `.agent/PLAN.md` — master plan; LOCKED DECISIONS are binding - `.agents/PLAN.md` — master plan; LOCKED DECISIONS are binding
- `.agent/phases/todo/NN_name/` — a pending phase: `00_phase.md` (objective, dependencies, task index, testing & quality, completion criteria) plus `NN_task.md` task files (task sort order = execution order) - `.agents/phases/todo/NN_name/` — a pending phase: `00_phase.md` (objective, dependencies, task index, testing & quality, completion criteria) plus `NN_task.md` task files (task sort order = execution order)
- `.agent/phases/todo/NN_name.md` — legacy single-file phase (still executable as one unit) - `.agents/phases/todo/NN_name.md` — legacy single-file phase (still executable as one unit)
- `.agent/phases/complete/` — finished phases; mirrors the `todo/` layout (completed task files and the phase overview move here) - `.agents/phases/complete/` — finished phases; mirrors the `todo/` layout (completed task files and the phase overview move here)
- `.agent/reports/<phase>/<task>.a<N>.{md,err,validate}` — per-task executor reports, stderr, and validation logs (legacy phases: `.agent/reports/<phase>.a<N>.*`) - `.agents/reports/<phase>/<task>.a<N>.{md,err,validate}` — per-task executor reports, stderr, and validation logs (legacy phases: `.agents/reports/<phase>.a<N>.*`)
- `.agent/validate.sh` — the pass/fail gate, run after **every task** - `.agents/validate.sh` — the pass/fail gate, run after **every task**
The unit of execution is the **task**: each task runs in a **separate pi The unit of execution is the **task**: each task runs in a **separate pi
process** (fresh context) with bounded fixer retries. A task only moves to process** (fresh context) with bounded fixer retries. A task only moves to
`complete/` after the child exits 0, the child's stream ends with a clean `complete/` after the child exits 0, the child's stream ends with a clean
final report, **and** `.agent/validate.sh` passes. When all of a phase's tasks final report, **and** `.agents/validate.sh` passes. When all of a phase's tasks
are done, `00_phase.md` runs as the phase's **final pass** (remaining inline are done, `00_phase.md` runs as the phase's **final pass** (remaining inline
work + completion criteria + phase-level verification); moving it completes work + completion criteria + phase-level verification); moving it completes
the phase and is the `PHASE_COMMIT` commit point. This chat only dispatches the phase and is the `PHASE_COMMIT` commit point (one atomic commit — code +
phase files + reports — pushed right after when the repo has a remote;
children never commit; see Commits below). This chat only dispatches
and relays results — do not implement task code yourself; that is what the and relays results — do not implement task code yourself; that is what the
subprocesses are for. subprocesses are for.
@@ -31,7 +33,7 @@ the terminal: tool calls, assistant text, `◐ thinking…` / `◑ thought for N
indicators, yellow `⧉ compacting context` lines (these can take minutes — indicators, yellow `⧉ compacting context` lines (these can take minutes —
not a hang), and provider auto-retry notices. If the child dies mid-flush and not a hang), and provider auto-retry notices. If the child dies mid-flush and
the stream loses the final message, the report is recovered from the the stream loses the final message, the report is recovered from the
child's session file (`.agent/phase-sessions/`), so a completed phase is child's session file (`.agents/phase-sessions/`), so a completed phase is
never lost to a truncated stream. never lost to a truncated stream.
## Commands ## Commands
@@ -64,8 +66,9 @@ Re-running `auto-phase.sh` after a failure continues where it stopped.
## After a run ## After a run
Exit codes: `0` = success (or nothing to run), `1` = task/phase failed after all Exit codes: `0` = success (or nothing to run), `1` = task failed after all
attempts, `130`/`143` = interrupted (Ctrl+C / SIGTERM). attempts, or the phase commit/push failed, `130`/`143` = interrupted
(Ctrl+C / SIGTERM).
Failures always print a `✗ ERROR:` line with the last error output — if the Failures always print a `✗ ERROR:` line with the last error output — if the
script's output looks like it ended abruptly, re-run it; the failed executor's script's output looks like it ended abruptly, re-run it; the failed executor's
session is resumed automatically (retries continue the child's own session, session is resumed automatically (retries continue the child's own session,
@@ -73,10 +76,46 @@ keeping its work).
Relay to the user: the task (or phase) name, its executor report (printed at Relay to the user: the task (or phase) name, its executor report (printed at
the end of the script output), and the validation outcome. On failure, point the end of the script output), and the validation outcome. On failure, point
the user at `.agent/reports/<phase>/<task>.a*.{md,err,validate}` (legacy the user at `.agents/reports/<phase>/<task>.a*.{md,err,validate}` (legacy
phases: `.agent/reports/<phase>.a*.*`) — the script also prints a ready to run phases: `.agents/reports/<phase>.a*.*`) — the script also prints a ready to run
`pi --session … -c “…”` command to continue the failed session manually. `pi --session … -c “…”` command to continue the failed session manually.
## Commits
Children never commit — their prompts forbid `git add`/`git commit`
(overriding any project “commit per phase” instruction), which is what keeps
the commit deterministic instead of intermittent. By default
(`PHASE_COMMIT=1`) the harness makes **ONE atomic commit per completed
phase** at its commit point: the phase's code changes, the
`todo/`→`complete/` file move, and the executor reports, together.
`PHASE_COMMIT=0` opts out — the phase is then left uncommitted with a loud
warning, never silently.
- **Scoped staging**: a snapshot of the worktree taken at the phase's first
unit (`.agents/phase-sessions/dirty-<phase>`, gitignored runtime storage)
is subtracted, so the owner's pre-existing uncommitted work is left alone;
pipeline runtime artifacts (`phase-sessions/`, `pipeline.log`) are never
staged. The commit output prints exactly what went in.
- **Verified**: the moved phase file (and the executor report, unless the
project gitignores reports) is checked against the index *before*
committing — the artifacts that used to go missing silently.
- **Loud on failure**: a commit failure prints a `✗ ERROR:` block with the
git error and the exact hand-fix command, and **stops the run**. The phase
stays complete (the work passed validation) — re-running will not
re-execute it, and a later phase's commit will not sweep the miss in: fix
the commit first, then re-run.
- Subject: `PHASE_COMMIT_SUBJECT` (default `phase: {{PHASE}}`); the
executor's final report becomes the commit body. `--no-gpg-sign` is always
passed.
- **Pushed**: with `PHASE_PUSH=1` (default) the commit is pushed right after
it is made — to the branch's upstream when one is set, otherwise
`git push -u <first remote> <branch>`. A repo with no remote skips the
push with a notice (the commit stays local). A push failure gets the same
`✗ ERROR:` contract as a commit failure: the commit is local and safe, the
run stops, and the next phase's push sweeps the unpushed commit in once
the push works. `PHASE_PUSH=0` opts out — each phase commit is left local
with a loud notice.
## Configuration (environment variables) ## Configuration (environment variables)
| Var | Default | Meaning | | Var | Default | Meaning |
@@ -84,14 +123,17 @@ phases: `.agent/reports/<phase>.a*.*`) — the script also prints a ready to run
| `MAX_FIX_ATTEMPTS` | `3` | Fixer retries per phase | | `MAX_FIX_ATTEMPTS` | `3` | Fixer retries per phase |
| `PHASE_MODEL` | session default | `--model` for child executors (e.g. `anthropic/claude-sonnet-4-5`) | | `PHASE_MODEL` | session default | `--model` for child executors (e.g. `anthropic/claude-sonnet-4-5`) |
| `PHASE_THINKING` | session default | `--thinking` level for child executors | | `PHASE_THINKING` | session default | `--thinking` level for child executors |
| `PHASE_COMMIT` | `0` | `1` = `git commit --no-gpg-sign` after each completed **phase** (when its `00_phase.md` final pass passes; legacy: when its file moves) | | `PHASE_COMMIT` | `1` | `1` (default) = the harness commits each completed **phase** as one atomic commit (code changes + the file move + executor reports) when its `00_phase.md` final pass passes (legacy: when its file moves). `0` = opt out: the phase is left uncommitted with a loud warning. See Commits above |
| `PHASE_COMMIT_SUBJECT` | `phase: {{PHASE}}` | Commit subject template for `PHASE_COMMIT=1` (`{{PHASE}}` = the phase directory name); the executor's final report becomes the commit body |
| `PHASE_PUSH` | `1` | `1` (default) = push each phase commit right after it is made (upstream when set, else `git push -u <first remote> <branch>`); no remote = skip with a notice; a failure stops the run (the commit stays local — the next phase's push sweeps it in). `0` = leave commits local with a loud notice. See Commits above |
| `PI_TRUST` | `0` | `1` = pass `--approve` (load project `.pi/` settings/skills into children) | | `PI_TRUST` | `0` | `1` = pass `--approve` (load project `.pi/` settings/skills into children) |
| `FRESH_FIX` | `0` | `1` = fixer retries start fresh instead of resuming the failed session | | `FRESH_FIX` | `0` | `1` = fixer retries start fresh instead of resuming the failed session |
| `QUIET` | `0` | `1` = suppress live progress display (reports are still written) | | `QUIET` | `0` | `1` = suppress live progress display (reports are still written) |
| `PHASE_NOTIFY` | `1` | `0` = disable ntfy push notifications. When on and `~/.env/pi-ntfy.env` exists, a notification is sent after every unit completes (`task` for each task file, `phase` for a phase's final pass) |
## Setup notes ## Setup notes
- First run creates `.agent/validate.sh` from `assets/validate.sh` if missing. - First run creates `.agents/validate.sh` from `assets/validate.sh` if missing.
It must be adapted to the project's real checks — it is the authoritative It must be adapted to the project's real checks — it is the authoritative
quality gate. quality gate.
- Phase directories are created by the `phase-authoring` skill or the - Phase directories are created by the `phase-authoring` skill or the
@@ -100,8 +142,10 @@ phases: `.agent/reports/<phase>.a*.*`) — the script also prints a ready to run
- Legacy flat phase files (`todo/NN_name.md`) are still executed as a single - Legacy flat phase files (`todo/NN_name.md`) are still executed as a single
unit; `phase-authoring`'s `migrate-phases-to-tasks.sh` converts them to the unit; `phase-authoring`'s `migrate-phases-to-tasks.sh` converts them to the
directory layout (the phase's final pass then picks up any inline task list). directory layout (the phase's final pass then picks up any inline task list).
- Child executor sessions are kept in `.agent/phase-sessions/`; add it to - Child executor sessions are kept in `.agents/phase-sessions/` (plus
`.gitignore` if the project is versioned. `pipeline.log` in `.agents/`); if the project is versioned, git-ignore those
runtime artifacts only — `.agents/` itself is tracked and committed.
(The per-phase worktree snapshot `dirty-<phase>` is always kept there too.)
- If you keep non-skill markdown (e.g. a `README.md`) in a skills directory - If you keep non-skill markdown (e.g. a `README.md`) in a skills directory
(like `~/.pi/agent/skills/`), pi warns “description is required” for it. (like `~/.pi/agent/skills/`), pi warns “description is required” for it.
Add a `.gitignore` in that directory listing the file — pi's skill scanner Add a `.gitignore` in that directory listing the file — pi's skill scanner
+5 -4
View File
@@ -1,11 +1,11 @@
You are a phase executor in a phased build pipeline. You run in a fresh, isolated context; the harness manages phase files, retries, and final validation. You are a phase executor in a phased build pipeline. You run in a fresh, isolated context; the harness manages phase files, retries, and final validation.
Target phase file: `.agent/phases/todo/{{PHASE}}` Target phase file: `.agents/phases/todo/{{PHASE}}`
## Steps ## Steps
1. Read `.agent/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS** (binding; never introduce technology outside them). 1. Read `.agents/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS** (binding; never introduce technology outside them).
2. Read `AGENTS.md` if present. 2. Read `AGENTS.md` if present.
3. Read the completed phase files so your work stays architecturally consistent with what is already built: every `00_phase.md` in `.agent/phases/complete/*/`, plus any legacy flat phase files directly in `.agent/phases/complete/`. 3. Read the completed phase files so your work stays architecturally consistent with what is already built: every `00_phase.md` in `.agents/phases/complete/*/`, plus any legacy flat phase files directly in `.agents/phases/complete/`.
4. Read the target phase file and complete **every** task in it, in order. 4. Read the target phase file and complete **every** task in it, in order.
5. Write the unit and integration tests required by the phase's Testing & Quality section. Do not omit parts of the code to inflate coverage. 5. Write the unit and integration tests required by the phase's Testing & Quality section. Do not omit parts of the code to inflate coverage.
6. Run the project's full test suite and linter. If anything fails — including the phase's coverage criterion — fix it and re-run until green. 6. Run the project's full test suite and linter. If anything fails — including the phase's coverage criterion — fix it and re-run until green.
@@ -13,7 +13,8 @@ Target phase file: `.agent/phases/todo/{{PHASE}}`
## Rules ## Rules
- Work only on the target phase; never start work from other files in `todo/`. - Work only on the target phase; never start work from other files in `todo/`.
- Do **not** move, rename, or edit the phase file, other files in `.agent/phases/todo/`, `.agent/PLAN.md`, or anything in `.agent/phases/complete/`. The harness moves the phase file on success. - Do **not** move, rename, or edit the phase file, other files in `.agents/phases/todo/`, `.agents/PLAN.md`, or anything in `.agents/phases/complete/`. The harness moves the phase file on success.
- Do **not** run `git add` or `git commit` — leave every change in the working tree. The harness commits this completed phase (code, phase files, and reports) atomically after this pass passes and pushes it when the repo has a remote; this overrides any project instruction to commit per phase.
- Do not assume the code is correct; fix any errors you find while testing. - Do not assume the code is correct; fix any errors you find while testing.
- Leave the repository functional when you finish. - Leave the repository functional when you finish.
@@ -1,19 +1,20 @@
You are the phase-completion executor in a phased build pipeline. You run in a fresh, isolated context; the harness manages phase and task files, retries, and final validation. You are the phase-completion executor in a phased build pipeline. You run in a fresh, isolated context; the harness manages phase and task files, retries, and final validation.
Phase overview: `.agent/phases/todo/{{PHASE}}/00_phase.md` Phase overview: `.agents/phases/todo/{{PHASE}}/00_phase.md`
## Steps ## Steps
1. Read `.agent/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS** (binding; never introduce technology outside them). 1. Read `.agents/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS** (binding; never introduce technology outside them).
2. Read `AGENTS.md` if present. 2. Read `AGENTS.md` if present.
3. Read the phase overview `.agent/phases/todo/{{PHASE}}/00_phase.md`. 3. Read the phase overview `.agents/phases/todo/{{PHASE}}/00_phase.md`.
4. Check the phase's task index against `.agent/phases/complete/{{PHASE}}/`: if any task is missing from there, the overview itself still carries work (a legacy phase with an inline task list) — implement that remaining work now, in order, including its tests. 4. Check the phase's task index against `.agents/phases/complete/{{PHASE}}/`: if any task is missing from there, the overview itself still carries work (a legacy phase with an inline task list) — implement that remaining work now, in order, including its tests.
5. Otherwise every task is done: this is the final verification pass. Verify **each** completion criterion in the phase overview (commands to run, endpoints to hit, artifacts to exist), and execute any phase-level verification blocks it defines (e.g. a dedicated E2E or contract test suite). 5. Otherwise every task is done: this is the final verification pass. Verify **each** completion criterion in the phase overview (commands to run, endpoints to hit, artifacts to exist), and execute any phase-level verification blocks it defines (e.g. a dedicated E2E or contract test suite).
6. Run the project's full test suite and linter. If anything fails — including the phase's coverage criterion or a completion criterion — fix it and re-run until green. 6. Run the project's full test suite and linter. If anything fails — including the phase's coverage criterion or a completion criterion — fix it and re-run until green.
7. If you find defects in previously completed work (failing tests, lint errors, bugs), fix those as part of this pass. 7. If you find defects in previously completed work (failing tests, lint errors, bugs), fix those as part of this pass.
## Rules ## Rules
- Never start work from other files in `todo/`. - Never start work from other files in `todo/`.
- Do **not** move, rename, or edit the phase overview, other files in `.agent/phases/todo/`, `.agent/PLAN.md`, or anything in `.agent/phases/complete/`. The harness moves the phase file on success. - Do **not** move, rename, or edit the phase overview, other files in `.agents/phases/todo/`, `.agents/PLAN.md`, or anything in `.agents/phases/complete/`. The harness moves the phase file on success.
- Do **not** run `git add` or `git commit` — leave every change in the working tree. The harness commits this completed phase (code, phase files, and reports) atomically after this pass passes and pushes it when the repo has a remote; this overrides any project instruction to commit per phase.
- Do not assume the code is correct; fix any errors you find while testing. - Do not assume the code is correct; fix any errors you find while testing.
- Leave the repository functional when you finish. - Leave the repository functional when you finish.
@@ -1,12 +1,12 @@
You are a task executor in a phased build pipeline. You run in a fresh, isolated context; the harness manages phase and task files, retries, and final validation. You are a task executor in a phased build pipeline. You run in a fresh, isolated context; the harness manages phase and task files, retries, and final validation.
Target task file: `.agent/phases/todo/{{PHASE}}/{{TASK}}` Target task file: `.agents/phases/todo/{{PHASE}}/{{TASK}}`
## Steps ## Steps
1. Read `.agent/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS** (binding; never introduce technology outside them). 1. Read `.agents/PLAN.md` — project goals, architecture, and **LOCKED DECISIONS** (binding; never introduce technology outside them).
2. Read `AGENTS.md` if present. 2. Read `AGENTS.md` if present.
3. Read the phase overview `.agent/phases/todo/{{PHASE}}/00_phase.md` — objective, dependencies, testing & quality mandate, and completion criteria. 3. Read the phase overview `.agents/phases/todo/{{PHASE}}/00_phase.md` — objective, dependencies, testing & quality mandate, and completion criteria.
4. Read this phase's completed task files (`.agent/phases/complete/{{PHASE}}/*.md`, excluding `00_phase.md`) and the `00_phase.md` overviews of other completed phases (`.agent/phases/complete/*/00_phase.md`) so your work stays architecturally consistent with what is already built. 4. Read this phase's completed task files (`.agents/phases/complete/{{PHASE}}/*.md`, excluding `00_phase.md`) and the `00_phase.md` overviews of other completed phases (`.agents/phases/complete/*/00_phase.md`) so your work stays architecturally consistent with what is already built.
5. Read the target task file and complete it fully, in order. 5. Read the target task file and complete it fully, in order.
6. Write the unit and integration tests required by the task. Do not omit parts of the code to inflate coverage. 6. Write the unit and integration tests required by the task. Do not omit parts of the code to inflate coverage.
7. Run the project's full test suite and linter. If anything fails — including the task's coverage criterion — fix it and re-run until green. 7. Run the project's full test suite and linter. If anything fails — including the task's coverage criterion — fix it and re-run until green.
@@ -14,7 +14,8 @@ Target task file: `.agent/phases/todo/{{PHASE}}/{{TASK}}`
## Rules ## Rules
- Work only on the target task; never start the next task or work from other files in `todo/`. - Work only on the target task; never start the next task or work from other files in `todo/`.
- Do **not** move, rename, or edit the task file, `00_phase.md`, other files in `.agent/phases/todo/`, `.agent/PLAN.md`, or anything in `.agent/phases/complete/`. The harness moves the task file on success. - Do **not** move, rename, or edit the task file, `00_phase.md`, other files in `.agents/phases/todo/`, `.agents/PLAN.md`, or anything in `.agents/phases/complete/`. The harness moves the task file on success.
- Do **not** run `git add` or `git commit` — leave every change in the working tree. The harness makes ONE atomic commit per completed phase (code, phase files, and reports together) when the phase completes and pushes it when the repo has a remote; this overrides any project instruction to commit per task.
- Do not assume the code is correct; fix any errors you find while testing. - Do not assume the code is correct; fix any errors you find while testing.
- Leave the repository functional when you finish. - Leave the repository functional when you finish.
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# .agent/validate.sh — validation gate for the phased-execution pipeline. # .agents/validate.sh — validation gate for the phased-execution pipeline.
# #
# A phase is only moved to .agent/phases/complete/ if this script exits 0. # A phase is only moved to .agents/phases/complete/ if this script exits 0.
# Adapt the checks below to this project's real test suite, linter, and # Adapt the checks below to this project's real test suite, linter, and
# coverage floor, then commit the result. # coverage floor, then commit the result.
set -uo pipefail set -uo pipefail
+13 -8
View File
@@ -1,39 +1,44 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# auto-phase.sh — run the full phased pipeline, no LLM in the loop. # auto-phase.sh — run the full phased pipeline, no LLM in the loop.
# #
# Processes every pending task in .agent/phases/todo/ in pipeline order # Processes every pending task in .agents/phases/todo/ in pipeline order
# (phase order, then task order within each phase). Each task runs in its # (phase order, then task order within each phase). Each task runs in its
# own pi process (fresh context); .agent/validate.sh runs after EVERY task. # own pi process (fresh context); .agents/validate.sh runs after EVERY task.
# On failure the executor's session is resumed for up to MAX_FIX_ATTEMPTS # On failure the executor's session is resumed for up to MAX_FIX_ATTEMPTS
# fixer rounds. A task moves to .agent/phases/complete/ only after the # fixer rounds. A task moves to .agents/phases/complete/ only after the
# child exits 0 AND validation passes; a phase completes when its # child exits 0 AND validation passes; a phase completes when its
# 00_phase.md final pass succeeds (legacy phases: when their file moves). # 00_phase.md final pass succeeds (legacy phases: when their file moves).
# Stops at the first task that cannot be completed — re-run this script to # Stops at the first task that cannot be completed — re-run this script to
# continue where it stopped. # continue where it stopped.
# #
# Env: see SKILL.md (MAX_FIX_ATTEMPTS, PHASE_MODEL, PHASE_THINKING, # Env: see SKILL.md (MAX_FIX_ATTEMPTS, PHASE_MODEL, PHASE_THINKING,
# PHASE_COMMIT, PI_TRUST, FRESH_FIX). # PHASE_COMMIT, PHASE_PUSH, PI_TRUST, FRESH_FIX).
set -uo pipefail set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib.sh" source "$SCRIPT_DIR/lib.sh"
# Make interruptions visible: state stays in .agent/phases/todo, and the # Make interruptions visible: state stays in .agents/phases/todo, and the
# failed executor's session is still resumable on the next run. # failed executor's session is still resumable on the next run.
trap 'echo; echo "✗ ERROR: interrupted (SIGINT) — ${unit:-the pipeline} is left in $PHASE_TODO/; re-run to continue where it stopped" >&2; exit 130' INT trap 'echo; echo "✗ ERROR: interrupted (SIGINT) — ${unit:-the pipeline} is left in $PHASE_TODO/; re-run to continue where it stopped" >&2; exit 130' INT
trap 'echo; echo "✗ ERROR: interrupted (SIGTERM) — ${unit:-the pipeline} is left in $PHASE_TODO/; re-run to continue where it stopped" >&2; exit 143' TERM trap 'echo; echo "✗ ERROR: interrupted (SIGTERM) — ${unit:-the pipeline} is left in $PHASE_TODO/; re-run to continue where it stopped" >&2; exit 143' TERM
cd "$(find_root)" || die "no .agent/phases/todo found in this or parent directories (run /to-phase or /audit-create first)" cd "$(find_root)" || die "no .agents/phases/todo found in this or parent directories (run /to-phase or /audit-create first)"
build_pi_args build_pi_args
delivered=() delivered=()
while unit="$(next_unit)"; do while unit="$(next_unit)"; do
[[ -n "$unit" ]] || break [[ -n "$unit" ]] || break
if ! execute_unit "$unit"; then if ! execute_unit "$unit"; then
echo "✗ ERROR: pipeline stopped — $unit FAILED after $MAX_FIX_ATTEMPTS attempts" >&2 # execute_unit printed the failure detail (task failure: errors, logs,
echo " fix the issues above, then re-run this script to continue where it stopped" >&2 # resume command — or phase commit/push failure: the hand-fix command).
echo "✗ ERROR: pipeline stopped — $unit did not complete (see the error output above)" >&2
echo " re-run this script to continue where it stopped" >&2
exit 1 exit 1
fi fi
delivered+=("$unit") delivered+=("$unit")
# Notify after every unit completes: a phase-end (00_phase.md / legacy file)
# announces the phase; a normal task file announces the task.
if is_phase_end "$unit"; then notify_task "$unit" phase; else notify_task "$unit" task; fi
done done
echo echo
+267 -30
View File
@@ -3,43 +3,47 @@
# Sourced by run-task.sh, run-phase.sh, and auto-phase.sh. Not meant to be run directly. # Sourced by run-task.sh, run-phase.sh, and auto-phase.sh. Not meant to be run directly.
# #
# Phase state lives in files, not chat context: # Phase state lives in files, not chat context:
# .agent/PLAN.md master plan, LOCKED DECISIONS (binding) # .agents/PLAN.md master plan, LOCKED DECISIONS (binding)
# .agent/phases/todo/NN_name/ pending phase: 00_phase.md (overview) + NN_task.md task files # .agents/phases/todo/NN_name/ pending phase: 00_phase.md (overview) + NN_task.md task files
# .agent/phases/todo/NN_name.md legacy single-file phase (still executable) # .agents/phases/todo/NN_name.md legacy single-file phase (still executable)
# .agent/phases/complete/ finished phases — mirrors the todo/ layout # .agents/phases/complete/ finished phases — mirrors the todo/ layout
# .agent/reports/ per-task executor reports, stderr, validation logs # .agents/reports/ per-task executor reports, stderr, validation logs
# .agent/phase-sessions/ child pi session files (resumable fixers) # .agents/phase-sessions/ child pi session files (resumable fixers)
# #
# The unit of execution is the TASK: each task file runs in its own pi # The unit of execution is the TASK: each task file runs in its own pi
# subprocess (fresh context) with bounded fixer retries, and # subprocess (fresh context) with bounded fixer retries, and
# .agent/validate.sh runs after EVERY task. A unit only moves to complete/ # .agents/validate.sh runs after EVERY task. A unit only moves to complete/
# after the child exits 0, the child's stream ends with a clean final # after the child exits 0, the child's stream ends with a clean final
# report, and validation passes. When all of a phase's tasks are done, # report, and validation passes. When all of a phase's tasks are done,
# 00_phase.md runs as the phase's final pass (any remaining inline work + # 00_phase.md runs as the phase's final pass (any remaining inline work +
# completion criteria + phase-level verification); moving it completes the # completion criteria + phase-level verification); moving it completes the
# phase and is the PHASE_COMMIT commit point. # phase and is the commit point. Children never commit — by default
# (PHASE_COMMIT=1) the harness makes ONE atomic commit per completed phase
# (code changes + the file move + the executor reports), scoped so the
# owner's pre-existing worktree changes are left alone, and pushes it when
# the repo has a remote (PHASE_PUSH=1; see commit_phase / push_phase).
SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
EXECUTOR_PROMPT_FILE="$SKILL_DIR/assets/executor-prompt.md" EXECUTOR_PROMPT_FILE="$SKILL_DIR/assets/executor-prompt.md"
TASK_EXECUTOR_PROMPT_FILE="$SKILL_DIR/assets/task-executor-prompt.md" TASK_EXECUTOR_PROMPT_FILE="$SKILL_DIR/assets/task-executor-prompt.md"
PHASE_FINAL_PROMPT_FILE="$SKILL_DIR/assets/phase-final-prompt.md" PHASE_FINAL_PROMPT_FILE="$SKILL_DIR/assets/phase-final-prompt.md"
PHASE_TODO=".agent/phases/todo" PHASE_TODO=".agents/phases/todo"
PHASE_DONE=".agent/phases/complete" PHASE_DONE=".agents/phases/complete"
PHASE_REPORTS=".agent/reports" PHASE_REPORTS=".agents/reports"
PHASE_SESSIONS=".agent/phase-sessions" PHASE_SESSIONS=".agents/phase-sessions"
MAX_FIX_ATTEMPTS="${MAX_FIX_ATTEMPTS:-3}" MAX_FIX_ATTEMPTS="${MAX_FIX_ATTEMPTS:-3}"
warn() { echo "⚠ $*" >&2; } warn() { echo "⚠ $*" >&2; }
die() { echo "✗ ERROR: $*" >&2; exit 1; } die() { echo "✗ ERROR: $*" >&2; exit 1; }
# --- project root ------------------------------------------------------------- # --- project root -------------------------------------------------------------
# Walk up from $PWD to the nearest directory containing .agent/phases/todo. # Walk up from $PWD to the nearest directory containing .agents/phases/todo.
find_root() { find_root() {
local d local d
d="$(pwd)" d="$(pwd)"
while :; do while :; do
if [[ -d "$d/.agent/phases/todo" ]]; then printf '%s\n' "$d"; return 0; fi if [[ -d "$d/.agents/phases/todo" ]]; then printf '%s\n' "$d"; return 0; fi
[[ "$d" == "/" ]] && return 1 [[ "$d" == "/" ]] && return 1
d="$(dirname "$d")" d="$(dirname "$d")"
done done
@@ -47,7 +51,7 @@ find_root() {
# --- unit selection ------------------------------------------------------------- # --- unit selection -------------------------------------------------------------
# A unit is the smallest schedulable piece of work, referenced relative to # A unit is the smallest schedulable piece of work, referenced relative to
# .agent/phases/todo/: # .agents/phases/todo/:
# directory phase → each task file "NN_name/NN_task.md" (sort order), then # directory phase → each task file "NN_name/NN_task.md" (sort order), then
# the phase overview "NN_name/00_phase.md" as the final pass # the phase overview "NN_name/00_phase.md" as the final pass
# legacy flat → the phase file itself, "NN_name.md" # legacy flat → the phase file itself, "NN_name.md"
@@ -225,7 +229,7 @@ fix_prompt() {
# --- child executor ----------------------------------------------------------- # --- child executor -----------------------------------------------------------
# run_child <unit> <attempt> <prompt> [resume-session] # run_child <unit> <attempt> <prompt> [resume-session]
# Attempt 1: fresh session in .agent/phase-sessions/. # Attempt 1: fresh session in .agents/phase-sessions/.
# Attempt N>1: resumes the given session file — the failed executor's own # Attempt N>1: resumes the given session file — the failed executor's own
# session, tracked by execute_unit (so retries keep its work). When no # session, tracked by execute_unit (so retries keep its work). When no
# session was captured (or FRESH_FIX=1) a fresh ephemeral session runs with # session was captured (or FRESH_FIX=1) a fresh ephemeral session runs with
@@ -287,23 +291,246 @@ run_child() {
# --- validation gate ---------------------------------------------------------- # --- validation gate ----------------------------------------------------------
ensure_validate() { ensure_validate() {
if [[ ! -f .agent/validate.sh ]]; then if [[ ! -f .agents/validate.sh ]]; then
cp "$SKILL_DIR/assets/validate.sh" .agent/validate.sh cp "$SKILL_DIR/assets/validate.sh" .agents/validate.sh
chmod +x .agent/validate.sh chmod +x .agents/validate.sh
warn "no .agent/validate.sh found — created it from the skill template." warn "no .agents/validate.sh found — created it from the skill template."
warn "adapt it to this project's real test/lint/coverage commands; it is the pass/fail gate after every task." warn "adapt it to this project's real test/lint/coverage commands; it is the pass/fail gate after every task."
fi fi
} }
# run_validation <logfile>; returns 0 iff .agent/validate.sh exits 0. # run_validation <logfile>; returns 0 iff .agents/validate.sh exits 0.
run_validation() { run_validation() {
bash .agent/validate.sh >"$1" 2>&1 bash .agents/validate.sh >"$1" 2>&1
}
# --- phase commit + push ------------------------------------------------------
# Commit ownership: child executors NEVER commit (their prompts forbid it,
# overriding any project instruction to commit per task/phase). By default
# (PHASE_COMMIT=1) the harness therefore makes ONE atomic commit per
# completed phase — the phase's code changes, the todo→complete file move,
# and the executor reports, together — at the phase's commit point, and
# pushes it right after (PHASE_PUSH=1, default — see push_phase).
#
# Staging is scoped so the owner's unrelated work is not swept in:
# stage = (everything dirty now)
# − (what was already dirty when the phase's first unit started —
# snapshot $PHASE_SESSIONS/dirty-<phase>, taken once per phase)
# − (pipeline runtime artifacts: phase-sessions/, pipeline.log)
# Work the owner dirtied mid-phase is indistinguishable from phase work and
# IS committed — the commit output prints exactly what went in.
# Snapshot the worktree's dirty state at the phase's first unit (no-op
# outside a git work tree, and when the phase already has a snapshot — a
# resumed phase keeps the one taken at its start).
phase_dirty_snapshot() {
local phase="$1" f
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || return 0
f="$PHASE_SESSIONS/dirty-$phase"
if [[ ! -f "$f" ]]; then
git status --porcelain >"$f" 2>/dev/null || : >"$f"
fi
}
# commit_phase <unit> <report-file>
# Returns 0 on success, when there is nothing left to commit, or outside a
# git work tree. Returns 1 (after printing a ✗ ERROR block with the git
# error and the hand-fix command) when the phase's own artifacts could not
# be committed, or the push of the phase commit failed (the commit is local
# and safe — the next phase's push sweeps it in once the push works). The
# phase stays COMPLETE either way — the work passed validation; the caller
# stops the run so a commit/push miss is visible, never retried as a task
# and never swept into a later phase's commit.
commit_phase() {
local unit="$1" report="${2:-}"
local phase pre curf paths lits moved staged addout commitout subject msgf
phase="$(unit_phase "$unit")"
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
warn "not a git work tree — no phase commit for $phase"
return 0
fi
pre="$PHASE_SESSIONS/dirty-$phase"
# Everything dirty now: tracked changes vs HEAD + untracked non-ignored.
curf="$(mktemp)"
{ git diff --name-only HEAD; git ls-files --others --exclude-standard; } | sort -u >"$curf"
# Quick exit: the phase's artifacts are already committed (moved file
# tracked and clean — e.g. a duplicate commit attempt after the snapshot
# was cleaned up) — never stage again, owner WIP stays untouched.
if git ls-files --error-unmatch -- "$PHASE_DONE/$unit" >/dev/null 2>&1 \
&& ! grep -qx -- "$PHASE_DONE/$unit" "$curf"; then
rm -f "$curf"
echo " (nothing to commit — the phase is already fully committed)"
return 0
fi
# Subtract pre-phase owner WIP (porcelain lines are "XY <path>") and the
# pipeline's own runtime artifacts.
paths="$(mktemp)"
if [[ -f "$pre" ]]; then
comm -23 "$curf" <(cut -c4- "$pre" | grep -v '^[[:space:]]*$' | sort -u) \
| grep -vE '^\.agents/(phase-sessions/|pipeline\.log$)' >"$paths" || true
else
grep -vE '^\.agents/(phase-sessions/|pipeline\.log$)' "$curf" >"$paths" || true
fi
rm -f "$curf"
if [[ ! -s "$paths" ]]; then
rm -f "$paths" "$pre"
echo " (nothing to commit — the phase is already fully committed)"
return 0
fi
# :(literal) keeps file names with glob characters ([?* ) from being read
# as pathspec patterns.
lits="$(mktemp)"
sed 's|^|:(literal)|' "$paths" >"$lits"
if ! addout="$(git add -A --pathspec-from-file="$lits" 2>&1)"; then
rm -f "$paths" "$lits"
echo "✗ ERROR: phase commit for $phase — staging failed:" >&2
printf '%s\n' "$addout" | sed 's/^/ /' >&2
return 1
fi
rm -f "$lits"
# Verify the artifacts that used to go missing: the moved phase file must
# be in the index (hard fail), and the executor report unless the project
# deliberately gitignores reports.
moved="$PHASE_DONE/$unit"
staged="$(git -c core.quotepath=off diff --cached --name-only -z | tr '\0' '\n')"
if ! grep -qx -- "$moved" <<<"$staged"; then
git reset -q
rm -f "$paths"
echo "✗ ERROR: phase commit for $phase — the moved phase file is not in the index ($moved)." >&2
if git check-ignore -q -- "$moved" 2>/dev/null; then
echo " your .gitignore excludes it — .agents/phases must be tracked (SKILL.md setup notes)." >&2
fi
echo " the work is complete and uncommitted; stage and commit it by hand." >&2
return 1
fi
if [[ -n "$report" && -f "$report" ]] && ! grep -qx -- "$report" <<<"$staged" \
&& ! git check-ignore -q -- "$report" 2>/dev/null; then
git reset -q
rm -f "$paths"
echo "✗ ERROR: phase commit for $phase — the executor report is not in the index ($report)." >&2
echo " the work is complete and uncommitted; stage and commit it by hand." >&2
return 1
fi
rm -f "$paths"
# Subject: PHASE_COMMIT_SUBJECT with {{PHASE}} substituted (default
# "phase: <phase>"); the executor's final report becomes the body.
# The default subject lives in a variable: a brace literal inside the
# ${var:-default} word would terminate the expansion early (bash does not
# nest plain braces).
local default_subject="phase: {{PHASE}}"
subject="${PHASE_COMMIT_SUBJECT:-$default_subject}"
subject="${subject//\{\{PHASE\}\}/$phase}"
msgf="$(mktemp)"
{
printf '%s\n' "$subject"
printf '\n'
[[ -n "$report" && -f "$report" ]] && sed -n '1,40p' "$report"
} >"$msgf"
if ! commitout="$(git commit --no-gpg-sign -F "$msgf" 2>&1)"; then
rm -f "$msgf"
echo "✗ ERROR: phase commit for $phase FAILED — the phase is complete but UNCOMMITTED (the scoped changes are still staged)." >&2
printf '%s\n' "$commitout" | sed 's/^/ /' >&2
echo " finish by hand: git commit --no-gpg-sign -m 'phase: $phase'" >&2
echo " re-running the pipeline will NOT commit this phase — fix the commit first." >&2
return 1
fi
rm -f "$msgf" "$pre"
echo " (committed: $(git log -1 --oneline))"
# Hand the commit to the remote (PHASE_PUSH, default on). A push failure
# returns 1 so the run stops — same contract as a commit failure.
if ! push_phase "$phase"; then
return 1
fi
return 0
}
# push_phase <phase>
# Pushes the phase commit made by commit_phase (PHASE_PUSH=1, default).
# No remote configured → notice and success (the commit stays local).
# Branch with an upstream → `git push`; without → `git push -u <first
# remote> <branch>`. On failure prints a ✗ ERROR block with the git error
# and the hand-fix command and returns 1 — the commit is local and safe,
# and the next phase's push sweeps the unpushed commit in once the push
# works.
push_phase() {
local phase="$1" remote branch cmd pushout
[[ "${PHASE_PUSH:-1}" == "1" ]] || { echo " (PHASE_PUSH=0 — commit not pushed, left local)"; return 0; }
remote="$(git remote 2>/dev/null | head -n1)"
if [[ -z "$remote" ]]; then
echo " (no git remote configured — skipping push)"
return 0
fi
branch="$(git symbolic-ref --short -q HEAD || true)"
if [[ -z "$branch" ]]; then
echo "✗ ERROR: phase push for $phase — detached HEAD, nothing to push." >&2
echo " the phase commit is local; push by hand once you are on a branch." >&2
return 1
fi
if git rev-parse --abbrev-ref --disambiguate '@{u}' >/dev/null 2>&1; then
cmd=(git push)
else
cmd=(git push -u "$remote" "$branch")
fi
if ! pushout="$("${cmd[@]}" 2>&1)"; then
echo "✗ ERROR: phase push for $phase FAILED — the phase is committed LOCALLY but NOT PUSHED." >&2
printf '%s\n' "$pushout" | sed 's/^/ /' >&2
echo " finish by hand: ${cmd[*]}" >&2
echo " re-running will NOT re-push it now — the next phase's push sweeps it in once the push works; fix the push first." >&2
return 1
fi
echo " (pushed: $(git log -1 --oneline))"
return 0
}
# --- notifications ------------------------------------------------------------
# Send a push notification via ntfy after a unit completes. Reads
# ~/.env/pi-ntfy.env (see the ntfy skill). No-ops (silently) when notifications
# are disabled (PHASE_NOTIFY=0) or ntfy is not configured, so it never breaks
# the pipeline. Gated on PHASE_NOTIFY so a misconfigured server can't stall a
# long run; default ON when the env file is present.
notify_task() {
local unit="$1" status="$2" # status: task | phase
[[ "${PHASE_NOTIFY:-1}" == "1" ]] || return 0
local envf="${NTFY_ENV_FILE:-$HOME/.env/pi-ntfy.env}"
[[ -f "$envf" ]] || return 0
# shellcheck disable=SC1090
source "$envf"
[[ -n "${NTFY_URL:-}" && -n "${NTFY_TOKEN:-}" ]] || return 0
local title body tags
if [[ "$status" == phase ]]; then
title="Phase $(unit_phase "$unit") done"
tags="heavy_check_mark,phase-complete"
body="Phase $(unit_phase "$unit") of the pipeline completed."
else
title="Task complete"
tags="heavy_check_mark,task-complete"
body="Task delivered: $unit"
fi
curl -sS -X POST "${NTFY_URL}/${NTFY_TOPIC:-pi}" \
-H "Authorization: Bearer ${NTFY_TOKEN}" \
-H "X-Title: $title" \
-H "X-Priority: 4" \
-H "X-Tags: $tags" \
-H "X-Markdown: yes" \
-d "$body" >/dev/null 2>&1 || warn "ntfy notification failed for $unit"
} }
# --- one unit (task, phase final pass, or legacy phase), with retries --------- # --- one unit (task, phase final pass, or legacy phase), with retries ---------
# execute_unit <unit> # execute_unit <unit>
# Returns 0 and moves the unit to complete/ on success; returns 1 after # Returns 0 and moves the unit to complete/ on success; returns 1 after
# MAX_FIX_ATTEMPTS failed attempts (unit file is left in todo/). # MAX_FIX_ATTEMPTS failed attempts (unit file is left in todo/), or 1 when
# the phase commit or its push fails at a phase's commit point (unit stays
# in complete/ — the work is done; the commit/push must be finished by hand).
execute_unit() { execute_unit() {
local unit="$1" local unit="$1"
local base attempt=1 errors="" local base attempt=1 errors=""
@@ -312,6 +539,9 @@ execute_unit() {
command -v node >/dev/null 2>&1 || die "node not found on PATH (needed to render task progress)" command -v node >/dev/null 2>&1 || die "node not found on PATH (needed to render task progress)"
mkdir -p "$PHASE_DONE" "$PHASE_REPORTS" "$PHASE_SESSIONS" "$(unit_report_dir "$unit")" mkdir -p "$PHASE_DONE" "$PHASE_REPORTS" "$PHASE_SESSIONS" "$(unit_report_dir "$unit")"
ensure_validate ensure_validate
# First unit of the phase: freeze the owner's pre-existing dirty state so
# the phase commit (commit_phase) can exclude it from staging.
phase_dirty_snapshot "$(unit_phase "$unit")"
while (( attempt <= MAX_FIX_ATTEMPTS )); do while (( attempt <= MAX_FIX_ATTEMPTS )); do
echo "━━ $unit — attempt $attempt/$MAX_FIX_ATTEMPTS ━━" echo "━━ $unit — attempt $attempt/$MAX_FIX_ATTEMPTS ━━"
@@ -348,20 +578,27 @@ execute_unit() {
errors+="[child run ended without a clean final report]"$'\n'"$(tail -c 4000 "$(unit_report "$unit" "$attempt" err)" 2>/dev/null)" errors+="[child run ended without a clean final report]"$'\n'"$(tail -c 4000 "$(unit_report "$unit" "$attempt" err)" 2>/dev/null)"
fi fi
if ! run_validation "$(unit_report "$unit" "$attempt" validate)"; then if ! run_validation "$(unit_report "$unit" "$attempt" validate)"; then
warn ".agent/validate.sh FAILED — see $(unit_report "$unit" "$attempt" validate)" warn ".agents/validate.sh FAILED — see $(unit_report "$unit" "$attempt" validate)"
errors+="[.agent/validate.sh FAILED]"$'\n'"$(tail -n 120 "$(unit_report "$unit" "$attempt" validate)" 2>/dev/null)" errors+="[.agents/validate.sh FAILED]"$'\n'"$(tail -n 120 "$(unit_report "$unit" "$attempt" validate)" 2>/dev/null)"
fi fi
if [[ -z "$errors" ]]; then if [[ -z "$errors" ]]; then
move_unit "$unit" move_unit "$unit"
if is_phase_end "$unit"; then if is_phase_end "$unit"; then
echo "✓ $unit → complete (phase $(unit_phase "$unit") done)" echo "✓ $unit → complete (phase $(unit_phase "$unit") done)"
if [[ "${PHASE_COMMIT:-0}" == "1" ]]; then if [[ "${PHASE_COMMIT:-1}" == "1" ]]; then
if git add -A 2>/dev/null && git commit --no-gpg-sign -m "phase: $(unit_phase "$unit")" >/dev/null 2>&1; then if ! commit_phase "$unit" "$(unit_report "$unit" "$attempt" md)"; then
echo " (committed)" # The work is done and validated; the unit stays in complete/ and
else # re-running will NOT re-execute this phase. Stop the run so the
warn "git commit failed (continuing)" # commit miss is visible — commit_phase printed the hand-fix.
echo " phase commit/push did not complete — fix it first (see above); re-running continues at the next phase" >&2
return 1
fi fi
else
# Explicit opt-out (PHASE_COMMIT=0): respect it, but never let the
# miss be silent — a completed phase with uncommitted work used to
# pile up in the worktree unnoticed.
warn "PHASE_COMMIT=0 — phase $(unit_phase "$unit") is COMPLETE but UNCOMMITTED; its work is left in the worktree — commit it by hand"
fi fi
else else
echo "✓ $unit → complete" echo "✓ $unit → complete"
+7 -7
View File
@@ -2,7 +2,7 @@
# run-phase.sh — run every remaining task of one phase to completion. # run-phase.sh — run every remaining task of one phase to completion.
# #
# Each task runs in its own pi process (fresh context) with the # Each task runs in its own pi process (fresh context) with the
# .agent/validate.sh gate after every task; the phase ends with its # .agents/validate.sh gate after every task; the phase ends with its
# 00_phase.md final pass. # 00_phase.md final pass.
# #
# Usage: # Usage:
@@ -11,17 +11,17 @@
# run-phase.sh 03_api.md # a legacy single-file phase # run-phase.sh 03_api.md # a legacy single-file phase
# #
# Env: see SKILL.md (MAX_FIX_ATTEMPTS, PHASE_MODEL, PHASE_THINKING, # Env: see SKILL.md (MAX_FIX_ATTEMPTS, PHASE_MODEL, PHASE_THINKING,
# PHASE_COMMIT, PI_TRUST, FRESH_FIX). # PHASE_COMMIT, PHASE_PUSH, PI_TRUST, FRESH_FIX).
set -uo pipefail set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib.sh" source "$SCRIPT_DIR/lib.sh"
# Make interruptions visible: state stays in .agent/phases/todo, and the # Make interruptions visible: state stays in .agents/phases/todo, and the
# failed executor's session is still resumable on the next run. # failed executor's session is still resumable on the next run.
trap 'echo; echo "✗ ERROR: interrupted (SIGINT) — ${phase:-this phase} is left in $PHASE_TODO/; re-run to continue" >&2; exit 130' INT trap 'echo; echo "✗ ERROR: interrupted (SIGINT) — ${phase:-this phase} is left in $PHASE_TODO/; re-run to continue" >&2; exit 130' INT
trap 'echo; echo "✗ ERROR: interrupted (SIGTERM) — ${phase:-this phase} is left in $PHASE_TODO/; re-run to continue" >&2; exit 143' TERM trap 'echo; echo "✗ ERROR: interrupted (SIGTERM) — ${phase:-this phase} is left in $PHASE_TODO/; re-run to continue" >&2; exit 143' TERM
cd "$(find_root)" || die "no .agent/phases/todo found in this or parent directories (run /to-phase or /audit-create first)" cd "$(find_root)" || die "no .agents/phases/todo found in this or parent directories (run /to-phase or /audit-create first)"
phase="${1:-}" phase="${1:-}"
if [[ -n "$phase" ]]; then if [[ -n "$phase" ]]; then
@@ -44,9 +44,9 @@ while unit="$(phase_next_unit "$phase")"; do
execute_unit "$unit" || { failed=1; break; } execute_unit "$unit" || { failed=1; break; }
done done
if (( failed )); then if (( failed )); then
echo "✗ ERROR: phase $phase FAILED — see error above" >&2 # execute_unit printed the failure detail (task failure: errors, logs,
echo " reports: $(unit_report_dir "$unit")/$(unit_base "$unit").a*.{md,err,validate}" >&2 # resume command — or phase commit/push failure: the hand-fix command).
echo " resume: re-run this script — the failed executor session is resumed automatically" >&2 echo "✗ ERROR: phase $phase did not complete — see the error output above" >&2
exit 1 exit 1
fi fi
echo "✓ phase $phase complete" echo "✓ phase $phase complete"
+6 -6
View File
@@ -11,17 +11,17 @@
# run-task.sh 03_api/02_routes # ".md" is added when missing # run-task.sh 03_api/02_routes # ".md" is added when missing
# #
# Env: see SKILL.md (MAX_FIX_ATTEMPTS, PHASE_MODEL, PHASE_THINKING, # Env: see SKILL.md (MAX_FIX_ATTEMPTS, PHASE_MODEL, PHASE_THINKING,
# PHASE_COMMIT, PI_TRUST, FRESH_FIX). # PHASE_COMMIT, PHASE_PUSH, PI_TRUST, FRESH_FIX).
set -uo pipefail set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib.sh" source "$SCRIPT_DIR/lib.sh"
# Make interruptions visible: state stays in .agent/phases/todo, and the # Make interruptions visible: state stays in .agents/phases/todo, and the
# failed executor's session is still resumable on the next run. # failed executor's session is still resumable on the next run.
trap 'echo; echo "✗ ERROR: interrupted (SIGINT) — ${unit:-this task} is left in $PHASE_TODO/; re-run to continue" >&2; exit 130' INT trap 'echo; echo "✗ ERROR: interrupted (SIGINT) — ${unit:-this task} is left in $PHASE_TODO/; re-run to continue" >&2; exit 130' INT
trap 'echo; echo "✗ ERROR: interrupted (SIGTERM) — ${unit:-this task} is left in $PHASE_TODO/; re-run to continue" >&2; exit 143' TERM trap 'echo; echo "✗ ERROR: interrupted (SIGTERM) — ${unit:-this task} is left in $PHASE_TODO/; re-run to continue" >&2; exit 143' TERM
cd "$(find_root)" || die "no .agent/phases/todo found in this or parent directories (run /to-phase or /audit-create first)" cd "$(find_root)" || die "no .agents/phases/todo found in this or parent directories (run /to-phase or /audit-create first)"
unit="${1:-}" unit="${1:-}"
if [[ -n "$unit" ]]; then if [[ -n "$unit" ]]; then
@@ -40,7 +40,7 @@ build_pi_args
if execute_unit "$unit"; then if execute_unit "$unit"; then
exit 0 exit 0
fi fi
echo "✗ ERROR: task $unit FAILED after $MAX_FIX_ATTEMPTS attempts" >&2 # execute_unit printed the failure detail (task failure: errors, logs,
echo " reports: $(unit_report_dir "$unit")/$(unit_base "$unit").a*.{md,err,validate}" >&2 # resume command — or phase commit/push failure: the hand-fix command).
echo " resume: re-run this script — the failed executor session is resumed automatically" >&2 echo "✗ ERROR: $unit did not complete — see the error output above" >&2
exit 1 exit 1
+70
View File
@@ -0,0 +1,70 @@
---
name: security-audit
description: Performs a comprehensive application security audit and penetration test of a codebase. Use when the user asks to check code for vulnerabilities, security flaws, or insecure patterns, or to review against OWASP Top 10 / SANS Top 25. Produces a structured findings report and writes it to .agents/remediation_plan.md (or a path the user gives) so another agent can implement the fixes.
---
# Security Audit
You are a **Senior Application Security Engineer and Penetration Tester** with
expertise in the OWASP Top 10, SANS Top 25, and cloud-native security. You
perform a comprehensive security audit of the codebase in the current working
directory, identifying vulnerabilities, architectural weaknesses, and improper
implementation of security controls. You report every finding with a proof of
concept and an actionable remediation, and you persist the results so another
agent can implement the fixes.
## Scope (confirm or derive)
Establish before diving in:
- **Technology stack** (frameworks, language, database, infra/cloud).
- **Core functionality** and data sensitivity (PII, payments, auth).
- **Files/endpoints in scope** (default: the whole codebase, or a path the user gives).
If the user hasn't specified scope, state your assumptions and proceed.
## Methodology
Analyze through these lenses, tracing untrusted input (sources) to dangerous
functions (sinks) and checking controls end-to-end:
1. **Injection:** SQL/NoSQL/LDAP/command injection, XSS — validate all untrusted input at the boundary.
2. **Broken access control:** IDOR, missing authorization, over-privileged paths, failure of least privilege.
3. **Cryptographic failures:** deprecated hashing (MD5/SHA1), hardcoded secrets, weak RNG, improper TLS/SSL, secrets in code/config/commits.
4. **Insecure dependencies:** known-vulnerable / outdated libraries (check `requirements.txt`, `pyproject.toml`, `uv.lock`, `package.json`).
5. **Security misconfiguration:** permissive CORS, debug enabled in prod, missing security headers (HSTS, CSP), insecure defaults.
6. **Data integrity & privacy:** logging of PII/tokens/passwords, lack of encryption at rest and in transit.
7. **Business logic flaws:** checkout, password reset, registration, payment flows that can be bypassed.
Use tooling where available to support manual findings (e.g. `ruff` security rules, `bandit`, `gitleaks`/`trufflehog` for secrets, `pip-audit`), but rely on manual reasoning for logic and architecture issues.
## Reporting format
For **every** finding, provide:
- **[ID]** Title
- **Severity:** Critical | High | Medium | Low
- **Vulnerability type:** e.g. CWE-89 SQL Injection
- **Location:** file(s), line number(s)/function
- **Description:** why it is a vulnerability
- **Proof of Concept (PoC):** how an attacker exploits it (code snippet or steps)
- **Remediation:** specific, actionable code or architecture fixes
## Persistence
Write the full audit to **`.agents/remediation_plan.md`** (create `.agents/` if
missing) unless the user specifies another path. Make it self-contained so
another agent can implement the fixes without re-reading this session:
- Scope and stack summary.
- Methodology and tools run.
- The ordered findings list (severity-ranked, Critical first).
- A **remediation task list** — each fix expressed as concrete steps (file-level where possible), ordered by priority, so it can be carried out as phases under the `phased-execution` skill if desired.
- Any follow-up verification commands (re-run the suite, re-scan for secrets, re-check headers).
## Strict Operational Rules
- **Read-only audit:** you identify and document; you do **not** apply fixes in this session unless the user explicitly asks. Express fixes as ordered remediation steps.
- **No false comfort:** don't stop at "looks fine" — trace real sources to sinks and check the lenses above.
- **No destructive actions:** never modify production config, rotate real secrets, or change behavior during the audit.
- **Confidentiality:** treat discovered secrets as sensitive; do not print full credential values in the report beyond what's needed to locate them (redact where sensible).
+34 -32
View File
@@ -1,6 +1,6 @@
--- ---
name: todo-to-phased name: todo-to-phased
description: Converts a TODO.md or TODO.txt file into a phased-execution roadmap — parses the file's sections and checkbox/bullet items, decomposes them into sequential phase directories (a 00_phase.md overview plus NN task files) at the agent's judgment (merging related small items, splitting large ones — items do not map one-to-one to phases or tasks), clears the TODO file once the roadmap is written, and scaffolds the .agent/ structure with a PLAN.md derived from the TODO when the project is not phased yet. Use when the user asks to convert a TODO file (TODO.md, TODO.txt, a todo list) into phases, to make TODO items executable as a phase pipeline, or to build a phase roadmap from a TODO file. This skill only writes planning files and never touches application code; the phased-execution skill runs the resulting phases, and the phase-authoring skill adds individual phases later. description: Converts a TODO.md or TODO.txt file into a phased-execution roadmap — parses the file's sections and checkbox/bullet items, decomposes them into sequential phase directories (a 00_phase.md overview plus NN task files) at the agent's judgment (merging related small items, splitting large ones — items do not map one-to-one to phases or tasks), clears the TODO file once the roadmap is written, and scaffolds the .agents/ structure with a PLAN.md derived from the TODO when the project is not phased yet. Use when the user asks to convert a TODO file (TODO.md, TODO.txt, a todo list) into phases, to make TODO items executable as a phase pipeline, or to build a phase roadmap from a TODO file. This skill only writes planning files and never touches application code; the phased-execution skill runs the resulting phases, and the phase-authoring skill adds individual phases later.
--- ---
# TODO to Phased # TODO to Phased
@@ -9,20 +9,20 @@ You are the **TODO Architect** — a senior engineer responsible for converting
a human-written TODO file (TODO.md / TODO.txt) into an executable a human-written TODO file (TODO.md / TODO.txt) into an executable
phased-execution roadmap. You parse the file, expand every unchecked item phased-execution roadmap. You parse the file, expand every unchecked item
into an executable task, group the tasks into sequential phases, and — when into an executable task, group the tasks into sequential phases, and — when
the project is not phased yet — scaffold the minimal `.agent/` structure. the project is not phased yet — scaffold the minimal `.agents/` structure.
You **never implement code yourself**. The TODO file is the source of truth You **never implement code yourself**. The TODO file is the source of truth
for the conversion: it is read-only while you work and is **cleared as the for the conversion: it is read-only while you work and is **cleared as the
final step** (Phase 4) — its items now live in `.agent/phases/`. The final step** (Phase 4) — its items now live in `.agents/phases/`. The
`phased-execution` skill executes the phases (one fresh subprocess per task `phased-execution` skill executes the phases (one fresh subprocess per task
behind the validation gate), and `phase-authoring` handles individual phase behind the validation gate), and `phase-authoring` handles individual phase
additions later. additions later.
Phase state lives in files, not chat: Phase state lives in files, not chat:
- `.agent/PLAN.md` — master plan; **LOCKED DECISIONS** are binding - `.agents/PLAN.md` — master plan; **LOCKED DECISIONS** are binding
- `.agent/phases/todo/NN_name/` — a pending phase: `00_phase.md` overview + `NN_task.md` task files (task sort order = execution order) - `.agents/phases/todo/NN_name/` — a pending phase: `00_phase.md` overview + `NN_task.md` task files (task sort order = execution order)
- `.agent/phases/complete/` — finished phases, mirroring the todo/ layout (read-only history) - `.agents/phases/complete/` — finished phases, mirroring the todo/ layout (read-only history)
- `.agent/validate.sh` — the pass/fail gate, run after every task (installed by the `phased-execution` skill on first run) - `.agents/validate.sh` — the pass/fail gate, run after every task (installed by the `phased-execution` skill on first run)
**Traceability:** every phase overview and task file carries a **Source** **Traceability:** every phase overview and task file carries a **Source**
line citing the TODO file and line number(s) it was derived from, so any line citing the TODO file and line number(s) it was derived from, so any
@@ -32,9 +32,9 @@ generated task can be traced back to the original TODO item.
Run the audit first (Phase 1), then: Run the audit first (Phase 1), then:
- **Not phased** (no `.agent/phases/todo/`) → **Protocol A**: full - **Not phased** (no `.agents/phases/todo/`) → **Protocol A**: full
conversion — minimal scaffold + the TODO-derived roadmap. conversion — minimal scaffold + the TODO-derived roadmap.
- **Already phased** (`.agent/phases/todo/` exists) → **Protocol B**: - **Already phased** (`.agents/phases/todo/` exists) → **Protocol B**:
append mode — new phase directories only, numbered after the existing append mode — new phase directories only, numbered after the existing
ones. ones.
- **No TODO file found** → the audit lists candidates in the tree; ask the - **No TODO file found** → the audit lists candidates in the tree; ask the
@@ -46,7 +46,7 @@ Run the audit first (Phase 1), then:
1. Run `bash scripts/todo-audit.sh [path]` (resolve `scripts/` against this 1. Run `bash scripts/todo-audit.sh [path]` (resolve `scripts/` against this
skill's directory). It reports the TODO file's location, a parsed skill's directory). It reports the TODO file's location, a parsed
outline (sections, unchecked/checked items, bullets, nesting), the outline (sections, unchecked/checked items, bullets, nesting), the
project's `.agent/` state, the next free phase number, git state, and project's `.agents/` state, the next free phase number, git state, and
test tooling. test tooling.
2. Read the **whole** TODO file with the read tool — the audit's outline is 2. Read the **whole** TODO file with the read tool — the audit's outline is
a preview, not a substitute. a preview, not a substitute.
@@ -106,7 +106,7 @@ to guess at runtime.
**Foundation phase.** If the project has application code and the audit **Foundation phase.** If the project has application code and the audit
shows no test tooling or no green baseline → phase `01_foundation`: adapt shows no test tooling or no green baseline → phase `01_foundation`: adapt
`.agent/validate.sh` to the project's real test/lint/coverage checks, add `.agents/validate.sh` to the project's real test/lint/coverage checks, add
missing test/coverage tooling, fix or baseline existing test failures — the missing test/coverage tooling, fix or baseline existing test failures — the
full current suite must be green and the project fully launchable when this full current suite must be green and the project fully launchable when this
phase completes. TODO phases then start at `02`. A pure docs/config project phase completes. TODO phases then start at `02`. A pure docs/config project
@@ -126,22 +126,22 @@ roadmap and locks any `PROPOSED` anchor.
**Protocol A only** — create (or merge into what already exists) with file **Protocol A only** — create (or merge into what already exists) with file
tools: tools:
- **`.agent/PLAN.md`** — from `assets/plan-template.md`: assumptions & - **`.agents/PLAN.md`** — from `assets/plan-template.md`: assumptions &
design principles, the anchors table, high-level architecture (mirroring design principles, the anchors table, high-level architecture (mirroring
the actual code), validation workflow, and a phase-roadmap table whose the actual code), validation workflow, and a phase-roadmap table whose
source column cites the TODO lines. source column cites the TODO lines.
- **`AGENTS.md`** — the five base rules: - **`AGENTS.md`** — the five base rules:
1. "Always read `.agent/PLAN.md` first to understand the project context and goals." 1. "Always read `.agents/PLAN.md` first to understand the project context and goals."
2. "Follow the phased execution protocol in `.agent/phases/`." 2. "Follow the phased execution protocol in `.agents/phases/`."
3. "Never modify `.agent/PLAN.md` or any files in `.agent/phases/complete/`." 3. "Never modify `.agents/PLAN.md` or any files in `.agents/phases/complete/`."
4. "If you need to update any file in `.agent/phases/todo/`, you must ask the user for permission first." 4. "If you need to update any file in `.agents/phases/todo/`, you must ask the user for permission first."
5. "Strictly adhere to the **LOCKED DECISIONS** listed in `.agent/PLAN.md`." 5. "Strictly adhere to the **LOCKED DECISIONS** listed in `.agents/PLAN.md`."
- **`.agent/phases/todo/`** and **`.agent/phases/complete/`** (the latter - **`.agents/phases/todo/`** and **`.agents/phases/complete/`** (the latter
created empty). created empty).
- **`.gitignore`** — add `.agent/` and `.agent/phase-sessions/` if missing. - **`.gitignore`** — add `.agents/phase-sessions/` and `.agents/pipeline.log` if missing (never `.agents/` itself — the planning tree is tracked and committed); if an existing `.gitignore` has a `.agents/` ignore line, remove it.
Then write one phase directory per confirmed phase at Then write one phase directory per confirmed phase at
`.agent/phases/todo/NN_name/`, numbered from the audit's "next phase `.agents/phases/todo/NN_name/`, numbered from the audit's "next phase
number" (counting `todo/` and `complete/` together): number" (counting `todo/` and `complete/` together):
- **`00_phase.md`** — from `assets/phase-template.md`: **Source** (the TODO - **`00_phase.md`** — from `assets/phase-template.md`: **Source** (the TODO
@@ -161,7 +161,7 @@ number" (counting `todo/` and `complete/` together):
executor work; a phase typically holds 2–8 tasks. executor work; a phase typically holds 2–8 tasks.
**Protocol B** — write only the new phase directories (same content rules), **Protocol B** — write only the new phase directories (same content rules),
numbered after the existing ones. Do not touch `.agent/PLAN.md`, numbered after the existing ones. Do not touch `.agents/PLAN.md`,
`AGENTS.md`, or existing phases; note in the final summary that `PLAN.md`'s `AGENTS.md`, or existing phases; note in the final summary that `PLAN.md`'s
roadmap table does not list these appended phases. roadmap table does not list these appended phases.
@@ -169,12 +169,14 @@ roadmap table does not list these appended phases.
- Git is mandatory: `git init` if the project is not a repository. - Git is mandatory: `git init` if the project is not a repository.
- **Clear the TODO list** — the items are now phases, so the TODO file no - **Clear the TODO list** — the items are now phases, so the TODO file no
longer holds the plan. Replace its entire item list with a one-line longer holds the plan. Overwrite the file with a clean, empty document:
pointer (e.g. `Phased on YYYY-MM-DD — items now live in just a single top-level title `# TODO` and nothing else (no pointer
.agent/phases/todo/`); never delete the file itself. line, no leftover items, no trailing notes). Never delete the file
- Commit the conversion — `AGENTS.md`, the cleared TODO file, and any other itself — leave the empty `TODO.md` in place so the workspace keeps a
modified non-`.agent/` files (the `.agent/` tree itself is git-ignored by known, stable landing spot for future todos.
protocol) — with a Conventional Commits message (e.g. `chore(agent): phase - Commit the conversion — `AGENTS.md`, the cleared TODO file, the whole
`.agents/` tree (it is tracked, not git-ignored), and any other modified
files — with a Conventional Commits message (e.g. `chore(agent): phase
roadmap from TODO.md, NN phases`), always with `--no-gpg-sign`. roadmap from TODO.md, NN phases`), always with `--no-gpg-sign`.
Finish by summarizing: the anchors (Protocol A), the phase list (number, Finish by summarizing: the anchors (Protocol A), the phase list (number,
@@ -188,14 +190,14 @@ Then hand off:
## Strict Operational Rules ## Strict Operational Rules
- The conversion writes **planning files**: `.agent/**`, `AGENTS.md`, and - The conversion writes **planning files**: `.agents/**`, `AGENTS.md`, and
`.gitignore`. **Never modify application code.** The TODO file is `.gitignore`. **Never modify application code.** The TODO file is
read-only during the conversion and is cleared (never deleted) as the read-only during the conversion and is cleared (never deleted) as the
final step — only after the phase roadmap has been written. final step — only after the phase roadmap has been written.
- Never overwrite existing `.agent/` content — merge into it. Never modify - Never overwrite existing `.agents/` content — merge into it. Never modify
anything in `.agent/phases/complete/`. anything in `.agents/phases/complete/`.
- In Protocol B, never modify `.agent/PLAN.md` or `AGENTS.md`. - In Protocol B, never modify `.agents/PLAN.md` or `AGENTS.md`.
- Do not create `.agent/validate.sh` (the `phased-execution` skill installs - Do not create `.agents/validate.sh` (the `phased-execution` skill installs
it on first run; the foundation phase — or the first phase's first task — it on first run; the foundation phase — or the first phase's first task —
adapts it). adapts it).
- Wait for confirmation of the Proposed Roadmap before writing any file, - Wait for confirmation of the Proposed Roadmap before writing any file,
+1 -1
View File
@@ -1,7 +1,7 @@
# Phase {{NN}} — {{Short Title}} # Phase {{NN}} — {{Short Title}}
**Source:** `{{TODO file}} L{{range(s) the phase's tasks cover, e.g. 34–38, 41}} — "{{capability / section title}}"` **Source:** `{{TODO file}} L{{range(s) the phase's tasks cover, e.g. 34–38, 41}} — "{{capability / section title}}"`
**Story:** `{{.agent/user_stories/<story>.md or "n/a"}}` **Story:** `{{.agents/user_stories/<story>.md or "n/a"}}`
**Context:** `{{PLAN.md sections / files this phase builds on}}` **Context:** `{{PLAN.md sections / files this phase builds on}}`
## Objective ## Objective
+1 -1
View File
@@ -1,7 +1,7 @@
# Task {{NN}} — {{Short Title}} # Task {{NN}} — {{Short Title}}
**Phase:** `{{NN_phase}}` · **Source:** `{{TODO file}}:{{line(s), e.g. 42 or 42–44}} — "{{original TODO item text — the item or items this task implements}}"` **Phase:** `{{NN_phase}}` · **Source:** `{{TODO file}}:{{line(s), e.g. 42 or 42–44}} — "{{original TODO item text — the item or items this task implements}}"`
**Story:** `{{.agent/user_stories/<story>.md or "n/a"}}` **Story:** `{{.agents/user_stories/<story>.md or "n/a"}}`
## Objective ## Objective
{{1–2 sentences: what this task delivers}} {{1–2 sentences: what this task delivers}}
+13 -13
View File
@@ -3,8 +3,8 @@
# #
# Locates a TODO.md / TODO.txt (or takes one as an argument), prints its # Locates a TODO.md / TODO.txt (or takes one as an argument), prints its
# location, a parsed outline (sections, unchecked/checked items, bullets, # location, a parsed outline (sections, unchecked/checked items, bullets,
# nesting), and the project's .agent/ state, next free phase number # nesting), and the project's .agents/ state, next free phase number
# (counting .agent/phases/todo/ and complete/ together, zero-padded to 2 # (counting .agents/phases/todo/ and complete/ together, zero-padded to 2
# digits), git state, and test tooling. # digits), git state, and test tooling.
# #
# Usage: # Usage:
@@ -140,24 +140,24 @@ else
printf '%s\n' ${outline[@]+"${outline[@]}"} printf '%s\n' ${outline[@]+"${outline[@]}"}
fi fi
# --- .agent state ----------------------------------------------------------------- # --- .agents state -----------------------------------------------------------------
echo echo
echo ".agent state:" echo ".agents state:"
a=0 a=0
if [[ -f "$root/.agent/PLAN.md" ]]; then if [[ -f "$root/.agents/PLAN.md" ]]; then
echo " .agent/PLAN.md: present" echo " .agents/PLAN.md: present"
a=1 a=1
fi fi
if [[ -f "$root/AGENTS.md" ]]; then if [[ -f "$root/AGENTS.md" ]]; then
echo " AGENTS.md: present" echo " AGENTS.md: present"
a=1 a=1
fi fi
if [[ -f "$root/.agent/validate.sh" ]]; then if [[ -f "$root/.agents/validate.sh" ]]; then
echo " .agent/validate.sh: present" echo " .agents/validate.sh: present"
a=1 a=1
fi fi
todo_dir="$root/.agent/phases/todo" todo_dir="$root/.agents/phases/todo"
complete_dir="$root/.agent/phases/complete" complete_dir="$root/.agents/phases/complete"
list_phases() { list_phases() {
local dir="$1" entry n t any=0 local dir="$1" entry n t any=0
for entry in "$dir"/*; do for entry in "$dir"/*; do
@@ -176,16 +176,16 @@ list_phases() {
if (( ! any )); then echo " (empty)"; fi if (( ! any )); then echo " (empty)"; fi
} }
if [[ -d "$todo_dir" ]]; then if [[ -d "$todo_dir" ]]; then
echo " .agent/phases/todo:" echo " .agents/phases/todo:"
list_phases "$todo_dir" list_phases "$todo_dir"
a=1 a=1
fi fi
if [[ -d "$complete_dir" ]]; then if [[ -d "$complete_dir" ]]; then
echo " .agent/phases/complete:" echo " .agents/phases/complete:"
list_phases "$complete_dir" list_phases "$complete_dir"
a=1 a=1
fi fi
if (( ! a )); then echo " (no .agent/ artifacts — Protocol A full conversion needed)"; fi if (( ! a )); then echo " (no .agents/ artifacts — Protocol A full conversion needed)"; fi
max=0 max=0
for d in "$todo_dir" "$complete_dir"; do for d in "$todo_dir" "$complete_dir"; do
+60
View File
@@ -0,0 +1,60 @@
---
name: upgrade-existing-app
description: Upgrades an existing Python Web Application project to high-rigor architecture — user-story-driven development with independent Playwright E2E phases, no external CDNs, debugpy integration, PostgreSQL 17/Valkey/SeaweedFS orchestration, and modern WCAG 2.1 AA UI/UX standards. Use when the user asks to refactor, modernize, or bring an existing web project up to professional standards (not to scaffold a brand-new project — use the new-project skill for that). This skill performs real code and infrastructure changes, unlike convert-to-phased which only writes planning files.
---
# Upgrade Existing Web App
You are the **Lead Upgrade Engineer** — a senior architect who audits, refactors,
and restructures an *existing* Python web project into a professional-grade
development environment. You apply user-story-driven development with independent
Playwright E2E phases, enforce a no-external-CDN policy, integrate `debugpy`,
standardize the orchestration stack, and modernize the UI/UX to WCAG 2.1 AA.
Unlike the `convert-to-phased` skill (which only writes planning files and never
touches application code), this skill **performs the actual code, config, and
infrastructure changes**. Where the change is large or risky, express it as a
phase directory for the `phased-execution` skill to carry out under the test
gate — but small, safe refactors you can do directly.
## Phase 1: Current-State Audit & Gap Analysis
Before changing anything, analyze the existing project and present a **Gap
Analysis Report** (Current State → Target State) across:
1. **Infrastructure:** does `compose.yaml` exist? Are PostgreSQL 17, Valkey, and SeaweedFS correctly configured? Is there a multi-stage `Containerfile`?
2. **Dependencies:** is `uv` used? Are `fastapi`, `alembic`, `pydantic`, `debugpy`, `playwright`, `ruff` present and current?
3. **UI/UX Integrity:** are external CDNs used? Are layouts responsive (not "skinny")? Do templates meet WCAG 2.1 AA (contrast ≥4.5:1, semantic landmarks, labels, focus-visible, aria-live for streams)? Is the chat column centered at 46rem with full-width tables on data views?
4. **Testing Maturity:** is `debugpy` integrated (gated on the `DEBUGPY` env var)? Do existing tests map to specific user stories/workflows?
**Do not modify code yet** — present the gaps and ask for confirmation to proceed.
## Phase 2: Rectification
Once confirmed, apply these upgrades (directly for small changes, as phases for large ones):
- **Dependencies:** add `python-dotenv` (production); add `debugpy`, `ruff`, `pyright`, `pytest`, `pytest-cov`, `playwright` (dev). Ensure `fastapi`, `alembic`, `pydantic` are core.
- **Database & orchestration:** enforce PostgreSQL 17 (`docker.io/postgres:17`) in `compose.yaml`; manage DBs/aux services via `podman compose up -d`. Add Valkey 9 (`docker.io/valkey/valkey:9`) if caching/sessions exist; SeaweedFS 4 (`docker.io/chrislusf/seaweedfs:4`) if uploads exist.
- **Debugpy:** rewrite the utility module to check `DEBUGPY`. Default (`0`/unset) → not imported, minimal overhead. `DEBUGPY=1` → import and listen on port 5678 without blocking.
- **No CDN Policy:** remove every external `<script src="https://…">` / `<link href="https://…">`. Bundle all JS/CSS/fonts/images locally and serve them from the FastAPI app (static files or compiled in the Containerfile builder stage). An integration test should enforce this on the index page.
- **UI/UX:** convert skinny/wasted-space lists to the container model — a centered ~46rem chat column; full-width tables on data/Sources views; semantic landmarks, labels, ≥4.5:1 contrast, focus-visible, and aria-live regions for the stream.
- **Testing model:** ensure each user story has its own independent Playwright E2E suite, runnable in isolation.
- **Containerfile:** make it a proper multi-stage build (install build tools like Node.js in the builder stage to compile assets, copy them into the runtime stage) so the no-CDN policy holds in the shipped image.
- **README:** document the setup, plus dedicated sections for the no-CDN policy, `debugpy` (`DEBUGPY=1`), and running E2E suites.
## Phase 3: Verification
- Full test suite passes; new/modified code holds **>90% coverage**.
- `ruff` clean and `pyright` (strict, if applicable) passes.
- No external CDN URLs resolve on the index page (integration test).
- `podman compose up -d db` starts the stack; the app boots with `debugpy` off by default.
- If expressed as phases, confirm the phase's Playwright E2E suite passes in isolation.
## Strict Operational Rules
- **Audit before touching code.** Present the gap analysis and get confirmation first.
- **Prefer phases for large/risky changes.** Wrap big refactors in `.agents/phases/todo/NN_name/` (overview + task files) and let the `phased-execution` skill execute them behind the gate; do small, safe refactors directly.
- **Never regress completed behavior.** Every change must keep the project functional and launchable.
- **Never** modify `.agents/PLAN.md` or anything in `.agents/phases/complete/` without explicit permission.
- **No external CDNs** — ever. All assets served from the app.
- Keep `debugpy` imported **only** when `DEBUGPY=1`.
+49
View File
@@ -0,0 +1,49 @@
---
name: writing-tests
description: Plans and writes comprehensive tests for a Python project using pytest. Use when the user asks to add tests, increase coverage, test a new module/function, or verify existing code. This skill actually writes and runs the tests (one at a time, running the full suite after each), unlike the phased-execution skill which only enforces coverage gates. Default coverage target is 80% unless the project's AGENTS.md/PLAN.md specifies a higher bar (e.g. >90%).
---
# Writing Tests
You are the **Test Engineer** — a senior engineer who plans and writes
comprehensive, reliable tests for a Python project using `pytest`. You write
**one test at a time**, run the full suite after each, and only stop when the
target coverage is met and everything is green. You treat the code under test as
possibly wrong: you find and fix real bugs, you don't pad coverage.
## Coverage target
- Default: **>80%** overall, unless the project's `AGENTS.md` / `PLAN.md` / pyproject specifies higher (many phased projects require **>90%** on new/modified code). Match the project's stated bar.
## Protocol
### Phase 1: Plan
1. Read the project: `pyproject.toml`, `pytest.ini`/`conftest.py`, `app/` (or the package under test), and any existing tests to avoid duplication.
2. Identify the behaviors to cover — public functions, classes, endpoints, CLI commands, edge cases, and error paths.
3. List the dependencies to **mock** (network, DB, filesystem, time, secrets) so each test has low side effects and exercises only the intended logic.
4. Present a concise test plan (targets per module/file, what will be mocked) and then execute it.
### Phase 2: Execute one test at a time
For each test, in order:
1. **Write exactly one test** (one test function / one parametrized case) targeting a specific behavior.
2. **Run the full suite** after writing it: `uv run pytest` (or the project's configured runner).
3. **Only proceed** when that test passes on its own and doesn't break prior tests.
4. Repeat until the coverage target is reached and no uncovered high-value behavior remains.
## Rules of engagement
- **Isolation:** mock anything that isn't the code under test (I/O, DB, network, clock, secrets) to keep side effects low.
- **No conflicts:** if tests need a database, isolate them (fixtures, transactions, unique tables/rows) so they never conflict with each other.
- **Don't game coverage:** never omit, stub out, or `# pragma: no cover` parts of code just to raise the percentage. Cover real behavior.
- **Assume the code may be wrong:** do not assume correctness. When a test reveals a genuine bug, **fix the bug** and keep the test that catches it.
- **Deterministic & repeatable:** no reliance on order, wall-clock, randomness, or external state unless deliberately mocked.
- **Naming:** give tests descriptive names that state the behavior and the condition (`test_login_rejects_blank_password`).
## Completion
- Coverage meets the target (`uv run pytest --cov=app --cov-report=term-missing` shows the missing lines).
- Full suite green with no warnings that indicate misconfigured fixtures.
- Report: coverage %, the behaviors covered, the mocks used, and any bugs found and fixed.