[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6991VBZQ4NZ1SNQPVNNZFFA":3,"skill-same:01M6991VBZQ4NZ1SNQPVNNZFFA":72},{"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":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":47,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M6991VBZQ4NZ1SNQPVNNZFFA","mantis-patch",null,"Generates minimal security fixes using transactional isolation (shadow directories or file backups), applies patches, and verifies them. Use when security findings are successfully reproduced and need patches applied and verified. Don't use for initial vulnerability research or reproduction payload generation.","google\u002Fmantis","google","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1342004?v=4","01M698VYEFDM0VJBZDYYJ2T83S","Google","01M6990SDGGFEAP21TJNS7HEG9",2778,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-patch\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"mantis patch","patch","when","security","fixes","for","verified","directories","transactional","isolation","generation","Shadow","minimal","payload","use","vulnerability","file","research","2026-11-10 10:12:30",false,"---\nname: mantis-patch\ndescription: >-\n  Generates minimal security fixes using transactional isolation (shadow directories or file backups), applies patches, and verifies them.\n  Use when security findings are successfully reproduced and need patches applied and verified.\n  Don't use for initial vulnerability research or reproduction payload generation.\n---\n\n# Patcher (\u002Fmantis-patch)\n\n## System Goal\n\nSecurity Patching Expert. Generates minimal, correct code fixes, applies them to\nsource code files, and verifies them inside isolated sandboxes before appending\nlogs to long-term memory.\n\n## Command Definition\n\n- **Command:**\n  `\u002Fmantis-patch [--target_root=\u003Cpath>] [--state_root=\u003Cpath>] [--snapshot_root=\u003Cpath>] [--snapshot_id=\u003Cid>] [--snapshot_pinned=\u003Ctrue|false>]`\n- **Description:** Generates minimal security fixes using transactional\n  isolation (shadow directories or file backups), applies patches, and verifies\n  them.\n- **Parameters (all optional; absent ⇒ today's behavior):**\n  - `--target_root`: Root of the code snapshot to read (CODE_ROOT). When the\n    orchestrator pins a snapshot it passes `--snapshot_root`; `--target_root` is\n    reserved for a caller that hands you an already-prepared tree.\n  - `--snapshot_root`: Root of the pinned immutable snapshot for this pass.\n  - `--snapshot_id`: The SNAPSHOT_ID string of the pinned snapshot (used by the\n    Snapshot Match Check).\n  - `--snapshot_pinned`: `true` when a pinned immutable snapshot exists this\n    pass; `false`\u002Fabsent ⇒ degraded\u002Flegacy (see Backward-compat).\n  - `--state_root`: Root of the Mantis state directory that contains\n    `workspace\u002F` (defaults to the current directory). ALL `workspace\u002F...` paths\n    in this file are STATE-RELATIVE and resolve under\n    `\u003Cstate_root>\u002Fworkspace\u002F...`.\n\n## Input\u002FOutput Contract\n\n- **Reads**:\n  - `workspace\u002Ffindings\u002F` (reproduced finding JSON files where `patch_status` is\n    not `\"VERIFIED_SECURE\"` or `\"MITIGATION_PROPOSED\"`).\n  - `workspace\u002F.mantis_state.json` (to track current loop pass).\n  - `workspace\u002F.mantis_state.json` `active_snapshot` (`root`, `snapshot_id`,\n    `snapshot_pinned`) — resolved via Block A; supplies CODE_ROOT and the\n    SNAPSHOT_ID used by the Snapshot Match Check when no `--snapshot_*` flag is\n    passed.\n  - Target source code files.\n  - Reproducer script path (`repro_file_path`) and command (`run_command`) from\n    findings.\n  - Pre-existing backup files matching finding ID (if Option B is used).\n- **Writes**:\n  - Source code modifications (applied transactionally and rolled back).\n  - Updates finding JSON files in-place (sets `\"patch_status\"`, `\"patch_diff\"`,\n    re-attack details including `\"reattack_status\"` and `\"reattack_variants\"`,\n    and history).\n  - Appends to `workspace\u002Flearnings.jsonl`.\n  - Reusable helper script `workspace\u002Fhelpers\u002Fappend_patch.py`.\n- **Preconditions**:\n  - Findings must exist in `workspace\u002Ffindings\u002F`.\n- **Idempotency Guarantee**:\n  - **Snapshot-aware skip:** Skips a finding whose `patch_status` is already\n    `\"VERIFIED_SECURE\"` or `\"MITIGATION_PROPOSED\"` ONLY when its recorded\n    `patch_base_snapshot` equals the current SNAPSHOT_ID (i.e. it was verified\n    against THIS snapshot). If `patch_base_snapshot` is absent, empty, or\n    different from the current SNAPSHOT_ID, the terminal status is stale — do\n    NOT skip; re-open and re-verify the finding against the current snapshot. In\n    legacy mode (no `active_snapshot` and no `--snapshot_*` flags) skip exactly\n    as today (by `patch_status` alone).\n  - Transactional isolation: modifies code inside uniquely generated temporary\n    directories or creates temporary file backups (`target.c.bak-[id]`),\n    restoring baseline state upon completion (using `try...finally` rollback\n    mechanisms).\n  - Reuses the existing `append_patch.py` script once created.\n\n## Instructions\n\nFix successfully reproduced security flaws without breaking standard code\nbehavior.\n\nExecute the patching and verification stage as follows:\n\n0. **Snapshot & Locator Resolution (run once, before touching any code):**\n\n   0a. Resolve CODE_ROOT, SNAPSHOT_ID, snapshot_pinned, and state_root via\n   **Block A** (Locator Resolution):\n\n   ```\n   LOCATOR RESOLUTION (before reading ANY target code or artifact):\n   0. ROLE: If this skill NEVER reads target source (report, calibrate, reflect),\n      you are a FINDINGS-ONLY stage: skip steps 2-6; still read active_snapshot from\n      state for provenance\u002Fannotation; NEVER stop merely because a code root is unset.\n   1. Determine CODE_ROOT, in this priority order:\n      a. If --target_root is passed on THIS invocation, CODE_ROOT = --target_root.\n         It is AUTHORITATIVE and OVERRIDES SNAPSHOT_ROOT and the state fallback\n         (used when a caller hands you a prepared tree, e.g. a patched shadow).\n      b. Else if --snapshot_root (or SNAPSHOT_ROOT) is passed, use it.\n      c. Else read state_root\u002Fworkspace\u002F.mantis_state.json (state_root from\n         --state_root if passed, else .\u002Fworkspace\u002F... relative to the current dir)\n         -> active_snapshot.root \u002F .snapshot_id \u002F .snapshot_pinned.\n      d. Else (no arg AND no readable active_snapshot): CODE_ROOT = current directory,\n         treat snapshot_pinned = false (MODE-OFF). Do NOT stop.\n   2. SENTINEL CHECK (only if snapshot_pinned is true AND you did NOT take path 1a):\n      verify CODE_ROOT\u002F.mantis_snapshot_id exists and equals SNAPSHOT_ID. If missing\n      or different -> STOP \"snapshot sentinel mismatch\". (A --target_root tree (1a) is\n      deliberately mutated and is sentinel-EXEMPT.)\n   3. PATH FIELDS:\n      - SNAPSHOT-RELATIVE (read under CODE_ROOT): code_paths entries; plan target_files\n        that are file paths. Strip ONLY a trailing \":\u003Cdigits>\". A code_paths entry\n        containing \":\u002F\u002F\" is a URL\u002Fendpoint, NOT a file read. A code_paths entry that is\n        NOT of the form \u003Cexisting-path>:\u003Cinteger> is a non-source LOCATOR\n        (symbol\u002Foffset\u002Fendpoint): only check that the artifact\u002Fsymbol exists; skip ALL\n        line-range and line-existence logic.\n      - STATE-RELATIVE (read\u002Fwrite under state_root\u002Fworkspace, NEVER prefix CODE_ROOT):\n        kb_references, repro_file_path, reattack_file_path, helper scripts, report\n        files, and all state\u002Ffindings JSON.\n   4. Never WRITE under CODE_ROOT when snapshot_pinned is true. Any command that\n      compiles, generates, or writes artifacts MUST run in a PRIVATE SHADOW copy\n      (mktemp -d from CODE_ROOT), never with cwd=CODE_ROOT. Read-only inspection may\n      cd into CODE_ROOT.\n   5. VCS-METADATA CARVE-OUT: history-log extraction and any VCS diff\u002Fblame command\n      run in the LIVE repository root (which still has .git\u002F.hg\u002F.repo), NOT CODE_ROOT\n      (the snapshot copy strips VCS metadata). Do NOT stop merely because CODE_ROOT\n      lacks .git\u002F.hg\u002F.repo.\n   6. Every shell command uses ABSOLUTE paths and sets its own working directory on\n      that call. Do NOT assume the working directory persists between calls.\n   ```\n\n   > [!NOTE] **CURRENT-PASS CHECK (defensive; the binding guarantee is on the\n   > harness per `mantis-pipeline-adapter` Scenario 2):** if `active_snapshot`\n   > is present AND `active_snapshot.pass != state.pass_number`, treat the\n   > snapshot as STALE for this pass — STOP \"stale active_snapshot: pass\n   > mismatch\" or degrade as HALT (`snapshot_pinned` effectively false: no\n   > authoritative verdicts, Block B NOT_MATCHED, reproduce `not_attempted`).\n   > This catches a custom harness that preserved `active_snapshot` across the\n   > Stage 15 pass increment without re-pinning. The reference meta-agent\n   > re-pins every pass, so this check never fires there. Block B itself cannot\n   > detect this (it is `snapshot_id`-only, not `pass`-aware).\n\n   For this stage: mantis-patch READS target code (it is NOT a findings-only\n   stage), so it runs Block A steps 1–6 in full. CODE_ROOT is the immutable\n   pinned snapshot; you MUST NOT write, compile, or run reproducers under it\n   (Block A step 4) — do all mutation in a private shadow (step 2 below).\n\n   0b. Determine PATCH_MODE (mechanical, using the resolved values):\n\n   - `active_snapshot` absent AND no `--snapshot_root`\u002F`--snapshot_id`\u002F\n     `--target_root` passed ⇒ **LEGACY mode** (today's behavior; the new\n     ceilings in step 3 do NOT fire).\n   - `snapshot_pinned == true` ⇒ **PINNED mode** (full gates below apply).\n   - `snapshot_pinned == false` AND SNAPSHOT_ID begins with the literal `live:`\n     ⇒ **HALT\u002FDEGRADED mode** (a snapshot was attempted but could not be pinned;\n     authoritative verdicts are forbidden this pass — see step 3).\n\n   0c. For each finding you process, compute its MATCHED\u002FNOT_MATCHED result via\n   **Block B** (Snapshot Match Check):\n\n   ```\n   SNAPSHOT MATCH CHECK for finding F (decides MATCHED vs NOT_MATCHED):\n   1. If snapshot_pinned is false -> NOT_MATCHED. Stop.\n   2. Read F.discovery_commit:\n      - missing OR empty OR the literal \"MIXED\" -> NOT_MATCHED.\n      - not exactly equal to SNAPSHOT_ID          -> NOT_MATCHED.\n      - exactly equal to SNAPSHOT_ID              -> MATCHED.\n   There is no other route to MATCHED; never fuzzy-compare. The global \"default the\n   field and proceed\" backward-compat rule does NOT apply to discovery_commit:\n   absent = NOT_MATCHED. (There is NO separate \"dirty\" gate: a dirty tree's\n   SNAPSHOT_ID already embeds the working-tree content hash, so within-pass findings\n   MATCH and cross-pass bare-commit findings do not.)\n   ```\n\n   The MATCHED\u002FNOT_MATCHED result is consumed in step 2 (isolation-mode choice)\n   and step 3 (verdict). It never on its own downgrades a verdict in PINNED\n   mode: a NOT_MATCHED finding is RE-verified against the current snapshot via\n   the step-3 gate and, if it passes, is stamped with the current\n   `patch_base_snapshot`.\n\n1. **Load Findings to Patch:** Read the JSON files in the `workspace\u002Ffindings\u002F`\n   directory. Filter for findings that are NOT already terminally verified\n   AGAINST THE CURRENT SNAPSHOT — i.e. treat a finding as still-to-process\n   unless its `patch_status` is `\"VERIFIED_SECURE\"` or `\"MITIGATION_PROPOSED\"`\n   **and** its `patch_base_snapshot` equals the current SNAPSHOT_ID (Snapshot &\n   Locator Resolution step 0). A terminal finding whose `patch_base_snapshot` is\n   absent\u002Fempty\u002Fdifferent is STALE — include it for re-verification. (In LEGACY\n   mode, where there is no SNAPSHOT_ID, fall back to filtering on `patch_status`\n   alone, exactly as before.) Among the included findings, keep those where\n   (either `repro_status` is `\"reproduced\"` OR the finding is an exploit chain,\n   e.g., the title starts with `\"Exploit Chain:\"`, or history has an entry from\n   the `\"chainer\"` stage, or the `\"constituent_findings\"` property is present\n   and non-empty). If none exist, notify the user.\n\n2. **Generate and Apply Minimal Patches:** For each reproduced security flaw:\n\n   - **Target Agnosticism (Binaries vs Source):** If the target is source code,\n     proceed with generating and applying a code patch as described below. If\n     the target is a compiled binary or firmware blob without source code\n     available, **do not attempt to modify the binary or write binary patching\n     scripts**. Instead, skip the branch isolation\u002Fmodification\u002Fdiff steps and\n     generate a general, high-level recommendation for how this issue could be\n     mitigated in a production environment without requiring deep technical\n     depth. Output this mitigation string in place of the `patch_diff` field,\n     and set `\"patch_status\"` to `\"MITIGATION_PROPOSED\"`.\n\n   - **Exploit Chains:** If the finding is an exploit chain (identified by\n     `\"Exploit Chain:\"` in the title, or history details, or if the\n     `\"constituent_findings\"` property is present and non-empty), do **not**\n     generate a code patch or diff. Instead, identify its sub-findings by\n     reading the `\"constituent_findings\"` array of UUIDs. Monitor the patch\n     status of these constituent findings (listed on disk as\n     `workspace\u002Ffindings\u002F\u003Cuuid>.json`). **Important:** Defer evaluating exploit\n     chains until all individual findings in the batch have been processed, so\n     that the latest patch statuses of their constituents are available on disk.\n\n     Evaluate the exploit chain status using these propagation rules (evaluated\n     in order):\n\n     1. **Validity Check:** Read the validity `\"status\"` of each constituent\n        finding. If any constituent's `\"status\"` is `\"FALSE_POSITIVE\"`, update\n        the exploit chain finding's `\"status\"` to match it (e.g.\n        `\"FALSE_POSITIVE\"`) and immediately skip any further\n        patching\u002Fverification for the chain. If any constituent's `\"status\"` is\n        `\"DUPLICATE\"`, resolve it to its canonical finding by recursively\n        following its `\"duplicate_of\"` property.\n\n        **Duplicate Resolution Process:**\n\n        1. **Locate the Finding File:** The finding file for the duplicate (or\n           any parent in the duplicate chain) may have been moved. Search for\n           `\u003Cuuid>.json` in the following locations in order:\n           - `workspace\u002Ffindings\u002F\u003Cuuid>.json` (active findings)\n           - `workspace\u002Ffindings\u002F.trash\u002F\u003Cuuid>.json` (de-duplicated trash)\n           - `workspace\u002Farchive\u002Ffindings_pass_*\u002F\u003Cuuid>.json` or\n             `workspace\u002Farchive\u002Floop*_findings\u002F\u003Cuuid>.json` (archives from\n             previous passes) If the file cannot be found in any of these\n             locations, treat it as a missing file error.\n        2. **Cycle Detection:** Maintain a set of visited finding UUIDs during\n           the resolution. If you encounter a UUID that has already been visited\n           in the current resolution chain, raise a validation error (cycle\n           detected).\n        3. **Maximum Depth:** Limit the recursion depth to a maximum of 5 steps.\n           If the chain is deeper, abort and report an error.\n        4. **Extract Status:** Once you resolve to the canonical finding (one\n           whose `\"status\"` is not `\"DUPLICATE\"` or does not have\n           `\"duplicate_of\"`), use that canonical finding's `\"status\"` and\n           `\"patch_status\"` for all downstream checks and propagation. Do not\n           update the exploit chain finding itself to `\"DUPLICATE\"`.\n\n     2. **Missing Files:** If any constituent finding's JSON file is missing\n        from the disk, set the chain's `\"patch_status\"` to `\"ERROR\"`.\n\n     3. **Constituent Unset or Stale (Pending):** A constituent counts as\n        NOT-YET-VERIFIED if EITHER its `\"patch_status\"` is unset (null or\n        missing, indicating it has not yet been reproduced\u002Fprocessed) OR its\n        `\"patch_status\"` is terminal but its `patch_base_snapshot` is\n        absent\u002Fempty\u002Fdifferent from the current SNAPSHOT_ID (verified against a\n        stale snapshot — Snapshot & Locator Resolution step 0). If ANY\n        constituent is NOT-YET-VERIFIED, the chain's `\"patch_status\"` must\n        remain unset (null or missing) and you must defer\u002Fsuspend further\n        evaluation of the chain until that constituent is re-verified on the\n        current snapshot. (In LEGACY mode, where there is no SNAPSHOT_ID, apply\n        only the \"unset\" half of this rule, exactly as before.)\n\n     4. **Constituent Errors:** If any constituent's `\"patch_status\"` is\n        `\"ERROR\"`, set the chain's `\"patch_status\"` to `\"ERROR\"`.\n\n     5. **Constituent Failures:** If any constituent's `\"patch_status\"` is\n        `\"VERIFICATION_FAILED\"`, set the chain's `\"patch_status\"` to\n        `\"VERIFICATION_FAILED\"`.\n\n     6. **Successful Propagation:** If all constituents have finished\n        verification AGAINST THE CURRENT SNAPSHOT (each is in\n        `{\"VERIFIED_SECURE\", \"MITIGATION_PROPOSED\", \"VERIFICATION_INCOMPLETE\"}`\n        AND — except in LEGACY mode — each terminal constituent's\n        `patch_base_snapshot` equals the current SNAPSHOT_ID):\n\n        - If any constituent is `\"MITIGATION_PROPOSED\"`, set the chain's\n          `\"patch_status\"` to `\"MITIGATION_PROPOSED\"`.\n        - If no constituent is `\"MITIGATION_PROPOSED\"` and any constituent is\n          `\"VERIFICATION_INCOMPLETE\"`, set the chain's `\"patch_status\"` to\n          `\"VERIFICATION_INCOMPLETE\"`.\n        - If all constituents are `\"VERIFIED_SECURE\"`, set the chain's\n          `\"patch_status\"` to `\"VERIFIED_SECURE\"`.\n\n     Skip branch isolation, testing, and re-attack steps for the chain finding\n     itself.\n\n   - *Optional Parallel Trajectory Search:* If your framework supports\n     subagents, you may spawn multiple concurrent subagents to design diverse\n     patch implementations. Test all generated patches that successfully secure\n     the code without breaking standard functionality, and select the *best*\n     patch (e.g., the most minimal, readable, and idiomatic fix) rather than\n     just the first one that works.\n\n   - Read the original flawed file to grasp function dependencies and\n     structures.\n\n   - Design a minimal, correct patch to mitigate the security flaw (e.g. adding\n     bound checks, validating sizes, inserting NUL-terminators) without breaking\n     other features.\n\n   - **Transactional Isolation (VCS-Agnostic & Safe):** To ensure safety,\n     reliability, and VCS-agnosticism, do NOT use VCS-based branch operations\n     (such as `git branch`, `git checkout`, or `git stash`).\n\n     You must ensure transactional isolation using a method appropriate for the\n     operating environment. **Isolation-method gate (mechanical):**\n\n     - If snapshot_pinned is true (PINNED mode) → **Option A (Temporary\n       Directory Shadowing) is MANDATORY. Option B and any method that writes\n       under CODE_ROOT are FORBIDDEN** (Block A step 4: never write under a\n       pinned snapshot).\n     - Else if the finding is a RETRY (it already carries a prior `\"patch\"`\n       history entry or a `patch_base_snapshot`) OR (PINNED mode AND its\n       Snapshot Match Check result is NOT_MATCHED) → **Option A is MANDATORY**\n       (do not risk editing a live tree that no longer matches the finding). The\n       `PINNED mode AND` qualifier on the NOT_MATCHED clause is essential: in\n       LEGACY mode (snapshot_pinned=false), Block B returns NOT_MATCHED for\n       every finding as an artifact of no snapshot, not as a signal of drift —\n       so NOT_MATCHED must only fire when it means \"the snapshot changed\"\n       (PINNED), not when it means \"no snapshot exists\" (LEGACY).\n     - Otherwise (snapshot_pinned is false AND first attempt — no prior\n       `\"patch\"` history entry and no `patch_base_snapshot`) you may choose\n       **Option A** (recommended), **Option B: File-Level Backups**, or\n       design\u002Fimplement **Option C: Alternative Isolation** (e.g., namespace\n       isolation, container volumes, or local sandboxes) as long as it fully\n       satisfies the invariants below. This covers both LEGACY and HALT mode\n       first-attempt findings (neither has a prior patch to protect, and neither\n       is in the PINNED read-only snapshot regime).\n\n     Whichever method you choose, you must guarantee these invariants:\n\n     1. **Zero Workspace Pollution**: No backup or intermediate build files left\n        in the original source tree.\n     2. **Concurrency Safety**: Isolation methods must not conflict with other\n        concurrent agents.\n     3. **Guaranteed Rollback**: Wrap all actions in error traps or\n        `try...finally` blocks to restore the original state on failure.\n\n     - **Option A: Temporary Directory Shadowing (Recommended \u002F mandatory when\n       pinned)**\n\n       - **Warning\u002FResource constraint:** For source trees larger than a few\n         hundred MB, or when many parallel patch workers share the host, and\n         ONLY when NOT in PINNED mode, you may prefer **Option B** (which\n         touches only the modified files) to avoid exhausting `\u002Ftmp` or memory.\n         In PINNED mode Option B is forbidden regardless of size (the snapshot\n         is read-only); if a full copy will not fit, do not fabricate a verdict\n         — see step 3 HALT handling.\n\n       - **Two-root copy:** Create a uniquely generated SHADOW_ROOT (e.g.\n         `mktemp -d` \u002F `tempfile.mkdtemp()`) OUTSIDE both CODE_ROOT and any\n         `\u002Fworkspace\u002F` path, then copy the relevant source tree **FROM\n         CODE_ROOT** (the snapshot resolved in Snapshot & Locator Resolution\n         step 0), NOT from an implicit cwd, into SHADOW_ROOT. CODE_ROOT stays\n         untouched and read-only.\n\n       - Perform all edits, compilation, and reproduction testing inside\n         SHADOW_ROOT. Never run a mutating\u002Fcompiling\u002Freproducing command with\n         cwd = CODE_ROOT (Block A step 4).\n\n     - **Critical Guard (Path and Working Directory Safety):** You must ensure\n       that every command executed (compilation, testing, verification) runs\n       with its working directory (`Cwd`) explicitly set to SHADOW_ROOT. If the\n       finding's `run_command` contains absolute paths under CODE_ROOT (the\n       snapshot) or under the live source root, you must rewrite that prefix to\n       the corresponding path under SHADOW_ROOT before execution.\n\n       **Guard Check:** When performing path rewriting, only rewrite paths that\n       represent the target codebase files. If a path starts with or contains a\n       `\u002Fworkspace\u002F` segment (where the Mantis state and findings are stored),\n       do NOT replace its prefix (findings\u002Fstate must remain in the\n       authoritative `state_root\u002Fworkspace\u002F`). This separation is unambiguous\n       because a pinned SNAPSHOT_ROOT\u002FCODE_ROOT never contains a `\u002Fworkspace\u002F`\n       segment (guaranteed by the orchestrator's snapshot materialization). Do\n       not execute any modification or verification command against CODE_ROOT or\n       against `state_root\u002Fworkspace\u002F`.\n\n     - **{TARGET_ROOT} token substitution (MANDATORY before executing any stored\n       command):** `mantis-reproduce` stores\n       `run_command`\u002F`reattack_run_command` with the literal token\n       `{TARGET_ROOT}` for target-tree paths (Step 3 of reproduce), expecting\n       the caller to substitute it. Before executing any stored `run_command` or\n       `reattack_run_command`, replace the literal `{TARGET_ROOT}` token with\n       the tree being executed against:\n\n       - For the Block-G **unpatched baseline** run: substitute the fresh\n         unpatched CODE_ROOT copy (a fresh `mktemp -d` copy taken FROM\n         CODE_ROOT).\n       - For **post-patch verification** and **attack\u002Freattack** runs:\n         substitute SHADOW_ROOT (the patched shadow copy). This substitution\n         MUST happen BEFORE the CODE_ROOT→SHADOW_ROOT prefix rewriting above\n         (the token may expand to a CODE_ROOT path that then needs rewriting for\n         shadow runs). If the literal token survives unsubstituted, the command\n         will fail → evidence absent → forced ERROR (Block F\u002FBlock G treat\n         command-not-found \u002F No-such-file as EVIDENCE ABSENT). Never execute a\n         command containing the literal `{TARGET_ROOT}` token.\n\n     - Generate the unified patch diff by comparing the original source files in\n       CODE_ROOT (the pinned snapshot) with the modified files in SHADOW_ROOT.\n       Use labels so no CODE_ROOT\u002FSHADOW_ROOT absolute prefix leaks into the\n       diff headers.\n\n     - Delete the temporary shadow directory completely when finished.\n\n     - **Option B: File-Level Backups (Fallback)**\n\n       - **Concurrency & Exclusivity Warning:** Because Option B modifies files\n         directly in the original workspace, it is concurrency-unsafe when run\n         in parallel with other workspace-modifying agents. Sequential execution\n         must be strictly enforced via locking.\n       - **Exclusive Workspace Lock:** Before performing backups or edits, the\n         agent **must** acquire an exclusive lock on\n         `workspace\u002F.workspace_edit.lock` (using `fcntl.flock` with\n         `fcntl.LOCK_EX` in Python, or a similar system-level lock). The agent\n         **must** hold this lock continuously throughout the entire patching,\n         verification, re-attack, and restoration lifecycle for the finding,\n         releasing it only when final baseline files are restored or finalized.\n       - **Pre-execution Check:** Prior to editing, scan the workspace for\n         pre-existing backup files matching the current finding's ID (e.g.,\n         `*.bak-[current_finding_id]`). If found, restore and delete them.\n       - **Create Backups:** For every source file you intend to modify, create\n         a copy with a unique suffix (e.g.,\n         `cp target.c target.c.bak-[finding_id]`).\n       - **Net-New Files:** Track any newly created files to delete them on\n         rollback.\n       - **Apply Modifications:** Edit original target files directly.\n       - **Generate Unified Diff:** Compare backup against modified file using\n         labels to normalize headers (e.g.,\n         `diff -u --label target.c --label target.c target.c.bak-[finding_id] target.c`).\n\n   - **3-Way Patch Rebasing (Phase 2 incremental efficiency):** When a prior\n     pass's snapshot and patch are still present on disk (see the reachability\n     check below), the patcher can attempt to REBASE a prior pass's patch onto\n     the current snapshot instead of generating a fresh patch from scratch. This\n     is an optimization for the common case where a prior fix still applies with\n     minor line-number shifts.\n\n     - **How:** If ALL reachability conditions (a)-(d) below hold, read\n       [3-Way Patch Rebasing](references\u002Fpatch_rebasing.md) with your\n       file-reading tool for the 3-way merge mechanics (`base`\u002F`ours`\u002F`theirs`\n       scratch copies, `git merge-file` \u002F `diff3` invocation, conflict-marker\n       handling). On ANY uncertainty or if the reference cannot be loaded, fall\n       back to fresh patch generation (Phase-1 behavior).\n     - **When to use (reachability by OBSERVABLE state, not a flag the patcher\n       cannot read):** attempt rebasing ONLY when ALL hold: (a) the prior pass's\n       snapshot directory AND the file's prior unpatched version actually EXIST\n       on disk under `\u003Cstate_root>\u002F.mantis_snapshots\u002F` (retention kept them; if\n       the base snapshot was GC'd this fails → fall back); (b) the finding's\n       `signature` matches an archived finding with a prior `patch_diff` (same\n       bug, same signature) — this is the ARCHIVED finding referenced by the\n       remaining gates; (c) the ARCHIVED finding's `patch_base_snapshot` is\n       present and DIFFERENT from the current `SNAPSHOT_ID` (the snapshot the\n       prior patch was verified against has changed; this is the correct\n       \"snapshot changed\" test — do NOT test Block B on the CURRENT finding,\n       whose `discovery_commit` is always `== SNAPSHOT_ID` in PINNED mode\n       because researcher stamps it, dedupe backfills it, and plan only\n       copy-verbatim's MATCHED findings preserving the original\n       `discovery_commit`); if the archived finding's `patch_base_snapshot` is\n       ABSENT or EMPTY (legacy prior pass, or a pre-Phase-2 patcher that did not\n       write it — detected by the helper-version marker at step 6), the\n       snapshot-changed test is UNKN and you MUST fall back to fresh patch\n       generation (do NOT rebase onto a possibly-unchanged base); and (d) the\n       finding's primary file is in `changed_files`. If `signature` is absent\n       (legacy finding), condition (b) cannot be satisfied — fall back to fresh\n       patch generation. Do NOT gate on `--snapshot_keep`: that flag is set on\n       the orchestrator and is NOT passed to or readable by the patch stage; the\n       on-disk presence check (a) is the correct observable substitute and works\n       under any retention setting (the default keep-2 already retains the\n       immediately-prior pass). `changed_files` and `changed_files_status` are\n       read from `workspace\u002F.mantis_state.json` (the same state object read for\n       `active_snapshot`).\n\n   - **When rebasing SUCCEEDS \u002F FAILS \u002F Guardrail:** See\n     [3-Way Patch Rebasing](references\u002Fpatch_rebasing.md) for the success (clean\n     merge → use rebased patch, still run Block G, history note\n     `patch-rebased-from: pass_\u003CN-1>`), failure (merge conflict \u002F file deleted \u002F\n     renamed → fall back to fresh patch generation), and guardrail (on ANY\n     uncertainty, fall back to Phase-1; never apply a rebased patch with\n     unresolved conflicts or unrelated changes).\n\n   - **Unpatched-Baseline Re-run in `--reattack` (Phase 2):** When the\n     `@mantis-reproduce --reattack` sub-agent is re-attacking a patch on a NEW\n     snapshot (Block B NOT_MATCHED, meaning the snapshot changed since the patch\n     was verified — in PINNED mode only), the re-attack MUST first re-establish\n     the unpatched baseline on the CURRENT snapshot before testing the attack\n     against the patched build. This ensures the re-attack is meaningful: if the\n     bug no longer triggers on the current unpatched snapshot (e.g., upstream\n     code fixed it), the re-attack result is inconclusive, not a pass.\n\n     - **How:** Before running the attack on the patched shadow, run the\n       reproducer against a FRESH UNPATCHED copy of the current snapshot (per\n       Block G step 1). If the unpatched baseline does NOT trigger (evidence\n       absent), set `reattack_status = \"inconclusive_baseline_changed\"` with a\n       history note, and do NOT claim `failed_to_bypass` (the patch was not\n       tested against a live bug). If the unpatched baseline DOES trigger,\n       proceed with the attack on the patched build as normal.\n     - **HALT-mode note:** In HALT mode (`snapshot_pinned=false`, `live:`\n       SNAPSHOT_ID), Block B is always NOT_MATCHED, but this does NOT represent\n       a genuine snapshot change — it means the tree couldn't be pinned. The\n       `@mantis-reproduce --reattack` sub-agent skips the C5 re-baseline in HALT\n       (see reproduce C5 HALT guardrail) and follows the existing HALT ceiling.\n     - **Guardrail:** This does NOT change the VERIFIED_SECURE gate — Block G\n       still requires the unpatched baseline to trigger. This only adds a\n       re-baseline step to the re-attack path when the snapshot changed.\n\n3. **Post-Patch Verification Run:** *(Skip this step for binary-only targets\n   where no code patch was applied)*. To confirm the patch works, re-run the\n   reproducer script inside your isolated execution environment. Use the exact\n   `\"repro_file_path\"` and `\"run_command\"` from the reproduction entry to verify\n   the patch.\n\n   - **Cwd Enforcement:** You must execute the reproducer script with the\n     working directory (`Cwd`) set to the shadow directory (if using Option A).\n     Ensure the command targets the copy in the shadow directory, not the\n     original workspace.\n\n   - **Reached-sink evidence definition** — **Block F** (Reached-Sink Evidence\n     Gate). In patch verification the evidence is required on the UNPATCHED\n     baseline, never on the post-patch attack run (a correct patch legitimately\n     stops the input before the sink):\n\n     ```\n     REACHED-SINK EVIDENCE GATE (mechanical):\n     Each reproducer produces REACHED-SINK EVIDENCE via ONE channel, recorded in repro_hints:\n        (a) script\u002Fsource harness -> write the exact bytes MANTIS_REACHED_ENTRYPOINT to a\n            sidecar file $SENTINEL_FILE and flush+fsync (or unbuffered write) BEFORE\n            invoking the sink. (A file survives a crash that truncates buffered stdout.)\n        (b) binary \u002F firmware \u002F raw-payload -> reached-sink evidence is a captured\n            crash backtrace or sanitizer frame (ASan\u002FUBSan\u002FMSan\u002FTSan) that\n            explicitly names the target sink function (target-produced tracing). A\n            marker written by a wrapper you author BEFORE invoking the target is\n            SETUP EVIDENCE ONLY: it proves \"launch attempted,\" not \"sink reached,\"\n            and does NOT qualify as reached-sink evidence. If no in-path marker\n            (channel a) and no target-produced backtrace\u002Fsanitizer trace\n            (channel b) is achievable, the sink is unreached.\n      EVIDENCE PRESENT (reached-sink) = (channel a) sidecar file contains\n        MANTIS_REACHED_ENTRYPOINT written in-path, OR (channel b) target-produced\n        backtrace\u002Fsanitizer output names the sink. A wrapper pre-launch marker alone is\n        NOT evidence present.\n     EVIDENCE ABSENT includes: any compiler\u002Fbuild nonzero exit; exit 127 (command not\n       found); exit 2 with a \"No such file\" message.\n     DECISION GATE (gate the DECISION, not specific verdict strings):\n       - Record repro_status = reproduced OR statically_confirmed ONLY if EVIDENCE is\n         PRESENT. If ABSENT -> repro_status = not_attempted (retry-eligible), STOP.\n       - In patch verification, EVIDENCE is required on the UNPATCHED baseline (Block G),\n         NOT on the post-patch attack run (a correct patch legitimately stops the input\n         before the sink).\n       - If NO evidence channel is achievable for this target, downgrade to\n         not_attempted \u002F VERIFICATION_INCOMPLETE. NEVER synthesize the marker.\n     ```\n\n   - **Hard gate before any `VERIFIED_SECURE`** — **Block G**\n     (Unpatched-Baseline + Benign-Control Gate). Run it inside SHADOW copies of\n     CODE_ROOT; the \"FRESH UNPATCHED copy of SNAPSHOT_ROOT\" in Block G step 1\n     means a fresh copy taken FROM CODE_ROOT:\n\n     ```\n     UNPATCHED-BASELINE + POST-PATCH GATE (before any VERIFIED_SECURE):\n     0. APPLICABILITY: applies ONLY when repro_status == reproduced (a runnable PoC\n        exists). If repro_status == statically_confirmed (no runnable PoC),\n        VERIFIED_SECURE is NOT applicable -> record MITIGATION_PROPOSED (NEVER ERROR).\n     1. UNPATCHED BASELINE: run the reproducer against a FRESH UNPATCHED copy of\n        SNAPSHOT_ROOT using Block F. If evidence ABSENT or the bug does NOT trigger ->\n        patch_status = ERROR (\"reproducer_invalid_on_current_snapshot\"); do NOT set\n        VERIFIED_SECURE.\n     2. POST-PATCH INTEGRITY (distinguish \"blocked by patch\" from \"build break\"):\n        - REQUIRED: the patched build must COMPILE with exit 0. Nonzero ->\n          VERIFICATION_INCOMPLETE.\n        - REQUIRED (benign control): run a legitimate BENIGN (non-attack) input through\n          the patched build; it MUST reach the sink path (EVIDENCE PRESENT via Block F)\n          with no crash. This proves the patch narrowed the bug rather than breaking the\n          harness\u002Fentrypoint. If NO benign control can be constructed for this target,\n          you may NOT claim VERIFIED_SECURE on a clean-run-only basis -> land\n          VERIFICATION_INCOMPLETE and record why the benign control was infeasible.\n          (Strict mode: a clean compile + clean run WITHOUT a benign control reaching\n          the sink is never sufficient for VERIFIED_SECURE.)\n     3. ATTACK ON PATCH: run the attack input through the patched build. VERIFIED_SECURE\n        requires ALL of: step 1 triggered on unpatched (evidence present), step 2\n        integrity holds, step 3 attack does NOT crash\u002Ftrigger, AND the `--reattack` run\n        also fails to bypass. Otherwise VERIFICATION_FAILED.\n     ```\n\n     **Sanitizer consistency guardrail (Block G):** All runs in this gate\n     (unpatched baseline, benign control, attack, and re-attack) MUST use the\n     SAME sanitizer flags that made the unpatched baseline trigger. If the\n     baseline triggered via UBSan (exit 0, recover-mode), the attack run must\n     also be compiled with UBSan — otherwise the attack might exit 0 without a\n     trace even though the bug is still present, producing a false\n     `VERIFIED_SECURE` (INV-1 violation). Record the sanitizer flags used in\n     `repro_hints` so downstream stages replicate them.\n\n   - **HALT\u002FDEGRADED ceiling:** If PATCH_MODE is HALT\u002FDEGRADED (snapshot_pinned\n     false with a `live:` SNAPSHOT_ID), authoritative verdicts are forbidden\n     this pass: the best attainable `patch_status` is\n     `\"VERIFICATION_INCOMPLETE\"`. Never emit `\"VERIFIED_SECURE\"` in this mode.\n     (LEGACY mode is unaffected.)\n\n   - **Missing-file rule:** If the reproducer file (`repro_file_path`) or a\n     `code_paths` target file cannot be found when you attempt verification, set\n     `patch_status` to `\"ERROR\"`. NEVER treat a missing file as \"did not\n     reproduce\" and NEVER emit `\"VERIFIED_SECURE\"` from a missing file. (This is\n     also what Block F\u002FBlock G's \"No such file\"\u002F`exit 127` → EVIDENCE ABSENT\n     path enforces.)\n\n   * **VERIFIED SECURE (all conditions REQUIRED):** Mark `patch_status` as\n     `\"VERIFIED_SECURE\"` ONLY if ALL of the following hold:\n\n     1. **Block G passes in full:** the UNPATCHED baseline triggered the bug\n        WITH reached-sink evidence (Block F) on a fresh copy of CODE_ROOT; the\n        patched build compiled (exit 0); the benign\u002Fintegrity control held; and\n        the attack input on the patched build does NOT crash\u002Ftrigger.\n     2. **Re-attack fails to bypass:** a fresh, independent\n        `@mantis-reproduce --reattack` sub-agent (spawned per the block below)\n        writes `reattack_status = \"failed_to_bypass\"` — meaning a non-empty\n        `reattack_variants` array with ≥ 3 valid variant inputs (reproduce Step\n        3a) ALL failed to trigger the original vulnerability class on the\n        patched shadow. An empty or short variant set caps at\n        `VERIFICATION_INCOMPLETE`, never `VERIFIED_SECURE`.\n     3. **Not degraded:** PATCH_MODE is not HALT\u002FDEGRADED. If PATCH_MODE is\n        HALT\u002FDEGRADED (snapshot mismatch \u002F unpinnable snapshot), the ceiling is\n        `\"VERIFICATION_INCOMPLETE\"`, never `\"VERIFIED_SECURE\"`. If Block G\n        reports its baseline could NOT be established (evidence absent or bug\n        does not trigger on the current unpatched snapshot), set `patch_status`\n        to `\"ERROR\"` (`\"reproducer_invalid_on_current_snapshot\"`) — do NOT emit\n        `\"VERIFIED_SECURE\"`. If Block G's applicability check found\n        `repro_status == statically_confirmed`, record `\"MITIGATION_PROPOSED\"`\n        (never ERROR). To ensure true independence, launch a fresh\n        `@mantis-reproduce --reattack --finding_id=[finding_id]` sub-agent\n        against the PATCHED shadow (a copy of SHADOW_ROOT after your patch is\n        applied) to perform the re-attack.\n\n     **Important:** When calling the `@mantis-reproduce` subagent for the\n     re-attack:\n\n     - If using **Option A (Shadowing)** (always, in PINNED mode), pass:\n       - `--reattack`\n       - `--target_root=\u003CPATCHED_SHADOW_ROOT>` — the shadow copy that contains\n         your applied patch. Because `--target_root` is AUTHORITATIVE and\n         sentinel-EXEMPT (Block A step 1a\u002F2), the sub-agent reads the patched\n         tree directly.\n       - `--snapshot_pinned=false` — the patched shadow is deliberately mutated,\n         so the reproduce sub-agent MUST skip the snapshot sentinel\u002Fmatch check\n         for it.\n       - `--state_root=\u003Cstate_root>` — your authoritative state directory (so\n         all `reattack_*` fields and history land under\n         `state_root\u002Fworkspace\u002F`).\n       - `--finding_id=[finding_id]` of the finding being verified.\n     - If using **Option B (Backups)** or **Option C (Alternative)** (only\n       possible in LEGACY mode), pass `--reattack`, both roots pointing at the\n       live workspace (or leave them default `.`), and\n       `--finding_id=[finding_id]`.\n\n     The reproducer agent running with `--reattack` will write its outcomes\n     directly into the primary finding's `reattack_status`,\n     `reattack_file_path`, `reattack_run_command`, and `reattack_output` fields\n     inside the original workspace findings (`state_root\u002Fworkspace\u002Ffindings\u002F`),\n     keeping the initial `repro_*` fields untouched.\n\n   * **VERIFICATION FAILED:** If the sandbox execution still triggers the bug,\n     or if your re-attack successfully bypasses your patch, the patch is\n     insufficient. Re-evaluate and adapt your fix.\n\n   * **VERIFICATION INCOMPLETE:** If the initial post-patch verification run\n     passed but the subsequent re-attack checks failed\u002Ftimed out due to sandbox\n     infrastructure errors, environment timeouts, or platform restrictions, set\n     `\"patch_status\"` to `\"VERIFICATION_INCOMPLETE\"`.\n\n   * **Re-attack unset \u002F SNAPSHOT_MISMATCH → VERIFICATION_INCOMPLETE:** If\n     `reattack_status` is unset (the re-attack sub-agent left it unset with a\n     `SNAPSHOT_MISMATCH` or `setup_failed` history note, or the re-attack did\n     not run at all), set `patch_status` to `\"VERIFICATION_INCOMPLETE\"` — never\n     `VERIFIED_SECURE`. An unset re-attack status means independence was not\n     confirmed; a `SNAPSHOT_MISMATCH` means the re-attack ran against a\n     different snapshot than the patch was verified on. In either case the patch\n     is not conclusively verified.\n\n   * **Inconclusive baseline → VERIFICATION_INCOMPLETE:** If `reattack_status`\n     is `\"inconclusive_baseline_changed\"` (the re-attack sub-agent re-ran the\n     unpatched baseline on the current snapshot and the bug no longer triggers —\n     the baseline changed since the patch was verified), set `patch_status` to\n     `\"VERIFICATION_INCOMPLETE\"` (or `\"ERROR\"` with details\n     `\"reproducer_invalid_on_current_snapshot\"`) — never `\"VERIFIED_SECURE\"`.\n     The patch was not tested against a live bug on the current snapshot;\n     claiming it is secure would be a false authoritative verdict.\n\n4. **Extract Patch and Rollback Transaction:** *(Skip this step for binary-only\n   targets)*. Do not leave the codebase in an altered state. Once you have a\n   final outcome (either `VERIFIED_SECURE` or you have exhausted your retries):\n\n   - If successful, generate a unified diff representing your exact changes and\n     save it to the `\"patch_diff\"` field:\n     - If using **Option A (Shadowing)**, generate this diff by comparing the\n       original files in CODE_ROOT with the modified files in the shadow\n       directory.\n     - If using **Option B (Backups)**, generate this diff by comparing the\n       backup file to the modified file, explicitly labeling the headers to\n       prevent the backup suffix from appearing (e.g.,\n       `diff -u --label target.c --label target.c target.c.bak-[finding_id] target.c`).\n     - If using **Option C (Alternative)**, generate a clean, VCS-agnostic\n       unified diff comparing the unmodified baseline files to the final patched\n       files.\n     - If multiple files were modified, generate individual unified diffs and\n       concatenate them cleanly into the single `\"patch_diff\"` string. Do NOT\n       use VCS-specific diff commands.\n   - **Transactional Clean Up \u002F Rollback**: Restore the codebase to its original\n     state.\n     - If using **Option A (Shadowing)**, delete the temporary shadow directory\n       completely (e.g., `rm -rf \u003Cshadow_directory>`). Since the original\n       codebase was never modified, no further restoration is needed.\n     - If using **Option B (Backups)**, restore the original files by copying\n       the backup files back onto the target files (e.g.,\n       `cp target.c.bak-[finding_id] target.c`), delete the backup copies\n       (`rm target.c.bak-[finding_id]`), and delete any net-new files created\n       during the patching process. **Do NOT delete any re-attack\u002FPoC script\n       files written inside the `workspace\u002Freproducers\u002F` directory, any helper\n       scripts written inside the `workspace\u002Fhelpers\u002F` directory, or the memory\n       database file `workspace\u002Flearnings.jsonl`; these must be explicitly\n       preserved.**\n     - If using **Option C (Alternative)**, execute the corresponding teardown\n       or rollback steps to fully purge all modification artifacts, delete any\n       temporary resources, and ensure the original workspace is left in its\n       clean baseline state.\n\n5. **Append to Long-Term Memory (Continuous Reviewing Link):** For each security\n   flaw processed, append a single structured JSON line to a workspace database\n   file named `workspace\u002Flearnings.jsonl` (using append mode). This allows the\n   strategist (`\u002Fmantis-plan`) to read these historical records in subsequent\n   passes and avoid proposing fixes for already patched files.\n\n   - **Memory Entry Format:**\n     `{\"title\": \"[security_flaw_title]\", \"code_paths\": [\"[path1:line1]\"], \"status\": \"[VERIFIED_SECURE \u002F MITIGATION_PROPOSED \u002F VERIFICATION_INCOMPLETE \u002F VERIFICATION_FAILED \u002F ERROR]\", \"patch_base_snapshot\": \"[current SNAPSHOT_ID, or omit in LEGACY mode]\", \"snapshot\": \"[current SNAPSHOT_ID, or omit in MODE-OFF]\"}`\n\n6. **Token-Optimized File Updates:** To minimize LLM output tokens, **do not\n   re-emit or manually rewrite the entire JSON object in your output.** Instead,\n   write a reusable helper script (e.g.,\n   `state_root\u002Fworkspace\u002Fhelpers\u002Fappend_patch.py`) during your first finding\n   update. Make the FIRST line of the helper a version marker comment:\n   `# MANTIS_HELPER_VERSION = 2`. Before reusing an existing helper, read its\n   first line: if it does NOT contain the exact marker\n   `MANTIS_HELPER_VERSION = 2`, the helper is stale (from an older pass\u002Fversion\n   that does not write `patch_base_snapshot`) — regenerate it. Only when the\n   marker matches may you reuse it: simply execute the existing helper with the\n   new parameters to append the required fields.\n\n   You must append the following to the existing object:\n\n   - A `\"patch_status\"` field (one of `\"VERIFIED_SECURE\"`,\n     `\"MITIGATION_PROPOSED\"`, `\"VERIFICATION_INCOMPLETE\"`,\n     `\"VERIFICATION_FAILED\"`, or `\"ERROR\"`).\n   - A `\"patch_base_snapshot\"` field set to the current SNAPSHOT_ID (Snapshot &\n     Locator Resolution step 0) — the snapshot this verdict was earned on. Omit\n     this field only in LEGACY mode (no SNAPSHOT_ID exists). This is what makes\n     the snapshot-aware skip (Idempotency Guarantee) and chain propagation\n     correct across passes.\n   - If a patch was successful, a `\"patch_diff\"` field containing the unified\n     diff.\n   - If a re-attack was performed, the `\"reattack_status\"`,\n     `\"reattack_file_path\"`, `\"reattack_run_command\"`, `\"reattack_output\"`, and\n     `\"reattack_variants\"` fields (each object in `\"reattack_variants\"` MUST\n     have EXACTLY `{\"description\": \"...\", \"triggered\": true\u002Ffalse}`).\n   - An entry to the `\"history\"` array:\n\n   ```json\n   {\n     \"stage\": \"patch\",\n     \"action\": \"patched\",\n      \"details\": \"Patch status evaluated as [VERIFIED_SECURE\u002FMITIGATION_PROPOSED\u002FVERIFICATION_INCOMPLETE\u002FVERIFICATION_FAILED\u002FERROR] on snapshot [patch_base_snapshot or 'legacy']\",\n     \"pass_number\": \u003Ccurrent_pass_number>,\n     \"timestamp\": \"\u003Ccurrent_iso8601_timestamp>\"\n   }\n   ```\n\nWhen complete, notify the user.\n","# Patcher (\u002Fmantis-patch)\n\n## System Goal\n\nSecurity Patching Expert. Generates minimal, correct code fixes, applies them to\nsource code files, and verifies them inside isolated sandboxes before appending\nlogs to long-term memory.\n\n## Command Definition\n\n- **Command:**\n  `\u002Fmantis-patch [--target_root=\u003Cpath>] [--state_root=\u003Cpath>] [--snapshot_root=\u003Cpath>] [--snapshot_id=\u003Cid>] [--snapshot_pinned=\u003Ctrue|false>]`\n- **Description:** Generates minimal security fixes using transactional\n  isolation (shadow directories or file backups), applies patches, and verifies\n  them.\n- **Parameters (all optional; absent ⇒ today's behavior):**\n  - `--target_root`: Root of the code snapshot to read (CODE_ROOT). When the\n    orchestrator pins a snapshot it passes `--snapshot_root`; `--target_root` is\n    reserved for a caller that hands you an already-prepared tree.\n  - `--snapshot_root`: Root of the pinned immutable snapshot for this pass.\n  - `--snapshot_id`: The SNAPSHOT_ID string of the pinned snapshot (used by the\n    Snapshot Match Check).\n  - `--snapshot_pinned`: `true` when a pinned immutable snapshot exists this\n    pass; `false`\u002Fabsent ⇒ degraded\u002Flegacy (see Backward-compat).\n  - `--state_root`: Root of the Mantis state directory that contains\n    `workspace\u002F` (defaults to the current directory). ALL `workspace\u002F...` paths\n    in this file are STATE-RELATIVE and resolve under\n    `\u003Cstate_root>\u002Fworkspace\u002F...`.\n\n## Input\u002FOutput Contract\n\n- **Reads**:\n  - `workspace\u002Ffindings\u002F` (reproduced finding JSON files where `patch_status` is\n    not `\"VERIFIED_SECURE\"` or `\"MITIGATION_PROPOSED\"`).\n  - `workspace\u002F.mantis_state.json` (to track current loop pass).\n  - `workspace\u002F.mantis_state.json` `active_snapshot` (`root`, `snapshot_id`,\n    `snapshot_pinned`) — resolved via Block A; supplies CODE_ROOT and the\n    SNAPSHOT_ID used by the Snapshot Match Check when no `--snapshot_*` flag is\n    passed.\n  - Target source code files.\n  - Reproducer script path (`repro_file_path`) and command (`run_command`) from\n    findings.\n  - Pre-existing backup files matching finding ID (if Option B is used).\n- **Writes**:\n  - Source code modifications (applied transactionally and rolled back).\n  - Updates finding JSON files in-place (sets `\"patch_status\"`, `\"patch_diff\"`,\n    re-attack details including `\"reattack_status\"` and `\"reattack_variants\"`,\n    and history).\n  - Appends to `workspace\u002Flearnings.jsonl`.\n  - Reusable helper script `workspace\u002Fhelpers\u002Fappend_patch.py`.\n- **Preconditions**:\n  - Findings must exist in `workspace\u002Ffindings\u002F`.\n- **Idempotency Guarantee**:\n  - **Snapshot-aware skip:** Skips a finding whose `patch_status` is already\n    `\"VERIFIED_SECURE\"` or `\"MITIGATION_PROPOSED\"` ONLY when its recorded\n    `patch_base_snapshot` equals the current SNAPSHOT_ID (i.e. it was verified\n    against THIS snapshot). If `patch_base_snapshot` is absent, empty, or\n    different from the current SNAPSHOT_ID, the terminal status is stale — do\n    NOT skip; re-open and re-verify the finding against the current snapshot. In\n    legacy mode (no `active_snapshot` and no `--snapshot_*` flags) skip exactly\n    as today (by `patch_status` alone).\n  - Transactional isolation: modifies code inside uniquely generated temporary\n    directories or creates temporary file backups (`target.c.bak-[id]`),\n    restoring baseline state upon completion (using `try...finally` rollback\n    mechanisms).\n  - Reuses the existing `append_patch.py` script once created.\n\n## Instructions\n\nFix successfully reproduced security flaws without breaking standard code\nbehavior.\n\nExecute the patching and verification stage as follows:\n\n0. **Snapshot & Locator Resolution (run once, before touching any code):**\n\n   0a. Resolve CODE_ROOT, SNAPSHOT_ID, snapshot_pinned, and state_root via\n   **Block A** (Locator Resolution):\n\n   ```\n   LOCATOR RESOLUTION (before reading ANY target code or artifact):\n   0. ROLE: If this skill NEVER reads target source (report, calibrate, reflect),\n      you are a FINDINGS-ONLY stage: skip steps 2-6; still read active_snapshot from\n      state for provenance\u002Fannotation; NEVER stop merely because a code root is unset.\n   1. Determine CODE_ROOT, in this priority order:\n      a. If --target_root is passed on THIS invocation, CODE_ROOT = --target_root.\n         It is AUTHORITATIVE and OVERRIDES SNAPSHOT_ROOT and the state fallback\n         (used when a caller hands you a prepared tree, e.g. a patched shadow).\n      b. Else if --snapshot_root (or SNAPSHOT_ROOT) is passed, use it.\n      c. Else read state_root\u002Fworkspace\u002F.mantis_state.json (state_root from\n         --state_root if passed, else .\u002Fworkspace\u002F... relative to the current dir)\n         -> active_snapshot.root \u002F .snapshot_id \u002F .snapshot_pinned.\n      d. Else (no arg AND no readable active_snapshot): CODE_ROOT = current directory,\n         treat snapshot_pinned = false (MODE-OFF). Do NOT stop.\n   2. SENTINEL CHECK (only if snapshot_pinned is true AND you did NOT take path 1a):\n      verify CODE_ROOT\u002F.mantis_snapshot_id exists and equals SNAPSHOT_ID. If missing\n      or different -> STOP \"snapshot sentinel mismatch\". (A --target_root tree (1a) is\n      deliberately mutated and is sentinel-EXEMPT.)\n   3. PATH FIELDS:\n      - SNAPSHOT-RELATIVE (read under CODE_ROOT): code_paths entries; plan target_files\n        that are file paths. Strip ONLY a trailing \":\u003Cdigits>\". A code_paths entry\n        containing \":\u002F\u002F\" is a URL\u002Fendpoint, NOT a file read. A code_paths entry that is\n        NOT of the form \u003Cexisting-path>:\u003Cinteger> is a non-source LOCATOR\n        (symbol\u002Foffset\u002Fendpoint): only check that the artifact\u002Fsymbol exists; skip ALL\n        line-range and line-existence logic.\n      - STATE-RELATIVE (read\u002Fwrite under state_root\u002Fworkspace, NEVER prefix CODE_ROOT):\n        kb_references, repro_file_path, reattack_file_path, helper scripts, report\n        files, and all state\u002Ffindings JSON.\n   4. Never WRITE under CODE_ROOT when snapshot_pinned is true. Any command that\n      compiles, generates, or writes artifacts MUST run in a PRIVATE SHADOW copy\n      (mktemp -d from CODE_ROOT), never with cwd=CODE_ROOT. Read-only inspection may\n      cd into CODE_ROOT.\n   5. VCS-METADATA CARVE-OUT: history-log extraction and any VCS diff\u002Fblame command\n      run in the LIVE repository root (which still has .git\u002F.hg\u002F.repo), NOT CODE_ROOT\n      (the snapshot copy strips VCS metadata). Do NOT stop merely because CODE_ROOT\n      lacks .git\u002F.hg\u002F.repo.\n   6. Every shell command uses ABSOLUTE paths and sets its own working directory on\n      that call. Do NOT assume the working directory persists between calls.\n   ```\n\n   > [!NOTE] **CURRENT-PASS CHECK (defensive; the binding guarantee is on the\n   > harness per `mantis-pipeline-adapter` Scenario 2):** if `active_snapshot`\n   > is present AND `active_snapshot.pass != state.pass_number`, treat the\n   > snapshot as STALE for this pass — STOP \"stale active_snapshot: pass\n   > mismatch\" or degrade as HALT (`snapshot_pinned` effectively false: no\n   > authoritative verdicts, Block B NOT_MATCHED, reproduce `not_attempted`).\n   > This catches a custom harness that preserved `active_snapshot` across the\n   > Stage 15 pass increment without re-pinning. The reference meta-agent\n   > re-pins every pass, so this check never fires there. Block B itself cannot\n   > detect this (it is `snapshot_id`-only, not `pass`-aware).\n\n   For this stage: mantis-patch READS target code (it is NOT a findings-only\n   stage), so it runs Block A steps 1–6 in full. CODE_ROOT is the immutable\n   pinned snapshot; you MUST NOT write, compile, or run reproducers under it\n   (Block A step 4) — do all mutation in a private shadow (step 2 below).\n\n   0b. Determine PATCH_MODE (mechanical, using the resolved values):\n\n   - `active_snapshot` absent AND no `--snapshot_root`\u002F`--snapshot_id`\u002F\n     `--target_root` passed ⇒ **LEGACY mode** (today's behavior; the new\n     ceilings in step 3 do NOT fire).\n   - `snapshot_pinned == true` ⇒ **PINNED mode** (full gates below apply).\n   - `snapshot_pinned == false` AND SNAPSHOT_ID begins with the literal `live:`\n     ⇒ **HALT\u002FDEGRADED mode** (a snapshot was attempted but could not be pinned;\n     authoritative verdicts are forbidden this pass — see step 3).\n\n   0c. For each finding you process, compute its MATCHED\u002FNOT_MATCHED result via\n   **Block B** (Snapshot Match Check):\n\n   ```\n   SNAPSHOT MATCH CHECK for finding F (decides MATCHED vs NOT_MATCHED):\n   1. If snapshot_pinned is false -> NOT_MATCHED. Stop.\n   2. Read F.discovery_commit:\n      - missing OR empty OR the literal \"MIXED\" -> NOT_MATCHED.\n      - not exactly equal to SNAPSHOT_ID          -> NOT_MATCHED.\n      - exactly equal to SNAPSHOT_ID              -> MATCHED.\n   There is no other route to MATCHED; never fuzzy-compare. The global \"default the\n   field and proceed\" backward-compat rule does NOT apply to discovery_commit:\n   absent = NOT_MATCHED. (There is NO separate \"dirty\" gate: a dirty tree's\n   SNAPSHOT_ID already embeds the working-tree content hash, so within-pass findings\n   MATCH and cross-pass bare-commit findings do not.)\n   ```\n\n   The MATCHED\u002FNOT_MATCHED result is consumed in step 2 (isolation-mode choice)\n   and step 3 (verdict). It never on its own downgrades a verdict in PINNED\n   mode: a NOT_MATCHED finding is RE-verified against the current snapshot via\n   the step-3 gate and, if it passes, is stamped with the current\n   `patch_base_snapshot`.\n\n1. **Load Findings to Patch:** Read the JSON files in the `workspace\u002Ffindings\u002F`\n   directory. Filter for findings that are NOT already terminally verified\n   AGAINST THE CURRENT SNAPSHOT — i.e. treat a finding as still-to-process\n   unless its `patch_status` is `\"VERIFIED_SECURE\"` or `\"MITIGATION_PROPOSED\"`\n   **and** its `patch_base_snapshot` equals the current SNAPSHOT_ID (Snapshot &\n   Locator Resolution step 0). A terminal finding whose `patch_base_snapshot` is\n   absent\u002Fempty\u002Fdifferent is STALE — include it for re-verification. (In LEGACY\n   mode, where there is no SNAPSHOT_ID, fall back to filtering on `patch_status`\n   alone, exactly as before.) Among the included findings, keep those where\n   (either `repro_status` is `\"reproduced\"` OR the finding is an exploit chain,\n   e.g., the title starts with `\"Exploit Chain:\"`, or history has an entry from\n   the `\"chainer\"` stage, or the `\"constituent_findings\"` property is present\n   and non-empty). If none exist, notify the user.\n\n2. **Generate and Apply Minimal Patches:** For each reproduced security flaw:\n\n   - **Target Agnosticism (Binaries vs Source):** If the target is source code,\n     proceed with generating and applying a code patch as described below. If\n     the target is a compiled binary or firmware blob without source code\n     available, **do not attempt to modify the binary or write binary patching\n     scripts**. Instead, skip the branch isolation\u002Fmodification\u002Fdiff steps and\n     generate a general, high-level recommendation for how this issue could be\n     mitigated in a production environment without requiring deep technical\n     depth. Output this mitigation string in place of the `patch_diff` field,\n     and set `\"patch_status\"` to `\"MITIGATION_PROPOSED\"`.\n\n   - **Exploit Chains:** If the finding is an exploit chain (identified by\n     `\"Exploit Chain:\"` in the title, or history details, or if the\n     `\"constituent_findings\"` property is present and non-empty), do **not**\n     generate a code patch or diff. Instead, identify its sub-findings by\n     reading the `\"constituent_findings\"` array of UUIDs. Monitor the patch\n     status of these constituent findings (listed on disk as\n     `workspace\u002Ffindings\u002F\u003Cuuid>.json`). **Important:** Defer evaluating exploit\n     chains until all individual findings in the batch have been processed, so\n     that the latest patch statuses of their constituents are available on disk.\n\n     Evaluate the exploit chain status using these propagation rules (evaluated\n     in order):\n\n     1. **Validity Check:** Read the validity `\"status\"` of each constituent\n        finding. If any constituent's `\"status\"` is `\"FALSE_POSITIVE\"`, update\n        the exploit chain finding's `\"status\"` to match it (e.g.\n        `\"FALSE_POSITIVE\"`) and immediately skip any further\n        patching\u002Fverification for the chain. If any constituent's `\"status\"` is\n        `\"DUPLICATE\"`, resolve it to its canonical finding by recursively\n        following its `\"duplicate_of\"` property.\n\n        **Duplicate Resolution Process:**\n\n        1. **Locate the Finding File:** The finding file for the duplicate (or\n           any parent in the duplicate chain) may have been moved. Search for\n           `\u003Cuuid>.json` in the following locations in order:\n           - `workspace\u002Ffindings\u002F\u003Cuuid>.json` (active findings)\n           - `workspace\u002Ffindings\u002F.trash\u002F\u003Cuuid>.json` (de-duplicated trash)\n           - `workspace\u002Farchive\u002Ffindings_pass_*\u002F\u003Cuuid>.json` or\n             `workspace\u002Farchive\u002Floop*_findings\u002F\u003Cuuid>.json` (archives from\n             previous passes) If the file cannot be found in any of these\n             locations, treat it as a missing file error.\n        2. **Cycle Detection:** Maintain a set of visited finding UUIDs during\n           the resolution. If you encounter a UUID that has already been visited\n           in the current resolution chain, raise a validation error (cycle\n           detected).\n        3. **Maximum Depth:** Limit the recursion depth to a maximum of 5 steps.\n           If the chain is deeper, abort and report an error.\n        4. **Extract Status:** Once you resolve to the canonical finding (one\n           whose `\"status\"` is not `\"DUPLICATE\"` or does not have\n           `\"duplicate_of\"`), use that canonical finding's `\"status\"` and\n           `\"patch_status\"` for all downstream checks and propagation. Do not\n           update the exploit chain finding itself to `\"DUPLICATE\"`.\n\n     2. **Missing Files:** If any constituent finding's JSON file is missing\n        from the disk, set the chain's `\"patch_status\"` to `\"ERROR\"`.\n\n     3. **Constituent Unset or Stale (Pending):** A constituent counts as\n        NOT-YET-VERIFIED if EITHER its `\"patch_status\"` is unset (null or\n        missing, indicating it has not yet been reproduced\u002Fprocessed) OR its\n        `\"patch_status\"` is terminal but its `patch_base_snapshot` is\n        absent\u002Fempty\u002Fdifferent from the current SNAPSHOT_ID (verified against a\n        stale snapshot — Snapshot & Locator Resolution step 0). If ANY\n        constituent is NOT-YET-VERIFIED, the chain's `\"patch_status\"` must\n        remain unset (null or missing) and you must defer\u002Fsuspend further\n        evaluation of the chain until that constituent is re-verified on the\n        current snapshot. (In LEGACY mode, where there is no SNAPSHOT_ID, apply\n        only the \"unset\" half of this rule, exactly as before.)\n\n     4. **Constituent Errors:** If any constituent's `\"patch_status\"` is\n        `\"ERROR\"`, set the chain's `\"patch_status\"` to `\"ERROR\"`.\n\n     5. **Constituent Failures:** If any constituent's `\"patch_status\"` is\n        `\"VERIFICATION_FAILED\"`, set the chain's `\"patch_status\"` to\n        `\"VERIFICATION_FAILED\"`.\n\n     6. **Successful Propagation:** If all constituents have finished\n        verification AGAINST THE CURRENT SNAPSHOT (each is in\n        `{\"VERIFIED_SECURE\", \"MITIGATION_PROPOSED\", \"VERIFICATION_INCOMPLETE\"}`\n        AND — except in LEGACY mode — each terminal constituent's\n        `patch_base_snapshot` equals the current SNAPSHOT_ID):\n\n        - If any constituent is `\"MITIGATION_PROPOSED\"`, set the chain's\n          `\"patch_status\"` to `\"MITIGATION_PROPOSED\"`.\n        - If no constituent is `\"MITIGATION_PROPOSED\"` and any constituent is\n          `\"VERIFICATION_INCOMPLETE\"`, set the chain's `\"patch_status\"` to\n          `\"VERIFICATION_INCOMPLETE\"`.\n        - If all constituents are `\"VERIFIED_SECURE\"`, set the chain's\n          `\"patch_status\"` to `\"VERIFIED_SECURE\"`.\n\n     Skip branch isolation, testing, and re-attack steps for the chain finding\n     itself.\n\n   - *Optional Parallel Trajectory Search:* If your framework supports\n     subagents, you may spawn multiple concurrent subagents to design diverse\n     patch implementations. Test all generated patches that successfully secure\n     the code without breaking standard functionality, and select the *best*\n     patch (e.g., the most minimal, readable, and idiomatic fix) rather than\n     just the first one that works.\n\n   - Read the original flawed file to grasp function dependencies and\n     structures.\n\n   - Design a minimal, correct patch to mitigate the security flaw (e.g. adding\n     bound checks, validating sizes, inserting NUL-terminators) without breaking\n     other features.\n\n   - **Transactional Isolation (VCS-Agnostic & Safe):** To ensure safety,\n     reliability, and VCS-agnosticism, do NOT use VCS-based branch operations\n     (such as `git branch`, `git checkout`, or `git stash`).\n\n     You must ensure transactional isolation using a method appropriate for the\n     operating environment. **Isolation-method gate (mechanical):**\n\n     - If snapshot_pinned is true (PINNED mode) → **Option A (Temporary\n       Directory Shadowing) is MANDATORY. Option B and any method that writes\n       under CODE_ROOT are FORBIDDEN** (Block A step 4: never write under a\n       pinned snapshot).\n     - Else if the finding is a RETRY (it already carries a prior `\"patch\"`\n       history entry or a `patch_base_snapshot`) OR (PINNED mode AND its\n       Snapshot Match Check result is NOT_MATCHED) → **Option A is MANDATORY**\n       (do not risk editing a live tree that no longer matches the finding). The\n       `PINNED mode AND` qualifier on the NOT_MATCHED clause is essential: in\n       LEGACY mode (snapshot_pinned=false), Block B returns NOT_MATCHED for\n       every finding as an artifact of no snapshot, not as a signal of drift —\n       so NOT_MATCHED must only fire when it means \"the snapshot changed\"\n       (PINNED), not when it means \"no snapshot exists\" (LEGACY).\n     - Otherwise (snapshot_pinned is false AND first attempt — no prior\n       `\"patch\"` history entry and no `patch_base_snapshot`) you may choose\n       **Option A** (recommended), **Option B: File-Level Backups**, or\n       design\u002Fimplement **Option C: Alternative Isolation** (e.g., namespace\n       isolation, container volumes, or local sandboxes) as long as it fully\n       satisfies the invariants below. This covers both LEGACY and HALT mode\n       first-attempt findings (neither has a prior patch to protect, and neither\n       is in the PINNED read-only snapshot regime).\n\n     Whichever method you choose, you must guarantee these invariants:\n\n     1. **Zero Workspace Pollution**: No backup or intermediate build files left\n        in the original source tree.\n     2. **Concurrency Safety**: Isolation methods must not conflict with other\n        concurrent agents.\n     3. **Guaranteed Rollback**: Wrap all actions in error traps or\n        `try...finally` blocks to restore the original state on failure.\n\n     - **Option A: Temporary Directory Shadowing (Recommended \u002F mandatory when\n       pinned)**\n\n       - **Warning\u002FResource constraint:** For source trees larger than a few\n         hundred MB, or when many parallel patch workers share the host, and\n         ONLY when NOT in PINNED mode, you may prefer **Option B** (which\n         touches only the modified files) to avoid exhausting `\u002Ftmp` or memory.\n         In PINNED mode Option B is forbidden regardless of size (the snapshot\n         is read-only); if a full copy will not fit, do not fabricate a verdict\n         — see step 3 HALT handling.\n\n       - **Two-root copy:** Create a uniquely generated SHADOW_ROOT (e.g.\n         `mktemp -d` \u002F `tempfile.mkdtemp()`) OUTSIDE both CODE_ROOT and any\n         `\u002Fworkspace\u002F` path, then copy the relevant source tree **FROM\n         CODE_ROOT** (the snapshot resolved in Snapshot & Locator Resolution\n         step 0), NOT from an implicit cwd, into SHADOW_ROOT. CODE_ROOT stays\n         untouched and read-only.\n\n       - Perform all edits, compilation, and reproduction testing inside\n         SHADOW_ROOT. Never run a mutating\u002Fcompiling\u002Freproducing command with\n         cwd = CODE_ROOT (Block A step 4).\n\n     - **Critical Guard (Path and Working Directory Safety):** You must ensure\n       that every command executed (compilation, testing, verification) runs\n       with its working directory (`Cwd`) explicitly set to SHADOW_ROOT. If the\n       finding's `run_command` contains absolute paths under CODE_ROOT (the\n       snapshot) or under the live source root, you must rewrite that prefix to\n       the corresponding path under SHADOW_ROOT before execution.\n\n       **Guard Check:** When performing path rewriting, only rewrite paths that\n       represent the target codebase files. If a path starts with or contains a\n       `\u002Fworkspace\u002F` segment (where the Mantis state and findings are stored),\n       do NOT replace its prefix (findings\u002Fstate must remain in the\n       authoritative `state_root\u002Fworkspace\u002F`). This separation is unambiguous\n       because a pinned SNAPSHOT_ROOT\u002FCODE_ROOT never contains a `\u002Fworkspace\u002F`\n       segment (guaranteed by the orchestrator's snapshot materialization). Do\n       not execute any modification or verification command against CODE_ROOT or\n       against `state_root\u002Fworkspace\u002F`.\n\n     - **{TARGET_ROOT} token substitution (MANDATORY before executing any stored\n       command):** `mantis-reproduce` stores\n       `run_command`\u002F`reattack_run_command` with the literal token\n       `{TARGET_ROOT}` for target-tree paths (Step 3 of reproduce), expecting\n       the caller to substitute it. Before executing any stored `run_command` or\n       `reattack_run_command`, replace the literal `{TARGET_ROOT}` token with\n       the tree being executed against:\n\n       - For the Block-G **unpatched baseline** run: substitute the fresh\n         unpatched CODE_ROOT copy (a fresh `mktemp -d` copy taken FROM\n         CODE_ROOT).\n       - For **post-patch verification** and **attack\u002Freattack** runs:\n         substitute SHADOW_ROOT (the patched shadow copy). This substitution\n         MUST happen BEFORE the CODE_ROOT→SHADOW_ROOT prefix rewriting above\n         (the token may expand to a CODE_ROOT path that then needs rewriting for\n         shadow runs). If the literal token survives unsubstituted, the command\n         will fail → evidence absent → forced ERROR (Block F\u002FBlock G treat\n         command-not-found \u002F No-such-file as EVIDENCE ABSENT). Never execute a\n         command containing the literal `{TARGET_ROOT}` token.\n\n     - Generate the unified patch diff by comparing the original source files in\n       CODE_ROOT (the pinned snapshot) with the modified files in SHADOW_ROOT.\n       Use labels so no CODE_ROOT\u002FSHADOW_ROOT absolute prefix leaks into the\n       diff headers.\n\n     - Delete the temporary shadow directory completely when finished.\n\n     - **Option B: File-Level Backups (Fallback)**\n\n       - **Concurrency & Exclusivity Warning:** Because Option B modifies files\n         directly in the original workspace, it is concurrency-unsafe when run\n         in parallel with other workspace-modifying agents. Sequential execution\n         must be strictly enforced via locking.\n       - **Exclusive Workspace Lock:** Before performing backups or edits, the\n         agent **must** acquire an exclusive lock on\n         `workspace\u002F.workspace_edit.lock` (using `fcntl.flock` with\n         `fcntl.LOCK_EX` in Python, or a similar system-level lock). The agent\n         **must** hold this lock continuously throughout the entire patching,\n         verification, re-attack, and restoration lifecycle for the finding,\n         releasing it only when final baseline files are restored or finalized.\n       - **Pre-execution Check:** Prior to editing, scan the workspace for\n         pre-existing backup files matching the current finding's ID (e.g.,\n         `*.bak-[current_finding_id]`). If found, restore and delete them.\n       - **Create Backups:** For every source file you intend to modify, create\n         a copy with a unique suffix (e.g.,\n         `cp target.c target.c.bak-[finding_id]`).\n       - **Net-New Files:** Track any newly created files to delete them on\n         rollback.\n       - **Apply Modifications:** Edit original target files directly.\n       - **Generate Unified Diff:** Compare backup against modified file using\n         labels to normalize headers (e.g.,\n         `diff -u --label target.c --label target.c target.c.bak-[finding_id] target.c`).\n\n   - **3-Way Patch Rebasing (Phase 2 incremental efficiency):** When a prior\n     pass's snapshot and patch are still present on disk (see the reachability\n     check below), the patcher can attempt to REBASE a prior pass's patch onto\n     the current snapshot instead of generating a fresh patch from scratch. This\n     is an optimization for the common case where a prior fix still applies with\n     minor line-number shifts.\n\n     - **How:** If ALL reachability conditions (a)-(d) below hold, read\n       [3-Way Patch Rebasing](references\u002Fpatch_rebasing.md) with your\n       file-reading tool for the 3-way merge mechanics (`base`\u002F`ours`\u002F`theirs`\n       scratch copies, `git merge-file` \u002F `diff3` invocation, conflict-marker\n       handling). On ANY uncertainty or if the reference cannot be loaded, fall\n       back to fresh patch generation (Phase-1 behavior).\n     - **When to use (reachability by OBSERVABLE state, not a flag the patcher\n       cannot read):** attempt rebasing ONLY when ALL hold: (a) the prior pass's\n       snapshot directory AND the file's prior unpatched version actually EXIST\n       on disk under `\u003Cstate_root>\u002F.mantis_snapshots\u002F` (retention kept them; if\n       the base snapshot was GC'd this fails → fall back); (b) the finding's\n       `signature` matches an archived finding with a prior `patch_diff` (same\n       bug, same signature) — this is the ARCHIVED finding referenced by the\n       remaining gates; (c) the ARCHIVED finding's `patch_base_snapshot` is\n       present and DIFFERENT from the current `SNAPSHOT_ID` (the snapshot the\n       prior patch was verified against has changed; this is the correct\n       \"snapshot changed\" test — do NOT test Block B on the CURRENT finding,\n       whose `discovery_commit` is always `== SNAPSHOT_ID` in PINNED mode\n       because researcher stamps it, dedupe backfills it, and plan only\n       copy-verbatim's MATCHED findings preserving the original\n       `discovery_commit`); if the archived finding's `patch_base_snapshot` is\n       ABSENT or EMPTY (legacy prior pass, or a pre-Phase-2 patcher that did not\n       write it — detected by the helper-version marker at step 6), the\n       snapshot-changed test is UNKN and you MUST fall back to fresh patch\n       generation (do NOT rebase onto a possibly-unchanged base); and (d) the\n       finding's primary file is in `changed_files`. If `signature` is absent\n       (legacy finding), condition (b) cannot be satisfied — fall back to fresh\n       patch generation. Do NOT gate on `--snapshot_keep`: that flag is set on\n       the orchestrator and is NOT passed to or readable by the patch stage; the\n       on-disk presence check (a) is the correct observable substitute and works\n       under any retention setting (the default keep-2 already retains the\n       immediately-prior pass). `changed_files` and `changed_files_status` are\n       read from `workspace\u002F.mantis_state.json` (the same state object read for\n       `active_snapshot`).\n\n   - **When rebasing SUCCEEDS \u002F FAILS \u002F Guardrail:** See\n     [3-Way Patch Rebasing](references\u002Fpatch_rebasing.md) for the success (clean\n     merge → use rebased patch, still run Block G, history note\n     `patch-rebased-from: pass_\u003CN-1>`), failure (merge conflict \u002F file deleted \u002F\n     renamed → fall back to fresh patch generation), and guardrail (on ANY\n     uncertainty, fall back to Phase-1; never apply a rebased patch with\n     unresolved conflicts or unrelated changes).\n\n   - **Unpatched-Baseline Re-run in `--reattack` (Phase 2):** When the\n     `@mantis-reproduce --reattack` sub-agent is re-attacking a patch on a NEW\n     snapshot (Block B NOT_MATCHED, meaning the snapshot changed since the patch\n     was verified — in PINNED mode only), the re-attack MUST first re-establish\n     the unpatched baseline on the CURRENT snapshot before testing the attack\n     against the patched build. This ensures the re-attack is meaningful: if the\n     bug no longer triggers on the current unpatched snapshot (e.g., upstream\n     code fixed it), the re-attack result is inconclusive, not a pass.\n\n     - **How:** Before running the attack on the patched shadow, run the\n       reproducer against a FRESH UNPATCHED copy of the current snapshot (per\n       Block G step 1). If the unpatched baseline does NOT trigger (evidence\n       absent), set `reattack_status = \"inconclusive_baseline_changed\"` with a\n       history note, and do NOT claim `failed_to_bypass` (the patch was not\n       tested against a live bug). If the unpatched baseline DOES trigger,\n       proceed with the attack on the patched build as normal.\n     - **HALT-mode note:** In HALT mode (`snapshot_pinned=false`, `live:`\n       SNAPSHOT_ID), Block B is always NOT_MATCHED, but this does NOT represent\n       a genuine snapshot change — it means the tree couldn't be pinned. The\n       `@mantis-reproduce --reattack` sub-agent skips the C5 re-baseline in HALT\n       (see reproduce C5 HALT guardrail) and follows the existing HALT ceiling.\n     - **Guardrail:** This does NOT change the VERIFIED_SECURE gate — Block G\n       still requires the unpatched baseline to trigger. This only adds a\n       re-baseline step to the re-attack path when the snapshot changed.\n\n3. **Post-Patch Verification Run:** *(Skip this step for binary-only targets\n   where no code patch was applied)*. To confirm the patch works, re-run the\n   reproducer script inside your isolated execution environment. Use the exact\n   `\"repro_file_path\"` and `\"run_command\"` from the reproduction entry to verify\n   the patch.\n\n   - **Cwd Enforcement:** You must execute the reproducer script with the\n     working directory (`Cwd`) set to the shadow directory (if using Option A).\n     Ensure the command targets the copy in the shadow directory, not the\n     original workspace.\n\n   - **Reached-sink evidence definition** — **Block F** (Reached-Sink Evidence\n     Gate). In patch verification the evidence is required on the UNPATCHED\n     baseline, never on the post-patch attack run (a correct patch legitimately\n     stops the input before the sink):\n\n     ```\n     REACHED-SINK EVIDENCE GATE (mechanical):\n     Each reproducer produces REACHED-SINK EVIDENCE via ONE channel, recorded in repro_hints:\n        (a) script\u002Fsource harness -> write the exact bytes MANTIS_REACHED_ENTRYPOINT to a\n            sidecar file $SENTINEL_FILE and flush+fsync (or unbuffered write) BEFORE\n            invoking the sink. (A file survives a crash that truncates buffered stdout.)\n        (b) binary \u002F firmware \u002F raw-payload -> reached-sink evidence is a captured\n            crash backtrace or sanitizer frame (ASan\u002FUBSan\u002FMSan\u002FTSan) that\n            explicitly names the target sink function (target-produced tracing). A\n            marker written by a wrapper you author BEFORE invoking the target is\n            SETUP EVIDENCE ONLY: it proves \"launch attempted,\" not \"sink reached,\"\n            and does NOT qualify as reached-sink evidence. If no in-path marker\n            (channel a) and no target-produced backtrace\u002Fsanitizer trace\n            (channel b) is achievable, the sink is unreached.\n      EVIDENCE PRESENT (reached-sink) = (channel a) sidecar file contains\n        MANTIS_REACHED_ENTRYPOINT written in-path, OR (channel b) target-produced\n        backtrace\u002Fsanitizer output names the sink. A wrapper pre-launch marker alone is\n        NOT evidence present.\n     EVIDENCE ABSENT includes: any compiler\u002Fbuild nonzero exit; exit 127 (command not\n       found); exit 2 with a \"No such file\" message.\n     DECISION GATE (gate the DECISION, not specific verdict strings):\n       - Record repro_status = reproduced OR statically_confirmed ONLY if EVIDENCE is\n         PRESENT. If ABSENT -> repro_status = not_attempted (retry-eligible), STOP.\n       - In patch verification, EVIDENCE is required on the UNPATCHED baseline (Block G),\n         NOT on the post-patch attack run (a correct patch legitimately stops the input\n         before the sink).\n       - If NO evidence channel is achievable for this target, downgrade to\n         not_attempted \u002F VERIFICATION_INCOMPLETE. NEVER synthesize the marker.\n     ```\n\n   - **Hard gate before any `VERIFIED_SECURE`** — **Block G**\n     (Unpatched-Baseline + Benign-Control Gate). Run it inside SHADOW copies of\n     CODE_ROOT; the \"FRESH UNPATCHED copy of SNAPSHOT_ROOT\" in Block G step 1\n     means a fresh copy taken FROM CODE_ROOT:\n\n     ```\n     UNPATCHED-BASELINE + POST-PATCH GATE (before any VERIFIED_SECURE):\n     0. APPLICABILITY: applies ONLY when repro_status == reproduced (a runnable PoC\n        exists). If repro_status == statically_confirmed (no runnable PoC),\n        VERIFIED_SECURE is NOT applicable -> record MITIGATION_PROPOSED (NEVER ERROR).\n     1. UNPATCHED BASELINE: run the reproducer against a FRESH UNPATCHED copy of\n        SNAPSHOT_ROOT using Block F. If evidence ABSENT or the bug does NOT trigger ->\n        patch_status = ERROR (\"reproducer_invalid_on_current_snapshot\"); do NOT set\n        VERIFIED_SECURE.\n     2. POST-PATCH INTEGRITY (distinguish \"blocked by patch\" from \"build break\"):\n        - REQUIRED: the patched build must COMPILE with exit 0. Nonzero ->\n          VERIFICATION_INCOMPLETE.\n        - REQUIRED (benign control): run a legitimate BENIGN (non-attack) input through\n          the patched build; it MUST reach the sink path (EVIDENCE PRESENT via Block F)\n          with no crash. This proves the patch narrowed the bug rather than breaking the\n          harness\u002Fentrypoint. If NO benign control can be constructed for this target,\n          you may NOT claim VERIFIED_SECURE on a clean-run-only basis -> land\n          VERIFICATION_INCOMPLETE and record why the benign control was infeasible.\n          (Strict mode: a clean compile + clean run WITHOUT a benign control reaching\n          the sink is never sufficient for VERIFIED_SECURE.)\n     3. ATTACK ON PATCH: run the attack input through the patched build. VERIFIED_SECURE\n        requires ALL of: step 1 triggered on unpatched (evidence present), step 2\n        integrity holds, step 3 attack does NOT crash\u002Ftrigger, AND the `--reattack` run\n        also fails to bypass. Otherwise VERIFICATION_FAILED.\n     ```\n\n     **Sanitizer consistency guardrail (Block G):** All runs in this gate\n     (unpatched baseline, benign control, attack, and re-attack) MUST use the\n     SAME sanitizer flags that made the unpatched baseline trigger. If the\n     baseline triggered via UBSan (exit 0, recover-mode), the attack run must\n     also be compiled with UBSan — otherwise the attack might exit 0 without a\n     trace even though the bug is still present, producing a false\n     `VERIFIED_SECURE` (INV-1 violation). Record the sanitizer flags used in\n     `repro_hints` so downstream stages replicate them.\n\n   - **HALT\u002FDEGRADED ceiling:** If PATCH_MODE is HALT\u002FDEGRADED (snapshot_pinned\n     false with a `live:` SNAPSHOT_ID), authoritative verdicts are forbidden\n     this pass: the best attainable `patch_status` is\n     `\"VERIFICATION_INCOMPLETE\"`. Never emit `\"VERIFIED_SECURE\"` in this mode.\n     (LEGACY mode is unaffected.)\n\n   - **Missing-file rule:** If the reproducer file (`repro_file_path`) or a\n     `code_paths` target file cannot be found when you attempt verification, set\n     `patch_status` to `\"ERROR\"`. NEVER treat a missing file as \"did not\n     reproduce\" and NEVER emit `\"VERIFIED_SECURE\"` from a missing file. (This is\n     also what Block F\u002FBlock G's \"No such file\"\u002F`exit 127` → EVIDENCE ABSENT\n     path enforces.)\n\n   * **VERIFIED SECURE (all conditions REQUIRED):** Mark `patch_status` as\n     `\"VERIFIED_SECURE\"` ONLY if ALL of the following hold:\n\n     1. **Block G passes in full:** the UNPATCHED baseline triggered the bug\n        WITH reached-sink evidence (Block F) on a fresh copy of CODE_ROOT; the\n        patched build compiled (exit 0); the benign\u002Fintegrity control held; and\n        the attack input on the patched build does NOT crash\u002Ftrigger.\n     2. **Re-attack fails to bypass:** a fresh, independent\n        `@mantis-reproduce --reattack` sub-agent (spawned per the block below)\n        writes `reattack_status = \"failed_to_bypass\"` — meaning a non-empty\n        `reattack_variants` array with ≥ 3 valid variant inputs (reproduce Step\n        3a) ALL failed to trigger the original vulnerability class on the\n        patched shadow. An empty or short variant set caps at\n        `VERIFICATION_INCOMPLETE`, never `VERIFIED_SECURE`.\n     3. **Not degraded:** PATCH_MODE is not HALT\u002FDEGRADED. If PATCH_MODE is\n        HALT\u002FDEGRADED (snapshot mismatch \u002F unpinnable snapshot), the ceiling is\n        `\"VERIFICATION_INCOMPLETE\"`, never `\"VERIFIED_SECURE\"`. If Block G\n        reports its baseline could NOT be established (evidence absent or bug\n        does not trigger on the current unpatched snapshot), set `patch_status`\n        to `\"ERROR\"` (`\"reproducer_invalid_on_current_snapshot\"`) — do NOT emit\n        `\"VERIFIED_SECURE\"`. If Block G's applicability check found\n        `repro_status == statically_confirmed`, record `\"MITIGATION_PROPOSED\"`\n        (never ERROR). To ensure true independence, launch a fresh\n        `@mantis-reproduce --reattack --finding_id=[finding_id]` sub-agent\n        against the PATCHED shadow (a copy of SHADOW_ROOT after your patch is\n        applied) to perform the re-attack.\n\n     **Important:** When calling the `@mantis-reproduce` subagent for the\n     re-attack:\n\n     - If using **Option A (Shadowing)** (always, in PINNED mode), pass:\n       - `--reattack`\n       - `--target_root=\u003CPATCHED_SHADOW_ROOT>` — the shadow copy that contains\n         your applied patch. Because `--target_root` is AUTHORITATIVE and\n         sentinel-EXEMPT (Block A step 1a\u002F2), the sub-agent reads the patched\n         tree directly.\n       - `--snapshot_pinned=false` — the patched shadow is deliberately mutated,\n         so the reproduce sub-agent MUST skip the snapshot sentinel\u002Fmatch check\n         for it.\n       - `--state_root=\u003Cstate_root>` — your authoritative state directory (so\n         all `reattack_*` fields and history land under\n         `state_root\u002Fworkspace\u002F`).\n       - `--finding_id=[finding_id]` of the finding being verified.\n     - If using **Option B (Backups)** or **Option C (Alternative)** (only\n       possible in LEGACY mode), pass `--reattack`, both roots pointing at the\n       live workspace (or leave them default `.`), and\n       `--finding_id=[finding_id]`.\n\n     The reproducer agent running with `--reattack` will write its outcomes\n     directly into the primary finding's `reattack_status`,\n     `reattack_file_path`, `reattack_run_command`, and `reattack_output` fields\n     inside the original workspace findings (`state_root\u002Fworkspace\u002Ffindings\u002F`),\n     keeping the initial `repro_*` fields untouched.\n\n   * **VERIFICATION FAILED:** If the sandbox execution still triggers the bug,\n     or if your re-attack successfully bypasses your patch, the patch is\n     insufficient. Re-evaluate and adapt your fix.\n\n   * **VERIFICATION INCOMPLETE:** If the initial post-patch verification run\n     passed but the subsequent re-attack checks failed\u002Ftimed out due to sandbox\n     infrastructure errors, environment timeouts, or platform restrictions, set\n     `\"patch_status\"` to `\"VERIFICATION_INCOMPLETE\"`.\n\n   * **Re-attack unset \u002F SNAPSHOT_MISMATCH → VERIFICATION_INCOMPLETE:** If\n     `reattack_status` is unset (the re-attack sub-agent left it unset with a\n     `SNAPSHOT_MISMATCH` or `setup_failed` history note, or the re-attack did\n     not run at all), set `patch_status` to `\"VERIFICATION_INCOMPLETE\"` — never\n     `VERIFIED_SECURE`. An unset re-attack status means independence was not\n     confirmed; a `SNAPSHOT_MISMATCH` means the re-attack ran against a\n     different snapshot than the patch was verified on. In either case the patch\n     is not conclusively verified.\n\n   * **Inconclusive baseline → VERIFICATION_INCOMPLETE:** If `reattack_status`\n     is `\"inconclusive_baseline_changed\"` (the re-attack sub-agent re-ran the\n     unpatched baseline on the current snapshot and the bug no longer triggers —\n     the baseline changed since the patch was verified), set `patch_status` to\n     `\"VERIFICATION_INCOMPLETE\"` (or `\"ERROR\"` with details\n     `\"reproducer_invalid_on_current_snapshot\"`) — never `\"VERIFIED_SECURE\"`.\n     The patch was not tested against a live bug on the current snapshot;\n     claiming it is secure would be a false authoritative verdict.\n\n4. **Extract Patch and Rollback Transaction:** *(Skip this step for binary-only\n   targets)*. Do not leave the codebase in an altered state. Once you have a\n   final outcome (either `VERIFIED_SECURE` or you have exhausted your retries):\n\n   - If successful, generate a unified diff representing your exact changes and\n     save it to the `\"patch_diff\"` field:\n     - If using **Option A (Shadowing)**, generate this diff by comparing the\n       original files in CODE_ROOT with the modified files in the shadow\n       directory.\n     - If using **Option B (Backups)**, generate this diff by comparing the\n       backup file to the modified file, explicitly labeling the headers to\n       prevent the backup suffix from appearing (e.g.,\n       `diff -u --label target.c --label target.c target.c.bak-[finding_id] target.c`).\n     - If using **Option C (Alternative)**, generate a clean, VCS-agnostic\n       unified diff comparing the unmodified baseline files to the final patched\n       files.\n     - If multiple files were modified, generate individual unified diffs and\n       concatenate them cleanly into the single `\"patch_diff\"` string. Do NOT\n       use VCS-specific diff commands.\n   - **Transactional Clean Up \u002F Rollback**: Restore the codebase to its original\n     state.\n     - If using **Option A (Shadowing)**, delete the temporary shadow directory\n       completely (e.g., `rm -rf \u003Cshadow_directory>`). Since the original\n       codebase was never modified, no further restoration is needed.\n     - If using **Option B (Backups)**, restore the original files by copying\n       the backup files back onto the target files (e.g.,\n       `cp target.c.bak-[finding_id] target.c`), delete the backup copies\n       (`rm target.c.bak-[finding_id]`), and delete any net-new files created\n       during the patching process. **Do NOT delete any re-attack\u002FPoC script\n       files written inside the `workspace\u002Freproducers\u002F` directory, any helper\n       scripts written inside the `workspace\u002Fhelpers\u002F` directory, or the memory\n       database file `workspace\u002Flearnings.jsonl`; these must be explicitly\n       preserved.**\n     - If using **Option C (Alternative)**, execute the corresponding teardown\n       or rollback steps to fully purge all modification artifacts, delete any\n       temporary resources, and ensure the original workspace is left in its\n       clean baseline state.\n\n5. **Append to Long-Term Memory (Continuous Reviewing Link):** For each security\n   flaw processed, append a single structured JSON line to a workspace database\n   file named `workspace\u002Flearnings.jsonl` (using append mode). This allows the\n   strategist (`\u002Fmantis-plan`) to read these historical records in subsequent\n   passes and avoid proposing fixes for already patched files.\n\n   - **Memory Entry Format:**\n     `{\"title\": \"[security_flaw_title]\", \"code_paths\": [\"[path1:line1]\"], \"status\": \"[VERIFIED_SECURE \u002F MITIGATION_PROPOSED \u002F VERIFICATION_INCOMPLETE \u002F VERIFICATION_FAILED \u002F ERROR]\", \"patch_base_snapshot\": \"[current SNAPSHOT_ID, or omit in LEGACY mode]\", \"snapshot\": \"[current SNAPSHOT_ID, or omit in MODE-OFF]\"}`\n\n6. **Token-Optimized File Updates:** To minimize LLM output tokens, **do not\n   re-emit or manually rewrite the entire JSON object in your output.** Instead,\n   write a reusable helper script (e.g.,\n   `state_root\u002Fworkspace\u002Fhelpers\u002Fappend_patch.py`) during your first finding\n   update. Make the FIRST line of the helper a version marker comment:\n   `# MANTIS_HELPER_VERSION = 2`. Before reusing an existing helper, read its\n   first line: if it does NOT contain the exact marker\n   `MANTIS_HELPER_VERSION = 2`, the helper is stale (from an older pass\u002Fversion\n   that does not write `patch_base_snapshot`) — regenerate it. Only when the\n   marker matches may you reuse it: simply execute the existing helper with the\n   new parameters to append the required fields.\n\n   You must append the following to the existing object:\n\n   - A `\"patch_status\"` field (one of `\"VERIFIED_SECURE\"`,\n     `\"MITIGATION_PROPOSED\"`, `\"VERIFICATION_INCOMPLETE\"`,\n     `\"VERIFICATION_FAILED\"`, or `\"ERROR\"`).\n   - A `\"patch_base_snapshot\"` field set to the current SNAPSHOT_ID (Snapshot &\n     Locator Resolution step 0) — the snapshot this verdict was earned on. Omit\n     this field only in LEGACY mode (no SNAPSHOT_ID exists). This is what makes\n     the snapshot-aware skip (Idempotency Guarantee) and chain propagation\n     correct across passes.\n   - If a patch was successful, a `\"patch_diff\"` field containing the unified\n     diff.\n   - If a re-attack was performed, the `\"reattack_status\"`,\n     `\"reattack_file_path\"`, `\"reattack_run_command\"`, `\"reattack_output\"`, and\n     `\"reattack_variants\"` fields (each object in `\"reattack_variants\"` MUST\n     have EXACTLY `{\"description\": \"...\", \"triggered\": true\u002Ffalse}`).\n   - An entry to the `\"history\"` array:\n\n   ```json\n   {\n     \"stage\": \"patch\",\n     \"action\": \"patched\",\n      \"details\": \"Patch status evaluated as [VERIFIED_SECURE\u002FMITIGATION_PROPOSED\u002FVERIFICATION_INCOMPLETE\u002FVERIFICATION_FAILED\u002FERROR] on snapshot [patch_base_snapshot or 'legacy']\",\n     \"pass_number\": \u003Ccurrent_pass_number>,\n     \"timestamp\": \"\u003Ccurrent_iso8601_timestamp>\"\n   }\n   ```\n\nWhen complete, notify the user.\n",{"name":5,"description":7},"main","f3162c039ecd9c9d5d8bc404dd1373c7ca3152f7","skills\u002Fmantis-patch",237,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis","https:\u002F\u002Fcloud.google.com\u002F","https:\u002F\u002Fgithub.com\u002Fgoogle","https:\u002F\u002Fopensource.google\u002F","Google ❤️ Open Source","2026-11-15 00:33:31",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add google\u002Fmantis --skill mantis-patch",{"tool":58,"command":59},"bunx","bunx skills add google\u002Fmantis --skill mantis-patch",{"tool":61,"command":62},"pnpm","pnpm dlx skills add google\u002Fmantis --skill mantis-patch","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-patch\u002FSKILL.md",true,[66],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fpatch_rebasing.md","REFERENCE","参考文档",2829,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-patch\u002Freferences\u002Fpatch_rebasing.md",[73,100,127,153,164,179],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":37},"01M6992XJHHV0R5N8E392EHRW3","mantis-threat-model","Synthesizes trust boundaries, attack surfaces, and attacker profiles into a living threat model. Use as Stage B of the Knowledge Base generation process, reading architecture and entity definitions from the KB. Don't use for analyzing source code or extracting raw learnings from JSONL files.","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-threat-model\u002FSKILL.md",[],[80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99],"mantis threat model","threat model","model","threat","architecture","code","analyzing","knowledge","kb","files","surfaces","trust","learnings","knowledge base","as","extracting","reading","jsonl","source","source code",{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":111,"publishedAt":37},"01M6992TR1BPA5HVF13QRM7EP0","mantis-summarize","Pre-processes the repository by generating security-focused summaries (mantis-summary.md) for each directory to make planning and research more efficient. Use when starting a review campaign to map the codebase before threat modeling and planning. Don't use for executing code reviews, writing test scripts, or patching code.","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-summarize\u002FSKILL.md",[106],{"categoryNo":107,"categoryName":108,"taxonomyType":109,"taxonomyTypeDesc":110},"01JBSEEDCAT000000000000021","资料检索与研究","SCENARIO","使用场景",[112,113,114,115,116,22,117,85,118,119,120,83,121,122,123,124,125,126,24,21],"summarize","mantis summarize","writing","directory","review","threat modeling","planning","repository","patching","campaign","map","modeling","scripts","make","reviews",{"skillNo":128,"name":129,"nameZh":6,"description":130,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":138,"publishedAt":37},"01M6992QB4DVMDR2AGT6BPSE3N","mantis-structural-index","Builds a content-addressed semantic-unit index from source code for structural context. Use when a pinned or live codebase is available and structural cross-reference data would improve research quality. Don't use for findings analysis, patching, or reporting.","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-structural-index\u002FSKILL.md",[133],{"categoryNo":134,"categoryName":135,"taxonomyType":136,"taxonomyTypeDesc":137},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[139,140,141,36,85,142,143,144,145,120,146,147,148,33,149,150,151,152,24,21],"mantis structural index","index","structural","content","reporting","data","analysis","improve","quality","context","research quality","reference","live","unit",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":37},"01M6992KRP2XYWEMV12P5M4GPE","mantis-review","Independently reviews findings and filters out false positives. Use when consolidated findings need validation against the actual source code. Don't use for reproducing crashes or patching code.","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-review\u002FSKILL.md",[],[116,160,85,161,120,33,162,163,126,24,98,99,21],"mantis review","validation","filters","false",{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":170,"publishedAt":37},"01M6992GKVGJ2NXEJWYFVCN01Q","mantis-researcher","Audits production source code files based on the strategy in workspace\u002Fplan.json. Use when a review plan exists and you need to perform static analysis and deep-dive reviews of targeted files. Don't use for planning, deduplicating, or writing patches.","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-researcher\u002FSKILL.md",[],[171,172,114,116,173,85,118,145,174,175,33,89,176,177,126,24,98,178,99,21],"mantis researcher","researcher","static analysis","plan","strategy","deep","you","static",{"skillNo":180,"name":181,"nameZh":6,"description":182,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":183,"categories":184,"keywords":185,"publishedAt":37},"01M6992D5WXENF3TW68GM5WPHC","mantis-reproduce","Generates and runs crash reproducers to verify security flaws. Use when viable findings exist and you need to write and execute a script or payload to verify the crash. Don't use for code auditing or patching.","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-reproduce\u002FSKILL.md",[],[186,187,22,85,120,188,189,190,33,191,32,192,177,24,21],"mantis reproduce","reproduce","verify","write","execute","crash","script"]