| name | agents-system-setup |
| description | Bootstrap, improve, replicate, or upgrade compact multi-agent systems across Copilot CLI, Claude Code, OpenCode, OpenAI Codex (CLI + App), and Gemini CLI. Generates AGENTS.md (with host-session Orchestration Operating Model) plus specialized subagents (no separate orchestrator file), governance matrices, and opt-in plugin/MCP recommendations. Uses Canonical IR, MCP approval gates, platform-correct formats, version stamping, and context-optimized output profiles. Triggers: "set up agents", "scaffold AGENTS.md", "improve my agents", "audit agent setup", "architecture review", "security audit agents", "replicate agents", "upgrade agents", "agents-system-setup upgrade", "configure copilot/claude/opencode/codex/gemini", "discover plugins/MCP". |
| argument-hint | [init | update | improve | replicate | upgrade] (omit to auto-detect) |
Setup Copilot Agents (multi-platform)
Scaffold or update a complete agent system for the current project across Copilot CLI, Claude Code, OpenCode, OpenAI Codex (CLI + App), and/or Gemini CLI. Produces a canonical AGENTS.md (with Orchestration Operating Model, Directory Architecture, Agent Roster, Capability Matrix, Security & Audit Matrix, Threat Model, and Architecture / Design Decisions), specialized subagent files (no orchestrator file — the host CLI session reads AGENTS.md), project-scoped skills, and approved plugins/MCP servers — derived from a structured interview.
When to Use
- Brand-new repository needs an agent setup from scratch (init)
- Existing project should adopt or extend the orchestrator + subagent pattern (update)
- Existing agent system needs an audit (improve) or a version-aware migration to current principles (upgrade — triggered by
agents-system-setup upgrade)
- Agents authored for one runtime need to be ported to another (replicate — Copilot ↔ Claude Code ↔ OpenCode ↔ OpenAI Codex ↔ Gemini)
- Discovering relevant plugins / MCP servers from the well-known marketplaces
Hard Rules
- Always interview first with the provider-native human-input tool. Use human input; in Copilot CLI this is the session
ask_user tool and --no-ask-user disables it. Never assume project type, language, scope, or target platform.
- Detect existing agent footprint on entry. If any of
AGENTS.md, CLAUDE.md, GEMINI.md, opencode.json, .github/agents/, .claude/agents/, .opencode/agents/, .codex/agents/, .gemini/agents/, ~/.codex/AGENTS.md exists, present mode choice with improve and replicate as first-class options — never silently jump to update.
- Orchestrator + subagent topology is mandatory. Subagent count (3 to ~50) is decided dynamically from scope.
- Directory Architecture is generated and enforced. Every subagent file references it; the orchestrator routes by ownership.
- Per-item opt-in recommendations. Plugin / skill / MCP candidates are always presented with rationale and explicit
ask_user choice — never bulk-applied silently.
- MCP config approval gate. Before writing any MCP config (
.mcp.json, opencode.json › mcp, agent mcp-servers: / mcp_servers:, extension/plugin MCP manifests), render the proposal and call ask_user for approval. No silent MCP writes — ever. Replication re-triggers this gate per new target.
- Marketplace-first lookup with vendor attribution. Recommendations come from registries listed in marketplaces, tagged
[Tier · Vendor] — never invent names or URLs.
- Replication goes through Canonical IR, not pairwise mappings. See replication. Never write a Copilot→Claude (or any other direction) function; always parse → IR → emit.
- Non-destructive updates.
cp <file> <file>.bak before any edit; merge into managed blocks, preserve user-authored content.
- Multi-platform aware. Emit per-platform paths and frontmatter per platforms. Never write Copilot frontmatter into a Claude file.
- Cross-OS aware. Detect host OS once (Linux / macOS / Windows-bash / Windows-pwsh) per cross-platform. Pick
.sh for POSIX shells, .ps1 for native PowerShell. Forward slashes in generated docs. Never symlink on Windows. Bundle .gitattributes so line endings stay correct on every clone.
- Git is optional and gated by
ask_user.
- Parallelism is mandatory where work is independent. The generator computes parallel-safety from the Directory Architecture and emits a wave table; the orchestrator prompt always contains a fan-out clause. For Claude Code, also emit
AGENT-TEAMS.md per parallelism. When GitHub Copilot CLI/app is a selected runtime, the same parallel-safety computation also feeds the optional Copilot-app cross-session advisory (child sessions / parallel PRs) per parallelism — advisory only; generated files never depend on it and subagents never orchestrate sessions. Sequential-only topologies are an error.
- If the project domain is software-development, recommend GitHub Spec-Kit. After domain detection (Phase 1.7), if the brief matches a software-dev keyword set, present spec-kit as an opt-in companion via
ask_user, never auto-install. See spec-kit.
- Security, audit, architecture, and design-pattern governance are mandatory. Every plan and generated
AGENTS.md must include the baseline from security-audit-architecture: Security & Audit Matrix, Threat Model, Architecture / Design Pattern Matrix, ADR plan, and Quality Gates. Small projects may merge roles, but not omit the concerns.
- Security-sensitive writes require evidence. MCP config, secrets-adjacent paths, CI/release config, and generated scripts must have an owner, approval state, and verification evidence in the output contract. No broad write permissions without rationale.
- Improve / upgrade are evidence-based. Score security boundaries, secrets, audit evidence, architecture ownership, instruction-memory conflicts/redundancy, design patterns, and supply-chain trust before applying deltas; use instruction-memory-audit.
- Context budget is a feature. Default to the
Balanced output profile from context optimization: keep routing and gates inline, move deep detail behind explicit references, and never duplicate long policy prose in every agent.
- Ask whether agent artifacts are git-tracked or local-only. Before writing project-scoped agent files, ask the tracking question from local tracking. For local-only project files, write
.git/info/exclude (never .gitignore) and verify with git check-ignore.
- Plan handoff is normalized before emission. Treat VS Code
plan prompt output, Spec-Kit /plan, and user-written plans as upstream planning input only. Convert them to the handoff contract / HandoffIR, then emit each selected runtime's native format. Never copy prompt frontmatter or another runtime's agent schema into generated artifacts.
- Runtime drift is source-backed and gated. Use runtime updates before changing platform support. Gemini CLI is supported for local project subagents; remote A2A/extension packaging surfaces remain explicit import/package work.
- Model overrides are opt-in only — never asked by default. Keep
model: lines omitted in every generated agent. Do not ask the model-override question in the interview unless the user has spontaneously named a model, asked for BYOK / multi-model routing / cost-perf tuning, or otherwise signalled awareness. When opt-in is triggered, load models for the runtime's accepted format, defaults, and rate-limit sources; never pin live RPM/TPM numbers in generated files. See interview Q9b for the opt-in gate.
- Task assignments use the canonical contract. Compose every orchestrator → subagent handoff with the Task Assignment Contract. Always fill the Required Minimum; add Expansion Blocks per the Recommended Packet Form. Subagents run the Acceptance Checklist before doing work and emit results via the Reporting Template; missing required fields trigger one consolidated
question_request: to the orchestrator.
- Learning memory is approval-safe and native-aware. When enabled, generated agents run the Learning Check before final response.
none is valid. Subagents propose learnings; only the orchestrator or memory owner writes plugin-managed memory, and overwrite requires orchestrator approval. Native provider memory is complementary and used only where documented; never emit unsupported memory fields such as Codex agent TOML memory.
- Human-input schemas are provider-specific. Never add
ask_user to Copilot custom-agent tools: profiles. Claude agents that need to ask include AskUserQuestion; OpenCode uses nested permission: { question: allow }; Codex uses request_user_input only in Plan mode and falls back to question_request; Gemini may allow ask_user. Subagents return question_request when they cannot ask directly.
- Run self-update preflight before setup. Phase -1 uses self-update preflight at
${AGENTS_SYSTEM_SETUP_HOME:-$HOME/github/agents-system-setup}. Fast-forward only clean Git checkouts; ask or emit question_request on dirty, missing, divergent, or install-manager ambiguity. Never update MCP/plugin config silently.
- Requirements triage is default-on recommended. Add
requirements-triage before planner for normal, ambiguous, cross-runtime, security-sensitive, release, MCP, replication, or multi-wave setups. For tiny direct setups, merge the role into planner and record why. Triage is read-mostly, uses question_request, and never owns final decisions or approval gates.
- Content quality is universal. Apply content quality to all generated agents, skills, memory files, recommendations, and output contracts. Generate
agent-quality-curator as a separate read-only role for normal/complex setups, merge into reviewer for tiny setups, and report Content quality: ok|warn|fail|n/a.
- Main-to-subagent handoff is structured. Use the handoff contract and prompt guidelines to compose provider-native Task Assignments. Recommended-only for safe tiny work; full-form for normal, risky, multi-file, fan-out, MCP, release, replication, security, architecture, or generated-agent-system work. Pass a subtask slice, not full project memory.
- Dedicated security teams are explicit. Generate the security team topology only when the user selects
Security team / Bug hunting, asks for bug hunting/security analysis/disclosure triage, or the risk intake justifies it. Security discovery, validation, attack-path, triage, and compliance roles are read-mostly by default; remediation writes, external scanning, exploit execution, credential use, production testing, disclosure outreach, MCP/tool config, and destructive tests require explicit approval and owning-agent routing.
- Operational state directory is artifact-free.
.agents-system-setup/ holds operational state only (replication ledger, MCP approval evidence, learning ledger, migration.jsonl, .bak files). Never write agents/, skills/, hooks/, commands/, prompts/, or plugins/ subtrees inside it; runtimes do not load them and existing misroutes go through misplaced-artifacts-migration.
- Capture user purpose before deep recon. Phase 0 sub-step 0 asks the headline purpose first; Phase 1 recon then scores and highlights signals against that intent (never filters). Allow an explicit
"I'm exploring — let recon lead" sentinel that defers the purpose ask until after the card. See cwd-reconnaissance.
- The orchestrator is the host CLI session, not a subagent file. Never emit
orchestrator.agent.md, .claude/agents/orchestrator.md, .opencode/agents/orchestrator.md, .codex/agents/orchestrator.toml, or .gemini/agents/orchestrator.md. The Orchestration Operating Model lives in AGENTS.md and is read by the host CLI session of any selected runtime. @orchestrator remains a routing role alias for that host session — it is never an emitted agent artifact. OpenCode's permission.task gate moves to opencode.json (host root agent) since no orchestrator file is emitted.
- Generated artifacts carry a
generated-by version stamp + central manifest. Every emitted Markdown/TOML artifact includes agents-system-setup:generated-by: vX.Y.Z (renderer substitutes {{PLUGIN_VERSION}} from plugin.json); .agents-system-setup/generated.json holds the authoritative manifest. Improve / upgrade modes read stamps and apply the per-version delta playbook in misplaced-artifacts-migration. Never hand-edit a stamp. The read-only agents-doctor skill/script reconciles on-disk agents against this manifest — strays (including a hand-written orchestrator), missing artifacts, checksum drift, missing stamps — and is re-runnable by a human, CI, or the host session; see agents-doctor.
- SDLC Build Gate is software-dev default-on, with
Skip opt-out. When Phase 1.7 classifies the project as software-dev, ask Q9d Build Gate strictness (Standard | Strict | Light | Skip). Unless Skip, generate build-runner, change-bug-hunter, change-validator (merge into @reviewer for Light), the code-change-build-gate skill at every selected runtime's skills path (Codex included), and AGENTS.md › Build Gate (SDLC) with the matrix snippet. The bucket is max(size_bucket, criticality_bucket); criticality always wins; the inline matrix is fail-closed. See sdlc-build-gate.
task-handoff skill is the host-side source of truth; subagents are executors. Emit task-handoff SKILL.md at every selected runtime's skills path (Copilot/Claude/OpenCode/Codex/Gemini). The host CLI session loads it before composing delegation packets and passes Skills Referenced: task-handoff loaded=true in the packet. Subagent templates keep an inline fail-closed Acceptance Checklist + Reporting Template that the skill body deduplicates. Subagents never re-delegate through this skill; if scope exceeds owned paths, they return-to-orchestrator.
- Layered context & self-contained subagents. When
subagent_count >= 2 AND profile is Balanced/Full, generated AGENTS.md MUST carry visible **Audience:** all | host-orchestrator | subagents markers under every ## Section plus a ## Subagent Self-Contained Notice block; subagent files MUST inline the project-standard digest in the <!-- subagent-digest:managed:start v=<hash> --> ... :end --> managed block, plus owned paths, handoff acceptance, safety boundaries, and reporting skeleton, while still permitted to reference AGENTS.md rows + the task-handoff skill. Compact profile and single-agent setups omit the markers/notice. Codex uses the 3-line minimal digest variant. See audience-tags snippet, project-standard-digest snippet, and explorer-agents for the plugin's own recon delegation.
- Native Runtime Agents routing (generated systems). When
subagent_count >= 2, render {{HOST_BUILTINS_ROUTING_BLOCK}} from host-builtins-routing snippet as subsection ### Native Runtime Agents under ## Orchestration Operating Model in AGENTS.md, with stable anchor <!-- agents-system-setup:host-builtins-routing -->. Balanced/Full → full per-runtime table; Compact → 1-line summary + reference link. The host orchestrator MAY route broad recon to explore-class built-ins (Copilot explore, Claude Explore, OpenCode explore, Codex explorer, Gemini codebase_investigator) and verbose ad-hoc command execution to task-class built-ins (Copilot task, Claude general-purpose, OpenCode general; Codex & Gemini have no task-class built-in — use custom worker / @build-runner / root session). Build Gate evidence stays with @build-runner / tester / e2e / @change-validator owners; native task-class output is non-gate evidence only. Subagents NEVER re-delegate to built-ins (hard rule #36); they return-to-orchestrator if scope exceeds owned surface. For OpenCode, also extend permission.task with explore and general allows (or record host_builtins_routing: declined). See host-builtins-routing.
- Tool catalog discipline. Generated agents' tool configurations MUST match runtime-correct names in tool-catalog (canonical data:
assets/tool-catalog.json). At emit time, include only tools with scope: both by default; cli-only (Copilot CLI) and vscode-only (VS Code Copilot) tools require explicit opt-in for the shared .github/agents/*.agent.md file. Per-runtime audit_kind differs: Copilot/Claude/Gemini = name-allowlist (validate every tools: / tool_allowlist entry against the runtime block); OpenCode = permission-policy (validate permission: map keys, not the deprecated tools: key); Codex = n/a unless tool_allowlist is explicitly set. Stamp every generated agent with <!-- agents-system-setup:tool-catalog-version: <plugin-version> --> so upgrade mode can distinguish current-catalog vs pre-catalog files. Audit skill tool-catalog-audit is host-side and read-only; subagents never invoke it (hard rule #36). Migration auto-classifies tool changes as manual-review because tool allowlists are security boundaries.
- Code quality & maintainability is mandatory for software-dev. Generated coding agents conform to the project's existing conventions first (configured linters/formatters and local patterns), then apply the authoring standards from code-quality while writing — not only at review. Derive
code_quality_strictness from the Build Gate (mirror build_gate_strictness; floor to light when the gate is skipped; advisory for non-software-dev code-bearing projects; n/a when there is no source code). Emit the code-quality skill at every selected runtime's skills path (Codex included), render AGENTS.md › Code Quality & Maintainability from the code-quality-standards snippet, and add a read-only code-quality-reviewer (merge into @reviewer for light/advisory/tiny). The host passes Skills Referenced: code-quality loaded=true on code-edit/bug-fix/refactor packets; edit-capable and reviewer subagents emit Code quality: ok|warn|fail|n/a. This is authoring craft, complementary to the Build Gate (verification) and distinct from content-quality (agent prose).
Procedure
Phase -1 — Self-Update Preflight
Before footprint detection, run the safe preflight from
self-update-preflight:
- Locate
${AGENTS_SYSTEM_SETUP_HOME:-$HOME/github/agents-system-setup}.
- If it is a clean Git checkout with an upstream,
git fetch and
git merge --ff-only when only behind.
- If the checkout is missing, dirty, ahead, divergent, lacks upstream, or the
install owner is ambiguous, ask with the provider-native human-input tool
from human input. If interaction is disabled,
emit
question_request and continue with the installed version.
- Do not edit MCP config, plugin config, runtime settings, generated agents, or
version/release files during this phase.
Record update_preflight_status, source path/manager, and evidence for Phase 2
and the final output contract.
Phase 0 — Capture Purpose, Detect Footprint, Choose Mode
Sub-step 0 — Capture headline purpose first. Before any directory
scan or mode choice, ask the user's intent with the provider-native
human-input tool:
"In one sentence, what are you trying to achieve with an agent system here?"
Freeform; offer "I'm exploring — let recon lead" as a labeled choice.
Persist headline_purpose: string | "exploring". This drives Phase 1
purpose-aware recon scoring — see
cwd-reconnaissance.
When exploring, defer the purpose ask until after the recon card.
Sub-step 1 — Detect footprint. Inspect cwd for project and agent
artifacts per Phase 1 step 1; do not run deep recon yet.
Sub-step 2 — Show profile card and ask mode. Display the captured
headline_purpose, detected project type, existing agent artifacts by
runtime, recommended mode, and inferred current runtime(s):
"I detected <footprint>. How should I proceed?"
Choices: ["Improve current setup (Recommended when artifacts exist)", "Init new setup", "Replicate / sync to another runtime", "Update managed blocks", "Cancel"]
Persist the selected mode. Do not ask target runtimes before this mode
choice. After mode is known:
init / update: ask which runtime(s) to generate unless the user's request already names them.
improve: default scope to detected runtime(s); ask a target runtime only if updating one runtime or expanding audit scope requires it.
replicate / sync: defer source and target runtime questions to Phase 1.5, and ask targets only for the requested expansion/sync.
All later phases loop over the selected or detected runtime scope using platforms.md as the source of truth for paths and frontmatter. Gemini CLI emits local subagents at .gemini/agents/*.md; see agent format for its non-recursive subagent and mcp_servers: rules.
Phase 1 — Footprint Details & Interview Continuation
-
Inspect cwd and detect runtime footprint:
- Project files:
package.json, *.csproj, Package.swift, build.gradle, pyproject.toml, go.mod, Cargo.toml, mkdocs.yml, .git/.
- Agent artifacts (per runtime):
- Copilot CLI:
AGENTS.md, .github/agents/*.agent.md, .github/agents/*.md (docs-drift import signal), .github/skills/, .mcp.json
- Claude Code:
CLAUDE.md, .claude/agents/, .claude/skills/, .claude/settings.json
- OpenCode:
opencode.json, .opencode/agents/, .opencode/skills/
- OpenAI Codex:
AGENTS.md (orchestrator + project rules), .codex/agents/*.toml (specialized subagents), .codex/config.toml, ~/.codex/AGENTS.md, ~/.codex/agents/; CLI-only plugin/command UX stays documented separately
- Gemini CLI:
GEMINI.md, .gemini/agents/*.md, .gemini/settings.json, ~/.gemini/GEMINI.md, ~/.gemini/agents/
- Project recon: run the safe-readonly cwd reconnaissance from cwd-reconnaissance using the Phase 0
headline_purpose for scoring: signals are sorted high → med → low → n-a by purpose_relevance but never filtered. When headline_purpose == "exploring", render in default order and re-ask the purpose question after card confirmation. Render the Reconnaissance Card and ask_user to accept/correct/skip. Privacy guardrails (no data file reads, magic-byte detection, secret redaction) are mandatory. For large codebases (source_files > 50 OR top_level_dirs > 8 OR frameworks_detected > 3 OR recon_threads_requested > 2), delegate recon to the host runtime's native explorer subagent per explorer-agents instead of sequential view/glob/grep.
- Misplaced artifacts: scan for
.agents-system-setup/{agents,skills,hooks,commands,prompts,plugins}/ and queue every match for the per-artifact prompt in misplaced-artifacts-migration.
-
Confirm the Phase 0 mode — do not re-ask target runtimes before the mode
choice. Use this table only to pick the recommended mode/default choices shown
in the Phase 0 profile card, or to re-prompt if the initial detection was
ambiguous:
| Detected footprint | Default offer | Choices |
|---|
| Nothing | init | ["Init (Recommended)", "Cancel"] |
| One runtime, looks healthy | improve | ["Improve current setup (Recommended)", "Upgrade (apply version migrations)", "Update (regenerate managed blocks)", "Replicate to another runtime", "Init alongside (additive)"] |
| One runtime, gaps | update | ["Update (Recommended)", "Upgrade (apply version migrations)", "Improve (audit + targeted fixes)", "Replicate to another runtime"] |
| Detected stamp older than current plugin version | upgrade | ["Upgrade to current version (Recommended)", "Improve (audit + targeted fixes)", "Update (regenerate managed blocks)"] |
| Two+ runtimes | improve | ["Improve current setup (Recommended)", "Upgrade (apply version migrations)", "Replicate / sync between runtimes", "Update one runtime"] |
-
Continue the interview — see interview script. One question per ask_user call. Skip questions already answered by detection (project type, framework). After the Phase 0 mode choice, offer to use detected/safe defaults for non-gated setup questions. Never skip artifact tracking, MCP approval, plan approval, or security-sensitive write gates. For init/update, ask target runtimes only after mode if needed. For improve/replicate, jump straight to Phase 1.5; runtime expansion questions happen there only if required.
Phase 1.5 — Improve / Upgrade / Replicate branch
If the user picked improve → run the improve procedure plus instruction-memory-audit: classify AGENTS.md as canonical memory, adapters (CLAUDE.md/GEMINI.md) as expected pointers/copies, and long workflows as skill/path-rule candidates before proposing deltas. Misplaced artifacts are first-class deltas. Skip Phases 2–4; jump to Phase 5.
If the user picked upgrade → run the version stamp detection & migration playbook plus the mismatch & deprecation detection, then the instruction-memory audit after known version deltas are classified: read .agents-system-setup/generated.json or stamps, walk version deltas in order, run the structural diff (missing sections/skills/roles, deprecated artifacts, stale prose, unsupported runtime fields), render the mismatch report grouped by delete | add | patch | replace, ask for per-group approval, back up (.bak per file + .agents-system-setup/migration-backup/<timestamp>/ for directory removals), preserve user content outside managed blocks, append .agents-system-setup/migration.jsonl entries, and update the manifest atomically. v1.5.0 → v1.6.0 deltas include missing-audience-tag and non-self-contained-subagent; migrate subagents FIRST (per-file backup + digest managed-block injection), then AGENTS.md (audience markers + Self-Contained Notice), with a 3-state ledger (prepared → applied → verified) before the manifest version bumps. Skip Phases 2–4; jump to Phase 5. Triggers include agents-system-setup upgrade, /setup-copilot-agents upgrade, and $agents-system-setup upgrade.
If the user picked replicate → run the replication procedure:
ask_user for source runtime (single-select among detected).
ask_user for target runtimes (multi-select; source excluded).
- Parse source → AgentIR / SkillIR / MCPServerIR records.
- Render lossiness report;
ask_user to approve dropped fields per target.
- Run Phase 1.6 before any target write.
- Re-run Phase 3.5 MCP approval gate against each new target.
- Emit per target with
<!-- agents-system-setup:replicated-from: <source> --> markers.
- Write replication ledger to
.agents-system-setup/replication.jsonl (one JSON object per line — never .md, never inside any agents/ directory, or it will be misread as a malformed agent).
- Verify round-trip (re-parse emitted → diff IR → surface drift).
For improve, run Phase 1.6 before applying any selected delta. For both branches, finish with Phase 7 (verify & summarize).
Phase 1.6 — Artifact Scope & Tracking
Run before Phase 1.7 for init/update, and before Phase 5 writes for improve/replicate. Use local tracking.
Ask:
"Should the generated agent system be shared through git or kept local to this checkout?"
Choices: ["Project files, git-tracked (Recommended for teams)", "Project files, local-only / untracked (Recommended for personal setup)", "Personal/global outside this repo"]
Record artifact_tracking as project-tracked | project-local | personal-global.
Rules:
project-tracked: use project paths; do not commit unless Phase 6 git actions are explicitly approved.
project-local: use project paths, then add only generated/modified artifact paths to .git/info/exclude if .git/ exists. Do not modify .gitignore for this.
personal-global: use runtime user paths and avoid repo writes unless separately approved.
Phase 1.7 — Domain Detection & Spec-Kit Recommendation
Run after Phase 1 (and 1.5 if branched), before Phase 2. Inspect the project brief gathered during interview against this software-development keyword set:
app, application, api, service, microservice, library, sdk, cli, tool, devtool, backend, frontend, fullstack, web, mobile, ios, android, desktop, framework, plugin, extension, package, module, infrastructure, infra, terraform, pulumi, kubernetes, helm, compiler, parser, runtime, database, orm.
If any keyword matches (case-insensitive, word-boundary), or the project already has source-language signals (package.json, pyproject.toml, go.mod, Cargo.toml, *.csproj, pom.xml, Package.swift, build.gradle, mix.exs, composer.json), classify as software-dev. Otherwise non-dev (marketing, research, content, data-analysis).
If software-dev, call ask_user:
"This looks like a software project. Would you like to install GitHub Spec-Kit (Spec-Driven Development: /specify → /plan → /tasks → /implement slash commands) alongside the agent system?"
Choices: ["Yes — install for this runtime (Recommended)", "Just print the install command", "No, skip"]
On approval, emit the runtime-matched command from spec-kit (uv tool install specify-cli --from git+https://github.com/github/spec-kit.git then specify init --here --ai <copilot|claude|codex|opencode>). Print, never silently shell-out unless the user picked "install".
Record the choice in the plan so Phase 4 orchestrator output can reference the /specify workflow when appropriate.
Phase 1.8 — Security, Audit, Architecture Intake
Run after domain detection and before Phase 2. Use security-audit-architecture as the source of truth.
Ask only questions not already answered by detection. Data sensitivity, auth
boundary, and external tools/MCP usage are mandatory. Infer audit evidence,
architecture style, critical qualities, and anti-pattern defaults into the plan
for low-risk projects unless the user asks to configure them explicitly.
- Data sensitivity.
- Auth boundary.
- External tools / MCP usage.
- Audit evidence expectations.
- Deployment / release risk.
- Architecture style.
- Critical quality attributes.
- Known design anti-patterns to avoid.
Record the answers in the plan. If the user is unsure, choose safe defaults: least privilege, no silent MCP writes, no secrets in code, architecture decisions documented in AGENTS.md, and dedicated security/architecture ownership when the project handles sensitive data or external tools.
Phase 1.8a — Security Team Scope
Run only for dedicated security team / bug-hunting setups; use security team. Record security_team_depth, security_team_scope, authorization_scope, selected roles, and source/vendor/license-attributed plugin candidates. Safe defaults: owned repo only, no external scanning/exploit execution/credential use/production testing/disclosure outreach/remediation writes without explicit approval; missing authorization returns question_request.
Phase 1.9 — Output Profile & Context Budget + Advanced Agent Behavior
Run after Phase 1.8 and before Phase 2. Run the grouped
interview Q9b Advanced agent behavior
block explicitly; do not leave model or tool choices as prose-only plan notes.
Group agent-behavior choices together so the user compares tradeoffs once:
optional model overrides, Copilot CLI tool profile when Copilot is selected,
output profile, and Memory & Learning profile. This phase owns those prompts:
ask each advanced behavior choice exactly once and do not re-ask output profile
or memory profile in Phase 1.10. Use context optimization.
Ask and record the Q9b choices before Phase 2:
- Per-agent model override policy — keep runtime defaults unless the user opts in. Ask for override policy by scope (
all agents | by role | exceptions only) and avoid looping over every agent by default.
- Copilot CLI Tool Profile — only when Copilot CLI is selected; persist
copilot_tools_profile.
- Output profile / context budget —
Balanced | Compact | Full.
- Memory & Learning profile — persist
learning_memory_profile, learning_gate_strength, overwrite policy, and whether native provider memory is only documented or explicitly enabled.
- Build Gate (SDLC) strictness — only when Phase 1.7 classified the project as
software-dev; persist build_gate_strictness (standard | strict | light | skipped). See sdlc-build-gate. This single answer also seeds code_quality_strictness (no separate question; derive per code-quality — mirror the gate, floor to light when skipped, advisory for non-software-dev code-bearing projects, n/a when there is no source code).
For Copilot CLI tools, keep prompt choices concise: Standard least-privilege by
role (recommended), Read-only everywhere, Inherit parent tools, or Custom after
generation. Render the full mapping in the plan/reference, not in the question.
For the output profile choice, ask once:
"How much detail should generated agent files include?"
Choices: ["Balanced (Recommended)", "Compact", "Full"]
Record:
output_profile: balanced | compact | full
inline_sections: which sections stay in AGENTS.md
overflow_targets: where long details should be written or proposed (for example docs/agents/security-audit.md)
context_budget_notes: any user constraints on verbosity
If the user is unsure, choose Balanced. This keeps all routing, ownership, governance, and quality gates inline while moving long rationale and overflow candidate lists to references.
Phase 1.10 — Memory & Learning Profile
Do not call ask_user here. Use the Memory & Learning answer already collected
in the Phase 1.9/Q9b advanced-agent-behavior group. This phase normalizes the
recorded choice for planning and rendering. Use learning memory.
Record:
learning_memory_profile: project-tracked | project-local | personal-global | disabled
native_learning_surface: runtime-native memory selected or document-only | disabled
learning_memory_owner: @memory-steward when the roster includes one, otherwise @orchestrator
learning_memory_path: path chosen from learning memory
learning_gate_strength: recommended by default; do not make it blocking unless the user explicitly asks
learning_update_policy: overwrite requires orchestrator approval
Do not ask a separate blocking Learning Check question by default. Native memory
setup follows learning memory: Copilot Memory
is public-preview, transparent server-side durable repo memory, Claude has
memory: user|project|local, OpenCode relies on AGENTS/skills/compaction/plugin
patterns, Codex memories require [features] memories = true, and Gemini has
save_memory, GEMINI.md, /memory, and experimental autoMemory. Ask
optional hook/script support only when the runtime has a supported hook surface
and this setup has not already handled learning. Render the exact hook/config
proposal and ask before writing it.
Phase 1.11 — Requirements Triage
Before Phase 2 planning, decide requirements_triage_status:
separate — generate requirements-triage as its own read-mostly subagent.
merged — merge triage into planner for tiny direct setups.
skipped — only when the task is direct, low-risk, single-runtime, and already has clear scope.
Default to separate for ambiguous, multi-step, cross-runtime, security-sensitive,
release, MCP, replication, audit, improve, or multi-wave setups. The triage role
returns an intake brief with intent summary, task type, in/out scope, ambiguities,
question_request items, risk classification, recommended routing/waves,
acceptance criteria, quality gates, and Learning Check. The orchestrator owns the
final plan, all user-facing questions, and every approval gate.
Phase 1.12 — Content Quality Review
Before Phase 2 planning, decide content_quality_curator:
separate — generate agent-quality-curator as its own read-only subagent.
merged — merge content-quality review into reviewer for tiny direct setups.
skipped — only when no generated agent, skill, memory, recommendation, or output-contract prose is changed.
Default to separate for normal, complex, cross-runtime, audit, improve,
replication, MCP, release, skill-heavy, or multi-wave setups. Use
content quality for signals, status levels,
and boundaries. The curator reports
Content quality: ok|warn|fail|n/a; signals=<list|none> and never owns broad
write, MCP config, runtime config, release metadata, or final approval gates.
Phase 2 — Plan (Directory Architecture, Roster, Matrix, Waves)
Build the plan and show it before writing anything. The plan must include:
- Directory Architecture — table of
path glob | purpose | owner agent | edit rule. Derived from project type + frameworks. Always covers: source dirs, tests, docs, infra, agent files, generated artifacts.
- Agent Roster — table of
name | role | owns | triggers | model (optional) | parallel-safe | wave. Use topology guide. Compute parallel-safety per parallelism: a subagent is parallel-safe iff its owns glob doesn't overlap any other's, it doesn't write outside owns, and it doesn't depend on another subagent's output in the same wave.
- Capability Matrix — capabilities × agents grid (✅ / 🟡).
- Wave plan — grouped list
Wave N → [parallel-safe subagents]; the orchestrator fans out per wave and awaits each before the next.
- Requirements triage — status (
separate | merged | skipped), intake brief, ambiguities, question_request count, risk flags, and recommended first-wave routing.
- Content quality — curator status (
separate | merged | skipped), review scope, expected signals, and output marker from content quality.
- Security team operating model — for
dedicated|expanded, include roles, authorization scope, evidence contract, read-mostly defaults, and gates from security team.
- Build Gate (SDLC) — for software-dev with strictness !=
skipped, include diff bucket rule (max(size_bucket, criticality_bucket)), gate matrix, evidence schema, and the build-runner / change-bug-hunter / change-validator roles (merge change-validator into @reviewer for light). Render n/a rationale otherwise. Use sdlc-build-gate. Code Quality & Maintainability — for software-dev, also include code_quality_strictness, Rule 0 (conform to existing conventions first) + the authoring standards, and the read-only code-quality-reviewer role (merge into @reviewer for light/advisory/tiny). Use code-quality.
- Plan Handoff Contract — accepted planning sources, HandoffIR fields, per-platform format targets, approval boundaries, and verification evidence. Use handoff.
- Prompt assignment quality — recommended handoff strictness, Orchestrator Assignment Format, Context Packet strategy, allowed capabilities, skills referenced, and expected
Task assignment quality marker from prompt guidelines.
- Self-update preflight — status, source path or provider manager, fast-forward evidence, and any
question_request from self-update preflight.
- Human Input protocol — selected runtime matrix, native question tool or fallback, allowlist/config syntax, and unresolved
question_request records from human input.
- Skills to create.
- Plugin/MCP candidates per capability (Phase 3 fills this).
- Per-platform file plan (Copilot/Claude/OpenCode/Codex/Gemini paths the user will actually get).
- Artifact tracking —
project-tracked | project-local | personal-global, plus exclude plan for local-only mode.
- Memory & Learning plan — native-vs-plugin-managed memory choice, storage profile, memory owner, curated memory path, operational ledger path (if any), Learning Check strength, overwrite approval policy, and Directory Architecture rows for memory paths.
- Git actions (if any).
- Output profile & context budget —
balanced|compact|full, sections kept inline, overflow targets, and biggest expected agent-memory file.
- Security & Audit Matrix — controls, owner agents, affected paths, evidence required, and source reference.
- Threat Model Summary — assets, trust boundaries, threats, mitigations, owners, and status.
- Architecture & Design Pattern Matrix — selected patterns, alternatives, rationale, risks/guardrails, and ADR refs.
- ADR plan — decisions that should become docs if the user approves docs writes.
- Quality Gates — build/test/lint/security/supply-chain/architecture evidence required before "done".
End the phase with ask_user: ["Proceed", "Edit plan first"].
Phase 3 — Marketplace Lookup with per-item Opt-in
For every capability the user named (e.g., "playwright", "azure", "postgres"):
- Search the marketplaces in tier order — see marketplaces. Tier 1 first; only fall through if it misses.
- Collect at most 3 candidates per capability. For each, populate mandatory rationale fields:
name, source_tier, repo_url, bundles (agents/skills/hooks/MCP/LSP), why_recommended, tradeoffs, install_command_per_platform. Empty rationale ⇒ drop the candidate.
- Render a comparison table to the user, then call
ask_user:
"For capability , which would you like?"
Choices: ["<candidate 1 — short label>", "<candidate 2>", "<candidate 3>", "Show more (Tier-3 fallback search)", "None — skip this capability"]
- Show more triggers Tier-3 search (capped at +5 additional candidates). Re-render table and re-prompt.
- Record the user's pick. Skipped capabilities never reach the MCP gate or final write.
See plugin discovery for the comparison-table format and rationale schema.
For security-team setups, security plugins or skills remain optional candidates.
Show vendor/license attribution and tradeoffs. Never clone proprietary plugin
workflow text into generated agents, and never auto-install scanners, MCP
servers, or disclosure tooling.
Phase 3.5 — MCP Config Approval Gate (mandatory, downstream of Phase 3)
If any user-selected candidate from Phase 3 includes an MCP server:
- Build the proposed config per platform:
- Copilot CLI →
.mcp.json (mcpServers key) and any approved agent-frontmatter mcp-servers:
- Claude Code →
.mcp.json (mcpServers key) and any approved project/user-agent mcpServers
- OpenCode → merge into
opencode.json (mcp key)
- OpenAI Codex →
.mcp.json plus any approved per-agent TOML [mcp_servers.<id>]
- Gemini CLI → approved per-agent
mcp_servers: blocks in .gemini/agents/*.md
- Render each proposed file/config block verbatim (full JSON/YAML/TOML as applicable).
- For central MCP config files (
.mcp.json and opencode.json with MCP
blocks), include concrete approval evidence with server names:
- Prefer a top-level
x-agents-system-setup object when the runtime schema
safely tolerates extension keys. Include mcp_approval.decision,
mcp_approval.servers, approved_by or approval_ref, and evidence.
- If extension keys are not schema-safe, write a sibling sidecar named
<config>.agents-system-setup.approval.json with the same metadata.
ask_user:
"I'm about to write the MCP configuration above to <paths>. Approve?"
Choices: ["Approve all (Recommended)", "Approve selectively (per-server)", "Skip MCP entirely"]
- If selective, loop per server:
["Include", "Skip"].
- If skip, strip every
mcp-servers: / mcpServers / mcp_servers: / TOML [mcp_servers.*] surface from generated agents and do not write .mcp.json / opencode.json mcp / extension MCP config.
- No MCP write may occur before this gate returns approval.
Phase 4 — Generate Artifacts (per platform, post-approval)
For each selected platform, look up paths and frontmatter in platforms.md, then render:
AGENTS.md at repo root → template. Fill Read First, Context Loading Policy, Instruction Memory Audit, Directory Architecture, Agent Roster, Capability Matrix, Plan Handoff Contract, Security & Audit Matrix, Threat Model, Architecture / Design Pattern Decisions, ADR Index, Quality Gates, Skills, Plugins/MCP tables. Use the selected output profile; summarize long sections and link overflow details.
GEMINI.md when Gemini CLI is selected → template. Keep it a compact pointer/sync copy that tells Gemini to load canonical AGENTS.md, preserves artifact tracking notes, and routes root-session fan-out because Gemini subagents cannot recursively delegate.
- Orchestrator — never emit as a subagent file (subagent files are for specialized roles only). The orchestrator role lives in
AGENTS.md › Orchestration Operating Model and is read by the host CLI session of any selected runtime. @orchestrator is a routing alias for that host session. OpenCode's permission.task subagent-gating moves to opencode.json › agent.<root>.permission.task. Improve / upgrade modes detect existing orchestrator subagent files and offer deletion/deprecation/manual-review choices via misplaced-artifacts-migration.
- Each subagent — use the platform-specific template and fill
{{OWNED_PATHS}} / {{READONLY_PATHS}} from the Directory Architecture:
- Copilot CLI → subagent.agent.md.template at
.github/agents/<name>.agent.md. Frontmatter: name, description, tools: list filled from the Standard Tool Profile per role (orchestrator + edit-capable subagents → [vscode, execute, read, agent, edit, search, todo]; reviewers/auditors → [read, search]; testers/release helpers → [execute, read, search, todo]; research/docs → [read, search, web, todo]; or omit when the user picked inherit), optional mcp-servers: (hyphenated key). .github/agents/<name>.md is recognized only as an upstream docs-drift/import signal, not the default emitter.
- Claude Code → subagent.claude.md.template at
.claude/agents/<name>.md. Frontmatter: name, description, optional tools: as comma-separated string (e.g. Read, Grep, Bash), optional disallowedTools:, permissionMode:, model:, etc. Do not use Copilot tool names or mcp-servers:.
- OpenCode → subagent.opencode.md.template at
.opencode/agents/<name>.md. Frontmatter: no name: (filename = agent name), description, mode: subagent, optional model: in provider/model-id format, optional permission: block. Do not embed mcp-servers: — MCP belongs in opencode.json.
- OpenAI Codex (CLI + App) → subagent.codex.toml.template at
.codex/agents/<kebab-name>.toml. Required fields: name, description, developer_instructions (TOML triple-quoted string). Carry the IR's tool_allowlist only if explicitly set (otherwise inherit from parent session). Map IR model → model and reasoning hints → model_reasoning_effort (low|medium|high). Set sandbox_mode = "read-only" for read-only subagents. Per-agent MCP servers go under [mcp_servers.<id>] in the same file. AGENTS.md keeps only the orchestrator section + Directory Architecture / Capability Matrix / Waves. See Codex layout and openai docs. CLI-only instructions such as /agent are usage notes, not requirements for App compatibility. Also emit/upsert .codex/config.toml with [agents] max_threads = 6 and max_depth = 1 unless the user supplied other values.
- Gemini CLI → subagent.gemini.md.template at
.gemini/agents/<kebab-name>.md. Required fields: name, description; emit kind: local; optional display_name, tools, mcp_servers, model, temperature, max_turns, timeout_mins. Use snake_case mcp_servers: only after Phase 3.5 approval. Gemini subagents cannot call other subagents, so cross-agent work returns to the orchestrator/root session.
- Each skill → template at the platform's skills path: Copilot →
.github/skills/<name>/SKILL.md; Claude → .claude/skills/<name>/SKILL.md; OpenCode → .opencode/skills/<name>/SKILL.md; Codex → .codex/skills/<name>/SKILL.md (project) or ~/.codex/skills/<name>/SKILL.md (user); Gemini → .gemini/skills/<name>/SKILL.md. Never write skills (or any other runtime artifact) under .agents-system-setup/; existing misroutes go through misplaced-artifacts-migration.
task-handoff skill — emit task-handoff template at every selected runtime's skills path (Codex included). The host CLI session loads it before composing delegation packets and passes Skills Referenced: task-handoff loaded=true. Subagent templates keep an inline fail-closed Acceptance Checklist + Reporting Template; subagents never re-delegate through this skill.
- Build Gate (SDLC) emission — for software-dev projects with strictness !=
skipped, render {{BUILD_GATE_MATRIX}} from build-gate-matrix snippet into AGENTS.md › Build Gate (SDLC); emit code-change-build-gate template at every runtime's skills path (Codex included); add build-runner, change-bug-hunter, change-validator to the roster (merge change-validator into @reviewer when strictness=light). For non-software-dev or skipped, render Build Gate (SDLC): n/a — non-software project | user skipped and emit no Build Gate roles/skill. See sdlc-build-gate. Code Quality & Maintainability emission — whenever code_quality_strictness ∈ {standard|strict|light|advisory} (any project with source code, including a non-software-dev code-bearing repo → advisory), also emit the code-quality skill at every runtime's skills path (Codex included), render AGENTS.md › Code Quality & Maintainability from the code-quality-standards snippet, add the read-only code-quality-reviewer (merge into @reviewer for light/advisory/tiny), and have the host pass Skills Referenced: code-quality loaded=true on code-edit/bug-fix/refactor/code-review packets so edit-capable and reviewer subagents apply the conventions-first standards while writing. Render Code quality: n/a — non-software project only when there is no source code or the user opted out (skipped/n/a). See code-quality.
- MCP config (only if Phase 3.5 approved) at the platform's MCP path.
- Central MCP config files include the Phase 3.5 approval evidence either in top-level
x-agents-system-setup metadata or in <config>.agents-system-setup.approval.json; generated configs with server names and no evidence are invalid.
- Per-agent MCP blocks include an
agents-system-setup:mcp-approved marker from the Phase 3.5 decision; generated or improved agents with MCP blocks but no marker must be treated as unapproved until Phase 3.5 runs again.
- Resolve optional placeholders (
{{OPTIONAL_MCP_APPROVAL_MARKER}}, {{OPTIONAL_MCP_APPROVAL_COMMENT}}, {{OPTIONAL_PERMISSION_TASK_BLOCK}}) using the optional placeholder substitution table before writing runtime agent directories. Generated runtime agents must contain no literal {{OPTIONAL_...}}; templates may keep placeholders.
- Drop the directory-architecture snippet into any agent missing the boundary block.
- Orchestrator parallelism clause — render the wave-aware fan-out instructions per parallelism into
AGENTS.md › Orchestration Operating Model › Wave Execution. The host CLI session orchestrator must invoke all parallel-safe subagents of a wave in a single response (multiple Task-tool calls), await all results, then start the next wave.
- Plan handoff contract — render the HandoffIR fields and platform format targets per handoff. Agent files receive a concise handoff input/output section; Codex subagents receive it inside
developer_instructions.
- Orchestrator Assignment Format — render compact main-to-subagent assignment guidance per prompt guidelines. Orchestrators pass a subtask slice with scope, Context Packet, allowed capabilities, skills referenced, verification, expected output, and stop/escalation conditions for normal/risky work.
- Self-update preflight notes — render the Phase -1 status and approved provider update command, if any. Do not imply that MCP/plugin config changed unless the normal gated write path changed it.
- Human input protocol — render the provider-specific question behavior from human input. Copilot agents never include
ask_user in tools:; Claude restrictive allowlists include AskUserQuestion only for agents expected to ask; OpenCode uses nested permission: { question: allow }; Codex TOML has no human-input field and uses question_request; Gemini may allow ask_user for interactive agents.
- Requirements triage role — render
requirements-triage as a read-mostly subagent when Phase 1.11 is separate; otherwise render the merged/skipped rationale in AGENTS.md. Triage owns no source paths, returns question_request for missing input, and cannot write MCP/runtime config or release metadata.
- Content quality role — render
agent-quality-curator as a read-only subagent when Phase 1.12 is separate; otherwise render the merged/skipped rationale in AGENTS.md. The curator reviews generated agent, skill, memory, recommendation, and output-contract prose, reports content-quality signals, and must not write MCP/runtime config or release metadata.
- Security team operating model — for
dedicated|expanded, render {{SECURITY_TEAM_OPERATING_MODEL}}, selected roles, read-mostly defaults, and security evidence fields: authorization, validation, counterevidence, severity, remediation verification, and proof gaps.
- Governance baseline — render the security, audit, architecture, design-pattern, ADR, and quality-gate sections from Phase 1.8 / Phase 2. Subagents that touch sensitive paths, MCP/tool config, CI/release config, dependency manifests, or architecture boundaries must include explicit security boundaries and audit evidence expectations.
- Context optimization — apply context optimization: compact inline summaries, links for overflow details, concise delegation packets, no duplicated long policy prose across subagents, and profile-aware compact-mode trimming for Compact subagents (Security/Architecture/Output sections collapse to one line + link; section anchors stay so validators can find them). Codex TOML always follows the summary + pointer rule. Set
Context freshness: recent in delegation packets when AGENTS.md was loaded this turn.
- Layered context emission (v1.6.0+) — when
subagent_count >= 2 AND profile is Balanced/Full, render visible **Audience:** markers under every ## Section in AGENTS.md from audience-tags snippet, append the ## Subagent Self-Contained Notice block, and inline the project-standard digest from project-standard-digest snippet into every subagent template (managed block with v=<sha256-first-12> hash). Compact profile omits markers/notice; Codex variant uses the 3-line minimal digest + pointer to keep developer_instructions within the 65-line soft target.
- Native Runtime Agents block (v1.7.0+) — when
subagent_count >= 2, render {{HOST_BUILTINS_ROUTING_BLOCK}} from host-builtins-routing snippet as subsection ### Native Runtime Agents under ## Orchestration Operating Model in AGENTS.md, with anchor <!-- agents-system-setup:host-builtins-routing -->. Balanced/Full emit the full per-runtime table; Compact emits a 1-line summary + reference link. For OpenCode targets, also extend permission.task with explore and general allows (or record host_builtins_routing: declined). Subagent templates receive no delegation hints — built-in routing is orchestrator-side only (hard rule #36). See host-builtins-routing.
- Tool catalog stamp & emit-time validation (v1.8.0+) — emit
<!-- agents-system-setup:tool-catalog-version: {{PLUGIN_VERSION}} --> in AGENTS.md and every generated agent immediately after the generated-by stamp. At emit time, consult tool-catalog for each runtime's tools: / tool_allowlist / permission: content; default-deny scope: cli-only and scope: vscode-only tools in shared .github/agents/*.agent.md files (opt-in must be recorded in the output contract). Emit the tool-catalog-audit skill at every selected runtime's skills path (Codex included) — host-side read-only audit. Do NOT add tool-catalog hints to subagent templates (hard rule #36).
agents-doctor health check (v1.9.0+) — emit the agents-doctor skill at every selected runtime's skills path (Codex included) and render the read-only engine agents-doctor.py.template to .agents-system-setup/agents-doctor.py (substitute {{PLUGIN_VERSION}} / {{GENERATED_AT}}). Record both in .agents-system-setup/generated.json (kind: skill and kind: other) so the doctor never flags its own files. Host-side read-only; subagents never invoke it (hard rule #36). It reconciles on-disk agents against the manifest and flags stray-agent / orchestrator-subagent-file / missing-artifact / checksum-drift. See agents-doctor.
- Memory & Learning System — render the chosen profile from learning memory:
AGENTS.md gets the native-vs-plugin-managed memory note, orchestrators get Reflect & Learn, subagents get Learning Check, and optional assets/learnings.md.template is emitted only when the memory profile needs a curated Markdown file. Sensitive new learnings require orchestrator and security-owner approval when tagged risk or when they mention MCP, CI/release, dependencies, secrets, or generated scripts. Do not write native memory config, hooks, or scripts unless separately approved.
- OpenCode root-session task gate — for OpenCode targets, render
permission.task in opencode.json (under the host root agent, e.g. agent.build.permission.task) with "*": deny plus explicit roster-agent allows. This replaces the deleted orchestrator.opencode.md permission.task frontmatter; the host root session is the orchestrator. Treat this as a separate config approval gate (not the MCP gate): always propose the snippet when OpenCode is selected; if the user declines, record opencode_task_gate: declined and report OpenCode task gate not installed; fan-out not permission-constrained in the output contract. Broaden allows only when the plan says why.
- OpenCode root-session skill gate — when emitting host-loaded skills like
task-handoff (and code-change-build-gate plus code-quality for code-bearing projects) for an OpenCode target, also render permission.skill in opencode.json (under the same host root agent, e.g. agent.build.permission.skill) with "*": ask plus explicit allow entries for the emitted skills. OpenCode skill loading is gated by permission.skill; without an allow entry the host cannot load task-handoff and the Skills Referenced: task-handoff loaded=true packet evidence is false. Treat this as a separate config approval gate parallel to permission.task; if the user declines, record opencode_skill_gate: declined, emit subagent templates with the full inline Acceptance Checklist + Reporting Template (no pointer-only optimization), and report OpenCode skill gate not installed; subagents use inline fail-closed minimum only in the output contract.
- Artifact tracking — apply local tracking. In
project-local mode, update .git/info/exclude after writes and verify at least AGENTS.md with git check-ignore -v.
- Spec-Kit block — if Phase 1.7 recorded
spec_kit_installed = true, render assets/spec-kit-block.snippet.md into the {{SPEC_KIT_BLOCK}} placeholder of AGENTS.md (substituting {{RUNTIME}} per platform: copilot|claude|codex|opencode|gemini). If false, replace the placeholder with an empty string. See spec-kit.
- Claude Code AGENT-TEAMS.md — when Claude Code is among the selected platforms AND the Agent Roster has 3+ subagents marked
team-suitable (independent + benefits from peer challenge), emit AGENT-TEAMS.md documenting: opt-in env var (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1), settings.json snippet, suggested teammate roster, token-cost warning, and when to fall back to parallel subagents.
Project-memory linking (after AGENTS.md is written):
- If both Claude Code and another platform are selected → pick by detected OS (see cross-platform):
- macOS / Linux / WSL:
bash ./scripts/link-project-memory.sh → symlinks CLAUDE.md → AGENTS.md.
- Windows native:
pwsh -File ./scripts/link-project-memory.ps1 → tries symlink (Developer Mode/admin), falls back to copy with regenerable header (re-runs keep them in sync).
- OpenCode reads
AGENTS.md natively — no linking required.
- Gemini CLI uses
GEMINI.md as its native context file; when Gemini is selected, keep GEMINI.md a compact pointer/sync copy of canonical AGENTS.md (same OS-specific symlink/copy caution as Claude).
Frontmatter rules (silent-failure traps):
- Formats with a
name field (Copilot CLI, Claude Code, Gemini CLI, Codex TOML) MUST match filename basename (kebab-case); OpenCode Markdown agents MUST omit name: because the filename is the agent name.
- Quote any
description containing colons.
- Subagent
description MUST start with "Use when...".
- Use the right frontmatter schema per platform (see platforms.md — Copilot uses
mcp-servers: and public tool aliases (vscode, execute, read, edit, search, agent, web, todo), Claude uses comma-string tools:, OpenCode uses mode: plus permission:, Codex subagents use .toml, and Gemini uses kind: local plus mcp_servers:).
- Restrict tools per subagent to the minimum needed. For Copilot CLI, apply the Phase 4 Role → Profile mapping from Copilot CLI Standard Tool Profiles (Q9c override wins; default
Standard).
- The
model: line is optional in every platform — emit only if the user specified an override. When users opt in to overrides during interview Q9b, load models for the runtime's accepted format, defaults, and rate-limit sources; never pin live RPM/TPM numbers in generated files.
Phase 5 — Update Mode (non-destructive)
For every existing target file: backup .bak first, parse frontmatter to preserve user-authored sections, merge new content under <!-- agents-system-setup:managed:start --> … <!-- agents-system-setup:managed:end --> markers (replace the block, never duplicate), update .git/info/exclude for project-local artifacts (verify with git check-ignore -v), and print a diff summary at the end.
Phase 6 — Optional Git Init
Only if user confirmed in Phase 1 AND no .git/ exists. Pick the script that matches the host OS — see cross-platform. The bundled scripts initialize main, write .gitignore and .gitattributes, stage, and commit.
Phase 7 — Verify & Summarize
- List every file created/modified with absolute paths, grouped by platform.
- Re-read each generated agent/skill: confirm
name matches filename for formats with a name field (Copilot, Claude Code, Gemini CLI, Codex TOML), no name: key in OpenCode files (filename is the name), description present and starts with "Use when...", no unquoted colons, frontmatter parses for the target platform's schema. Confirm Claude Code tools: is a comma-separated string — not a YAML list. Confirm OpenCode files have no mcp-servers: key. Confirm Gemini files use mcp_servers: (not mcpServers) and do not instruct subagents to call subagents. Confirm no agent: Plan frontmatter was copied into any generated file.
- Verify
AGENTS.md contains non-empty Directory Architecture, Agent Roster, Capability Matrix.
- Verify
AGENTS.md contains non-empty Security & Audit Matrix, Threat Model, Architecture / Design Pattern Decisions, ADR Index, and Quality Gates. If a concern is not applicable, it must still have an explicit n/a rationale.
- Verify security-sensitive files (
.mcp.json, opencode.json, .env*, CI/release config, lockfiles, generated scripts) have an owner and evidence requirement in the governance sections.
- Verify
AGENTS.md contains Plan Handoff Contract, Context Loading Policy, Instruction Memory Audit, Task-Type Routing Map rows, and the selected output profile.
- Verify
AGENTS.md contains Memory & Learning System, the chosen memory profile, and the rule that overwrite requires orchestrator approval. Confirm every orchestrator includes Reflect & Learn and every subagent/Codex TOML includes Learning Check with the no-secrets rule.
- Verify every generated agent/subagent uses its target runtime's native handoff surface: Markdown body for Copilot/Claude/OpenCode/Gemini, TOML
developer_instructions for Codex. Confirm each subagent template includes the Assignment Intake / Preflight, Acceptance Checklist, Reporting Template, and Task assignment quality marker; Codex TOML mirrors them inside developer_instructions. For Copilot CLI agents, confirm the tools: line matches the role's profile from Copilot CLI Standard Tool Profiles: orchestrator + edit-capable subagents emit [vscode, execute, read, agent, edit, search, todo]; reviewers/auditors emit [read, search]; the marker <!-- agents-system-setup:tools-profile: <profile> --> records the chosen profile.
- Verify self-update preflight: the output records checked/current/fast-forwarded/requires-human/skipped status, and no MCP/plugin/runtime config changed outside the normal approval gates.
- Verify human-input protocol: no Copilot
tools: profile contains ask_user; Claude restrictive ask-capable agents include AskUserQuestion; OpenCode uses nested permission with question; Codex TOML has no request_user_input or memory field; Gemini interactive ask-capable agents may include ask_user; subagents document question_request fallback.
- Verify content quality:
AGENTS.md records agent-quality-curator status, generated subagents report Content quality, and final output includes content-quality status/signals.
- Verify artifact tracking: project-tracked files are visible to git; project-local files are ignored via
.git/info/exclude; personal-global mode wrote no repo artifacts unless approved. Confirm no agents/skills/hooks/commands/prompts/plugins live under .agents-system-setup/ — any detection from Phase 1 must have a migration.jsonl entry.
- Print "Try it" examples per selected platform (
copilot, claude, opencode, codex, gemini).
- Suggest 2–3 next customizations.
- Verify Build Gate (SDLC): for software-dev with strictness !=
skipped, AGENTS.md › Build Gate (SDLC) contains the matrix snippet, code-change-build-gate skill exists at every selected runtime's skills path (Codex included), and the roster includes build-runner, change-bug-hunter, and change-validator (or change-validator merged into reviewer for light). For non-software-dev or skipped, the section has an n/a rationale. Verify Code Quality & Maintainability: AGENTS.md › Code Quality & Maintainability is present (or Code quality: n/a — non-software project), the code-quality skill exists at each selected runtime's skills path (Codex included), the roster includes code-quality-reviewer (or merged into @reviewer), and edit-capable/reviewer subagent templates carry the Code quality: marker.
- Verify
task-handoff skill exists at every selected runtime's skills path (Codex included). AGENTS.md › Orchestration Operating Model instructs the host to load it and pass Skills Referenced: task-handoff loaded=true. Subagent templates retain the fail-closed inline guard and never re-delegate through the skill.
- Verify Layered context & Self-containment (#37): when
subagent_count >= 2 AND profile is Balanced/Full, AGENTS.md ## Section headings carry visible **Audience:** markers and the ## Subagent Self-Contained Notice block is present; every subagent file contains the <!-- subagent-digest:managed:start v=<hash> --> ... :end --> block with the 5 required digest lines (or 3 for Codex). Compact profile and single-agent setups omit markers/notice. Digest hash mismatch reports WARNING, not ERROR.
- Verify Native Runtime Agents routing (#38): when
subagent_count >= 2, AGENTS.md contains the <!-- agents-system-setup:host-builtins-routing --> anchor and ### Native Runtime Agents subsection under ## Orchestration Operating Model; Balanced/Full include the per-runtime table; Compact includes the 1-line summary + reference link; subagent files contain NO delegation hint to native built-ins (orchestrator-side only). For OpenCode targets, either opencode.json permission.task allows explore and general, or the output contract records host_builtins_routing: declined.
- Verify Tool catalog discipline (#39): every generated agent and
AGENTS.md carries the <!-- agents-system-setup:tool-catalog-version: <plugin-version> --> stamp marker; every tools: / tool_allowlist entry exists in the runtime's catalog block from assets/tool-catalog.json; OpenCode files have no deprecated tools: key (use permission:); no scope: cli-only / scope: vscode-only tools in shared .github/agents/*.agent.md unless explicitly opted in (recorded in the output contract). The tool-catalog-audit skill template exists at every selected runtime's skills path (Codex included).
- Verify the
agents-doctor health check (v1.9.0+): the agents-doctor skill exists at every selected runtime's skills path (Codex included) and the read-only engine is emitted to .agents-system-setup/agents-doctor.py; both carry the generated-by stamp and appear in .agents-system-setup/generated.json. Run python3 .agents-system-setup/agents-doctor.py and confirm it reconciles clean (no stray-agent / orchestrator-subagent-file / missing-artifact errors) for the just-generated system.
Phase 8 — Final Wrap-Up (single consolidated ask)
Run after Phase 7, before exiting. Present one compact multi-select menu from wrap-up, filtered by domain/plugins/MCP/platform signals. Never show installed items; never ask one item at a time. Re-confirm only if an action edits config outside AGENTS.md. Skip the entire phase only when mode == update and no agents/plugins/MCP changed.
Anti-patterns
- Approval-gate skips. Never write files before showing the plan; never write MCP config without explicit
ask_user approval; never bulk-apply recommendations without per-item rationale + choice.
- Agent identity & naming hygiene. Don't mix platform frontmatters (e.g., Copilot keys in a Claude agent file); don't write generic descriptions ("helps with code") that kill discovery; don't invent plugin/skill/MCP names — always cite
[Tier · Vendor] from marketplaces.
- Pairwise replication code (Copilot→Claude function, Claude→OpenCode function, …) — always go through the Canonical IR.
- Replication / update safety lapses. Don't replicate without re-triggering the MCP approval gate for the new target(s); don't overwrite existing
AGENTS.md / opencode.json without .bak.
- Cross-OS slips on generated files — never symlink
CLAUDE.md on Windows (use the .ps1 fallback-copy path); always use forward slashes in generated Markdown paths; always bundle .gitattributes so *.sh files keep LF on Windows checkouts (CRLF breaks execution).
- Topology violations. Don't ship a single monolithic agent (violates orchestrator + subagent rule); don't ship a sequential-only orchestrator — must fan out parallel-safe subagents (see parallelism).
- Mishandling Codex/Gemini subagent contracts. Codex subagents live at
.codex/agents/<name>.toml and MUST have name, description, and developer_instructions (missing any = silent skip on load); reserve ## <Name> headings in AGENTS.md for orchestrator + project rules. Gemini local subagents at .gemini/agents/*.md cannot recursively delegate (fan-out routes through the parent session) and must use loader-valid mcp_servers: (snake_case), not the docs-spelled mcpServers. Both still pass the MCP approval gate. See openai docs.
- Wrap-up hygiene failures. Skipping Phase 8 denies users the curated add-on menu; the wrap-up must be a single multi-select prompt (not per-item round-robin); only cite vendor-official docs or the catalogs listed in wrap-up.
- Wrong directory for operational logs / runtime artifacts. Operational logs (replication, migration, MCP approval evidence) belong in
.agents-system-setup/*.jsonl — never .md and never inside any agents/ tree (the runtime loader parses them as malformed agents). Writing runtime artifacts under .agents-system-setup/ (agents, skills, hooks, commands, prompts, plugins) is silently inert; use per-platform paths from Phase 4. See replication and misplaced-artifacts-migration.
- Running deep recon before knowing user purpose — anchors the interview on what the directory looks like instead of what the user wants. Phase 0 sub-step 0 captures
headline_purpose first; Phase 1 recon scores against that intent. See hard rule #32 and cwd-reconnaissance.
- Emitting an
orchestrator subagent file — @orchestrator is the host CLI session reading AGENTS.md, not a runtime artifact. A delegated orchestrator subagent often does the work itself instead of fanning out to specialists (subagent runtimes give it the same broad toolset). Codex CLI has never emitted an orchestrator TOML; v1.3.0 normalizes Copilot/Claude/OpenCode/Gemini to that pattern and moves OpenCode permission.task to opencode.json. See hard rule #33 and misplaced-artifacts-migration.
- Governance treated as optional. Security/architecture baselines are part of planning and generation (not a wrap-up postscript); every architecture/design-pattern decision needs alternatives, guardrails, and an ADR reference (or
n/a rationale); security review is read-mostly unless the plan grants tightly scoped remediation paths.
- Content-quality and artifact-tracking slips. Content-quality review must remove generic/unsupported/repetitive prose, keep generated subagent prose lean (no long quality rules pasted everywhere), and link moved overflow detail from
AGENTS.md or the output contract; always ask the tracking mode before writing project files; local-only project agents go in .git/info/exclude, never .gitignore.
- Frontmatter-schema confusion. Don't copy VS Code
plan prompt frontmatter (agent: Plan) into agent files — normalize to HandoffIR, then emit per-platform; don't put human-input tools in the wrong schema (no Copilot ask_user in custom-agent tools:, no literal OpenCode permission.question, no Codex TOML request_user_input, no unsupported memory fields).
- Silent self-updates that change config — Phase -1 may fast-forward the skill checkout only; plugin/MCP/runtime config changes still need their normal approval gates.
Output Contract
Use output-contract. Always include Update preflight, Human input, Context profile, Context split, and largest memory file. For Compact and Balanced, lead with counts, changed paths, security/architecture evidence, and "Try it" commands; expand full lists only for failures, warnings, or explicit user requests.