---
name: peaks-code
description: Code-domain loop engineering orchestrator for the Peaks-Loop skill family. Use when the user asks Peaks-Loop to handle a code-repo workflow end-to-end (端到端/全流程/需求开发), especially from a product document (PRD/飞书文档/Feishu doc) through implementation and validation. Coordinates peaks-prd, peaks-rd, peaks-qa, peaks-ui, peaks-sc, and peaks-txt while preserving user confirmation gates. Triggers on `/peaks-code`, "peaks code", "全流程开发", "端到端迭代". General primitives (peaks-resume / peaks-status / peaks-test) are sibling skills, not children.
---

<!-- peaks:loop-hygiene — HAND-MAINTAINED block, NOT generated; byte-identical in every SKILL.md, enforced by tests/unit/skills/loop-hygiene-block.test.ts. Edit one, edit all 23. -->

## Loop hygiene (every turn — MANDATORY)

**Skill header.** While this skill is active, open every turn with
`Peaks-Loop Skill: <skill> | Peaks-Loop Role: <role> | Peaks-Loop Gate: <gate> | Peaks-Loop Context: <ratio%> (<zone>) | Next: <one short action>`.
Every turn, not only the first — it is how the user knows which skill is driving.
`Role` and `Context` are machine facts: copy them from `peaks skill presence --json`
(`data.role`, `data.context.ratioPct`, `data.context.action`) — never invent them.

**Context is this skill's own business.** Run `peaks skill presence --json` every turn and
read its `context` block. When `action` is `auto-fire`, `pre-compact`, or `red-line`,
run `peaks code auto-compact --project .` **yourself**, then continue. Tell the user the
ratio in one line if it helps, but never hand them the compaction step: asking the user to
run `/compact` is the regression the zero-pause contract forbids. This holds in **every
mode** — standard *and* 24h. The mode moves the threshold, never the obligation.

**Read before you edit.** Read a file before your first `Edit` / `Write` / `MultiEdit` on
it — the normal way to work here — for every path outside `.peaks/**` (source, tests, docs,
config); `.peaks/**` writes are exempt.

**Expect one denial per file anyway — and do NOT pre-empt it.** A `PreToolUse` gate (ECC's
"Fact-Forcing Gate") denies the FIRST edit a session makes to any given path, once, by
design. Reading does NOT prevent it: the gate keys on the path's first touch, not on whether
you read it. **Do not recite its four questions before every edit** — it asks when it wants
them, and reciting unprompted burns a round-trip per file for nothing. Answer only when a
denial actually arrives.

