pan-wizard 3.13.1 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +4 -5
  3. package/commands/pan/audit-deployment.md +384 -384
  4. package/commands/pan/focus-auto.md +683 -683
  5. package/commands/pan/focus-doc-audit.md +530 -530
  6. package/commands/pan/focus-drift-walking.md +525 -525
  7. package/commands/pan/git.md +1 -1
  8. package/commands/pan/hud.md +3 -2
  9. package/commands/pan/report.md +70 -0
  10. package/hooks/dist/pan-check-update.js +62 -62
  11. package/hooks/dist/pan-context-monitor.js +134 -122
  12. package/hooks/dist/pan-statusline.js +7 -1
  13. package/package.json +5 -5
  14. package/pan-wizard-core/bin/lib/config.cjs +14 -1
  15. package/pan-wizard-core/bin/lib/core.cjs +6 -2
  16. package/pan-wizard-core/bin/lib/doc-lint.cjs +86 -1
  17. package/pan-wizard-core/bin/lib/focus.cjs +48 -2
  18. package/pan-wizard-core/bin/lib/frontmatter.cjs +442 -442
  19. package/pan-wizard-core/bin/lib/hud.cjs +202 -17
  20. package/pan-wizard-core/bin/lib/knowledge.cjs +2 -2
  21. package/pan-wizard-core/bin/lib/optimize.cjs +2 -2
  22. package/pan-wizard-core/bin/lib/phase-remove.cjs +1 -1
  23. package/pan-wizard-core/bin/lib/phase-report.cjs +723 -0
  24. package/pan-wizard-core/bin/lib/phase.cjs +4 -4
  25. package/pan-wizard-core/bin/lib/review-deep.cjs +3 -1
  26. package/pan-wizard-core/bin/lib/utils.cjs +171 -171
  27. package/pan-wizard-core/bin/lib/verify.cjs +172 -61
  28. package/pan-wizard-core/bin/pan-tools.cjs +1499 -1463
  29. package/pan-wizard-core/references/checkpoints.md +776 -776
  30. package/pan-wizard-core/references/continuation-format.md +249 -249
  31. package/pan-wizard-core/references/questioning.md +145 -145
  32. package/pan-wizard-core/references/tdd.md +263 -263
  33. package/pan-wizard-core/references/ui-brand.md +160 -160
  34. package/pan-wizard-core/templates/config.json +38 -38
  35. package/pan-wizard-core/workflows/exec-phase.md +14 -0
  36. package/scripts/build-hooks.js +51 -51
  37. package/scripts/git-hooks/pre-commit +0 -0
  38. package/scripts/release-check.js +53 -47
  39. package/scripts/run-tests.cjs +44 -0
