Vulnerability Chainer (/mantis-chain)
System Goal
Exploit Chain Architect. Analyzes isolated, individually-validated security
findings and historical knowledge base primitives to identify and construct
complex, multi-step exploit chains.
Command Definition
- Command:
/mantis-chain
- Description: Analyzes individual security findings to identify and
construct complex exploit chains.
- Arguments (all optional; supplied by the orchestrator per the harness
lifecycle contract — see
schema.json "Non-JSON Contracts"):
--snapshot_root / SNAPSHOT_ROOT — the pinned, immutable code snapshot
root for this pass. Consumed by Block A.
--snapshot_id / SNAPSHOT_ID — the snapshot identity string for this
pass. Consumed by Block A (sentinel) and Block B (match check).
--state_root — parent directory of workspace/. When absent, defaults to
the current directory (Block A step 1c/1d).
--target_root — an already-prepared tree that OVERRIDES the snapshot root
(rarely used by this stage; honored by Block A step 1a). When NONE of these
are passed, Block A falls back to active_snapshot in
workspace/.mantis_state.json; if that is absent too, the stage runs
MODE-OFF (snapshot_pinned = false) and behaves exactly as today (see
Backward-compat).
Input/Output Contract
- Reads:
workspace/findings/ (validated finding JSON files where status is
"VALID", and viability is "VIABLE", "CONDITIONAL_VIABLE", or
"SAMPLE_OR_TEST").
workspace/kb/entities/*.md and workspace/kb/vulnerabilities/*.md
(knowledge base primitives).
workspace/.mantis_state.json (to track current loop pass).
- Writes:
- Net-new exploit chain finding JSON files to
workspace/findings/<new_uuid>.json. Original findings are left unmodified.
- Preconditions:
- Validated or viable findings must exist in
workspace/findings/.
- Idempotency Guarantee:
- Before writing a new exploit chain finding, the skill must check existing
exploit chain findings by comparing the constituent finding sequence. Scan
BOTH the current
workspace/findings/ directory AND every archived pass
under workspace/archive/findings_pass_*/ AND legacy
workspace/archive/loop*_findings/ (all STATE-RELATIVE — never prefix
CODE_ROOT). A chain JSON is any finding whose constituent_findings array
is present and non-empty. If a chain with the EXACT same ordered constituent
sequence already exists in EITHER location, skip creating a duplicate.
- Signature-keyed idempotency (preferred) — with a code_paths tiebreak: If
ALL constituent findings have a
signature field, compare the ordered
constituent signature sequence (not UUIDs). Treat two chains as the SAME
(and skip creating the new one) ONLY IF their ordered signature sequences
are equal AND, for each corresponding constituent pair, at least one
code_paths entry (line-inclusive, i.e. compared WITH its trailing :line)
is identical. If the signature sequences match but any corresponding
constituent's code_paths differ, the chains are DISTINCT — create the new
chain. (Over-reporting is safe; a signature collision must never suppress
a genuinely new exploit chain, because signature strips line numbers and
can collide between distinct same-file bugs.)
- UUID fallback (today's behavior): If ANY constituent finding lacks a
signature field, fall back to comparing the ordered constituent UUID
sequence exactly as before. This preserves today's behavior for legacy /
un-upgraded findings.
- This archive scan is now fully effective with stable finding signatures: two
chains whose constituents share the same signatures are correctly
deduplicated across passes. When signatures are absent (legacy findings),
the scan remains HARMLESS — it cannot falsely suppress a legitimate new
chain (no silent dropped result) and simply prevents exact-UUID
re-duplication within a resumed / rerun pass. If the
workspace/archive/
directory does not exist, treat the archived set as empty and proceed.
Instructions
Locator Resolution (run first — all stages)
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).
Stage-specific notes for Block A:
mantis-chain is NOT a findings-only stage (it is not
report/calibrate/reflect), so Block A runs steps 1–6 and resolves CODE_ROOT,
SNAPSHOT_ID, and snapshot_pinned from --snapshot_root / --snapshot_id
/ state active_snapshot.
- This stage WRITES only new finding JSON to
workspace/findings/
(STATE-RELATIVE, Block A step 3). It never writes under CODE_ROOT, so Block
A step 4 is satisfied trivially. If you optionally re-inspect a constituent's
code_paths to sanity-check a chain, read them SNAPSHOT-RELATIVE under
CODE_ROOT (Block A step 3) and never cd-and-write there.
- A chain finding's
code_paths are COPIED verbatim from its constituents (they
are already SNAPSHOT-RELATIVE). Do not re-prefix, re-resolve, or renumber
them.
Snapshot Match Check (used to select constituents)
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.)
You will run Block B once per candidate constituent finding in Step 1 below,
using that finding's discovery_commit as F.discovery_commit.
Read the current batch of validated findings and explore whether multiple
seemingly low-severity or disparate vulnerabilities can be sequentially combined
to achieve a higher-impact compromise.
Execute the chaining stage as follows:
Load Primitives & Validated Findings:
- Read the JSON files in the
workspace/findings/ directory. Filter for
findings that have passed validation (e.g., status is "VALID" and
viability is "VIABLE", "CONDITIONAL_VIABLE", or "SAMPLE_OR_TEST").
- Snapshot eligibility gate (NEW — branches on
active_snapshot presence,
3-state model):
- MODE-OFF (no
active_snapshot in state — no --sync was requested,
today's default): SKIP this gate entirely: every finding that passed the
validation/viability filter above is an eligible constituent, exactly as
today. Build chains normally.
- HALT (
active_snapshot IS present but snapshot_pinned == false):
do NOT build any chains this pass. In HALT, findings' locators and
pre/post-conditions may be stale (the tree raced or could not be pinned),
so no authoritative chain verdicts may be produced. Log "no chain: HALT
mode (active_snapshot present, snapshot_pinned=false)" and stop the
chaining stage cleanly (produce no chain files). This mirrors the
minimum-eligibility guard below — a chain requires
proven-against-snapshot constituents, which HALT cannot provide.
- PINNED (
active_snapshot present AND snapshot_pinned == true): run
the Snapshot Match Check (Block B) on EACH such finding, using its
discovery_commit. Keep ONLY findings that return MATCHED as
eligible constituents. A finding that returns NOT_MATCHED — including
any finding whose discovery_commit is absent/empty, is the literal
"MIXED", or differs from the current SNAPSHOT_ID — was discovered
against a DIFFERENT code snapshot; its file:line locators and its
pre/post-conditions may no longer hold, so it MUST NOT be used as a chain
link this pass.
- Minimum-eligibility guard (NEW): If fewer than 2 eligible constituents
remain, do NOT construct any chain this pass — a chain requires at
least two links proven against the SAME snapshot. Log "no chain: fewer than
2 snapshot-matched constituents" and stop the chaining stage cleanly (this
is not an error; simply produce no chain files). This mirrors today's
behavior whenever there are fewer than two chainable findings.
- Read the Markdown Knowledge Base (
workspace/kb/entities/ and
workspace/kb/vulnerabilities/) to identify architectural primitives that
might not be bugs on their own, but could serve as stepping stones (e.g.,
"User controls file upload path", "Service runs as root").
Cross-Finding Analysis (The Chaining Matrix):
- Analyze the preconditions and postconditions of each validated finding.
- Ask: Can the output or side-effect of Finding A satisfy the strict
precondition required to trigger Finding B?
- Example Chains to look for:
- Path Traversal + Loose Permissions = RCE: A low-severity path
traversal (Finding A) allows writing to
/tmp, but a separate
misconfiguration (Finding B) allows a cron job to execute scripts in
/tmp.
- XSS + CSRF = Account Takeover: A stored XSS (Finding A) can be used
to harvest an anti-CSRF token to execute a state-changing action (Finding
B).
- Info Leak (Memory Revelation) + Buffer Overflow = ASLR Bypass: An
info leak (Finding A) reveals base pointers, satisfying the precondition
to exploit a stack buffer overflow (Finding B).
Construct "Super Findings":
- If a viable exploit chain is discovered, do NOT modify or delete the
original isolated findings. They still need to be patched individually.
- Idempotency check (run BEFORE minting a UUID): Apply the Idempotency
Guarantee above — scan current
workspace/findings/ AND
workspace/archive/findings_pass_*/ AND legacy
workspace/archive/loop*_findings/ for a chain whose constituent sequence
equals this chain's ordered constituent sequence. If ALL constituents have
signature, compare ordered signature sequences AND require the
per-constituent line-inclusive code_paths tiebreak described in the
Idempotency Guarantee (a signature-sequence match ALONE is NOT enough to
skip); if ANY constituent lacks signature, fall back to ordered
constituent UUID sequences (today's behavior). Only if a match satisfies
the tiebreak, SKIP this chain (do not create a file) and move on to the
next candidate.
- Instead, generate a net-new UUID and create a new finding JSON file in
workspace/findings/<new_uuid>.json.
- Constituent Findings: You must record the array of constituent finding
UUIDs in the structured
"constituent_findings" property (e.g.,
["UUID_A", "UUID_B"]). This clearly documents the links of the exploit
chain.
- Determine Discovery Snapshot (
discovery_commit): Set the chain
finding's discovery_commit from its ELIGIBLE constituents (the ones you
kept in Step 1):
- MODE-OFF short-circuit (3-state rule): if
active_snapshot is ABSENT
in state (MODE-OFF — no --sync was requested), OMIT discovery_commit
on the chain finding entirely. In MODE-OFF, researcher OMITS
discovery_commit on every constituent (researcher:317,340-341: "OMIT
this key entirely if active_snapshot is absent or snapshot_pinned is
false"), so every constituent has a missing/empty discovery_commit. The
SAME/MIXED logic below would thus write the literal "MIXED" on every
chain — a snapshot-era artifact that did not exist in Phase 1 and
violates MODE-OFF's "byte-for-byte today's behavior" guarantee
(schema.json:4). The chain's own schema comment (chain:307) says
"Absent on legacy/unpinned runs," confirming the intended MODE-OFF
behavior is omission, not "MIXED". (Functional impact is low —
schema.json:232 treats both "absent" and "MIXED" as NOT_MATCHED — but
mode purity matters.) Do NOT write "MIXED" or any value in MODE-OFF.
- If ALL eligible constituents have the SAME non-empty
discovery_commit
value, set the chain's discovery_commit to that exact string.
- If the constituents'
discovery_commit values DIFFER from one another,
OR any eligible constituent has a missing/empty discovery_commit (only
reachable in PINNED/HALT mode — in MODE-OFF, the short-circuit above
already OMITted the field), set the chain's discovery_commit to the
literal string "MIXED". Do NOT invent, hash, or fuzzy- normalize this
value — copy an exact string or write the literal "MIXED". Rationale:
in pinned mode every eligible constituent is MATCHED, so they all share
the current SNAPSHOT_ID, and the chain inherits it (a later Block B on
the chain then MATCHES this pass). The "MIXED" sentinel makes Block B
return NOT_MATCHED for the chain (Block B step 2 treats the literal
"MIXED" as NOT_MATCHED) — the safe branch for a chain whose links
cannot be proven against a single snapshot.
- Compute
signature (deterministic content-identity hash for the
chain):
- Collect the
signature field from every ELIGIBLE constituent finding
(the same set used for discovery_commit in Step 1).
- If EVERY eligible constituent has a non-empty
signature: sort the
constituent signatures lexicographically (ascending), then compute
signature = first 16 hex characters of
sha256("chain|" + "|".join(sorted_constituent_signatures)). The
"chain|" prefix prevents any collision with a non-chain finding's
signature (which is hashed from title+cwe+target, a different input
domain). Sorting makes the chain signature invariant under constituent
re-ordering.
- If ANY eligible constituent lacks a
signature field (legacy /
un-upgraded finding): set the chain's signature to the EMPTY STRING and
OMIT it from the JSON (downstream consumers then fall back to UUID-based
fold/dedupe per schema.json:256). This is the safe branch — it can
never cause a wrong fold, only an over-report.
- Compute the signature ONCE at chain creation and NEVER recompute, edit,
or invent it (same rule as
discovery_commit and as researcher:241-242
for regular findings).
- Compute
lineage_id (cross-pass chain lineage):
- Scan
workspace/archive/findings_pass_*/ AND legacy
workspace/archive/loop*_findings/ for any archived chain finding JSON
(any finding with a non-empty constituent_findings array) whose
signature field EXACTLY equals this chain's computed signature.
- If a match is found:
lineage_id = the archived ancestor's lineage_id
(inherit the lineage chain so report can fold across passes). If MULTIPLE
archived chains share the same signature, inherit from the MOST RECENT
(highest pass number) ancestor. All ancestors with the same chain
signature SHOULD share the same lineage_id; if they don't, inherit
from the most recent one and log a warning.
- If no match (including when this chain's
signature is the EMPTY
STRING): lineage_id = a fresh UUIDv4.
- These are STATE-RELATIVE paths (Block A step 3) — read under
--state_root/workspace/archive/, NEVER under CODE_ROOT. (Same scan
targets and same algorithm shape as researcher:246-272 for regular
findings — chains simply skip the basename-normalized rename fallback,
because a chain's identity is the set of its constituents, not a single
file path.)
- Determine Entry Point Privileges: The
privileges_required field for
the chain must represent the privilege level required to initiate the
first step of the chain (the entry point). For example, if the chain
starts with an unauthenticated exploit (NONE) that leads to admin access,
which is then used to trigger RCE, the chain's privileges_required must
be set to NONE.
- Determine Attacker Position: The
attacker_position field for the
chain must inherit the attacker position from the entry point / first
constituent finding of the chain.
- Determine User Interaction Requirement: The
user_interaction field
for the chain must be set to REQUIRED if the entry point or any step in
the chain requires user interaction. It should only be set to NONE if the
entire chain is zero-click.
- Determine Status: Set
status to "VALID".
- Determine Production Viability: Inherit from constituent findings. If
any constituent is
"SAMPLE_OR_TEST", set to "SAMPLE_OR_TEST". Else if
any constituent is "CONDITIONAL_VIABLE", set to "CONDITIONAL_VIABLE".
Otherwise, set to "VIABLE".
- Determine Reproduction Status: Inherit from constituent findings:
- If any constituent has a
repro_status of "failed_to_reproduce" or
"not_attempted", set to "not_attempted".
- Otherwise, if all constituents have a
repro_status of "reproduced" or
"statically_confirmed", set to "statically_confirmed".
- An exploit chain must never inherit
"reproduced" (as reproduction
of constituents does not prove the end-to-end chain works).
Chain Findings Schema Format (Per File)
{
"id": "A unique identifier generated for this chain finding. Must match filename.",
"title": "Exploit Chain: [Impact] via [Finding A] and [Finding B]",
"description": "Step-by-step documentation of the exploit chain. Start with Step 1 (Triggering Finding A) and explain how its outcome feeds into Step N (Triggering Finding Z).",
"impact": "The combined, escalated impact of the chain (e.g., Remote Code Execution, Full Database Exfiltration). This should be higher than the individual findings.",
"severity": "CRITICAL / HIGH",
"privileges_required": "NONE / LOW / HIGH",
"user_interaction": "NONE / REQUIRED",
"code_paths": [
"relative/file/path_A.c:line_number",
"relative/file/path_B.c:line_number"
],
"attacker_position": "EXTERNAL / LOCAL / etc. (inherited from entry point)",
"mitigation": "Recommended strategy to break the chain. Usually involves fixing at least one, if not all, of the underlying links.",
"status": "VALID",
"production_viability": "VIABLE / SAMPLE_OR_TEST / CONDITIONAL_VIABLE",
"repro_status": "statically_confirmed / not_attempted",
"constituent_findings": ["UUID_A", "UUID_B"],
"signature": "First 16 hex chars of sha256(\"chain|\" + \"|\".join(sorted(constituent_signatures))) if EVERY constituent has a non-empty `signature`; else the EMPTY STRING (absent-equivalent -> downstream falls back to UUID-only behavior). Computed ONCE at chain creation and NEVER recomputed (same rule as discovery_commit). See the signature/lineage computation steps above.",
"lineage_id": "Inherited from the most-recent archived chain finding whose `signature` equals this chain's `signature` (scan workspace/archive/findings_pass_*/ AND workspace/archive/loop*_findings/); else a fresh UUIDv4. See the signature/lineage computation steps above.",
"discovery_commit": "The SNAPSHOT_ID shared by all constituents, or the literal \"MIXED\" if they differ / are missing (only computed in PINNED/HALT mode). OMITTED (absent) on legacy/unpinned runs (MODE-OFF) — see the MODE-OFF short-circuit in the discovery_commit computation step above.",
"history": [
{
"stage": "chainer",
"action": "created",
"details": "Constructed by chaining findings [UUID_A] and [UUID_B].",
"pass_number": <current_pass_number>,
"timestamp": "<current_iso8601_timestamp>"
}
]
}
Chain Deduplication Tagging:
- To ensure
/mantis-dedupe treats these chains differently than raw
findings, ensure the word "Chain" is prominently featured in the "title"
and "history" fields as shown in the schema.
Ensure any newly constructed chain files are written to the
workspace/findings/ directory. When complete, notify the user.
1---
2name: mantis-chain
3description: >-
4 Analyzes individual security findings to identify and construct complex exploit chains.
5 Use after validation stages to see if multiple low-severity bugs can be combined into a higher impact vulnerability.
6 Don't use for initial codebase auditing or writing patch code.
7metadata:
8 source: https://skillmd.com/skills/google/mantis-chain
9---
10
11# Vulnerability Chainer (/mantis-chain)
12
13## System Goal
14
15Exploit Chain Architect. Analyzes isolated, individually-validated security
16findings and historical knowledge base primitives to identify and construct
17complex, multi-step exploit chains.
18
19## Command Definition
20
21- **Command:** `/mantis-chain`
22- **Description:** Analyzes individual security findings to identify and
23 construct complex exploit chains.
24- **Arguments (all optional; supplied by the orchestrator per the harness
25 lifecycle contract — see `schema.json` "Non-JSON Contracts"):**
26 - `--snapshot_root` / `SNAPSHOT_ROOT` — the pinned, immutable code snapshot
27 root for this pass. Consumed by Block A.
28 - `--snapshot_id` / `SNAPSHOT_ID` — the snapshot identity string for this
29 pass. Consumed by Block A (sentinel) and Block B (match check).
30 - `--state_root` — parent directory of `workspace/`. When absent, defaults to
31 the current directory (Block A step 1c/1d).
32 - `--target_root` — an already-prepared tree that OVERRIDES the snapshot root
33 (rarely used by this stage; honored by Block A step 1a). When NONE of these
34 are passed, Block A falls back to `active_snapshot` in
35 `workspace/.mantis_state.json`; if that is absent too, the stage runs
36 MODE-OFF (`snapshot_pinned = false`) and behaves exactly as today (see
37 Backward-compat).
38
39## Input/Output Contract
40
41- **Reads**:
42 - `workspace/findings/` (validated finding JSON files where status is
43 `"VALID"`, and viability is `"VIABLE"`, `"CONDITIONAL_VIABLE"`, or
44 `"SAMPLE_OR_TEST"`).
45 - `workspace/kb/entities/*.md` and `workspace/kb/vulnerabilities/*.md`
46 (knowledge base primitives).
47 - `workspace/.mantis_state.json` (to track current loop pass).
48- **Writes**:
49 - Net-new exploit chain finding JSON files to
50 `workspace/findings/<new_uuid>.json`. Original findings are left unmodified.
51- **Preconditions**:
52 - Validated or viable findings must exist in `workspace/findings/`.
53- **Idempotency Guarantee**:
54 - Before writing a new exploit chain finding, the skill must check existing
55 exploit chain findings by comparing the constituent finding sequence. Scan
56 BOTH the current `workspace/findings/` directory AND every archived pass
57 under `workspace/archive/findings_pass_*/` AND legacy
58 `workspace/archive/loop*_findings/` (all STATE-RELATIVE — never prefix
59 `CODE_ROOT`). A chain JSON is any finding whose `constituent_findings` array
60 is present and non-empty. If a chain with the EXACT same ordered constituent
61 sequence already exists in EITHER location, skip creating a duplicate.
62 - **Signature-keyed idempotency (preferred) — with a code_paths tiebreak:** If
63 ALL constituent findings have a `signature` field, compare the ordered
64 constituent `signature` sequence (not UUIDs). Treat two chains as the SAME
65 (and skip creating the new one) ONLY IF their ordered `signature` sequences
66 are equal AND, for each corresponding constituent pair, at least one
67 `code_paths` entry (line-inclusive, i.e. compared WITH its trailing `:line`)
68 is identical. If the signature sequences match but any corresponding
69 constituent's `code_paths` differ, the chains are DISTINCT — create the new
70 chain. (Over-reporting is safe; a `signature` collision must never suppress
71 a genuinely new exploit chain, because `signature` strips line numbers and
72 can collide between distinct same-file bugs.)
73 - **UUID fallback (today's behavior):** If ANY constituent finding lacks a
74 `signature` field, fall back to comparing the ordered constituent UUID
75 sequence exactly as before. This preserves today's behavior for legacy /
76 un-upgraded findings.
77 - This archive scan is now fully effective with stable finding signatures: two
78 chains whose constituents share the same signatures are correctly
79 deduplicated across passes. When signatures are absent (legacy findings),
80 the scan remains HARMLESS — it cannot falsely suppress a legitimate new
81 chain (no silent dropped result) and simply prevents exact-UUID
82 re-duplication within a resumed / rerun pass. If the `workspace/archive/`
83 directory does not exist, treat the archived set as empty and proceed.
84
85## Instructions
86
87### Locator Resolution (run first — all stages)
88
89```
90LOCATOR RESOLUTION (before reading ANY target code or artifact):
910. ROLE: If this skill NEVER reads target source (report, calibrate, reflect),
92 you are a FINDINGS-ONLY stage: skip steps 2-6; still read active_snapshot from
93 state for provenance/annotation; NEVER stop merely because a code root is unset.
941. Determine CODE_ROOT, in this priority order:
95 a. If --target_root is passed on THIS invocation, CODE_ROOT = --target_root.
96 It is AUTHORITATIVE and OVERRIDES SNAPSHOT_ROOT and the state fallback
97 (used when a caller hands you a prepared tree, e.g. a patched shadow).
98 b. Else if --snapshot_root (or SNAPSHOT_ROOT) is passed, use it.
99 c. Else read state_root/workspace/.mantis_state.json (state_root from
100 --state_root if passed, else ./workspace/... relative to the current dir)
101 -> active_snapshot.root / .snapshot_id / .snapshot_pinned.
102 d. Else (no arg AND no readable active_snapshot): CODE_ROOT = current directory,
103 treat snapshot_pinned = false (MODE-OFF). Do NOT stop.
1042. SENTINEL CHECK (only if snapshot_pinned is true AND you did NOT take path 1a):
105 verify CODE_ROOT/.mantis_snapshot_id exists and equals SNAPSHOT_ID. If missing
106 or different -> STOP "snapshot sentinel mismatch". (A --target_root tree (1a) is
107 deliberately mutated and is sentinel-EXEMPT.)
1083. PATH FIELDS:
109 - SNAPSHOT-RELATIVE (read under CODE_ROOT): code_paths entries; plan target_files
110 that are file paths. Strip ONLY a trailing ":<digits>". A code_paths entry
111 containing "://" is a URL/endpoint, NOT a file read. A code_paths entry that is
112 NOT of the form <existing-path>:<integer> is a non-source LOCATOR
113 (symbol/offset/endpoint): only check that the artifact/symbol exists; skip ALL
114 line-range and line-existence logic.
115 - STATE-RELATIVE (read/write under state_root/workspace, NEVER prefix CODE_ROOT):
116 kb_references, repro_file_path, reattack_file_path, helper scripts, report
117 files, and all state/findings JSON.
1184. Never WRITE under CODE_ROOT when snapshot_pinned is true. Any command that
119 compiles, generates, or writes artifacts MUST run in a PRIVATE SHADOW copy
120 (mktemp -d from CODE_ROOT), never with cwd=CODE_ROOT. Read-only inspection may
121 cd into CODE_ROOT.
1225. VCS-METADATA CARVE-OUT: history-log extraction and any VCS diff/blame command
123 run in the LIVE repository root (which still has .git/.hg/.repo), NOT CODE_ROOT
124 (the snapshot copy strips VCS metadata). Do NOT stop merely because CODE_ROOT
125 lacks .git/.hg/.repo.
1266. Every shell command uses ABSOLUTE paths and sets its own working directory on
127 that call. Do NOT assume the working directory persists between calls.
128```
129
130> [!NOTE] **CURRENT-PASS CHECK (defensive; the binding guarantee is on the
131> harness per `mantis-pipeline-adapter` Scenario 2):** if `active_snapshot` is
132> present AND `active_snapshot.pass != state.pass_number`, treat the snapshot as
133> STALE for this pass — STOP "stale active_snapshot: pass mismatch" or degrade
134> as HALT (`snapshot_pinned` effectively false: no authoritative verdicts, Block
135> B NOT_MATCHED, reproduce `not_attempted`). This catches a custom harness that
136> preserved `active_snapshot` across the Stage 15 pass increment without
137> re-pinning. The reference meta-agent re-pins every pass, so this check never
138> fires there. Block B itself cannot detect this (it is `snapshot_id`-only, not
139> `pass`-aware).
140
141Stage-specific notes for Block A:
142
143- `mantis-chain` is NOT a findings-only stage (it is not
144 report/calibrate/reflect), so Block A runs steps 1–6 and resolves `CODE_ROOT`,
145 `SNAPSHOT_ID`, and `snapshot_pinned` from `--snapshot_root` / `--snapshot_id`
146 / state `active_snapshot`.
147- This stage WRITES only new finding JSON to `workspace/findings/`
148 (STATE-RELATIVE, Block A step 3). It never writes under `CODE_ROOT`, so Block
149 A step 4 is satisfied trivially. If you optionally re-inspect a constituent's
150 `code_paths` to sanity-check a chain, read them SNAPSHOT-RELATIVE under
151 `CODE_ROOT` (Block A step 3) and never cd-and-write there.
152- A chain finding's `code_paths` are COPIED verbatim from its constituents (they
153 are already SNAPSHOT-RELATIVE). Do not re-prefix, re-resolve, or renumber
154 them.
155
156### Snapshot Match Check (used to select constituents)
157
158```
159SNAPSHOT MATCH CHECK for finding F (decides MATCHED vs NOT_MATCHED):
1601. If snapshot_pinned is false -> NOT_MATCHED. Stop.
1612. Read F.discovery_commit:
162 - missing OR empty OR the literal "MIXED" -> NOT_MATCHED.
163 - not exactly equal to SNAPSHOT_ID -> NOT_MATCHED.
164 - exactly equal to SNAPSHOT_ID -> MATCHED.
165There is no other route to MATCHED; never fuzzy-compare. The global "default the
166field and proceed" backward-compat rule does NOT apply to discovery_commit:
167absent = NOT_MATCHED. (There is NO separate "dirty" gate: a dirty tree's
168SNAPSHOT_ID already embeds the working-tree content hash, so within-pass findings
169MATCH and cross-pass bare-commit findings do not.)
170```
171
172You will run Block B once per candidate constituent finding in Step 1 below,
173using that finding's `discovery_commit` as `F.discovery_commit`.
174
175Read the current batch of validated findings and explore whether multiple
176seemingly low-severity or disparate vulnerabilities can be sequentially combined
177to achieve a higher-impact compromise.
178
179Execute the chaining stage as follows:
180
1811. **Load Primitives & Validated Findings:**
182
183 - Read the JSON files in the `workspace/findings/` directory. Filter for
184 findings that have passed validation (e.g., status is `"VALID"` and
185 viability is `"VIABLE"`, `"CONDITIONAL_VIABLE"`, or `"SAMPLE_OR_TEST"`).
186 - **Snapshot eligibility gate (NEW — branches on `active_snapshot` presence,
187 3-state model):**
188 - **MODE-OFF** (no `active_snapshot` in state — no `--sync` was requested,
189 today's default): SKIP this gate entirely: every finding that passed the
190 validation/viability filter above is an eligible constituent, exactly as
191 today. Build chains normally.
192 - **HALT** (`active_snapshot` IS present but `snapshot_pinned == false`):
193 do NOT build any chains this pass. In HALT, findings' locators and
194 pre/post-conditions may be stale (the tree raced or could not be pinned),
195 so no authoritative chain verdicts may be produced. Log "no chain: HALT
196 mode (active_snapshot present, snapshot_pinned=false)" and stop the
197 chaining stage cleanly (produce no chain files). This mirrors the
198 minimum-eligibility guard below — a chain requires
199 proven-against-snapshot constituents, which HALT cannot provide.
200 - **PINNED** (`active_snapshot` present AND `snapshot_pinned == true`): run
201 the **Snapshot Match Check (Block B)** on EACH such finding, using its
202 `discovery_commit`. Keep ONLY findings that return **MATCHED** as
203 eligible constituents. A finding that returns **NOT_MATCHED** — including
204 any finding whose `discovery_commit` is absent/empty, is the literal
205 `"MIXED"`, or differs from the current `SNAPSHOT_ID` — was discovered
206 against a DIFFERENT code snapshot; its `file:line` locators and its
207 pre/post-conditions may no longer hold, so it MUST NOT be used as a chain
208 link this pass.
209 - **Minimum-eligibility guard (NEW):** If fewer than 2 eligible constituents
210 remain, do **NOT** construct any chain this pass — a chain requires at
211 least two links proven against the SAME snapshot. Log "no chain: fewer than
212 2 snapshot-matched constituents" and stop the chaining stage cleanly (this
213 is not an error; simply produce no chain files). This mirrors today's
214 behavior whenever there are fewer than two chainable findings.
215 - Read the Markdown Knowledge Base (`workspace/kb/entities/` and
216 `workspace/kb/vulnerabilities/`) to identify architectural primitives that
217 might not be bugs on their own, but could serve as stepping stones (e.g.,
218 "User controls file upload path", "Service runs as root").
219
2202. **Cross-Finding Analysis (The Chaining Matrix):**
221
222 - Analyze the preconditions and postconditions of each validated finding.
223 - Ask: *Can the output or side-effect of Finding A satisfy the strict
224 precondition required to trigger Finding B?*
225 - Example Chains to look for:
226 - **Path Traversal + Loose Permissions = RCE:** A low-severity path
227 traversal (Finding A) allows writing to `/tmp`, but a separate
228 misconfiguration (Finding B) allows a cron job to execute scripts in
229 `/tmp`.
230 - **XSS + CSRF = Account Takeover:** A stored XSS (Finding A) can be used
231 to harvest an anti-CSRF token to execute a state-changing action (Finding
232 B).
233 - **Info Leak (Memory Revelation) + Buffer Overflow = ASLR Bypass:** An
234 info leak (Finding A) reveals base pointers, satisfying the precondition
235 to exploit a stack buffer overflow (Finding B).
236
2373. **Construct "Super Findings":**
238
239 - If a viable exploit chain is discovered, do **NOT** modify or delete the
240 original isolated findings. They still need to be patched individually.
241 - **Idempotency check (run BEFORE minting a UUID):** Apply the Idempotency
242 Guarantee above — scan current `workspace/findings/` AND
243 `workspace/archive/findings_pass_*/` AND legacy
244 `workspace/archive/loop*_findings/` for a chain whose constituent sequence
245 equals this chain's ordered constituent sequence. If ALL constituents have
246 `signature`, compare ordered `signature` sequences AND require the
247 per-constituent line-inclusive `code_paths` tiebreak described in the
248 Idempotency Guarantee (a signature-sequence match ALONE is NOT enough to
249 skip); if ANY constituent lacks `signature`, fall back to ordered
250 constituent UUID sequences (today's behavior). Only if a match satisfies
251 the tiebreak, SKIP this chain (do not create a file) and move on to the
252 next candidate.
253 - Instead, generate a **net-new UUID** and create a new finding JSON file in
254 `workspace/findings/<new_uuid>.json`.
255 - **Constituent Findings**: You must record the array of constituent finding
256 UUIDs in the structured `"constituent_findings"` property (e.g.,
257 `["UUID_A", "UUID_B"]`). This clearly documents the links of the exploit
258 chain.
259 - **Determine Discovery Snapshot (`discovery_commit`)**: Set the chain
260 finding's `discovery_commit` from its ELIGIBLE constituents (the ones you
261 kept in Step 1):
262 - **MODE-OFF short-circuit (3-state rule):** if `active_snapshot` is ABSENT
263 in state (MODE-OFF — no `--sync` was requested), OMIT `discovery_commit`
264 on the chain finding entirely. In MODE-OFF, researcher OMITS
265 `discovery_commit` on every constituent (`researcher:317,340-341`: "OMIT
266 this key entirely if active_snapshot is absent or snapshot_pinned is
267 false"), so every constituent has a missing/empty `discovery_commit`. The
268 SAME/MIXED logic below would thus write the literal `"MIXED"` on every
269 chain — a snapshot-era artifact that did not exist in Phase 1 and
270 violates MODE-OFF's "byte-for-byte today's behavior" guarantee
271 (`schema.json:4`). The chain's own schema comment (`chain:307`) says
272 "Absent on legacy/unpinned runs," confirming the intended MODE-OFF
273 behavior is omission, not `"MIXED"`. (Functional impact is low —
274 `schema.json:232` treats both "absent" and `"MIXED"` as NOT_MATCHED — but
275 mode purity matters.) Do NOT write `"MIXED"` or any value in MODE-OFF.
276 - If ALL eligible constituents have the SAME non-empty `discovery_commit`
277 value, set the chain's `discovery_commit` to that exact string.
278 - If the constituents' `discovery_commit` values DIFFER from one another,
279 OR any eligible constituent has a missing/empty `discovery_commit` (only
280 reachable in PINNED/HALT mode — in MODE-OFF, the short-circuit above
281 already OMITted the field), set the chain's `discovery_commit` to the
282 literal string `"MIXED"`. Do NOT invent, hash, or fuzzy- normalize this
283 value — copy an exact string or write the literal `"MIXED"`. Rationale:
284 in pinned mode every eligible constituent is MATCHED, so they all share
285 the current `SNAPSHOT_ID`, and the chain inherits it (a later Block B on
286 the chain then MATCHES this pass). The `"MIXED"` sentinel makes Block B
287 return NOT_MATCHED for the chain (Block B step 2 treats the literal
288 `"MIXED"` as NOT_MATCHED) — the safe branch for a chain whose links
289 cannot be proven against a single snapshot.
290 - **Compute `signature` (deterministic content-identity hash for the
291 chain):**
292 - Collect the `signature` field from every ELIGIBLE constituent finding
293 (the same set used for `discovery_commit` in Step 1).
294 - If EVERY eligible constituent has a non-empty `signature`: sort the
295 constituent signatures lexicographically (ascending), then compute
296 `signature` = first 16 hex characters of
297 `sha256("chain|" + "|".join(sorted_constituent_signatures))`. The
298 `"chain|"` prefix prevents any collision with a non-chain finding's
299 `signature` (which is hashed from title+cwe+target, a different input
300 domain). Sorting makes the chain signature invariant under constituent
301 re-ordering.
302 - If ANY eligible constituent lacks a `signature` field (legacy /
303 un-upgraded finding): set the chain's `signature` to the EMPTY STRING and
304 OMIT it from the JSON (downstream consumers then fall back to UUID-based
305 fold/dedupe per `schema.json:256`). This is the safe branch — it can
306 never cause a wrong fold, only an over-report.
307 - Compute the signature ONCE at chain creation and NEVER recompute, edit,
308 or invent it (same rule as `discovery_commit` and as `researcher:241-242`
309 for regular findings).
310 - **Compute `lineage_id` (cross-pass chain lineage):**
311 - Scan `workspace/archive/findings_pass_*/` AND legacy
312 `workspace/archive/loop*_findings/` for any archived chain finding JSON
313 (any finding with a non-empty `constituent_findings` array) whose
314 `signature` field EXACTLY equals this chain's computed `signature`.
315 - If a match is found: `lineage_id` = the archived ancestor's `lineage_id`
316 (inherit the lineage chain so report can fold across passes). If MULTIPLE
317 archived chains share the same `signature`, inherit from the MOST RECENT
318 (highest pass number) ancestor. All ancestors with the same chain
319 `signature` SHOULD share the same `lineage_id`; if they don't, inherit
320 from the most recent one and log a warning.
321 - If no match (including when this chain's `signature` is the EMPTY
322 STRING): `lineage_id` = a fresh UUIDv4.
323 - These are STATE-RELATIVE paths (Block A step 3) — read under
324 `--state_root/workspace/archive/`, NEVER under CODE_ROOT. (Same scan
325 targets and same algorithm shape as `researcher:246-272` for regular
326 findings — chains simply skip the basename-normalized rename fallback,
327 because a chain's identity is the set of its constituents, not a single
328 file path.)
329 - **Determine Entry Point Privileges**: The `privileges_required` field for
330 the chain must represent the privilege level required to initiate the
331 *first* step of the chain (the entry point). For example, if the chain
332 starts with an unauthenticated exploit (NONE) that leads to admin access,
333 which is then used to trigger RCE, the chain's `privileges_required` must
334 be set to `NONE`.
335 - **Determine Attacker Position**: The `attacker_position` field for the
336 chain must inherit the attacker position from the entry point / first
337 constituent finding of the chain.
338 - **Determine User Interaction Requirement**: The `user_interaction` field
339 for the chain must be set to `REQUIRED` if the entry point or any step in
340 the chain requires user interaction. It should only be set to `NONE` if the
341 entire chain is zero-click.
342 - **Determine Status**: Set `status` to `"VALID"`.
343 - **Determine Production Viability**: Inherit from constituent findings. If
344 any constituent is `"SAMPLE_OR_TEST"`, set to `"SAMPLE_OR_TEST"`. Else if
345 any constituent is `"CONDITIONAL_VIABLE"`, set to `"CONDITIONAL_VIABLE"`.
346 Otherwise, set to `"VIABLE"`.
347 - **Determine Reproduction Status**: Inherit from constituent findings:
348 - If any constituent has a `repro_status` of `"failed_to_reproduce"` or
349 `"not_attempted"`, set to `"not_attempted"`.
350 - Otherwise, if all constituents have a `repro_status` of `"reproduced"` or
351 `"statically_confirmed"`, set to `"statically_confirmed"`.
352 - An exploit chain must **never** inherit `"reproduced"` (as reproduction
353 of constituents does not prove the end-to-end chain works).
354
355 ### Chain Findings Schema Format (Per File)
356
357 ```json
358 {
359 "id": "A unique identifier generated for this chain finding. Must match filename.",
360 "title": "Exploit Chain: [Impact] via [Finding A] and [Finding B]",
361 "description": "Step-by-step documentation of the exploit chain. Start with Step 1 (Triggering Finding A) and explain how its outcome feeds into Step N (Triggering Finding Z).",
362 "impact": "The combined, escalated impact of the chain (e.g., Remote Code Execution, Full Database Exfiltration). This should be higher than the individual findings.",
363 "severity": "CRITICAL / HIGH",
364 "privileges_required": "NONE / LOW / HIGH",
365 "user_interaction": "NONE / REQUIRED",
366 "code_paths": [
367 "relative/file/path_A.c:line_number",
368 "relative/file/path_B.c:line_number"
369 ],
370 "attacker_position": "EXTERNAL / LOCAL / etc. (inherited from entry point)",
371 "mitigation": "Recommended strategy to break the chain. Usually involves fixing at least one, if not all, of the underlying links.",
372 "status": "VALID",
373 "production_viability": "VIABLE / SAMPLE_OR_TEST / CONDITIONAL_VIABLE",
374 "repro_status": "statically_confirmed / not_attempted",
375 "constituent_findings": ["UUID_A", "UUID_B"],
376 "signature": "First 16 hex chars of sha256(\"chain|\" + \"|\".join(sorted(constituent_signatures))) if EVERY constituent has a non-empty `signature`; else the EMPTY STRING (absent-equivalent -> downstream falls back to UUID-only behavior). Computed ONCE at chain creation and NEVER recomputed (same rule as discovery_commit). See the signature/lineage computation steps above.",
377 "lineage_id": "Inherited from the most-recent archived chain finding whose `signature` equals this chain's `signature` (scan workspace/archive/findings_pass_*/ AND workspace/archive/loop*_findings/); else a fresh UUIDv4. See the signature/lineage computation steps above.",
378 "discovery_commit": "The SNAPSHOT_ID shared by all constituents, or the literal \"MIXED\" if they differ / are missing (only computed in PINNED/HALT mode). OMITTED (absent) on legacy/unpinned runs (MODE-OFF) — see the MODE-OFF short-circuit in the discovery_commit computation step above.",
379 "history": [
380 {
381 "stage": "chainer",
382 "action": "created",
383 "details": "Constructed by chaining findings [UUID_A] and [UUID_B].",
384 "pass_number": <current_pass_number>,
385 "timestamp": "<current_iso8601_timestamp>"
386 }
387 ]
388 }
389 ```
390
3914. **Chain Deduplication Tagging:**
392
393 - To ensure `/mantis-dedupe` treats these chains differently than raw
394 findings, ensure the word "Chain" is prominently featured in the `"title"`
395 and `"history"` fields as shown in the schema.
396
397Ensure any newly constructed chain files are written to the
398`workspace/findings/` directory. When complete, notify the user.