---
name: ayf:go
description: |
  Full /go cycle: observe, lock, plan, verify, build, review, test, learn, finalize.
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Glob
  - Grep
  - Agent
  - AskUserQuestion
---

# /go -- Full Build Cycle

This is the core command. It runs the complete task lifecycle from picking a task to shipping it.

## Context-Pressure Check (run at the start of every phase)

Before beginning **each** phase below, check how full the context window is — long
`/go` runs die when the window fills mid-build and unsaved reasoning is lost. The
`context-pressure.sh` UserPromptSubmit hook surfaces this automatically each turn,
but also self-check at phase boundaries:

- **≥ 60% full** → finish the current phase, then `/compact` (or `/pause` if mid-BUILD)
  before starting the next one. Summarize large tool results instead of keeping them
  verbatim; delegate remaining big reads to a subagent (see Self-Inventory in CLAUDE.md).
- **≥ 85% full** → stop now. `/pause` to snapshot state to `.ay/sessions/`, then
  `/compact` or resume in a fresh session. Do not start a new phase at this level.

This is advisory and never blocks — but ignoring a red alert risks losing work.

## Phase 0: BOARD CHECK (First Contact gate)

Before observing or locking anything, decide whether this project has **any tasks
at all**. This decision is based on the **contents of BOARD.md ONLY** — never on
whether `.ay/state.json` exists.

> Why not `state.json`? The installer pre-creates `.ay/state.json`, so the
> `state.json`-based "is this a fresh install?" auto-detection in CLAUDE.md never
> fires on a real install. `/go` therefore performs its own explicit, BOARD-based
> emptiness check so First Contact still triggers regardless of `state.json`.

1. Resolve `.ay/` and read BOARD.md:
   ```bash
   AY="$(dirname "$(git rev-parse --git-common-dir 2>/dev/null)")/.ay"
   # Count real task rows: table rows whose first cell is a numeric task id.
   # Excludes headers, the `|---|` separator, and prose.
   task_rows=$(grep -E '^\|\s*[0-9]+\s*\|' "$AY/tracking/BOARD.md" | wc -l | tr -d ' ')
   echo "task_rows=$task_rows"
   ```

2. **If `task_rows` is 0** (BOARD has no task rows — a fresh or empty project):
   - Print exactly: `No tasks found — starting First Contact to set up your project.`
   - **Auto-invoke the First Contact Protocol** (defined in CLAUDE.md). Do NOT stop,
     and do NOT wait for the user to ask — the transition is automatic.
   - Do this **even if `.ay/state.json` already exists.** Presence of `state.json`
     must not suppress First Contact; only a non-empty BOARD does.
   - When First Contact finishes and tasks have been written to BOARD.md, re-read
     BOARD.md and continue to Phase 1 (OBSERVE) normally in the same `/go` run.
   - If First Contact ends without producing any tasks (user aborted), stop with a
     short note — there is nothing to build yet.

3. **If `task_rows` > 0**, proceed to Phase 1 (OBSERVE) as normal. A BOARD that has
   tasks but none currently READY is a *different* case, handled in Phase 1 — do not
   trigger First Contact for it.

## Phase 1: OBSERVE

1. Check for paused sessions in `.ay/sessions/pause-*.md`. If one exists, ask: "Found paused session from {timestamp}. Resume it or start fresh?"
2. Read `.ay/tracking/BOARD.md` to see all tasks and their statuses.
3. Check `.ay/tracking/locks/` for any active lock files. Locked tasks are off-limits.
4. Pick the best READY task using this priority:
   - Highest priority first (P0 > P1 > P2 > P3)
   - No unresolved blockers
   - Dependencies already DONE
   - If multiple equal candidates, pick the one with the most downstream dependents
5. Present the selected task to the human. If the BOARD has tasks but none are
   currently READY (all are BLOCKED/IN PROGRESS/DONE), say so and stop — this is
   distinct from the empty-BOARD case, which Phase 0 already handled by triggering
   First Contact.