@@ -1,683 +1,683 @@
1
- ---
2
- name: focus-auto
3
- group: Focus
4
- description: Continuous scan-plan-exec loop with purpose-driven categories and 5-layer safety harness
5
- allowed-tools:
6
- - Read
7
- - Write
8
- - Edit
9
- - Bash
10
- - Grep
11
- - Glob
12
- - Agent
13
- ---
14
-
15
- # /pan:focus-auto — Continuous Autonomous Improvement Campaigns
16
-
17
- Run purpose-driven improvement campaigns with a single command. The auto-runner orchestrates scan, plan, and exec cycles automatically with category-scoped scanning, intelligent defaults, and structured stopping.
18
-
19
- **ADR:** ADR-0015 | **Heritage:** execplan budget + PanMonty categories + focus-exec pipeline
20
-
21
- ## Project Scope Boundary
22
-
23
- This command runs improvement campaigns on the **host project's source code** — not on PAN Wizard's own infrastructure.
24
-
25
- **Exclude these directories from scanning and execution:**
26
- - `.claude/`, `.github/copilot-instructions.md`, `.opencode/`, `.gemini/`, `.codex/` — PAN runtime directories
27
- - Any `pan-wizard-core/`, `pan-tools`, agent `.md`, or command `.md` files within PAN runtime directories
28
-
29
- **These directories are PAN's own tooling installed into the project.** Do not scan PAN files for TODOs, do not report PAN files as lacking coverage, do not modify PAN agents/commands/core as part of a campaign. If a scan finding or batch item targets a PAN infrastructure file — DROP IT.
30
-
31
- ---
32
-
33
- <completion_contract>
34
- A campaign is complete when ANY stop condition is met:
35
- 1. Max cycles reached (--max-cycles, default 10)
36
- 2. Total budget exhausted (--total-budget, default 200)
37
- 3. Scan returns zero items for the selected category
38
- 4. Context window drops below 25% (CRITICAL threshold)
39
- 5. User sends /pan:focus-auto --stop
40
- 6. Category-specific completion (e.g., prompts_remaining === 0)
41
-
42
- Each cycle is complete when: scan → plan → exec → commit succeeds, OR a safety harness triggers and the cycle is cleanly aborted with state preserved.
43
- </completion_contract>
44
-
45
- ## FIRST ACTION — Category Selection (if no --category argument)
46
-
47
- If `$ARGUMENTS` does NOT contain `--category`, you MUST ask the user before doing anything else.
48
-
49
- **Display this text menu and STOP — wait for the user to reply:**
50
-
51
- ```
52
- Which category should this auto campaign focus on?
53
-
54
- 1. **cleanup** — Dead code, unused imports, duplicated logic, magic numbers (P3-P5)
55
- 2. **stability** — Unguarded file ops, missing error handling, crash risks (P0-P2)
56
- 3. **tests** — Missing test coverage, low assertion density (P2-P5)
57
- 4. **features** — Roadmap items, new capabilities (P3-P5)
58
- 5. **docs** — Stale documentation, missing command descriptions (P5-P6)
59
- 6. **optimize** — Performance bottlenecks, redundant computation, robustness hardening (P1-P4)
60
- 7. **prompts** — Execute micro-prompt documents sequentially, or generate them from specs (P0-P6)
61
- 8. **security** — OWASP Top 10 violations, STRIDE threats, auth/injection/crypto hardening (P0-P2)
62
- 9. **distill** — AI code-bloat: phantom try/catch, unused imports, repeated blocks, premature abstraction, god functions (P1-P5)
63
-
64
- Reply with a number (1-9) or category name.
65
- ```
66
-
67
- **After the user replies, map their response to a category name:**
68
- - "1" or "cleanup" → SELECTED_CATEGORY = cleanup
69
- - "2" or "stability" → SELECTED_CATEGORY = stability
70
- - "3" or "tests" → SELECTED_CATEGORY = tests
71
- - "4" or "features" → SELECTED_CATEGORY = features
72
- - "5" or "docs" → SELECTED_CATEGORY = docs
73
- - "6" or "optimize" → SELECTED_CATEGORY = optimize
74
- - "7" or "prompts" → SELECTED_CATEGORY = prompts
75
- - "8" or "security" → SELECTED_CATEGORY = security
76
- - "9" or "distill" → SELECTED_CATEGORY = distill
77
-
78
- Wait for the user's reply before proceeding. Do not guess or pick a default category.
79
-
80
- ## AUTONOMY RULES (apply AFTER category is selected)
81
-
82
- - **DO NOT invoke the Skill tool.** All scan, plan, and exec work is done INLINE within this command.
83
- - **DO NOT stop between phases.** Execute Phase 0 through Phase 3 (or until a safety harness triggers) without pausing.
84
- - **DO NOT ask the user any more questions.** After category selection, run fully autonomously.
85
- - **DO NOT show intermediate results.** Only display: the cycle summary line after each cycle, and the campaign summary table at the end.
86
-
87
- ## Arguments
88
-
89
- ```
90
- /pan:focus-auto [--source scan|backlog] [--category CAT] [--mode MODE] [--budget N]
91
- [--max-cycles N] [--total-budget N] [--continue] [--stop] [--status]
92
- [--dry-run] [--deep-review]
93
- [--parallel-research] [--parallel-verify] [--clean-seal]
94
- ```
95
-
96
- | Flag | Default | Description |
97
- |------|---------|-------------|
98
- | `--source` | `scan` | Work selection. `scan` = category-scoped code scan (below). `backlog` = rank actionable items from `roadmap.md` / `requirements.md` (ADR-0031). |
99
- | `--category` | null (all) | cleanup, tests, stability, features, docs, optimize, prompts, security, distill. Applies to `--source scan`. |
100
- | `--mode` | category-dependent | bugfix, balanced, features, full |
101
- | `--budget` | category-dependent | Points per cycle (5-100) |
102
- | `--max-cycles` | 10 | Maximum iterations (1-50) |
103
- | `--total-budget` | 500 | Cumulative points cap (5-5000) |
104
- | `--continue` | — | Resume stopped/interrupted run |
105
- | `--stop` | — | Gracefully stop active run |
106
- | `--status` | — | Show current campaign progress |
107
- | `--dry-run` | — | Show plan without executing |
108
- | `--deep-review` | off | After every exec cycle, run inline OWASP security check on changed files. Verdict `block` or `review_required` stops the campaign (6th safety harness). Works with all categories. |
109
- | `--parallel-research` | off | Fan out the per-item *research* stage via the Workflow tool (read-only agents). No-op fallback to sequential where the host has no Workflow tool. (ADR-0031) |
110
- | `--parallel-verify` | off | Fan out the per-item *verify* stage via the Workflow tool (read-only). The implement/exec stage always stays a single agent. (ADR-0031) |
111
- | `--clean-seal` | off | After the loop's last item, run one clean build + full verification (commands from `config.json → build`/`verification`) to catch cross-item orphans. (ADR-0031) |
112
-
113
- ## Category Defaults
114
-
115
- | Category | Priority Range | Default Mode | Default Budget |
116
- |----------|---------------|--------------|----------------|
117
- | cleanup | P3-P5 | balanced | 50 |
118
- | tests | P2-P5 | balanced | 50 |
119
- | stability | P0-P2 | bugfix | 40 |
120
- | features | P3-P5 | features | 50 |
121
- | docs | P5-P6 | balanced | 30 |
122
- | optimize | P1-P4 | balanced | 50 |
123
- | prompts | P0-P6 | balanced | 100 |
124
- | security | P0-P2 | bugfix | 40 |
125
-
126
- ## Backlog source (`--source backlog`, ADR-0031)
127
-
128
- When `--source backlog` is set, work is selected from the **curated planning surface** instead of a code scan — for campaigns that work a human-prioritized roadmap rather than whatever grep finds.
129
-
130
- 1. **Read the backlog once** at Phase 0: actionable items are unchecked rows in `roadmap.md` (phase/plan checkboxes) and unmet `requirements.md` REQ rows. Skip anything struck, completed, or marked blocked.
131
- 2. **Score from the CURRENT document — never a hardcoded ID list.** For each item, derive `RS = (UserValue + TimeCriticality + RiskReduction) / Effort` (1–5 each; Effort from the row's size tag). Sort by wave/priority ascending → RS descending → effort ascending. This re-derives the order from whatever the roadmap says today, so it never goes stale.
132
- 3. **Pop the top survivor each cycle**; re-rank only if a landing changed a dependency. The same budget/cycle/context stops and safety harness apply unchanged.
133
- 4. The backlog ranker reads only PAN's planning files — it embeds **no** project-specific item IDs, test counts, or build commands. A project with no actionable backlog items is a clean stop (`scan returns zero items` equivalent).
134
-
135
- ## Concurrency model (when `--parallel-research` / `--parallel-verify`, ADR-0031)
136
-
137
- The proven shape is **parallel read-only research → exactly ONE serial implement/exec → parallel read-only verify**:
138
-
139
- | Stage | Concurrency | Why |
140
- |-------|-------------|-----|
141
- | Research | Parallel (Workflow fan-out, read-only) when `--parallel-research` | Reads source/specs; mutates nothing. |
142
- | Implement / exec | **Single agent, always** | Mutates the tree; never fanned out. |
143
- | Verify | Parallel (Workflow fan-out, read-only) when `--parallel-verify` | Runs against the already-built tree; mutates nothing. |
144
-
145
- **Serial-build constraint:** if `.planning/config.json → concurrency.serial_build` is `true`, the runner additionally guarantees at most one build process at any instant across the whole loop (for projects whose build trees corrupt under concurrency). This is **off by default** — most projects build in parallel safely. PAN does not assume it.
146
-
147
- **Commit-quality gates** (advisory, always on): a *staging-miss guard* (no exec-touched file left unstaged) and an *orphan audit* (HEAD must not reference a symbol defined only in an uncommitted file). With `--clean-seal`, a single clean build + full verification runs after the last item to catch cross-item orphans the per-cycle incremental commits hid.
148
-
149
- ## Pipeline
150
-
151
- ### Phase 0: Initialization
152
-
153
- 1. Parse arguments from `$ARGUMENTS`
154
- 2. Handle quick operations first:
155
- - If `--status`: run `pan-tools focus auto --status`, display result, STOP
156
- - If `--stop`: run `pan-tools focus auto --stop`, display result, STOP
157
- 3. If `--continue`:
158
- - Run `pan-tools focus auto --continue` to resume
159
- - Read the restored state to get category, mode, budget, etc.
160
- - Skip to Phase 2 (Main Loop)
161
- 4. If no `--category` was provided, you already displayed the menu in FIRST ACTION above. Use SELECTED_CATEGORY from the user's reply.
162
- 5. Initialize new run using the category from step 4:
163
- - Run `pan-tools focus auto --category <SELECTED_CATEGORY> [--mode MODE] [--budget N] [--max-cycles N] [--total-budget N] [--dry-run]`
164
- - If `--dry-run`: display the plan, STOP
165
- - Record the run state
166
-
167
- ### Phase 1: Baseline Capture
168
-
169
- 1. Run the project's test suite (discover the test command from `package.json` scripts, `Makefile`, or project docs)
170
- 2. Record baseline test count from the summary line (e.g., "tests 1314")
171
- 3. If tests fail: ERROR — "Cannot start: N tests failing. Fix tests before running auto campaign."
172
- 4. Run `git status` to verify clean working tree (warn if dirty, don't block)
173
- 5. Create safety tag: `git tag -f focus-auto-baseline`
174
-
175
- <phase_dependencies>
176
- Phase 0 → Phase 1: Init MUST succeed before baseline (state tracking requires valid run)
177
- Phase 1 → Phase 2: Baseline MUST be captured before main loop (regression circuit breaker needs it)
178
- Phase 2 (each cycle): Scan → Plan → Exec → Commit is strictly sequential within a cycle
179
- - Scan MUST complete before plan (plan needs scan items)
180
- - Plan MUST complete before exec (exec needs batch file)
181
- - Exec MUST complete and tests pass before commit (never commit broken code)
182
-
183
- HARD STOP conditions:
184
- - Phase 1 fails (tests broken): Do not enter main loop — report and exit
185
- - Any cycle: test count drops below baseline after revert → stop campaign, preserve state
186
- - Context drops below 25%: stop campaign cleanly (safety harness 3)
187
- </phase_dependencies>
188
-
189
- ### Phase 2: Main Loop
190
-
191
- **For each cycle (1 to max_cycles), execute Steps 2.1 through 2.5 without stopping:**
192
-
193
- #### Step 2.1: Scan (INLINE — do NOT invoke /pan:focus-scan)
194
-
195
- Perform a deep codebase scan to find actionable work items with evidence.
196
-
197
- **2.1.1 Read Codebase State**
198
- - Read project source files via Glob + Read: modules, entry points, key directories
199
- - Read planning state: `.planning/config.json`, any state/roadmap files that exist
200
- - Read `package.json` (or equivalent project manifest) for version and entry points
201
-
202
- **2.1.2 Search for Issues**
203
- - Grep for `TODO`, `FIXME`, `HACK`, `STUB` in source and test directories
204
- - Grep for error-prone patterns relevant to the category:
205
- - **stability:** unguarded `readdirSync`/`readFileSync` without try-catch, `existsSync` calls, `.forEach()` on unverified values, `parseInt` without NaN checks, `.match()` results accessed without null check
206
- - **cleanup:** dead code, unused imports, duplicated logic, magic numbers
207
- - **tests:** modules without corresponding test files, low assertion density
208
- - **features:** roadmap items not yet implemented, README promises without backing code
209
- - **docs:** stale documentation, missing command descriptions
210
- - **optimize:** N+1 operations (file I/O / network calls inside loops), redundant re-computation (`JSON.parse`/`stringify` of same data), synchronous blocking in async modules (`readFileSync`/`execSync` alongside async exports), algorithmic complexity (nested `.find()`/`.filter()` in loops creating O(n²)+), unnecessary allocations in hot paths (spread in loops, string concat vs `join()`), regex construction inside loops (should be hoisted), unbounded collection growth (`.push()` without size limits), swallowed errors (`catch {}` / `catch { /* */ }`), suboptimal data structures (array `.includes()` where Set is better), dead assignments, unguarded property access on nullable values (`.length`/`.split()`/`.match()[0]` without null check)
211
- - **security:** Three-pass approach:
212
- - **Pass 1 — Injection & crypto (inline grep):** Scan source files for `eval(`, `execSync`, `exec(`, string concatenation in SQL patterns (`` `SELECT...${`` / `"SELECT..."+`), `md5(`/`sha1(`/`createHash('md5'`/`createHash('sha1'`, hardcoded secrets (`password\s*=\s*['"]`, `api_key\s*=\s*['"]`, `secret\s*=\s*['"`), `Math.random()` used for security purposes.
213
- - **Pass 2 — Auth & access control (inline grep):** Routes without auth middleware (look for `router.get/post/put/delete` without preceding `app.use(...auth...)`), `req.params.id` used directly without ownership check, `JSON.parse(` on `req.body` without schema validation, CORS `origin: '*'` or `Access-Control-Allow-Origin: *`, verbose errors that expose stack traces (`res.json({ stack:`).
214
- - **Pass 3 — Semantic depth (Agent tool, optional):** For M/L items where grep found a suspicious pattern but fix guidance needs code-path tracing, use the Agent tool to spawn the `pan-hardener` subagent (pinned to `model: opus`, off Fable's cybersecurity classifier) to read the specific file and confirm the weakness is genuinely reachable before including in the batch.
215
- - **Classification:** Map findings to priorities: OWASP critical/directly-reachable → P0, High/missing-authorization → P1, Medium/defense-in-depth → P2. Drop LOW/INFO — they don't meet the P0-P2 filter.
216
- - **prompts:** Two operational modes — detect which applies:
217
- - **Execute mode:** Find micro-prompt documents (`.md` files containing ordered prompt blocks, e.g., `## Prompt 1`, `## Prompt 2`, or numbered checklist items `- [ ] Prompt: ...`). Look in `.planning/`, project root, and `docs/` for files matching patterns: `*prompts*`, `*micro-prompt*`, `*prompt-plan*`, `*prompt-sequence*`. Each unchecked/incomplete prompt block is one work item.
218
- - **Generate mode:** Find specification documents (files matching `*spec*`, `*prd*`, `*requirements*`, `*feature*` in `.planning/`, `docs/specs/`, project root) that do NOT already have a corresponding micro-prompt document. Each spec needing decomposition is one work item.
219
-
220
- **Optimize category: convergent re-scan.** On cycles 2+, cross-reference scan findings against previous cycle completions (`cycles[].items` in auto-run state). Only pick genuinely new items — skip IDs already completed or failed. If the count of new findings drops AND cycle efficiency drops below 30% of the prior cycle's, this signals convergence and the `diminishing_returns` stop condition fires.
221
- - Use the Agent tool with Explore subagent for thorough analysis if needed
222
- - Cross-reference findings with any previously completed scan items
223
-
224
- **2.1.3 Classify Items**
225
-
226
- | Priority | Focus | Criteria |
227
- |----------|-------|----------|
228
- | P0 | CRASH/ERROR | Runtime throws, uncaught exceptions |
229
- | P1 | WRONG RESULTS | Silent corruption, incorrect output |
230
- | P2 | TEST GAPS | Missing coverage, low assertion density |
231
- | P3 | INCOMPLETE | Partially implemented features |
232
- | P4 | NEW FEATURES | From roadmap, not yet started |
233
- | P5 | TOOLING | DX improvements, CLI UX |
234
- | P6 | DOCUMENTATION | Docs sync, reference updates |
235
-
236
- For P3-P6 items, compute Reality Score: `RS = (UV + TC + RR) / JS`
237
- - UV = User Value (1-5), TC = Time Criticality (1-5), RR = Risk Reduction (1-5)
238
- - JS = Job Size: XS=1, S=2, M=3, L=5, XL=8
239
- - RS >= 3.0 = DO, RS 1.5-2.9 = DEFER, RS < 1.5 = BACKLOG
240
-
241
- **2.1.4 Filter by Category**
242
- Only keep items within the run's category priority range (see Category Defaults table). Drop items outside the range. If 0 items match: go to Phase 3 (Campaign End).
243
-
244
- **2.1.5 Write Scan**
245
- Write scan results to `.planning/focus/scan-<YYYY-MM-DD>-<category>.md` with:
246
- - Baseline snapshot table (version, tests, modules)
247
- - Items grouped by priority tier, each with: ID, title, symptom, root cause, fix guidance, file paths, effort size
248
- - Summary: item count by priority, total points
249
-
250
- #### Step 2.2: Plan (INLINE — do NOT invoke /pan:focus-plan)
251
-
252
- Create a capacity-budgeted batch from the scan items found in Step 2.1.
253
-
254
- **Capacity Points:** XS=1, S=2, M=4, L=10, XL=20
255
-
256
- **Allocation by Mode:**
257
- - `bugfix`: All budget on P0 mandatory, then P1, then P2-P4 smallest-first. No feature work.
258
- - `balanced`: 60% stability (P0-P2), 40% features (P3-P6)
259
- - `features`: P0 mandatory, then 80% on P3-P5, 20% on P1-P2 quick wins
260
- - `full`: All priorities equally weighted, largest-impact-first
261
-
262
- **Execution Tiers:** XS/S = MICRO, M = STANDARD, L/XL = FULL
263
- Select items fitting within the cycle's `budget_per_cycle`. Order: MICRO first, then STANDARD, then FULL.
264
-
265
- Write batch to `.planning/focus/batch-<YYYY-MM-DD>-<category>.json`:
266
- ```json
267
- { "date": "...", "mode": "...", "budget": N, "allocated": N,
268
- "items": [{ "order": N, "id": "...", "title": "...", "priority": "P1",
269
- "size": "XS", "points": N, "tier": "MICRO", "file": "...", "fix": "..." }],
270
- "deferred": [{ "id": "...", "title": "...", "reason": "..." }] }
271
- ```
272
-
273
- #### Step 2.3: Execute (INLINE — do NOT invoke /pan:focus-exec)
274
-
275
- Implement each item from the batch created in Step 2.2. Record `tests_before` by running the test suite first.
276
-
277
- **For each item in execution order:**
278
-
279
- **MICRO items (XS/S):**
280
- 1. Read target file(s) — always read before editing
281
- 2. Implement the fix
282
- 3. Run the specific test file for the changed module
283
- 4. Pass = DONE | Fail = one fix attempt, then revert changes, mark FAILED
284
-
285
- **STANDARD items (M):**
286
- 1. State understanding: "Item X — Understanding: ..., Files: ..., Confidence: HIGH/MED"
287
- 2. Read target files + test files
288
- 3. Implement across necessary files
289
- 4. Run the project's test suite
290
- 5. Pass = DONE | Regression = revert all changes for this item, mark FAILED
291
-
292
- **FULL items (L/XL):**
293
- 1. State detailed understanding
294
- 2. Read widely: target, callers, tests, related code
295
- 3. Design approach before coding
296
- 4. Implement in logical chunks
297
- 5. Run the project's build step if applicable
298
- 6. Run the project's test suite
299
- 7. Pass = DONE | Fail = investigate (15 min max), then revert, mark FAILED
300
-
301
- **Error Recovery Classification:**
302
- - RECOVERABLE (retry up to 3 times): test failure after code change, build syntax error, file not found (search for moved path)
303
- - UNRECOVERABLE (mark FAILED, move to next item): same failure after 3 retries, permission errors, state corruption, unrelated test regression
304
- A failed item never blocks subsequent items.
305
-
306
- **After all items in the batch:**
307
- 1. Run full test suite — ALL tests must pass
308
- 2. Record `tests_after` from the summary line
309
- 3. If `tests_after < tests_before`: REGRESSION — revert all changes for this cycle, mark all items FAILED
310
- 4. Update the scan file: mark completed/failed items
311
- 5. Stage specific changed files (not `git add -A`) and commit with accurate message listing only verified items
312
- 6. Count: `items_completed`, `items_failed`, `points_used`
313
-
314
- **If `--deep-review` flag is active (run after commit, before recording cycle):**
315
-
316
- Get changed files from this cycle's commit:
317
- ```bash
318
- CHANGED=$(git diff HEAD~1 --name-only 2>/dev/null | grep -E '\.(js|ts|jsx|tsx|py|go|rb|java|php)$')
319
- ```
320
-
321
- Run inline OWASP security check on changed files only:
322
- - Grep each changed file for critical patterns:
323
- - Injection: `eval(`, `execSync(`, SQL string concat (`` `SELECT...${`` ), `child_process.exec(`
324
- - Crypto: `createHash('md5'`, `createHash('sha1'`, `Math.random()` near auth/token/secret context
325
- - Auth bypass: routes with no auth guard added, `req.params` used as DB key without ownership check
326
- - Secrets: `password\s*=\s*['"]`, `apiKey\s*=\s*['"]`, `token\s*=\s*['"]` assigned to a literal value
327
- - Score findings by severity: critical (exploit-ready) → BLOCK; high (auth/injection surface) → WARN; medium/low → LOG
328
-
329
- **Handle deep-review verdict:**
330
-
331
- | Severity found | Verdict | Action |
332
- |---------------|---------|--------|
333
- | Critical pattern in changed file | `block` | STOP campaign — do NOT record cycle, revert last commit, present finding to user |
334
- | High pattern in changed file | `review_required` | STOP campaign — record cycle as completed, flag finding, recommend manual review |
335
- | Medium/low only | `ok_with_minor` | Continue — append findings to `.planning/focus/security-log-<date>.md` |
336
- | No patterns | `ok` | Continue silently |
337
-
338
- Write all non-ok findings to `.planning/focus/security-log-<date>.md` with file:line references.
339
-
340
- #### Step 2.4: Record Cycle
341
-
342
- Run: `pan-tools focus auto --update --items-completed N --items-failed N --points-used N --tests-before N --tests-after N --batch-file <path>`
343
-
344
- Check the response for stop conditions:
345
- - `regression`: Tests decreased — STOP IMMEDIATELY
346
- - `budget_cap`: Cumulative budget exceeded — go to Phase 3
347
- - `max_cycles`: Maximum iterations reached — go to Phase 3
348
- - `zero_completed`: No items completed in this cycle — go to Phase 3
349
- - `diminishing_returns`: Optimize only — cycle efficiency < 30% of previous cycle — go to Phase 3
350
- - `prompts_complete`: Prompts only — all prompts in document executed — go to Phase 3
351
- - `security_complete`: Security only — scan found no HIGH/CRITICAL items remaining — go to Phase 3
352
- - `deep_review_block`: `--deep-review` only — critical pattern detected in changed files — go to Phase 3 with warning
353
- - `null`: Continue to next cycle
354
-
355
- #### Step 2.5: Inter-Cycle Context Management
356
-
357
- Between cycles, manage context to prevent quality degradation over long campaigns:
358
- - **KEEP:** Current cycle goals, test baseline, error states, active file paths
359
- - **SUMMARIZE:** Previous cycle results to a one-line summary each
360
- - **DISCARD:** Raw tool output from previous cycles, superseded scan results
361
-
362
- Display one-line cycle summary: `Cycle N/M | X/Y pts | Z items done | Tests: A -> B`
363
-
364
- #### Step 2.5a: Reflection Gate (Opus 4.7 thinking-capable models only)
365
-
366
- Before committing to the next cycle, call the reflection helper:
367
-
368
- ```
369
- echo '{"run": <run-state>, "cycle": <just-completed-cycle>, "batch": <proposed-next-batch>, "tier": "reasoning"}' \
370
- | pan-tools focus reflection
371
- ```
372
-
373
- The helper returns `{reflect: true, prompt: "..."}` when the current model tier supports extended thinking. If `reflect: true`, think through the prompt — which asks whether running another cycle is worthwhile given telemetry and remaining items — and respond with JSON: `{"continue": true|false, "rationale": "..."}`.
374
-
375
- - If `continue: false`: stop the campaign and treat as a user-reason stop (preserve state, skip to Phase 3).
376
- - If `continue: true`: proceed to the next cycle.
377
-
378
- If the helper returns `reflect: false` (tier doesn't support thinking, or `reflection_enabled: false` in run state, or no next batch): skip this step silently and continue to the next cycle.
379
-
380
- The reflection gate catches "zero progress" or "wrong category" drift earlier than the automatic stop rules.
381
-
382
- **Attention anchor — emit after every cycle summary:**
383
- ```
384
- Remaining: {cycles_left} cycles | {budget_remaining}/{total_budget} pts | Safety: {active_harness_warnings}
385
- Next: Cycle {N+1} — Scan → Plan → Exec → Commit
386
- ```
387
- This prevents lost-in-the-middle drift in 10+ cycle campaigns where the agent forgets budget limits or stop conditions.
388
-
389
- Then continue immediately to the next cycle (back to Step 2.1).
390
-
391
- ### Phase 3: Campaign End
392
-
393
- 1. Run `pan-tools focus auto --status` to get final state
394
- 2. Display campaign summary:
395
-
396
- ```
397
- ## Campaign Complete
398
-
399
- | Metric | Value |
400
- |--------|-------|
401
- | Category | <category> |
402
- | Cycles | N completed |
403
- | Items completed | X |
404
- | Items failed | Y |
405
- | Points used | Z / total_budget |
406
- | Tests | baseline -> current (delta) |
407
- | Stop reason | <reason> |
408
- ```
409
-
410
- 3. Remove safety tag: `git tag -d focus-auto-baseline 2>/dev/null`
411
-
412
- ## 6-Layer Safety Harness
413
-
414
- | Layer | Mechanism | Action |
415
- |-------|-----------|--------|
416
- | Per-cycle budget | `--budget N` per cycle | Limits single-cycle damage |
417
- | Cumulative budget | `--total-budget N` | Prevents runaway spending |
418
- | Iteration limit | `--max-cycles N` | Hard stop on loop count |
419
- | Regression circuit breaker | tests_after < tests_before | Immediate stop, status=stopped |
420
- | Zero-completed guard | 0 items done in a cycle | Stop — further cycles won't help |
421
- | Security gate (`--deep-review`) | Critical/high OWASP pattern in changed files | Revert last commit (critical) or flag for manual review (high), stop campaign |
422
-
423
- ## 9 Behavioral Rules
424
-
425
- 1. **Read Before Write** — Read every file before editing. Understand context, callers, invariants.
426
- 2. **Root Cause** — Fix the actual defect, not symptoms. Trace the code path.
427
- 3. **One Change, One Test** — Test after every code change. MICRO: specific test. STANDARD/FULL: full suite.
428
- 4. **Follow the Plan** — Implement exactly what the batch says. No scope creep.
429
- 5. **Cross-Platform** — Use platform-agnostic path APIs. Follow the project's module format conventions.
430
- 6. **Revert Fast** — 5 min limit on debugging a single failure, then revert and mark FAILED.
431
- 7. **Verify Understanding** — State understanding for M+ items before coding.
432
- 8. **Preserve Tests** — Never change test expectations to match broken code.
433
- 9. **Accurate Commits** — Only claim verified items in commit messages. Include actual test counts.
434
- 10. **Vary Similar Fixes** — When 3+ items in a cycle share the same fix pattern (e.g., "add null check"), re-read each module's conventions before applying. The same pattern may need different implementations in different modules. Check after the 3rd fix whether a shared helper would be better than scattered copies.
435
-
436
- ## Prompts Category — Execution Details
437
-
438
- The prompts category operates in two distinct modes. Detect which mode applies during the scan phase based on what the scan finds.
439
-
440
- ### Execute Mode (micro-prompt document found)
441
-
442
- A micro-prompt document contains an ordered sequence of self-contained implementation prompts. Each prompt describes a single, testable change.
443
-
444
- **Document format recognized:**
445
-
446
- ```markdown
447
- # Micro-Prompts: <Feature Name>
448
-
449
- Source: <spec file or description>
450
- Generated: <date>
451
-
452
- ## Prompt 1: <title>
453
- - [ ] Complete
454
-
455
- <implementation instructions>
456
-
457
- ### Expected outcome
458
- <what should work after this prompt>
459
-
460
- ### Test
461
- <how to verify>
462
-
463
- ---
464
-
465
- ## Prompt 2: <title>
466
- - [ ] Complete
467
- ...
468
- ```
469
-
470
- Alternative format — checklist style:
471
- ```markdown
472
- - [ ] Prompt 1: <title> — <instructions>
473
- - [ ] Prompt 2: <title> — <instructions>
474
- ```
475
-
476
- **Execution strategy:**
477
-
478
- 1. Read the micro-prompt document, identify all prompt blocks
479
- 2. Find the first uncompleted prompt (unchecked `- [ ]`)
480
- 3. Execute that prompt's instructions — implement the code changes described
481
- 4. Run the project's test suite (or the prompt-specific test if given)
482
- 5. If tests pass: mark the prompt as complete (`- [x]`), commit, move to next prompt
483
- 6. If tests fail: one fix attempt, then revert and mark prompt as FAILED, move to next prompt
484
- 7. Each prompt = one batch item. Budget: 1 prompt per cycle unless prompt is trivial (XS)
485
- 8. Record `prompts_remaining` count in cycle update — when 0, `prompts_complete` stop fires
486
-
487
- **Key rules:**
488
- - Execute prompts in document order — NEVER skip ahead or reorder
489
- - Each prompt is atomic — commit after each successful prompt
490
- - A failed prompt does NOT block subsequent prompts (mark failed, continue)
491
- - The prompt document is the plan — do not re-plan or expand scope beyond what each prompt says
492
-
493
- ### Generate Mode (spec found without corresponding prompt document)
494
-
495
- When a specification document is found that doesn't have a matching micro-prompt document, decompose it into ordered prompts.
496
-
497
- **Generation strategy:**
498
-
499
- 1. Read the spec document thoroughly
500
- 2. Identify all discrete implementation steps
501
- 3. Order steps by dependency — foundation first, features that depend on earlier steps later
502
- 4. For each step, write a prompt block containing:
503
- - Clear title describing the change
504
- - Implementation instructions (files to create/modify, logic to implement)
505
- - Expected outcome (what should work after this prompt)
506
- - Test instruction (how to verify the prompt succeeded)
507
- 5. Write the micro-prompt document to `.planning/prompts/<spec-slug>-prompts.md`
508
- 6. Each generated document = one batch item (typically M or L size)
509
-
510
- **Decomposition heuristics:**
511
- - One prompt per logical unit of work (one function, one API endpoint, one component)
512
- - Each prompt should be independently testable
513
- - Prompts should be 5-30 minutes of implementation work each
514
- - Aim for 5-20 prompts per spec (split large specs, combine trivial items)
515
- - Include a "Prompt 0: Project setup" if the spec requires new dependencies or scaffolding
516
- - Include a final "Prompt N: Integration test" that verifies the full feature end-to-end
517
-
518
- **After generation:** The document is written and committed. The next cycle will detect it in execute mode and begin executing prompts sequentially.
519
-
520
- ## Security Category — Execution Details
521
-
522
- The security category scans for OWASP Top 10 (2025) violations and STRIDE threats, then fixes them cycle by cycle until the scan returns zero HIGH/CRITICAL findings.
523
-
524
- ### Scan approach (Step 2.1)
525
-
526
- Three passes per cycle:
527
-
528
- **Pass 1 — Fast grep scan (always runs):**
529
-
530
- | OWASP | Grep pattern | Priority |
531
- |-------|-------------|---------|
532
- | A03 Injection | `eval(`, `execSync(`, `` `SELECT.*\${ ``, `child_process.exec(` | P0 |
533
- | A02 Crypto | `createHash\(['"]md5\|sha1`, `Math\.random\(\)` near auth/token | P0 |
534
- | A01 Access | Route without auth middleware, IDOR (raw `req.params.id` to DB) | P1 |
535
- | A05 Misconfig | `origin:\s*['"]?\*`, `Access-Control-Allow-Origin: \*`, stack in response | P1 |
536
- | A07 Auth | No session expiry, credentials in URL params | P1 |
537
- | A04 Design | Missing rate-limit on auth/payment endpoints | P2 |
538
- | A09 Logging | Security events (`login`, `payment`, `admin`) with no log call nearby | P2 |
539
-
540
- **Pass 2 — Structural check (always runs):**
541
- - Read route files and check: does every mutating endpoint (POST/PUT/PATCH/DELETE) have auth middleware before the handler?
542
- - Check for hardcoded secrets: grep for `['"][A-Za-z0-9_]{20,}['"]` assigned to variables named `key`/`token`/`secret`/`password`/`apiKey`
543
- - Check for prototype pollution risk: `Object.assign(req.body)` or spread from untrusted input into a stored object
544
-
545
- **Pass 3 — Semantic depth (Agent tool, for M/L items only):**
546
- When a pattern match needs code-path confirmation, spawn an Explore subagent:
547
- > "Read [file]. Confirm whether [line N] is reachable from an unauthenticated request path and whether the input is sanitized before use."
548
-
549
- Use the confirmation to decide whether to include the item at P0/P1 or drop it as a false positive.
550
-
551
- ### Item classification
552
-
553
- | Hardener severity | Focus priority | Example |
554
- |------------------|----------------|---------|
555
- | Critical | P0 | `eval(req.body.code)` — direct remote code execution risk |
556
- | High | P1 | Missing authorization on admin route |
557
- | Medium | P2 | Rate-limiting absent on login |
558
- | Low / Info | DROP | Missing security header on non-sensitive route |
559
-
560
- ### Execution (Step 2.3)
561
-
562
- This is authorized, defensive hardening of the user's own codebase — you assess and remediate weaknesses; you never write exploit code or attack instructions.
563
-
564
- **Model routing (important).** Some session models — notably Claude Fable 5 — run a cybersecurity classifier that can refuse defensive security review. Do the vulnerability *assessment* (the Pass 3 semantic analysis and each item's risk statement below) by spawning the `pan-hardener` subagent, which is pinned to `model: opus` and is not subject to that classifier. The main loop runs the grep triage (Passes 1–2) and implements the fixes; it does not narrate exploit paths inline. If any security step is refused on the main loop, delegate it to `pan-hardener` and continue.
565
-
566
- Treat each security item as a STANDARD or FULL item regardless of effort estimate:
567
-
568
- 1. **State the risk:** "This is [OWASP category]. How it could be reached and the impact: [unvalidated input reaches X → Y → data exposure or loss], so it must be fixed."
569
- 2. **Read the file** — confirm the pattern is real, not a false positive
570
- 3. **Implement the fix** — use established patterns (parameterized queries, allowlists, bcrypt, rate-limit middleware)
571
- 4. **Write or update the test** — every security fix MUST have a test that proves the weakness is closed (e.g., send the crafted/invalid input, assert 400/403 not 200)
572
- 5. **Run full test suite** — regression check before marking DONE
573
-
574
- ### Stop condition
575
-
576
- `security_complete` fires when the scan finds zero P0/P1 items. P2 items (medium) may remain — they won't stop the campaign unless `zero_completed` fires (no items at all).
577
-
578
- A security campaign that ends with `security_complete` means: no critical or high OWASP violations found in the scanned files. Medium/low items can be addressed in subsequent targeted passes or documented as accepted risk.
579
-
580
- ---
581
-
582
- ## Distill Category — Execution Details
583
-
584
- The `distill` category targets **AI-generated code bloat** with a 5-pass pipeline based on the SOTA agentic-refactoring architecture (deterministic-first, LLM-on-narrow-spans).
585
-
586
- ### Pipeline
587
-
588
- | Pass | What | Cost | Tier output |
589
- |------|------|------|-------------|
590
- | 1 | **Deterministic patterns** — phantom try/catch, unused imports, magic numbers, long functions, wide param lists | Free | safe / review |
591
- | 2 | **AST-style analysis** — single-instance factories, deep nesting | Free | review |
592
- | 3 | **Cross-file graph** — repeated 5+ line blocks, unreferenced exports | Free | review |
593
- | 4 | **LLM judgment** — pan-distiller agent receives ONLY flagged spans (max 50 lines context per finding); validates pattern, refines tier, proposes minimal rewrite | LLM tokens | safe / review / risky |
594
- | 5 | **Cross-session memory** — compares findings to `.planning/memory/distill-patterns.md`; flags **regressed** patterns ("we already fixed this") | Free | metadata |
595
-
596
- ### Safety Tiers
597
-
598
- | Tier | Rule | Action |
599
- |------|------|--------|
600
- | `safe` | Deterministic, behavior-preserving (e.g., remove unused import) | Auto-applied |
601
- | `review_required` | Behavior preserved under invariants but human should verify | Surfaced to user |
602
- | `risky` | Cross-file impact or might surface latent bugs | Never auto-applied |
603
-
604
- A finding's confidence below 0.85 is automatically downgraded to `review_required` regardless of original tier.
605
-
606
- ### Bloat Budget
607
-
608
- After each cycle, distill computes:
609
- - **touched_loc** — total LOC modified in cycle
610
- - **removable_loc** — sum of `loc_saved` across findings
611
- - **essential_loc** — touched_loc − removable_loc
612
- - **bloat ratio** — touched_loc / essential_loc
613
-
614
- Default threshold: **2.0x**. If a cycle's ratio exceeds threshold, the bloat budget gate flags it for review.
615
-
616
- ### Stop condition
617
-
618
- `distill_complete` fires when the scan finds zero bloat findings. The codebase is fully distilled for the patterns the deterministic + AST + graph passes detect.
619
-
620
- ### CLI
621
-
622
- ```bash
623
- node ~/.claude/pan-wizard-core/bin/pan-tools.cjs distill scan
624
- node ~/.claude/pan-wizard-core/bin/pan-tools.cjs distill analyze [--touched-loc N] [--bloat-threshold X]
625
- node ~/.claude/pan-wizard-core/bin/pan-tools.cjs distill report
626
- ```
627
-
628
- `scan` returns findings. `analyze` adds bloat budget + regressed pattern detection. `report` writes findings to `.planning/memory/distill-patterns.md` for the next session.
629
-
630
- <failure_pattern_capture>
631
- When the same failure pattern appears in 2+ items within a campaign, capture it for future runs.
632
-
633
- **Detection:** After marking an item FAILED, check if the error classification matches any previous failure in this campaign:
634
- - Same error type (e.g., "test regression in unrelated module")
635
- - Same file or module involved
636
- - Same root cause category (e.g., "missing null check pattern", "import path mismatch")
637
-
638
- **Capture (when pattern repeats):**
639
- Append to `.planning/focus/failure-patterns.md`:
640
- ```markdown
641
- ## Pattern: {short description}
642
- - **First seen:** Cycle {N}, Item {ID}
643
- - **Recurrence:** Cycle {M}, Item {ID2}
644
- - **Error type:** {classification}
645
- - **Root cause:** {what actually went wrong}
646
- - **Avoidance rule:** {what to check before attempting similar items}
647
- - **Files involved:** {paths}
648
- ```
649
-
650
- **Use (on subsequent cycles):**
651
- Before executing an item, check if its target files or error category match a known failure pattern. If so:
652
- - Apply the avoidance rule BEFORE implementing
653
- - If the pattern suggests the item will fail (e.g., "all items touching module X regress"), skip with reason "matches known failure pattern — defer to manual investigation"
654
-
655
- This prevents the campaign from burning budget on items that will predictably fail.
656
- </failure_pattern_capture>
657
-
658
- ## NEVER DO
659
-
660
- - Invoke the Skill tool — scan/plan/exec must run inline so state stays coherent across cycles
661
- - Stop or pause between phases — interruptions break the autonomous loop and lose cycle momentum
662
- - Ask the user questions after category selection — the whole point is autonomous execution; questions defeat that
663
- - Skip the baseline test capture — without a baseline, the regression circuit breaker has nothing to compare against
664
- - Continue after a test regression — a test count decrease means code was broken; continuing compounds the damage
665
- - Expand scope beyond what the scan found — scope creep in an autonomous loop compounds unpredictably across cycles
666
- - Run more cycles than --max-cycles — the limit exists to cap total cost and prevent runaway loops
667
- - Spend more points than --total-budget — the budget cap is the user's cost control mechanism
668
- - Skip recording cycle results via --update — unrecorded cycles break resume, status, and stop-condition checks
669
- - Change test expectations to match broken code — this hides bugs instead of fixing them
670
- - Use `git add -A` or `git add .` — bulk staging can accidentally commit secrets, build artifacts, or unrelated changes
671
-
672
- ## ALWAYS DO
673
-
674
- - Execute all phases autonomously from start to finish
675
- - Capture baseline before first cycle
676
- - Read every file before editing it
677
- - Test after every code change
678
- - Record every cycle via `pan-tools focus auto --update`
679
- - Stop on ANY safety harness trigger
680
- - Revert fast when stuck (5 min limit)
681
- - Display one-line cycle summary between cycles
682
- - Display campaign summary table at end
683
- - Commit once per cycle with accurate item list
1
+ ---
2
+ name: focus-auto
3
+ group: Focus
4
+ description: Continuous scan-plan-exec loop with purpose-driven categories and 5-layer safety harness
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Bash
10
+ - Grep
11
+ - Glob
12
+ - Agent
13
+ ---
14
+
15
+ # /pan:focus-auto — Continuous Autonomous Improvement Campaigns
16
+
17
+ Run purpose-driven improvement campaigns with a single command. The auto-runner orchestrates scan, plan, and exec cycles automatically with category-scoped scanning, intelligent defaults, and structured stopping.
18
+
19
+ **ADR:** ADR-0015 | **Heritage:** execplan budget + PanMonty categories + focus-exec pipeline
20
+
21
+ ## Project Scope Boundary
22
+
23
+ This command runs improvement campaigns on the **host project's source code** — not on PAN Wizard's own infrastructure.
24
+
25
+ **Exclude these directories from scanning and execution:**
26
+ - `.claude/`, `.github/copilot-instructions.md`, `.opencode/`, `.gemini/`, `.codex/` — PAN runtime directories
27
+ - Any `pan-wizard-core/`, `pan-tools`, agent `.md`, or command `.md` files within PAN runtime directories
28
+
29
+ **These directories are PAN's own tooling installed into the project.** Do not scan PAN files for TODOs, do not report PAN files as lacking coverage, do not modify PAN agents/commands/core as part of a campaign. If a scan finding or batch item targets a PAN infrastructure file — DROP IT.
30
+
31
+ ---
32
+
33
+ <completion_contract>
34
+ A campaign is complete when ANY stop condition is met:
35
+ 1. Max cycles reached (--max-cycles, default 10)
36
+ 2. Total budget exhausted (--total-budget, default 200)
37
+ 3. Scan returns zero items for the selected category
38
+ 4. Context window drops below 25% (CRITICAL threshold)
39
+ 5. User sends /pan:focus-auto --stop
40
+ 6. Category-specific completion (e.g., prompts_remaining === 0)
41
+
42
+ Each cycle is complete when: scan → plan → exec → commit succeeds, OR a safety harness triggers and the cycle is cleanly aborted with state preserved.
43
+ </completion_contract>
44
+
45
+ ## FIRST ACTION — Category Selection (if no --category argument)
46
+
47
+ If `$ARGUMENTS` does NOT contain `--category`, you MUST ask the user before doing anything else.
48
+
49
+ **Display this text menu and STOP — wait for the user to reply:**
50
+
51
+ ```
52
+ Which category should this auto campaign focus on?
53
+
54
+ 1. **cleanup** — Dead code, unused imports, duplicated logic, magic numbers (P3-P5)
55
+ 2. **stability** — Unguarded file ops, missing error handling, crash risks (P0-P2)
56
+ 3. **tests** — Missing test coverage, low assertion density (P2-P5)
57
+ 4. **features** — Roadmap items, new capabilities (P3-P5)
58
+ 5. **docs** — Stale documentation, missing command descriptions (P5-P6)
59
+ 6. **optimize** — Performance bottlenecks, redundant computation, robustness hardening (P1-P4)
60
+ 7. **prompts** — Execute micro-prompt documents sequentially, or generate them from specs (P0-P6)
61
+ 8. **security** — OWASP Top 10 violations, STRIDE threats, auth/injection/crypto hardening (P0-P2)
62
+ 9. **distill** — AI code-bloat: phantom try/catch, unused imports, repeated blocks, premature abstraction, god functions (P1-P5)
63
+
64
+ Reply with a number (1-9) or category name.
65
+ ```
66
+
67
+ **After the user replies, map their response to a category name:**
68
+ - "1" or "cleanup" → SELECTED_CATEGORY = cleanup
69
+ - "2" or "stability" → SELECTED_CATEGORY = stability
70
+ - "3" or "tests" → SELECTED_CATEGORY = tests
71
+ - "4" or "features" → SELECTED_CATEGORY = features
72
+ - "5" or "docs" → SELECTED_CATEGORY = docs
73
+ - "6" or "optimize" → SELECTED_CATEGORY = optimize
74
+ - "7" or "prompts" → SELECTED_CATEGORY = prompts
75
+ - "8" or "security" → SELECTED_CATEGORY = security
76
+ - "9" or "distill" → SELECTED_CATEGORY = distill
77
+
78
+ Wait for the user's reply before proceeding. Do not guess or pick a default category.
79
+
80
+ ## AUTONOMY RULES (apply AFTER category is selected)
81
+
82
+ - **DO NOT invoke the Skill tool.** All scan, plan, and exec work is done INLINE within this command.
83
+ - **DO NOT stop between phases.** Execute Phase 0 through Phase 3 (or until a safety harness triggers) without pausing.
84
+ - **DO NOT ask the user any more questions.** After category selection, run fully autonomously.
85
+ - **DO NOT show intermediate results.** Only display: the cycle summary line after each cycle, and the campaign summary table at the end.
86
+
87
+ ## Arguments
88
+
89
+ ```
90
+ /pan:focus-auto [--source scan|backlog] [--category CAT] [--mode MODE] [--budget N]
91
+ [--max-cycles N] [--total-budget N] [--continue] [--stop] [--status]
92
+ [--dry-run] [--deep-review]
93
+ [--parallel-research] [--parallel-verify] [--clean-seal]
94
+ ```
95
+
96
+ | Flag | Default | Description |
97
+ |------|---------|-------------|
98
+ | `--source` | `scan` | Work selection. `scan` = category-scoped code scan (below). `backlog` = rank actionable items from `roadmap.md` / `requirements.md` (ADR-0031). |
99
+ | `--category` | null (all) | cleanup, tests, stability, features, docs, optimize, prompts, security, distill. Applies to `--source scan`. |
100
+ | `--mode` | category-dependent | bugfix, balanced, features, full |
101
+ | `--budget` | category-dependent | Points per cycle (5-100) |
102
+ | `--max-cycles` | 10 | Maximum iterations (1-50) |
103
+ | `--total-budget` | 500 | Cumulative points cap (5-5000) |
104
+ | `--continue` | — | Resume stopped/interrupted run |
105
+ | `--stop` | — | Gracefully stop active run |
106
+ | `--status` | — | Show current campaign progress |
107
+ | `--dry-run` | — | Show plan without executing |
108
+ | `--deep-review` | off | After every exec cycle, run inline OWASP security check on changed files. Verdict `block` or `review_required` stops the campaign (6th safety harness). Works with all categories. |
109
+ | `--parallel-research` | off | Fan out the per-item *research* stage via the Workflow tool (read-only agents). No-op fallback to sequential where the host has no Workflow tool. (ADR-0031) |
110
+ | `--parallel-verify` | off | Fan out the per-item *verify* stage via the Workflow tool (read-only). The implement/exec stage always stays a single agent. (ADR-0031) |
111
+ | `--clean-seal` | off | After the loop's last item, run one clean build + full verification (commands from `config.json → build`/`verification`) to catch cross-item orphans. (ADR-0031) |
112
+
113
+ ## Category Defaults
114
+
115
+ | Category | Priority Range | Default Mode | Default Budget |
116
+ |----------|---------------|--------------|----------------|
117
+ | cleanup | P3-P5 | balanced | 50 |
118
+ | tests | P2-P5 | balanced | 50 |
119
+ | stability | P0-P2 | bugfix | 40 |
120
+ | features | P3-P5 | features | 50 |
121
+ | docs | P5-P6 | balanced | 30 |
122
+ | optimize | P1-P4 | balanced | 50 |
123
+ | prompts | P0-P6 | balanced | 100 |
124
+ | security | P0-P2 | bugfix | 40 |
125
+
126
+ ## Backlog source (`--source backlog`, ADR-0031)
127
+
128
+ When `--source backlog` is set, work is selected from the **curated planning surface** instead of a code scan — for campaigns that work a human-prioritized roadmap rather than whatever grep finds.
129
+
130
+ 1. **Read the backlog once** at Phase 0: actionable items are unchecked rows in `roadmap.md` (phase/plan checkboxes) and unmet `requirements.md` REQ rows. Skip anything struck, completed, or marked blocked.
131
+ 2. **Score from the CURRENT document — never a hardcoded ID list.** For each item, derive `RS = (UserValue + TimeCriticality + RiskReduction) / Effort` (1–5 each; Effort from the row's size tag). Sort by wave/priority ascending → RS descending → effort ascending. This re-derives the order from whatever the roadmap says today, so it never goes stale.
132
+ 3. **Pop the top survivor each cycle**; re-rank only if a landing changed a dependency. The same budget/cycle/context stops and safety harness apply unchanged.
133
+ 4. The backlog ranker reads only PAN's planning files — it embeds **no** project-specific item IDs, test counts, or build commands. A project with no actionable backlog items is a clean stop (`scan returns zero items` equivalent).
134
+
135
+ ## Concurrency model (when `--parallel-research` / `--parallel-verify`, ADR-0031)
136
+
137
+ The proven shape is **parallel read-only research → exactly ONE serial implement/exec → parallel read-only verify**:
138
+
139
+ | Stage | Concurrency | Why |
140
+ |-------|-------------|-----|
141
+ | Research | Parallel (Workflow fan-out, read-only) when `--parallel-research` | Reads source/specs; mutates nothing. |
142
+ | Implement / exec | **Single agent, always** | Mutates the tree; never fanned out. |
143
+ | Verify | Parallel (Workflow fan-out, read-only) when `--parallel-verify` | Runs against the already-built tree; mutates nothing. |
144
+
145
+ **Serial-build constraint:** if `.planning/config.json → concurrency.serial_build` is `true`, the runner additionally guarantees at most one build process at any instant across the whole loop (for projects whose build trees corrupt under concurrency). This is **off by default** — most projects build in parallel safely. PAN does not assume it.
146
+
147
+ **Commit-quality gates** (advisory, always on): a *staging-miss guard* (no exec-touched file left unstaged) and an *orphan audit* (HEAD must not reference a symbol defined only in an uncommitted file). With `--clean-seal`, a single clean build + full verification runs after the last item to catch cross-item orphans the per-cycle incremental commits hid.
148
+
149
+ ## Pipeline
150
+
151
+ ### Phase 0: Initialization
152
+
153
+ 1. Parse arguments from `$ARGUMENTS`
154
+ 2. Handle quick operations first:
155
+ - If `--status`: run `pan-tools focus auto --status`, display result, STOP
156
+ - If `--stop`: run `pan-tools focus auto --stop`, display result, STOP
157
+ 3. If `--continue`:
158
+ - Run `pan-tools focus auto --continue` to resume
159
+ - Read the restored state to get category, mode, budget, etc.
160
+ - Skip to Phase 2 (Main Loop)
161
+ 4. If no `--category` was provided, you already displayed the menu in FIRST ACTION above. Use SELECTED_CATEGORY from the user's reply.
162
+ 5. Initialize new run using the category from step 4:
163
+ - Run `pan-tools focus auto --category <SELECTED_CATEGORY> [--mode MODE] [--budget N] [--max-cycles N] [--total-budget N] [--dry-run]`
164
+ - If `--dry-run`: display the plan, STOP
165
+ - Record the run state
166
+
167
+ ### Phase 1: Baseline Capture
168
+
169
+ 1. Run the project's test suite (discover the test command from `package.json` scripts, `Makefile`, or project docs)
170
+ 2. Record baseline test count from the summary line (e.g., "tests 1314")
171
+ 3. If tests fail: ERROR — "Cannot start: N tests failing. Fix tests before running auto campaign."
172
+ 4. Run `git status` to verify clean working tree (warn if dirty, don't block)
173
+ 5. Create safety tag: `git tag -f focus-auto-baseline`
174
+
175
+ <phase_dependencies>
176
+ Phase 0 → Phase 1: Init MUST succeed before baseline (state tracking requires valid run)
177
+ Phase 1 → Phase 2: Baseline MUST be captured before main loop (regression circuit breaker needs it)
178
+ Phase 2 (each cycle): Scan → Plan → Exec → Commit is strictly sequential within a cycle
179
+ - Scan MUST complete before plan (plan needs scan items)
180
+ - Plan MUST complete before exec (exec needs batch file)
181
+ - Exec MUST complete and tests pass before commit (never commit broken code)
182
+
183
+ HARD STOP conditions:
184
+ - Phase 1 fails (tests broken): Do not enter main loop — report and exit
185
+ - Any cycle: test count drops below baseline after revert → stop campaign, preserve state
186
+ - Context drops below 25%: stop campaign cleanly (safety harness 3)
187
+ </phase_dependencies>
188
+
189
+ ### Phase 2: Main Loop
190
+
191
+ **For each cycle (1 to max_cycles), execute Steps 2.1 through 2.5 without stopping:**
192
+
193
+ #### Step 2.1: Scan (INLINE — do NOT invoke /pan:focus-scan)
194
+
195
+ Perform a deep codebase scan to find actionable work items with evidence.
196
+
197
+ **2.1.1 Read Codebase State**
198
+ - Read project source files via Glob + Read: modules, entry points, key directories
199
+ - Read planning state: `.planning/config.json`, any state/roadmap files that exist
200
+ - Read `package.json` (or equivalent project manifest) for version and entry points
201
+
202
+ **2.1.2 Search for Issues**
203
+ - Grep for `TODO`, `FIXME`, `HACK`, `STUB` in source and test directories
204
+ - Grep for error-prone patterns relevant to the category:
205
+ - **stability:** unguarded `readdirSync`/`readFileSync` without try-catch, `existsSync` calls, `.forEach()` on unverified values, `parseInt` without NaN checks, `.match()` results accessed without null check
206
+ - **cleanup:** dead code, unused imports, duplicated logic, magic numbers
207
+ - **tests:** modules without corresponding test files, low assertion density
208
+ - **features:** roadmap items not yet implemented, README promises without backing code
209
+ - **docs:** stale documentation, missing command descriptions
210
+ - **optimize:** N+1 operations (file I/O / network calls inside loops), redundant re-computation (`JSON.parse`/`stringify` of same data), synchronous blocking in async modules (`readFileSync`/`execSync` alongside async exports), algorithmic complexity (nested `.find()`/`.filter()` in loops creating O(n²)+), unnecessary allocations in hot paths (spread in loops, string concat vs `join()`), regex construction inside loops (should be hoisted), unbounded collection growth (`.push()` without size limits), swallowed errors (`catch {}` / `catch { /* */ }`), suboptimal data structures (array `.includes()` where Set is better), dead assignments, unguarded property access on nullable values (`.length`/`.split()`/`.match()[0]` without null check)
211
+ - **security:** Three-pass approach:
212
+ - **Pass 1 — Injection & crypto (inline grep):** Scan source files for `eval(`, `execSync`, `exec(`, string concatenation in SQL patterns (`` `SELECT...${`` / `"SELECT..."+`), `md5(`/`sha1(`/`createHash('md5'`/`createHash('sha1'`, hardcoded secrets (`password\s*=\s*['"]`, `api_key\s*=\s*['"]`, `secret\s*=\s*['"`), `Math.random()` used for security purposes.
213
+ - **Pass 2 — Auth & access control (inline grep):** Routes without auth middleware (look for `router.get/post/put/delete` without preceding `app.use(...auth...)`), `req.params.id` used directly without ownership check, `JSON.parse(` on `req.body` without schema validation, CORS `origin: '*'` or `Access-Control-Allow-Origin: *`, verbose errors that expose stack traces (`res.json({ stack:`).
214
+ - **Pass 3 — Semantic depth (Agent tool, optional):** For M/L items where grep found a suspicious pattern but fix guidance needs code-path tracing, use the Agent tool to spawn the `pan-hardener` subagent (pinned to `model: opus`, off Fable's cybersecurity classifier) to read the specific file and confirm the weakness is genuinely reachable before including in the batch.
215
+ - **Classification:** Map findings to priorities: OWASP critical/directly-reachable → P0, High/missing-authorization → P1, Medium/defense-in-depth → P2. Drop LOW/INFO — they don't meet the P0-P2 filter.
216
+ - **prompts:** Two operational modes — detect which applies:
217
+ - **Execute mode:** Find micro-prompt documents (`.md` files containing ordered prompt blocks, e.g., `## Prompt 1`, `## Prompt 2`, or numbered checklist items `- [ ] Prompt: ...`). Look in `.planning/`, project root, and `docs/` for files matching patterns: `*prompts*`, `*micro-prompt*`, `*prompt-plan*`, `*prompt-sequence*`. Each unchecked/incomplete prompt block is one work item.
218
+ - **Generate mode:** Find specification documents (files matching `*spec*`, `*prd*`, `*requirements*`, `*feature*` in `.planning/`, `docs/specs/`, project root) that do NOT already have a corresponding micro-prompt document. Each spec needing decomposition is one work item.
219
+
220
+ **Optimize category: convergent re-scan.** On cycles 2+, cross-reference scan findings against previous cycle completions (`cycles[].items` in auto-run state). Only pick genuinely new items — skip IDs already completed or failed. If the count of new findings drops AND cycle efficiency drops below 30% of the prior cycle's, this signals convergence and the `diminishing_returns` stop condition fires.
221
+ - Use the Agent tool with Explore subagent for thorough analysis if needed
222
+ - Cross-reference findings with any previously completed scan items
223
+
224
+ **2.1.3 Classify Items**
225
+
226
+ | Priority | Focus | Criteria |
227
+ |----------|-------|----------|
228
+ | P0 | CRASH/ERROR | Runtime throws, uncaught exceptions |
229
+ | P1 | WRONG RESULTS | Silent corruption, incorrect output |
230
+ | P2 | TEST GAPS | Missing coverage, low assertion density |
231
+ | P3 | INCOMPLETE | Partially implemented features |
232
+ | P4 | NEW FEATURES | From roadmap, not yet started |
233
+ | P5 | TOOLING | DX improvements, CLI UX |
234
+ | P6 | DOCUMENTATION | Docs sync, reference updates |
235
+
236
+ For P3-P6 items, compute Reality Score: `RS = (UV + TC + RR) / JS`
237
+ - UV = User Value (1-5), TC = Time Criticality (1-5), RR = Risk Reduction (1-5)
238
+ - JS = Job Size: XS=1, S=2, M=3, L=5, XL=8
239
+ - RS >= 3.0 = DO, RS 1.5-2.9 = DEFER, RS < 1.5 = BACKLOG
240
+
241
+ **2.1.4 Filter by Category**
242
+ Only keep items within the run's category priority range (see Category Defaults table). Drop items outside the range. If 0 items match: go to Phase 3 (Campaign End).
243
+
244
+ **2.1.5 Write Scan**
245
+ Write scan results to `.planning/focus/scan-<YYYY-MM-DD>-<category>.md` with:
246
+ - Baseline snapshot table (version, tests, modules)
247
+ - Items grouped by priority tier, each with: ID, title, symptom, root cause, fix guidance, file paths, effort size
248
+ - Summary: item count by priority, total points
249
+
250
+ #### Step 2.2: Plan (INLINE — do NOT invoke /pan:focus-plan)
251
+
252
+ Create a capacity-budgeted batch from the scan items found in Step 2.1.
253
+
254
+ **Capacity Points:** XS=1, S=2, M=4, L=10, XL=20
255
+
256
+ **Allocation by Mode:**
257
+ - `bugfix`: All budget on P0 mandatory, then P1, then P2-P4 smallest-first. No feature work.
258
+ - `balanced`: 60% stability (P0-P2), 40% features (P3-P6)
259
+ - `features`: P0 mandatory, then 80% on P3-P5, 20% on P1-P2 quick wins
260
+ - `full`: All priorities equally weighted, largest-impact-first
261
+
262
+ **Execution Tiers:** XS/S = MICRO, M = STANDARD, L/XL = FULL
263
+ Select items fitting within the cycle's `budget_per_cycle`. Order: MICRO first, then STANDARD, then FULL.
264
+
265
+ Write batch to `.planning/focus/batch-<YYYY-MM-DD>-<category>.json`:
266
+ ```json
267
+ { "date": "...", "mode": "...", "budget": N, "allocated": N,
268
+ "items": [{ "order": N, "id": "...", "title": "...", "priority": "P1",
269
+ "size": "XS", "points": N, "tier": "MICRO", "file": "...", "fix": "..." }],
270
+ "deferred": [{ "id": "...", "title": "...", "reason": "..." }] }
271
+ ```
272
+
273
+ #### Step 2.3: Execute (INLINE — do NOT invoke /pan:focus-exec)
274
+
275
+ Implement each item from the batch created in Step 2.2. Record `tests_before` by running the test suite first.
276
+
277
+ **For each item in execution order:**
278
+
279
+ **MICRO items (XS/S):**
280
+ 1. Read target file(s) — always read before editing
281
+ 2. Implement the fix
282
+ 3. Run the specific test file for the changed module
283
+ 4. Pass = DONE | Fail = one fix attempt, then revert changes, mark FAILED
284
+
285
+ **STANDARD items (M):**
286
+ 1. State understanding: "Item X — Understanding: ..., Files: ..., Confidence: HIGH/MED"
287
+ 2. Read target files + test files
288
+ 3. Implement across necessary files
289
+ 4. Run the project's test suite
290
+ 5. Pass = DONE | Regression = revert all changes for this item, mark FAILED
291
+
292
+ **FULL items (L/XL):**
293
+ 1. State detailed understanding
294
+ 2. Read widely: target, callers, tests, related code
295
+ 3. Design approach before coding
296
+ 4. Implement in logical chunks
297
+ 5. Run the project's build step if applicable
298
+ 6. Run the project's test suite
299
+ 7. Pass = DONE | Fail = investigate (15 min max), then revert, mark FAILED
300
+
301
+ **Error Recovery Classification:**
302
+ - RECOVERABLE (retry up to 3 times): test failure after code change, build syntax error, file not found (search for moved path)
303
+ - UNRECOVERABLE (mark FAILED, move to next item): same failure after 3 retries, permission errors, state corruption, unrelated test regression
304
+ A failed item never blocks subsequent items.
305
+
306
+ **After all items in the batch:**
307
+ 1. Run full test suite — ALL tests must pass
308
+ 2. Record `tests_after` from the summary line
309
+ 3. If `tests_after < tests_before`: REGRESSION — revert all changes for this cycle, mark all items FAILED
310
+ 4. Update the scan file: mark completed/failed items
311
+ 5. Stage specific changed files (not `git add -A`) and commit with accurate message listing only verified items
312
+ 6. Count: `items_completed`, `items_failed`, `points_used`
313
+
314
+ **If `--deep-review` flag is active (run after commit, before recording cycle):**
315
+
316
+ Get changed files from this cycle's commit:
317
+ ```bash
318
+ CHANGED=$(git diff HEAD~1 --name-only 2>/dev/null | grep -E '\.(js|ts|jsx|tsx|py|go|rb|java|php)$')
319
+ ```
320
+
321
+ Run inline OWASP security check on changed files only:
322
+ - Grep each changed file for critical patterns:
323
+ - Injection: `eval(`, `execSync(`, SQL string concat (`` `SELECT...${`` ), `child_process.exec(`
324
+ - Crypto: `createHash('md5'`, `createHash('sha1'`, `Math.random()` near auth/token/secret context
325
+ - Auth bypass: routes with no auth guard added, `req.params` used as DB key without ownership check
326
+ - Secrets: `password\s*=\s*['"]`, `apiKey\s*=\s*['"]`, `token\s*=\s*['"]` assigned to a literal value
327
+ - Score findings by severity: critical (exploit-ready) → BLOCK; high (auth/injection surface) → WARN; medium/low → LOG
328
+
329
+ **Handle deep-review verdict:**
330
+
331
+ | Severity found | Verdict | Action |
332
+ |---------------|---------|--------|
333
+ | Critical pattern in changed file | `block` | STOP campaign — do NOT record cycle, revert last commit, present finding to user |
334
+ | High pattern in changed file | `review_required` | STOP campaign — record cycle as completed, flag finding, recommend manual review |
335
+ | Medium/low only | `ok_with_minor` | Continue — append findings to `.planning/focus/security-log-<date>.md` |
336
+ | No patterns | `ok` | Continue silently |
337
+
338
+ Write all non-ok findings to `.planning/focus/security-log-<date>.md` with file:line references.
339
+
340
+ #### Step 2.4: Record Cycle
341
+
342
+ Run: `pan-tools focus auto --update --items-completed N --items-failed N --points-used N --tests-before N --tests-after N --batch-file <path>`
343
+
344
+ Check the response for stop conditions:
345
+ - `regression`: Tests decreased — STOP IMMEDIATELY
346
+ - `budget_cap`: Cumulative budget exceeded — go to Phase 3
347
+ - `max_cycles`: Maximum iterations reached — go to Phase 3
348
+ - `zero_completed`: No items completed in this cycle — go to Phase 3
349
+ - `diminishing_returns`: Optimize only — cycle efficiency < 30% of previous cycle — go to Phase 3
350
+ - `prompts_complete`: Prompts only — all prompts in document executed — go to Phase 3
351
+ - `security_complete`: Security only — scan found no HIGH/CRITICAL items remaining — go to Phase 3
352
+ - `deep_review_block`: `--deep-review` only — critical pattern detected in changed files — go to Phase 3 with warning
353
+ - `null`: Continue to next cycle
354
+
355
+ #### Step 2.5: Inter-Cycle Context Management
356
+
357
+ Between cycles, manage context to prevent quality degradation over long campaigns:
358
+ - **KEEP:** Current cycle goals, test baseline, error states, active file paths
359
+ - **SUMMARIZE:** Previous cycle results to a one-line summary each
360
+ - **DISCARD:** Raw tool output from previous cycles, superseded scan results
361
+
362
+ Display one-line cycle summary: `Cycle N/M | X/Y pts | Z items done | Tests: A -> B`
363
+
364
+ #### Step 2.5a: Reflection Gate (Opus 4.7 thinking-capable models only)
365
+
366
+ Before committing to the next cycle, call the reflection helper:
367
+
368
+ ```
369
+ echo '{"run": <run-state>, "cycle": <just-completed-cycle>, "batch": <proposed-next-batch>, "tier": "reasoning"}' \
370
+ | pan-tools focus reflection
371
+ ```
372
+
373
+ The helper returns `{reflect: true, prompt: "..."}` when the current model tier supports extended thinking. If `reflect: true`, think through the prompt — which asks whether running another cycle is worthwhile given telemetry and remaining items — and respond with JSON: `{"continue": true|false, "rationale": "..."}`.
374
+
375
+ - If `continue: false`: stop the campaign and treat as a user-reason stop (preserve state, skip to Phase 3).
376
+ - If `continue: true`: proceed to the next cycle.
377
+
378
+ If the helper returns `reflect: false` (tier doesn't support thinking, or `reflection_enabled: false` in run state, or no next batch): skip this step silently and continue to the next cycle.
379
+
380
+ The reflection gate catches "zero progress" or "wrong category" drift earlier than the automatic stop rules.
381
+
382
+ **Attention anchor — emit after every cycle summary:**
383
+ ```
384
+ Remaining: {cycles_left} cycles | {budget_remaining}/{total_budget} pts | Safety: {active_harness_warnings}
385
+ Next: Cycle {N+1} — Scan → Plan → Exec → Commit
386
+ ```
387
+ This prevents lost-in-the-middle drift in 10+ cycle campaigns where the agent forgets budget limits or stop conditions.
388
+
389
+ Then continue immediately to the next cycle (back to Step 2.1).
390
+
391
+ ### Phase 3: Campaign End
392
+
393
+ 1. Run `pan-tools focus auto --status` to get final state
394
+ 2. Display campaign summary:
395
+
396
+ ```
397
+ ## Campaign Complete
398
+
399
+ | Metric | Value |
400
+ |--------|-------|
401
+ | Category | <category> |
402
+ | Cycles | N completed |
403
+ | Items completed | X |
404
+ | Items failed | Y |
405
+ | Points used | Z / total_budget |
406
+ | Tests | baseline -> current (delta) |
407
+ | Stop reason | <reason> |
408
+ ```
409
+
410
+ 3. Remove safety tag: `git tag -d focus-auto-baseline 2>/dev/null`
411
+
412
+ ## 6-Layer Safety Harness
413
+
414
+ | Layer | Mechanism | Action |
415
+ |-------|-----------|--------|
416
+ | Per-cycle budget | `--budget N` per cycle | Limits single-cycle damage |
417
+ | Cumulative budget | `--total-budget N` | Prevents runaway spending |
418
+ | Iteration limit | `--max-cycles N` | Hard stop on loop count |
419
+ | Regression circuit breaker | tests_after < tests_before | Immediate stop, status=stopped |
420
+ | Zero-completed guard | 0 items done in a cycle | Stop — further cycles won't help |
421
+ | Security gate (`--deep-review`) | Critical/high OWASP pattern in changed files | Revert last commit (critical) or flag for manual review (high), stop campaign |
422
+
423
+ ## 9 Behavioral Rules
424
+
425
+ 1. **Read Before Write** — Read every file before editing. Understand context, callers, invariants.
426
+ 2. **Root Cause** — Fix the actual defect, not symptoms. Trace the code path.
427
+ 3. **One Change, One Test** — Test after every code change. MICRO: specific test. STANDARD/FULL: full suite.
428
+ 4. **Follow the Plan** — Implement exactly what the batch says. No scope creep.
429
+ 5. **Cross-Platform** — Use platform-agnostic path APIs. Follow the project's module format conventions.
430
+ 6. **Revert Fast** — 5 min limit on debugging a single failure, then revert and mark FAILED.
431
+ 7. **Verify Understanding** — State understanding for M+ items before coding.
432
+ 8. **Preserve Tests** — Never change test expectations to match broken code.
433
+ 9. **Accurate Commits** — Only claim verified items in commit messages. Include actual test counts.
434
+ 10. **Vary Similar Fixes** — When 3+ items in a cycle share the same fix pattern (e.g., "add null check"), re-read each module's conventions before applying. The same pattern may need different implementations in different modules. Check after the 3rd fix whether a shared helper would be better than scattered copies.
435
+
436
+ ## Prompts Category — Execution Details
437
+
438
+ The prompts category operates in two distinct modes. Detect which mode applies during the scan phase based on what the scan finds.
439
+
440
+ ### Execute Mode (micro-prompt document found)
441
+
442
+ A micro-prompt document contains an ordered sequence of self-contained implementation prompts. Each prompt describes a single, testable change.
443
+
444
+ **Document format recognized:**
445
+
446
+ ```markdown
447
+ # Micro-Prompts: <Feature Name>
448
+
449
+ Source: <spec file or description>
450
+ Generated: <date>
451
+
452
+ ## Prompt 1: <title>
453
+ - [ ] Complete
454
+
455
+ <implementation instructions>
456
+
457
+ ### Expected outcome
458
+ <what should work after this prompt>
459
+
460
+ ### Test
461
+ <how to verify>
462
+
463
+ ---
464
+
465
+ ## Prompt 2: <title>
466
+ - [ ] Complete
467
+ ...
468
+ ```
469
+
470
+ Alternative format — checklist style:
471
+ ```markdown
472
+ - [ ] Prompt 1: <title> — <instructions>
473
+ - [ ] Prompt 2: <title> — <instructions>
474
+ ```
475
+
476
+ **Execution strategy:**
477
+
478
+ 1. Read the micro-prompt document, identify all prompt blocks
479
+ 2. Find the first uncompleted prompt (unchecked `- [ ]`)
480
+ 3. Execute that prompt's instructions — implement the code changes described
481
+ 4. Run the project's test suite (or the prompt-specific test if given)
482
+ 5. If tests pass: mark the prompt as complete (`- [x]`), commit, move to next prompt
483
+ 6. If tests fail: one fix attempt, then revert and mark prompt as FAILED, move to next prompt
484
+ 7. Each prompt = one batch item. Budget: 1 prompt per cycle unless prompt is trivial (XS)
485
+ 8. Record `prompts_remaining` count in cycle update — when 0, `prompts_complete` stop fires
486
+
487
+ **Key rules:**
488
+ - Execute prompts in document order — NEVER skip ahead or reorder
489
+ - Each prompt is atomic — commit after each successful prompt
490
+ - A failed prompt does NOT block subsequent prompts (mark failed, continue)
491
+ - The prompt document is the plan — do not re-plan or expand scope beyond what each prompt says
492
+
493
+ ### Generate Mode (spec found without corresponding prompt document)
494
+
495
+ When a specification document is found that doesn't have a matching micro-prompt document, decompose it into ordered prompts.
496
+
497
+ **Generation strategy:**
498
+
499
+ 1. Read the spec document thoroughly
500
+ 2. Identify all discrete implementation steps
501
+ 3. Order steps by dependency — foundation first, features that depend on earlier steps later
502
+ 4. For each step, write a prompt block containing:
503
+ - Clear title describing the change
504
+ - Implementation instructions (files to create/modify, logic to implement)
505
+ - Expected outcome (what should work after this prompt)
506
+ - Test instruction (how to verify the prompt succeeded)
507
+ 5. Write the micro-prompt document to `.planning/prompts/<spec-slug>-prompts.md`
508
+ 6. Each generated document = one batch item (typically M or L size)
509
+
510
+ **Decomposition heuristics:**
511
+ - One prompt per logical unit of work (one function, one API endpoint, one component)
512
+ - Each prompt should be independently testable
513
+ - Prompts should be 5-30 minutes of implementation work each
514
+ - Aim for 5-20 prompts per spec (split large specs, combine trivial items)
515
+ - Include a "Prompt 0: Project setup" if the spec requires new dependencies or scaffolding
516
+ - Include a final "Prompt N: Integration test" that verifies the full feature end-to-end
517
+
518
+ **After generation:** The document is written and committed. The next cycle will detect it in execute mode and begin executing prompts sequentially.
519
+
520
+ ## Security Category — Execution Details
521
+
522
+ The security category scans for OWASP Top 10 (2025) violations and STRIDE threats, then fixes them cycle by cycle until the scan returns zero HIGH/CRITICAL findings.
523
+
524
+ ### Scan approach (Step 2.1)
525
+
526
+ Three passes per cycle:
527
+
528
+ **Pass 1 — Fast grep scan (always runs):**
529
+
530
+ | OWASP | Grep pattern | Priority |
531
+ |-------|-------------|---------|
532
+ | A03 Injection | `eval(`, `execSync(`, `` `SELECT.*\${ ``, `child_process.exec(` | P0 |
533
+ | A02 Crypto | `createHash\(['"]md5\|sha1`, `Math\.random\(\)` near auth/token | P0 |
534
+ | A01 Access | Route without auth middleware, IDOR (raw `req.params.id` to DB) | P1 |
535
+ | A05 Misconfig | `origin:\s*['"]?\*`, `Access-Control-Allow-Origin: \*`, stack in response | P1 |
536
+ | A07 Auth | No session expiry, credentials in URL params | P1 |
537
+ | A04 Design | Missing rate-limit on auth/payment endpoints | P2 |
538
+ | A09 Logging | Security events (`login`, `payment`, `admin`) with no log call nearby | P2 |
539
+
540
+ **Pass 2 — Structural check (always runs):**
541
+ - Read route files and check: does every mutating endpoint (POST/PUT/PATCH/DELETE) have auth middleware before the handler?
542
+ - Check for hardcoded secrets: grep for `['"][A-Za-z0-9_]{20,}['"]` assigned to variables named `key`/`token`/`secret`/`password`/`apiKey`
543
+ - Check for prototype pollution risk: `Object.assign(req.body)` or spread from untrusted input into a stored object
544
+
545
+ **Pass 3 — Semantic depth (Agent tool, for M/L items only):**
546
+ When a pattern match needs code-path confirmation, spawn an Explore subagent:
547
+ > "Read [file]. Confirm whether [line N] is reachable from an unauthenticated request path and whether the input is sanitized before use."
548
+
549
+ Use the confirmation to decide whether to include the item at P0/P1 or drop it as a false positive.
550
+
551
+ ### Item classification
552
+
553
+ | Hardener severity | Focus priority | Example |
554
+ |------------------|----------------|---------|
555
+ | Critical | P0 | `eval(req.body.code)` — direct remote code execution risk |
556
+ | High | P1 | Missing authorization on admin route |
557
+ | Medium | P2 | Rate-limiting absent on login |
558
+ | Low / Info | DROP | Missing security header on non-sensitive route |
559
+
560
+ ### Execution (Step 2.3)
561
+
562
+ This is authorized, defensive hardening of the user's own codebase — you assess and remediate weaknesses; you never write exploit code or attack instructions.
563
+
564
+ **Model routing (important).** Some session models — notably Claude Fable 5 — run a cybersecurity classifier that can refuse defensive security review. Do the vulnerability *assessment* (the Pass 3 semantic analysis and each item's risk statement below) by spawning the `pan-hardener` subagent, which is pinned to `model: opus` and is not subject to that classifier. The main loop runs the grep triage (Passes 1–2) and implements the fixes; it does not narrate exploit paths inline. If any security step is refused on the main loop, delegate it to `pan-hardener` and continue.
565
+
566
+ Treat each security item as a STANDARD or FULL item regardless of effort estimate:
567
+
568
+ 1. **State the risk:** "This is [OWASP category]. How it could be reached and the impact: [unvalidated input reaches X → Y → data exposure or loss], so it must be fixed."
569
+ 2. **Read the file** — confirm the pattern is real, not a false positive
570
+ 3. **Implement the fix** — use established patterns (parameterized queries, allowlists, bcrypt, rate-limit middleware)
571
+ 4. **Write or update the test** — every security fix MUST have a test that proves the weakness is closed (e.g., send the crafted/invalid input, assert 400/403 not 200)
572
+ 5. **Run full test suite** — regression check before marking DONE
573
+
574
+ ### Stop condition
575
+
576
+ `security_complete` fires when the scan finds zero P0/P1 items. P2 items (medium) may remain — they won't stop the campaign unless `zero_completed` fires (no items at all).
577
+
578
+ A security campaign that ends with `security_complete` means: no critical or high OWASP violations found in the scanned files. Medium/low items can be addressed in subsequent targeted passes or documented as accepted risk.
579
+
580
+ ---
581
+
582
+ ## Distill Category — Execution Details
583
+
584
+ The `distill` category targets **AI-generated code bloat** with a 5-pass pipeline based on the SOTA agentic-refactoring architecture (deterministic-first, LLM-on-narrow-spans).
585
+
586
+ ### Pipeline
587
+
588
+ | Pass | What | Cost | Tier output |
589
+ |------|------|------|-------------|
590
+ | 1 | **Deterministic patterns** — phantom try/catch, unused imports, magic numbers, long functions, wide param lists | Free | safe / review |
591
+ | 2 | **AST-style analysis** — single-instance factories, deep nesting | Free | review |
592
+ | 3 | **Cross-file graph** — repeated 5+ line blocks, unreferenced exports | Free | review |
593
+ | 4 | **LLM judgment** — pan-distiller agent receives ONLY flagged spans (max 50 lines context per finding); validates pattern, refines tier, proposes minimal rewrite | LLM tokens | safe / review / risky |
594
+ | 5 | **Cross-session memory** — compares findings to `.planning/memory/distill-patterns.md`; flags **regressed** patterns ("we already fixed this") | Free | metadata |
595
+
596
+ ### Safety Tiers
597
+
598
+ | Tier | Rule | Action |
599
+ |------|------|--------|
600
+ | `safe` | Deterministic, behavior-preserving (e.g., remove unused import) | Auto-applied |
601
+ | `review_required` | Behavior preserved under invariants but human should verify | Surfaced to user |
602
+ | `risky` | Cross-file impact or might surface latent bugs | Never auto-applied |
603
+
604
+ A finding's confidence below 0.85 is automatically downgraded to `review_required` regardless of original tier.
605
+
606
+ ### Bloat Budget
607
+
608
+ After each cycle, distill computes:
609
+ - **touched_loc** — total LOC modified in cycle
610
+ - **removable_loc** — sum of `loc_saved` across findings
611
+ - **essential_loc** — touched_loc − removable_loc
612
+ - **bloat ratio** — touched_loc / essential_loc
613
+
614
+ Default threshold: **2.0x**. If a cycle's ratio exceeds threshold, the bloat budget gate flags it for review.
615
+
616
+ ### Stop condition
617
+
618
+ `distill_complete` fires when the scan finds zero bloat findings. The codebase is fully distilled for the patterns the deterministic + AST + graph passes detect.
619
+
620
+ ### CLI
621
+
622
+ ```bash
623
+ node ~/.claude/pan-wizard-core/bin/pan-tools.cjs distill scan
624
+ node ~/.claude/pan-wizard-core/bin/pan-tools.cjs distill analyze [--touched-loc N] [--bloat-threshold X]
625
+ node ~/.claude/pan-wizard-core/bin/pan-tools.cjs distill report
626
+ ```
627
+
628
+ `scan` returns findings. `analyze` adds bloat budget + regressed pattern detection. `report` writes findings to `.planning/memory/distill-patterns.md` for the next session.
629
+
630
+ <failure_pattern_capture>
631
+ When the same failure pattern appears in 2+ items within a campaign, capture it for future runs.
632
+
633
+ **Detection:** After marking an item FAILED, check if the error classification matches any previous failure in this campaign:
634
+ - Same error type (e.g., "test regression in unrelated module")
635
+ - Same file or module involved
636
+ - Same root cause category (e.g., "missing null check pattern", "import path mismatch")
637
+
638
+ **Capture (when pattern repeats):**
639
+ Append to `.planning/focus/failure-patterns.md`:
640
+ ```markdown
641
+ ## Pattern: {short description}
642
+ - **First seen:** Cycle {N}, Item {ID}
643
+ - **Recurrence:** Cycle {M}, Item {ID2}
644
+ - **Error type:** {classification}
645
+ - **Root cause:** {what actually went wrong}
646
+ - **Avoidance rule:** {what to check before attempting similar items}
647
+ - **Files involved:** {paths}
648
+ ```
649
+
650
+ **Use (on subsequent cycles):**
651
+ Before executing an item, check if its target files or error category match a known failure pattern. If so:
652
+ - Apply the avoidance rule BEFORE implementing
653
+ - If the pattern suggests the item will fail (e.g., "all items touching module X regress"), skip with reason "matches known failure pattern — defer to manual investigation"
654
+
655
+ This prevents the campaign from burning budget on items that will predictably fail.
656
+ </failure_pattern_capture>
657
+
658
+ ## NEVER DO
659
+
660
+ - Invoke the Skill tool — scan/plan/exec must run inline so state stays coherent across cycles
661
+ - Stop or pause between phases — interruptions break the autonomous loop and lose cycle momentum
662
+ - Ask the user questions after category selection — the whole point is autonomous execution; questions defeat that
663
+ - Skip the baseline test capture — without a baseline, the regression circuit breaker has nothing to compare against
664
+ - Continue after a test regression — a test count decrease means code was broken; continuing compounds the damage
665
+ - Expand scope beyond what the scan found — scope creep in an autonomous loop compounds unpredictably across cycles
666
+ - Run more cycles than --max-cycles — the limit exists to cap total cost and prevent runaway loops
667
+ - Spend more points than --total-budget — the budget cap is the user's cost control mechanism
668
+ - Skip recording cycle results via --update — unrecorded cycles break resume, status, and stop-condition checks
669
+ - Change test expectations to match broken code — this hides bugs instead of fixing them
670
+ - Use `git add -A` or `git add .` — bulk staging can accidentally commit secrets, build artifacts, or unrelated changes
671
+
672
+ ## ALWAYS DO
673
+
674
+ - Execute all phases autonomously from start to finish
675
+ - Capture baseline before first cycle
676
+ - Read every file before editing it
677
+ - Test after every code change
678
+ - Record every cycle via `pan-tools focus auto --update`
679
+ - Stop on ANY safety harness trigger
680
+ - Revert fast when stuck (5 min limit)
681
+ - Display one-line cycle summary between cycles
682
+ - Display campaign summary table at end
683
+ - Commit once per cycle with accurate item list