[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79EDNSGCNB5KQP5M8WM11ZB":3,"skill-same:01M79EDNSGCNB5KQP5M8WM11ZB":57},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":14,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":46},"01M79EDNSGCNB5KQP5M8WM11ZB","implement",null,"Run the full implement-review-fix loop using implementer and reviewer personas. Supports effort-based multi-reviewer scaling (1-5 reviewers) with automatic specialization selection. Includes memory-based feedback loop that learns from past review patterns. Loops until all reviewers find 0 issues of any severity.","zfifteen\u002Fskills-catalog","zfifteen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F221906715?v=4","01M79CQFXDZM5J5CJTCECPFA66","Dionisio Alberto Lopez III","01M79CQFY4C62PN8A2T5KDAHGA",1,"MIT","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fimplement\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: implement\ndescription: >-\n  Run the full implement-review-fix loop using implementer and reviewer personas.\n  Supports effort-based multi-reviewer scaling (1-5 reviewers) with automatic\n  specialization selection. Includes memory-based feedback loop that learns from\n  past review patterns. Loops until all reviewers find 0 issues of any severity.\nwhen-to-use: Use when asked to \"implement\", \"build\", \"add feature\", \"fix bug\", or \"\u002Fimplement\".\nargument-hint: \"[--effort N] \u003Cdescription of what to implement>\"\ndisable-model-invocation: true\n---\n\n# Implement Skill\n\nYou are an orchestrator that runs the **implement → review → fix** loop using the `implementer` and `reviewer` personas. Your job is to keep the loop running until the code is clean. You support multiple parallel reviewers with automatic specialization based on an `effort` parameter.\n\nYou coordinate only. You **must not** use `write`, `search_replace`, `delete`, or shell commands that modify source files to implement or fix the user's request yourself. **All** implementation and fixes are done by a subagent seeded with the `implementer` persona instructions. **All** review is done by a subagent seeded with the `reviewer` or `security-auditor` persona instructions (or by prompt-only subagents for Tests and Plan Alignment specialists).\n\n## Tool-Call Discipline (Anti-Hallucination)\n\nEvery action you describe in your text **must** correspond to an actual tool call in the same assistant response. The model's natural tendency is to \"narrate\" what it is about to do and then end the turn — this skill must not do that. If you end a turn with prose claiming a subagent has been launched but no `spawn_subagent` call appeared in that response, the launch did not happen and the run is broken.\n\n1. **Tool call first, narration second.** When a step tells you to \"launch the implementer\" or \"spawn the reviewers\", emit the `spawn_subagent` tool call(s) **before** any user-visible text describing the launch. Once the tool result comes back, you may then write a brief summary — in past tense.\n2. **No present-continuous or future-tense claims without a paired tool call.** Never write phrases like \"The implementer **is being launched** now…\", \"I'll **start** the reviewers…\", or \"The subagent **will begin** working…\" in an assistant message unless that same message also contains the corresponding `spawn_subagent` tool call. Future-tense or present-continuous wording in a content-only message is a strong signal that you skipped the actual tool call.\n3. **No permission-asking at launch time.** Setup, spawn, and progress-cadence decisions are yours to make. Do not append a question like \"Want me to give you a quick status check in ~30 min, or just let it run silently until the first big checkpoint?\" to a launch message. Pick a sensible default (see In-Progress Reporting) and proceed. Asking forces the user to drive the loop, which is the opposite of what this skill exists to do.\n4. **Past-tense announcements only.** Correct: \"Launched 5 reviewers in parallel (general × 2, security, tests, plan alignment). subagent_ids: …\". Incorrect: \"I will now launch 5 reviewers…\". Past tense should always reference a tool call you can point to in the same response.\n5. **Self-check before ending a turn.** Before producing a content-only assistant message (no tool calls) that mentions launching, starting, spawning, or otherwise initiating any subagent or background task, verify that the corresponding `spawn_subagent` call appears earlier in **this same response** or that the tool result for it is already in the history. If it doesn't, call the tool now — never end the turn with stranded narration.\n\n## Todo Scaffold\n\nOpen the run with a `todo_write` (merge: false) listing the canonical phases. Use exactly this id schema so the runtime turn-end gate can correlate phases consistently across compactions:\n\n- `setup` — Step 0 (memory retrieval) + reviewer-config decision\n- `implement` — Step 1 (spawn implementer)\n- `review-round-1` — Step 2 (spawn reviewers) + Step 3 (merge & check)\n- `fix-round-1` — Step 4 (resume implementer to fix)\n- `rereview-round-1` — Step 5 (resume reviewers) + Step 3 (merge & check)\n- (repeat `fix-round-N` + `rereview-round-N` as needed)\n- `memory-flush` — Step 6\n- `final-report` — Final report message\n\nMark exactly one `in_progress` at a time. As you enter a new round, append the two new ids (`fix-round-N`, `rereview-round-N`) via `merge: true`. A `review-round-N` that produces 0 open issues skips directly to `memory-flush`; mark intermediate `fix-round-N` \u002F `rereview-round-N` ids as `cancelled` with reason \"0 open issues this round\" only if you created them.\n\nNever end a turn with `in_progress` set to a phase whose subagent has not been spawned yet. Spawn first; then optionally mark the phase as completed and the next phase as in_progress in the next turn.\n\n**Reseed after compaction** — the harness no longer surfaces a pre-compaction todo snapshot. If a compaction lands mid-implementation, rebuild the scaffold from the canonical phase ids above (`setup`, `implement`, `review-round-N`, etc.) plus the persisted review\u002Fsummary files for the current round, and seed the remaining phases before continuing. The Recall v1 regression was caused exactly by skipping this rebuild.\n\n## Persona Injection\n\nThis skill uses the **implementer**, **reviewer**, and **security-auditor** personas. The persona instructions are defined at:\n\n```\n\u003Cdirname of this SKILL.md>\u002F..\u002Fshared\u002Fpersonas\u002Fimplementer.md\n\u003Cdirname of this SKILL.md>\u002F..\u002Fshared\u002Fpersonas\u002Freviewer.md\n\u003Cdirname of this SKILL.md>\u002F..\u002Fshared\u002Fpersonas\u002Fsecurity-auditor.md\n```\n\nResolve these paths once at the start of the run (the system context gives you the absolute path to this SKILL.md). Read each file with `read_file` and store their contents as `implementer_persona_instructions`, `reviewer_persona_instructions`, and `security_auditor_persona_instructions`.\n\nWhen launching a subagent, **prepend** the appropriate persona instructions to its prompt. Do NOT pass a `persona` parameter to `spawn_subagent` — that parameter is not supported. Instead, prefix the `description` with a bracketed role tag (`[implementer]`, `[reviewer]`, `[security]`, `[tests]`, `[plan]`, etc.) so the pager's subagent label renderer (see `format_subagent_label` in `xai-grok-pager`) surfaces the role name at the top of the subagent row instead of the generic \"General\" fallback. The bracketed prefix is stripped from the displayed description. On `resume_from` follow-ups, the persona is already in the subagent's transcript from the initial launch — do not re-inject it; **do** keep the bracketed tag in the description so the label remains correct.\n\n## Invocation\n\nThe user runs:\n```\n\u002Fimplement [--effort N] \u003Cdescription>\n```\n\nThe `\u003Cdescription>` is the implementation task — it can be a feature request, bug fix, refactoring goal, plan, or any coding task. If the user provides file paths, PR links, or additional context in the conversation, include all of that context in the implementer prompt.\n\nThe `effort` parameter is an optional integer, 1–5 (default: 1). It controls how many reviewers participate in the review phase:\n\n| Effort | Reviewer Count | Behavior |\n|--------|---------------|----------|\n| 1 | 1 | Single general-purpose `reviewer` (current behavior + wontfix\u002Fstalemate mechanism) |\n| 2 | 2 | Coordinator splits 2 slots between generals and specialists based on description |\n| 3 | 3 | 3 slots — more coverage, same adaptive split |\n| 4 | 5 | 5 slots — room for multiple generals + full specialist coverage |\n| 5 | 6 | Maximum rigor — up to 3 generals + all 3 specialists |\n\nExtract the effort level from the argument string using natural language understanding. Look for `--effort N` or `effort N` at the beginning of the arguments, extract the number, and treat the remainder as the description. If `--effort` is not present, or the value is out of range, default to 1.\n\n## Setup\n\nGenerate a unique ID for this run's artifact files. Execute this via `run_terminal_cmd` and capture the output:\n\n```bash\npython3 -c \"import uuid; print(uuid.uuid4().hex[:8])\"\n```\n\n**Validate** that the command succeeded and produced a non-empty string. If `IMPL_ID` is empty or the command failed, report the error to the user and stop.\n\nStore the output as `IMPL_ID`.\n\nThen compute a **per-user, `$TMPDIR`-respecting scratch directory** for all artifact files. Never write skill artifacts directly under `\u002Ftmp` on a shared host: it leaks their contents to other users and ignores a user-configured `$TMPDIR`. Run via `run_terminal_cmd` and capture stdout:\n\n```bash\nscratch_dir=\"${TMPDIR:-\u002Ftmp}\u002Fgrok-$(id -u)\"; mkdir -p \"$scratch_dir\" && chmod 700 \"$scratch_dir\" && echo \"$scratch_dir\"\n```\n\nStore the output as `scratch_dir`. **Inline the resolved absolute path** into every file path below and into every subagent prompt; do not rely on a `$scratch_dir` shell variable surviving across separate `run_terminal_cmd` calls (the same reason this skill inlines `${MEMORY_HELPER}`).\n\nThen define the shared file paths (all under `scratch_dir`):\n- `summary_file`: `${scratch_dir}\u002Fgrok-impl-summary-${IMPL_ID}.md`\n- `review_file`: `${scratch_dir}\u002Fgrok-review-${IMPL_ID}.md` (merged review — what the implementer reads)\n\nFor `effort >= 2`, also define individual review files per reviewer:\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-general.md`\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-general-2.md` (if effort >= 4)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-general-3.md` (if effort >= 5)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-tests.md` (if tests specialist selected)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-security.md` (if security specialist selected)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-plan.md` (if plan alignment specialist selected)\n\nThese paths stay the same for the entire loop. Never regenerate them between iterations.\n\nInitialize these state variables for the orchestrator to maintain across rounds:\n- `round_count`: `0` — incremented each time a review completes.\n- `total_issues_by_severity`: `{}` — a map from severity (bug, suggestion, nit) to cumulative count. After each review, add the count of open issues by severity to this accumulator.\n- `previous_review_snapshot`: `\"\"` — after each review, before the implementer fixes, save a copy of the review_file contents so you can detect stalemates by comparing the current round's wontfix\u002Fre-opened issues against the prior round.\n- `reviewer_configs`: `[]` — list of reviewer config objects (see Specialization Selection below).\n- `past_issues_briefing`: `\"\"` — populated in Step 0 from the workspace memory file (resolved via the `memory.py` helper, see Step 0). Contains a formatted markdown block of common issue patterns from previous runs, injected into implementer and reviewer prompts. Empty string if no past issues exist.\n- `issue_patterns`: `[]` — a list of concise one-line issue descriptions accumulated across rounds. After each Step 3, extract a one-line description from each open issue and append it to this list (deduplicating exact matches). Used in Step 6 (Memory Flush) instead of relying on LLM recall of earlier rounds.\n\n## Specialization Selection\n\nWhen `effort >= 2`, the orchestrator decides how to fill the reviewer slots. It first identifies which specialists are relevant based on the description, then fills any remaining slots with additional independent general reviewers. This means effort 2 with no specialist matches produces 2 independent general reviewers — not a forced specialist. For effort=1, a single general reviewer is always used. This decision is made **before Step 1 (Implement)** based on the implementation description and conversation context.\n\n### Specialization Catalog\n\n| Specialization | Persona to Inject | Focus Areas | When to Use |\n|---------------|-------------------|-------------|-------------|\n| **General** | `reviewer` | Code quality, bugs, naming, SOLID, style | Always (every run) |\n| **Tests** | None (prompt-only) | Test coverage, test quality, edge cases, mocking | When implementation involves new logic, APIs, or data processing |\n| **Plan Alignment** | None (prompt-only) | Implementation matches the design\u002Fplan, no scope drift, all requirements addressed | When a design doc or detailed plan is referenced in the description |\n| **Security** | `security-auditor` | Auth, injection, data handling, secrets, OWASP | When implementation touches auth, user input, APIs, data storage, or network |\n\n**Note on persona injection:** The `Tests` and `Plan Alignment` specializations do NOT get persona instructions prepended — they rely entirely on the task prompt to define their behavior. This avoids a conflict between the `reviewer` persona's review focus and the specialist prompt's scope restriction.\n\nThe `security-auditor` persona instructions are prepended for security review because they contain purpose-built audit methodology.\n\nThe `reviewer` persona instructions are prepended as-is for the general code quality review.\n\n### Decision Algorithm\n\nThe coordinator determines the reviewer composition in two steps:\n\n```\n# Step 1: Determine total reviewer slots from effort\nif effort \u003C= 3:\n    total_slots = effort\nelif effort == 4:\n    total_slots = 5\nelse:  # effort == 5\n    total_slots = 6\n\n# Step 2: Identify relevant specialists from description\nmatched_specialists = []\n\nif description mentions auth, security, user input, API keys, \n   secrets, encryption, permissions, tokens, or OWASP:\n    matched_specialists.append(\"security\")\n\nif description references a design doc, plan, spec, RFC, \n   or linked document:\n    matched_specialists.append(\"plan_alignment\")\n\nif description involves new logic, endpoints, data processing,\n   algorithms, or business rules:\n    matched_specialists.append(\"tests\")\n\n# Step 3: Allocate slots\n# Cap specialists by available slots (total - 1, since at least 1 general)\nspecialists = matched_specialists[:total_slots - 1]\n\n# Remaining slots become additional general reviewers\nnum_generals = total_slots - len(specialists)\n```\n\n**Examples:**\n- Effort 2, simple refactoring (no matches) → 2 generals, 0 specialists\n- Effort 2, touches auth → 1 general + security\n- Effort 3, touches auth → 2 generals + security\n- Effort 3, touches auth + has design doc → 1 general + security + plan alignment\n- Effort 4, only tests match → 4 generals + tests\n- Effort 5, all 3 match → 3 generals + all 3 specialists\n\n### Building reviewer_configs\n\nBuild `reviewer_configs` for every effort level. The general reviewer is always included. For `effort >= 2`, also append specialists and (for effort 4-5) additional general reviewers:\n\n```\nreviewer_configs = []\n\n# Add general reviewers\nfor i in range(1, num_generals + 1):\n    tag = \"general\" if i == 1 else f\"general-{i}\"\n    reviewer_configs.append({\n        subagent_id: null,\n        persona_to_inject: \"reviewer\",  # key into loaded persona instructions\n        specialization: tag,\n        review_file: effort == 1 ? review_file : f\"${scratch_dir}\u002Fgrok-review-{IMPL_ID}-{tag}.md\"\n    })\n\n# Add specialist reviewers\nfor each specialist in specialists:\n    reviewer_configs.append({\n        subagent_id: null,\n        persona_to_inject: specialist == \"security\" ? \"security-auditor\" : null,  # null = prompt-only, no persona prepended\n        specialization: specialist,\n        review_file: f\"${scratch_dir}\u002Fgrok-review-{IMPL_ID}-{suffix_map[specialist]}.md\"\n    })\n```\n\nThe specialization-to-suffix mapping is: `general` → `general`, `general-2` → `general-2`, `general-3` → `general-3`, `tests` → `tests`, `security` → `security`, `plan_alignment` → `plan`.\n\nFor source tags in the merged review, use `[General]`, `[General-2]`, `[General-3]` to distinguish independent general reviewers. All general reviewers use the same `reviewer` persona and the same General Reviewer prompt — independent runs naturally produce different findings due to LLM variance.\n\n### Announce Specializations\n\nAnnounce the specialization choices to the user **once**, then move on. Examples of correct messages:\n> \"Using effort level 2: 2 independent general reviewers (no specialist triggers matched).\"\n> \"Using effort level 2: general reviewer + security specialist (implementation touches auth endpoints).\"\n> \"Using effort level 4: 3 general reviewers + security + tests (5 reviewers).\"\n\nStrict rules for this announcement:\n- This message describes **only the specialization selection**. Do **not** also claim that the implementer is being launched, that reviewers are starting, or that the run is \"now running\" — those statements belong to later steps, after the corresponding `spawn_subagent` calls.\n- Do **not** end the announcement with a question to the user. No \"Want me to check in every 30 minutes?\", no \"Should I proceed?\", no \"Let me know if you want me to do anything different.\" This step is fire-and-forget: no blocking interaction, no approval step, no cadence negotiation.\n- Proceed directly to Step 0 (Memory Retrieval) and Step 1 (Implement) in the same turn. The next user-visible message should be the post-spawn launch confirmation described in Step 1, not a continuation of this announcement.\n\n## Step 0: Memory Retrieval (Past Issues Briefing)\n\nBefore launching the implementer, attempt to load past issue patterns from the workspace memory file. This briefing is injected into both the implementer and reviewer prompts to help avoid recurring issues.\n\nThe memory file is **workspace-scoped** and lives under `$HOME\u002F.grok\u002Fimplement-memory\u002F`, keyed by a stable workspace id derived in this order:\n\n1. Canonicalised `git config remote.origin.url` (SSH and HTTPS variants of the same upstream collapse onto one id, with or without the `.git` suffix).\n2. Absolute path of the main `.git` directory (`git rev-parse --git-common-dir`) for repos with no remote.\n3. Absolute path of cwd as a last-ditch fallback for non-git workspaces.\n\nThe `memory.py` helper at `\u003Cdirname of this SKILL.md>\u002Fscripts\u002Fmemory.py` resolves the path and handles concurrent access via Python's `fcntl.flock` (no `flock(1)` shell binary required).\n\n### Resolve the helper path once\n\nThe helper script lives at a fixed location **relative to this SKILL.md file**: `\u003Cdirname of SKILL.md>\u002Fscripts\u002Fmemory.py`. The orchestrator already knows the absolute path to this SKILL.md file from its system context (the skills list announces each skill's path when it's loaded). Derive the helper path from that, **not** from `$(pwd)` — the skill can be loaded from a workspace-local `.grok\u002Fskills\u002F`, the user's home `~\u002F.grok\u002Fskills\u002F`, or a bundled `~\u002F.grok\u002Fbundled\u002F...` location, and only the SKILL-relative path works in all cases.\n\nCapture it once at the start of the run as **orchestrator state** (a value held in your own working memory):\n\n```\nmemory_helper_path = dirname(\u003Cpath-to-this-SKILL.md>) + \"\u002Fscripts\u002Fmemory.py\"\n```\n\nFor example, if this SKILL.md is at `\u002FUsers\u002Falice\u002F.grok\u002Fworktrees\u002Forg\u002Frepo\u002F.grok\u002Fskills\u002Fimplement\u002FSKILL.md`, then `memory_helper_path` is `\u002FUsers\u002Falice\u002F.grok\u002Fworktrees\u002Forg\u002Frepo\u002F.grok\u002Fskills\u002Fimplement\u002Fscripts\u002Fmemory.py`. If this SKILL.md is at `\u002FUsers\u002Falice\u002F.grok\u002Fskills\u002Fimplement\u002FSKILL.md`, then `memory_helper_path` is `\u002FUsers\u002Falice\u002F.grok\u002Fskills\u002Fimplement\u002Fscripts\u002Fmemory.py`.\n\n**Substitute this absolute path directly** into every helper invocation throughout the run — do not rely on a bash environment variable surviving across `run_terminal_cmd` calls. All examples below show `${MEMORY_HELPER}` for readability; in practice, inline the absolute `memory_helper_path` value (or set `MEMORY_HELPER=\u003Cabsolute path>` at the top of each shell invocation that uses it).\n\n**Invoke the helper from the workspace root**, not from the helper's own directory. The helper itself is cwd-sensitive only for its workspace-id derivation: it runs `git config --get remote.origin.url` and `git rev-parse --git-common-dir` in the cwd, so cwd needs to be inside the workspace. `run_terminal_cmd` defaults to the workspace root, so this is the natural case — just don't `cd` to the helper's own directory before invoking it (especially relevant when the skill is loaded from `~\u002F.grok\u002Fskills\u002F`, where `cd`-ing to the helper would put cwd outside any workspace and the workspace-id would fall back to that home-dir cwd).\n\n### Read Path\n\n1. Run `python3 \"${MEMORY_HELPER}\" snapshot` via `run_terminal_cmd` and capture stdout. The helper prints structured JSON — no markdown re-parsing in the orchestrator. The shape is:\n\n   ```json\n   {\n     \"common_issues\": [\n       {\"category\": \"Error Handling\", \"description\": \"Missing null check\", \"count\": 5},\n       ...\n     ],\n     \"recent_runs\": [\n       {\"date\": \"2026-04-23\", \"description\": \"\\\"Add retry logic\\\"\", \"body_lines\": [\"- **Rounds**: 2\", \"- **Issues**: 7 total (1 bug, 1 suggestion, 5 nits)\", \"- **Key patterns**: Missing entries in error-type allowlists, incomplete configuration validation\", \"- **Specializations used**: general\"]},\n       ...\n     ],\n     \"exists\": true\n   }\n   ```\n\n   Parse the JSON and store the `common_issues` list as `existing_patterns_snapshot` (used in Step 6b). Store the boolean `exists` as `memory_existed_before` (used in the Final Report to decide between \"file created\" and \"file updated\" wording). The `recent_runs` array is included in the snapshot for debugging and forward compatibility (`memory.py snapshot | jq '.recent_runs'`); the orchestrator does not currently consume it. Each entry's `body_lines` are the verbatim markdown bullets (leading `- ` and `**...**` formatting preserved).\n2. If the helper exits non-zero (very rare — only happens if `$HOME` is unset and inferable home fails, or if cwd is unreadable), log a brief note, set `past_issues_briefing` to `\"\"`, `existing_patterns_snapshot` to `[]`, `memory_existed_before` to `false`, and proceed to Step 1. Note that a non-git workspace is **not** a failure mode — the helper falls back to a cwd-based id.\n3. If `existing_patterns_snapshot` is empty (or `exists` is `false`), set `past_issues_briefing` to `\"\"` and skip the briefing block below.\n\nDo NOT read or write `.grok\u002Fimplement-issues.md` directly during a \u002Fimplement run — that legacy path is per-worktree and is no longer used. The helper is the single source of truth for the path.\n\n**One-time migration from the legacy file:** if a user has a populated `.grok\u002Fimplement-issues.md` from a prior version, its `## Common Issues` and `## Recent Runs` sections use the **same markdown format** documented under [Memory File Format](#memory-file-format) below. To bring that history forward:\n\n1. **From the workspace root** (the same directory where `.grok\u002Fimplement-issues.md` lives — the workspace-id is derived from the cwd's git context, so running this from `~` or any unrelated directory will write to the wrong workspace's memory file), run `python3 \"${MEMORY_HELPER}\" update` once with an empty spec (`echo '{}' | python3 \"${MEMORY_HELPER}\" update`) to create the workspace-scoped file and its parent directory — `memory.py path` only computes the path, it does not create the directory.\n2. Open the printed file path in an editor.\n3. Hand-copy the bullets from the legacy file's `## Common Issues` section into the corresponding categories in the new file (preserving the `- description (seen N time(s))` syntax).\n4. The helper picks up the entries on the next `update`.\n\nThere is no automatic migration.\n\n### Parsing & Formatting\n\nIf `existing_patterns_snapshot` is non-empty:\n\n1. Filter to only entries with `count >= 2` (minimum threshold — one-off issues are excluded as they may not represent real patterns).\n2. Sort by `count` descending.\n3. Take the top 10 entries.\n4. Format them into the briefing block and store in `past_issues_briefing`:\n\n```\n## Past Issues to Avoid\nBased on previous implementation runs, the following patterns commonly cause issues:\n1. Missing null\u002Fundefined checks on function inputs (seen 5 times)\n2. Missing tests for error\u002Fedge case paths (seen 8 times)\n3. Functions exceeding 50 lines without decomposition (seen 4 times)\n4. Magic numbers without named constants (seen 6 times)\n\nPay special attention to these patterns in your work.\n```\n\n(Use `time` for `count == 1`, `times` otherwise. The helper renders both forms identically in the file, so the briefing should match.)\n\nIf there are no qualifying entries, set `past_issues_briefing` to `\"\"`.\n\n### Graceful Degradation\n\nIf the helper command fails for any reason, set `past_issues_briefing` to `\"\"`, `existing_patterns_snapshot` to `[]`, `memory_existed_before` to `false`, and proceed normally. Never fail the run due to memory retrieval issues — log a brief note and continue.\n\n## Step 1: Implement\n\n**Use `spawn_subagent` only** — do not implement code yourself.\n\nLaunch the implementer subagent by calling `spawn_subagent`. **Emit the `spawn_subagent` tool call before producing any user-visible \"implementer is launching\" message** — the launch announcement belongs in a *later* assistant message, after you have the tool result and a real `subagent_id` in hand. A content-only assistant message claiming the implementer has been launched, without a paired `spawn_subagent` call in the same response, is a hallucination and breaks the run (see Tool-Call Discipline above).\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `description`: `\"[implementer] \u003Cshort summary>\"` (the `[implementer]` prefix becomes the pager's row label)\n\n**Prepend the implementer persona instructions** (loaded during setup) to the prompt.\n\nPrompt:\n```\n\u003Cimplementer_persona_instructions>\n\n---\n\nImplement the following:\n\n\u003Cfull user description and all relevant context from the conversation>\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\nBe proactive about avoiding these patterns in your implementation.\n\u003Cend if>\n\nWhen you are done, write an implementation summary to: \u003Csummary_file>\nThe summary must include: what files were changed, what was added\u002Fmodified, and any design decisions made.\n```\n\nWait for the subagent to complete. If it fails, report the error to the user and stop.\n\nSave the returned `subagent_id` — you will resume this agent for all fix rounds.\n\nReport to the user: \"Implementation complete. Starting review...\" (for effort=1) or \"Implementation complete. Starting parallel review (N reviewers)...\" (for effort >= 2).\n\n### Prepare reviewer focus areas\n\nBefore launching reviewers, read `\u003Csummary_file>` yourself. Based on the implementation summary, identify 2-5 concrete areas the reviewer should pay extra attention to. Examples:\n\n- If the summary mentions new error handling paths: \"Verify error paths are tested and propagated correctly\"\n- If files were refactored: \"Check that callers of renamed\u002Fmoved functions were all updated\"\n- If concurrency primitives were added: \"Review lock ordering and potential deadlocks\"\n- If new public APIs were introduced: \"Check input validation at API boundaries\"\n\nStore these as `reviewer_focus_areas` (a short bulleted list). Include them in every reviewer prompt alongside `past_issues_briefing`.\n\n## Step 2: Review\n\n**Use `spawn_subagent` only** — do not review code yourself.\n\nThe review step differs based on effort level.\n\n### Effort = 1 (Single Reviewer)\n\nLaunch a single reviewer subagent by calling `spawn_subagent`.\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `description`: `\"[reviewer] Review implementation\"`\n\n**Prepend the reviewer persona instructions** (loaded during setup) to the prompt.\n\nPrompt:\n```\n\u003Creviewer_persona_instructions>\n\n---\n\nReview the changes made by the implementer.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\n\u003Cif reviewer_focus_areas is non-empty:>\n## Additional focus areas (from implementation summary)\n\u003Creviewer_focus_areas>\n\u003Cend if>\n\nWrite your review notes to: \u003Creview_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\nWait for the subagent to complete. If it fails, report the error to the user and stop.\n\nSave the returned `subagent_id` to `reviewer_configs[0].subagent_id`.\n\n### Effort >= 2 (Parallel Reviewers)\n\nLaunch all reviewers in parallel by calling `spawn_subagent` with `background: true` for each.\n\nFor each config in `reviewer_configs`, launch with the appropriate prompt for the specialization:\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `background`: `true`\n- `description`: `\"[\u003Ctag>] Review: \u003Cspecialization>\"` where `\u003Ctag>` matches the specialization: `[reviewer]` for `general`\u002F`general-2`\u002F`general-3`, `[tests]` for tests, `[security]` for security, `[plan]` for plan alignment. The bracketed tag drives the pager's subagent row label.\n\nIf `config.persona_to_inject` is non-null, prepend the corresponding persona instructions to the prompt. If null (Tests, Plan Alignment), use the prompt as-is — those specializations are prompt-only.\n\nUse the specialization-specific prompt (see Specialized Review Prompts below).\n\nAfter launching all reviewers, wait for all to complete via `get_command_or_subagent_output(task_id=..., block=true)` for each.\n\nSave each returned `subagent_id` to the corresponding `reviewer_configs` entry.\n\nIf any reviewer fails on initial launch:\n- If the **general reviewer** fails: report the error and stop entirely.\n- If a **specialist** fails: report a warning, remove that entry from `reviewer_configs`, and continue with remaining reviewers.\n\nAfter all reviewers complete, proceed to Step 3 (Merge & Check).\n\nReport to the user: \"All reviewers complete. Merging findings...\"\n\n## Specialized Review Prompts\n\nEach reviewer specialization gets a different prompt while sharing the same structured output format and severity taxonomy (`bug`, `suggestion`, `nit`).\n\nAll specialized review prompts include the `past_issues_briefing` block (if non-empty) to give reviewers awareness of historically common issues.\n\n### General Reviewer\n\nInject: `reviewer` persona instructions.\n\n```\n\u003Creviewer_persona_instructions>\n\n---\n\nReview the changes made by the implementer.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\n\u003Cif reviewer_focus_areas is non-empty:>\n## Additional focus areas (from implementation summary)\n\u003Creviewer_focus_areas>\n\u003Cend if>\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n### Tests Specialist\n\nInject: none (prompt-only subagent — no persona prepended).\n\n```\nYou are a thorough test engineer reviewing code changes for test coverage and quality.\n\nReview the changes made by the implementer, focusing specifically on test coverage and quality.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\nYour review should focus on:\n- Whether new\u002Fchanged code has adequate test coverage\n- Whether tests cover edge cases, error paths, and boundary conditions\n- Whether test assertions are specific enough (not just \"doesn't throw\")\n- Whether tests are maintainable and not overly coupled to implementation details\n- Whether integration tests exist for new endpoints or interfaces\n- Whether mocking is used appropriately (not over-mocking)\n\nDo NOT review for general code style, naming, or architecture — another reviewer handles that.\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n### Security Specialist\n\nInject: `security-auditor` persona instructions.\n\n```\n\u003Csecurity_auditor_persona_instructions>\n\n---\n\nReview the changes made by the implementer, focusing specifically on security.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\nYour review should focus on:\n- Input validation and sanitization\n- Authentication and authorization checks\n- Injection vulnerabilities (SQL, command, path traversal)\n- Sensitive data handling (secrets, PII, tokens in logs)\n- Cryptographic correctness\n- Rate limiting and abuse prevention\n- OWASP Top 10 patterns\n\nIMPORTANT: Use the following severity labels (not security-standard severities):\n- bug: for critical\u002Fhigh severity findings (exploitable vulnerabilities)\n- suggestion: for medium severity findings (defense-in-depth improvements)\n- nit: for low\u002Finformational findings (best-practice recommendations)\n\nOnly flag real, exploitable issues — not theoretical concerns.\nDo NOT review for general code style or test coverage — other reviewers handle that.\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n### Plan Alignment Specialist\n\nInject: none (prompt-only subagent — no persona prepended).\n\n```\nYou are a technical lead reviewing whether an implementation correctly follows its design plan.\n\nReview the changes made by the implementer, focusing on whether the implementation matches the plan\u002Fdesign.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\nThe original plan\u002Fdesign is referenced in the conversation context.\nIf a design document, plan, or spec is referenced by file path in the conversation context, read it in full before starting your review.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\nYour review should focus on:\n- Whether all requirements from the plan are addressed\n- Whether the implementation deviates from the planned approach\n- Whether any scope creep has occurred (implementing things not in the plan)\n- Whether any planned items are missing\n- Whether the implementation order matches the plan's dependency graph\n- Whether interfaces match what was specified\n\nDo NOT review for code style, tests, or security — other reviewers handle that.\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n## Step 3: Merge & Check Exit Condition\n\nThis step differs based on effort level.\n\n### Effort = 1\n\nRead the `review_file` yourself. Count all issues with `Status: open` regardless of severity.\n\nIncrement `round_count`. For each open issue, add its severity to `total_issues_by_severity`. Also extract a one-line description of each open issue and append to `issue_patterns` (skip exact duplicates already in the list).\n\n### Effort >= 2 (Merge)\n\nAfter all reviewers complete:\n\n1. Read each reviewer's individual review file.\n2. Merge into the single `review_file` with source tags. Prefix each issue with a tag indicating its source: `[General]`, `[General-2]`, `[General-3]`, `[Tests]`, `[Security]`, `[Plan]`. For effort 1-3, only `[General]` is used for the single general reviewer.\n3. Consolidate obviously duplicated findings — use your judgment to identify issues that reference the same file, same line, and the same underlying problem. When in doubt, keep both issues — false duplicates are worse than redundant findings.\n4. Write the merged result to `review_file`.\n\nIncrement `round_count`. Count all open issues and add their severities to `total_issues_by_severity`. Also extract a one-line description of each open issue and append to `issue_patterns` (skip exact duplicates already in the list).\n\n**Merge format:**\n\n```markdown\n## Review Issues\n\n### Issue 1 [General] — Severity: bug\n- **File**: src\u002Fhandler.rs:45\n- **Description**: Missing null check on user input\n- **Suggestion**: Add validation before processing\n- **Status**: open\n\n### Issue 2 [Security] — Severity: bug\n- **File**: src\u002Fauth.rs:102\n- **Description**: JWT token not validated for expiration\n- **Suggestion**: Add exp claim validation\n- **Status**: open\n\n### Issue 3 [Tests] — Severity: suggestion\n- **File**: tests\u002Fhandler_test.rs\n- **Description**: No test for error path when user input is null\n- **Suggestion**: Add test case for None input\n- **Status**: open\n```\n\nFor effort >= 4 with multiple general reviewers, the source tags distinguish them: `[General]`, `[General-2]`, `[General-3]`. If two general reviewers flag the same issue, consolidate as usual.\n\n### Stalemate Detection\n\nCompare the current review_file against `previous_review_snapshot` from the prior round. If any issue (matched by file reference and description, and by source tag if present) was marked `Status: wontfix` by the implementer in the previous round and has been re-opened (`Status: open`) by a reviewer in the current round, the implementer and reviewer have reached a disagreement they cannot resolve on their own.\n\nIf a stalemate is detected, proceed to Step 3a (Escalate to User).\n\nAfter completing Step 3 checks, update `previous_review_snapshot` with the current review_file contents.\n\n### Decision Logic\n\nReport the review results to the user using the appropriate message format from the In-Progress Reporting section (effort=1 vs effort>=2 variants for both the 0-issue and N-issue cases).\n\n- **0 open issues**: Done. Proceed to Step 6 (Memory Flush), then Final Report.\n- **Stalemate detected**: Proceed to Step 3a (Escalate to User).\n- **Any open issues (>0)**: Proceed to Step 4.\n\n### Step 3a: Escalate to User\n\nFor any stalemate disputes, ask the user for a decision (use the appropriate ask\u002Fquestion tool if available):\n- Frame the question clearly, including both the reviewer's position and the implementer's position\n- Provide the competing options as selectable choices\n- Include context from the implementation so the user can make an informed decision\n\nAfter the user responds, resume the implementer (Step 4) with the user's decisions included in the prompt. Tell the implementer to treat user decisions as final — incorporate them without further debate and set the corresponding issues to `Status: fixed`.\n\n## Step 4: Fix (resume implementer)\n\n**Use `spawn_subagent` only** — do not apply fixes yourself.\n\nResume the original implementer to address **all** review findings.\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `resume_from`: `\u003Cimplementer_subagent_id>`\n- `description`: `\"[implementer] Fix review issues\"`\n\nPrompt:\n```\nThe reviewer found issues. The review_file is at: \u003Creview_file>\n\nRead the review_file. Address ALL issues with Status: open — including nits, suggestions, and any style or hint-level feedback. Nothing is too small to fix.\n\nFor each issue, implement the fix, then update the review_file:\n- Change Status: open → Status: fixed\n- Add a Response field explaining what you changed\n\nYou are encouraged to push back on feedback that doesn't make sense, is contradictory, or would make the implementation worse. If you disagree with an issue:\n- Set Status: wontfix\n- Write a clear, technical explanation of why the reviewer's suggestion is wrong or counterproductive\n- Do NOT comply with feedback just to make a reviewer happy — defend good implementation decisions\n\nAppend an updated Implementation Summary at the bottom of the review_file.\n```\n\nWait for completion. If it fails, report the error to the user and stop.\n\nUpdate the saved implementer `subagent_id` with the new one returned.\n\nReport to the user: \"Fixes applied. Running re-review (round N)...\" (for effort=1) or \"Fixes applied. Running parallel re-review (round N)...\" (for effort >= 2), where N is the current `round_count` + 1.\n\n## Step 5: Re-review\n\n**Use `spawn_subagent` only** — do not re-review yourself.\n\nThe re-review step differs based on effort level.\n\n### Effort = 1 (Single Reviewer Re-review)\n\nResume the original reviewer to re-review the fixes.\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `resume_from`: `\u003Creviewer_subagent_id>`\n- `description`: `\"[reviewer] Re-review fixes\"`\n\nPrompt:\n```\nThe implementer addressed the review issues. Re-review all changes.\n\nThe updated review_file with implementer responses is at: \u003Creview_file>\nThe implementer's summary is at: \u003Csummary_file>\n\nRead both files. Review the code again thoroughly.\n\nRewrite the review_file with your new findings:\n- If a previous issue was properly fixed, do not re-list it.\n- If a fix introduced a new problem, list it as a new issue with Status: open.\n- If any issue was not properly addressed, re-list it with Status: open.\n- Use the same structured format (severity: bug\u002Fsuggestion\u002Fnit, file:line, description, suggestion, status).\n```\n\nWait for completion. If it fails, report the error to the user and stop.\n\nUpdate the saved reviewer `subagent_id` with the new one returned.\n\nIf `resume_from` fails (subagent expired), launch a fresh reviewer, prepending the `reviewer` persona instructions to the prompt. Log a warning.\n\n### Effort >= 2 (Parallel Re-review)\n\nResume all reviewers in parallel. Each reviewer is resumed with `resume_from` (using the `subagent_id` from `reviewer_configs`) and `background: true`. The persona instructions are already in each reviewer's transcript from the initial launch, so no re-injection is needed on resume.\n\nFor each config in `reviewer_configs`:\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `resume_from`: `config.subagent_id`\n- `background`: `true`\n- `description`: `\"[\u003Ctag>] Re-review: \u003Cspecialization>\"` — use the same bracketed tag as the initial launch (`[reviewer]` for `general`\u002F`general-2`\u002F`general-3`, `[tests]`, `[security]`, `[plan]`) so the pager row label stays consistent across rounds.\n\nPrompt (same structure as initial review, but with re-review instructions):\n```\nThe implementer addressed the review issues. Re-review all changes.\n\nThe updated merged review_file with implementer responses is at: \u003Creview_file>\nThe implementer's summary is at: \u003Csummary_file>\n\nRead both files. Review the code again thoroughly.\n\nRewrite your review file at: \u003Cindividual_review_file>\n- If a previous issue was properly fixed, do not re-list it.\n- If a fix introduced a new problem, list it as a new issue with Status: open.\n- If any issue was not properly addressed, re-list it with Status: open.\n- Use the same structured format (severity: bug\u002Fsuggestion\u002Fnit, file:line, description, suggestion, status).\n- Stay within the same review scope as your initial review.\n```\n\nAfter launching all re-reviewers, wait for all to complete via `get_command_or_subagent_output(task_id=..., block=true)` for each.\n\nUpdate each `subagent_id` in `reviewer_configs` with the new ones returned.\n\nIf a reviewer fails during re-review:\n- Report a warning and exclude that reviewer's findings from the merge.\n- Continue with remaining reviewers.\n\nIf `resume_from` fails for a reviewer (subagent expired), launch a fresh reviewer for that specialization, prepending the persona instructions from `config.persona_to_inject` (if non-null) to the prompt. Log a warning.\n\n**Regardless of effort level, go back to Step 3.** Repeat until 0 open issues.\n\n## Exit Condition\n\nThe **only** exit condition is **all reviewers** reporting **0 issues** of any severity in the same round. There is no iteration cap. Every issue — including nits, suggestions, and minor improvements — must be addressed before the loop terminates.\n\nThere is no per-reviewer exit — if the security reviewer has 0 issues but the general reviewer has 2, the implementer fixes those 2 and all reviewers re-review in the next round.\n\n## Step 6: Memory Flush\n\nAfter the loop terminates with 0 open issues, update the workspace memory file with patterns from this run. The orchestrator performs this directly using its own tools — no subagent is needed for this step.\n\nThe write goes through `python3 \"${MEMORY_HELPER}\" update` so that:\n- The path resolves to the **shared workspace-scoped file** (`$HOME\u002F.grok\u002Fimplement-memory\u002F\u003Cworkspace-id>.md`), not a per-worktree file.\n- An exclusive `fcntl.flock` (Python stdlib; no `flock(1)` shell binary required) is held during the read-merge-write, so a \u002Fimplement run in another worktree of the same repo can't clobber this update.\n- Dedup against existing entries is enforced **deterministically** (case- and whitespace-insensitive match within each category).\n- Compaction is enforced: each category is capped at 25 entries (lowest-count entries dropped first); Recent Runs is capped at 20 entries (oldest dropped).\n- Strict input validation: malformed types (e.g., a non-list `key_patterns`, a string where a dict is required, a calendar-invalid `date`) fail fast with exit code 4 and a clear error message rather than silently corrupting the file.\n\n### Step 6a: Collect & Categorize This Run's Patterns\n\n1. Use the `issue_patterns` list accumulated during Step 3 across all rounds. This list contains a one-line description of every distinct issue that was open at any review checkpoint during the run.\n2. **Generalize each pattern.** The memory file exists to help *future* runs on *different* tasks — patterns that reference this task's specific code, variable names, or domain objects are useless noise. Strip implementation-specific details (file names, variable names, type names, function names, domain-specific terms) and rewrite each pattern as a reusable principle that applies across different codebases and tasks:\n   - Bad: \"Missing error type `RetryableError` in retry handler list\" → Good: \"Missing entries in error-type or configuration allowlists\"\n   - Bad: \"JWT token not validated for expiration\" → Good: \"Missing expiration\u002FTTL validation on tokens or credentials\"\n   - Bad: \"`calculateTotal` function exceeds 80 lines\" → Good: \"Functions exceeding reasonable length without decomposition\"\n   - Bad: \"No test for `handleUserAuth` error path\" → Good: \"Missing tests for error\u002Fedge case paths\"\n   - Bad: \"Missing null check on `userId` parameter\" → Good: \"Missing null\u002Fundefined checks on function inputs\"\n   If a pattern is *already* general (e.g., \"Missing null checks on function inputs\"), keep it as-is. If multiple task-specific patterns generalize to the same reusable principle, collapse them into one entry.\n3. Categorize each generalized pattern into one of: Error Handling, Testing, Security, Code Quality, Naming, Documentation, Performance, or another short category name as appropriate. Reuse existing category names from `existing_patterns_snapshot` (captured in Step 0) whenever the pattern fits — do not invent a near-duplicate category like \"Error-Handling\" or \"Tests\" when one already exists.\n4. For each pattern, write a concise one-line description. Keep descriptions on a single line; the helper collapses any embedded newlines but it's cleaner to write them without.\n\n### Step 6b: Harmonize Phrasing Against Existing Entries\n\nBefore handing generalized patterns to the helper, dedup at the *phrasing* level using `existing_patterns_snapshot`:\n\n1. For each of this run's patterns, scan `existing_patterns_snapshot` for an entry in the same (or semantically equivalent) category whose description means the same thing — even if worded differently. Examples of matches:\n   - \"missing null check on input\" ≈ \"No null validation for function parameters\"\n   - \"functions over 50 lines\" ≈ \"Long functions without decomposition\"\n   - \"no tests for error path\" ≈ \"Missing tests for failure cases\"\n2. **If a semantic match exists:** replace this run's description with the **exact existing description string** (so the helper's normalised match will collapse them onto the same entry).\n3. **If no match exists:** keep your concise description as-is. It will be added as a new entry.\n4. **Within this run's own list:** also dedup by phrasing — if you have two patterns that mean the same thing, collapse them to a single entry (the helper would otherwise count them as two distinct hits, which is fine but slightly inflates new-pattern stats).\n\nThe helper will also do a final case\u002Fwhitespace\u002Fpunctuation normalisation, but it cannot infer semantic equivalence — that's the orchestrator's job here. Skipping this step leads to the file accumulating near-duplicates over time.\n\n### Step 6c: Build the Update Spec\n\nConstruct a JSON object with this shape (omit `run` only if you want to record patterns without logging a run; in normal flow, always include both):\n\n```json\n{\n  \"patterns\": [\n    {\"category\": \"Error Handling\", \"description\": \"Missing null\u002Fundefined checks on function inputs\"},\n    {\"category\": \"Testing\", \"description\": \"Missing tests for error\u002Fedge case paths\"}\n  ],\n  \"run\": {\n    \"date\": \"2026-04-23\",\n    \"description\": \"Add retry logic to blackbox client\",\n    \"rounds\": 2,\n    \"issues_by_severity\": {\"bug\": 1, \"suggestion\": 1, \"nit\": 5},\n    \"key_patterns\": [\"Missing entries in error-type allowlists\", \"Incomplete configuration validation\"],\n    \"specializations\": [\"general\"]\n  }\n}\n```\n\nField notes (the helper rejects wrong-typed input with exit code 4 and a clear error message identifying the offending field; empty-or-null input falls back to defaults or is silently skipped per the per-field rules below):\n- `patterns[]`: each entry must be an object. `category` must be a string (defaults to `\"Other\"` if empty\u002Fnull). `description` must be a string; **null and omitted are treated identically** (both result in a silent skip with no error).\n- `patterns[].description`: one-line, harmonised in Step 6b. Newlines\u002Ftabs are collapsed to single spaces; internal multi-space runs are preserved.\n- `run` must be an object (not a list, not a string). Send `null` or omit it entirely to skip the Recent Runs entry.\n- `run.date`: a string in `YYYY-MM-DD` format. Calendar-invalid dates like `2026-13-99` are rejected. Pass `null`, empty string, or whitespace-only string and the helper fills in today's UTC date.\n- `run.description`: the user's implementation request, trimmed to a short label. Must be a string (or `null`\u002Fomitted to fall back to `\"(no description)\"`). The helper strips ALL double-quote characters from the description and then wraps it in exactly one outer pair, so internal quotes never produce broken nested-quote markup. (`Add retry \"logic\" to client` becomes `\"Add retry logic to client\"`.) If you need to preserve quotes verbatim, escape them yourself before submission — the helper assumes the description is a free-form label, not a structured string.\n- `run.rounds`: `round_count` as an integer. Booleans, floats, strings, and lists are rejected. Zero is accepted as-is (structurally unreachable in the actual \u002Fimplement loop, but not enforced).\n- `run.issues_by_severity`: derived from `total_issues_by_severity`. Must be an object with string keys and integer values (or `null`\u002Fomitted to skip the `**Issues**` body line entirely). Zero-count severities are silently dropped from the rendered summary; if all severities are zero (or the object is empty) the helper omits the `**Issues**` body line entirely.\n- `run.key_patterns`: must be a list of strings (or `null`\u002Fomitted to skip the `**Key patterns**` body line). Pick the 2-3 most-significant patterns from this run. **Apply the same generalization rules as Step 6a** — strip task-specific names and rewrite as reusable principles. Two implementable options, pick consistently across runs:\n  - **Option A (recommended): severity-ranked.** Re-read the latest merged review_file (still on disk at this point in the loop). Each issue has a `Severity:` tag. Take 1-2 of the highest-severity issues first (bugs > suggestions > nits), then top up with the next-highest severity until you have 3 entries. This sees only **final-round survivors** (issues that the implementer actually had to address) which is the natural \"most-significant\" reading.\n  - **Option B (lower-effort): recency-ranked.** Take the **last 2-3 entries** of `issue_patterns` (the list grows by appending per round in Step 3, so the tail is the most-recent round's issues). This sees **cross-round accumulation** including issues that were introduced and fixed mid-loop. Use this only if re-reading the review_file is impractical — the resulting `key_patterns` will sometimes include issues that ended up wontfix or were ephemeral.\n  - **Pick one option and stick with it for the run.** The two options return semantically different sets, so mixing them across runs makes the Recent Runs log inconsistent.\n- `run.specializations`: must be a list of strings (or `null`\u002Fomitted to skip the `**Specializations used**` body line). Strip the `-N` suffix from `general-2`\u002F`general-3` first so the list is the set of distinct specialization classes (e.g., `[\"general\", \"security\"]`, not `[\"general\", \"general-2\", \"security\"]`); deduplicate.\n\n### Step 6d: Invoke the Helper\n\nUse the `write` tool to create `${scratch_dir}\u002Fgrok-mem-${IMPL_ID}.json` with the JSON spec above (using a temp file avoids quoting issues that heredocs introduce), then invoke the helper via `run_terminal_cmd`:\n\n```bash\npython3 \"${MEMORY_HELPER}\" update \u003C ${scratch_dir}\u002Fgrok-mem-${IMPL_ID}.json\n```\n\nThe helper acquires the lock, parses the existing file, merges, compacts, writes atomically, and prints a JSON stats summary on stdout (pretty-printed with `indent=2`):\n\n```json\n{\n  \"file\": \"\u002FUsers\u002F...\u002Fimplement-memory\u002Fproj-d5016f47e5cb.md\",\n  \"existed_before\": false,\n  \"stats\": {\n    \"new_patterns\": 2,\n    \"merged_patterns\": 5,\n    \"categories_touched\": [\"Error Handling\", \"Testing\"],\n    \"categories_capped\": {},\n    \"recent_runs_dropped\": 0\n  },\n  \"total_categories\": 4,\n  \"total_patterns\": 17,\n  \"total_recent_runs\": 12\n}\n```\n\nKey fields:\n- `existed_before`: `true` if the file existed before this update, `false` if the helper just created it. Use this for the report wording.\n- `stats.categories_capped`: dict of `{category: dropped_count}` for any category that exceeded `MAX_PATTERNS_PER_CATEGORY` and had its lowest-count entries dropped. Empty dict in the typical case.\n\nUse these stats to report to the user:\n> \"Memory updated: 2 new patterns, 5 merged into existing entries (file at \u003Cfile>).\"\n\nOr if `existed_before` is `false`:\n> \"Memory file created at \u003Cfile> with N patterns.\"\n\n### Memory File Format\n\nThe helper writes a markdown file with this structure:\n\n\u003C!-- mirror-of: scripts\u002Fmemory.py DEFAULT_HEADER -->\n\u003C!-- The 5-line block immediately following this comment must match -->\n\u003C!-- '\\n'.join(memory.DEFAULT_HEADER) verbatim. The drift-check unit -->\n\u003C!-- test TestDocsConsistency.test_skill_md_default_header_matches -->\n\u003C!-- asserts this on every test run. -->\n```markdown\n# Implementation Review Patterns\n\n> This file is maintained by the \u002Fimplement skill.\n> It records common issues found during implementation reviews to help avoid them in future runs.\n> Shared across all working directories that resolve to the same workspace id.\n\n## Common Issues\n\n### Error Handling\n- Missing null\u002Fundefined checks on function inputs (seen 5 times)\n- Not handling async errors in promise chains (seen 3 times)\n- Missing error logging before re-throwing (seen 2 times)\n\n### Testing\n- Missing tests for error\u002Fedge case paths (seen 8 times)\n- Tests that don't assert on error messages, only error types (seen 3 times)\n- No integration tests for new API endpoints (seen 2 times)\n\n### Security\n- User input not validated before database queries (seen 2 times)\n- Missing rate limiting on new endpoints (seen 1 time)\n\n### Code Quality\n- Functions exceeding 50 lines without decomposition (seen 4 times)\n- Magic numbers without named constants (seen 6 times)\n- Inconsistent naming conventions within new code (seen 3 times)\n\n## Recent Runs\n\n### 2026-04-23 — \"Add retry logic to blackbox client\"\n- **Rounds**: 2\n- **Issues**: 7 total (1 bug, 1 suggestion, 5 nits)\n- **Key patterns**: Missing entries in error-type allowlists, incomplete configuration validation\n- **Specializations used**: general\n\n### 2026-04-22 — \"Implement user auth endpoints\"\n- **Rounds**: 3\n- **Issues**: 12 total (3 bugs, 4 suggestions, 5 nits)\n- **Key patterns**: Missing expiration\u002FTTL validation on tokens, missing rate limiting on new endpoints, missing tests for error\u002Fedge case paths\n- **Specializations used**: general, security\n```\n\nNotes on the format:\n- Within each category, entries are sorted by count desc then description asc (case-insensitive).\n- `seen 1 time` (singular) and `seen N times` (plural) are both produced and parsed.\n- `—` (em-dash), `–` (en-dash), and `-` (ASCII hyphen) are all accepted as separators in run headers.\n- The helper preserves any custom lines you add to the header (anything before `## Common Issues`) on round-trip. Custom freeform paragraphs **inside** a category in `## Common Issues` are not preserved — only `### Category` headers and well-formed `- desc (seen N time(s))` bullets survive. **Caveat:** anything written to the file before the first `## Common Issues` heading becomes part of the preserved header indefinitely, including unintentional garbage from a hand-edit. To reset a corrupted file, delete it and the helper will recreate it with the default header on the next `update`. If you delete the header itself (leaving the file starting at `## Common Issues`), the helper re-injects the default header on the next render — not byte-stable, but the data survives.\n- Both the memory file and its sibling `.lock` file are written and then chmodded to mode `0o600` (owner read\u002Fwrite only, best-effort — if a cross-user race makes the chmod fail, the file's umask-default mode is preserved). The memory file may contain security-review patterns and `key_patterns` drawn from non-public source review, so we deliberately keep it owner-only on shared hosts (the workspace id is a deterministic SHA-256 of the canonical remote URL, so an unprivileged account that knows or guesses the public-repo URL could otherwise read the file directly). In the typical single-user case both files end up at `0o600` regardless of the process umask. The lock file's content is irrelevant; it exists purely as an `flock` target.\n\n### Graceful Degradation\n\nIf the helper exits non-zero (lock contention timeout, malformed spec, disk full, etc.), log a warning with the helper's stderr and skip the memory update. The implementation is already complete and reviewed at this point — never fail the run due to memory flush issues. Also remove the temp JSON spec file in the cleanup step regardless.\n\nExit codes:\n- `0`: success.\n- `1`: unexpected I\u002FO error (disk full mid-write, permission flips during execution, FS races). The stderr message says `memory.py: I\u002FO error: ...`.\n- `2`: workspace id could not be determined (cwd unreadable and `$HOME` unset — very rare).\n- `3`: lock could not be acquired within 30 seconds (another concurrent \u002Fimplement run is monopolising the file; usually retrying once works).\n- `4`: stdin JSON is missing, malformed, or fails type validation. The stderr message identifies the offending field. Surface it verbatim in the report so the user can see what was wrong with the spec.\n\n## Cleanup\n\nAfter Step 6 (Memory Flush) and the Final Report, clean up the temporary artifact files:\n\n```bash\nrm -f ${scratch_dir}\u002Fgrok-impl-summary-${IMPL_ID}.md ${scratch_dir}\u002Fgrok-review-${IMPL_ID}.md ${scratch_dir}\u002Fgrok-review-${IMPL_ID}-*.md ${scratch_dir}\u002Fgrok-mem-${IMPL_ID}.json\n```\n\nNote: the workspace memory file under `$HOME\u002F.grok\u002Fimplement-memory\u002F` is NOT cleaned up — it persists across runs as the shared memory file for this workspace.\n\n## Final Report\n\nWhen the loop terminates (0 issues), read the summary_file and review_file one last time (before cleanup), then present a final report to the user:\n\n1. **Summary of what was implemented** — from the summary_file: which files were changed, what was added\u002Fmodified, key design decisions.\n2. **Effort level** — the effort parameter used and which specializations were active (e.g., \"Effort 2: general + security\").\n3. **Review rounds** — how many review→fix iterations it took to reach 0 issues (the value of `round_count`).\n4. **Total issues fixed** — the cumulative count from `total_issues_by_severity`, broken down by severity (bugs, suggestions, nits).\n5. **Issues by reviewer** — breakdown of how many issues each reviewer found across all rounds (by specialization tag).\n6. **Files changed** — list the files that were created or modified.\n7. **Anything notable** — if the implementer made design decisions, disagreed with a reviewer suggestion (wontfix), or encountered anything unexpected, call it out.\n8. **Memory update** — what patterns were written or updated in the workspace memory file (path returned by the helper as the `file` field). Use the `existed_before` flag from the helper's stats output to choose between \"file created\" (false) and \"file updated\" (true) wording.\n\n## In-Progress Reporting\n\nGive the user a brief status update after each phase:\n\n- After specialization selection (effort >= 2): \"Using effort level N: general reviewer + \u003Cspecialist(s)> (\u003Creason>).\"\n- After implement (effort=1): \"Implementation complete. Starting review...\"\n- After implement (effort >= 2): \"Implementation complete. Starting parallel review (N reviewers)...\"\n- After all reviewers complete (effort >= 2): \"All reviewers complete. Merging findings...\"\n- After review (0 issues, effort=1): \"Review passed with 0 issues. Flushing to memory...\" (then run Step 6, then print the Final Report)\n- After review (0 issues, effort >= 2): \"All reviews passed with 0 issues. Flushing to memory...\" (then run Step 6, then print the Final Report)\n- After review (N issues, effort=1): \"Reviewer found N issues (X bugs, Y suggestions, Z nits). Resuming implementer to fix...\"\n- After review (N issues, effort >= 2): \"Merged review: N issues (X bugs [1 General, 1 Security], Y suggestions [General], Z nits [Tests]). Resuming implementer to fix...\" — include per-source-tag breakdown within each severity, showing how many issues came from each reviewer.\n- After fix (effort=1): \"Fixes applied. Running re-review (round N)...\" (where N = `round_count` + 1, i.e., the upcoming round number)\n- After fix (effort >= 2): \"Fixes applied. Running parallel re-review (round N)...\" (where N = `round_count` + 1)\n- After stalemate escalation: \"Stalemate detected on N issue(s). Escalating to user...\"\n- After memory flush: \"Memory updated with N patterns from this run.\" (or \"Memory file created with N patterns.\" for first run)\n\n## Rules\n\n- **Tool-call discipline** — every \"launching\", \"spawning\", \"starting\", or \"running\" statement in your prose must be backed by a `spawn_subagent` tool call in the same assistant response. Never end a turn with a content-only message that claims a subagent is being launched. See [Tool-Call Discipline (Anti-Hallucination)](#tool-call-discipline-anti-hallucination) for the full rule set.\n- **No permission-asking on launch** — the launch announcement is informational, not interactive. Do not append \"Want me to check in every 30 min, or run silently?\" or similar cadence-negotiation questions to launch messages. Pick a default and proceed.\n- **Inject personas into prompts** — prepend `implementer` persona instructions for the implementer, `reviewer` for general reviewer, `security-auditor` for security specialist. Do NOT pass a `persona` parameter to `spawn_subagent`. For Tests and Plan Alignment specialists, do not prepend any persona — they are prompt-only subagents. On `resume_from` follow-ups, the persona is already in the transcript from the initial launch.\n- **Prefix `description` with a bracketed role tag** — `[implementer]`, `[reviewer]`, `[security]`, `[tests]`, or `[plan]`. The pager's subagent label renderer parses the first `[tag]` of the description and uses it as the row label (the bracketed prefix is stripped from the displayed description). Without this, every row falls through to the generic \"General\" label because `subagent_type` is `general-purpose` and no persona\u002Frole is plumbed through the spawn args. Keep the tag on `resume_from` follow-ups too so the label stays stable across rounds.\n- **resume_from on follow-ups** — never launch a fresh subagent for fix or re-review rounds. Always resume the previous one so it retains its full working memory. Exception: if `resume_from` fails (subagent expired), launch a fresh one and log a warning.\n- **Save every subagent_id** returned by `spawn_subagent` — these are needed for `resume_from` on subsequent rounds. Store them in `reviewer_configs` for reviewers.\n- **Read the review_file yourself** after each review to count open issues and decide whether to continue the loop.\n- **Don't modify the implementation yourself** — all code changes go through the implementer persona subagent.\n- **Explicitly tell subagents to write their output files** — include the file path and what to write in every prompt.\n- **Thread the same file paths** across all rounds — never generate new paths between iterations.\n- **No iteration cap** — the loop runs until 0 issues. Do not add a max rounds limit.\n- **If the user provides additional instructions** (like \"run tests after\", \"use this pattern\", \"don't touch file X\"), include those constraints in the implementer prompt.\n- **Error handling** — if a subagent fails or cannot be resumed, report the error to the user and stop. Do not silently continue with missing results. Exception: specialist reviewer failures are non-fatal (warn and continue with remaining reviewers); only general reviewer failure is fatal.\n- **Effort=1 is structurally simple** — for effort=1, the single general-purpose reviewer writes directly to `review_file`. No individual review files, no merge step. This is the current behavior with the added wontfix\u002Fstalemate mechanism.\n- **Effort>=2 uses individual files + merge** — each reviewer writes to its own file to avoid write conflicts during parallel execution. The orchestrator merges them into `review_file` after all complete.\n- **Severity normalization** — all reviewers must use `bug`, `suggestion`, `nit` as severity labels. The security specialist prompt explicitly maps native security severities to this taxonomy.\n- **Implementer can push back** — the implementer is explicitly allowed (and encouraged) to set `Status: wontfix` with a technical justification. If a reviewer re-opens a wontfix'd issue, it's a stalemate that gets escalated to the user.\n- **Escalate, don't spin** — if the implementer and a reviewer cannot reach consensus on an issue after two rounds, escalate to the user by asking them directly (use the appropriate ask\u002Fquestion tool if available). Never let the loop spin on a disagreement.\n- **User decisions are final** — once the user resolves a disputed issue, the implementer must incorporate it without further debate.\n- **Memory is best-effort.** The past-issues briefing and memory flush are additive features. If the `memory.py` helper fails (lock contention timeout, malformed spec, disk full, etc.) proceed without it. Never fail a run due to memory issues. A non-git workspace is **not** a failure mode — the helper falls back to a cwd-based id.\n- **Always go through the `memory.py` helper.** The file lives at `$HOME\u002F.grok\u002Fimplement-memory\u002F\u003Cworkspace-id>.md`, resolved by `python3 \"${MEMORY_HELPER}\" path`. The helper itself lives at `\u003Cdirname of this SKILL.md>\u002Fscripts\u002Fmemory.py` — derive `MEMORY_HELPER` from the SKILL.md path the system context gave you (it works whether the skill is loaded from a workspace, from `~\u002F.grok\u002Fskills\u002F`, or from a bundled location), **never** from `$(pwd)`. The workspace id is derived from a canonicalised `git config remote.origin.url` (falling back to the absolute `--git-common-dir` path, then to the absolute cwd), so all worktrees and SSH\u002FHTTPS clones of the same upstream repo share one file. Never reference the legacy `.grok\u002Fimplement-issues.md` path — it is per-worktree and useless. Never read or write the file directly — the helper is the single source of truth.\n- **Concurrency-safe writes are the helper's job, not yours.** The helper holds an exclusive `fcntl.flock` (Python stdlib, not the `flock(1)` shell tool) on a sibling `.lock` file during the read-merge-write and commits via temp-file + rename, so two \u002Fimplement runs in different worktrees can update the file simultaneously without losing writes. Do **not** implement your own locking around the helper.\n- **Dedup is a two-layer responsibility.** The orchestrator harmonises this run's pattern phrasings against `existing_patterns_snapshot` (semantic dedup, Step 6b); the helper then performs case\u002Fwhitespace\u002Fpunctuation normalisation as a safety net. Skipping the orchestrator step leads to near-duplicate entries the helper cannot collapse.\n- **Compaction is automatic.** The helper caps each category at 25 entries (lowest-count entries dropped) and Recent Runs at 20 entries (oldest dropped). The orchestrator does not need to enforce caps.\n- **Use the `snapshot` subcommand for reads, not `read`.** `python3 \"${MEMORY_HELPER}\" snapshot` returns structured JSON (`common_issues`, `recent_runs`, `exists`) so the orchestrator never has to parse markdown. The `read` subcommand is preserved for human inspection only.\n- **Briefing is injected, not enforced** — the past-issues briefing is informational context. It tells the implementer and reviewers what patterns to watch for, but does not mandate specific behaviors or block the run if patterns are found.\n","# Implement Skill\n\nYou are an orchestrator that runs the **implement → review → fix** loop using the `implementer` and `reviewer` personas. Your job is to keep the loop running until the code is clean. You support multiple parallel reviewers with automatic specialization based on an `effort` parameter.\n\nYou coordinate only. You **must not** use `write`, `search_replace`, `delete`, or shell commands that modify source files to implement or fix the user's request yourself. **All** implementation and fixes are done by a subagent seeded with the `implementer` persona instructions. **All** review is done by a subagent seeded with the `reviewer` or `security-auditor` persona instructions (or by prompt-only subagents for Tests and Plan Alignment specialists).\n\n## Tool-Call Discipline (Anti-Hallucination)\n\nEvery action you describe in your text **must** correspond to an actual tool call in the same assistant response. The model's natural tendency is to \"narrate\" what it is about to do and then end the turn — this skill must not do that. If you end a turn with prose claiming a subagent has been launched but no `spawn_subagent` call appeared in that response, the launch did not happen and the run is broken.\n\n1. **Tool call first, narration second.** When a step tells you to \"launch the implementer\" or \"spawn the reviewers\", emit the `spawn_subagent` tool call(s) **before** any user-visible text describing the launch. Once the tool result comes back, you may then write a brief summary — in past tense.\n2. **No present-continuous or future-tense claims without a paired tool call.** Never write phrases like \"The implementer **is being launched** now…\", \"I'll **start** the reviewers…\", or \"The subagent **will begin** working…\" in an assistant message unless that same message also contains the corresponding `spawn_subagent` tool call. Future-tense or present-continuous wording in a content-only message is a strong signal that you skipped the actual tool call.\n3. **No permission-asking at launch time.** Setup, spawn, and progress-cadence decisions are yours to make. Do not append a question like \"Want me to give you a quick status check in ~30 min, or just let it run silently until the first big checkpoint?\" to a launch message. Pick a sensible default (see In-Progress Reporting) and proceed. Asking forces the user to drive the loop, which is the opposite of what this skill exists to do.\n4. **Past-tense announcements only.** Correct: \"Launched 5 reviewers in parallel (general × 2, security, tests, plan alignment). subagent_ids: …\". Incorrect: \"I will now launch 5 reviewers…\". Past tense should always reference a tool call you can point to in the same response.\n5. **Self-check before ending a turn.** Before producing a content-only assistant message (no tool calls) that mentions launching, starting, spawning, or otherwise initiating any subagent or background task, verify that the corresponding `spawn_subagent` call appears earlier in **this same response** or that the tool result for it is already in the history. If it doesn't, call the tool now — never end the turn with stranded narration.\n\n## Todo Scaffold\n\nOpen the run with a `todo_write` (merge: false) listing the canonical phases. Use exactly this id schema so the runtime turn-end gate can correlate phases consistently across compactions:\n\n- `setup` — Step 0 (memory retrieval) + reviewer-config decision\n- `implement` — Step 1 (spawn implementer)\n- `review-round-1` — Step 2 (spawn reviewers) + Step 3 (merge & check)\n- `fix-round-1` — Step 4 (resume implementer to fix)\n- `rereview-round-1` — Step 5 (resume reviewers) + Step 3 (merge & check)\n- (repeat `fix-round-N` + `rereview-round-N` as needed)\n- `memory-flush` — Step 6\n- `final-report` — Final report message\n\nMark exactly one `in_progress` at a time. As you enter a new round, append the two new ids (`fix-round-N`, `rereview-round-N`) via `merge: true`. A `review-round-N` that produces 0 open issues skips directly to `memory-flush`; mark intermediate `fix-round-N` \u002F `rereview-round-N` ids as `cancelled` with reason \"0 open issues this round\" only if you created them.\n\nNever end a turn with `in_progress` set to a phase whose subagent has not been spawned yet. Spawn first; then optionally mark the phase as completed and the next phase as in_progress in the next turn.\n\n**Reseed after compaction** — the harness no longer surfaces a pre-compaction todo snapshot. If a compaction lands mid-implementation, rebuild the scaffold from the canonical phase ids above (`setup`, `implement`, `review-round-N`, etc.) plus the persisted review\u002Fsummary files for the current round, and seed the remaining phases before continuing. The Recall v1 regression was caused exactly by skipping this rebuild.\n\n## Persona Injection\n\nThis skill uses the **implementer**, **reviewer**, and **security-auditor** personas. The persona instructions are defined at:\n\n```\n\u003Cdirname of this SKILL.md>\u002F..\u002Fshared\u002Fpersonas\u002Fimplementer.md\n\u003Cdirname of this SKILL.md>\u002F..\u002Fshared\u002Fpersonas\u002Freviewer.md\n\u003Cdirname of this SKILL.md>\u002F..\u002Fshared\u002Fpersonas\u002Fsecurity-auditor.md\n```\n\nResolve these paths once at the start of the run (the system context gives you the absolute path to this SKILL.md). Read each file with `read_file` and store their contents as `implementer_persona_instructions`, `reviewer_persona_instructions`, and `security_auditor_persona_instructions`.\n\nWhen launching a subagent, **prepend** the appropriate persona instructions to its prompt. Do NOT pass a `persona` parameter to `spawn_subagent` — that parameter is not supported. Instead, prefix the `description` with a bracketed role tag (`[implementer]`, `[reviewer]`, `[security]`, `[tests]`, `[plan]`, etc.) so the pager's subagent label renderer (see `format_subagent_label` in `xai-grok-pager`) surfaces the role name at the top of the subagent row instead of the generic \"General\" fallback. The bracketed prefix is stripped from the displayed description. On `resume_from` follow-ups, the persona is already in the subagent's transcript from the initial launch — do not re-inject it; **do** keep the bracketed tag in the description so the label remains correct.\n\n## Invocation\n\nThe user runs:\n```\n\u002Fimplement [--effort N] \u003Cdescription>\n```\n\nThe `\u003Cdescription>` is the implementation task — it can be a feature request, bug fix, refactoring goal, plan, or any coding task. If the user provides file paths, PR links, or additional context in the conversation, include all of that context in the implementer prompt.\n\nThe `effort` parameter is an optional integer, 1–5 (default: 1). It controls how many reviewers participate in the review phase:\n\n| Effort | Reviewer Count | Behavior |\n|--------|---------------|----------|\n| 1 | 1 | Single general-purpose `reviewer` (current behavior + wontfix\u002Fstalemate mechanism) |\n| 2 | 2 | Coordinator splits 2 slots between generals and specialists based on description |\n| 3 | 3 | 3 slots — more coverage, same adaptive split |\n| 4 | 5 | 5 slots — room for multiple generals + full specialist coverage |\n| 5 | 6 | Maximum rigor — up to 3 generals + all 3 specialists |\n\nExtract the effort level from the argument string using natural language understanding. Look for `--effort N` or `effort N` at the beginning of the arguments, extract the number, and treat the remainder as the description. If `--effort` is not present, or the value is out of range, default to 1.\n\n## Setup\n\nGenerate a unique ID for this run's artifact files. Execute this via `run_terminal_cmd` and capture the output:\n\n```bash\npython3 -c \"import uuid; print(uuid.uuid4().hex[:8])\"\n```\n\n**Validate** that the command succeeded and produced a non-empty string. If `IMPL_ID` is empty or the command failed, report the error to the user and stop.\n\nStore the output as `IMPL_ID`.\n\nThen compute a **per-user, `$TMPDIR`-respecting scratch directory** for all artifact files. Never write skill artifacts directly under `\u002Ftmp` on a shared host: it leaks their contents to other users and ignores a user-configured `$TMPDIR`. Run via `run_terminal_cmd` and capture stdout:\n\n```bash\nscratch_dir=\"${TMPDIR:-\u002Ftmp}\u002Fgrok-$(id -u)\"; mkdir -p \"$scratch_dir\" && chmod 700 \"$scratch_dir\" && echo \"$scratch_dir\"\n```\n\nStore the output as `scratch_dir`. **Inline the resolved absolute path** into every file path below and into every subagent prompt; do not rely on a `$scratch_dir` shell variable surviving across separate `run_terminal_cmd` calls (the same reason this skill inlines `${MEMORY_HELPER}`).\n\nThen define the shared file paths (all under `scratch_dir`):\n- `summary_file`: `${scratch_dir}\u002Fgrok-impl-summary-${IMPL_ID}.md`\n- `review_file`: `${scratch_dir}\u002Fgrok-review-${IMPL_ID}.md` (merged review — what the implementer reads)\n\nFor `effort >= 2`, also define individual review files per reviewer:\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-general.md`\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-general-2.md` (if effort >= 4)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-general-3.md` (if effort >= 5)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-tests.md` (if tests specialist selected)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-security.md` (if security specialist selected)\n- `${scratch_dir}\u002Fgrok-review-${IMPL_ID}-plan.md` (if plan alignment specialist selected)\n\nThese paths stay the same for the entire loop. Never regenerate them between iterations.\n\nInitialize these state variables for the orchestrator to maintain across rounds:\n- `round_count`: `0` — incremented each time a review completes.\n- `total_issues_by_severity`: `{}` — a map from severity (bug, suggestion, nit) to cumulative count. After each review, add the count of open issues by severity to this accumulator.\n- `previous_review_snapshot`: `\"\"` — after each review, before the implementer fixes, save a copy of the review_file contents so you can detect stalemates by comparing the current round's wontfix\u002Fre-opened issues against the prior round.\n- `reviewer_configs`: `[]` — list of reviewer config objects (see Specialization Selection below).\n- `past_issues_briefing`: `\"\"` — populated in Step 0 from the workspace memory file (resolved via the `memory.py` helper, see Step 0). Contains a formatted markdown block of common issue patterns from previous runs, injected into implementer and reviewer prompts. Empty string if no past issues exist.\n- `issue_patterns`: `[]` — a list of concise one-line issue descriptions accumulated across rounds. After each Step 3, extract a one-line description from each open issue and append it to this list (deduplicating exact matches). Used in Step 6 (Memory Flush) instead of relying on LLM recall of earlier rounds.\n\n## Specialization Selection\n\nWhen `effort >= 2`, the orchestrator decides how to fill the reviewer slots. It first identifies which specialists are relevant based on the description, then fills any remaining slots with additional independent general reviewers. This means effort 2 with no specialist matches produces 2 independent general reviewers — not a forced specialist. For effort=1, a single general reviewer is always used. This decision is made **before Step 1 (Implement)** based on the implementation description and conversation context.\n\n### Specialization Catalog\n\n| Specialization | Persona to Inject | Focus Areas | When to Use |\n|---------------|-------------------|-------------|-------------|\n| **General** | `reviewer` | Code quality, bugs, naming, SOLID, style | Always (every run) |\n| **Tests** | None (prompt-only) | Test coverage, test quality, edge cases, mocking | When implementation involves new logic, APIs, or data processing |\n| **Plan Alignment** | None (prompt-only) | Implementation matches the design\u002Fplan, no scope drift, all requirements addressed | When a design doc or detailed plan is referenced in the description |\n| **Security** | `security-auditor` | Auth, injection, data handling, secrets, OWASP | When implementation touches auth, user input, APIs, data storage, or network |\n\n**Note on persona injection:** The `Tests` and `Plan Alignment` specializations do NOT get persona instructions prepended — they rely entirely on the task prompt to define their behavior. This avoids a conflict between the `reviewer` persona's review focus and the specialist prompt's scope restriction.\n\nThe `security-auditor` persona instructions are prepended for security review because they contain purpose-built audit methodology.\n\nThe `reviewer` persona instructions are prepended as-is for the general code quality review.\n\n### Decision Algorithm\n\nThe coordinator determines the reviewer composition in two steps:\n\n```\n# Step 1: Determine total reviewer slots from effort\nif effort \u003C= 3:\n    total_slots = effort\nelif effort == 4:\n    total_slots = 5\nelse:  # effort == 5\n    total_slots = 6\n\n# Step 2: Identify relevant specialists from description\nmatched_specialists = []\n\nif description mentions auth, security, user input, API keys, \n   secrets, encryption, permissions, tokens, or OWASP:\n    matched_specialists.append(\"security\")\n\nif description references a design doc, plan, spec, RFC, \n   or linked document:\n    matched_specialists.append(\"plan_alignment\")\n\nif description involves new logic, endpoints, data processing,\n   algorithms, or business rules:\n    matched_specialists.append(\"tests\")\n\n# Step 3: Allocate slots\n# Cap specialists by available slots (total - 1, since at least 1 general)\nspecialists = matched_specialists[:total_slots - 1]\n\n# Remaining slots become additional general reviewers\nnum_generals = total_slots - len(specialists)\n```\n\n**Examples:**\n- Effort 2, simple refactoring (no matches) → 2 generals, 0 specialists\n- Effort 2, touches auth → 1 general + security\n- Effort 3, touches auth → 2 generals + security\n- Effort 3, touches auth + has design doc → 1 general + security + plan alignment\n- Effort 4, only tests match → 4 generals + tests\n- Effort 5, all 3 match → 3 generals + all 3 specialists\n\n### Building reviewer_configs\n\nBuild `reviewer_configs` for every effort level. The general reviewer is always included. For `effort >= 2`, also append specialists and (for effort 4-5) additional general reviewers:\n\n```\nreviewer_configs = []\n\n# Add general reviewers\nfor i in range(1, num_generals + 1):\n    tag = \"general\" if i == 1 else f\"general-{i}\"\n    reviewer_configs.append({\n        subagent_id: null,\n        persona_to_inject: \"reviewer\",  # key into loaded persona instructions\n        specialization: tag,\n        review_file: effort == 1 ? review_file : f\"${scratch_dir}\u002Fgrok-review-{IMPL_ID}-{tag}.md\"\n    })\n\n# Add specialist reviewers\nfor each specialist in specialists:\n    reviewer_configs.append({\n        subagent_id: null,\n        persona_to_inject: specialist == \"security\" ? \"security-auditor\" : null,  # null = prompt-only, no persona prepended\n        specialization: specialist,\n        review_file: f\"${scratch_dir}\u002Fgrok-review-{IMPL_ID}-{suffix_map[specialist]}.md\"\n    })\n```\n\nThe specialization-to-suffix mapping is: `general` → `general`, `general-2` → `general-2`, `general-3` → `general-3`, `tests` → `tests`, `security` → `security`, `plan_alignment` → `plan`.\n\nFor source tags in the merged review, use `[General]`, `[General-2]`, `[General-3]` to distinguish independent general reviewers. All general reviewers use the same `reviewer` persona and the same General Reviewer prompt — independent runs naturally produce different findings due to LLM variance.\n\n### Announce Specializations\n\nAnnounce the specialization choices to the user **once**, then move on. Examples of correct messages:\n> \"Using effort level 2: 2 independent general reviewers (no specialist triggers matched).\"\n> \"Using effort level 2: general reviewer + security specialist (implementation touches auth endpoints).\"\n> \"Using effort level 4: 3 general reviewers + security + tests (5 reviewers).\"\n\nStrict rules for this announcement:\n- This message describes **only the specialization selection**. Do **not** also claim that the implementer is being launched, that reviewers are starting, or that the run is \"now running\" — those statements belong to later steps, after the corresponding `spawn_subagent` calls.\n- Do **not** end the announcement with a question to the user. No \"Want me to check in every 30 minutes?\", no \"Should I proceed?\", no \"Let me know if you want me to do anything different.\" This step is fire-and-forget: no blocking interaction, no approval step, no cadence negotiation.\n- Proceed directly to Step 0 (Memory Retrieval) and Step 1 (Implement) in the same turn. The next user-visible message should be the post-spawn launch confirmation described in Step 1, not a continuation of this announcement.\n\n## Step 0: Memory Retrieval (Past Issues Briefing)\n\nBefore launching the implementer, attempt to load past issue patterns from the workspace memory file. This briefing is injected into both the implementer and reviewer prompts to help avoid recurring issues.\n\nThe memory file is **workspace-scoped** and lives under `$HOME\u002F.grok\u002Fimplement-memory\u002F`, keyed by a stable workspace id derived in this order:\n\n1. Canonicalised `git config remote.origin.url` (SSH and HTTPS variants of the same upstream collapse onto one id, with or without the `.git` suffix).\n2. Absolute path of the main `.git` directory (`git rev-parse --git-common-dir`) for repos with no remote.\n3. Absolute path of cwd as a last-ditch fallback for non-git workspaces.\n\nThe `memory.py` helper at `\u003Cdirname of this SKILL.md>\u002Fscripts\u002Fmemory.py` resolves the path and handles concurrent access via Python's `fcntl.flock` (no `flock(1)` shell binary required).\n\n### Resolve the helper path once\n\nThe helper script lives at a fixed location **relative to this SKILL.md file**: `\u003Cdirname of SKILL.md>\u002Fscripts\u002Fmemory.py`. The orchestrator already knows the absolute path to this SKILL.md file from its system context (the skills list announces each skill's path when it's loaded). Derive the helper path from that, **not** from `$(pwd)` — the skill can be loaded from a workspace-local `.grok\u002Fskills\u002F`, the user's home `~\u002F.grok\u002Fskills\u002F`, or a bundled `~\u002F.grok\u002Fbundled\u002F...` location, and only the SKILL-relative path works in all cases.\n\nCapture it once at the start of the run as **orchestrator state** (a value held in your own working memory):\n\n```\nmemory_helper_path = dirname(\u003Cpath-to-this-SKILL.md>) + \"\u002Fscripts\u002Fmemory.py\"\n```\n\nFor example, if this SKILL.md is at `\u002FUsers\u002Falice\u002F.grok\u002Fworktrees\u002Forg\u002Frepo\u002F.grok\u002Fskills\u002Fimplement\u002FSKILL.md`, then `memory_helper_path` is `\u002FUsers\u002Falice\u002F.grok\u002Fworktrees\u002Forg\u002Frepo\u002F.grok\u002Fskills\u002Fimplement\u002Fscripts\u002Fmemory.py`. If this SKILL.md is at `\u002FUsers\u002Falice\u002F.grok\u002Fskills\u002Fimplement\u002FSKILL.md`, then `memory_helper_path` is `\u002FUsers\u002Falice\u002F.grok\u002Fskills\u002Fimplement\u002Fscripts\u002Fmemory.py`.\n\n**Substitute this absolute path directly** into every helper invocation throughout the run — do not rely on a bash environment variable surviving across `run_terminal_cmd` calls. All examples below show `${MEMORY_HELPER}` for readability; in practice, inline the absolute `memory_helper_path` value (or set `MEMORY_HELPER=\u003Cabsolute path>` at the top of each shell invocation that uses it).\n\n**Invoke the helper from the workspace root**, not from the helper's own directory. The helper itself is cwd-sensitive only for its workspace-id derivation: it runs `git config --get remote.origin.url` and `git rev-parse --git-common-dir` in the cwd, so cwd needs to be inside the workspace. `run_terminal_cmd` defaults to the workspace root, so this is the natural case — just don't `cd` to the helper's own directory before invoking it (especially relevant when the skill is loaded from `~\u002F.grok\u002Fskills\u002F`, where `cd`-ing to the helper would put cwd outside any workspace and the workspace-id would fall back to that home-dir cwd).\n\n### Read Path\n\n1. Run `python3 \"${MEMORY_HELPER}\" snapshot` via `run_terminal_cmd` and capture stdout. The helper prints structured JSON — no markdown re-parsing in the orchestrator. The shape is:\n\n   ```json\n   {\n     \"common_issues\": [\n       {\"category\": \"Error Handling\", \"description\": \"Missing null check\", \"count\": 5},\n       ...\n     ],\n     \"recent_runs\": [\n       {\"date\": \"2026-04-23\", \"description\": \"\\\"Add retry logic\\\"\", \"body_lines\": [\"- **Rounds**: 2\", \"- **Issues**: 7 total (1 bug, 1 suggestion, 5 nits)\", \"- **Key patterns**: Missing entries in error-type allowlists, incomplete configuration validation\", \"- **Specializations used**: general\"]},\n       ...\n     ],\n     \"exists\": true\n   }\n   ```\n\n   Parse the JSON and store the `common_issues` list as `existing_patterns_snapshot` (used in Step 6b). Store the boolean `exists` as `memory_existed_before` (used in the Final Report to decide between \"file created\" and \"file updated\" wording). The `recent_runs` array is included in the snapshot for debugging and forward compatibility (`memory.py snapshot | jq '.recent_runs'`); the orchestrator does not currently consume it. Each entry's `body_lines` are the verbatim markdown bullets (leading `- ` and `**...**` formatting preserved).\n2. If the helper exits non-zero (very rare — only happens if `$HOME` is unset and inferable home fails, or if cwd is unreadable), log a brief note, set `past_issues_briefing` to `\"\"`, `existing_patterns_snapshot` to `[]`, `memory_existed_before` to `false`, and proceed to Step 1. Note that a non-git workspace is **not** a failure mode — the helper falls back to a cwd-based id.\n3. If `existing_patterns_snapshot` is empty (or `exists` is `false`), set `past_issues_briefing` to `\"\"` and skip the briefing block below.\n\nDo NOT read or write `.grok\u002Fimplement-issues.md` directly during a \u002Fimplement run — that legacy path is per-worktree and is no longer used. The helper is the single source of truth for the path.\n\n**One-time migration from the legacy file:** if a user has a populated `.grok\u002Fimplement-issues.md` from a prior version, its `## Common Issues` and `## Recent Runs` sections use the **same markdown format** documented under [Memory File Format](#memory-file-format) below. To bring that history forward:\n\n1. **From the workspace root** (the same directory where `.grok\u002Fimplement-issues.md` lives — the workspace-id is derived from the cwd's git context, so running this from `~` or any unrelated directory will write to the wrong workspace's memory file), run `python3 \"${MEMORY_HELPER}\" update` once with an empty spec (`echo '{}' | python3 \"${MEMORY_HELPER}\" update`) to create the workspace-scoped file and its parent directory — `memory.py path` only computes the path, it does not create the directory.\n2. Open the printed file path in an editor.\n3. Hand-copy the bullets from the legacy file's `## Common Issues` section into the corresponding categories in the new file (preserving the `- description (seen N time(s))` syntax).\n4. The helper picks up the entries on the next `update`.\n\nThere is no automatic migration.\n\n### Parsing & Formatting\n\nIf `existing_patterns_snapshot` is non-empty:\n\n1. Filter to only entries with `count >= 2` (minimum threshold — one-off issues are excluded as they may not represent real patterns).\n2. Sort by `count` descending.\n3. Take the top 10 entries.\n4. Format them into the briefing block and store in `past_issues_briefing`:\n\n```\n## Past Issues to Avoid\nBased on previous implementation runs, the following patterns commonly cause issues:\n1. Missing null\u002Fundefined checks on function inputs (seen 5 times)\n2. Missing tests for error\u002Fedge case paths (seen 8 times)\n3. Functions exceeding 50 lines without decomposition (seen 4 times)\n4. Magic numbers without named constants (seen 6 times)\n\nPay special attention to these patterns in your work.\n```\n\n(Use `time` for `count == 1`, `times` otherwise. The helper renders both forms identically in the file, so the briefing should match.)\n\nIf there are no qualifying entries, set `past_issues_briefing` to `\"\"`.\n\n### Graceful Degradation\n\nIf the helper command fails for any reason, set `past_issues_briefing` to `\"\"`, `existing_patterns_snapshot` to `[]`, `memory_existed_before` to `false`, and proceed normally. Never fail the run due to memory retrieval issues — log a brief note and continue.\n\n## Step 1: Implement\n\n**Use `spawn_subagent` only** — do not implement code yourself.\n\nLaunch the implementer subagent by calling `spawn_subagent`. **Emit the `spawn_subagent` tool call before producing any user-visible \"implementer is launching\" message** — the launch announcement belongs in a *later* assistant message, after you have the tool result and a real `subagent_id` in hand. A content-only assistant message claiming the implementer has been launched, without a paired `spawn_subagent` call in the same response, is a hallucination and breaks the run (see Tool-Call Discipline above).\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `description`: `\"[implementer] \u003Cshort summary>\"` (the `[implementer]` prefix becomes the pager's row label)\n\n**Prepend the implementer persona instructions** (loaded during setup) to the prompt.\n\nPrompt:\n```\n\u003Cimplementer_persona_instructions>\n\n---\n\nImplement the following:\n\n\u003Cfull user description and all relevant context from the conversation>\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\nBe proactive about avoiding these patterns in your implementation.\n\u003Cend if>\n\nWhen you are done, write an implementation summary to: \u003Csummary_file>\nThe summary must include: what files were changed, what was added\u002Fmodified, and any design decisions made.\n```\n\nWait for the subagent to complete. If it fails, report the error to the user and stop.\n\nSave the returned `subagent_id` — you will resume this agent for all fix rounds.\n\nReport to the user: \"Implementation complete. Starting review...\" (for effort=1) or \"Implementation complete. Starting parallel review (N reviewers)...\" (for effort >= 2).\n\n### Prepare reviewer focus areas\n\nBefore launching reviewers, read `\u003Csummary_file>` yourself. Based on the implementation summary, identify 2-5 concrete areas the reviewer should pay extra attention to. Examples:\n\n- If the summary mentions new error handling paths: \"Verify error paths are tested and propagated correctly\"\n- If files were refactored: \"Check that callers of renamed\u002Fmoved functions were all updated\"\n- If concurrency primitives were added: \"Review lock ordering and potential deadlocks\"\n- If new public APIs were introduced: \"Check input validation at API boundaries\"\n\nStore these as `reviewer_focus_areas` (a short bulleted list). Include them in every reviewer prompt alongside `past_issues_briefing`.\n\n## Step 2: Review\n\n**Use `spawn_subagent` only** — do not review code yourself.\n\nThe review step differs based on effort level.\n\n### Effort = 1 (Single Reviewer)\n\nLaunch a single reviewer subagent by calling `spawn_subagent`.\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `description`: `\"[reviewer] Review implementation\"`\n\n**Prepend the reviewer persona instructions** (loaded during setup) to the prompt.\n\nPrompt:\n```\n\u003Creviewer_persona_instructions>\n\n---\n\nReview the changes made by the implementer.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\n\u003Cif reviewer_focus_areas is non-empty:>\n## Additional focus areas (from implementation summary)\n\u003Creviewer_focus_areas>\n\u003Cend if>\n\nWrite your review notes to: \u003Creview_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\nWait for the subagent to complete. If it fails, report the error to the user and stop.\n\nSave the returned `subagent_id` to `reviewer_configs[0].subagent_id`.\n\n### Effort >= 2 (Parallel Reviewers)\n\nLaunch all reviewers in parallel by calling `spawn_subagent` with `background: true` for each.\n\nFor each config in `reviewer_configs`, launch with the appropriate prompt for the specialization:\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `background`: `true`\n- `description`: `\"[\u003Ctag>] Review: \u003Cspecialization>\"` where `\u003Ctag>` matches the specialization: `[reviewer]` for `general`\u002F`general-2`\u002F`general-3`, `[tests]` for tests, `[security]` for security, `[plan]` for plan alignment. The bracketed tag drives the pager's subagent row label.\n\nIf `config.persona_to_inject` is non-null, prepend the corresponding persona instructions to the prompt. If null (Tests, Plan Alignment), use the prompt as-is — those specializations are prompt-only.\n\nUse the specialization-specific prompt (see Specialized Review Prompts below).\n\nAfter launching all reviewers, wait for all to complete via `get_command_or_subagent_output(task_id=..., block=true)` for each.\n\nSave each returned `subagent_id` to the corresponding `reviewer_configs` entry.\n\nIf any reviewer fails on initial launch:\n- If the **general reviewer** fails: report the error and stop entirely.\n- If a **specialist** fails: report a warning, remove that entry from `reviewer_configs`, and continue with remaining reviewers.\n\nAfter all reviewers complete, proceed to Step 3 (Merge & Check).\n\nReport to the user: \"All reviewers complete. Merging findings...\"\n\n## Specialized Review Prompts\n\nEach reviewer specialization gets a different prompt while sharing the same structured output format and severity taxonomy (`bug`, `suggestion`, `nit`).\n\nAll specialized review prompts include the `past_issues_briefing` block (if non-empty) to give reviewers awareness of historically common issues.\n\n### General Reviewer\n\nInject: `reviewer` persona instructions.\n\n```\n\u003Creviewer_persona_instructions>\n\n---\n\nReview the changes made by the implementer.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\n\u003Cif reviewer_focus_areas is non-empty:>\n## Additional focus areas (from implementation summary)\n\u003Creviewer_focus_areas>\n\u003Cend if>\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n### Tests Specialist\n\nInject: none (prompt-only subagent — no persona prepended).\n\n```\nYou are a thorough test engineer reviewing code changes for test coverage and quality.\n\nReview the changes made by the implementer, focusing specifically on test coverage and quality.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\nYour review should focus on:\n- Whether new\u002Fchanged code has adequate test coverage\n- Whether tests cover edge cases, error paths, and boundary conditions\n- Whether test assertions are specific enough (not just \"doesn't throw\")\n- Whether tests are maintainable and not overly coupled to implementation details\n- Whether integration tests exist for new endpoints or interfaces\n- Whether mocking is used appropriately (not over-mocking)\n\nDo NOT review for general code style, naming, or architecture — another reviewer handles that.\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n### Security Specialist\n\nInject: `security-auditor` persona instructions.\n\n```\n\u003Csecurity_auditor_persona_instructions>\n\n---\n\nReview the changes made by the implementer, focusing specifically on security.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\nYour review should focus on:\n- Input validation and sanitization\n- Authentication and authorization checks\n- Injection vulnerabilities (SQL, command, path traversal)\n- Sensitive data handling (secrets, PII, tokens in logs)\n- Cryptographic correctness\n- Rate limiting and abuse prevention\n- OWASP Top 10 patterns\n\nIMPORTANT: Use the following severity labels (not security-standard severities):\n- bug: for critical\u002Fhigh severity findings (exploitable vulnerabilities)\n- suggestion: for medium severity findings (defense-in-depth improvements)\n- nit: for low\u002Finformational findings (best-practice recommendations)\n\nOnly flag real, exploitable issues — not theoretical concerns.\nDo NOT review for general code style or test coverage — other reviewers handle that.\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n### Plan Alignment Specialist\n\nInject: none (prompt-only subagent — no persona prepended).\n\n```\nYou are a technical lead reviewing whether an implementation correctly follows its design plan.\n\nReview the changes made by the implementer, focusing on whether the implementation matches the plan\u002Fdesign.\n\nThe implementer's summary is at: \u003Csummary_file>\nRead it to understand what was changed.\n\nThe original plan\u002Fdesign is referenced in the conversation context.\nIf a design document, plan, or spec is referenced by file path in the conversation context, read it in full before starting your review.\n\n\u003Cif past_issues_briefing is non-empty, include the following block verbatim:>\n\u003Cpast_issues_briefing>\n\u003Cend if>\n\nYour review should focus on:\n- Whether all requirements from the plan are addressed\n- Whether the implementation deviates from the planned approach\n- Whether any scope creep has occurred (implementing things not in the plan)\n- Whether any planned items are missing\n- Whether the implementation order matches the plan's dependency graph\n- Whether interfaces match what was specified\n\nDo NOT review for code style, tests, or security — other reviewers handle that.\n\nWrite your review notes to: \u003Cindividual_review_file>\nUse the structured format with severity (bug\u002Fsuggestion\u002Fnit), file:line, description, suggestion, and status for each issue.\nEvery issue must have a Status field set to \"open\".\n```\n\n## Step 3: Merge & Check Exit Condition\n\nThis step differs based on effort level.\n\n### Effort = 1\n\nRead the `review_file` yourself. Count all issues with `Status: open` regardless of severity.\n\nIncrement `round_count`. For each open issue, add its severity to `total_issues_by_severity`. Also extract a one-line description of each open issue and append to `issue_patterns` (skip exact duplicates already in the list).\n\n### Effort >= 2 (Merge)\n\nAfter all reviewers complete:\n\n1. Read each reviewer's individual review file.\n2. Merge into the single `review_file` with source tags. Prefix each issue with a tag indicating its source: `[General]`, `[General-2]`, `[General-3]`, `[Tests]`, `[Security]`, `[Plan]`. For effort 1-3, only `[General]` is used for the single general reviewer.\n3. Consolidate obviously duplicated findings — use your judgment to identify issues that reference the same file, same line, and the same underlying problem. When in doubt, keep both issues — false duplicates are worse than redundant findings.\n4. Write the merged result to `review_file`.\n\nIncrement `round_count`. Count all open issues and add their severities to `total_issues_by_severity`. Also extract a one-line description of each open issue and append to `issue_patterns` (skip exact duplicates already in the list).\n\n**Merge format:**\n\n```markdown\n## Review Issues\n\n### Issue 1 [General] — Severity: bug\n- **File**: src\u002Fhandler.rs:45\n- **Description**: Missing null check on user input\n- **Suggestion**: Add validation before processing\n- **Status**: open\n\n### Issue 2 [Security] — Severity: bug\n- **File**: src\u002Fauth.rs:102\n- **Description**: JWT token not validated for expiration\n- **Suggestion**: Add exp claim validation\n- **Status**: open\n\n### Issue 3 [Tests] — Severity: suggestion\n- **File**: tests\u002Fhandler_test.rs\n- **Description**: No test for error path when user input is null\n- **Suggestion**: Add test case for None input\n- **Status**: open\n```\n\nFor effort >= 4 with multiple general reviewers, the source tags distinguish them: `[General]`, `[General-2]`, `[General-3]`. If two general reviewers flag the same issue, consolidate as usual.\n\n### Stalemate Detection\n\nCompare the current review_file against `previous_review_snapshot` from the prior round. If any issue (matched by file reference and description, and by source tag if present) was marked `Status: wontfix` by the implementer in the previous round and has been re-opened (`Status: open`) by a reviewer in the current round, the implementer and reviewer have reached a disagreement they cannot resolve on their own.\n\nIf a stalemate is detected, proceed to Step 3a (Escalate to User).\n\nAfter completing Step 3 checks, update `previous_review_snapshot` with the current review_file contents.\n\n### Decision Logic\n\nReport the review results to the user using the appropriate message format from the In-Progress Reporting section (effort=1 vs effort>=2 variants for both the 0-issue and N-issue cases).\n\n- **0 open issues**: Done. Proceed to Step 6 (Memory Flush), then Final Report.\n- **Stalemate detected**: Proceed to Step 3a (Escalate to User).\n- **Any open issues (>0)**: Proceed to Step 4.\n\n### Step 3a: Escalate to User\n\nFor any stalemate disputes, ask the user for a decision (use the appropriate ask\u002Fquestion tool if available):\n- Frame the question clearly, including both the reviewer's position and the implementer's position\n- Provide the competing options as selectable choices\n- Include context from the implementation so the user can make an informed decision\n\nAfter the user responds, resume the implementer (Step 4) with the user's decisions included in the prompt. Tell the implementer to treat user decisions as final — incorporate them without further debate and set the corresponding issues to `Status: fixed`.\n\n## Step 4: Fix (resume implementer)\n\n**Use `spawn_subagent` only** — do not apply fixes yourself.\n\nResume the original implementer to address **all** review findings.\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `resume_from`: `\u003Cimplementer_subagent_id>`\n- `description`: `\"[implementer] Fix review issues\"`\n\nPrompt:\n```\nThe reviewer found issues. The review_file is at: \u003Creview_file>\n\nRead the review_file. Address ALL issues with Status: open — including nits, suggestions, and any style or hint-level feedback. Nothing is too small to fix.\n\nFor each issue, implement the fix, then update the review_file:\n- Change Status: open → Status: fixed\n- Add a Response field explaining what you changed\n\nYou are encouraged to push back on feedback that doesn't make sense, is contradictory, or would make the implementation worse. If you disagree with an issue:\n- Set Status: wontfix\n- Write a clear, technical explanation of why the reviewer's suggestion is wrong or counterproductive\n- Do NOT comply with feedback just to make a reviewer happy — defend good implementation decisions\n\nAppend an updated Implementation Summary at the bottom of the review_file.\n```\n\nWait for completion. If it fails, report the error to the user and stop.\n\nUpdate the saved implementer `subagent_id` with the new one returned.\n\nReport to the user: \"Fixes applied. Running re-review (round N)...\" (for effort=1) or \"Fixes applied. Running parallel re-review (round N)...\" (for effort >= 2), where N is the current `round_count` + 1.\n\n## Step 5: Re-review\n\n**Use `spawn_subagent` only** — do not re-review yourself.\n\nThe re-review step differs based on effort level.\n\n### Effort = 1 (Single Reviewer Re-review)\n\nResume the original reviewer to re-review the fixes.\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `resume_from`: `\u003Creviewer_subagent_id>`\n- `description`: `\"[reviewer] Re-review fixes\"`\n\nPrompt:\n```\nThe implementer addressed the review issues. Re-review all changes.\n\nThe updated review_file with implementer responses is at: \u003Creview_file>\nThe implementer's summary is at: \u003Csummary_file>\n\nRead both files. Review the code again thoroughly.\n\nRewrite the review_file with your new findings:\n- If a previous issue was properly fixed, do not re-list it.\n- If a fix introduced a new problem, list it as a new issue with Status: open.\n- If any issue was not properly addressed, re-list it with Status: open.\n- Use the same structured format (severity: bug\u002Fsuggestion\u002Fnit, file:line, description, suggestion, status).\n```\n\nWait for completion. If it fails, report the error to the user and stop.\n\nUpdate the saved reviewer `subagent_id` with the new one returned.\n\nIf `resume_from` fails (subagent expired), launch a fresh reviewer, prepending the `reviewer` persona instructions to the prompt. Log a warning.\n\n### Effort >= 2 (Parallel Re-review)\n\nResume all reviewers in parallel. Each reviewer is resumed with `resume_from` (using the `subagent_id` from `reviewer_configs`) and `background: true`. The persona instructions are already in each reviewer's transcript from the initial launch, so no re-injection is needed on resume.\n\nFor each config in `reviewer_configs`:\n\n`spawn_subagent` parameters:\n- `subagent_type`: `\"general-purpose\"`\n- `resume_from`: `config.subagent_id`\n- `background`: `true`\n- `description`: `\"[\u003Ctag>] Re-review: \u003Cspecialization>\"` — use the same bracketed tag as the initial launch (`[reviewer]` for `general`\u002F`general-2`\u002F`general-3`, `[tests]`, `[security]`, `[plan]`) so the pager row label stays consistent across rounds.\n\nPrompt (same structure as initial review, but with re-review instructions):\n```\nThe implementer addressed the review issues. Re-review all changes.\n\nThe updated merged review_file with implementer responses is at: \u003Creview_file>\nThe implementer's summary is at: \u003Csummary_file>\n\nRead both files. Review the code again thoroughly.\n\nRewrite your review file at: \u003Cindividual_review_file>\n- If a previous issue was properly fixed, do not re-list it.\n- If a fix introduced a new problem, list it as a new issue with Status: open.\n- If any issue was not properly addressed, re-list it with Status: open.\n- Use the same structured format (severity: bug\u002Fsuggestion\u002Fnit, file:line, description, suggestion, status).\n- Stay within the same review scope as your initial review.\n```\n\nAfter launching all re-reviewers, wait for all to complete via `get_command_or_subagent_output(task_id=..., block=true)` for each.\n\nUpdate each `subagent_id` in `reviewer_configs` with the new ones returned.\n\nIf a reviewer fails during re-review:\n- Report a warning and exclude that reviewer's findings from the merge.\n- Continue with remaining reviewers.\n\nIf `resume_from` fails for a reviewer (subagent expired), launch a fresh reviewer for that specialization, prepending the persona instructions from `config.persona_to_inject` (if non-null) to the prompt. Log a warning.\n\n**Regardless of effort level, go back to Step 3.** Repeat until 0 open issues.\n\n## Exit Condition\n\nThe **only** exit condition is **all reviewers** reporting **0 issues** of any severity in the same round. There is no iteration cap. Every issue — including nits, suggestions, and minor improvements — must be addressed before the loop terminates.\n\nThere is no per-reviewer exit — if the security reviewer has 0 issues but the general reviewer has 2, the implementer fixes those 2 and all reviewers re-review in the next round.\n\n## Step 6: Memory Flush\n\nAfter the loop terminates with 0 open issues, update the workspace memory file with patterns from this run. The orchestrator performs this directly using its own tools — no subagent is needed for this step.\n\nThe write goes through `python3 \"${MEMORY_HELPER}\" update` so that:\n- The path resolves to the **shared workspace-scoped file** (`$HOME\u002F.grok\u002Fimplement-memory\u002F\u003Cworkspace-id>.md`), not a per-worktree file.\n- An exclusive `fcntl.flock` (Python stdlib; no `flock(1)` shell binary required) is held during the read-merge-write, so a \u002Fimplement run in another worktree of the same repo can't clobber this update.\n- Dedup against existing entries is enforced **deterministically** (case- and whitespace-insensitive match within each category).\n- Compaction is enforced: each category is capped at 25 entries (lowest-count entries dropped first); Recent Runs is capped at 20 entries (oldest dropped).\n- Strict input validation: malformed types (e.g., a non-list `key_patterns`, a string where a dict is required, a calendar-invalid `date`) fail fast with exit code 4 and a clear error message rather than silently corrupting the file.\n\n### Step 6a: Collect & Categorize This Run's Patterns\n\n1. Use the `issue_patterns` list accumulated during Step 3 across all rounds. This list contains a one-line description of every distinct issue that was open at any review checkpoint during the run.\n2. **Generalize each pattern.** The memory file exists to help *future* runs on *different* tasks — patterns that reference this task's specific code, variable names, or domain objects are useless noise. Strip implementation-specific details (file names, variable names, type names, function names, domain-specific terms) and rewrite each pattern as a reusable principle that applies across different codebases and tasks:\n   - Bad: \"Missing error type `RetryableError` in retry handler list\" → Good: \"Missing entries in error-type or configuration allowlists\"\n   - Bad: \"JWT token not validated for expiration\" → Good: \"Missing expiration\u002FTTL validation on tokens or credentials\"\n   - Bad: \"`calculateTotal` function exceeds 80 lines\" → Good: \"Functions exceeding reasonable length without decomposition\"\n   - Bad: \"No test for `handleUserAuth` error path\" → Good: \"Missing tests for error\u002Fedge case paths\"\n   - Bad: \"Missing null check on `userId` parameter\" → Good: \"Missing null\u002Fundefined checks on function inputs\"\n   If a pattern is *already* general (e.g., \"Missing null checks on function inputs\"), keep it as-is. If multiple task-specific patterns generalize to the same reusable principle, collapse them into one entry.\n3. Categorize each generalized pattern into one of: Error Handling, Testing, Security, Code Quality, Naming, Documentation, Performance, or another short category name as appropriate. Reuse existing category names from `existing_patterns_snapshot` (captured in Step 0) whenever the pattern fits — do not invent a near-duplicate category like \"Error-Handling\" or \"Tests\" when one already exists.\n4. For each pattern, write a concise one-line description. Keep descriptions on a single line; the helper collapses any embedded newlines but it's cleaner to write them without.\n\n### Step 6b: Harmonize Phrasing Against Existing Entries\n\nBefore handing generalized patterns to the helper, dedup at the *phrasing* level using `existing_patterns_snapshot`:\n\n1. For each of this run's patterns, scan `existing_patterns_snapshot` for an entry in the same (or semantically equivalent) category whose description means the same thing — even if worded differently. Examples of matches:\n   - \"missing null check on input\" ≈ \"No null validation for function parameters\"\n   - \"functions over 50 lines\" ≈ \"Long functions without decomposition\"\n   - \"no tests for error path\" ≈ \"Missing tests for failure cases\"\n2. **If a semantic match exists:** replace this run's description with the **exact existing description string** (so the helper's normalised match will collapse them onto the same entry).\n3. **If no match exists:** keep your concise description as-is. It will be added as a new entry.\n4. **Within this run's own list:** also dedup by phrasing — if you have two patterns that mean the same thing, collapse them to a single entry (the helper would otherwise count them as two distinct hits, which is fine but slightly inflates new-pattern stats).\n\nThe helper will also do a final case\u002Fwhitespace\u002Fpunctuation normalisation, but it cannot infer semantic equivalence — that's the orchestrator's job here. Skipping this step leads to the file accumulating near-duplicates over time.\n\n### Step 6c: Build the Update Spec\n\nConstruct a JSON object with this shape (omit `run` only if you want to record patterns without logging a run; in normal flow, always include both):\n\n```json\n{\n  \"patterns\": [\n    {\"category\": \"Error Handling\", \"description\": \"Missing null\u002Fundefined checks on function inputs\"},\n    {\"category\": \"Testing\", \"description\": \"Missing tests for error\u002Fedge case paths\"}\n  ],\n  \"run\": {\n    \"date\": \"2026-04-23\",\n    \"description\": \"Add retry logic to blackbox client\",\n    \"rounds\": 2,\n    \"issues_by_severity\": {\"bug\": 1, \"suggestion\": 1, \"nit\": 5},\n    \"key_patterns\": [\"Missing entries in error-type allowlists\", \"Incomplete configuration validation\"],\n    \"specializations\": [\"general\"]\n  }\n}\n```\n\nField notes (the helper rejects wrong-typed input with exit code 4 and a clear error message identifying the offending field; empty-or-null input falls back to defaults or is silently skipped per the per-field rules below):\n- `patterns[]`: each entry must be an object. `category` must be a string (defaults to `\"Other\"` if empty\u002Fnull). `description` must be a string; **null and omitted are treated identically** (both result in a silent skip with no error).\n- `patterns[].description`: one-line, harmonised in Step 6b. Newlines\u002Ftabs are collapsed to single spaces; internal multi-space runs are preserved.\n- `run` must be an object (not a list, not a string). Send `null` or omit it entirely to skip the Recent Runs entry.\n- `run.date`: a string in `YYYY-MM-DD` format. Calendar-invalid dates like `2026-13-99` are rejected. Pass `null`, empty string, or whitespace-only string and the helper fills in today's UTC date.\n- `run.description`: the user's implementation request, trimmed to a short label. Must be a string (or `null`\u002Fomitted to fall back to `\"(no description)\"`). The helper strips ALL double-quote characters from the description and then wraps it in exactly one outer pair, so internal quotes never produce broken nested-quote markup. (`Add retry \"logic\" to client` becomes `\"Add retry logic to client\"`.) If you need to preserve quotes verbatim, escape them yourself before submission — the helper assumes the description is a free-form label, not a structured string.\n- `run.rounds`: `round_count` as an integer. Booleans, floats, strings, and lists are rejected. Zero is accepted as-is (structurally unreachable in the actual \u002Fimplement loop, but not enforced).\n- `run.issues_by_severity`: derived from `total_issues_by_severity`. Must be an object with string keys and integer values (or `null`\u002Fomitted to skip the `**Issues**` body line entirely). Zero-count severities are silently dropped from the rendered summary; if all severities are zero (or the object is empty) the helper omits the `**Issues**` body line entirely.\n- `run.key_patterns`: must be a list of strings (or `null`\u002Fomitted to skip the `**Key patterns**` body line). Pick the 2-3 most-significant patterns from this run. **Apply the same generalization rules as Step 6a** — strip task-specific names and rewrite as reusable principles. Two implementable options, pick consistently across runs:\n  - **Option A (recommended): severity-ranked.** Re-read the latest merged review_file (still on disk at this point in the loop). Each issue has a `Severity:` tag. Take 1-2 of the highest-severity issues first (bugs > suggestions > nits), then top up with the next-highest severity until you have 3 entries. This sees only **final-round survivors** (issues that the implementer actually had to address) which is the natural \"most-significant\" reading.\n  - **Option B (lower-effort): recency-ranked.** Take the **last 2-3 entries** of `issue_patterns` (the list grows by appending per round in Step 3, so the tail is the most-recent round's issues). This sees **cross-round accumulation** including issues that were introduced and fixed mid-loop. Use this only if re-reading the review_file is impractical — the resulting `key_patterns` will sometimes include issues that ended up wontfix or were ephemeral.\n  - **Pick one option and stick with it for the run.** The two options return semantically different sets, so mixing them across runs makes the Recent Runs log inconsistent.\n- `run.specializations`: must be a list of strings (or `null`\u002Fomitted to skip the `**Specializations used**` body line). Strip the `-N` suffix from `general-2`\u002F`general-3` first so the list is the set of distinct specialization classes (e.g., `[\"general\", \"security\"]`, not `[\"general\", \"general-2\", \"security\"]`); deduplicate.\n\n### Step 6d: Invoke the Helper\n\nUse the `write` tool to create `${scratch_dir}\u002Fgrok-mem-${IMPL_ID}.json` with the JSON spec above (using a temp file avoids quoting issues that heredocs introduce), then invoke the helper via `run_terminal_cmd`:\n\n```bash\npython3 \"${MEMORY_HELPER}\" update \u003C ${scratch_dir}\u002Fgrok-mem-${IMPL_ID}.json\n```\n\nThe helper acquires the lock, parses the existing file, merges, compacts, writes atomically, and prints a JSON stats summary on stdout (pretty-printed with `indent=2`):\n\n```json\n{\n  \"file\": \"\u002FUsers\u002F...\u002Fimplement-memory\u002Fproj-d5016f47e5cb.md\",\n  \"existed_before\": false,\n  \"stats\": {\n    \"new_patterns\": 2,\n    \"merged_patterns\": 5,\n    \"categories_touched\": [\"Error Handling\", \"Testing\"],\n    \"categories_capped\": {},\n    \"recent_runs_dropped\": 0\n  },\n  \"total_categories\": 4,\n  \"total_patterns\": 17,\n  \"total_recent_runs\": 12\n}\n```\n\nKey fields:\n- `existed_before`: `true` if the file existed before this update, `false` if the helper just created it. Use this for the report wording.\n- `stats.categories_capped`: dict of `{category: dropped_count}` for any category that exceeded `MAX_PATTERNS_PER_CATEGORY` and had its lowest-count entries dropped. Empty dict in the typical case.\n\nUse these stats to report to the user:\n> \"Memory updated: 2 new patterns, 5 merged into existing entries (file at \u003Cfile>).\"\n\nOr if `existed_before` is `false`:\n> \"Memory file created at \u003Cfile> with N patterns.\"\n\n### Memory File Format\n\nThe helper writes a markdown file with this structure:\n\n\u003C!-- mirror-of: scripts\u002Fmemory.py DEFAULT_HEADER -->\n\u003C!-- The 5-line block immediately following this comment must match -->\n\u003C!-- '\\n'.join(memory.DEFAULT_HEADER) verbatim. The drift-check unit -->\n\u003C!-- test TestDocsConsistency.test_skill_md_default_header_matches -->\n\u003C!-- asserts this on every test run. -->\n```markdown\n# Implementation Review Patterns\n\n> This file is maintained by the \u002Fimplement skill.\n> It records common issues found during implementation reviews to help avoid them in future runs.\n> Shared across all working directories that resolve to the same workspace id.\n\n## Common Issues\n\n### Error Handling\n- Missing null\u002Fundefined checks on function inputs (seen 5 times)\n- Not handling async errors in promise chains (seen 3 times)\n- Missing error logging before re-throwing (seen 2 times)\n\n### Testing\n- Missing tests for error\u002Fedge case paths (seen 8 times)\n- Tests that don't assert on error messages, only error types (seen 3 times)\n- No integration tests for new API endpoints (seen 2 times)\n\n### Security\n- User input not validated before database queries (seen 2 times)\n- Missing rate limiting on new endpoints (seen 1 time)\n\n### Code Quality\n- Functions exceeding 50 lines without decomposition (seen 4 times)\n- Magic numbers without named constants (seen 6 times)\n- Inconsistent naming conventions within new code (seen 3 times)\n\n## Recent Runs\n\n### 2026-04-23 — \"Add retry logic to blackbox client\"\n- **Rounds**: 2\n- **Issues**: 7 total (1 bug, 1 suggestion, 5 nits)\n- **Key patterns**: Missing entries in error-type allowlists, incomplete configuration validation\n- **Specializations used**: general\n\n### 2026-04-22 — \"Implement user auth endpoints\"\n- **Rounds**: 3\n- **Issues**: 12 total (3 bugs, 4 suggestions, 5 nits)\n- **Key patterns**: Missing expiration\u002FTTL validation on tokens, missing rate limiting on new endpoints, missing tests for error\u002Fedge case paths\n- **Specializations used**: general, security\n```\n\nNotes on the format:\n- Within each category, entries are sorted by count desc then description asc (case-insensitive).\n- `seen 1 time` (singular) and `seen N times` (plural) are both produced and parsed.\n- `—` (em-dash), `–` (en-dash), and `-` (ASCII hyphen) are all accepted as separators in run headers.\n- The helper preserves any custom lines you add to the header (anything before `## Common Issues`) on round-trip. Custom freeform paragraphs **inside** a category in `## Common Issues` are not preserved — only `### Category` headers and well-formed `- desc (seen N time(s))` bullets survive. **Caveat:** anything written to the file before the first `## Common Issues` heading becomes part of the preserved header indefinitely, including unintentional garbage from a hand-edit. To reset a corrupted file, delete it and the helper will recreate it with the default header on the next `update`. If you delete the header itself (leaving the file starting at `## Common Issues`), the helper re-injects the default header on the next render — not byte-stable, but the data survives.\n- Both the memory file and its sibling `.lock` file are written and then chmodded to mode `0o600` (owner read\u002Fwrite only, best-effort — if a cross-user race makes the chmod fail, the file's umask-default mode is preserved). The memory file may contain security-review patterns and `key_patterns` drawn from non-public source review, so we deliberately keep it owner-only on shared hosts (the workspace id is a deterministic SHA-256 of the canonical remote URL, so an unprivileged account that knows or guesses the public-repo URL could otherwise read the file directly). In the typical single-user case both files end up at `0o600` regardless of the process umask. The lock file's content is irrelevant; it exists purely as an `flock` target.\n\n### Graceful Degradation\n\nIf the helper exits non-zero (lock contention timeout, malformed spec, disk full, etc.), log a warning with the helper's stderr and skip the memory update. The implementation is already complete and reviewed at this point — never fail the run due to memory flush issues. Also remove the temp JSON spec file in the cleanup step regardless.\n\nExit codes:\n- `0`: success.\n- `1`: unexpected I\u002FO error (disk full mid-write, permission flips during execution, FS races). The stderr message says `memory.py: I\u002FO error: ...`.\n- `2`: workspace id could not be determined (cwd unreadable and `$HOME` unset — very rare).\n- `3`: lock could not be acquired within 30 seconds (another concurrent \u002Fimplement run is monopolising the file; usually retrying once works).\n- `4`: stdin JSON is missing, malformed, or fails type validation. The stderr message identifies the offending field. Surface it verbatim in the report so the user can see what was wrong with the spec.\n\n## Cleanup\n\nAfter Step 6 (Memory Flush) and the Final Report, clean up the temporary artifact files:\n\n```bash\nrm -f ${scratch_dir}\u002Fgrok-impl-summary-${IMPL_ID}.md ${scratch_dir}\u002Fgrok-review-${IMPL_ID}.md ${scratch_dir}\u002Fgrok-review-${IMPL_ID}-*.md ${scratch_dir}\u002Fgrok-mem-${IMPL_ID}.json\n```\n\nNote: the workspace memory file under `$HOME\u002F.grok\u002Fimplement-memory\u002F` is NOT cleaned up — it persists across runs as the shared memory file for this workspace.\n\n## Final Report\n\nWhen the loop terminates (0 issues), read the summary_file and review_file one last time (before cleanup), then present a final report to the user:\n\n1. **Summary of what was implemented** — from the summary_file: which files were changed, what was added\u002Fmodified, key design decisions.\n2. **Effort level** — the effort parameter used and which specializations were active (e.g., \"Effort 2: general + security\").\n3. **Review rounds** — how many review→fix iterations it took to reach 0 issues (the value of `round_count`).\n4. **Total issues fixed** — the cumulative count from `total_issues_by_severity`, broken down by severity (bugs, suggestions, nits).\n5. **Issues by reviewer** — breakdown of how many issues each reviewer found across all rounds (by specialization tag).\n6. **Files changed** — list the files that were created or modified.\n7. **Anything notable** — if the implementer made design decisions, disagreed with a reviewer suggestion (wontfix), or encountered anything unexpected, call it out.\n8. **Memory update** — what patterns were written or updated in the workspace memory file (path returned by the helper as the `file` field). Use the `existed_before` flag from the helper's stats output to choose between \"file created\" (false) and \"file updated\" (true) wording.\n\n## In-Progress Reporting\n\nGive the user a brief status update after each phase:\n\n- After specialization selection (effort >= 2): \"Using effort level N: general reviewer + \u003Cspecialist(s)> (\u003Creason>).\"\n- After implement (effort=1): \"Implementation complete. Starting review...\"\n- After implement (effort >= 2): \"Implementation complete. Starting parallel review (N reviewers)...\"\n- After all reviewers complete (effort >= 2): \"All reviewers complete. Merging findings...\"\n- After review (0 issues, effort=1): \"Review passed with 0 issues. Flushing to memory...\" (then run Step 6, then print the Final Report)\n- After review (0 issues, effort >= 2): \"All reviews passed with 0 issues. Flushing to memory...\" (then run Step 6, then print the Final Report)\n- After review (N issues, effort=1): \"Reviewer found N issues (X bugs, Y suggestions, Z nits). Resuming implementer to fix...\"\n- After review (N issues, effort >= 2): \"Merged review: N issues (X bugs [1 General, 1 Security], Y suggestions [General], Z nits [Tests]). Resuming implementer to fix...\" — include per-source-tag breakdown within each severity, showing how many issues came from each reviewer.\n- After fix (effort=1): \"Fixes applied. Running re-review (round N)...\" (where N = `round_count` + 1, i.e., the upcoming round number)\n- After fix (effort >= 2): \"Fixes applied. Running parallel re-review (round N)...\" (where N = `round_count` + 1)\n- After stalemate escalation: \"Stalemate detected on N issue(s). Escalating to user...\"\n- After memory flush: \"Memory updated with N patterns from this run.\" (or \"Memory file created with N patterns.\" for first run)\n\n## Rules\n\n- **Tool-call discipline** — every \"launching\", \"spawning\", \"starting\", or \"running\" statement in your prose must be backed by a `spawn_subagent` tool call in the same assistant response. Never end a turn with a content-only message that claims a subagent is being launched. See [Tool-Call Discipline (Anti-Hallucination)](#tool-call-discipline-anti-hallucination) for the full rule set.\n- **No permission-asking on launch** — the launch announcement is informational, not interactive. Do not append \"Want me to check in every 30 min, or run silently?\" or similar cadence-negotiation questions to launch messages. Pick a default and proceed.\n- **Inject personas into prompts** — prepend `implementer` persona instructions for the implementer, `reviewer` for general reviewer, `security-auditor` for security specialist. Do NOT pass a `persona` parameter to `spawn_subagent`. For Tests and Plan Alignment specialists, do not prepend any persona — they are prompt-only subagents. On `resume_from` follow-ups, the persona is already in the transcript from the initial launch.\n- **Prefix `description` with a bracketed role tag** — `[implementer]`, `[reviewer]`, `[security]`, `[tests]`, or `[plan]`. The pager's subagent label renderer parses the first `[tag]` of the description and uses it as the row label (the bracketed prefix is stripped from the displayed description). Without this, every row falls through to the generic \"General\" label because `subagent_type` is `general-purpose` and no persona\u002Frole is plumbed through the spawn args. Keep the tag on `resume_from` follow-ups too so the label stays stable across rounds.\n- **resume_from on follow-ups** — never launch a fresh subagent for fix or re-review rounds. Always resume the previous one so it retains its full working memory. Exception: if `resume_from` fails (subagent expired), launch a fresh one and log a warning.\n- **Save every subagent_id** returned by `spawn_subagent` — these are needed for `resume_from` on subsequent rounds. Store them in `reviewer_configs` for reviewers.\n- **Read the review_file yourself** after each review to count open issues and decide whether to continue the loop.\n- **Don't modify the implementation yourself** — all code changes go through the implementer persona subagent.\n- **Explicitly tell subagents to write their output files** — include the file path and what to write in every prompt.\n- **Thread the same file paths** across all rounds — never generate new paths between iterations.\n- **No iteration cap** — the loop runs until 0 issues. Do not add a max rounds limit.\n- **If the user provides additional instructions** (like \"run tests after\", \"use this pattern\", \"don't touch file X\"), include those constraints in the implementer prompt.\n- **Error handling** — if a subagent fails or cannot be resumed, report the error to the user and stop. Do not silently continue with missing results. Exception: specialist reviewer failures are non-fatal (warn and continue with remaining reviewers); only general reviewer failure is fatal.\n- **Effort=1 is structurally simple** — for effort=1, the single general-purpose reviewer writes directly to `review_file`. No individual review files, no merge step. This is the current behavior with the added wontfix\u002Fstalemate mechanism.\n- **Effort>=2 uses individual files + merge** — each reviewer writes to its own file to avoid write conflicts during parallel execution. The orchestrator merges them into `review_file` after all complete.\n- **Severity normalization** — all reviewers must use `bug`, `suggestion`, `nit` as severity labels. The security specialist prompt explicitly maps native security severities to this taxonomy.\n- **Implementer can push back** — the implementer is explicitly allowed (and encouraged) to set `Status: wontfix` with a technical justification. If a reviewer re-opens a wontfix'd issue, it's a stalemate that gets escalated to the user.\n- **Escalate, don't spin** — if the implementer and a reviewer cannot reach consensus on an issue after two rounds, escalate to the user by asking them directly (use the appropriate ask\u002Fquestion tool if available). Never let the loop spin on a disagreement.\n- **User decisions are final** — once the user resolves a disputed issue, the implementer must incorporate it without further debate.\n- **Memory is best-effort.** The past-issues briefing and memory flush are additive features. If the `memory.py` helper fails (lock contention timeout, malformed spec, disk full, etc.) proceed without it. Never fail a run due to memory issues. A non-git workspace is **not** a failure mode — the helper falls back to a cwd-based id.\n- **Always go through the `memory.py` helper.** The file lives at `$HOME\u002F.grok\u002Fimplement-memory\u002F\u003Cworkspace-id>.md`, resolved by `python3 \"${MEMORY_HELPER}\" path`. The helper itself lives at `\u003Cdirname of this SKILL.md>\u002Fscripts\u002Fmemory.py` — derive `MEMORY_HELPER` from the SKILL.md path the system context gave you (it works whether the skill is loaded from a workspace, from `~\u002F.grok\u002Fskills\u002F`, or from a bundled location), **never** from `$(pwd)`. The workspace id is derived from a canonicalised `git config remote.origin.url` (falling back to the absolute `--git-common-dir` path, then to the absolute cwd), so all worktrees and SSH\u002FHTTPS clones of the same upstream repo share one file. Never reference the legacy `.grok\u002Fimplement-issues.md` path — it is per-worktree and useless. Never read or write the file directly — the helper is the single source of truth.\n- **Concurrency-safe writes are the helper's job, not yours.** The helper holds an exclusive `fcntl.flock` (Python stdlib, not the `flock(1)` shell tool) on a sibling `.lock` file during the read-merge-write and commits via temp-file + rename, so two \u002Fimplement runs in different worktrees can update the file simultaneously without losing writes. Do **not** implement your own locking around the helper.\n- **Dedup is a two-layer responsibility.** The orchestrator harmonises this run's pattern phrasings against `existing_patterns_snapshot` (semantic dedup, Step 6b); the helper then performs case\u002Fwhitespace\u002Fpunctuation normalisation as a safety net. Skipping the orchestrator step leads to near-duplicate entries the helper cannot collapse.\n- **Compaction is automatic.** The helper caps each category at 25 entries (lowest-count entries dropped) and Recent Runs at 20 entries (oldest dropped). The orchestrator does not need to enforce caps.\n- **Use the `snapshot` subcommand for reads, not `read`.** `python3 \"${MEMORY_HELPER}\" snapshot` returns structured JSON (`common_issues`, `recent_runs`, `exists`) so the orchestrator never has to parse markdown. The `read` subcommand is preserved for human inspection only.\n- **Briefing is injected, not enforced** — the past-issues briefing is informational context. It tells the implementer and reviewers what patterns to watch for, but does not mandate specific behaviors or block the run if patterns are found.\n",{"name":5,"description":7,"when-to-use":24,"argument-hint":25,"disable-model-invocation":26},"Use when asked to \"implement\", \"build\", \"add feature\", \"fix bug\", or \"\u002Fimplement\".","[--effort N] \u003Cdescription of what to implement>",true,"main","d9535210da9af28aa76bca80de80355197e1b6d6","skills\u002Fimplement","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog","https:\u002F\u002Fgithub.com\u002Fzfifteen","I like to measure things.","2026-07-19 23:41:54",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":26},[36,39,42],{"tool":37,"command":38},"npx","npx skills add zfifteen\u002Fskills-catalog --skill implement",{"tool":40,"command":41},"bunx","bunx skills add zfifteen\u002Fskills-catalog --skill implement",{"tool":43,"command":44},"pnpm","pnpm dlx skills add zfifteen\u002Fskills-catalog --skill implement","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fimplement\u002FSKILL.md",[47,53],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"scripts\u002Fmemory.py","SCRIPT","脚本",39437,"https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fimplement\u002Fscripts\u002Fmemory.py",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"tests\u002Ftest_memory.py",36785,"https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fimplement\u002Ftests\u002Ftest_memory.py",[58,65,72,79,88,95],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M79GXQ2PWPT2E4CJYHXVJ0YE","Zotero","Use Zotero Desktop from Codex to enable\u002Fprobe the local API, search a local Zotero library, list items\u002Fcollections\u002Ftags, export BibTeX, insert citation keys into LaTeX or Markdown drafts, read indexed full text when requested, and import BibTeX\u002FRIS records into Zotero through the connector server. Use when the user mentions Zotero, citations, references.bib, BibTeX export, local Zotero API, localhost:23119, or adding citations from a Zotero library.","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fzotero\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M79GXN85NETKBE06865CWK6Z","zoom-apps-sdk","Use when using Apps SDK.","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M79GXCYD7FGYS932J9N9RFFY","youtube","Obtain accurate, timestamped YouTube video transcripts (preferring manual captions over auto-generated) as the primary deliverable, then derive summaries, key claims, or notes from that transcript.  Use when the user provides a YouTube URL (or video ID) and wants the transcript, a faithful summary, key claims with attribution, timestamped notes, or \"what does this video actually say\".  The skill is transcript-first: never substitute metadata, title, description, or search snippets for the spoken content.  Triggers: \"youtube transcript\", \"get the transcript of this video\", \"summarize this youtube video\", \"what did they say in https:\u002F\u002Fyoutube.com\u002F...\", \"key claims from this talk\".","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":83,"licenseFileUrl":84,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M79GX8EXHHYM566BKR7MS778","yeet","Publish local changes to GitHub by confirming scope, committing intentionally, pushing the branch, and opening a draft PR through the GitHub app from this plugin, with `gh` used only as a fallback where connector coverage is insufficient.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M79GX2HFJPX84NMRE5VBTYX9","x-post-creator","Create X-ready post threads and co-located story packages from the active conversation or referenced project material. Use when the user says turn this into an X-post, \u002Fx-post, make this into an X thread, or wants plain-language social posts with supporting images saved to docs\u002Fx-posts\u002F[story-name]\u002F.","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fx-post-creator\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M79GWXQT4HBT6QME6QSBZJFA","x-api","Search, read, and write X posts through the local X API MCP server (the same backend used by the Codex x-api skill). Use for searching X\u002Fx.com, reading threads and replies, creating lists, staging\u002Fpublishing posts for @alltheputs, finding high-visibility reply targets for research outreach, ingesting public context, or any request that mentions \u002Fx-api or \"search X\".","https:\u002F\u002Fgithub.com\u002Fzfifteen\u002Fskills-catalog\u002Fblob\u002Fmain\u002Fskills\u002Fx-api\u002FSKILL.md",[],[]]