[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6991ZT5W9B37KBPMS37GQC6":3,"skill-same:01M6991ZT5W9B37KBPMS37GQC6":85},{"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":23,"publishedAt":42,"linkOnly":43,"markdownContent":44,"markdownBody":45,"frontMatter":46,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":52,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M6991ZT5W9B37KBPMS37GQC6","mantis-pipeline-adapter",null,"Interactively guides the design and implementation of custom deterministic orchestrator harnesses. Use when a user wants to build their own pipeline to wrap and run Mantis skills reliably. Don't use for executing the default pipeline directly.","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-pipeline-adapter\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41],"pipeline","adapter","mantis pipeline adapter","use","wrap","deterministic","orchestrator","when","default","user","implementation","build","custom","for","run","guides","harnesses","design","2026-11-10 10:12:30",false,"---\nname: mantis-pipeline-adapter\ndescription: >-\n  Interactively guides the design and implementation of custom deterministic orchestrator harnesses.\n  Use when a user wants to build their own pipeline to wrap and run Mantis skills reliably.\n  Don't use for executing the default pipeline directly.\n---\n\n# Mantis Pipeline Designer (\u002Fmantis-pipeline-adapter)\n\n## System Goal\n\nInteractive Pipeline Design Consultant. Assists the user in designing and\nimplementing their own deterministic orchestrator harness for Mantis Skills.\nHelps the user apply best practices for reliability, token efficiency, and\ncustom environment integration.\n\n## Command Definition\n\n- **Command:** `\u002Fmantis-pipeline-adapter`\n- **Description:** Interactively guides the design and implementation of custom\n  deterministic orchestrator harnesses.\n\n## Input\u002FOutput Contract\n\n- **Reads**:\n  - `workspace\u002F.mantis_state.json` (to track current loop pass).\n  - `workspace\u002F.mantis_state.json` fields `active_snapshot`, `snapshot_history`,\n    and `vcs_info.snapshot_id` — the per-pass snapshot pin, present only when\n    the target harness has opted into sync (absent on today's single-snapshot\n    runs; see Reference Architecture Guideline 5).\n  - `schema.json` (as the canonical pipeline specification reference).\n  - `workspace\u002Ffindings\u002F*.json` (as the State Store).\n  - `workspace\u002Flearnings.jsonl` (to understand memory rotation).\n  - User's interactive configuration input.\n- **Writes**:\n  - Outputs user-customized orchestrator harness code, configurations, or\n    architecture documentation.\n- **Preconditions**:\n  - User initiates interactive design session.\n- **Idempotency Guarantee**:\n  - As a consulting agent, it advises the user to implement idempotency in their\n    custom harness using three primary mechanisms: (1) state store\n    synchronization, (2) atomic transactional file\u002FVCS operations, and (3)\n    proper locks (e.g. database\u002Ffile level locks).\n\n## Instructions\n\nInteractively guide the user in designing and building a deterministic pipeline\nthat wraps Mantis Skills.\n\nFollow these guidelines during the consultation:\n\n01. **Understand User Context:** Ask about their target programming language,\n    agent framework (if any), execution environments (VMs, local containers,\n    physical hardware), and scale requirements.\n02. **Recommend Core Principles:** Guide them to implement the reference\n    architecture patterns (detailed below), specifically emphasizing:\n    - **Deterministic Orchestration**: Use code (not LLM) for control flow.\n    - **State Store**: Use a database or structured filesystem as the single\n      source of truth.\n    - **Token Efficiency**: Use the UUID-based referencing pattern to avoid LLM\n      text duplication.\n    - **Custom Environment Integration**: Use Custom MCP servers for isolated\n      testing (VMs) or hardware interaction.\n03. **Ensure Schema Consistency**: Advise the user to strictly adhere to the\n    inter-stage data contracts defined in [schema.json](..\u002F..\u002Fschema.json) when\n    building their harness.\n04. **Adaptive Design**: Help them draft the code\u002Farchitecture tailored to their\n    specific stack, rather than imposing a rigid template.\n05. **Advise on Scale and Concurrency**: If they have high-scale needs, guide\n    them on decomposing the pipeline and implementing locking mechanisms to\n    prevent race conditions.\n06. **Suggest Evaluations:** Remind them to perform empirical evaluations when\n    choosing cheaper models for utility stages.\n07. **Advise the Pass Lifecycle Contract (living \u002F synced codebases):** If the\n    user wants their harness to *continue a run after the target code changes*,\n    or to *sync the target repo at the start of a new pass*, walk them through\n    the harness-agnostic Pass Lifecycle Contract in Reference Architecture\n    Guideline 5 below. Emphasize that this support is **opt-in**: a harness that\n    does not implement the contract MUST leave `snapshot_pinned` unset, which\n    preserves today's single-snapshot behavior byte-for-byte. When `--sync` is\n    requested, the harness PINs in the PIN step and passes\n    `--snapshot_root`\u002F`--snapshot_id` normally; Block A (Locator Resolution) is\n    universal across all code-reading stages.\n08. **Advise on Semantic Retrieval at Scale:** If the user is targeting a large\n    codebase (e.g., thousands of source files, multi-pass campaigns, or multiple\n    teams contributing findings), walk them through the optional semantic\n    retrieval patterns in Reference Architecture Guidelines 6 and 7 below.\n    Emphasize that these are **opt-in**: they augment the pipeline via a\n    dedicated query skill or MCP tools, but never modify the existing skills'\n    own deterministic logic or fail-safe invariants.\n09. **Advise on SAST Seeding:** If the user wants to augment LLM-based discovery\n    with external SAST tool findings (CodeQL, Semgrep, etc.), walk them through\n    the optional SAST seeding pattern in Reference Architecture Guideline 8\n    below. Emphasize that this is **opt-in**: it ingests external findings as\n    candidates that must earn their verdict through unchanged downstream gates,\n    and it follows exactly the RAG pattern (provenance-tracked, snapshot-aware,\n    fallback on failure).\n10. **Advise on Structural Code Indexing:** If the user is targeting a large\n    codebase where grep-based call-site discovery is unreliable, walk them\n    through the optional structural code index stage in Reference Architecture\n    Guideline 9 below. Emphasize that this is an **optional first-class stage**:\n    it provides structural context (function boundaries, call graphs) to improve\n    LLM reasoning, runs after the snapshot is pinned and before the first\n    code-reading analysis stage, and degrades gracefully to grep when\n    unavailable.\n11. **Advise on Tiered Iterative Reproduction & Multi-Conversation Retries:** If\n    the user is targeting complex services where single-shot repro is brittle,\n    walk them through the tiered iterative reproduction strategy and\n    multi-conversation retry pattern in Reference Architecture Guideline 10.\n\n## Reference Architecture Guidelines\n\nUse the following guidelines as your technical reference when advising the user.\n\n### Core Principles\n\n1. **Deterministic Orchestration:** Do not let the LLM decide the control flow\n   of the pipeline. Use a programmatic harness to call skills sequentially or in\n   parallel.\n2. **State on Disk \u002F Database:** Use the filesystem\n   (`workspace\u002Ffindings\u002F*.json`) or a database as the single source of truth.\n   Skills should read from and write to this store. For horizontal scaling,\n   recommend a centralized database.\n3. **Deterministic Reporting:** Treat findings as internal state. Minimize the\n   use of the LLM to convert JSON findings into Markdown reports for human\n   consumption; instead, write deterministic scripts to render the JSON into\n   reports or upload them to bug trackers. Only use an LLM for non-deterministic\n   subsets of this (like textual synthesis), such as by providing an executive\n   summary if necessary.\n4. **Token Efficiency & Reusable Deterministic Tools:** Structure LLM outputs to\n   return only the *minimum necessary information* (e.g., UUIDs, status codes).\n   Do not force the LLM to write one-off scripts (e.g., Python or bash) on the\n   fly for routine tasks like appending JSON fields or merging findings, as this\n   wastes reasoning tokens. Instead, the harness should provide reusable,\n   deterministic tools (such as pre-written helper scripts or MCP endpoints)\n   that the LLM can simply invoke to perform text manipulation and state\n   updates.\n5. **State Store & Memory Rotation:** To prevent token bloat and infinite loops,\n   ephemeral queues (like `workspace\u002Flearnings.jsonl`) must be rotated. Upon\n   successful completion and verification of the Knowledge Base synthesis stage,\n   the orchestrator should ensure the archive directory exists (e.g.,\n   `mkdir -p workspace\u002Farchive\u002Flearnings\u002F`) and **move**\n   `workspace\u002Flearnings.jsonl` to a numbered archive (e.g.,\n   `workspace\u002Farchive\u002Flearnings\u002Flearnings_pass_${N}_${X}.jsonl` where `${N}` is\n   the loop pass and `${X}` is a sub-index). If the synthesis fails, the active\n   queue must be left intact to prevent data loss.\n\n### Architectural Overview\n\n```mermaid\ngraph TD\n    Harness[Programmatic Harness \u002F Orchestrator] \u003C--> DB[(State Store: Disk\u002FDB)]\n\n    subgraph Stages [Decomposed Stages]\n        KB[KB Architect]\n        TM[Threat Modeler]\n        P[Plan]\n        R[Researcher]\n        D[Deduplicator]\n        V[Validator\u002FReview]\n        C[Critic]\n        Rep[Reproducer]\n        Ch[Chainer]\n        Pat[Patcher]\n        Cal[Calibrator]\n        Ref[Reflector]\n    end\n\n    Harness --> KB\n    Harness --> TM\n    Harness --> P\n    Harness --> R\n    Harness --> D\n    Harness --> V\n    Harness --> C\n    Harness --> Rep\n    Harness --> Ch\n    Harness --> Pat\n    Pat -.->|Re-attack Bypass Loop| Rep\n    Harness --> Cal\n    Harness --> Ref\n\n    subgraph LLM Pool [Tailored LLMs]\n        ModelA[Frontier Model: Deep Reasoning]\n        ModelB[Flash\u002FLite Model: Fast & Cheap]\n        ModelC[Alternative Provider: Diversified Logic]\n    end\n\n    KB -.-> ModelA\n    TM -.-> ModelB\n    P -.-> ModelB\n    R -.-> ModelA\n    R -.-> ModelC\n    D -.-> ModelB\n    V -.-> ModelB\n    C -.-> ModelA\n    Rep -.-> ModelA\n    Ch -.-> ModelA\n    Pat -.-> ModelA\n    Cal -.-> ModelB\n    Ref -.-> ModelB\n```\n\n### 1. UUID-Based Referencing Pattern\n\nTo prevent the LLM from repeating large blocks of text (which increases latency,\ncost, and the risk of mangling data), use UUIDs as the primary key for all\nfindings.\n\n#### A. Researcher Stage\n\n- **Action:** Sweeps the codebase and identifies potential vulnerabilities.\n- **LLM Output:** Generates a unique UUID for each finding and writes\n  `workspace\u002Ffindings\u002F\u003CUUID>.json` containing the full details (matching the\n  standard schema in [Mantis Researcher](..\u002Fmantis-researcher\u002FSKILL.md)).\n\n#### B. Deduplication Stage (Optimized)\n\nInstead of asking the LLM to read all findings, merge them in context, and write\nthem back, use the following pattern:\n\n1. **Harness Action:** Reads all `workspace\u002Ffindings\u002F*.json` files and prepares\n   a summary list for the LLM containing only key identifiers. To align with the\n   standard schema, map the `code_paths` array (which uses `\"file:line\"` format)\n   to a simplified summary for the LLM:\n   `[ { \"id\": \"UUID\", \"file\": \"path\", \"line\": 12, \"snippet\": \"...\" } ]`.\n\n2. **LLM Action:** Analyzes the summary and outputs a mapping of duplicates:\n\n   ```json\n   {\n     \"primary_uuid_1\": [\"duplicate_uuid_a\", \"duplicate_uuid_b\"],\n     \"primary_uuid_2\": []\n   }\n   ```\n\n3. **Harness Action (Deterministic):**\n\n   - Reads the content of the affected files.\n   - Programmatically merges fields following the rules in\n     [Mantis Deduplicator](..\u002Fmantis-dedupe\u002FSKILL.md) (e.g., union of\n     `code_paths`, taking highest severity, concatenating history).\n   - Updates `workspace\u002Ffindings\u002Fprimary_uuid_1.json` on disk.\n   - Ensures the trash directory exists (e.g.,\n     `mkdir -p workspace\u002Ffindings\u002F.trash\u002F`).\n   - Moves `workspace\u002Ffindings\u002Fduplicate_uuid_a.json` and\n     `workspace\u002Ffindings\u002Fduplicate_uuid_b.json` to the trash staging directory\n     (`workspace\u002Ffindings\u002F.trash\u002F`).\n\n#### C. Validation & Review Stages (Reviewer, Critic)\n\n- **Harness Action:** For each finding `workspace\u002Ffindings\u002F\u003CUUID>.json`, pass\n  only the relevant code context and finding description to the LLM.\n- **LLM Action:** Output *only* a structured verification result (e.g.,\n  `{\"valid\": true, \"reason\": \"...\"}`).\n- **Harness Action (Deterministic):** Programmatically update the\n  `workspace\u002Ffindings\u002F\u003CUUID>.json` file with the validation status and reason.\n\n### 2. Adaptable Reproducers via Custom MCP\n\nWhen validating findings, the agent may need to interact with diverse\nenvironments (VMs, physical hardware). Use the **Model Context Protocol (MCP)**\nto expose a clean, restricted API.\n\n- **Architecture**:\n  `[Reproducer Agent] \u003C--- MCP ---> [Custom MCP Server] \u003C--- API ---> [Target Env]`\n- **Custom Environments**:\n  - *VMs*: Implement tools like `reboot_vm()`, `execute_payload()`.\n  - *Hardware\u002FUSB*: Implement tools like `power_cycle_device()` (via smart\n    plug), `send_usb_packet()`.\n- **Integration Note**: If the user's harness uses raw LLM APIs (e.g., direct\n  Gemini API calls) instead of an MCP-native client framework, the harness must\n  manually register these tools in the API's schema format and handle\n  dispatching tool calls to the MCP server.\n\n### 3. Decomposition & Multi-Model Strategy\n\n#### A. Pipeline Decomposition & Concurrency\n\nThe pipeline can be split into independent services. When scaling horizontally\n(e.g., multiple workers running the `Reproducer` stage in parallel):\n\n- **Concurrency Control**: Implement database or file locking to ensure two\n  workers do not attempt to process or update the same finding simultaneously.\n- **Parallel Trajectory Search**: For deep reasoning stages (`Reproducer`,\n  `Patcher`), spawn multiple parallel agents attempting to solve the exact same\n  finding using diverse logic paths. For the `Reproducer` stage, prune all other\n  trajectories as soon as one worker succeeds to save compute costs while\n  escaping LLM \"give up\" loops. For the `Patcher` stage, wait for all patches to\n  be generated and tested, then evaluate the successful ones to select the most\n  minimal, idiomatic, and correct fix.\n\n#### B. Heterogeneous LLM Selection (Multi-Model)\n\nMatch task complexity with the appropriate model tier:\n\n- *Frontier Models*: For deep reasoning (Research, Reproduce, Patch).\n- *Flash\u002FLite Models*: For structured utility tasks (Dedupe, Calibrate).\n- *Variability*: Run different models in parallel during the Research stage to\n  increase bug-hunting coverage.\n\n#### C. Importance of Evaluation\n\nEmphasize that using cheaper models for utility stages (like deduplication or\ncalibration) must be validated with empirical evaluations against a benchmark\ndataset to ensure quality is not degraded.\n\n### 4. The Planning Stage and workspace\u002Fplan.json\n\nThe planning stage plays a critical role in structuring the security campaign.\nThe strategist (`\u002Fmantis-plan`) generates `workspace\u002Fplan.json` to define\ntargeted investigations, context pointers, and specific questions for the\nauditor. The researcher (`\u002Fmantis-researcher`) reads `workspace\u002Fplan.json` at\nstartup to guide its sweep. By decoupling strategy and execution via this\nstructured contract, the orchestrator can easily direct subagents, parallelize\nsweeps, and maintain historical context across pipeline runs without repeating\nwork.\n\n### 5. The Pass Lifecycle Contract (Living \u002F Synced Codebases)\n\nA custom orchestrator (a bespoke CLI, an ADK agent, an MCP-native pipeline, or\nany deterministic harness) does **not** inherit the living-project lifecycle\nthat `mantis-meta-agent` implements. To support *continue-after-edits* and\n*opt-in boundary sync* **without producing silent wrong results** (false\n`VERIFIED_SECURE`, false `failed_to_reproduce`, dropped regressions), the\nharness must implement the following harness-agnostic contract. This is the same\ncontract recorded in [schema.json](..\u002F..\u002Fschema.json) under **Non-JSON\nContracts**; the `Block A`–`Block G` and `SNAPSHOT_ID` references below name\nmechanisms each Mantis stage already carries in its own `SKILL.md`.\n\nMantis runs under multiple harnesses (various CLIs, ADK, custom deterministic\npipelines), so the lifecycle must not live only in `mantis-meta-agent`. Any\nharness is **conformant** iff, per pass, it:\n\n1. **SYNCs first** (Block C) — the very first action; never mid-pass.\n2. **Detects `vcs_info` + computes `SNAPSHOT_ID`** (Block D steps 1-5) — only\n   after sync.\n3. **PINs** the immutable copy + writes the sentinel + **appends**\n   `snapshot_history` (Block D step 5, not RECORD).\n4. **Records** `vcs_info` (incl. `snapshot_id`) + `active_snapshot`. Never\n   record an id or pin before syncing.\n5. **Runs every stage** with\n   `--snapshot_root=\u003CSNAPSHOT_ROOT> --snapshot_id=\u003CSNAPSHOT_ID> --state_root=\u003Cworkspace parent>`.\n6. **Archives & increments** (existing Stage 15); retried findings keep their\n   **original** `discovery_commit`.\n\nA harness that does not implement the contract MUST leave `snapshot_pinned`\nunset → today's behavior. When `--sync` is requested, the harness PINs in the\nPIN step and passes `--snapshot_root`\u002F `--snapshot_id` normally; Block A\n(Locator Resolution) is universal across all code-reading stages.\n\n#### Advisory notes when helping a builder implement this contract\n\n- **Opt-in, default off.** Sync\u002Fpinning is a feature the builder turns on. A\n  harness that never sets `snapshot_pinned` behaves exactly like today (one live\n  snapshot per run). Downstream stages treat an absent\n  `active_snapshot`\u002F`discovery_commit` as the conservative branch, so an\n  un-upgraded harness is always safe — just not living-project-aware. Do **not**\n  advise treating these absent fields as an error.\n- **Store snapshots OUTSIDE `workspace\u002F`.** The pinned copy (`SNAPSHOT_ROOT`)\n  must live under `\u003Cstate_root>\u002F.mantis_snapshots\u002Fpass_\u003CN>` (or a clean-VCS\n  worktree\u002Farchive), and its path **must not** contain the segment `\u002Fworkspace\u002F`\n  — otherwise `mantis-patch`'s state-vs-code path guard misfires. Keep the last\n  2 snapshots and garbage-collect older ones with the matching teardown\n  (`rm -rf` for copies, `git worktree remove\u002Fprune` for worktrees).\n- **Non-destructive sync only.** Sync is the **first** action of a pass,\n  **never** mid-pass, and must be **skipped** when the tree is dirty, ahead of\n  upstream, detached, or has no upstream. The harness must **never** run\n  `git reset --hard`, `git checkout -- .`, `git clean`, or `hg update -C`, or\n  any command that discards uncommitted\u002Funtracked\u002Flocal-commit state — user\n  edits and in-progress work must survive every pass.\n- **Full-fidelity `SNAPSHOT_ID`s, including dirty \u002F no-VCS.** Compute the id\n  over the **whole** pinned copy: clean git\u002Fhg → `commit_hash`; dirty git\u002Fhg →\n  `commit_hash + \":\" + content_hash`; multi-vcs →\n  `revision + \":\" + content_hash`; no-VCS \u002F unknown copyable tree →\n  `\"content:\" + content_hash`. The embedded content hash is exactly what lets an\n  **unchanged dirty or no-VCS tree MATCH across passes** and still receive\n  verification + dedup — and what makes a `repo sync` that advances commits\n  under an unchanged manifest `revision` compare **unequal**. Never trust a bare\n  branch name or manifest revision string as an identity.\n- **Pass the three roots to EVERY stage.** Include the findings-only stages\n  (report, calibrate, reflect): they do not read target code, but they still\n  read `active_snapshot` for provenance\u002Fannotation. When the harness archives\n  and increments, retried findings must keep their **original**\n  `discovery_commit`.\n\n#### Conformance scenarios\n\nThe scenarios below expose nearly every issue in the snapshot model. They are\n**reference checks**, not features: the harness is responsible for preventing or\nhandling each one in its own environment. The table is a quick-reference; prose\ndetail follows for each scenario. The **State** column uses the 3-STATE RULE\n(MODE-OFF \u002F HALT \u002F PINNED, branched on `active_snapshot` presence — see the\nglobal backward-compat rule in [schema.json](..\u002F..\u002Fschema.json) and the advisory\nnotes above); `SNAPSHOT_ID` formats follow the ladder in the advisory notes\nabove (e.g. `live:\u003Cts>` signals an unpinned\u002FHALT pass).\n\n**Invariant legend** (the labels below name safety properties enforced by the\nblocks and the global backward-compat rule in [schema.json](..\u002F..\u002Fschema.json)):\n\n| Label | Property                       | Enforced by                                   |\n| ----- | ------------------------------ | --------------------------------------------- |\n| INV-1 | No false `VERIFIED_SECURE`     | Block G + HALT ceiling                        |\n| INV-2 | No false `failed_to_reproduce` | Block F + HALT ceiling                        |\n| INV-3 | No dropped regression          | Block B NOT_MATCHED + POSSIBLE REGRESSION     |\n| INV-4 | Within-pass consistency        | Block A sentinel + single pinned snapshot     |\n| INV-5 | No user data loss              | Block C non-destructive sync + Block A step 4 |\n| INV-6 | Fail-safe on missing data      | Global backward-compat rule                   |\n\n**Quick-reference table:**\n\n| #   | Scenario                                                            | State                                        | Harness behavior                                                                                                                                                                           | Stage behavior                                                                                                                                                                                                      | Block \u002F INV                             | Key fields                                                                                            |\n| --- | ------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------- |\n| 1   | Colocated state                                                     | PINNED                                       | HALT-and-yield (safe default), or relocate `state_root` outside `CODE_ROOT` when explicitly authorized (e.g. `--auto_relocate_state`); `SNAPSHOT_ROOT` path must not contain `\u002Fworkspace\u002F` | `mantis-patch` state-vs-code guard misfires; Block A step 3 confuses SNAPSHOT- vs STATE-relative paths                                                                                                              | A:3, D:3; INV-5                         | `active_snapshot.root`, `snapshot_root`, `state_root`                                                 |\n| 2   | Stale active_snapshot (`active_snapshot.pass != state.pass_number`) | PINNED → STOP or HALT-degrade                | Block D step 0: handles same-pass re-entry only; if dir missing → STOP, yield to user                                                                                                      | Block A step 2 sentinel may still MATCH (dir retained); CURRENT-PASS CHECK (`active_snapshot.pass == state.pass_number`) required: mismatch → STOP or HALT-degrade (Block B NOT_MATCHED, no authoritative verdicts) | A:2, D:0, B; INV-1, INV-3, INV-4, INV-6 | `active_snapshot.{root, snapshot_id, snapshot_pinned, pass}`, `state.pass_number`, `discovery_commit` |\n| 3   | Pin failure                                                         | HALT                                         | Block D step 2\u002F4: skip copy on ENOSPC\u002Ferror → step 5b; still write `active_snapshot` + pass roots                                                                                          | Authoritative verdicts forbidden; Block B always NOT_MATCHED; reproduce `not_attempted`; patch `VERIFICATION_INCOMPLETE`                                                                                            | D:2, D:4, D:5b; INV-1, INV-2, INV-6     | `active_snapshot.{snapshot_id, snapshot_pinned}`                                                      |\n| 4   | Patched shadows                                                     | PINNED (pass); `--snapshot_pinned=false` arg | Pass `--target_root=\u003CPATCHED_SHADOW_ROOT>` + `--snapshot_pinned=false` to reattack sub-agent                                                                                               | Block A step 1a: `CODE_ROOT=--target_root` (authoritative); step 2 sentinel SKIPPED (sentinel-EXEMPT)                                                                                                               | A:1a, A:2; INV-4                        | `target_root`, `snapshot_pinned` (arg), `snapshot_root`, `discovery_commit`                           |\n| 5   | Different-snapshot duplicate candidates                             | PINNED                                       | No special action — both passes pinned correctly; dedupe handles it                                                                                                                        | Block B pairwise: `discovery_commit` differs → NOT_MATCHED → keep ACTIVE + `possible_duplicate_of`; POSSIBLE REGRESSION if archived was RESOLVED                                                                    | B; INV-3, INV-6                         | `discovery_commit`, `possible_duplicate_of`, `status`, `patch_status`                                 |\n| 6   | Absent sink evidence                                                | Any                                          | No special action — Block F is a stage-level mechanical gate                                                                                                                               | Block F: evidence absent (build error, exit 127, sink unreached) → `not_attempted` (retry-eligible), NEVER `failed_to_reproduce`; HALT ceiling additionally forces `not_attempted`                                  | F; INV-2, INV-6                         | `repro_status`, `reattack_status`, `repro_hints`                                                      |\n\n**Per-scenario detail:**\n\n**1. Colocated state** (`state_root` nested inside `CODE_ROOT` \u002F snapshot root)\n— The pinned `SNAPSHOT_ROOT` must live under\n`\u003Cstate_root>\u002F.mantis_snapshots\u002Fpass_\u003CN>` (or a clean-VCS worktree\u002Farchive), and\nits path **must not** contain the segment `\u002Fworkspace\u002F` — otherwise\n`mantis-patch`'s state-vs-code path guard misfires (state files appear to be\n\"under `CODE_ROOT`\"). If `state_root` itself is inside `CODE_ROOT`, the harness\nmust HALT-and-yield (safe default) or, when explicitly authorized (e.g.\n`--auto_relocate_state`), relocate it outside the snapshot before pinning. Block\nA step 3 distinguishes SNAPSHOT-RELATIVE path fields (read under `CODE_ROOT`)\nfrom STATE-RELATIVE fields (read under `state_root\u002Fworkspace`, never prefixed\nwith `CODE_ROOT`); colocation breaks this separation.\n\n**2. Stale active_snapshot** (`active_snapshot.pass != state.pass_number` —\n`active_snapshot` was preserved across the Stage 15 pass increment) — Block D\nstep 0 (crash-resume) handles only the SAME-pass re-entry case\n(`active_snapshot.pass == N` → reuse). It does NOT catch a stale snapshot\ncarried across the Stage 15 pass increment, because Stage 15 deliberately\npreserves `active_snapshot` while bumping `pass_number` (see Stage 15). Two\nsub-cases:\n\n(a) The prior snapshot dir is now MISSING: Block D step 0 STOPs and yields to\nthe user (never re-pin to a possibly-drifted live tree). (b) The prior snapshot\ndir still EXISTS (default keep-2 retention) and its sentinel matches the\npreserved `active_snapshot.snapshot_id`: Block A step 2 sentinel check SUCCEEDS\n(it only compares the sentinel file to `SNAPSHOT_ID`, not to the current pass).\nBlock B's pairwise `discovery_commit` check would MATCH a carried-forward\nfinding against a new finding stamped with the same stale `SNAPSHOT_ID`,\nsilently dropping it as `DUPLICATE` — a false authoritative verdict.\n\nTo prevent (b), the HARNESS MUST guarantee that\n`active_snapshot.pass == state.pass_number` before any consumer stage reads it.\nThe reference harness (`mantis-meta-agent`) satisfies this by re-pinning every\npass (Block D step 0 sees `active_snapshot.pass != N` → re-pins → refreshes\n`active_snapshot.pass` before any stage runs), so sub-case (b) never fires\nthere. A custom harness that preserves `active_snapshot` across the Stage 15\npass increment WITHOUT re-pinning MUST either (a) re-pin every pass (the\nreference behavior), or (b) inject an equivalent pre-stage gate that refreshes\n`active_snapshot.pass` or clears `active_snapshot` entirely before invoking\nstages. Stages CANNOT self-detect this staleness via Block B (which is\n`snapshot_id`-only, not `pass`-aware): a carried-forward finding and a new\nfinding stamped with the same stale `SNAPSHOT_ID` will MATCH in Block B despite\nthe snapshot being stale. The `active_snapshot.pass` field is defined in\n`schema.json` `#\u002F$defs\u002Fstate\u002Factive_snapshot\u002Fpass` for exactly this check. The\nharness's Block D step 0 reuse check is NOT a substitute: it only fires on\nsame-pass re-entry. (Stages that read `active_snapshot` MAY additionally\nself-check defensively — see each stage's Step 0 sentinel check — but the\nbinding guarantee is on the harness.)\n\n**3. Pin failure** (snapshot copy fails — disk full, permissions, too-large\ntree) — Block D step 2 (free-space precheck): compare `du -s` of the live tree\nto `df` free space at `state_root`; if it won't fit → skip copy → step 5b. Block\nD step 4 (failure-tolerant verify): check copy exit status + sanity check (file\ncount\u002Fsize within ~90%); on failure → step 5b (unpinned\u002FHALT). Step 5b:\n`SNAPSHOT_ROOT=\u003Clive root>`, `snapshot_pinned=false`,\n`SNAPSHOT_ID=\"live:\"+ISO8601`. The harness still writes `active_snapshot` and\nstill passes `--snapshot_root`\u002F`--snapshot_id` to stages so they see the HALT\nsignal. Every stage then degrades conservatively: authoritative verdicts\nforbidden (`VERIFIED_SECURE`, `failed_to_reproduce`, `DUPLICATE`,\n`FALSE_POSITIVE`, `NON_VIABLE`); Block B always returns NOT_MATCHED; reproduce\nrecords `not_attempted`; patch's best attainable is `VERIFICATION_INCOMPLETE`.\n\n**4. Patched shadows** (`--target_root` pointing at a pre-mutated tree;\nsentinel-exempt path 1a in Block A) — `mantis-patch` passes\n`--target_root=\u003CPATCHED_SHADOW_ROOT>` and `--snapshot_pinned=false` to the\nreproduce sub-agent for re-attack verification. Block A step 1a:\n`CODE_ROOT = --target_root` (authoritative override, overrides `--snapshot_root`\nand state fallback). Block A step 2: sentinel check SKIPPED (a `--target_root`\ntree is deliberately mutated and is sentinel-EXEMPT). The\n`--snapshot_pinned=false` argument is the sentinel-exemption, NOT a HALT signal\n— detect HALT by reading STATE (`active_snapshot.snapshot_id` starts with\n`live:`, equivalently `active_snapshot.snapshot_pinned` is `false` in state),\nnever from the argument passed on this invocation. The finding's\n`discovery_commit` is unaffected — it retains the pass-level `SNAPSHOT_ID` from\nwhen it was discovered; only the `--snapshot_pinned=false` argument is local to\nthe reattack invocation.\n\n**5. Different-snapshot duplicate candidates** (cross-pass dedupe where\n`discovery_commit` differs — the pairwise Block B NOT_MATCHED path) — Both\npasses pinned correctly; the findings simply come from different snapshots.\n`mantis-dedupe` Block B pairwise check compares the CURRENT finding's\n`discovery_commit` against the ARCHIVED finding's `discovery_commit` (NOT\nagainst the global `SNAPSHOT_ID`). If they differ → NOT_MATCHED. NOT_MATCHED\nkeeps the current finding ACTIVE and sets `possible_duplicate_of` (a soft,\nnon-terminal hint — the finding is NOT filtered or trashed). If the archived\nfinding was RESOLVED (`patch_status` in {`VERIFIED_SECURE`,\n`MITIGATION_PROPOSED`} OR `status`==`FALSE_POSITIVE` OR\n`production_viability`==`NON_VIABLE`) AND the pair is NOT_MATCHED → POSSIBLE\nREGRESSION: keep ACTIVE, add a history note, never filter (a reverted fix\nre-discovered on new code must never be trashed).\n\n**6. Absent sink evidence** (Block F — PoC compiles but produces no reached-sink\nevidence; `not_attempted` vs `failed_to_reproduce`) — `mantis-reproduce` Block\nF: if EVIDENCE is ABSENT (any compiler\u002Fbuild nonzero exit, exit 127\ncommand-not-found, exit 2 \"No such file\", or the sink was never reached) →\n`repro_status = not_attempted` (retry-eligible), STOP. NEVER\n`failed_to_reproduce`. In `--reattack` mode: leave `reattack_status` UNSET with\na history note \"setup_failed\" — NEVER `failed_to_bypass`. `failed_to_reproduce`\nis reserved for when the harness PROVABLY reached the vulnerable entrypoint —\ni.e. reached-sink evidence, not setup evidence — but the bug did not fire.\nReached-sink evidence must originate INSIDE the invoked path or from\ntarget-produced tracing\u002Fbacktraces: (a) a PoC script\u002Fsource harness writes\n`MANTIS_REACHED_ENTRYPOINT` to a sidecar file at the point just before the sink\ncall, within its own execution flow (the marker write is part of the invoked\npath, not a pre-launch step); OR (b) for binary\u002Ffirmware\u002Fraw-payload targets,\nthe captured crash backtrace or sanitizer trace (ASan\u002FUBSan\u002FMSan\u002FTSan)\nexplicitly names the target sink function (target-produced tracing). A marker\nwritten by an external wrapper BEFORE invoking the target is SETUP EVIDENCE ONLY\n(proves \"launch attempted,\" not \"sink reached\") and does NOT by itself justify\n`failed_to_reproduce` — treat it as EVIDENCE ABSENT for the decision gate.\nEvidence is recorded in `repro_hints`. In HALT mode, the HALT ceiling\nadditionally forces `not_attempted` (no `failed_to_reproduce`), since a negative\nresult on an unpinned tree cannot be trusted as authoritative.\n\n______________________________________________________________________\n\n### 6. Semantic Retrieval (RAG) for Large Codebases\n\nFor small repositories, the planner can manually scan `workspace\u002Fkb\u002Findex.md`\nand the researcher can grep for call-sites. At scale (thousands of files, deep\ndirectory trees, multi-pass campaigns), these approaches miss relevant context\nand waste tokens reading irrelevant files. A semantic retrieval layer lets the\nplanner and researcher query for relevant KB entries and code locations without\nreading everything.\n\nTwo implementations are supported, sharing the same data contract:\n\n- **Option A (Default — Skill-Based):** A dedicated skill that runs a\n  BM25\u002FTF-IDF helper script over `chunks.jsonl`. Zero external dependencies —\n  works air-gapped, no vector embeddings or vector store required. Optional\n  vector embedding support if available.\n- **Option B (Maximum Scale — MCP-Based):** The harness owns a persistent vector\n  index using vector embeddings, serving persistent `semantic_search_kb` \u002F\n  `semantic_search_code` MCP tools. Better for very large codebases where\n  per-invocation BM25 is too slow.\n\nBoth are **opt-in**. The existing skills are not modified; the planner and\nresearcher receive runtime instructions to use whichever retrieval mechanism is\navailable, falling back to today's manual behavior if neither is present.\nRetrieval results are **coverage HINTs only** — they decide ordering and\nprioritization, never the membership of the audit set. A miss must never cause a\nfile, call-site, or investigation to be skipped or dropped.\n\n#### A. Shared Data Contract: `chunks.jsonl`\n\nAfter Stage 2 (`\u002Fmantis-architecture`) completes, chunks are extracted into\n`workspace\u002Fkb\u002Fchunks.jsonl` (one JSON object per line). The harness can do this\npost-hoc by reading `workspace\u002Fkb\u002F*.md`, or the architecture skill can be\ninstructed to write it during synthesis as a text-only side effect. Two chunk\ntypes are produced:\n\n1. **KB chunks** from the existing `workspace\u002Fkb\u002F*.md` files:\n\n   ```json\n   {\"id\": \"auth_module:0\", \"source_file\": \"workspace\u002Fkb\u002Fentities\u002Fauth_module.md\", \"entity_type\": \"entity\", \"chunk_text\": \"The auth module handles...\"}\n   ```\n\n2. **Code chunks** from `CODE_ROOT` (the pinned snapshot). Each chunk includes\n   the file path and line range so the researcher can request specific files\n   from the snapshot:\n\n   ```json\n   {\"id\": \"src\u002Fparser.c:0\", \"source_file\": \"src\u002Fparser.c\", \"start_line\": 1, \"end_line\": 80, \"chunk_text\": \"int parse_input(...\"}\n   ```\n\nThe first line of `chunks.jsonl` is a provenance header recording the\n`SNAPSHOT_ID` the chunks were built against:\n\n```json\n{\"_provenance\": true, \"snapshot_id\": \"abc123\", \"kb_snapshot_id\": \"abc123\"}\n```\n\nBefore serving queries, check `snapshot_id` in the provenance header against the\ncurrent `SNAPSHOT_ID`; rebuild if they differ. In MODE-OFF (no\n`active_snapshot`), `kb_snapshot_id` is never stamped — skip the index entirely\nand let skills fall back to manual scanning. Never build code chunks from the\nlive tree — they must reflect the pinned copy the skills are reading.\n\n#### B. Option A: Skill-Based Retrieval (Default — No Infrastructure)\n\nA dedicated skill reads `chunks.jsonl` and writes+runs a helper script (e.g.\n`workspace\u002Fhelpers\u002Fsearch_chunks.py`) that performs BM25\u002FTF-IDF similarity\nsearch. The script is generated by the agent at runtime — no code is shipped\nwith the skill (same pattern as `mantis-dedupe`'s `merge_findings.py`). This\nrequires zero external dependencies — no embedding model, no vector store, no\nMCP server. It works in air-gapped and VPC-SC environments.\n\nA complete reference blueprint for this skill is available at\n[references\u002Fmantis-kb-query.md](references\u002Fmantis-kb-query.md). Builders can\nadapt it to their environment. The blueprint includes Block A (Locator\nResolution), chunk provenance checking, the versioned helper script contract\n(`MANTIS_HELPER_VERSION = 1`), and the JSON output schema.\n\n- **Invocation:** The planner or researcher spawns the skill as a sub-agent with\n  a query string. The skill writes the helper if not already present, runs it,\n  and returns top-K matching chunks as JSON.\n- **Optional embeddings:** If vector embeddings are available, the agent can be\n  instructed to use cosine similarity instead of BM25. This is a runtime\n  configuration toggle, not a different skill.\n- **Snapshot safety:** The skill reads `active_snapshot` from state via Block A\n  (same as every other skill) and checks chunk provenance before serving.\n\n#### C. Option B: MCP-Based Retrieval (For Maximum Scale)\n\nFor very large codebases where per-invocation BM25 is too slow, the harness can\nown a persistent vector index using vector embeddings, serving two MCP tools\n(following the same pattern as Guideline 2's Custom MCP for VMs\u002Fhardware):\n\n- `semantic_search_kb(query: string) → [{id, source_file, entity_type, chunk_text, score}]`\n  — Searches KB chunks. Returns relevant entity\u002Fvulnerability markdown context.\n\n- `semantic_search_code(query: string) → [{file, start_line, end_line, snippet, score}]`\n  — Searches code chunks from the pinned snapshot. Returns relevant code\n  locations.\n\nThe harness manages the vector index lifecycle: build from `chunks.jsonl` (or\ndirectly from `CODE_ROOT`), rebuild when `SNAPSHOT_ID` changes, and handle\nfreshness checks. In HALT mode, serve with a `STALE` flag or refuse. In\nMODE-OFF, skip entirely.\n\n#### D. Per-Skill Augmentation Guidance\n\nWhen a retrieval mechanism (skill or MCP) is available, instruct the following\nskills to use it. These are runtime instructions passed by the harness or\nmeta-agent when invoking the skill — the skill files themselves are not\nmodified:\n\n- **mantis-architecture:** No changes needed. The harness chunks the existing\n  `workspace\u002Fkb\u002F*.md` files after the architect completes Stage 2. If the\n  builder prefers, they may instruct the architect to also write\n  `workspace\u002Fkb\u002Fchunks.jsonl` during synthesis (Step 3) as a text-only side\n  effect — but this is optional, since the harness can extract chunks post-hoc.\n\n- **mantis-plan:** If a retrieval mechanism is available, instruct the planner\n  to use it to discover `kb_references` for each investigation instead of only\n  manually scanning `workspace\u002Fkb\u002Findex.md`. For each investigation, query with\n  the investigation title and target file names, then add the top-K matching KB\n  entity\u002Fvulnerability files to the `kb_references` array. Manual scanning of\n  `index.md` remains the fallback when no mechanism is available.\n\n- **mantis-researcher:** If a retrieval mechanism is available, instruct Wave 1\n  sub-agents to use it to PRIORITIZE relevant call-sites and cross-module data\n  flows into sinks (e.g., \"where does untrusted input reach `memcpy` in the\n  parser module\"). Semantic search SUPPLEMENTS grep as a ranking HINT ONLY — it\n  decides ORDER, never MEMBERSHIP of the audit set. It MUST NEVER replace the\n  exhaustive Step-3 call-site sweep; every call-site or data-flow that a full\n  grep would reach must still be audited whether or not it ranks in top-K. Audit\n  the union of grep results and semantic search results. The researcher's\n  existing Wave 1\u002FWave 2 structure is unchanged.\n\n#### E. Snapshot Safety\n\nThe retrieval index — whether served by the skill or the harness — is a **cache\nof the pinned snapshot**, never a live view:\n\n- Build code chunks from `CODE_ROOT` (the pinned snapshot), not the live tree.\n- Rebuild when `SNAPSHOT_ID` changes (new pass, new pin).\n- In HALT mode (`snapshot_pinned=false`), serve results with a `STALE` flag or\n  refuse to serve — same conservative degradation as every other stage.\n- In MODE-OFF, skip the index entirely.\n\n______________________________________________________________________\n\n### 7. Embedding-Based Deduplication Pre-Filtering\n\nWhen the pipeline runs many passes over a large codebase, the deduplicator\n(`\u002Fmantis-dedupe`) must compare each current finding against every archived\nfinding — an O(n×m) comparison performed by an LLM reading summaries. At scale\n(hundreds of findings across many passes), this is token-expensive and slow.\n\nThe harness can use embeddings as a **fast pre-filter** to reduce the candidate\nspace before invoking `\u002Fmantis-dedupe`. The skill's existing deterministic\nmatching (`code_paths` + `title` + `discovery_commit`) remains the **sole\nauthority** for hard dedup decisions.\n\n**This is entirely harness-side and opt-in.** `\u002Fmantis-dedupe` is not modified.\n\n#### A. How It Works\n\n1. **Harness Action:** Reads all `workspace\u002Ffindings\u002F*.json` (current) and\n   `workspace\u002Farchive\u002Ffindings_pass_*\u002F*.json` (archived). For each finding,\n   computes an embedding from a normalized text representation (e.g.,\n   `title + description + first code_paths entry with line stripped`).\n\n2. **Harness Action:** Computes pairwise cosine similarity between current and\n   archived findings. Surfaces candidate pairs above a configurable threshold\n   (e.g., 0.85).\n\n3. **Harness Action:** Writes a candidate-pairs manifest (e.g.,\n   `workspace\u002Fhelpers\u002Fdedup_candidates.json`) containing the UUID pairs and\n   similarity scores.\n\n4. **mantis-dedupe invocation:** The harness invokes `\u002Fmantis-dedupe` as usual.\n   If the candidate manifest exists, instruct the skill to read it and\n   prioritize those pairs for the LLM's pairwise comparison, instead of\n   comparing every finding against every archived finding. **All existing\n   deterministic matching rules apply unchanged** — the manifest only narrows\n   the search space.\n\n#### B. Safety Guardrails\n\n- **Pre-filter only, never the decision.** The embedding similarity score can\n  never cause a `DUPLICATE` verdict, a trash move, or a `possible_duplicate_of`\n  assignment. Only the skill's existing `code_paths`, `title`, and\n  `discovery_commit` checks can do that. A miss in the pre-filter only\n  over-retains a duplicate (safe — the LLM sees it and skips it); it never\n  under-retains (never drops a real duplicate).\n\n- **No false negatives.** The threshold should be set low enough (e.g., 0.75) to\n  avoid missing true duplicates. Better to surface too many candidates than to\n  miss a real one — the LLM and deterministic matching will filter false\n  positives.\n\n- **Fallback on failure.** If the embedding computation is unavailable, the\n  candidate manifest is absent, or any error occurs, `\u002Fmantis-dedupe` falls back\n  to its existing O(n×m) comparison. The skill must not stop or error if the\n  manifest is missing.\n\n- **Snapshot awareness.** The harness should not compute embeddings across\n  different `discovery_commit` values without flagging them as cross-snapshot\n  candidates — the skill's Block B pairwise check will handle the final\n  MATCHED\u002FNOT_MATCHED decision.\n\n#### C. Shared Infrastructure\n\nIf the builder also implements Guideline 6 (Semantic Retrieval), reuse the same\nvector embedding infrastructure for finding embeddings. The finding embedding is\na different payload (finding JSON, not KB chunks) but the same embedding\ncapability can serve both.\n\n#### D. Enterprise Vector Architecture & Cloud Scalability\n\nFor enterprise deployments tracking hundreds of thousands of vulnerabilities\nacross distributed codebases and multi-tenant audit pipelines, SQLite vector\nstorage can be swapped for managed cloud vector engines:\n\n- **Cloud Spanner Vector Search:**\n  - *Best For*: Mission-critical enterprise pipelines requiring global ACID\n    consistency, 99.999% availability, and synchronized finding lineage\n    tracking.\n  - *Architecture*: Store findings and `lineage_vectors` in Spanner with\n    `ARRAY\u003CFLOAT32>` vector columns. Utilize `COSINE_DISTANCE` with KNN search\n    indexes for real-time finding deduplication during parallel scan passes.\n- **Cloud SQL for PostgreSQL (`pgvector`):**\n  - *Best For*: Standard enterprise relational backends needing ACID compliance\n    with low operational complexity.\n  - *Architecture*: Enable the `vector` extension. Store finding embeddings in a\n    `vector(768)` or `vector(256)` column with HNSW (`vector_cosine_ops`) or\n    IVFFlat indexes for sub-millisecond similarity queries.\n- **AlloyDB for PostgreSQL:**\n  - *Best For*: High-throughput multi-agent audit farms running concurrent\n    research waves.\n  - *Architecture*: Leverage AlloyDB's columnar vector engine and ScaNN-based\n    approximate nearest neighbor indexing for up to 10x faster vector queries\n    over standard PostgreSQL.\n- **BigQuery Vector Search:**\n  - *Best For*: Batch analytical processing, organization-wide threat\n    intelligence clustering, and cross-campaign vulnerability lineage analysis.\n  - *Architecture*: Ingest finding embeddings into BigQuery and execute\n    `VECTOR_SEARCH(TABLE findings, 'embedding', ...)` with `COSINE` distance for\n    serverless batch deduplication and historical regression analytics.\n\n______________________________________________________________________\n\n### 8. SAST Seeding (External Tool Ingestion)\n\nMantis's discovery engine is 100% LLM-generative (grep swarm + reasoning). A\nweak LLM can structurally under-detect whole-program taint classes (injection,\npath traversal, deserialization, UAF, format-string) that mature SAST tools\n(CodeQL, Semgrep-taint) encode as interprocedural queries. A SAST seeding\nadapter ingests external tool findings as `PROVISIONALLY_VALID` \u002F\n`NEEDS_RESEARCH` candidates that must earn their verdict through the unchanged\ndownstream gates. This is purely additive (INV-2-strengthening) — it expands\ndetection breadth without weakening any verification gate.\n\nThis follows exactly the RAG pattern from Guideline 6: opt-in, default off,\nprovenance-tracked, snapshot-aware, fallback on failure.\n\n**Platform-agnostic IR (not SARIF):** Rather than tying the adapter to SARIF (a\ncomplex, tool-specific format), the adapter consumes a minimal JSONL\nintermediate representation (IR). Any SAST tool's output (SARIF, Semgrep JSON,\nBandit JSON, etc.) is converted to this IR by a thin wrapper. This maximizes\nplatform agnosticism — the adapter works with any tool that can produce the\nsimple JSONL format.\n\nTwo implementations are supported, sharing the same data contract:\n\n- **Option A (Default — Skill-Based):** A dedicated skill (`\u002Fmantis-sast-seed`)\n  reads the IR and uses LLM reasoning to normalize findings into mantis finding\n  JSONs. The LLM reads actual source code at each reported location under\n  CODE_ROOT to verify the finding and enrich the description with root-cause\n  analysis. Zero external dependencies — works air-gapped.\n- **Option B (Maximum Control — Harness-Based):** The harness directly\n  normalizes SAST output into finding JSONs using deterministic code (e.g., a\n  SARIF-to-finding converter script), bypassing the LLM for the normalization\n  step. The harness writes finding JSONs to `workspace\u002Ffindings\u002F` before\n  invoking `\u002Fmantis-dedupe`.\n\nBoth are **opt-in**. The existing skills are not modified. Seeded findings enter\n`workspace\u002Ffindings\u002F` alongside researcher findings and flow through the\nunchanged downstream gates (dedupe -> review -> critic -> reproduce -> patch ->\ncalibrate).\n\nA complete reference blueprint is available at\n[references\u002Fmantis-sast-seed.md](references\u002Fmantis-sast-seed.md).\n\n#### A. Shared Data Contract: `sast_findings.jsonl`\n\nThe IR is a JSONL file at `workspace\u002Fsast_findings.jsonl` (STATE-RELATIVE). It\nfollows the same provenance-header pattern as `chunks.jsonl` (Guideline 6A).\n\n**Line 1 — Provenance header:**\n\n```json\n{\"_provenance\": true, \"scan_snapshot_id\": \"abc123def456\", \"tool\": \"codeql\", \"tool_version\": \"2.15.0\", \"scan_timestamp\": \"2026-07-22T10:00:00Z\"}\n```\n\n- `scan_snapshot_id`: The SNAPSHOT_ID the scan was run against. This is the\n  **primary provenance anchor** — compared byte-for-byte to the current pass\n  `SNAPSHOT_ID` (same comparison as Block B). If the harness ran the SAST tool\n  against the pinned CODE_ROOT, it sets this to `SNAPSHOT_ID`.\n- `tool`: Tool name (e.g., `codeql`, `semgrep`, `bandit`). Informational.\n- `tool_version`: Tool version. Informational.\n- `scan_timestamp`: ISO 8601. Informational.\n\n**Lines 2+ — One finding per line:**\n\n```json\n{\"rule_id\": \"cpp\u002Fsql-injection\", \"rule_name\": \"SQL injection\", \"cwe\": \"CWE-89\", \"severity\": \"HIGH\", \"code_paths\": [\"src\u002Fdb\u002Fquery.c:42\"], \"message\": \"User input flows into SQL query without sanitization\"}\n```\n\n| Field        | Type   | Required | Description                                        |\n| ------------ | ------ | -------- | -------------------------------------------------- |\n| `rule_id`    | string | Yes      | Tool-specific rule identifier                      |\n| `severity`   | string | Yes      | `CRITICAL`, `HIGH`, `MEDIUM`, `LOW` (Mantis scale) |\n| `code_paths` | array  | Yes      | Array of `\"file:line\"` strings (SNAPSHOT-RELATIVE) |\n| `message`    | string | Yes      | Original SAST finding message                      |\n| `rule_name`  | string | No       | Human-readable rule name                           |\n| `cwe`        | string | No       | CWE identifier (e.g., `CWE-89`)                    |\n\n**IR conversion (harness responsibility):** The harness converts SAST tool\noutput to this IR before invoking the adapter. Conversion examples:\n\n- SARIF: extract `ruleId`, map `level` to severity (`error`->`HIGH`,\n  `warning`->`MEDIUM`, `note`->`LOW`), extract `locations` to `code_paths`, copy\n  `message.text`.\n- Semgrep JSON: extract `check_id` as `rule_id`, map `extra.severity` to Mantis\n  severity, extract `path:start.line` as `code_paths`, copy `extra.message`.\n\n#### B. Option A: Skill-Based Ingestion (Default — No Infrastructure)\n\nA dedicated skill reads `sast_findings.jsonl`, applies allow-listing, verifies\nprovenance, computes `signature`\u002F`lineage_id`\u002F`discovery_commit`, and writes\nfinding JSONs. The LLM reads actual source code at each reported location under\nCODE_ROOT to verify the finding and enrich the description.\n\n- **Invocation:** The harness invokes `\u002Fmantis-sast-seed` with\n  `--snapshot_root`\u002F`--snapshot_id`\u002F`--state_root` after Stage 6 (Research) and\n  before Stage 7 (Dedupe). The seeded findings land in `workspace\u002Ffindings\u002F`\n  before `\u002Fmantis-dedupe` runs.\n- **Inert until wired:** If `sast_findings.jsonl` is absent, the skill outputs\n  nothing and notifies the caller. It never fails — it simply returns empty.\n- **Anti-hallucination:** The LLM MUST read the actual code at each reported\n  location before writing the finding JSON. It MUST NOT invent findings not\n  present in the SAST output. The `sast_provenance.line_verified` field records\n  whether verification succeeded.\n- **Snapshot safety:** The skill reads `active_snapshot` from state via Block A\n  and stamps `discovery_commit` only when the snapshot is pinned and the\n  finding's location is verified under CODE_ROOT.\n\n#### C. Option B: Harness-Based Ingestion (For Deterministic Ingestion)\n\nFor maximum determinism, the harness can normalize SAST output into finding\nJSONs using deterministic code. This bypasses the LLM for the normalization\nstep:\n\n1. **Harness Action:** Reads the SAST tool output, parses it deterministically,\n   and writes finding JSONs to `workspace\u002Ffindings\u002F`.\n2. **Harness Action:** Stamps `discovery_commit` only if the scan provably ran\n   against the pinned CODE_ROOT.\n3. **Harness Action:** Applies allow-listing filters.\n4. **mantis-dedupe invocation:** Proceeds as usual — the seeded findings are\n   indistinguishable from researcher findings.\n\n#### D. Provenance Verification\n\nThe adapter stamps `discovery_commit` ONLY if the scan provably ran against a\nline-identical pinned CODE_ROOT. Verification ladder:\n\n1. Read `active_snapshot` from `workspace\u002F.mantis_state.json` (via Block A). If\n   absent, this is MODE-OFF — skip to step 5.\n2. If `snapshot_pinned` is false, this is HALT — skip to step 6.\n3. Read the IR provenance header's `scan_snapshot_id`.\n4. **VERIFIED**: `scan_snapshot_id` present AND exactly equals `SNAPSHOT_ID`.\n   Stamp `discovery_commit = SNAPSHOT_ID`. Status = `PROVISIONALLY_VALID`.\n5. **MODE-OFF**: `active_snapshot` absent. OMIT `discovery_commit`. Status =\n   `PROVISIONALLY_VALID` (MODE-OFF permits all verdicts).\n6. **HALT**: `snapshot_pinned` is false. OMIT `discovery_commit`. Status =\n   `NEEDS_RESEARCH`.\n7. **DRIFT**: `scan_snapshot_id` present but differs. OMIT `discovery_commit`\n   entirely. Status = `NEEDS_RESEARCH`.\n8. **UNVERIFIED**: `scan_snapshot_id` absent. OMIT `discovery_commit`. Status =\n   `NEEDS_RESEARCH`.\n\n**Line-existence verification** (additional check when VERIFIED or DRIFT and\nCODE_ROOT is resolved): For each finding, verify each `code_paths` entry: strip\ntrailing `:line`, check file exists under CODE_ROOT, check line number is within\nfile's line count. If file missing or line out of range -> downgrade to DRIFT\n(omit `discovery_commit`, status = `NEEDS_RESEARCH`).\n\nThis is the exact same \"UNTRUSTED-IF-ABSENT\" pattern as `discovery_commit`\n(schema.json) and `signature`\u002F`lineage_id`.\n\n#### E. Allow-Listing and Noise Control\n\n`workspace\u002Fsast_allowlist.json` (optional config file, STATE-RELATIVE):\n\n```json\n{\n  \"enabled\": true,\n  \"severity_filter\": [\"CRITICAL\", \"HIGH\"],\n  \"cwe_allowlist\": {\n    \"enabled\": true,\n    \"cwes\": [\"CWE-89\", \"CWE-78\", \"CWE-79\", \"CWE-22\", \"CWE-787\", \"CWE-416\", \"CWE-502\"]\n  },\n  \"rule_allowlist\": {\n    \"enabled\": false,\n    \"rules\": []\n  },\n  \"per_rule_cap\": 5,\n  \"total_cap\": 50\n}\n```\n\nIf the config file is absent, defaults apply: CRITICAL+HIGH only,\n`per_rule_cap=5`, `total_cap=50`.\n\n**How allow-listing protects the retry cap:** The reproduce stage\n(`\u002Fmantis-reproduce`) has a hard ceiling of 6 attempts per finding (absolute,\nnever reset). If 1000 SAST findings are seeded without filtering, the reproduce\nstage would need up to 6000 attempts — starving the retry budget. The\nallow-listing chain (severity filter -> CWE\u002Frule filters -> per-rule cap ->\ntotal cap) ensures only a bounded, high-signal set of candidates enters the\npipeline. The review (13-rule negative filter) and critic (production viability)\nstages further filter before reproduce runs.\n\n#### F. Per-Skill Augmentation Guidance\n\nWhen the SAST seed skill is available, instruct the harness to invoke it between\nStage 6 (Research) and Stage 7 (Dedupe). These are runtime instructions passed\nby the harness — the skill files themselves are not modified:\n\n- **mantis-meta-agent:** Invoke `\u002Fmantis-sast-seed` with\n  `--snapshot_root`\u002F`--snapshot_id`\u002F`--state_root` after `\u002Fmantis-researcher`\n  completes and before `\u002Fmantis-dedupe`.\n- **mantis-dedupe:** No changes needed. Seeded findings are in\n  `workspace\u002Ffindings\u002F` alongside researcher findings. Dedupe processes them\n  identically (signature-based matching, Block B pairwise check).\n- **mantis-review:** No changes needed. The 13-rule negative filter applies to\n  seeded findings identically.\n- **mantis-report:** No changes needed. The `sast_provenance` field is\n  informational and can be displayed in reports.\n\n#### G. Snapshot Safety\n\nThe SAST seed adapter follows Block A (Locator Resolution) exactly like every\nother code-reading skill:\n\n- Resolve CODE_ROOT from `--snapshot_root` \u002F state `active_snapshot`.\n- Honor the sentinel check (Block A step 2).\n- Read source files under CODE_ROOT (SNAPSHOT-RELATIVE) for line-existence\n  verification.\n- Write findings under `state_root\u002Fworkspace\u002Ffindings\u002F` (STATE-RELATIVE).\n- Never write under CODE_ROOT when pinned.\n- In MODE-OFF: proceed without `discovery_commit`. All verdicts permitted.\n- In HALT: omit `discovery_commit`. Seeded findings get `NEEDS_RESEARCH`.\n- In PINNED: verify each finding's location under CODE_ROOT, stamp\n  `discovery_commit = SNAPSHOT_ID` if verified.\n\nThe SAST tool output itself is NOT snapshot-aware — it may have been produced\nagainst a different tree. The adapter's provenance verification is what bridges\nthe gap: it re-grounds each finding against the pinned CODE_ROOT before stamping\n`discovery_commit`.\n\n#### H. Safety Guardrails\n\n- **Purely additive.** Seeded findings are `PROVISIONALLY_VALID` \u002F\n  `NEEDS_RESEARCH` candidates. They must pass through the unchanged downstream\n  gates: dedupe (Block B), review (13-rule filter), critic (viability),\n  reproduce (Block F reached-sink evidence + HALT ceiling), patch (Block G\n  re-attack), calibrate (sanity caps). No gate is weakened.\n- **No false `VERIFIED_SECURE`.** Seeded findings start at `PROVISIONALLY_VALID`\n  — they can never reach `VERIFIED_SECURE` without passing through the full\n  patch + re-attack pipeline.\n- **No false `failed_to_reproduce`.** Seeded findings that reach reproduce are\n  subject to the same Block F evidence gate and HALT ceiling.\n- **No dropped regression.** If a SAST-seeded finding matches an archived\n  finding with a different `discovery_commit`, Block B returns NOT_MATCHED ->\n  `possible_duplicate_of` -> finding stays active.\n- **Fail-safe on missing data.** If `sast_findings.jsonl` is absent, no findings\n  written. If a finding can't be verified, `NEEDS_RESEARCH`.\n- **No existing skills modified.** The adapter writes findings to\n  `workspace\u002Ffindings\u002F` before `\u002Fmantis-dedupe` runs.\n- **`sast_provenance` is informational only.** It does not affect any safety-\n  critical invariant, gate, or verdict. The finding's `discovery_commit` is the\n  field that governs Block B snapshot matching.\n\n______________________________________________________________________\n\n### 9. Structural Code Index (AST-Level Context)\n\nFor small repositories, the researcher can grep for call-sites and the planner\ncan infer dependencies. At scale, grep-based call-site discovery is unreliable\n(misses indirect calls, cannot distinguish calls from comments\u002Fstrings, no\nfunction boundary awareness). A structural code index provides AST-level context\n(function boundaries, call graphs, symbol tables) to improve LLM reasoning\nquality during discovery.\n\nThis follows the RAG pattern from Guideline 6: optional, provenance-tracked,\nsnapshot-aware, fallback on failure. The structural index is a **coverage HINT\nonly** — it decides ordering and prioritization, never the membership of the\naudit set. A miss must never cause a file, call-site, or investigation to be\nskipped or dropped.\n\nThe full specification — including the manifest schema, SQLite serving store,\ncapability-based per-partition backend selection, canonical symbol IDs, query\ninterface, baseline-plus-delta overlay, deterministic partial coverage, and\nsafety guardrails — lives in a single source of truth:\n\n**→ [..\u002Fmantis-structural-index\u002FSKILL.md](..\u002Fmantis-structural-index\u002FSKILL.md)**\n\nA thin reference blueprint is at\n[references\u002Fmantis-structural-index.md](references\u002Fmantis-structural-index.md).\n\nTwo implementations are supported, sharing the same query contract:\n\n- **Option A (Default — Skill-Based):** The `mantis-structural-index` skill\n  generates and runs helper scripts (`build_structural_index.py` and\n  `query_structural_index.py`, both `# MANTIS_HELPER_VERSION = 5`) using\n  capability-based per-partition backend selection, degrading to grep.\n- **Option B (Maximum Power — MCP-Based):** The harness owns a persistent\n  structural index serving `find_callers(symbol)`, `find_callees(function)`,\n  `get_function_boundary(file, line)` MCP tools, backed by the same SQLite\n  serving store.\n\nBoth are **optional**. A non-conformant harness simply skips the structural\nindex stage. The structural index supplements grep as a ranking HINT ONLY — it\ndecides ORDER, never MEMBERSHIP of the audit set.\n\nConsumers MUST use the query interface (`query_structural_index.py`) rather than\nfiltering JSONL directly. The query interface provides bounded results,\npagination, explicit name resolution, precision\u002Fbackend metadata, and coverage\non empty results.\n\n#### D. Per-Skill Augmentation Guidance\n\nWhen a structural index is available, instruct the following skills to use it.\nThese are the consumption contract — runtime instructions passed by the harness.\nThe structural index is a HINT-only enhancement; skills that do not use it\nbehave exactly as they do today:\n\n- **mantis-architecture:** Optionally read the pre-built structural index (built\n  by `mantis-structural-index` at Stage 0.5) during KB synthesis,\n  cross-referencing it with `dependencies.json`.\n- **mantis-plan:** Use the structural index for function-level dependency\n  fan-out (more precise than file-level `dependencies.json`).\n- **mantis-researcher:** Wave 1 sub-agents use `find_callers()` to SUPPLEMENT\n  grep as a ranking HINT for call-site discovery — it decides ORDER, never\n  MEMBERSHIP. It MUST NEVER replace the exhaustive Step-3 call-site sweep; every\n  call-site that a full grep would reach must still be audited whether or not it\n  ranks in the structural index. Audit the union of grep results and structural\n  index results. Wave 2 deep auditors use `get_function_boundary()` to start\n  with the enclosing function, expanding to callers\u002Fcallees\u002Ffile as needed for\n  cross-function context. The researcher's existing Wave 1\u002FWave 2 structure is\n  unchanged.\n\n#### E. Integration with RAG (Guideline 6)\n\n- Structural index entries can be added to `chunks.jsonl` as\n  `entity_type: \"structural\"` chunks.\n- Code chunks can become function-boundary-aligned (instead of dumb line-range\n  slices) by using function boundaries from the structural index.\n- The structural index and the RAG index can share the same vector embedding\n  infrastructure if both are implemented.\n\n______________________________________________________________________\n\n### 10. Tiered Iterative Reproduction & Multi-Conversation Retry Strategy\n\nFor complex services, attempting a single-shot reproduction directly against a\nfull sandboxed service often suffers from high search entropy, brittle\nconfiguration, and hard-to-debug failures. A tiered strategy breaks reproduction\ninto incremental milestones, while an inter-conversation retry architecture\nprevents reasoning deadlocks and context bloat.\n\n#### A. Orchestration & Inter-Conversation Retries\n\n1. **Intra-Conversation Retries (Local Agent Trajectory):**\n\n   - The active subagent conversation retries 2–3 times locally within its\n     context window to adjust parameters, fix setup bugs, or refine payloads.\n\n2. **Inter-Conversation Retries (Fresh Context + Accumulated Artifacts):**\n\n   - **Trigger:** If intra-conversation retries fail to reach Tier 3\n     (`reproduced`), the orchestrator terminates the stalled conversation and\n     launches a **new subagent conversation** (a fresh context window).\n   - **Context Provisioning:** The orchestrator populates the new prompt with\n     structured attempt data from\n     `state_root\u002Fworkspace\u002Farchive\u002F.repro_attempts.json` and trajectory\n     learnings from `workspace\u002Flearnings.jsonl` (e.g., *\"Attempt 1 failed due to\n     missing auth header X; Attempt 2 proved parser strips unescaped quotes\"*).\n   - **Benefit:** Eliminates context bloat and reasoning inertia (\"hallucination\n     traps\"), enabling a fresh agent to solve the problem using prior empirical\n     observations without repeating past mistakes.\n\n3. **Attempt Cap Accounting & Arithmetic:**\n\n   - The orchestrator maintains\n     `state_root\u002Fworkspace\u002Farchive\u002F.repro_attempts.json`.\n   - **Tier 3 Increment Only:** Only Tier-3 full sandboxed service executions\n     (or full end-to-end reproducer runs) increment the per-finding attempt\n     counter toward the absolute hard ceiling of 6.\n   - **Stepping-Stone Sub-Budget:** Internal Tier-1 and Tier-2 trial runs are\n     bounded by a local sub-budget (max 3 trial executions per conversation) and\n     do not consume the absolute 6-attempt cap.\n\n#### B. Harness-Enforced Tier 4 (Staging & Live Pre-Production Execution)\n\nTo prevent un-gated exploit execution on live infrastructure, Tier 4 (Staging \u002F\nPre-Production verification) is **strictly owned and enforced by the\nprogrammatic orchestrator harness**, never by LLM discretion:\n\n- **Sandbox Boundary:** `mantis-reproduce` executes strictly within isolated\n  local sandboxes (Tiers 1–3) ending at Tier 3 (`reproduced` \u002F\n  `failed_to_reproduce`).\n- **Deterministic Gate:** The harness intercepts a Tier 3 `reproduced` verdict.\n  If live\u002Fstaging validation (Tier 4) is configured, the harness **MUST NOT**\n  automatically invoke remote execution. It must enforce a **programmatic\n  Human-in-the-Loop gate**:\n  - Prompt the human operator for explicit interactive confirmation, OR\n  - Require a cryptographically signed approval token \u002F authorization callback.\n- **Fail-Closed Default:** If human approval is missing or denied, Tier 4 is\n  skipped and the Tier 3 sandboxed verdict remains authoritative.\n\n#### C. Local Ingress \u002F Middlebox Edge Annotation (Post-Tier-3 Sandbox Verification)\n\nTo eliminate false-positive findings caused by default edge filters (\"Works on\nlocalhost:8080, but dies at the WAF\u002Fproxy\"), the orchestrator can optionally\nexecute a Tier 3 PoC through a local reverse proxy or API gateway (e.g. NGINX,\nEnvoy, ModSecurity) running inside the local sandbox:\n\n- **Annotation Only:** A payload blocked by a local middlebox MUST NOT downgrade\n  a Tier 3 `reproduced` verdict to `failed_to_reproduce`.\n- **Critic Integration:** The harness records `ingress_blocked: true` (or edge\n  filter details) in the finding's `repro_hints` or history. This provides\n  empirical evidence for `\u002Fmantis-critic` to classify `production_viability` as\n  `\"CONDITIONAL_VIABLE\"` (mitigated by default edge proxy configuration).\n","# Mantis Pipeline Designer (\u002Fmantis-pipeline-adapter)\n\n## System Goal\n\nInteractive Pipeline Design Consultant. Assists the user in designing and\nimplementing their own deterministic orchestrator harness for Mantis Skills.\nHelps the user apply best practices for reliability, token efficiency, and\ncustom environment integration.\n\n## Command Definition\n\n- **Command:** `\u002Fmantis-pipeline-adapter`\n- **Description:** Interactively guides the design and implementation of custom\n  deterministic orchestrator harnesses.\n\n## Input\u002FOutput Contract\n\n- **Reads**:\n  - `workspace\u002F.mantis_state.json` (to track current loop pass).\n  - `workspace\u002F.mantis_state.json` fields `active_snapshot`, `snapshot_history`,\n    and `vcs_info.snapshot_id` — the per-pass snapshot pin, present only when\n    the target harness has opted into sync (absent on today's single-snapshot\n    runs; see Reference Architecture Guideline 5).\n  - `schema.json` (as the canonical pipeline specification reference).\n  - `workspace\u002Ffindings\u002F*.json` (as the State Store).\n  - `workspace\u002Flearnings.jsonl` (to understand memory rotation).\n  - User's interactive configuration input.\n- **Writes**:\n  - Outputs user-customized orchestrator harness code, configurations, or\n    architecture documentation.\n- **Preconditions**:\n  - User initiates interactive design session.\n- **Idempotency Guarantee**:\n  - As a consulting agent, it advises the user to implement idempotency in their\n    custom harness using three primary mechanisms: (1) state store\n    synchronization, (2) atomic transactional file\u002FVCS operations, and (3)\n    proper locks (e.g. database\u002Ffile level locks).\n\n## Instructions\n\nInteractively guide the user in designing and building a deterministic pipeline\nthat wraps Mantis Skills.\n\nFollow these guidelines during the consultation:\n\n01. **Understand User Context:** Ask about their target programming language,\n    agent framework (if any), execution environments (VMs, local containers,\n    physical hardware), and scale requirements.\n02. **Recommend Core Principles:** Guide them to implement the reference\n    architecture patterns (detailed below), specifically emphasizing:\n    - **Deterministic Orchestration**: Use code (not LLM) for control flow.\n    - **State Store**: Use a database or structured filesystem as the single\n      source of truth.\n    - **Token Efficiency**: Use the UUID-based referencing pattern to avoid LLM\n      text duplication.\n    - **Custom Environment Integration**: Use Custom MCP servers for isolated\n      testing (VMs) or hardware interaction.\n03. **Ensure Schema Consistency**: Advise the user to strictly adhere to the\n    inter-stage data contracts defined in [schema.json](..\u002F..\u002Fschema.json) when\n    building their harness.\n04. **Adaptive Design**: Help them draft the code\u002Farchitecture tailored to their\n    specific stack, rather than imposing a rigid template.\n05. **Advise on Scale and Concurrency**: If they have high-scale needs, guide\n    them on decomposing the pipeline and implementing locking mechanisms to\n    prevent race conditions.\n06. **Suggest Evaluations:** Remind them to perform empirical evaluations when\n    choosing cheaper models for utility stages.\n07. **Advise the Pass Lifecycle Contract (living \u002F synced codebases):** If the\n    user wants their harness to *continue a run after the target code changes*,\n    or to *sync the target repo at the start of a new pass*, walk them through\n    the harness-agnostic Pass Lifecycle Contract in Reference Architecture\n    Guideline 5 below. Emphasize that this support is **opt-in**: a harness that\n    does not implement the contract MUST leave `snapshot_pinned` unset, which\n    preserves today's single-snapshot behavior byte-for-byte. When `--sync` is\n    requested, the harness PINs in the PIN step and passes\n    `--snapshot_root`\u002F`--snapshot_id` normally; Block A (Locator Resolution) is\n    universal across all code-reading stages.\n08. **Advise on Semantic Retrieval at Scale:** If the user is targeting a large\n    codebase (e.g., thousands of source files, multi-pass campaigns, or multiple\n    teams contributing findings), walk them through the optional semantic\n    retrieval patterns in Reference Architecture Guidelines 6 and 7 below.\n    Emphasize that these are **opt-in**: they augment the pipeline via a\n    dedicated query skill or MCP tools, but never modify the existing skills'\n    own deterministic logic or fail-safe invariants.\n09. **Advise on SAST Seeding:** If the user wants to augment LLM-based discovery\n    with external SAST tool findings (CodeQL, Semgrep, etc.), walk them through\n    the optional SAST seeding pattern in Reference Architecture Guideline 8\n    below. Emphasize that this is **opt-in**: it ingests external findings as\n    candidates that must earn their verdict through unchanged downstream gates,\n    and it follows exactly the RAG pattern (provenance-tracked, snapshot-aware,\n    fallback on failure).\n10. **Advise on Structural Code Indexing:** If the user is targeting a large\n    codebase where grep-based call-site discovery is unreliable, walk them\n    through the optional structural code index stage in Reference Architecture\n    Guideline 9 below. Emphasize that this is an **optional first-class stage**:\n    it provides structural context (function boundaries, call graphs) to improve\n    LLM reasoning, runs after the snapshot is pinned and before the first\n    code-reading analysis stage, and degrades gracefully to grep when\n    unavailable.\n11. **Advise on Tiered Iterative Reproduction & Multi-Conversation Retries:** If\n    the user is targeting complex services where single-shot repro is brittle,\n    walk them through the tiered iterative reproduction strategy and\n    multi-conversation retry pattern in Reference Architecture Guideline 10.\n\n## Reference Architecture Guidelines\n\nUse the following guidelines as your technical reference when advising the user.\n\n### Core Principles\n\n1. **Deterministic Orchestration:** Do not let the LLM decide the control flow\n   of the pipeline. Use a programmatic harness to call skills sequentially or in\n   parallel.\n2. **State on Disk \u002F Database:** Use the filesystem\n   (`workspace\u002Ffindings\u002F*.json`) or a database as the single source of truth.\n   Skills should read from and write to this store. For horizontal scaling,\n   recommend a centralized database.\n3. **Deterministic Reporting:** Treat findings as internal state. Minimize the\n   use of the LLM to convert JSON findings into Markdown reports for human\n   consumption; instead, write deterministic scripts to render the JSON into\n   reports or upload them to bug trackers. Only use an LLM for non-deterministic\n   subsets of this (like textual synthesis), such as by providing an executive\n   summary if necessary.\n4. **Token Efficiency & Reusable Deterministic Tools:** Structure LLM outputs to\n   return only the *minimum necessary information* (e.g., UUIDs, status codes).\n   Do not force the LLM to write one-off scripts (e.g., Python or bash) on the\n   fly for routine tasks like appending JSON fields or merging findings, as this\n   wastes reasoning tokens. Instead, the harness should provide reusable,\n   deterministic tools (such as pre-written helper scripts or MCP endpoints)\n   that the LLM can simply invoke to perform text manipulation and state\n   updates.\n5. **State Store & Memory Rotation:** To prevent token bloat and infinite loops,\n   ephemeral queues (like `workspace\u002Flearnings.jsonl`) must be rotated. Upon\n   successful completion and verification of the Knowledge Base synthesis stage,\n   the orchestrator should ensure the archive directory exists (e.g.,\n   `mkdir -p workspace\u002Farchive\u002Flearnings\u002F`) and **move**\n   `workspace\u002Flearnings.jsonl` to a numbered archive (e.g.,\n   `workspace\u002Farchive\u002Flearnings\u002Flearnings_pass_${N}_${X}.jsonl` where `${N}` is\n   the loop pass and `${X}` is a sub-index). If the synthesis fails, the active\n   queue must be left intact to prevent data loss.\n\n### Architectural Overview\n\n```mermaid\ngraph TD\n    Harness[Programmatic Harness \u002F Orchestrator] \u003C--> DB[(State Store: Disk\u002FDB)]\n\n    subgraph Stages [Decomposed Stages]\n        KB[KB Architect]\n        TM[Threat Modeler]\n        P[Plan]\n        R[Researcher]\n        D[Deduplicator]\n        V[Validator\u002FReview]\n        C[Critic]\n        Rep[Reproducer]\n        Ch[Chainer]\n        Pat[Patcher]\n        Cal[Calibrator]\n        Ref[Reflector]\n    end\n\n    Harness --> KB\n    Harness --> TM\n    Harness --> P\n    Harness --> R\n    Harness --> D\n    Harness --> V\n    Harness --> C\n    Harness --> Rep\n    Harness --> Ch\n    Harness --> Pat\n    Pat -.->|Re-attack Bypass Loop| Rep\n    Harness --> Cal\n    Harness --> Ref\n\n    subgraph LLM Pool [Tailored LLMs]\n        ModelA[Frontier Model: Deep Reasoning]\n        ModelB[Flash\u002FLite Model: Fast & Cheap]\n        ModelC[Alternative Provider: Diversified Logic]\n    end\n\n    KB -.-> ModelA\n    TM -.-> ModelB\n    P -.-> ModelB\n    R -.-> ModelA\n    R -.-> ModelC\n    D -.-> ModelB\n    V -.-> ModelB\n    C -.-> ModelA\n    Rep -.-> ModelA\n    Ch -.-> ModelA\n    Pat -.-> ModelA\n    Cal -.-> ModelB\n    Ref -.-> ModelB\n```\n\n### 1. UUID-Based Referencing Pattern\n\nTo prevent the LLM from repeating large blocks of text (which increases latency,\ncost, and the risk of mangling data), use UUIDs as the primary key for all\nfindings.\n\n#### A. Researcher Stage\n\n- **Action:** Sweeps the codebase and identifies potential vulnerabilities.\n- **LLM Output:** Generates a unique UUID for each finding and writes\n  `workspace\u002Ffindings\u002F\u003CUUID>.json` containing the full details (matching the\n  standard schema in [Mantis Researcher](..\u002Fmantis-researcher\u002FSKILL.md)).\n\n#### B. Deduplication Stage (Optimized)\n\nInstead of asking the LLM to read all findings, merge them in context, and write\nthem back, use the following pattern:\n\n1. **Harness Action:** Reads all `workspace\u002Ffindings\u002F*.json` files and prepares\n   a summary list for the LLM containing only key identifiers. To align with the\n   standard schema, map the `code_paths` array (which uses `\"file:line\"` format)\n   to a simplified summary for the LLM:\n   `[ { \"id\": \"UUID\", \"file\": \"path\", \"line\": 12, \"snippet\": \"...\" } ]`.\n\n2. **LLM Action:** Analyzes the summary and outputs a mapping of duplicates:\n\n   ```json\n   {\n     \"primary_uuid_1\": [\"duplicate_uuid_a\", \"duplicate_uuid_b\"],\n     \"primary_uuid_2\": []\n   }\n   ```\n\n3. **Harness Action (Deterministic):**\n\n   - Reads the content of the affected files.\n   - Programmatically merges fields following the rules in\n     [Mantis Deduplicator](..\u002Fmantis-dedupe\u002FSKILL.md) (e.g., union of\n     `code_paths`, taking highest severity, concatenating history).\n   - Updates `workspace\u002Ffindings\u002Fprimary_uuid_1.json` on disk.\n   - Ensures the trash directory exists (e.g.,\n     `mkdir -p workspace\u002Ffindings\u002F.trash\u002F`).\n   - Moves `workspace\u002Ffindings\u002Fduplicate_uuid_a.json` and\n     `workspace\u002Ffindings\u002Fduplicate_uuid_b.json` to the trash staging directory\n     (`workspace\u002Ffindings\u002F.trash\u002F`).\n\n#### C. Validation & Review Stages (Reviewer, Critic)\n\n- **Harness Action:** For each finding `workspace\u002Ffindings\u002F\u003CUUID>.json`, pass\n  only the relevant code context and finding description to the LLM.\n- **LLM Action:** Output *only* a structured verification result (e.g.,\n  `{\"valid\": true, \"reason\": \"...\"}`).\n- **Harness Action (Deterministic):** Programmatically update the\n  `workspace\u002Ffindings\u002F\u003CUUID>.json` file with the validation status and reason.\n\n### 2. Adaptable Reproducers via Custom MCP\n\nWhen validating findings, the agent may need to interact with diverse\nenvironments (VMs, physical hardware). Use the **Model Context Protocol (MCP)**\nto expose a clean, restricted API.\n\n- **Architecture**:\n  `[Reproducer Agent] \u003C--- MCP ---> [Custom MCP Server] \u003C--- API ---> [Target Env]`\n- **Custom Environments**:\n  - *VMs*: Implement tools like `reboot_vm()`, `execute_payload()`.\n  - *Hardware\u002FUSB*: Implement tools like `power_cycle_device()` (via smart\n    plug), `send_usb_packet()`.\n- **Integration Note**: If the user's harness uses raw LLM APIs (e.g., direct\n  Gemini API calls) instead of an MCP-native client framework, the harness must\n  manually register these tools in the API's schema format and handle\n  dispatching tool calls to the MCP server.\n\n### 3. Decomposition & Multi-Model Strategy\n\n#### A. Pipeline Decomposition & Concurrency\n\nThe pipeline can be split into independent services. When scaling horizontally\n(e.g., multiple workers running the `Reproducer` stage in parallel):\n\n- **Concurrency Control**: Implement database or file locking to ensure two\n  workers do not attempt to process or update the same finding simultaneously.\n- **Parallel Trajectory Search**: For deep reasoning stages (`Reproducer`,\n  `Patcher`), spawn multiple parallel agents attempting to solve the exact same\n  finding using diverse logic paths. For the `Reproducer` stage, prune all other\n  trajectories as soon as one worker succeeds to save compute costs while\n  escaping LLM \"give up\" loops. For the `Patcher` stage, wait for all patches to\n  be generated and tested, then evaluate the successful ones to select the most\n  minimal, idiomatic, and correct fix.\n\n#### B. Heterogeneous LLM Selection (Multi-Model)\n\nMatch task complexity with the appropriate model tier:\n\n- *Frontier Models*: For deep reasoning (Research, Reproduce, Patch).\n- *Flash\u002FLite Models*: For structured utility tasks (Dedupe, Calibrate).\n- *Variability*: Run different models in parallel during the Research stage to\n  increase bug-hunting coverage.\n\n#### C. Importance of Evaluation\n\nEmphasize that using cheaper models for utility stages (like deduplication or\ncalibration) must be validated with empirical evaluations against a benchmark\ndataset to ensure quality is not degraded.\n\n### 4. The Planning Stage and workspace\u002Fplan.json\n\nThe planning stage plays a critical role in structuring the security campaign.\nThe strategist (`\u002Fmantis-plan`) generates `workspace\u002Fplan.json` to define\ntargeted investigations, context pointers, and specific questions for the\nauditor. The researcher (`\u002Fmantis-researcher`) reads `workspace\u002Fplan.json` at\nstartup to guide its sweep. By decoupling strategy and execution via this\nstructured contract, the orchestrator can easily direct subagents, parallelize\nsweeps, and maintain historical context across pipeline runs without repeating\nwork.\n\n### 5. The Pass Lifecycle Contract (Living \u002F Synced Codebases)\n\nA custom orchestrator (a bespoke CLI, an ADK agent, an MCP-native pipeline, or\nany deterministic harness) does **not** inherit the living-project lifecycle\nthat `mantis-meta-agent` implements. To support *continue-after-edits* and\n*opt-in boundary sync* **without producing silent wrong results** (false\n`VERIFIED_SECURE`, false `failed_to_reproduce`, dropped regressions), the\nharness must implement the following harness-agnostic contract. This is the same\ncontract recorded in [schema.json](..\u002F..\u002Fschema.json) under **Non-JSON\nContracts**; the `Block A`–`Block G` and `SNAPSHOT_ID` references below name\nmechanisms each Mantis stage already carries in its own `SKILL.md`.\n\nMantis runs under multiple harnesses (various CLIs, ADK, custom deterministic\npipelines), so the lifecycle must not live only in `mantis-meta-agent`. Any\nharness is **conformant** iff, per pass, it:\n\n1. **SYNCs first** (Block C) — the very first action; never mid-pass.\n2. **Detects `vcs_info` + computes `SNAPSHOT_ID`** (Block D steps 1-5) — only\n   after sync.\n3. **PINs** the immutable copy + writes the sentinel + **appends**\n   `snapshot_history` (Block D step 5, not RECORD).\n4. **Records** `vcs_info` (incl. `snapshot_id`) + `active_snapshot`. Never\n   record an id or pin before syncing.\n5. **Runs every stage** with\n   `--snapshot_root=\u003CSNAPSHOT_ROOT> --snapshot_id=\u003CSNAPSHOT_ID> --state_root=\u003Cworkspace parent>`.\n6. **Archives & increments** (existing Stage 15); retried findings keep their\n   **original** `discovery_commit`.\n\nA harness that does not implement the contract MUST leave `snapshot_pinned`\nunset → today's behavior. When `--sync` is requested, the harness PINs in the\nPIN step and passes `--snapshot_root`\u002F `--snapshot_id` normally; Block A\n(Locator Resolution) is universal across all code-reading stages.\n\n#### Advisory notes when helping a builder implement this contract\n\n- **Opt-in, default off.** Sync\u002Fpinning is a feature the builder turns on. A\n  harness that never sets `snapshot_pinned` behaves exactly like today (one live\n  snapshot per run). Downstream stages treat an absent\n  `active_snapshot`\u002F`discovery_commit` as the conservative branch, so an\n  un-upgraded harness is always safe — just not living-project-aware. Do **not**\n  advise treating these absent fields as an error.\n- **Store snapshots OUTSIDE `workspace\u002F`.** The pinned copy (`SNAPSHOT_ROOT`)\n  must live under `\u003Cstate_root>\u002F.mantis_snapshots\u002Fpass_\u003CN>` (or a clean-VCS\n  worktree\u002Farchive), and its path **must not** contain the segment `\u002Fworkspace\u002F`\n  — otherwise `mantis-patch`'s state-vs-code path guard misfires. Keep the last\n  2 snapshots and garbage-collect older ones with the matching teardown\n  (`rm -rf` for copies, `git worktree remove\u002Fprune` for worktrees).\n- **Non-destructive sync only.** Sync is the **first** action of a pass,\n  **never** mid-pass, and must be **skipped** when the tree is dirty, ahead of\n  upstream, detached, or has no upstream. The harness must **never** run\n  `git reset --hard`, `git checkout -- .`, `git clean`, or `hg update -C`, or\n  any command that discards uncommitted\u002Funtracked\u002Flocal-commit state — user\n  edits and in-progress work must survive every pass.\n- **Full-fidelity `SNAPSHOT_ID`s, including dirty \u002F no-VCS.** Compute the id\n  over the **whole** pinned copy: clean git\u002Fhg → `commit_hash`; dirty git\u002Fhg →\n  `commit_hash + \":\" + content_hash`; multi-vcs →\n  `revision + \":\" + content_hash`; no-VCS \u002F unknown copyable tree →\n  `\"content:\" + content_hash`. The embedded content hash is exactly what lets an\n  **unchanged dirty or no-VCS tree MATCH across passes** and still receive\n  verification + dedup — and what makes a `repo sync` that advances commits\n  under an unchanged manifest `revision` compare **unequal**. Never trust a bare\n  branch name or manifest revision string as an identity.\n- **Pass the three roots to EVERY stage.** Include the findings-only stages\n  (report, calibrate, reflect): they do not read target code, but they still\n  read `active_snapshot` for provenance\u002Fannotation. When the harness archives\n  and increments, retried findings must keep their **original**\n  `discovery_commit`.\n\n#### Conformance scenarios\n\nThe scenarios below expose nearly every issue in the snapshot model. They are\n**reference checks**, not features: the harness is responsible for preventing or\nhandling each one in its own environment. The table is a quick-reference; prose\ndetail follows for each scenario. The **State** column uses the 3-STATE RULE\n(MODE-OFF \u002F HALT \u002F PINNED, branched on `active_snapshot` presence — see the\nglobal backward-compat rule in [schema.json](..\u002F..\u002Fschema.json) and the advisory\nnotes above); `SNAPSHOT_ID` formats follow the ladder in the advisory notes\nabove (e.g. `live:\u003Cts>` signals an unpinned\u002FHALT pass).\n\n**Invariant legend** (the labels below name safety properties enforced by the\nblocks and the global backward-compat rule in [schema.json](..\u002F..\u002Fschema.json)):\n\n| Label | Property                       | Enforced by                                   |\n| ----- | ------------------------------ | --------------------------------------------- |\n| INV-1 | No false `VERIFIED_SECURE`     | Block G + HALT ceiling                        |\n| INV-2 | No false `failed_to_reproduce` | Block F + HALT ceiling                        |\n| INV-3 | No dropped regression          | Block B NOT_MATCHED + POSSIBLE REGRESSION     |\n| INV-4 | Within-pass consistency        | Block A sentinel + single pinned snapshot     |\n| INV-5 | No user data loss              | Block C non-destructive sync + Block A step 4 |\n| INV-6 | Fail-safe on missing data      | Global backward-compat rule                   |\n\n**Quick-reference table:**\n\n| #   | Scenario                                                            | State                                        | Harness behavior                                                                                                                                                                           | Stage behavior                                                                                                                                                                                                      | Block \u002F INV                             | Key fields                                                                                            |\n| --- | ------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------- |\n| 1   | Colocated state                                                     | PINNED                                       | HALT-and-yield (safe default), or relocate `state_root` outside `CODE_ROOT` when explicitly authorized (e.g. `--auto_relocate_state`); `SNAPSHOT_ROOT` path must not contain `\u002Fworkspace\u002F` | `mantis-patch` state-vs-code guard misfires; Block A step 3 confuses SNAPSHOT- vs STATE-relative paths                                                                                                              | A:3, D:3; INV-5                         | `active_snapshot.root`, `snapshot_root`, `state_root`                                                 |\n| 2   | Stale active_snapshot (`active_snapshot.pass != state.pass_number`) | PINNED → STOP or HALT-degrade                | Block D step 0: handles same-pass re-entry only; if dir missing → STOP, yield to user                                                                                                      | Block A step 2 sentinel may still MATCH (dir retained); CURRENT-PASS CHECK (`active_snapshot.pass == state.pass_number`) required: mismatch → STOP or HALT-degrade (Block B NOT_MATCHED, no authoritative verdicts) | A:2, D:0, B; INV-1, INV-3, INV-4, INV-6 | `active_snapshot.{root, snapshot_id, snapshot_pinned, pass}`, `state.pass_number`, `discovery_commit` |\n| 3   | Pin failure                                                         | HALT                                         | Block D step 2\u002F4: skip copy on ENOSPC\u002Ferror → step 5b; still write `active_snapshot` + pass roots                                                                                          | Authoritative verdicts forbidden; Block B always NOT_MATCHED; reproduce `not_attempted`; patch `VERIFICATION_INCOMPLETE`                                                                                            | D:2, D:4, D:5b; INV-1, INV-2, INV-6     | `active_snapshot.{snapshot_id, snapshot_pinned}`                                                      |\n| 4   | Patched shadows                                                     | PINNED (pass); `--snapshot_pinned=false` arg | Pass `--target_root=\u003CPATCHED_SHADOW_ROOT>` + `--snapshot_pinned=false` to reattack sub-agent                                                                                               | Block A step 1a: `CODE_ROOT=--target_root` (authoritative); step 2 sentinel SKIPPED (sentinel-EXEMPT)                                                                                                               | A:1a, A:2; INV-4                        | `target_root`, `snapshot_pinned` (arg), `snapshot_root`, `discovery_commit`                           |\n| 5   | Different-snapshot duplicate candidates                             | PINNED                                       | No special action — both passes pinned correctly; dedupe handles it                                                                                                                        | Block B pairwise: `discovery_commit` differs → NOT_MATCHED → keep ACTIVE + `possible_duplicate_of`; POSSIBLE REGRESSION if archived was RESOLVED                                                                    | B; INV-3, INV-6                         | `discovery_commit`, `possible_duplicate_of`, `status`, `patch_status`                                 |\n| 6   | Absent sink evidence                                                | Any                                          | No special action — Block F is a stage-level mechanical gate                                                                                                                               | Block F: evidence absent (build error, exit 127, sink unreached) → `not_attempted` (retry-eligible), NEVER `failed_to_reproduce`; HALT ceiling additionally forces `not_attempted`                                  | F; INV-2, INV-6                         | `repro_status`, `reattack_status`, `repro_hints`                                                      |\n\n**Per-scenario detail:**\n\n**1. Colocated state** (`state_root` nested inside `CODE_ROOT` \u002F snapshot root)\n— The pinned `SNAPSHOT_ROOT` must live under\n`\u003Cstate_root>\u002F.mantis_snapshots\u002Fpass_\u003CN>` (or a clean-VCS worktree\u002Farchive), and\nits path **must not** contain the segment `\u002Fworkspace\u002F` — otherwise\n`mantis-patch`'s state-vs-code path guard misfires (state files appear to be\n\"under `CODE_ROOT`\"). If `state_root` itself is inside `CODE_ROOT`, the harness\nmust HALT-and-yield (safe default) or, when explicitly authorized (e.g.\n`--auto_relocate_state`), relocate it outside the snapshot before pinning. Block\nA step 3 distinguishes SNAPSHOT-RELATIVE path fields (read under `CODE_ROOT`)\nfrom STATE-RELATIVE fields (read under `state_root\u002Fworkspace`, never prefixed\nwith `CODE_ROOT`); colocation breaks this separation.\n\n**2. Stale active_snapshot** (`active_snapshot.pass != state.pass_number` —\n`active_snapshot` was preserved across the Stage 15 pass increment) — Block D\nstep 0 (crash-resume) handles only the SAME-pass re-entry case\n(`active_snapshot.pass == N` → reuse). It does NOT catch a stale snapshot\ncarried across the Stage 15 pass increment, because Stage 15 deliberately\npreserves `active_snapshot` while bumping `pass_number` (see Stage 15). Two\nsub-cases:\n\n(a) The prior snapshot dir is now MISSING: Block D step 0 STOPs and yields to\nthe user (never re-pin to a possibly-drifted live tree). (b) The prior snapshot\ndir still EXISTS (default keep-2 retention) and its sentinel matches the\npreserved `active_snapshot.snapshot_id`: Block A step 2 sentinel check SUCCEEDS\n(it only compares the sentinel file to `SNAPSHOT_ID`, not to the current pass).\nBlock B's pairwise `discovery_commit` check would MATCH a carried-forward\nfinding against a new finding stamped with the same stale `SNAPSHOT_ID`,\nsilently dropping it as `DUPLICATE` — a false authoritative verdict.\n\nTo prevent (b), the HARNESS MUST guarantee that\n`active_snapshot.pass == state.pass_number` before any consumer stage reads it.\nThe reference harness (`mantis-meta-agent`) satisfies this by re-pinning every\npass (Block D step 0 sees `active_snapshot.pass != N` → re-pins → refreshes\n`active_snapshot.pass` before any stage runs), so sub-case (b) never fires\nthere. A custom harness that preserves `active_snapshot` across the Stage 15\npass increment WITHOUT re-pinning MUST either (a) re-pin every pass (the\nreference behavior), or (b) inject an equivalent pre-stage gate that refreshes\n`active_snapshot.pass` or clears `active_snapshot` entirely before invoking\nstages. Stages CANNOT self-detect this staleness via Block B (which is\n`snapshot_id`-only, not `pass`-aware): a carried-forward finding and a new\nfinding stamped with the same stale `SNAPSHOT_ID` will MATCH in Block B despite\nthe snapshot being stale. The `active_snapshot.pass` field is defined in\n`schema.json` `#\u002F$defs\u002Fstate\u002Factive_snapshot\u002Fpass` for exactly this check. The\nharness's Block D step 0 reuse check is NOT a substitute: it only fires on\nsame-pass re-entry. (Stages that read `active_snapshot` MAY additionally\nself-check defensively — see each stage's Step 0 sentinel check — but the\nbinding guarantee is on the harness.)\n\n**3. Pin failure** (snapshot copy fails — disk full, permissions, too-large\ntree) — Block D step 2 (free-space precheck): compare `du -s` of the live tree\nto `df` free space at `state_root`; if it won't fit → skip copy → step 5b. Block\nD step 4 (failure-tolerant verify): check copy exit status + sanity check (file\ncount\u002Fsize within ~90%); on failure → step 5b (unpinned\u002FHALT). Step 5b:\n`SNAPSHOT_ROOT=\u003Clive root>`, `snapshot_pinned=false`,\n`SNAPSHOT_ID=\"live:\"+ISO8601`. The harness still writes `active_snapshot` and\nstill passes `--snapshot_root`\u002F`--snapshot_id` to stages so they see the HALT\nsignal. Every stage then degrades conservatively: authoritative verdicts\nforbidden (`VERIFIED_SECURE`, `failed_to_reproduce`, `DUPLICATE`,\n`FALSE_POSITIVE`, `NON_VIABLE`); Block B always returns NOT_MATCHED; reproduce\nrecords `not_attempted`; patch's best attainable is `VERIFICATION_INCOMPLETE`.\n\n**4. Patched shadows** (`--target_root` pointing at a pre-mutated tree;\nsentinel-exempt path 1a in Block A) — `mantis-patch` passes\n`--target_root=\u003CPATCHED_SHADOW_ROOT>` and `--snapshot_pinned=false` to the\nreproduce sub-agent for re-attack verification. Block A step 1a:\n`CODE_ROOT = --target_root` (authoritative override, overrides `--snapshot_root`\nand state fallback). Block A step 2: sentinel check SKIPPED (a `--target_root`\ntree is deliberately mutated and is sentinel-EXEMPT). The\n`--snapshot_pinned=false` argument is the sentinel-exemption, NOT a HALT signal\n— detect HALT by reading STATE (`active_snapshot.snapshot_id` starts with\n`live:`, equivalently `active_snapshot.snapshot_pinned` is `false` in state),\nnever from the argument passed on this invocation. The finding's\n`discovery_commit` is unaffected — it retains the pass-level `SNAPSHOT_ID` from\nwhen it was discovered; only the `--snapshot_pinned=false` argument is local to\nthe reattack invocation.\n\n**5. Different-snapshot duplicate candidates** (cross-pass dedupe where\n`discovery_commit` differs — the pairwise Block B NOT_MATCHED path) — Both\npasses pinned correctly; the findings simply come from different snapshots.\n`mantis-dedupe` Block B pairwise check compares the CURRENT finding's\n`discovery_commit` against the ARCHIVED finding's `discovery_commit` (NOT\nagainst the global `SNAPSHOT_ID`). If they differ → NOT_MATCHED. NOT_MATCHED\nkeeps the current finding ACTIVE and sets `possible_duplicate_of` (a soft,\nnon-terminal hint — the finding is NOT filtered or trashed). If the archived\nfinding was RESOLVED (`patch_status` in {`VERIFIED_SECURE`,\n`MITIGATION_PROPOSED`} OR `status`==`FALSE_POSITIVE` OR\n`production_viability`==`NON_VIABLE`) AND the pair is NOT_MATCHED → POSSIBLE\nREGRESSION: keep ACTIVE, add a history note, never filter (a reverted fix\nre-discovered on new code must never be trashed).\n\n**6. Absent sink evidence** (Block F — PoC compiles but produces no reached-sink\nevidence; `not_attempted` vs `failed_to_reproduce`) — `mantis-reproduce` Block\nF: if EVIDENCE is ABSENT (any compiler\u002Fbuild nonzero exit, exit 127\ncommand-not-found, exit 2 \"No such file\", or the sink was never reached) →\n`repro_status = not_attempted` (retry-eligible), STOP. NEVER\n`failed_to_reproduce`. In `--reattack` mode: leave `reattack_status` UNSET with\na history note \"setup_failed\" — NEVER `failed_to_bypass`. `failed_to_reproduce`\nis reserved for when the harness PROVABLY reached the vulnerable entrypoint —\ni.e. reached-sink evidence, not setup evidence — but the bug did not fire.\nReached-sink evidence must originate INSIDE the invoked path or from\ntarget-produced tracing\u002Fbacktraces: (a) a PoC script\u002Fsource harness writes\n`MANTIS_REACHED_ENTRYPOINT` to a sidecar file at the point just before the sink\ncall, within its own execution flow (the marker write is part of the invoked\npath, not a pre-launch step); OR (b) for binary\u002Ffirmware\u002Fraw-payload targets,\nthe captured crash backtrace or sanitizer trace (ASan\u002FUBSan\u002FMSan\u002FTSan)\nexplicitly names the target sink function (target-produced tracing). A marker\nwritten by an external wrapper BEFORE invoking the target is SETUP EVIDENCE ONLY\n(proves \"launch attempted,\" not \"sink reached\") and does NOT by itself justify\n`failed_to_reproduce` — treat it as EVIDENCE ABSENT for the decision gate.\nEvidence is recorded in `repro_hints`. In HALT mode, the HALT ceiling\nadditionally forces `not_attempted` (no `failed_to_reproduce`), since a negative\nresult on an unpinned tree cannot be trusted as authoritative.\n\n______________________________________________________________________\n\n### 6. Semantic Retrieval (RAG) for Large Codebases\n\nFor small repositories, the planner can manually scan `workspace\u002Fkb\u002Findex.md`\nand the researcher can grep for call-sites. At scale (thousands of files, deep\ndirectory trees, multi-pass campaigns), these approaches miss relevant context\nand waste tokens reading irrelevant files. A semantic retrieval layer lets the\nplanner and researcher query for relevant KB entries and code locations without\nreading everything.\n\nTwo implementations are supported, sharing the same data contract:\n\n- **Option A (Default — Skill-Based):** A dedicated skill that runs a\n  BM25\u002FTF-IDF helper script over `chunks.jsonl`. Zero external dependencies —\n  works air-gapped, no vector embeddings or vector store required. Optional\n  vector embedding support if available.\n- **Option B (Maximum Scale — MCP-Based):** The harness owns a persistent vector\n  index using vector embeddings, serving persistent `semantic_search_kb` \u002F\n  `semantic_search_code` MCP tools. Better for very large codebases where\n  per-invocation BM25 is too slow.\n\nBoth are **opt-in**. The existing skills are not modified; the planner and\nresearcher receive runtime instructions to use whichever retrieval mechanism is\navailable, falling back to today's manual behavior if neither is present.\nRetrieval results are **coverage HINTs only** — they decide ordering and\nprioritization, never the membership of the audit set. A miss must never cause a\nfile, call-site, or investigation to be skipped or dropped.\n\n#### A. Shared Data Contract: `chunks.jsonl`\n\nAfter Stage 2 (`\u002Fmantis-architecture`) completes, chunks are extracted into\n`workspace\u002Fkb\u002Fchunks.jsonl` (one JSON object per line). The harness can do this\npost-hoc by reading `workspace\u002Fkb\u002F*.md`, or the architecture skill can be\ninstructed to write it during synthesis as a text-only side effect. Two chunk\ntypes are produced:\n\n1. **KB chunks** from the existing `workspace\u002Fkb\u002F*.md` files:\n\n   ```json\n   {\"id\": \"auth_module:0\", \"source_file\": \"workspace\u002Fkb\u002Fentities\u002Fauth_module.md\", \"entity_type\": \"entity\", \"chunk_text\": \"The auth module handles...\"}\n   ```\n\n2. **Code chunks** from `CODE_ROOT` (the pinned snapshot). Each chunk includes\n   the file path and line range so the researcher can request specific files\n   from the snapshot:\n\n   ```json\n   {\"id\": \"src\u002Fparser.c:0\", \"source_file\": \"src\u002Fparser.c\", \"start_line\": 1, \"end_line\": 80, \"chunk_text\": \"int parse_input(...\"}\n   ```\n\nThe first line of `chunks.jsonl` is a provenance header recording the\n`SNAPSHOT_ID` the chunks were built against:\n\n```json\n{\"_provenance\": true, \"snapshot_id\": \"abc123\", \"kb_snapshot_id\": \"abc123\"}\n```\n\nBefore serving queries, check `snapshot_id` in the provenance header against the\ncurrent `SNAPSHOT_ID`; rebuild if they differ. In MODE-OFF (no\n`active_snapshot`), `kb_snapshot_id` is never stamped — skip the index entirely\nand let skills fall back to manual scanning. Never build code chunks from the\nlive tree — they must reflect the pinned copy the skills are reading.\n\n#### B. Option A: Skill-Based Retrieval (Default — No Infrastructure)\n\nA dedicated skill reads `chunks.jsonl` and writes+runs a helper script (e.g.\n`workspace\u002Fhelpers\u002Fsearch_chunks.py`) that performs BM25\u002FTF-IDF similarity\nsearch. The script is generated by the agent at runtime — no code is shipped\nwith the skill (same pattern as `mantis-dedupe`'s `merge_findings.py`). This\nrequires zero external dependencies — no embedding model, no vector store, no\nMCP server. It works in air-gapped and VPC-SC environments.\n\nA complete reference blueprint for this skill is available at\n[references\u002Fmantis-kb-query.md](references\u002Fmantis-kb-query.md). Builders can\nadapt it to their environment. The blueprint includes Block A (Locator\nResolution), chunk provenance checking, the versioned helper script contract\n(`MANTIS_HELPER_VERSION = 1`), and the JSON output schema.\n\n- **Invocation:** The planner or researcher spawns the skill as a sub-agent with\n  a query string. The skill writes the helper if not already present, runs it,\n  and returns top-K matching chunks as JSON.\n- **Optional embeddings:** If vector embeddings are available, the agent can be\n  instructed to use cosine similarity instead of BM25. This is a runtime\n  configuration toggle, not a different skill.\n- **Snapshot safety:** The skill reads `active_snapshot` from state via Block A\n  (same as every other skill) and checks chunk provenance before serving.\n\n#### C. Option B: MCP-Based Retrieval (For Maximum Scale)\n\nFor very large codebases where per-invocation BM25 is too slow, the harness can\nown a persistent vector index using vector embeddings, serving two MCP tools\n(following the same pattern as Guideline 2's Custom MCP for VMs\u002Fhardware):\n\n- `semantic_search_kb(query: string) → [{id, source_file, entity_type, chunk_text, score}]`\n  — Searches KB chunks. Returns relevant entity\u002Fvulnerability markdown context.\n\n- `semantic_search_code(query: string) → [{file, start_line, end_line, snippet, score}]`\n  — Searches code chunks from the pinned snapshot. Returns relevant code\n  locations.\n\nThe harness manages the vector index lifecycle: build from `chunks.jsonl` (or\ndirectly from `CODE_ROOT`), rebuild when `SNAPSHOT_ID` changes, and handle\nfreshness checks. In HALT mode, serve with a `STALE` flag or refuse. In\nMODE-OFF, skip entirely.\n\n#### D. Per-Skill Augmentation Guidance\n\nWhen a retrieval mechanism (skill or MCP) is available, instruct the following\nskills to use it. These are runtime instructions passed by the harness or\nmeta-agent when invoking the skill — the skill files themselves are not\nmodified:\n\n- **mantis-architecture:** No changes needed. The harness chunks the existing\n  `workspace\u002Fkb\u002F*.md` files after the architect completes Stage 2. If the\n  builder prefers, they may instruct the architect to also write\n  `workspace\u002Fkb\u002Fchunks.jsonl` during synthesis (Step 3) as a text-only side\n  effect — but this is optional, since the harness can extract chunks post-hoc.\n\n- **mantis-plan:** If a retrieval mechanism is available, instruct the planner\n  to use it to discover `kb_references` for each investigation instead of only\n  manually scanning `workspace\u002Fkb\u002Findex.md`. For each investigation, query with\n  the investigation title and target file names, then add the top-K matching KB\n  entity\u002Fvulnerability files to the `kb_references` array. Manual scanning of\n  `index.md` remains the fallback when no mechanism is available.\n\n- **mantis-researcher:** If a retrieval mechanism is available, instruct Wave 1\n  sub-agents to use it to PRIORITIZE relevant call-sites and cross-module data\n  flows into sinks (e.g., \"where does untrusted input reach `memcpy` in the\n  parser module\"). Semantic search SUPPLEMENTS grep as a ranking HINT ONLY — it\n  decides ORDER, never MEMBERSHIP of the audit set. It MUST NEVER replace the\n  exhaustive Step-3 call-site sweep; every call-site or data-flow that a full\n  grep would reach must still be audited whether or not it ranks in top-K. Audit\n  the union of grep results and semantic search results. The researcher's\n  existing Wave 1\u002FWave 2 structure is unchanged.\n\n#### E. Snapshot Safety\n\nThe retrieval index — whether served by the skill or the harness — is a **cache\nof the pinned snapshot**, never a live view:\n\n- Build code chunks from `CODE_ROOT` (the pinned snapshot), not the live tree.\n- Rebuild when `SNAPSHOT_ID` changes (new pass, new pin).\n- In HALT mode (`snapshot_pinned=false`), serve results with a `STALE` flag or\n  refuse to serve — same conservative degradation as every other stage.\n- In MODE-OFF, skip the index entirely.\n\n______________________________________________________________________\n\n### 7. Embedding-Based Deduplication Pre-Filtering\n\nWhen the pipeline runs many passes over a large codebase, the deduplicator\n(`\u002Fmantis-dedupe`) must compare each current finding against every archived\nfinding — an O(n×m) comparison performed by an LLM reading summaries. At scale\n(hundreds of findings across many passes), this is token-expensive and slow.\n\nThe harness can use embeddings as a **fast pre-filter** to reduce the candidate\nspace before invoking `\u002Fmantis-dedupe`. The skill's existing deterministic\nmatching (`code_paths` + `title` + `discovery_commit`) remains the **sole\nauthority** for hard dedup decisions.\n\n**This is entirely harness-side and opt-in.** `\u002Fmantis-dedupe` is not modified.\n\n#### A. How It Works\n\n1. **Harness Action:** Reads all `workspace\u002Ffindings\u002F*.json` (current) and\n   `workspace\u002Farchive\u002Ffindings_pass_*\u002F*.json` (archived). For each finding,\n   computes an embedding from a normalized text representation (e.g.,\n   `title + description + first code_paths entry with line stripped`).\n\n2. **Harness Action:** Computes pairwise cosine similarity between current and\n   archived findings. Surfaces candidate pairs above a configurable threshold\n   (e.g., 0.85).\n\n3. **Harness Action:** Writes a candidate-pairs manifest (e.g.,\n   `workspace\u002Fhelpers\u002Fdedup_candidates.json`) containing the UUID pairs and\n   similarity scores.\n\n4. **mantis-dedupe invocation:** The harness invokes `\u002Fmantis-dedupe` as usual.\n   If the candidate manifest exists, instruct the skill to read it and\n   prioritize those pairs for the LLM's pairwise comparison, instead of\n   comparing every finding against every archived finding. **All existing\n   deterministic matching rules apply unchanged** — the manifest only narrows\n   the search space.\n\n#### B. Safety Guardrails\n\n- **Pre-filter only, never the decision.** The embedding similarity score can\n  never cause a `DUPLICATE` verdict, a trash move, or a `possible_duplicate_of`\n  assignment. Only the skill's existing `code_paths`, `title`, and\n  `discovery_commit` checks can do that. A miss in the pre-filter only\n  over-retains a duplicate (safe — the LLM sees it and skips it); it never\n  under-retains (never drops a real duplicate).\n\n- **No false negatives.** The threshold should be set low enough (e.g., 0.75) to\n  avoid missing true duplicates. Better to surface too many candidates than to\n  miss a real one — the LLM and deterministic matching will filter false\n  positives.\n\n- **Fallback on failure.** If the embedding computation is unavailable, the\n  candidate manifest is absent, or any error occurs, `\u002Fmantis-dedupe` falls back\n  to its existing O(n×m) comparison. The skill must not stop or error if the\n  manifest is missing.\n\n- **Snapshot awareness.** The harness should not compute embeddings across\n  different `discovery_commit` values without flagging them as cross-snapshot\n  candidates — the skill's Block B pairwise check will handle the final\n  MATCHED\u002FNOT_MATCHED decision.\n\n#### C. Shared Infrastructure\n\nIf the builder also implements Guideline 6 (Semantic Retrieval), reuse the same\nvector embedding infrastructure for finding embeddings. The finding embedding is\na different payload (finding JSON, not KB chunks) but the same embedding\ncapability can serve both.\n\n#### D. Enterprise Vector Architecture & Cloud Scalability\n\nFor enterprise deployments tracking hundreds of thousands of vulnerabilities\nacross distributed codebases and multi-tenant audit pipelines, SQLite vector\nstorage can be swapped for managed cloud vector engines:\n\n- **Cloud Spanner Vector Search:**\n  - *Best For*: Mission-critical enterprise pipelines requiring global ACID\n    consistency, 99.999% availability, and synchronized finding lineage\n    tracking.\n  - *Architecture*: Store findings and `lineage_vectors` in Spanner with\n    `ARRAY\u003CFLOAT32>` vector columns. Utilize `COSINE_DISTANCE` with KNN search\n    indexes for real-time finding deduplication during parallel scan passes.\n- **Cloud SQL for PostgreSQL (`pgvector`):**\n  - *Best For*: Standard enterprise relational backends needing ACID compliance\n    with low operational complexity.\n  - *Architecture*: Enable the `vector` extension. Store finding embeddings in a\n    `vector(768)` or `vector(256)` column with HNSW (`vector_cosine_ops`) or\n    IVFFlat indexes for sub-millisecond similarity queries.\n- **AlloyDB for PostgreSQL:**\n  - *Best For*: High-throughput multi-agent audit farms running concurrent\n    research waves.\n  - *Architecture*: Leverage AlloyDB's columnar vector engine and ScaNN-based\n    approximate nearest neighbor indexing for up to 10x faster vector queries\n    over standard PostgreSQL.\n- **BigQuery Vector Search:**\n  - *Best For*: Batch analytical processing, organization-wide threat\n    intelligence clustering, and cross-campaign vulnerability lineage analysis.\n  - *Architecture*: Ingest finding embeddings into BigQuery and execute\n    `VECTOR_SEARCH(TABLE findings, 'embedding', ...)` with `COSINE` distance for\n    serverless batch deduplication and historical regression analytics.\n\n______________________________________________________________________\n\n### 8. SAST Seeding (External Tool Ingestion)\n\nMantis's discovery engine is 100% LLM-generative (grep swarm + reasoning). A\nweak LLM can structurally under-detect whole-program taint classes (injection,\npath traversal, deserialization, UAF, format-string) that mature SAST tools\n(CodeQL, Semgrep-taint) encode as interprocedural queries. A SAST seeding\nadapter ingests external tool findings as `PROVISIONALLY_VALID` \u002F\n`NEEDS_RESEARCH` candidates that must earn their verdict through the unchanged\ndownstream gates. This is purely additive (INV-2-strengthening) — it expands\ndetection breadth without weakening any verification gate.\n\nThis follows exactly the RAG pattern from Guideline 6: opt-in, default off,\nprovenance-tracked, snapshot-aware, fallback on failure.\n\n**Platform-agnostic IR (not SARIF):** Rather than tying the adapter to SARIF (a\ncomplex, tool-specific format), the adapter consumes a minimal JSONL\nintermediate representation (IR). Any SAST tool's output (SARIF, Semgrep JSON,\nBandit JSON, etc.) is converted to this IR by a thin wrapper. This maximizes\nplatform agnosticism — the adapter works with any tool that can produce the\nsimple JSONL format.\n\nTwo implementations are supported, sharing the same data contract:\n\n- **Option A (Default — Skill-Based):** A dedicated skill (`\u002Fmantis-sast-seed`)\n  reads the IR and uses LLM reasoning to normalize findings into mantis finding\n  JSONs. The LLM reads actual source code at each reported location under\n  CODE_ROOT to verify the finding and enrich the description with root-cause\n  analysis. Zero external dependencies — works air-gapped.\n- **Option B (Maximum Control — Harness-Based):** The harness directly\n  normalizes SAST output into finding JSONs using deterministic code (e.g., a\n  SARIF-to-finding converter script), bypassing the LLM for the normalization\n  step. The harness writes finding JSONs to `workspace\u002Ffindings\u002F` before\n  invoking `\u002Fmantis-dedupe`.\n\nBoth are **opt-in**. The existing skills are not modified. Seeded findings enter\n`workspace\u002Ffindings\u002F` alongside researcher findings and flow through the\nunchanged downstream gates (dedupe -> review -> critic -> reproduce -> patch ->\ncalibrate).\n\nA complete reference blueprint is available at\n[references\u002Fmantis-sast-seed.md](references\u002Fmantis-sast-seed.md).\n\n#### A. Shared Data Contract: `sast_findings.jsonl`\n\nThe IR is a JSONL file at `workspace\u002Fsast_findings.jsonl` (STATE-RELATIVE). It\nfollows the same provenance-header pattern as `chunks.jsonl` (Guideline 6A).\n\n**Line 1 — Provenance header:**\n\n```json\n{\"_provenance\": true, \"scan_snapshot_id\": \"abc123def456\", \"tool\": \"codeql\", \"tool_version\": \"2.15.0\", \"scan_timestamp\": \"2026-07-22T10:00:00Z\"}\n```\n\n- `scan_snapshot_id`: The SNAPSHOT_ID the scan was run against. This is the\n  **primary provenance anchor** — compared byte-for-byte to the current pass\n  `SNAPSHOT_ID` (same comparison as Block B). If the harness ran the SAST tool\n  against the pinned CODE_ROOT, it sets this to `SNAPSHOT_ID`.\n- `tool`: Tool name (e.g., `codeql`, `semgrep`, `bandit`). Informational.\n- `tool_version`: Tool version. Informational.\n- `scan_timestamp`: ISO 8601. Informational.\n\n**Lines 2+ — One finding per line:**\n\n```json\n{\"rule_id\": \"cpp\u002Fsql-injection\", \"rule_name\": \"SQL injection\", \"cwe\": \"CWE-89\", \"severity\": \"HIGH\", \"code_paths\": [\"src\u002Fdb\u002Fquery.c:42\"], \"message\": \"User input flows into SQL query without sanitization\"}\n```\n\n| Field        | Type   | Required | Description                                        |\n| ------------ | ------ | -------- | -------------------------------------------------- |\n| `rule_id`    | string | Yes      | Tool-specific rule identifier                      |\n| `severity`   | string | Yes      | `CRITICAL`, `HIGH`, `MEDIUM`, `LOW` (Mantis scale) |\n| `code_paths` | array  | Yes      | Array of `\"file:line\"` strings (SNAPSHOT-RELATIVE) |\n| `message`    | string | Yes      | Original SAST finding message                      |\n| `rule_name`  | string | No       | Human-readable rule name                           |\n| `cwe`        | string | No       | CWE identifier (e.g., `CWE-89`)                    |\n\n**IR conversion (harness responsibility):** The harness converts SAST tool\noutput to this IR before invoking the adapter. Conversion examples:\n\n- SARIF: extract `ruleId`, map `level` to severity (`error`->`HIGH`,\n  `warning`->`MEDIUM`, `note`->`LOW`), extract `locations` to `code_paths`, copy\n  `message.text`.\n- Semgrep JSON: extract `check_id` as `rule_id`, map `extra.severity` to Mantis\n  severity, extract `path:start.line` as `code_paths`, copy `extra.message`.\n\n#### B. Option A: Skill-Based Ingestion (Default — No Infrastructure)\n\nA dedicated skill reads `sast_findings.jsonl`, applies allow-listing, verifies\nprovenance, computes `signature`\u002F`lineage_id`\u002F`discovery_commit`, and writes\nfinding JSONs. The LLM reads actual source code at each reported location under\nCODE_ROOT to verify the finding and enrich the description.\n\n- **Invocation:** The harness invokes `\u002Fmantis-sast-seed` with\n  `--snapshot_root`\u002F`--snapshot_id`\u002F`--state_root` after Stage 6 (Research) and\n  before Stage 7 (Dedupe). The seeded findings land in `workspace\u002Ffindings\u002F`\n  before `\u002Fmantis-dedupe` runs.\n- **Inert until wired:** If `sast_findings.jsonl` is absent, the skill outputs\n  nothing and notifies the caller. It never fails — it simply returns empty.\n- **Anti-hallucination:** The LLM MUST read the actual code at each reported\n  location before writing the finding JSON. It MUST NOT invent findings not\n  present in the SAST output. The `sast_provenance.line_verified` field records\n  whether verification succeeded.\n- **Snapshot safety:** The skill reads `active_snapshot` from state via Block A\n  and stamps `discovery_commit` only when the snapshot is pinned and the\n  finding's location is verified under CODE_ROOT.\n\n#### C. Option B: Harness-Based Ingestion (For Deterministic Ingestion)\n\nFor maximum determinism, the harness can normalize SAST output into finding\nJSONs using deterministic code. This bypasses the LLM for the normalization\nstep:\n\n1. **Harness Action:** Reads the SAST tool output, parses it deterministically,\n   and writes finding JSONs to `workspace\u002Ffindings\u002F`.\n2. **Harness Action:** Stamps `discovery_commit` only if the scan provably ran\n   against the pinned CODE_ROOT.\n3. **Harness Action:** Applies allow-listing filters.\n4. **mantis-dedupe invocation:** Proceeds as usual — the seeded findings are\n   indistinguishable from researcher findings.\n\n#### D. Provenance Verification\n\nThe adapter stamps `discovery_commit` ONLY if the scan provably ran against a\nline-identical pinned CODE_ROOT. Verification ladder:\n\n1. Read `active_snapshot` from `workspace\u002F.mantis_state.json` (via Block A). If\n   absent, this is MODE-OFF — skip to step 5.\n2. If `snapshot_pinned` is false, this is HALT — skip to step 6.\n3. Read the IR provenance header's `scan_snapshot_id`.\n4. **VERIFIED**: `scan_snapshot_id` present AND exactly equals `SNAPSHOT_ID`.\n   Stamp `discovery_commit = SNAPSHOT_ID`. Status = `PROVISIONALLY_VALID`.\n5. **MODE-OFF**: `active_snapshot` absent. OMIT `discovery_commit`. Status =\n   `PROVISIONALLY_VALID` (MODE-OFF permits all verdicts).\n6. **HALT**: `snapshot_pinned` is false. OMIT `discovery_commit`. Status =\n   `NEEDS_RESEARCH`.\n7. **DRIFT**: `scan_snapshot_id` present but differs. OMIT `discovery_commit`\n   entirely. Status = `NEEDS_RESEARCH`.\n8. **UNVERIFIED**: `scan_snapshot_id` absent. OMIT `discovery_commit`. Status =\n   `NEEDS_RESEARCH`.\n\n**Line-existence verification** (additional check when VERIFIED or DRIFT and\nCODE_ROOT is resolved): For each finding, verify each `code_paths` entry: strip\ntrailing `:line`, check file exists under CODE_ROOT, check line number is within\nfile's line count. If file missing or line out of range -> downgrade to DRIFT\n(omit `discovery_commit`, status = `NEEDS_RESEARCH`).\n\nThis is the exact same \"UNTRUSTED-IF-ABSENT\" pattern as `discovery_commit`\n(schema.json) and `signature`\u002F`lineage_id`.\n\n#### E. Allow-Listing and Noise Control\n\n`workspace\u002Fsast_allowlist.json` (optional config file, STATE-RELATIVE):\n\n```json\n{\n  \"enabled\": true,\n  \"severity_filter\": [\"CRITICAL\", \"HIGH\"],\n  \"cwe_allowlist\": {\n    \"enabled\": true,\n    \"cwes\": [\"CWE-89\", \"CWE-78\", \"CWE-79\", \"CWE-22\", \"CWE-787\", \"CWE-416\", \"CWE-502\"]\n  },\n  \"rule_allowlist\": {\n    \"enabled\": false,\n    \"rules\": []\n  },\n  \"per_rule_cap\": 5,\n  \"total_cap\": 50\n}\n```\n\nIf the config file is absent, defaults apply: CRITICAL+HIGH only,\n`per_rule_cap=5`, `total_cap=50`.\n\n**How allow-listing protects the retry cap:** The reproduce stage\n(`\u002Fmantis-reproduce`) has a hard ceiling of 6 attempts per finding (absolute,\nnever reset). If 1000 SAST findings are seeded without filtering, the reproduce\nstage would need up to 6000 attempts — starving the retry budget. The\nallow-listing chain (severity filter -> CWE\u002Frule filters -> per-rule cap ->\ntotal cap) ensures only a bounded, high-signal set of candidates enters the\npipeline. The review (13-rule negative filter) and critic (production viability)\nstages further filter before reproduce runs.\n\n#### F. Per-Skill Augmentation Guidance\n\nWhen the SAST seed skill is available, instruct the harness to invoke it between\nStage 6 (Research) and Stage 7 (Dedupe). These are runtime instructions passed\nby the harness — the skill files themselves are not modified:\n\n- **mantis-meta-agent:** Invoke `\u002Fmantis-sast-seed` with\n  `--snapshot_root`\u002F`--snapshot_id`\u002F`--state_root` after `\u002Fmantis-researcher`\n  completes and before `\u002Fmantis-dedupe`.\n- **mantis-dedupe:** No changes needed. Seeded findings are in\n  `workspace\u002Ffindings\u002F` alongside researcher findings. Dedupe processes them\n  identically (signature-based matching, Block B pairwise check).\n- **mantis-review:** No changes needed. The 13-rule negative filter applies to\n  seeded findings identically.\n- **mantis-report:** No changes needed. The `sast_provenance` field is\n  informational and can be displayed in reports.\n\n#### G. Snapshot Safety\n\nThe SAST seed adapter follows Block A (Locator Resolution) exactly like every\nother code-reading skill:\n\n- Resolve CODE_ROOT from `--snapshot_root` \u002F state `active_snapshot`.\n- Honor the sentinel check (Block A step 2).\n- Read source files under CODE_ROOT (SNAPSHOT-RELATIVE) for line-existence\n  verification.\n- Write findings under `state_root\u002Fworkspace\u002Ffindings\u002F` (STATE-RELATIVE).\n- Never write under CODE_ROOT when pinned.\n- In MODE-OFF: proceed without `discovery_commit`. All verdicts permitted.\n- In HALT: omit `discovery_commit`. Seeded findings get `NEEDS_RESEARCH`.\n- In PINNED: verify each finding's location under CODE_ROOT, stamp\n  `discovery_commit = SNAPSHOT_ID` if verified.\n\nThe SAST tool output itself is NOT snapshot-aware — it may have been produced\nagainst a different tree. The adapter's provenance verification is what bridges\nthe gap: it re-grounds each finding against the pinned CODE_ROOT before stamping\n`discovery_commit`.\n\n#### H. Safety Guardrails\n\n- **Purely additive.** Seeded findings are `PROVISIONALLY_VALID` \u002F\n  `NEEDS_RESEARCH` candidates. They must pass through the unchanged downstream\n  gates: dedupe (Block B), review (13-rule filter), critic (viability),\n  reproduce (Block F reached-sink evidence + HALT ceiling), patch (Block G\n  re-attack), calibrate (sanity caps). No gate is weakened.\n- **No false `VERIFIED_SECURE`.** Seeded findings start at `PROVISIONALLY_VALID`\n  — they can never reach `VERIFIED_SECURE` without passing through the full\n  patch + re-attack pipeline.\n- **No false `failed_to_reproduce`.** Seeded findings that reach reproduce are\n  subject to the same Block F evidence gate and HALT ceiling.\n- **No dropped regression.** If a SAST-seeded finding matches an archived\n  finding with a different `discovery_commit`, Block B returns NOT_MATCHED ->\n  `possible_duplicate_of` -> finding stays active.\n- **Fail-safe on missing data.** If `sast_findings.jsonl` is absent, no findings\n  written. If a finding can't be verified, `NEEDS_RESEARCH`.\n- **No existing skills modified.** The adapter writes findings to\n  `workspace\u002Ffindings\u002F` before `\u002Fmantis-dedupe` runs.\n- **`sast_provenance` is informational only.** It does not affect any safety-\n  critical invariant, gate, or verdict. The finding's `discovery_commit` is the\n  field that governs Block B snapshot matching.\n\n______________________________________________________________________\n\n### 9. Structural Code Index (AST-Level Context)\n\nFor small repositories, the researcher can grep for call-sites and the planner\ncan infer dependencies. At scale, grep-based call-site discovery is unreliable\n(misses indirect calls, cannot distinguish calls from comments\u002Fstrings, no\nfunction boundary awareness). A structural code index provides AST-level context\n(function boundaries, call graphs, symbol tables) to improve LLM reasoning\nquality during discovery.\n\nThis follows the RAG pattern from Guideline 6: optional, provenance-tracked,\nsnapshot-aware, fallback on failure. The structural index is a **coverage HINT\nonly** — it decides ordering and prioritization, never the membership of the\naudit set. A miss must never cause a file, call-site, or investigation to be\nskipped or dropped.\n\nThe full specification — including the manifest schema, SQLite serving store,\ncapability-based per-partition backend selection, canonical symbol IDs, query\ninterface, baseline-plus-delta overlay, deterministic partial coverage, and\nsafety guardrails — lives in a single source of truth:\n\n**→ [..\u002Fmantis-structural-index\u002FSKILL.md](..\u002Fmantis-structural-index\u002FSKILL.md)**\n\nA thin reference blueprint is at\n[references\u002Fmantis-structural-index.md](references\u002Fmantis-structural-index.md).\n\nTwo implementations are supported, sharing the same query contract:\n\n- **Option A (Default — Skill-Based):** The `mantis-structural-index` skill\n  generates and runs helper scripts (`build_structural_index.py` and\n  `query_structural_index.py`, both `# MANTIS_HELPER_VERSION = 5`) using\n  capability-based per-partition backend selection, degrading to grep.\n- **Option B (Maximum Power — MCP-Based):** The harness owns a persistent\n  structural index serving `find_callers(symbol)`, `find_callees(function)`,\n  `get_function_boundary(file, line)` MCP tools, backed by the same SQLite\n  serving store.\n\nBoth are **optional**. A non-conformant harness simply skips the structural\nindex stage. The structural index supplements grep as a ranking HINT ONLY — it\ndecides ORDER, never MEMBERSHIP of the audit set.\n\nConsumers MUST use the query interface (`query_structural_index.py`) rather than\nfiltering JSONL directly. The query interface provides bounded results,\npagination, explicit name resolution, precision\u002Fbackend metadata, and coverage\non empty results.\n\n#### D. Per-Skill Augmentation Guidance\n\nWhen a structural index is available, instruct the following skills to use it.\nThese are the consumption contract — runtime instructions passed by the harness.\nThe structural index is a HINT-only enhancement; skills that do not use it\nbehave exactly as they do today:\n\n- **mantis-architecture:** Optionally read the pre-built structural index (built\n  by `mantis-structural-index` at Stage 0.5) during KB synthesis,\n  cross-referencing it with `dependencies.json`.\n- **mantis-plan:** Use the structural index for function-level dependency\n  fan-out (more precise than file-level `dependencies.json`).\n- **mantis-researcher:** Wave 1 sub-agents use `find_callers()` to SUPPLEMENT\n  grep as a ranking HINT for call-site discovery — it decides ORDER, never\n  MEMBERSHIP. It MUST NEVER replace the exhaustive Step-3 call-site sweep; every\n  call-site that a full grep would reach must still be audited whether or not it\n  ranks in the structural index. Audit the union of grep results and structural\n  index results. Wave 2 deep auditors use `get_function_boundary()` to start\n  with the enclosing function, expanding to callers\u002Fcallees\u002Ffile as needed for\n  cross-function context. The researcher's existing Wave 1\u002FWave 2 structure is\n  unchanged.\n\n#### E. Integration with RAG (Guideline 6)\n\n- Structural index entries can be added to `chunks.jsonl` as\n  `entity_type: \"structural\"` chunks.\n- Code chunks can become function-boundary-aligned (instead of dumb line-range\n  slices) by using function boundaries from the structural index.\n- The structural index and the RAG index can share the same vector embedding\n  infrastructure if both are implemented.\n\n______________________________________________________________________\n\n### 10. Tiered Iterative Reproduction & Multi-Conversation Retry Strategy\n\nFor complex services, attempting a single-shot reproduction directly against a\nfull sandboxed service often suffers from high search entropy, brittle\nconfiguration, and hard-to-debug failures. A tiered strategy breaks reproduction\ninto incremental milestones, while an inter-conversation retry architecture\nprevents reasoning deadlocks and context bloat.\n\n#### A. Orchestration & Inter-Conversation Retries\n\n1. **Intra-Conversation Retries (Local Agent Trajectory):**\n\n   - The active subagent conversation retries 2–3 times locally within its\n     context window to adjust parameters, fix setup bugs, or refine payloads.\n\n2. **Inter-Conversation Retries (Fresh Context + Accumulated Artifacts):**\n\n   - **Trigger:** If intra-conversation retries fail to reach Tier 3\n     (`reproduced`), the orchestrator terminates the stalled conversation and\n     launches a **new subagent conversation** (a fresh context window).\n   - **Context Provisioning:** The orchestrator populates the new prompt with\n     structured attempt data from\n     `state_root\u002Fworkspace\u002Farchive\u002F.repro_attempts.json` and trajectory\n     learnings from `workspace\u002Flearnings.jsonl` (e.g., *\"Attempt 1 failed due to\n     missing auth header X; Attempt 2 proved parser strips unescaped quotes\"*).\n   - **Benefit:** Eliminates context bloat and reasoning inertia (\"hallucination\n     traps\"), enabling a fresh agent to solve the problem using prior empirical\n     observations without repeating past mistakes.\n\n3. **Attempt Cap Accounting & Arithmetic:**\n\n   - The orchestrator maintains\n     `state_root\u002Fworkspace\u002Farchive\u002F.repro_attempts.json`.\n   - **Tier 3 Increment Only:** Only Tier-3 full sandboxed service executions\n     (or full end-to-end reproducer runs) increment the per-finding attempt\n     counter toward the absolute hard ceiling of 6.\n   - **Stepping-Stone Sub-Budget:** Internal Tier-1 and Tier-2 trial runs are\n     bounded by a local sub-budget (max 3 trial executions per conversation) and\n     do not consume the absolute 6-attempt cap.\n\n#### B. Harness-Enforced Tier 4 (Staging & Live Pre-Production Execution)\n\nTo prevent un-gated exploit execution on live infrastructure, Tier 4 (Staging \u002F\nPre-Production verification) is **strictly owned and enforced by the\nprogrammatic orchestrator harness**, never by LLM discretion:\n\n- **Sandbox Boundary:** `mantis-reproduce` executes strictly within isolated\n  local sandboxes (Tiers 1–3) ending at Tier 3 (`reproduced` \u002F\n  `failed_to_reproduce`).\n- **Deterministic Gate:** The harness intercepts a Tier 3 `reproduced` verdict.\n  If live\u002Fstaging validation (Tier 4) is configured, the harness **MUST NOT**\n  automatically invoke remote execution. It must enforce a **programmatic\n  Human-in-the-Loop gate**:\n  - Prompt the human operator for explicit interactive confirmation, OR\n  - Require a cryptographically signed approval token \u002F authorization callback.\n- **Fail-Closed Default:** If human approval is missing or denied, Tier 4 is\n  skipped and the Tier 3 sandboxed verdict remains authoritative.\n\n#### C. Local Ingress \u002F Middlebox Edge Annotation (Post-Tier-3 Sandbox Verification)\n\nTo eliminate false-positive findings caused by default edge filters (\"Works on\nlocalhost:8080, but dies at the WAF\u002Fproxy\"), the orchestrator can optionally\nexecute a Tier 3 PoC through a local reverse proxy or API gateway (e.g. NGINX,\nEnvoy, ModSecurity) running inside the local sandbox:\n\n- **Annotation Only:** A payload blocked by a local middlebox MUST NOT downgrade\n  a Tier 3 `reproduced` verdict to `failed_to_reproduce`.\n- **Critic Integration:** The harness records `ingress_blocked: true` (or edge\n  filter details) in the finding's `repro_hints` or history. This provides\n  empirical evidence for `\u002Fmantis-critic` to classify `production_viability` as\n  `\"CONDITIONAL_VIABLE\"` (mitigated by default edge proxy configuration).\n",{"name":5,"description":7},"main","729d31653d4c2a61764d66e4de713838ce2ed2e2","skills\u002Fmantis-pipeline-adapter",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":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add google\u002Fmantis --skill mantis-pipeline-adapter",{"tool":63,"command":64},"bunx","bunx skills add google\u002Fmantis --skill mantis-pipeline-adapter",{"tool":66,"command":67},"pnpm","pnpm dlx skills add google\u002Fmantis --skill mantis-pipeline-adapter","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-pipeline-adapter\u002FSKILL.md",true,[71,77,81],{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002Fmantis-kb-query.md","REFERENCE","参考文档",8878,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-pipeline-adapter\u002Freferences\u002Fmantis-kb-query.md",{"path":78,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fmantis-sast-seed.md",19428,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-pipeline-adapter\u002Freferences\u002Fmantis-sast-seed.md",{"path":82,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Fmantis-structural-index.md",1537,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fmantis\u002Fblob\u002Fmain\u002Fskills\u002Fmantis-pipeline-adapter\u002Freferences\u002Fmantis-structural-index.md",[86,113,139,166,177,192],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":42},"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",[],[93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112],"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":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":122,"publishedAt":42},"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",[119],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000021","资料检索与研究",[123,124,125,126,127,128,129,98,130,131,132,96,133,134,135,136,137,138,37,31],"summarize","mantis summarize","writing","directory","review","security","threat modeling","planning","repository","patching","campaign","map","modeling","scripts","make","reviews",{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":150,"publishedAt":42},"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",[145],{"categoryNo":146,"categoryName":147,"taxonomyType":148,"taxonomyTypeDesc":149},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[151,152,153,154,98,155,156,157,158,132,159,160,161,27,162,163,164,165,37,31],"mantis structural index","index","structural","research","content","reporting","data","analysis","improve","quality","context","research quality","reference","live","unit",{"skillNo":167,"name":168,"nameZh":6,"description":169,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":170,"categories":171,"keywords":172,"publishedAt":42},"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",[],[127,173,98,174,132,27,175,176,138,37,111,112,31],"mantis review","validation","filters","false",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":183,"publishedAt":42},"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",[],[184,185,125,127,186,98,130,158,187,188,27,102,189,190,138,37,111,191,112,31],"mantis researcher","researcher","static analysis","plan","strategy","deep","you","static",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":198,"publishedAt":42},"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",[],[199,200,128,98,132,201,202,203,27,204,205,206,190,37,31],"mantis reproduce","reproduce","verify","write","execute","crash","payload","script"]