**When one does arrive:** a denial is not a failure and the tool is not broken — your edit
was NOT applied. State the facts it asks for (importers, affected API, data schemas if any,
the user's verbatim instruction), then retry the SAME operation. The retry is allowed. Do not
switch tools, do not give up, do not retry blindly. One more thing worth knowing: an idle gap
of ~30 minutes clears the gate's "already passed" list, so a file you cleared earlier can be
denied again after a long pause. That is the gate resetting, not you regressing.
<!-- /peaks:loop-hygiene -->

> **Detached sub-agent mode (Phase A, slice 2026-08-10).** When the orchestrator requires true parallelism with isolated context windows and survives orchestrator session exit, dispatch sub-agents with `--mode detached --vendor <claude|codex|copilot>`. The CLI spawns a real OS process via `ProcessSupervisor` (Windows `DETACHED_PROCESS` + `CREATE_NEW_PROCESS_GROUP`, POSIX `setsid` + `nohup`); the child vendor LLM receives a 5–8KB minimum prompt slice (no orchestrator session history) and, via the `<peaks-auto-compact>` marker, is told to persist durable state to `.peaks/_runtime/<sid>/detached/<rid>/compact/<n>.json` before its own harness compacts the session (G8, corrected 2026-09-13 rid `2026-09-13-defects-e`: the child cannot compact itself and nothing is spliced back into its prompt; peaks runtime simply has no token-cost throttle, which is not the same as a granted budget). Orchestrator MUST emit one line of prose before every detached dispatch: `⏳ Spawning detached sub-agent via <vendor>: rid=<rid> (ETA ~60s)`. Status is read from `.peaks/_runtime/<sid>/detached/<rid>/status.json`; `LifecycleOwner` enforces 100% cleanup of `pid` / `log.txt` / `status.json` / `owner-session` on every exit path. `--no-throttle --max-concurrent <N>` bypasses `ResourceBudgetGuard` (user accepts risk; default max=8). See `references/sub-agent-dispatch.md` §"Detached Mode" for the full contract. Default mode remains `in-process` for backward compat (existing 106+ dispatch tests untouched).
---

## Scope (RL-8 — red line, locked 2026-07-08)

`peaks-code` is a **code-domain long-task loop engineering orchestrator; not a general-purpose orchestrator.**

This is RL-8, stated in `.peaks/standards/loop-engineering-guidelines.md` (the 2026-07-07
crystallization design spec that first wrote it, §0.4 and §10, was retired from the tree in
commit `e6e35842`).
The boundary is closed under this slice:

- **In scope:** end-to-end code-domain workflows — repository scanning, RD planning, code implementation via RD, QA verification, UI changes inside a code repo, source-control handoff, and code-repo context packaging. Coordinated role skills: `peaks-prd`, `peaks-rd`, `peaks-qa`, `peaks-ui`, `peaks-sc`, `peaks-txt`.
- **Out of scope:** research / content / product / medical / non-code domains. Each of those ships as an independent `peaks-*` skill that imports `.peaks/standards/loop-engineering-guidelines.md` and passes `peaks skill lint --category loop-engineering-readiness`. They are **not** subclasses or variants of `peaks-code`.
- **Failure modes this rule prevents:** (a) `peaks-code` widening into a general orchestrator; (b) non-code capabilities being smuggled into `peaks-code`; (c) other domains being expressed as "peaks-code variants".
- **Self-check:** before any new peak-* capability is added here, ask "is this code-domain?" If the answer is no, the right move is a new `peaks-*` skill, not an extension of `peaks-code`.

## Single-scope-axis naming convention (2.7.1)

The `.peaks/` workspace has a **single scope axis** (session-id) plus a nested **sub-agent axis** under `.peaks/_sub_agents/<sessionId>/...`. Use `<sessionId>` (NEVER bare `<sid>`). Reviewable artifacts live at `.peaks/_runtime/<sessionId>/<role>/...` (gitignored); the change-id is an optional filename slug and does NOT route filesystem writes. CLI: session-id → `peaks session *`; sub-agent → `peaks sub-agent *`. Normative by documentation only — the guard that once asserted (a) zero bare `<sid>`, (b) axis labels, and (c) this callout's presence was deleted in `457b9a87`. Comply by convention.

## Karpathy guidance (Slice 1/6 — karpathy prompt-injection-lift)

Every sub-agent dispatch (`peaks-prd`, `peaks-rd`, `peaks-qa`, `peaks-ui`, `peaks-sc`, `peaks-txt`) MUST receive the 4 Karpathy guidelines. Append the verbatim block from `skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md` §"Karpathy-guidelines context" to the dispatch prompt. Canonical skill id: `andrej-karpathy-skills:karpathy-guidelines`. Summary: **#1 Think Before Coding**, **#2 Simplicity First**, **#3 Surgical Changes**, **#4 Goal-Driven Execution**.

## Hard ban (effective 2.8.3 — read every session, no exceptions)

Never create `.peaks/_runtime/<YYYY-MM-DD-*>/` at the top level of `.peaks/`. ALL reviewable artifact dirs live under `.peaks/_runtime/<sessionId>/<role>/...` (gitignored) — never as siblings of `.peaks/_runtime/`. `peaks workspace init` creates only `.peaks/_runtime/<sessionId>/session.json`. If you find yourself about to write a date-prefixed directory directly under `.peaks/`, STOP and reroute under `.peaks/_runtime/<sessionId>/`. The `.gitignore` rule + vitest guard at `tests/unit/workspace/top-level-change-id-guard.test.ts` enforce this.

# Peaks-Loop Code

Peaks-Loop Code is the orchestration facade for the Peaks-Loop short skill family. Use it to identify the user scenario, recommend an execution mode, coordinate role skills, and produce the final handoff report. Do not collapse role responsibilities into this skill.

## 产品定位(2026-06-28 校准)

> peaks-loop 真实定位 = 24h AI 程序员编排器;user 角色 = 业务/产品审阅者,不参与技术决策。详见 `.peaks/memory/peaks-cli-24h-ai-programmer-positioning.md`。

## Skill-first architecture note (read once, internalise)

This skill is the **primary surface**. The `peaks <cmd>` CLI is **auxiliary** — invoked by the skill prompt only when a primitive is the right tool. Behaviour only an LLM in a skill prompt would use lives **here in the SKILL.md**.

## Code-Change Red Line (BLOCKING — read before ANY tool call)

**Peaks-Loop Code is an orchestrator, NOT an implementer. You MUST NOT write, edit, or modify any application source code directly.** Every code change goes through `peaks-code → RD → QA → verdict`. **If you catch yourself about to write code, STOP.** Hand off to RD. Before declaring workflow complete, run `peaks workflow verify-pipeline --rid <rid> --project <repo> --json`.

### Hard-blocked path families (the orchestrator may NOT directly Edit/Write these)

| Family | Examples |
|---|---|
| `src/` | `src/services/foo.ts`, `src/cli/commands/x.ts` |
| `tests/unit/` | `tests/unit/services/foo.test.ts` |
| `tests/integration/` | `tests/integration/x.test.ts` |
| `config/` | `config/peaks.json`, `tsconfig.json` |
| `bin/` | `bin/peaks.js` |
| `scripts/` | `scripts/release-pack.mjs` |

ANY direct `Edit` / `Write` / `MultiEdit` of these paths from the orchestrator context is a **hard error**. The orchestrator's role is ONLY to dispatch sub-agents; it never owns a code-change tool call against these families.

### Allowed path families (orchestrator may touch freely)

- `.peaks/**` (memory sediment, project metadata, audit logs)
- `.peaks/_runtime/**` (session-bound reviewable artifacts, gitignored)
- `skills/**/SKILL.md` and other skill manifest files (orchestrator self-documents)
- `docs/**` (governance / spec / plan docs)

These families are non-source-code; the orchestrator may `Edit`/`Write` them directly (memory sediment, SKILL.md prose updates, doc snapshots). The PreToolUse hook + the `orchestrator-can-do` probe do NOT block these.

### Code-Gate (slice 2026-08-06-codegate-vendor-neutral)

Two-layer enforcement — do NOT try to bypass either:

1. **LLM-level guard — `peaks code orchestrator-can-do`** (Step 0.51). Before any Edit/Write/MultiEdit tool call, run:
   ```bash
   peaks code orchestrator-can-do --slice-spec '<your task>' --json
   ```
   For source-code changes (mentioning `src/`, `tests/unit/`, `tests/integration/`, `config/`, `bin/`, `scripts/`) the probe MUST return `canDoInSession: false` with `blockers: ["requires-sub-agent-dispatch"]`. The probe does NOT block non-source slices (memory sediment, docs, SKILL.md updates).

2. **Tool-level guard — `peaks code-gate`** (PreToolUse hook). When the orchestrator reaches for `Edit`/`Write`/`MultiEdit` against a hard-blocked path family, the hook exits 2 with stderr `PEAKS_CODE_PROHIBITED_DIRECT_EDIT: <file>... use 'peaks sub-agent dispatch rd'`. The hook is vendor-neutral — it inspects only the standard `{tool, input}` JSON contract, never env vars. **The rule lives in ONE implementation**: `src/services/hooks/pre-tool-code-gate.ts`, with the path arithmetic in `gate-path-normalize.ts` and the payload's own directory in `hook-payload-cwd.ts`. The shell sibling `src/services/hooks/pre-tool-code-gate.sh` is a **thin wrapper** that execs `peaks code-gate`; it carries a second copy of the rule **only** for a machine where no Node CLI is reachable, and that fallback **refuses rather than guessing** when it cannot place the file.

### If you catch yourself reaching for Edit/Write on `src/**`

STOP. Run:

```bash
peaks sub-agent dispatch rd --prompt '<your task>' --graph-node <nid> --workflow-id <wid> --request-id <rid> --project . --batch-id <uuid> --json
```

`--graph-node <nid>` and `--workflow-id <wid>` are OPTIONAL. Slice 4.0.8 RD §4 D4c made `--graph-node` required; it was relaxed again in `provisionDispatchNode` (`src/services/workflow/provision-dispatch-node.ts`) because the requirement was enforced but never validated — nothing downstream read the node, the record writer's graph transition is best-effort, and the documented "prepare a node first" ritual had no viable first step (`peaks workflow node prepare` never persisted the node). Passing neither flag now provisions the node and the graph on demand, so a dispatch works in a project with no graph infrastructure. When you DO pass a node, the binding is real: `provisionDispatchNode` writes it into `graphs/<wid>.json`. The RD sub-agent owns the actual `Edit`/`Write`/`MultiEdit` tool calls against source code. The orchestrator only emits the dispatch request.

**Anti-pattern:** directly calling `Edit`/`Write`/`MultiEdit` on `src/**` from the orchestrator session because "the change is tiny" / "it's just one line" / "the dispatch overhead is too high" / "the LLM feels confident". None of these override the Code-Gate; the probe + the hook both fail-closed.

## 24h mode (orchestrator flag, NOT a new skill)

24h mode is a *flag* the orchestrator flips, not a sibling skill. See `.peaks/memory/2026-07-28-peaks-code-loop-skill-proposal.md` for the RL-8 tension analysis. State machine via `peaks session 24h-mode {state,transition,attempts,reset}`; snapshot at `.peaks/_runtime/<sessionId>/24h-state.json` (read-only for peaks-code).

**5 auto-engage triggers:** T1 user NL keyword (`24h / 通宵 / 不计成本 / 不停机 / ...`) / T2 ≥30 active slices + ≥6h wall-clock / T3 ≥3 monotonic-guard fires + ≥10 slices remaining / T4 session gap ≥4h / T5 ≥3 active slices for restart. T3+T4 auto-engage 24H_ACTIVE; T1/T2/T5 surface for LLM judgement.

**3 decision buckets:** A (T3/T4, auto-engage, no brainstorming gate) / B (non-T3/T4, runbook brainstorming sub-step) / C (T1/T2/T5, surface `peaks session 24h-mode transition --state USER_CONFIRM`).

**Integration surfaces:** `peaks code run --24h` / `peaks dashboard long-run --since 24h` / `peaks session 24h-mode state|transition|attempts|reset`.

**Red lines (peaks-code side):**
- No auto-compact prose ban: never write "ask the user to compact" / "prompt the user to run `/compact`" / "the user should run `peaks code auto-compact` manually" / "the user is responsible for context management" / legacy 50/75/90 percent tiers. **Tier contract (standard mode): `auto-fire` ≥ 0.80 / `pre-compact` ≥ 0.85 / `red-line` ≥ 0.95. Compact on the FIRST of these to arrive — 0.80, not 0.85.**
- SquabbyZ sole-author rule: no `Co-Authored-By: Claude/Anthropic` trailer.
- 24h mode is a flag on `peaks-code`; MUST NOT introduce a sibling `peaks-24h` skill or competing top-level verb.

## 24h mode spill/hydrate (opt-in experimental, rid-032)

When 24h mode is active and an in-flight sub-agent batch is detected, the LLM MAY persist its current turn context to disk through the `session spill-demo` helper. Creates a `SpillRecord` in `.peaks/_runtime/<sessionId>/spill/`. Round-trip is idempotent; existing in-flight deferral still works without spill/hydrate. **Opt-in experimental** — not required.

## Peaks-Loop Superpowers 协作边界 (BRIDGE — MANDATORY, effective 2026-07-24)

Pins the boundary between `peaks-code` and the **superpowers** skill family (`brainstorming`, `writing-plans`, `executing-plans`, `subagent-driven-development`, `dispatching-parallel-agents`, `verification-before-completion`, `test-driven-development`, `systematic-debugging`, `requesting-code-review`, `receiving-code-review`, `using-superpowers`, `using-git-worktrees`, `finishing-a-development-branch`). Closed under slice 2026-07-24-peaks-code-bridge-002-rootcause.

- superpowers skills are **reference material**, not workflows peaks-code runs. They may NOT auto-replace peaks-rd, peaks-qa, peaks-ui, peaks-sc, or peaks-txt.
- When `superpowers:brainstorming` or `superpowers:writing-plans` is suggested, peaks-code MUST: (1) run as a **reference** to seed its own PRD/RD artefacts, (2) re-author as a peaks-rd PRD under `.peaks/_runtime/<sessionId>/rd/requests/<rid>.md`, (3) continue peaks-code's 11-step sequence from Step 3 — never the superpowers plan execution.
- `superpowers:writing-plans` / `superpowers:executing-plans` are **NOT** dispatched directly. peaks-rd is the only authoritative planner/executor pair.
- Any peaks-managed hook entry emitted by `peaks hooks install` MUST originate from `src/services/hooks/*.sh` in the peaks-loop repo. LLM-improvised hook scripts are forbidden (001-bridge root cause).
- Before any LLM edit to `~/.claude/skills/<skill>/*`, verify the path is a junction (`fsutil reparsepoint query` on Windows / `readlink` on POSIX). If it is a real directory, STOP and re-route via `peaks skill sync` after a junction rebuild — never write to a real directory (would pollute the npm sync chain).
- Mandatory closure: every peaks-code request MUST finish `peaks request transition` through `spec-locked → implemented → qa-handoff → handed-off` plus `peaks memory extract`. Half-finished state files are treated as pollution and the LLM MUST NOT exit without a transition note.

**Self-check (read before any tool call):** *Is the tool I am about to call a superpowers auto-runner, or a peaks-rd / peaks-qa sub-agent dispatch?* If it would short-circuit peaks-rd, STOP and dispatch via `peaks sub-agent dispatch rd`.

## Worktree governance (3-layer design, locked 2026-07-29)

> **npm-contract boundary.** Editing this file in `peaks-loop` source propagates to every consumer project on `npm install`. The 3-layer design is binding; downstream projects MAY extend Layer 2 with their own `peaks worktree auth grant` reasons but MUST NOT widen Layer 3's deny list outside the upstream `SUPERPOWERS_DENIED_SKILLS` constant. Full design, sub-agent contract, operator runbook → `references/worktree-governance.md`.

- **L1 — sub-agent system prompt** (`MUST NOT` on superpowers chain in dispatch templates; weakest, prose-only).
- **L2 — hook + lifecycle gate** (`peaks hooks install` → `peaks gate enforce` → `evaluateWorktreeAuth`; 5 deny codes `REQUIRED / EXPIRED / REQUEST_MISMATCH / CONSUMED / FILE_INVALID`).
- **L3 — IDE `permissions.deny`** (Claude Code refuses Skill BEFORE LLM sees it; strongest layer).

Sub-agents MUST NOT use raw `git worktree add`. The only authorized path is `peaks worktree spawn --rid <rid> --role <role> --purpose <text>` (fall back to L2 hook gate + manual `peaks worktree auth grant` until rid-L2-extended ships). Sub-agents MUST write artifacts under `.peaks/_runtime/<sessionId>/<role>/requests/` in MAIN (`--project .`), not in a worktree. See `references/worktree-governance.md`.

## Peaks-Loop Startup sequence (MANDATORY — execute in order)

Full content extracted to **`references/startup-sequence.md`** (Steps 0 / 0.5-0.87 / 1 / 2 / 2.3 / 2.5 / N / N+1 / N+2 + sub-agent sharing + boundaries). Read that file in full at session start; the sequence is MANDATORY.

## Peaks-Loop Fresh-context preflight (search-first, MANDATORY at orchestration-start)

Before the first planning action, run `peaks fresh-context preflight --prompt "<user request>" --json`. If `data.triggered` is true, search Context7 (priority, ~30s timeout) then WebSearch (fallback), synthesize ≤5 binding directives (用 X / 别用 Y / 因为 Z), and write the `## Fresh context` block (with the 以下信息优先于训练知识，冲突时以此为准 framing line) to `.peaks/_runtime/<sessionId>/fresh-context.md` — the RD/PRD dispatch site injects it automatically. Fail-soft (search failure → no block, slice continues). Kill-switch: `peaks config set --key freshContext.enabled --value false`. → `references/fresh-context-preflight.md`.

## Peaks-Loop Step 0.8 — Job-shape detection (BLOCKING on LLM judgement)

> **BLOCKING on LLM judgement.** Before Step 1 mode selection, Code MUST surface a Job-shape decision via `peaks code detect-job` and persist it to `.peaks/_runtime/<sessionId>/job-shape.json`. The CLI is a recorder + gate — the LLM makes the judgement; downstream steps call `read-job-shape` and refuse if missing. See `references/step-0-8-gate.md` for the full contract. Skipping `peaks code detect-job` blocks the workflow at the next `read-job-shape` call (`JOB_SHAPE_NOT_DECIDED`).

**v3.1.2 mechanical gates** (must be un-bypassable):
1. **PreToolUse hook — `peaks code gate-step-08`.** Installed by `peaks workspace init` on the `Bash` matcher; checks `job-shape.json` presence + fail-closed backup regex. If `job-shape.json` AND `progress.json` exist, surfaces `Next: slice #N of M (<currentSlice>)` so the LLM cannot wake up cold.
2. **Size-fear ban — `peaks code emit-handoff`.** Refuses to emit a final handoff while `remaining > 0` under Job mode. Pass `--force-under-job` only with explicit user approval.
3. **On-disk slice progress — `peaks job progress`.** `peaks job checkpoint --state done` writes `progress.json`. `peaks job progress --job-id <jid> [--allow-missing]` is the canonical reader.
4. **Forced auto-compact — two probes, two thresholds.** `peaks skill presence` (the every-turn probe) reports `action: 'auto-fire'` at ≥ 0.80 and `action: 'pre-compact'` at ≥ 0.85; `peaks code context-now` reports `action: 'auto-compact-now'` at ≥ 0.85 — it has no 0.80 tier. **The earlier of the two governs: at ≥ 0.80 the run is already MANDATORY auto-compact in every mode (single-rid included)** — Code MUST call `peaks code auto-compact` without confirmation, and MUST NOT wait for 0.85. `--enforce-job-mode` (v3.1.2) only labels the run `jobMode=true`; the ≥ 0.85 downgrade that used to apply to single-rid sessions was removed 2026-09-12.

**Step 0.7 resume rule (read-FIRST):** on resume, `peaks code gate-step-08` reads `progress.json` first and surfaces `Next: slice #N of M (<currentSlice>)` so the orchestrator picks up at the right slice without re-reading the artifact tree.

### Peaks-Loop Step 0.51 — `orchestrator-can-do` probe (slice 2026-08-05, lesson-encoded CLI)

> **Before deciding to push a slice to the next session**, run `peaks code orchestrator-can-do --slice-spec '<text>' --json`. The command evaluates 4 boundary questions (source code? sub-agent available? requires user decision? context sustainable?) and returns whether the slice can be done in the current session. Default to `canDoInSession=true` unless hard blockers are present; sub-agent dispatch (`peaks sub-agent dispatch rd`) is the canonical delegation path for source-code changes. This encodes the 2026-08-05 lesson — orchestrator MUST NOT Edit/Write `src/` directly, but MUST delegate via sub-agent dispatch. See `.peaks/memory/2026-08-05-peaks-code-orchestrator-capability-misjudgment.md`.

### Peaks-Loop Step N+2: Auto-compact at the warning line (v2.13.0 zero-pause contract)

> **Zero-pause contract.** When context usage crosses the pre-compact threshold, peaks-loop **automatically fires `peaks code auto-compact` — the LLM does NOT prompt the user to run `/compact` manually**. Stale prose that says "ask the user to compact" silently stalls the workflow. The v2.13.0 contract makes auto-compact a system responsibility, not a user action.

**Thresholds (standard mode, replacing legacy 50/75/90; `partial` / 24h mode moves every line down to 0.65 / 0.70 / 0.85):**

| ratio zone | zone name | action |
|---|---|---|
| `< 0.80` | normal | skip — LLM keeps working |
| `0.80 ≤ ratio < 0.85` | **auto-fire zone** | `peaks skill presence` returns `action: 'auto-fire'` here: peaks-loop preempts on its own, without asking the LLM to decide. The LLM MUST run `peaks code auto-compact` and MUST NOT wait for 0.85. **This is the tier that fires first, so this row — not the 0.85 row — is the real trigger line.** `peaks code context-now` has no 0.80 tier and still reports `soft-warn` here, so its `action` alone under-reports this band. |
| `0.85 ≤ ratio < 0.95` | **pre-compact zone** | `peaks code auto-compact` fires **automatically** (deferred only when in-flight sub-agent batch is running; fires the moment the batch lands). The LLM does not prompt the user. In practice peaks-loop already fired at the 0.80 tier above, so this band is today the "already fired" zone; `peaks code context-now` reports `action: 'auto-compact-now'` from 0.85 up. |
| `ratio ≥ 0.95` | **red-line (Karpathy §4)** | `peaks code auto-compact` invoked immediately; `peaks code context-now` returns `action: 'red-line'`. **Since 4.0.47 the red line REQUESTS the compaction and says it is waiting — it does NOT block sub-agent dispatch, and it does not refuse to advance.** Keep working and re-probe with `peaks code context-now`; the harness performs the compaction, and nothing peaks-loop can do lowers the ratio on its own, so blocking here was a deadlock rather than a gate. If the ratio keeps climbing and no compaction lands, report that and hand control back — do not stall. `--bypass-red-line` is a no-op. |

**Probe primitive:** `peaks code context-now --json` — authoritative for `ratio` and for the `action` tier **from 0.85 up**. Do NOT use `peaks context check --prompt-size` (deprecated, will silently under-report ratio). Returns `{ ratio, action: 'ok' | 'soft-warn' | 'auto-compact-now' | 'red-line' }` — Code reads `action` and dispatches `peaks code auto-compact` on `auto-compact-now` or `red-line` without user confirmation. **It has no 0.80 tier** (see the tier table above): the `0.80 ≤ ratio < 0.85` band belongs to `peaks skill presence`'s `auto-fire`, and that probe runs every turn. **Read both probes and act on whichever fires first — the earlier of the two governs, so 0.80, not 0.85.**

**Enforcement layers (defense in depth):**
1. `src/services/code/auto-compact-orchestrator.ts` — `evaluateAutoCompactDecision` default-returns `shouldCompact: true` for both `pre-compact` and `red-line`. Only deferral is `inFlightBatch.hasInFlightBatch` (D6.e); no LLM/human approval branch.
2. `peaks skill presence` — ≥ 0.80 is MANDATORY (`auto-fire`) in every mode; this probe runs every turn, so it is the one that cannot be forgotten. `peaks code context-now` — ≥ 0.85 is MANDATORY (`auto-compact-now`) in every mode; `--enforce-job-mode` no longer gates that (2026-09-12). Only an in-flight sub-agent batch defers it.
3. `peaks code gate-step-08` (PreToolUse hook) — surfaces `auto-compact-now` on every Bash call when ratio is in the zone, so the LLM cannot wake up cold and forget.
4. Karpathy §4 exception: `peaks code auto-compact` is fired *by the orchestrator*, not by the user. If you find yourself about to write "ask the user to compact" / "prompt the user to run `/compact`", STOP — that is the regression.

**Anti-pattern (DO NOT introduce):** any of these strings in skills/* or comments signals the zero-pause contract has been broken:
- "ask the user to compact" / "prompt the user to run `/compact`" / "the user should run `peaks code auto-compact` manually" / "the user is responsible for context management" / legacy mid/seventy-five/ninety percent tiers (current is 0.80 auto-fire / 0.85 pre-compact / 0.95 red-line).

If the prose audit (`peaks audit red-lines`) flags any of the above, the slice is **blocked** until the prose is rewritten.

See also: references/session-overload-signal-index.md for the 7-signal lookup table the LLM consults before deciding to open a new session.

## CLI Drift Index (sediment 2026-07-09)

> **Reading guide:** Verified against peaks-loop 4.0.0-beta.6. Each drift below is annotated inline at the relevant step with a `> CLI reality check`. On `error: unknown option ...`, **read the inline reality check first** before guessing.

| Drift ID | Step | Symptom | Fix | Inline location |
|---|---|---|---|---|
| **D-001** | 0.8 | `peaks code detect-job --is-job ...` rejected with `error: unknown option '--is-job'` | Use `peaks job init --job-id <jid> --slice-list <list> --main-loop-strategy <single\|rotating>` | §Step 0.8 first paragraph |
| **D-002** | 2.5 | `peaks session title --session-id <sid> ...` rejected with `error: unknown option '--session-id'` (this is the bare `<sid>` anti-pattern) | sid is positional: `peaks session title <sessionId> "<title>" --json` | §Step 2.5a |
| **D-003** | 0.8 | `JOB_SHAPE_NOT_DECIDED` exception expected but never thrown | Current behavior is `peaks job status` reports `done: 0` passively — treat as recoverable miss, not hard error | §Step 0.8 third paragraph |
| **D-010** | 11c | `peaks memory extract` returns `extractedCount: 0` despite `<!-- peaks-memory:start -->` existing | Block requires YAML frontmatter (`title:` + `kind:` + `---`) + closing `<!-- peaks-memory:end -->`. A marker without those fields, and a marker that is not the exact literal (e.g. with a `kind=…` written inside it), produce no writes and are both named in the envelope's `warnings[]` — read it before concluding there was no block | §Step 11c + 11d |
| **D-011** | 11c | `extractedCount` ≥ 1 but `.peaks/memory/` gains fewer files than `plannedWrites` lists, with `warnings: []` | A third outcome, separate from D-010: the block parsed and was planned, and the **write** was skipped because the store already held its target name (`writtenFiles` shorter than `plannedWrites`). Since 2026-10-13 the envelope names each skipped block and closes with `Wrote N of M planned memories; K skipped because the target file already exists`. Re-read `warnings[]` before reporting the step complete — a re-run of the same handoff is the ordinary way to hit this, and it is not a failure | §Step 11c + 11d |

> **Sediment lesson (master record):** `.peaks/memory/peaks-code-runbook-4-0-0-beta-6-skill-md-cli-d-001-d-002-d-003-d-010.md`

## Peaks-Loop GStack integration

Map gstack stages to Peaks-Loop role artifacts; preserve confirmation gates. → `references/gstack-integration.md` + `references/browser-workflow.md`.

## Peaks-Loop Local intermediate artifact workspace (MANDATORY)

Step 0 creates the workspace; all intermediate artifacts land under `.peaks/_runtime/<sessionId>/`. NEVER write Peaks-Loop intermediate artifacts to the project root.

## Peaks-Loop Pre-RD project scan checklist (MANDATORY)

Before handing off to `peaks-rd`, scan the project and record findings to `.peaks/project-scan/project-scan.md` (project-level, git-tracked; sibling of `.peaks/PROJECT.md`). Slice 2026-07-15-project-scan-bootstrap (G1 + G2): `peaks workspace init` and `peaks project context` both bootstrap this file automatically; only re-run the manual flow when the scan output is genuinely out of date. → `references/project-scan-checklist.md`.

> **Slice 2026-07-15-project-scan-bootstrap G4b / AC9:** after `peaks workspace init`, the consumer project's `.peaks/project-scan/` directory carries 5 files: `project-scan.md` (generated by the scan logic) + `business-knowledge.md` + `security-template.md` + `perf-template.md` + `audit-output-schema.md` (the 4 audit/business templates bundled at `src/services/workspace/templates/project-scan/*.md`, copied on init; idempotent — existing files preserved unless `--force-project-scan-templates`). RD / UI / TXT / QA read from this tree; nothing else.

## Peaks-Loop Frontend-only development mode

When the project has no live backend (no swagger.json, no API server), Code must activate frontend-only mode. The CLI is authoritative — read `frontendOnly` and `frontendOnlyReason` from `peaks scan archetype --json`. → `references/frontend-only-mode.md`.

## Peaks-Loop Step 2.5: Best-practice scan (BPS) (NEW 2026-08-12)

Inserted between current Step 2 (PRD) and Step 3 (RD). Sub-step does a **business-aware,
language-aware, LLM-recommended best-practice scan** before RD kicks off.

**Trigger:** Fires at peak-prd exit when business-goal is non-empty + sub-step not yet
triggered for this intent.

**Action sequence — the LLM performs the lookup; the CLI never calls Context7:**
1. Detect project language (TS / JS / Python / Go / Java) via `language-detector` (5-lang
   priority chain), or let the CLI auto-detect it.
2. **You** query Context7 (`@upstash/context7-mcp`) with your own MCP tool — priority 1, 30s budget —
   and WebSearch as the priority-2 fallback when Context7 answers nothing.
3. **You** write those results to `.peaks/_runtime/<sessionId>/best-practice/lookup-results.json` in
   the scan seam's own vocabulary — `{ "intent": "<the --intent value>", "context7": { "ok": …,
   "results": [{ "title", "url", "snippet" }] }, "websearch": { … } }` — then run
   `peaks best-practice-scan --project <repo> --intent "<goal>" --lookup-results <that file>`. The
   path is resolved against your cwd, so pass it explicitly. A lookup that returned nothing is
   `"ok": false, "results": []`; `"ok": true` with an empty `results` is refused, because that is
   the shape a fabrication would take. Each fragment may carry `title`/`url`/`snippet` and nothing
   else, and **the `url` is yours to construct** — Context7's response contains no URL, only a
   library ID (`/org/project`), so state that when the recommendation is read.
4. The CLI validates the file and renders the 8-row markdown comparison table per `output-formatter`
   into `<project>/best-practice/<date>-<intent-slug>.md`.
5. LLM picks one recommendation (★ marker) with reasoning block.
6. **Mandatory ⚠️ catch gate** — user explicitly acks / picks alt / rejects + reason.

**When the scan cannot be performed, the sub-step is SKIPPED — never fabricated.** With no
`--lookup-results`, the CLI's built-in lookups are stubs and return synthetic fragments: the scan
**refuses** — `ok:false`, `BEST_PRACTICE_SCAN_SYNTHETIC_LOOKUP`, exit 1 — and prints no recommendation,
no comparison table and no ⚠️ catch gate, because there is nothing real for the user to judge. Record
the sub-step as **skipped with reason `synthetic-lookup`** and carry on; do not synthesise a
recommendation to satisfy the gate. **Every miss is refused**, in one of two ways: with no real
WebSearch behind a Context7 miss the fall-through lands on the stub and gives the refusal above; when
you supply the `websearch` seam and it *also* reports `ok: false`, the chain is real and found nothing,
and the command refuses with `BEST_PRACTICE_SCAN_NO_FRAGMENTS` and writes no artifact at all. A scan
with zero fragments never renders — a table with a `★` on it and nothing behind it is the fabrication
this sub-step exists to prevent. `--intent <text>` is required (the business goal, not the project
path) — omitting it is `BEST_PRACTICE_SCAN_INTENT_REQUIRED`, also exit 1. Supply real results with
`--lookup-results <file>`; a malformed, mismatched or empty-results file is refused as
`BEST_PRACTICE_SCAN_INVALID_RESULTS` without scanning. A real scan renders the full table and the gate
normally. Run the injected scan **after** the PRD state transition, so the real recommendation is the
artifact left on disk; a refusal never overwrites it — it is recorded under
`<project>/best-practice/skipped/` instead.

**Out of scope for this sub-step:**
- ❌ No changes to RD dispatch Karpathy prose (Step 3 unchanged)
- ❌ No changes to QA / SC / TXT skills
- ❌ No new `peaks-best-practice` standalone skill (sub-step inside peaks-prd only)
- ❌ No framework-knowledge persistent index (future slice)

**Reference:** Spec at `.peaks/_runtime/<sessionId>/sc/spec-step-2-5-best-practice-scan.md`
§4-7. Implementation: `src/cli/commands/best-practice-scan-command.ts` + `src/services/best-practice/`.

## Peaks-Loop Request type classification + Workflow order + Transition verification gates

The 6-type table + 11-step order + 7 transition gates (A-G) live in `references/workflow-gates-and-types.md`. peaks-code narrative references Gate A-G — keep both files in lockstep.

## Peaks-Loop Default sub-agent fan-out (≥ 2 leaves/topological level → `--from-dag`)

> **Slice 5:** when the slice DAG has ≥ 2 leaves at one topological level, dispatch via `peaks sub-agent dispatch --from-dag <dag-file>` (wall-time ≈ max, not sum).

Write DAG → `.peaks/_runtime/<sessionId>/sc/slice-dag.json`, run `peaks sub-agent dispatch --from-dag <dag-file> --batch-id <id>` once; orchestrator emits N parallel `buildToolCall` (`dispatchCount === N`). 主路径 = 唯一蜂群;config/docs/chore 跳过不打断。详见 `.peaks/memory/peaks-cli-24h-ai-programmer-positioning.md`。

### Hard constraint: fan-out is mandatory (slice 2026-06-24-audit-5th-p2)

> **No serial opt-out.** `preferences.fanout.defaultMode = 'serial'` was removed in 2.8.4; legacy values auto-migrate to `fan-out`.

→ see `references/swarm-dispatch-contract.md`, `references/sub-agent-dispatch.md` (NOT `Skill` tool), `references/fanout-mandatory.md`.

## Slice 调度:分层并行 + 上游同步(2026-06-28 校准)

> 分层并行(G12)+ 上游同步(G11)见 `.peaks/memory/peaks-cli-fork-sync-and-layered-parallel.md`。

## Peaks-Loop Mandatory RD QA repair loop (AUTO-PROCEED)

After `peaks-rd` finishes, Code MUST auto-route to `peaks-qa` without waiting for confirmation. Cap: 3 cycles; on 3rd failure emit blocked TXT handoff. Full 5-step procedure at `references/micro-cycle.md`.

> **Fast-mode exception.** Under `peaks code plan --fast` this loop is off — `repairLoop: !opts.fast` in `buildCodePlan`. Without this line the `MUST` above contradicts fast mode, which is reachable only through `references/fast-mode.md`; what a fast lane must still satisfy, and when a task is not a fast-lane task at all, is in **`references/fast-lane-norm.md`** (the single source).

## Default runbook

The end-to-end CLI sequence for `full-auto` lives in `references/runbook.md`. `assisted`/`strict` pause at `[CONFIRM]`; `full-auto`/`24h` auto-proceed. At a `[CONFIRM]` gate the CLI never prompts: the transition throws `CONFIRMATION_REQUIRED`, so Code asks the user via `AskUserQuestion` and, on approval, re-runs the same command with `--confirm`. Never expect or ask for a terminal `y/N` prompt.

When adding new CLI commands, mirror into `references/runbook.md` (the CLI falls back to that reference; no test asserts the mirror).

## RD micro-cycle (TDD small-step rapid-test loop)

> **Slice 内部**的修复 / refactor / lint 修复走 micro-cycle（5-10s/cycle）；Slice 边界走 `peaks slice check`。完整手册：`references/micro-cycle.md`。

## Peaks-Loop Project standards preflight

Gather via `peaks standards init/update --project <path> --dry-run`. Standards must reflect the project scan (component library, CSS, build tool, state, routing) — never emit a generic template.

## Peaks-Loop Refactor mode

Read `references/refactor-mode.md` first. Default MVP: `peaks-code refactor`. Red lines: understand before changes, ≥95% UT coverage, split broad refactors, strict verifiable specs, 100% acceptance per slice.

## Peaks-Loop Quality-gate commands (CLI cheat sheet)

Five CLI commands harden the workflow against silent skips: `peaks request lint`, `peaks request repair-status`, `peaks scan request-type-sanity`, `peaks scan libraries`, `peaks slice check` (plus `peaks request transition`). For JS/TS project lint enforcement (Gate B5 expansion), use `peaks lint [--scope <path>] [--format json]` (ESLint read-only verifier; layer-3 dynamic loading via `npx --package`; soft-fail when ESLint is missing — does not block the slice). See `references/quality-gate-cheatsheet.md`.

## Peaks-Loop Completion handoff

After final validation, refresh project-local standards via `peaks standards init/update` (never hand-write). Use Peaks-Loop TXT for the compact handoff capsule. **Presence management is delegated to the last downstream skill** — peaks-code does not call `peaks skill presence:clear` itself.

## Peaks-Loop Step 11: Memory sediment (BLOCKING on workflow complete)

> **Hard rule.** Code MUST NOT declare a workflow complete until Step 11 has produced ≥ 1 file in `.peaks/memory/` OR the user has explicitly approved a no-sediment outcome via AskUserQuestion. Canonical CLI: `peaks memory extract --project <repo> --artifact .peaks/_runtime/<sessionId>/txt/handoff.md --apply --json` (the artifact-scoped extract; the batch-scoped sibling `peaks project memories:extract` is for non-handoff flows only). **Single authority:** inside a peaks-code workflow, sedimenting memory writes to `.peaks/memory/`; the IDE-side memory dir (`~/.claude/projects/<hash>/memory/`) is a session note, not the authority and is read-only for peaks — pull any session note in with `peaks memory ingest --apply`, and keep the index in sync with `peaks memory reindex --apply`. Substeps 11a/11b/11c/11d (Gate A/B/C), 11e (index hygiene), 11f (IDE-side ingest), D-010 fix root cause check → `references/step-11-memory-sediment.md` + `references/runbook.md` §Step 11.

## Peaks-Loop External references and lifecycle

3rd-party integrations (codegraph, mattpocock/skills, shadcn/ui, MCPs, Context7) follow Discovery → Reference → Side effect through Peaks CLI only. Run `peaks capabilities` for capability discovery; treat external skills as reference material only. MCP servers (Playwright / Chrome DevTools / Figma) are user-installed — check the tool list for `mcp__<server>__*` entries. Do not execute upstream installer / run upstream commands / persist sensitive examples / install upstream resources directly — funnel side effects through the Peaks CLI surface. Peaks-Loop Code gates remain authoritative. → `references/external-references.md` + `references/external-skill-invocation.md`.

## Codegraph orchestration context

`peaks codegraph affected` is an optional project-analysis enhancement (untrusted supporting evidence) for role handoff. Code must not treat codegraph output as approval for scope, design, or QA verdict. Never mutate agent settings / hooks from codegraph; do not commit `.codegraph/` artifacts. RD writes `.peaks/_runtime/<sessionId>/rd/codegraph-context.md`; QA / TXT consume the same envelope. → `references/codegraph-orchestration.md`.

## Sub-agent context governance (G7 + G8 + G9 — slice #010)

Main LLM reducer sees metadata-only view (~200 chars/sub-agent); on-demand `Read` for full content. Threshold table: 50% soft warn, 75% `CONTEXT_NEAR_LIMIT`, 80% hard reject (CLI + hook double-guard). → `references/context-governance.md`.

## Large tool output discipline (BLOCKING — slice 2026-09-10-context-audit-and-discipline)

> **Hard rule.** Any tool output larger than **2 KB** MUST NOT be dumped into the orchestrator's own context. Use `--summary` (bounded counts + names-of-first-N, ≤ 2 KB) when the command offers it — `peaks memory reindex --summary`, `peaks memory list --summary`, `peaks doctor --summary`, `peaks request list --summary` — otherwise write the output to a file and `Read` only the slice you need. The default envelopes are unchanged; `--summary` is strictly opt-in.
>
> **Why (measured, not cargo-cult).** In session `2026-09-07-session-245530` the orchestrator spent ~68% of a 1M window on its OWN context. Two offenders dominated: 4 × dumping a full `peaks memory reindex --json` unclassified array ≈ 160 KB ≈ 40K tokens, and 20 × sub-agent final reports ≈ 60 KB ≈ 15K tokens. Neither was dispatch boilerplate — both were the orchestrator reading things it did not need in full. `peaks code context-audit` now measures this per group (`{tool, key, bytes, pctOfTotal, count}`); run it when the window feels heavy.
>
> **Quality guard.** `--summary` removes no information — it is an additive view. Every path, name and count stays on disk and is re-readable by re-running the command without the flag. Never silently drop data; shrink the in-context copy instead.

## Sub-agent cross-batch signal — G8.4 share / shared-read / await

Three CLI primitives: `peaks sub-agent share / shared-read / await` (last-write-wins, ≤ 1KB warn / ≥ 64KB reject). Channel gitignored under `.peaks/_sub_agents/<sessionId>/shared/`.

## References

Index of every `references/` file. Read on demand. There is no separate generated index — list `references/` directly (kept outside the SKILL.md byte cap). Top-5 by usage: `runbook.md`, `sub-agent-dispatch.md`, `micro-cycle.md`, `worktree-governance.md`, `workflow-gates-and-types.md`.