- name
- mantis-patch
- description
- 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.
# Patcher (/mantis-patch)
## System Goal
Security Patching Expert. Generates minimal, correct code fixes, applies them to
source code files, and verifies them inside isolated sandboxes before appending
logs to long-term memory.
## Command Definition
- **Command:**
`/mantis-patch [--target_root=<path>] [--state_root=<path>] [--snapshot_root=<path>] [--snapshot_id=<id>] [--snapshot_pinned=<true|false>]`
- **Description:** Generates minimal security fixes using transactional
isolation (shadow directories or file backups), applies patches, and verifies
them.
- **Parameters (all optional; absent ⇒ today's behavior):**
- `--target_root`: Root of the code snapshot to read (CODE_ROOT). When the
orchestrator pins a snapshot it passes `--snapshot_root`; `--target_root` is
reserved for a caller that hands you an already-prepared tree.
- `--snapshot_root`: Root of the pinned immutable snapshot for this pass.
- `--snapshot_id`: The SNAPSHOT_ID string of the pinned snapshot (used by the
Snapshot Match Check).
- `--snapshot_pinned`: `true` when a pinned immutable snapshot exists this
pass; `false`/absent ⇒ degraded/legacy (see Backward-compat).
- `--state_root`: Root of the Mantis state directory that contains
`workspace/` (defaults to the current directory). ALL `workspace/...` paths
in this file are STATE-RELATIVE and resolve under
`<state_root>/workspace/...`.
## Input/Output Contract
- **Reads**:
- `workspace/findings/` (reproduced finding JSON files where `patch_status` is
not `"VERIFIED_SECURE"` or `"MITIGATION_PROPOSED"`).
- `workspace/.mantis_state.json` (to track current loop pass).
- `workspace/.mantis_state.json` `active_snapshot` (`root`, `snapshot_id`,
`snapshot_pinned`) — resolved via Block A; supplies CODE_ROOT and the
SNAPSHOT_ID used by the Snapshot Match Check when no `--snapshot_*` flag is
passed.
- Target source code files.
- Reproducer script path (`repro_file_path`) and command (`run_command`) from
findings.
- Pre-existing backup files matching finding ID (if Option B is used).
- **Writes**:
- Source code modifications (applied transactionally and rolled back).
- Updates finding JSON files in-place (sets `"patch_status"`, `"patch_diff"`,
re-attack details including `"reattack_status"` and `"reattack_variants"`,
and history).
- Appends to `workspace/learnings.jsonl`.
- Reusable helper script `workspace/helpers/append_patch.py`.
- **Preconditions**:
- Findings must exist in `workspace/findings/`.
- **Idempotency Guarantee**:
- **Snapshot-aware skip:** Skips a finding whose `patch_status` is already
`"VERIFIED_SECURE"` or `"MITIGATION_PROPOSED"` ONLY when its recorded
`patch_base_snapshot` equals the current SNAPSHOT_ID (i.e. it was verified
against THIS snapshot). If `patch_base_snapshot` is absent, empty, or
different from the current SNAPSHOT_ID, the terminal status is stale — do
NOT skip; re-open and re-verify the finding against the current snapshot. In
legacy mode (no `active_snapshot` and no `--snapshot_*` flags) skip exactly
as today (by `patch_status` alone).
- Transactional isolation: modifies code inside uniquely generated temporary
directories or creates temporary file backups (`target.c.bak-[id]`),
restoring baseline state upon completion (using `try...finally` rollback
mechanisms).
- Reuses the existing `append_patch.py` script once created.
## Instructions
Fix successfully reproduced security flaws without breaking standard code
behavior.
Execute the patching and verification stage as follows:
0. **Snapshot & Locator Resolution (run once, before touching any code):**
0a. Resolve CODE_ROOT, SNAPSHOT_ID, snapshot_pinned, and state_root via
**Block A** (Locator Resolution):
```
LOCATOR RESOLUTION (before reading ANY target code or artifact):
0. ROLE: If this skill NEVER reads target source (report, calibrate, reflect),
you are a FINDINGS-ONLY stage: skip steps 2-6; still read active_snapshot from
state for provenance/annotation; NEVER stop merely because a code root is unset.
1. Determine CODE_ROOT, in this priority order:
a. If --target_root is passed on THIS invocation, CODE_ROOT = --target_root.
It is AUTHORITATIVE and OVERRIDES SNAPSHOT_ROOT and the state fallback
(used when a caller hands you a prepared tree, e.g. a patched shadow).
b. Else if --snapshot_root (or SNAPSHOT_ROOT) is passed, use it.
c. Else read state_root/workspace/.mantis_state.json (state_root from
--state_root if passed, else ./workspace/... relative to the current dir)
-> active_snapshot.root / .snapshot_id / .snapshot_pinned.
d. Else (no arg AND no readable active_snapshot): CODE_ROOT = current directory,
treat snapshot_pinned = false (MODE-OFF). Do NOT stop.
2. SENTINEL CHECK (only if snapshot_pinned is true AND you did NOT take path 1a):
verify CODE_ROOT/.mantis_snapshot_id exists and equals SNAPSHOT_ID. If missing
or different -> STOP "snapshot sentinel mismatch". (A --target_root tree (1a) is
deliberately mutated and is sentinel-EXEMPT.)
3. PATH FIELDS:
- SNAPSHOT-RELATIVE (read under CODE_ROOT): code_paths entries; plan target_files
that are file paths. Strip ONLY a trailing ":<digits>". A code_paths entry
containing "://" is a URL/endpoint, NOT a file read. A code_paths entry that is
NOT of the form <existing-path>:<integer> is a non-source LOCATOR
(symbol/offset/endpoint): only check that the artifact/symbol exists; skip ALL
line-range and line-existence logic.
- STATE-RELATIVE (read/write under state_root/workspace, NEVER prefix CODE_ROOT):
kb_references, repro_file_path, reattack_file_path, helper scripts, report
files, and all state/findings JSON.
4. Never WRITE under CODE_ROOT when snapshot_pinned is true. Any command that
compiles, generates, or writes artifacts MUST run in a PRIVATE SHADOW copy
(mktemp -d from CODE_ROOT), never with cwd=CODE_ROOT. Read-only inspection may
cd into CODE_ROOT.
5. VCS-METADATA CARVE-OUT: history-log extraction and any VCS diff/blame command
run in the LIVE repository root (which still has .git/.hg/.repo), NOT CODE_ROOT
(the snapshot copy strips VCS metadata). Do NOT stop merely because CODE_ROOT
lacks .git/.hg/.repo.
6. Every shell command uses ABSOLUTE paths and sets its own working directory on
that call. Do NOT assume the working directory persists between calls.
```
> [!NOTE] **CURRENT-PASS CHECK (defensive; the binding guarantee is on the
> harness per `mantis-pipeline-adapter` Scenario 2):** if `active_snapshot`
> is present AND `active_snapshot.pass != state.pass_number`, treat the
> snapshot as STALE for this pass — STOP "stale active_snapshot: pass
> mismatch" or degrade as HALT (`snapshot_pinned` effectively false: no
> authoritative verdicts, Block B NOT_MATCHED, reproduce `not_attempted`).
> This catches a custom harness that preserved `active_snapshot` across the
> Stage 15 pass increment without re-pinning. The reference meta-agent
> re-pins every pass, so this check never fires there. Block B itself cannot
> detect this (it is `snapshot_id`-only, not `pass`-aware).
For this stage: mantis-patch READS target code (it is NOT a findings-only
stage), so it runs Block A steps 1–6 in full. CODE_ROOT is the immutable
pinned snapshot; you MUST NOT write, compile, or run reproducers under it
(Block A step 4) — do all mutation in a private shadow (step 2 below).
0b. Determine PATCH_MODE (mechanical, using the resolved values):
- `active_snapshot` absent AND no `--snapshot_root`/`--snapshot_id`/
`--target_root` passed ⇒ **LEGACY mode** (today's behavior; the new
ceilings in step 3 do NOT fire).
- `snapshot_pinned == true` ⇒ **PINNED mode** (full gates below apply).
- `snapshot_pinned == false` AND SNAPSHOT_ID begins with the literal `live:`
⇒ **HALT/DEGRADED mode** (a snapshot was attempted but could not be pinned;
authoritative verdicts are forbidden this pass — see step 3).
0c. For each finding you process, compute its MATCHED/NOT_MATCHED result via
**Block B** (Snapshot Match Check):
```
SNAPSHOT MATCH CHECK for finding F (decides MATCHED vs NOT_MATCHED):
1. If snapshot_pinned is false -> NOT_MATCHED. Stop.
2. Read F.discovery_commit:
- missing OR empty OR the literal "MIXED" -> NOT_MATCHED.
- not exactly equal to SNAPSHOT_ID -> NOT_MATCHED.
- exactly equal to SNAPSHOT_ID -> MATCHED.
There is no other route to MATCHED; never fuzzy-compare. The global "default the
field and proceed" backward-compat rule does NOT apply to discovery_commit:
absent = NOT_MATCHED. (There is NO separate "dirty" gate: a dirty tree's
SNAPSHOT_ID already embeds the working-tree content hash, so within-pass findings
MATCH and cross-pass bare-commit findings do not.)
```
The MATCHED/NOT_MATCHED result is consumed in step 2 (isolation-mode choice)
and step 3 (verdict). It never on its own downgrades a verdict in PINNED
mode: a NOT_MATCHED finding is RE-verified against the current snapshot via
the step-3 gate and, if it passes, is stamped with the current
`patch_base_snapshot`.
1. **Load Findings to Patch:** Read the JSON files in the `workspace/findings/`
directory. Filter for findings that are NOT already terminally verified
AGAINST THE CURRENT SNAPSHOT — i.e. treat a finding as still-to-process
unless its `patch_status` is `"VERIFIED_SECURE"` or `"MITIGATION_PROPOSED"`
**and** its `patch_base_snapshot` equals the current SNAPSHOT_ID (Snapshot &
Locator Resolution step 0). A terminal finding whose `patch_base_snapshot` is
absent/empty/different is STALE — include it for re-verification. (In LEGACY
mode, where there is no SNAPSHOT_ID, fall back to filtering on `patch_status`
alone, exactly as before.) Among the included findings, keep those where
(either `repro_status` is `"reproduced"` OR the finding is an exploit chain,
e.g., the title starts with `"Exploit Chain:"`, or history has an entry from
the `"chainer"` stage, or the `"constituent_findings"` property is present
and non-empty). If none exist, notify the user.
2. **Generate and Apply Minimal Patches:** For each reproduced security flaw:
- **Target Agnosticism (Binaries vs Source):** If the target is source code,
proceed with generating and applying a code patch as described below. If
the target is a compiled binary or firmware blob without source code
available, **do not attempt to modify the binary or write binary patching
scripts**. Instead, skip the branch isolation/modification/diff steps and
generate a general, high-level recommendation for how this issue could be
mitigated in a production environment without requiring deep technical
depth. Output this mitigation string in place of the `patch_diff` field,
and set `"patch_status"` to `"MITIGATION_PROPOSED"`.
- **Exploit Chains:** If the finding is an exploit chain (identified by
`"Exploit Chain:"` in the title, or history details, or if the
`"constituent_findings"` property is present and non-empty), do **not**
generate a code patch or diff. Instead, identify its sub-findings by
reading the `"constituent_findings"` array of UUIDs. Monitor the patch
status of these constituent findings (listed on disk as
`workspace/findings/<uuid>.json`). **Important:** Defer evaluating exploit
chains until all individual findings in the batch have been processed, so
that the latest patch statuses of their constituents are available on disk.
Evaluate the exploit chain status using these propagation rules (evaluated
in order):
1. **Validity Check:** Read the validity `"status"` of each constituent
finding. If any constituent's `"status"` is `"FALSE_POSITIVE"`, update
the exploit chain finding's `"status"` to match it (e.g.
`"FALSE_POSITIVE"`) and immediately skip any further
patching/verification for the chain. If any constituent's `"status"` is
`"DUPLICATE"`, resolve it to its canonical finding by recursively
following its `"duplicate_of"` property.
**Duplicate Resolution Process:**
1. **Locate the Finding File:** The finding file for the duplicate (or
any parent in the duplicate chain) may have been moved. Search for
`<uuid>.json` in the following locations in order:
- `workspace/findings/<uuid>.json` (active findings)
- `workspace/findings/.trash/<uuid>.json` (de-duplicated trash)
- `workspace/archive/findings_pass_*/<uuid>.json` or
`workspace/archive/loop*_findings/<uuid>.json` (archives from
previous passes) If the file cannot be found in any of these
locations, treat it as a missing file error.
2. **Cycle Detection:** Maintain a set of visited finding UUIDs during
the resolution. If you encounter a UUID that has already been visited
in the current resolution chain, raise a validation error (cycle
detected).
3. **Maximum Depth:** Limit the recursion depth to a maximum of 5 steps.
If the chain is deeper, abort and report an error.
4. **Extract Status:** Once you resolve to the canonical finding (one
whose `"status"` is not `"DUPLICATE"` or does not have
`"duplicate_of"`), use that canonical finding's `"status"` and
`"patch_status"` for all downstream checks and propagation. Do not
update the exploit chain finding itself to `"DUPLICATE"`.
2. **Missing Files:** If any constituent finding's JSON file is missing
from the disk, set the chain's `"patch_status"` to `"ERROR"`.
3. **Constituent Unset or Stale (Pending):** A constituent counts as
NOT-YET-VERIFIED if EITHER its `"patch_status"` is unset (null or
missing, indicating it has not yet been reproduced/processed) OR its
`"patch_status"` is terminal but its `patch_base_snapshot` is
absent/empty/different from the current SNAPSHOT_ID (verified against a
stale snapshot — Snapshot & Locator Resolution step 0). If ANY
constituent is NOT-YET-VERIFIED, the chain's `"patch_status"` must
remain unset (null or missing) and you must defer/suspend further
evaluation of the chain until that constituent is re-verified on the
current snapshot. (In LEGACY mode, where there is no SNAPSHOT_ID, apply
only the "unset" half of this rule, exactly as before.)
4. **Constituent Errors:** If any constituent's `"patch_status"` is
`"ERROR"`, set the chain's `"patch_status"` to `"ERROR"`.
5. **Constituent Failures:** If any constituent's `"patch_status"` is
`"VERIFICATION_FAILED"`, set the chain's `"patch_status"` to
`"VERIFICATION_FAILED"`.
6. **Successful Propagation:** If all constituents have finished
verification AGAINST THE CURRENT SNAPSHOT (each is in
`{"VERIFIED_SECURE", "MITIGATION_PROPOSED", "VERIFICATION_INCOMPLETE"}`
AND — except in LEGACY mode — each terminal constituent's
`patch_base_snapshot` equals the current SNAPSHOT_ID):
- If any constituent is `"MITIGATION_PROPOSED"`, set the chain's
`"patch_status"` to `"MITIGATION_PROPOSED"`.
- If no constituent is `"MITIGATION_PROPOSED"` and any constituent is
`"VERIFICATION_INCOMPLETE"`, set the chain's `"patch_status"` to
`"VERIFICATION_INCOMPLETE"`.
- If all constituents are `"VERIFIED_SECURE"`, set the chain's
`"patch_status"` to `"VERIFIED_SECURE"`.
Skip branch isolation, testing, and re-attack steps for the chain finding
itself.
- *Optional Parallel Trajectory Search:* If your framework supports
subagents, you may spawn multiple concurrent subagents to design diverse
patch implementations. Test all generated patches that successfully secure
the code without breaking standard functionality, and select the *best*
patch (e.g., the most minimal, readable, and idiomatic fix) rather than
just the first one that works.
- Read the original flawed file to grasp function dependencies and
structures.
- Design a minimal, correct patch to mitigate the security flaw (e.g. adding
bound checks, validating sizes, inserting NUL-terminators) without breaking
other features.
- **Transactional Isolation (VCS-Agnostic & Safe):** To ensure safety,
reliability, and VCS-agnosticism, do NOT use VCS-based branch operations
(such as `git branch`, `git checkout`, or `git stash`).
You must ensure transactional isolation using a method appropriate for the
operating environment. **Isolation-method gate (mechanical):**
- If snapshot_pinned is true (PINNED mode) → **Option A (Temporary
Directory Shadowing) is MANDATORY. Option B and any method that writes
under CODE_ROOT are FORBIDDEN** (Block A step 4: never write under a
pinned snapshot).
- Else if the finding is a RETRY (it already carries a prior `"patch"`
history entry or a `patch_base_snapshot`) OR (PINNED mode AND its
Snapshot Match Check result is NOT_MATCHED) → **Option A is MANDATORY**
(do not risk editing a live tree that no longer matches the finding). The
`PINNED mode AND` qualifier on the NOT_MATCHED clause is essential: in
LEGACY mode (snapshot_pinned=false), Block B returns NOT_MATCHED for
every finding as an artifact of no snapshot, not as a signal of drift —
so NOT_MATCHED must only fire when it means "the snapshot changed"
(PINNED), not when it means "no snapshot exists" (LEGACY).
- Otherwise (snapshot_pinned is false AND first attempt — no prior
`"patch"` history entry and no `patch_base_snapshot`) you may choose
Auf GitHub ansehen