## Phase 2: LOCK

1. Create lock file at `.ay/tracking/locks/task-{N}.lock` with content:
   ```
   agent: {agent-name}
   task: {task-number}
   started: {ISO timestamp}
   session: {session-id}
   ```
2. Update `.ay/tracking/BOARD.md`: move task status from READY to IN PROGRESS.

## Phase 3: PLAN

1. Read the task file at `.ay/tasks/task-{N}.md`.
2. Read the agent definition if one is assigned.
3. Read relevant skills referenced by the task.
4. Read `.ay/tracking/HANDOFFS.md` for prior learnings.
5. Read `.ay/tracking/DECISIONS.md` for architectural constraints.
6. Check what already exists in the codebase (files, patterns, conventions).
7. If the task references external APIs or libraries, fetch real documentation via MCP or web search. Never guess API shapes.
8. If you are unclear about how any part of the ay-framework works (MCPs, autonomous mode, agent setup, the janitor), open the relevant guide in `Human/` before asking the human or guessing. `Human/index.html` is the entry point — no server needed.
9. Create the plan folder `.ay/plans/task-{N}/` with these files:

   - **README.md** -- Plan overview: goal, approach, key decisions, risks.
   - **context.md** -- Relevant codebase context: existing patterns, conventions, related files.
   - **rules.md** -- 13 universal rules + task-specific rules. Universal rules:
     1. Never modify files outside your agent scope without explicit approval
     2. Every new file must have a clear single responsibility
     3. No hardcoded secrets, keys, or environment-specific values
     4. All public functions/methods must have doc comments
     5. Follow existing naming conventions in the codebase
     6. No TODO/FIXME/HACK without a linked task number
     7. Error handling must be explicit, never swallowed
     8. No circular dependencies
     9. Tests must be deterministic (no flaky tests)
     10. No console.log/print in production code (use proper logging)
     11. Imports must be explicit (no wildcard imports in production)
     12. No dead code committed
     13. Every file change must be traceable to a plan step
   - **files.md** -- Complete list of files to create/modify/delete with purpose for each.
   - **sequence.md** -- Ordered build steps. Each step has: description, files involved, checkpoint type.
   - **tests.md** -- Test plan: what to test, how, expected results, mapped to requirements.
   - **api-reference.md** -- External API signatures, endpoints, types used in this task.
   - **schema.md** -- Data models, type definitions, interfaces introduced or modified.
   - **diff-from-plan.md** -- Starts empty. Filled during BUILD with any deviations from plan.
   - **references/** -- Subfolder for any reference docs, examples, or external material.

## Phase 4: VERIFY

Run the 8-dimension plan quality check (same as `/verify-plan`):

1. **Requirement coverage** -- Every requirement in the task maps to at least one build step and one test.
2. **Task atomicity** -- No single step touches more than 5 files.
3. **Dependency ordering** -- No step references output from a later step.
4. **File scope** -- All files are within the agent's declared scope. Total files < 30.
5. **Test mapping** -- Every requirement has at least one test.
6. **Context fit** -- Plan folder total content < 2000 lines.
7. **Gap detection** -- No missing exports, unhandled error paths, or undefined types.
8. **Rules compliance** -- All 13 universal rules are addressed in rules.md.

If any dimension FAILS, fix the plan before proceeding. Re-verify after fixes.

### Ghost-op scan (human-only operations)

Run the executable gate over the plan folder. It rejects any plan step or command
containing a human-only operation -- `git push`, `git merge`, `gh pr create`/`merge`,
or `npm`/`yarn`/`pnpm publish`:

```bash
bin/ayf-ghost-scan .ay/plans/<task>/     # exit 1 + file:line offenders if a ghost op is present
```

On a non-zero exit it prints `GHOST-OP DETECTED` and each offending `file:line`.
Strip the offending step(s) from the plan and re-verify. Agents commit only -- they
never push, merge, open/merge PRs, or publish; the human manages those. (The same
ops are blocked at runtime by the operator-guardrails hook, task 80 -- this is the
earlier, plan-time gate.)

## Phase 5: HUMAN APPROVAL GATE

Present the plan to the human with:
- Task summary (1-2 sentences)
- File count (create/modify/delete)
- Step count
- Test count
- Any risks or open questions
- Estimated complexity (S/M/L)

Wait for response:
- **"go"** -- Proceed to BUILD.
- **"change X"** -- Modify the plan as requested, re-verify, re-present.
- **"skip"** -- Unlock the task, revert BOARD status to READY, stop.

Do NOT proceed without explicit human approval.

## Phase 6: BUILD

Follow the sequence from `.ay/plans/task-{N}/sequence.md` step by step.

### Checkpoint Types

Each step in the sequence has a checkpoint type:

- **[auto]** -- Verify programmatically (build passes, tests pass, types check). Proceed automatically.
- **[human-verify]** -- Show the human what was built. Wait for confirmation before continuing.
- **[decision]** -- Present options to the human. Wait for a choice before continuing.
- **[human-action]** -- Something the human must do (e.g., create an API key, configure a service). Wait for them to confirm completion.

### Build Rhythm

- After every 3-5 files changed, run the build/typecheck/lint cycle.
- If a build fails, fix it before proceeding. Do not accumulate broken state.
  Retries are capped — see **Fix-Loop Cap** below (max 3 attempts per checkpoint,
  then escalate).
- Log any deviations from the plan in `.ay/plans/task-{N}/diff-from-plan.md`.

### Build Rules

- Follow the sequence order exactly. Do not skip ahead.
- If a step is blocked by something unexpected, stop and ask the human.
- If you discover the plan is wrong, update `diff-from-plan.md` and ask the human before deviating.

### Fix-Loop Cap (max 3 attempts per checkpoint)

When a checkpoint fails and you retry the fix, you MUST cap retries at **3
consecutive failed attempts for the same checkpoint**. Never loop indefinitely —
a runaway fix loop burns tokens and makes no progress. Attempt counts persist
across tool calls in `.ay/tracking/fix-loop-state.json` so the cap survives even
if context is summarized mid-build.

**State file** — `.ay/tracking/fix-loop-state.json`:

```json
{
  "task": 66,
  "checkpoint": "step-4-typecheck",
  "attempts": 2,
  "errors": [
    "tsc: Cannot find name 'Foo' (src/a.ts:12)",
    "tsc: Property 'bar' does not exist (src/a.ts:20)"
  ],
  "updated": "2026-07-12T14:00:00Z"
}
```

Use a stable `checkpoint` key per sequence step (e.g. `step-{N}-{type}`). Resolve
the file with the standard resolver:
```bash
AY="$(dirname "$(git rev-parse --git-common-dir 2>/dev/null)")/.ay"
STATE="$AY/tracking/fix-loop-state.json"
```

**On each checkpoint result:**

1. **Checkpoint PASSES** → reset the counter for that checkpoint to `0` (clear its
   entry, or write `attempts: 0` with an empty `errors` array). A fresh checkpoint
   always starts from a clean slate.
2. **Checkpoint FAILS** →
   - Increment `attempts` for that checkpoint and append a **one-line summary** of
     the failure (the key error, not the full log) to `errors`. Update `updated`.
   - If `attempts < 3`: attempt one more fix, then re-run the checkpoint.
   - If `attempts == 3`: **STOP. Do not attempt a 4th fix.** Escalate (below).

**Escalation after 3 failed attempts:**

1. Print an escalation message that **names the failing checkpoint and lists the 3
   error summaries** from `errors`, e.g.:
   ```
   ESCALATION — task {N}, checkpoint {checkpoint} failed 3 times, stopping.
   Attempt 1: {errors[0]}
   Attempt 2: {errors[1]}
   Attempt 3: {errors[2]}
   Needs a human decision — I will not attempt a 4th fix.
   ```
2. **Automatically write a BLOCKER entry** to `.ay/tracking/BLOCKERS.md`. Append a
   new row to the table (next free `B-NN` id):
   ```
   | B-NN | Fix-loop cap hit on task {N}, checkpoint {checkpoint}: 3 consecutive failed fixes. Last errors: {errors joined}. | {N} | {agent} | OPEN | {YYYY-MM-DD} |
   ```
3. **Ping the human and pause the session** rather than looping — save state with
   the equivalent of `/pause` (snapshot to `.ay/sessions/pause-{timestamp}.md`) and
   surface a notification (PushNotification if available). Wait for human direction;
   do not resume the same checkpoint automatically.
4. Leave `fix-loop-state.json` intact so the human can see the attempt history. It
   is reset when the human resolves the blocker and the checkpoint next passes.

The cap is **per checkpoint**: passing checkpoint A resets A's counter; a later
failure at checkpoint B starts B at attempt 1. Only *consecutive* failures at the
*same* checkpoint count toward the 3-strike limit.

## Phase 6.5: REVIEW GATE (ayf-server verdict)

As soon as BUILD produces something runnable — and before the deep SELF-REVIEW in
Phase 7 — put the work in front of the reviewer and **block on a verdict**. This is
the fast "is this even right?" gate; Phase 8 is the full human-review loop.

1. **Is ayf-server up?** Probe the feedback server:
   ```bash
   curl -sf http://localhost:3847/health >/dev/null 2>&1 && echo up || echo down
   ```
   - **down** → start it if available, else skip this gate (note it and go to Phase 7):
     ```bash
     [ -f bin/ayf-server.py ] && python3 bin/ayf-server.py --task {N} --port 3847 &
     sleep 1
     ```
2. **Trigger a review pack** for the current task:
   ```
   /review-pack {N}
   ```
   This writes `.ay/reviews/task-{N}/review-pack.html` and registers it with
   ayf-server. Then surface it:
   ```
   Review ready: http://localhost:3847/task-{N}
   ```
   (Fire `PushNotification` / `cmux notify` so the operator sees it.)
3. **Wait for `/verdict` before proceeding.** Do not advance to Phase 7 until a
   verdict lands. Poll for it (max ~10 min), or accept a pasted `/verdict`:
   ```bash
   # /verdict writes .ay/reviews/task-{N}/verdict.json → {"verdict":"pass|fail|changes", "notes":"..."}
   for _ in $(seq 1 20); do
     [ -f ".ay/reviews/task-{N}/verdict.json" ] && break
     sleep 30
   done
   ```
   - **pass** → proceed to Phase 7.
   - **changes / fail** → apply the requested changes (respect the Phase 6 fix-loop
     cap: 3 strikes per checkpoint → escalate), then re-run `/review-pack {N}` and
     wait for a fresh `/verdict`.
   - **timeout / ayf-server down** → note that the gate was skipped and continue to
     Phase 7; the full Phase 8 human-review loop still runs before TEST.

Never skip straight to Phase 7 while a `fail`/`changes` verdict is outstanding.

## Phase 7: SELF-REVIEW

Two passes over all changes:

### Pass 1: Critical (must fix before proceeding)
- Syntax errors
- Type errors
- Missing imports/exports
- Broken references
- Security issues (hardcoded secrets, SQL injection, XSS)
- Logic errors (off-by-one, null handling, race conditions)

### Pass 2: Quality (fix if reasonable, note if not)
- Code style consistency
- Naming clarity
- Documentation completeness
- Error message quality
- Edge case handling
- Performance concerns

Fix all Critical issues. Fix Quality issues that take < 2 minutes. Note remaining Quality issues for the human.

Run the full build + typecheck + test suite after fixes.

## Phase 8: HUMAN REVIEW (automated review loop)

### 6a. Agent self-test

Run /self-test {N}:
- Uses ayb to walk every use case in `.ay/plans/task-{N}/tests.md`
- If ayb unavailable (ayb ping fails), skip to 6c with note
- Writes `.ay/reviews/task-{N}/agent-findings.json`

### 6b. Generate review pack

Run /review-pack {N}:
- Reads agent-findings.json + tests.md
- Generates `.ay/reviews/task-{N}/review-pack.html` with inline base64 screenshots
- Starts ayf-server if available:
    ```
    python3 bin/ayf-server.py --task {N} --port 3847 &
    sleep 1
    ```
- Opens in browser:
    ```
    open http://localhost:3847/task-{N}   # macOS
    xdg-open http://localhost:3847/task-{N}   # Linux
    ```
  Falls back to: tell human to open `.ay/reviews/task-{N}/review-pack.html`

### 6c. Notify human

Use PushNotification:
  title: "Task #{N} ready for review"
  body: "http://localhost:3847/task-{N}"

Also print:
  ```
  Review pack ready: http://localhost:3847/task-{N}
  Direct file: .ay/reviews/task-{N}/review-pack.html
  ```

### 6d. Wait for feedback

If ayf-server running: poll `.ay/reviews/task-{N}/human-review-round-1.json` every 30s (max 10 min)
If no server: wait for human to paste the "Copy Prompt" output

### 6e. Process feedback

- All PASS or human wrote "approved": proceed to TEST phase
- Any FAIL: fix the failures, re-run /self-test {N}, re-run /review-pack {N} (round 2)
- Max 3 rounds, then stop and ask human how to proceed

## Phase 9: TEST

1. Run the full test suite.
2. Verify every requirement from the task file is covered by a passing test.
3. Verify the build completes without errors.
4. If any test fails, fix it and re-run. If a fix is non-trivial, escalate to the human.

## Phase 10: LEARN

> This is the "Phase 11" HANDOFF gate referenced on the board — the HANDOFF
> entry is written here, in LEARN, not in FINALIZE below.

1. Update `.ay/plans/task-{N}/diff-from-plan.md` with final deviations.
2. Extract gotchas into a HANDOFF entry using the canonical schema (required
   fields: `To`, `From`, `Task`, `Date`, `Summary`; optional `Detail`):

   ```
   ---
   To: {target-agent or "all"}
   From: {agent-name}
   Task: {N}
   Date: {YYYY-MM-DD HH:MM}
   Summary: {one-line summary}
   Detail: {gotchas, API discoveries, what downstream agents must know}
   ---
   ```

   Validate the entry through the gate **before** writing it to
   `.ay/tracking/HANDOFFS.md`:

   ```bash
   printf '%s' "$ENTRY" | bin/ayf-validate-handoff.sh -
   ```

   If the validator exits non-zero, it lists the missing/invalid fields. Fix
   the entry and re-validate. Only append to `HANDOFFS.md` once it exits 0 — do
   not write an entry that fails validation.
3. If any learnings apply broadly, add them to `.ay/learnings.jsonl`.

## Phase 11: FINALIZE

1. Delete lock file `.ay/tracking/locks/task-{N}.lock`.
2. Update `.ay/tracking/BOARD.md`: move task to DONE with completion timestamp.
3. Check if completing this task unblocks other tasks. Move any BLOCKED tasks to READY if all their dependencies are now DONE.
4. Append entry to `.ay/tracking/AGENTS-LOG.md`:
   ```
   ## Task {N}: {title}
   - Agent: {agent}
   - Started: {timestamp}
   - Completed: {timestamp}
   - Files: {count} created, {count} modified, {count} deleted
   - Deviations: {count}
   - Learnings: {count}
   ```
5. Append entry to `.ay/tracking/CHANGELOG.md` under the current version/date.

## Phase 12: NEXT

Report what was done:
- Task completed
- Time spent (if trackable)
- Files touched
- Tests added

List available READY tasks from BOARD.md for the next cycle.
