Architect (/mantis-architecture)
System Goal
Knowledge Base Synthesizer. Translates ephemeral insights from the learnings
queue (workspace/learnings.jsonl) and structural analysis of the codebase into
a canonical, interlinked Markdown Knowledge Base (workspace/kb/).
Command Definition
- Command:
/mantis-architecture - Description: Builds the foundation of the KB by defining system architecture, mapping specific entities (components), and categorizing historical vulnerability patterns.
- Arguments (all optional; resolved by LOCATOR RESOLUTION / Block A):
--snapshot_root=<dir>(or theSNAPSHOT_ROOTenv var) — the pinned code snapshot to read target source from;--snapshot_id=<id>— theSNAPSHOT_IDof that snapshot;--state_root=<dir>— the parent ofworkspace/for all state and KB paths;--target_root=<dir>— an already-prepared tree that OVERRIDES the snapshot (rarely passed to this stage). When none are passed, behavior is byte-for-byte today's (degraded/unpinned): read source from the current directory and treatsnapshot_pinnedas false.
Input/Output Contract
- Reads:
workspace/learnings.jsonl(raw insights from the current round).workspace/historical_learnings.jsonl(optional, past vulnerability metadata).- Codebase directory structure and key source files.
- Existing Markdown files in
workspace/kb/(to validate/decay check). workspace/.mantis_state.json(to retrieve pass count).workspace/.mantis_state.json→active_snapshot(root,snapshot_id,snapshot_pinned) andsnapshot_history— provenance for the KB freshness gate (step 0b). Read the snapshot from STATE ONLY; NEVER run a live VCS command (git/hg/repo) to decide KB currency.workspace/.mantis_state.json→kb_snapshot_id(theSNAPSHOT_IDthe current KB was last built against; absent on a first/legacy KB).workspace/.mantis_state.json→changed_filesandchanged_files_status(written by mantis-plan's Block E; consumed by the scoped KB invalidation in step 0b outcome 3. Present from pass 2 on, but may be stale (written in a prior pass) — the scoped path checkschanged_files_passagainststate.pass_numberand falls back to full rebuild if they differ.)
- Writes:
- Markdown files under
workspace/kb/(architecture.md,entities/[component_name].md,vulnerabilities/[CWE-ID].md,index.md). workspace/kb/dependencies.json— a JSON map of import/dependency edges extracted during architectural analysis (keys = source file paths relative to CODE_ROOT; values = arrays of files that import/depend on the key file). This is consumed bymantis-plan's dependency-aware fan-out (Phase 2). If the codebase has no parseable import structure, write{}. Re-derive only changed entries during scoped invalidation (see outcome 3 below).- Archives
workspace/learnings.jsonltoworkspace/archive/learnings/learnings_pass_${N}_${X}.jsonl. - A
<!-- KB_SNAPSHOT: <SNAPSHOT_ID> -->marker as the FIRST line of every (re)written KB file (index.md, eachentities/*.md, eachvulnerabilities/*.md), pluskb_snapshot_id=SNAPSHOT_IDinworkspace/.mantis_state.json. - An immutable per-pass copy of the whole KB tree to
workspace/archive/kb/kb_pass_${N}_${X}/(so a later reverted fix cannot silently erase the record of what the KB claimed at pass N).
- Markdown files under
- Preconditions:
workspace/learnings.jsonlmust exist.
- Idempotency Guarantee:
- Transactional: moves
workspace/learnings.jsonlto archive only after programmatically verifying all KB Markdown updates were written successfully. KB files are overwritten in-place. - Snapshot stamping is part of the same transaction: the
KB_SNAPSHOTmarkers, the per-passworkspace/archive/kb/kb_pass_${N}_${X_kb}/copy, and thekb_snapshot_idstate write complete before (or together with) the learnings move. On any failure, leaveworkspace/learnings.jsonlintact.
- Transactional: moves
Instructions
Analyze the codebase and pending learnings to construct a permanent, Markdown-based memory for future agents.
Execute the architecture stage as follows:
- LOCATOR RESOLUTION (Block A, inlined below):
This is a CODE-READING stage (steps 2 and 4 read target source), so Block A
steps 1-6 all apply; it is NOT findings-only. Resolve CODE_ROOT,
SNAPSHOT_ID, and snapshot_pinned from state BEFORE doing anything below. Per
Block A step 3, all workspace/kb/... paths are STATE-RELATIVE: read and write
them under state_root/workspace, NEVER under CODE_ROOT. Read all target
source under CODE_ROOT. Do NOT run any VCS command to decide KB freshness
(Block A step 5's carve-out is only for history/diff/blame, which this stage
does not use).
0b. KB SNAPSHOT FRESHNESS GATE (mechanical; STATE + KB marker only, NO live VCS):
-
Read the Inbox (
workspace/learnings.jsonlandworkspace/historical_learnings.jsonl):- Parse the contents of
workspace/learnings.jsonl(andworkspace/historical_learnings.jsonlif it exists). Extract all trajectory insights, discovered vulnerabilities, viable crash paths, and verified patches.
- Parse the contents of
-
Analyze Source Code Boundaries:
- Examine the directory structure and key source files under
CODE_ROOT(the pinned snapshot resolved by Block A; use absolute paths per Block A step 6, and do NOT run a VCS command). Dynamically identify the core components, interfaces, and trust boundaries of the system based on the repository's contents. This applies broadly across domains: whether it is a software system (e.g., identifying parsers, controllers, or network daemons), a hardware/RTL design (e.g., identifying IP blocks, JTAG interfaces, or memory controllers), Infrastructure-as-Code (e.g., identifying cloud permissions, VPC perimeters, or deployment descriptors), or data/ML pipelines (e.g., identifying data ingress points, model serialization mechanisms, or training boundaries).
- Examine the directory structure and key source files under
-
Build or Update the Knowledge Base (KB):
-
Create or update files in the
workspace/kb/directory using standard Markdown. Follow these strict paths:workspace/kb/architecture.md: High-level data flows, zone definitions, system design, and overall availability/uptime requirements (if documented or inferable from configuration like systemd, kubernetes, or load balancers).workspace/kb/entities/[component_name].md: Specific definitions for components (e.g.,auth_module.md). Must include links to associated vulnerability classes and document known constraints (e.g., "This module sanitizes input X"). Document the component's criticality and availability requirements (classify as CRITICAL, STANDARD, or LOW_CRITICALITY if applicable). Incorporate trajectory insights here.workspace/kb/vulnerabilities/[CWE-ID_or_BugClass].md: Descriptions of bug classes (e.g.,CWE-79.mdorMemory-Corruption.md) that have been historically relevant to this codebase, including examples of what not to do.workspace/kb/index.md: A root catalog containing links and 1-line summaries to every file created above. This is the map the Planner will read.
-
Important Formatting Rules: Use relative links to cross-reference entities and vulnerabilities (e.g.,
[Auth Module](entities/auth_module.md)). Ensure all markdown files are concise and focused on actionable security context. -
Snapshot stamping (REQUIRED on every (re)written KB file when running the freshness gate, i.e. HALT or PINNED; never in MODE-OFF): Make the FIRST line of
index.md, eachentities/*.md, and eachvulnerabilities/*.mdexactly<!-- KB_SNAPSHOT: <SNAPSHOT_ID> -->(substituteCURfrom step 0b; it is an HTML comment so it does not render). This is how the next pass's freshness gate (step 0b) detects drift. MODE-OFF gate (3-state rule): ifactive_snapshotis ABSENT (MODE-OFF — no--syncwas requested), do NOT stamp the per-fileKB_SNAPSHOTmarker:CURis the empty string (arch:145: "the empty string ifactive_snapshotwas absent"), so the mandated marker would be<!-- KB_SNAPSHOT: -->(empty value) — a snapshot-era artifact that did not exist in Phase 1. The per-file marker is ONLY consumed by step 0b's freshness gate, which MODE-OFF skips entirely (arch:147-152: "SKIP the freshness gate entirely... This is byte-for-byte today's behavior. Only HALT and PINNED run the gate below."). This MODE-OFF gate mirrors the freshness gate logic below and step 0b's outcome clauses, which mention per-fileKB_SNAPSHOT: CURstamping only in HALT/PINNED outcomes (CURRENT:164, scoped BUILD FRESH:178, full BUILD FRESH:195). -
Per-file
KB_SNAPSHOTstamping is the sole provenance mechanism for KB assertions. Do NOT write per-assertion(AS_OF:<snapshot>)tags — theAS_OFre-verification reader was never built, and staleness protection is already provided by the freshness gate (step 0b) comparingkb_snapshot_idtoSNAPSHOT_ID, plus per-findingdiscovery_commit(enforced bymantis-criticBlock B). A later-reverted fix is caught by these mechanisms, not by per-assertion tags.
-
-
Validate and Decay Knowledge (Drift Prevention):
- Knowledge becomes stale when code is patched or refactored. Before
finalizing the KB updates, spot-check the assertions in the existing
workspace/kb/entities/against the source underCODE_ROOT(the pinned snapshot — NOT a live VCS query, and NOT the live working tree). In the BUILD FRESH outcome (step 0b) do NOT spot-check at all: discard the prior assertions and re-derive every entity fromCODE_ROOTthis pass. In the STALE / HALT outcome, spot-check only best-effort and keep the STALE banner regardless of the result. - If an entity file claims a variable is un-sanitized (based on an old learning) but the live code now contains a sanitization function (because a patch landed), delete or correct that outdated learning in the KB.
- If a learning is repeatedly proven wrong by the current trajectory insights, actively correct it to prevent the "wrong learning" from persisting and blinding future agents.
- When you correct or re-confirm a finding-derived assertion, re-stamp the
KB_SNAPSHOTmarker on that KB file.
- Knowledge becomes stale when code is patched or refactored. Before
finalizing the KB updates, spot-check the assertions in the existing
-
Transactional Inbox Clearing & Archiving:
- To prevent infinite loops and token bloat, you must clear the queue and archive the learnings.
- Verify and Finalize: Programmatically verify that all Markdown KB
updates were successfully written to disk and that cross-references are
valid. Also verify, before committing, that every (re)written KB file
BEGINS with its
<!-- KB_SNAPSHOT: <SNAPSHOT_ID> -->marker and that every finding-derived verdict is grounded in the currentSNAPSHOT_ID. - Commit by Moving: Only after verifying synthesis success, move
workspace/learnings.jsonlto the archive directory:- Ensure the target directory exists (e.g.,
mkdir -p workspace/archive/learnings/). - Determine the loop pass number
Nby reading"pass_number"fromworkspace/.mantis_state.json. If missing or invalid, scanworkspace/archive/for folders matchingfindings_pass_NorloopN_findingsand resolveNtomax_found + 1, defaulting to 1 if no archives exist. - Determine the sub-index
Xby counting existing files matchinglearnings_pass_${N}_*.jsonlinworkspace/archive/learnings/and adding 1. - Move the file:
mv workspace/learnings.jsonl workspace/archive/learnings/learnings_pass_${N}_${X}.jsonl.
- Ensure the target directory exists (e.g.,
- Snapshot the KB (per-pass archive): After a successful synthesis, copy
the whole KB tree to a per-pass archive:
- Ensure the directory exists (
mkdir -p workspace/archive/kb/). - Compute sub-index
X_kb= (count of existingkb_pass_${N}_*directories inworkspace/archive/kb/) + 1. - Copy (do NOT move — the live
workspace/kb/must persist for the next pass):cp -a workspace/kb/. workspace/archive/kb/kb_pass_${N}_${X_kb}/.
- Ensure the directory exists (
- Stamp state: Write
kb_snapshot_id=SNAPSHOT_ID(CURfrom step 0b) intoworkspace/.mantis_state.json. Ifactive_snapshotwas absent (MODE-OFF), do NOT writekb_snapshot_idand do NOT prepend any STALE banner (the freshness gate was skipped). In HALT mode, writekb_snapshot_id=CURand leave the STALE banner inindex.md. - If synthesis fails or is interrupted, leave
workspace/learnings.jsonlintact in its original location to ensure no data is lost. - If
workspace/learnings.jsonlis ABSENT on entry (e.g. the Stage-15 invocation, because the Stage-2 invocation already archived it this pass), skip ONLY the learnings move; STILL run the freshness gate (step 0b), stamp theKB_SNAPSHOTmarkers, writekb_snapshot_id, and copy the per-pass KB archive. KB provenance must be recorded on every invocation.
When complete, notify the user.
