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 and targeted upgrades (improve)
- 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. 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 mode is evidence-based. Existing systems are scored for security boundaries, secrets, audit evidence, architecture ownership, design-pattern consistency, and supply-chain source trust before any delta is applied.
- 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 optional and source-backed. Keep
model: blank by default. Only when the user opts in 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.
- 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.
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 platforms and 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.
- 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)", "Update (regenerate managed blocks)", "Replicate to another runtime", "Init alongside (additive)"] |
| One runtime, gaps |
update |
["Update (Recommended)", "Improve (audit + targeted fixes)", "Replicate to another runtime"] |
| Two+ runtimes |
improve |
["Improve current setup (Recommended)", "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 / Replicate branch
If the user picked improve → run the improve procedure (audit → score → propose deltas → opt-in apply). Misplaced artifacts detected in Phase 1 are first-class deltas in this audit; surface them through misplaced-artifacts-migration before any Phase 5 write. Skip Phases 2–4; jump to Phase 5 mechanics for backups + write.
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.
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.
- 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, 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 from Phase 1.9; summarize long sections and link overflow details instead of dumping exhaustive prose inline.
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 (Role, Hard Rules, Context Load Order, Lifecycle, Orchestrator Assignment Format, Wave Execution, Memory & Learning, Subagent Routing, Out of Scope) and is read by the host CLI session of any selected runtime — Copilot CLI, Claude Code, OpenCode, OpenAI Codex (CLI + App), and Gemini CLI. @orchestrator is a routing alias for that host session. OpenCode's permission.task subagent-gating moves to opencode.json › agent.<root>.permission.task (or equivalent host config) since no orchestrator markdown is emitted; see platforms and agent-format. Improve mode detects existing orchestrator subagent files and offers 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 s
…(truncated)
1---2name: ytthuan-agents-system-setup-agents-system-setup3description: Setup Copilot Agents (multi-platform)4---56# Setup Copilot Agents (multi-platform)78Scaffold 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.910## When to Use1112- Brand-new repository needs an agent setup from scratch (**init**)13- Existing project should adopt or extend the orchestrator + subagent pattern (**update**)14- Existing agent system needs an audit and targeted upgrades (**improve**)15- Agents authored for one runtime need to be ported to another (**replicate** — Copilot ↔ Claude Code ↔ OpenCode ↔ OpenAI Codex ↔ Gemini)16- Discovering relevant plugins / MCP servers from the well-known marketplaces1718## Hard Rules19201. **Always interview first** with the provider-native human-input tool. Use [human input](./references/human-input.md); 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.212. **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`.223. **Orchestrator + subagent topology is mandatory.** Subagent count (3 to ~50) is decided dynamically from scope.234. **Directory Architecture is generated and enforced.** Every subagent file references it; the orchestrator routes by ownership.245. **Per-item opt-in recommendations.** Plugin / skill / MCP candidates are always presented with rationale and explicit `ask_user` choice — never bulk-applied silently.256. **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.267. **Marketplace-first lookup with vendor attribution.** Recommendations come from registries listed in [marketplaces](./references/marketplaces.md), tagged `[Tier · Vendor]` — never invent names or URLs.278. **Replication goes through Canonical IR, not pairwise mappings.** See [replication](./references/replication.md). Never write a Copilot→Claude (or any other direction) function; always parse → IR → emit.289. **Non-destructive updates.** `cp <file> <file>.bak` before any edit; merge into managed blocks, preserve user-authored content.2910. **Multi-platform aware.** Emit per-platform paths and frontmatter per [platforms](./references/platforms.md). Never write Copilot frontmatter into a Claude file.3011. **Cross-OS aware.** Detect host OS once (Linux / macOS / Windows-bash / Windows-pwsh) per [cross-platform](./references/cross-platform.md). 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.3112. **Git is optional and gated by `ask_user`.**3213. **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](./references/parallelism.md). Sequential-only topologies are an error.3314. **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](./references/spec-kit.md).3415. **Security, audit, architecture, and design-pattern governance are mandatory.** Every plan and generated `AGENTS.md` must include the baseline from [security-audit-architecture](./references/security-audit-architecture.md): Security & Audit Matrix, Threat Model, Architecture / Design Pattern Matrix, ADR plan, and Quality Gates. Small projects may merge roles, but not omit the concerns.3516. **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.3617. **Improve mode is evidence-based.** Existing systems are scored for security boundaries, secrets, audit evidence, architecture ownership, design-pattern consistency, and supply-chain source trust before any delta is applied.3718. **Context budget is a feature.** Default to the `Balanced` output profile from [context optimization](./references/context-optimization.md): keep routing and gates inline, move deep detail behind explicit references, and never duplicate long policy prose in every agent.3819. **Ask whether agent artifacts are git-tracked or local-only.** Before writing project-scoped agent files, ask the tracking question from [local tracking](./references/local-tracking.md). For local-only project files, write `.git/info/exclude` (never `.gitignore`) and verify with `git check-ignore`.3920. **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](./references/handoff.md) / HandoffIR, then emit each selected runtime's native format. Never copy prompt frontmatter or another runtime's agent schema into generated artifacts.4021. **Runtime drift is source-backed and gated.** Use [runtime updates](./references/runtime-updates.md) before changing platform support. Gemini CLI is supported for local project subagents; remote A2A/extension packaging surfaces remain explicit import/package work.4122. **Model overrides are optional and source-backed.** Keep `model:` blank by default. Only when the user opts in during interview Q9b, load [models](./references/models.md) for the runtime's accepted format, defaults, and rate-limit sources. Never pin live RPM/TPM numbers in generated files.4223. **Task assignments use the canonical contract.** Compose every orchestrator → subagent handoff with the [Task Assignment Contract](./references/handoff.md#delegation-packet-canonical-schema). Always fill the Required Minimum; add Expansion Blocks per the [Recommended Packet Form](./references/handoff.md#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.4324. **Learning memory is approval-safe and native-aware.** When enabled, generated agents run the [Learning Check](./references/learning-memory.md#learning-check-contract) 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`.4425. **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.4526. **Run self-update preflight before setup.** Phase -1 uses [self-update preflight](./references/self-update-preflight.md) 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.4627. **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.4728. **Content quality is universal.** Apply [content quality](./references/content-quality.md) 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`.4829. **Main-to-subagent handoff is structured.** Use the [handoff contract](./references/handoff.md) and [prompt guidelines](./references/prompt-guidelines.md) 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.4930. **Dedicated security teams are explicit.** Generate the [security team](./references/security-team.md) 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.5031. **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](./references/misplaced-artifacts-migration.md).5132. **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](./references/cwd-reconnaissance.md#purpose-aware-scoring).5233. **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.5354## Procedure5556### Phase -1 — Self-Update Preflight5758Before footprint detection, run the safe preflight from59[self-update-preflight](./references/self-update-preflight.md):60611. Locate `${AGENTS_SYSTEM_SETUP_HOME:-$HOME/github/agents-system-setup}`.622. If it is a clean Git checkout with an upstream, `git fetch` and63 `git merge --ff-only` when only behind.643. If the checkout is missing, dirty, ahead, divergent, lacks upstream, or the65 install owner is ambiguous, ask with the provider-native human-input tool66 from [human input](./references/human-input.md). If interaction is disabled,67 emit `question_request` and continue with the installed version.684. Do not edit MCP config, plugin config, runtime settings, generated agents, or69 version/release files during this phase.7071Record `update_preflight_status`, source path/manager, and evidence for Phase 272and the final output contract.7374### Phase 0 — Capture Purpose, Detect Footprint, Choose Mode7576**Sub-step 0 — Capture headline purpose first.** Before any directory77scan or mode choice, ask the user's intent with the provider-native78human-input tool:7980> "In one sentence, what are you trying to achieve with an agent system here?"81> Freeform; offer `"I'm exploring — let recon lead"` as a labeled choice.8283Persist `headline_purpose: string | "exploring"`. This drives Phase 184purpose-aware recon scoring — see85[cwd-reconnaissance](./references/cwd-reconnaissance.md#purpose-aware-scoring).86When `exploring`, defer the purpose ask until after the recon card.8788**Sub-step 1 — Detect footprint.** Inspect cwd for project and agent89artifacts per Phase 1 step 1; do not run deep recon yet.9091**Sub-step 2 — Show profile card and ask mode.** Display the captured92`headline_purpose`, detected project type, existing agent artifacts by93runtime, recommended mode, and inferred current runtime(s):9495> "I detected `<footprint>`. How should I proceed?"96> Choices: `["Improve current setup (Recommended when artifacts exist)", "Init new setup", "Replicate / sync to another runtime", "Update managed blocks", "Cancel"]`9798Persist the selected mode. Do **not** ask target runtimes before this mode99choice. After mode is known:100101- `init` / `update`: ask which runtime(s) to generate unless the user's request already names them.102- `improve`: default scope to detected runtime(s); ask a target runtime only if updating one runtime or expanding audit scope requires it.103- `replicate` / `sync`: defer source and target runtime questions to Phase 1.5, and ask targets only for the requested expansion/sync.104105All later phases loop over the selected or detected runtime scope using [platforms.md](./references/platforms.md) as the source of truth for paths and frontmatter.106107Gemini CLI emits local subagents at `.gemini/agents/*.md`. See [platforms](./references/platforms.md) and [agent format](./references/agent-format.md) for its non-recursive subagent and `mcp_servers:` rules.108109### Phase 1 — Footprint Details & Interview Continuation1101111. **Inspect cwd** and detect runtime footprint:112 - Project files: `package.json`, `*.csproj`, `Package.swift`, `build.gradle`, `pyproject.toml`, `go.mod`, `Cargo.toml`, `mkdocs.yml`, `.git/`.113 - Agent artifacts (per runtime):114 - Copilot CLI: `AGENTS.md`, `.github/agents/*.agent.md`, `.github/agents/*.md` (docs-drift import signal), `.github/skills/`, `.mcp.json`115 - Claude Code: `CLAUDE.md`, `.claude/agents/`, `.claude/skills/`, `.claude/settings.json`116 - OpenCode: `opencode.json`, `.opencode/agents/`, `.opencode/skills/`117 - 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 separately118 - Gemini CLI: `GEMINI.md`, `.gemini/agents/*.md`, `.gemini/settings.json`, `~/.gemini/GEMINI.md`, `~/.gemini/agents/`119 - **Project recon**: run the safe-readonly cwd reconnaissance from [cwd-reconnaissance](./references/cwd-reconnaissance.md) **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.120 - **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](./references/misplaced-artifacts-migration.md).1212. **Confirm the Phase 0 mode** — do not re-ask target runtimes before the mode122 choice. Use this table only to pick the recommended mode/default choices shown123 in the Phase 0 profile card, or to re-prompt if the initial detection was124 ambiguous:125126 | Detected footprint | Default offer | Choices |127 |---|---|---|128 | Nothing | `init` | `["Init (Recommended)", "Cancel"]` |129 | One runtime, looks healthy | `improve` | `["Improve current setup (Recommended)", "Update (regenerate managed blocks)", "Replicate to another runtime", "Init alongside (additive)"]` |130 | One runtime, gaps | `update` | `["Update (Recommended)", "Improve (audit + targeted fixes)", "Replicate to another runtime"]` |131 | Two+ runtimes | `improve` | `["Improve current setup (Recommended)", "Replicate / sync between runtimes", "Update one runtime"]` |1321333. Continue the interview — see [interview script](./references/interview.md). 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.134135### Phase 1.5 — Improve / Replicate branch136137If the user picked **improve** → run the [improve procedure](./references/replication.md#4-improve-mode-audit--targeted-upgrade) (audit → score → propose deltas → opt-in apply). Misplaced artifacts detected in Phase 1 are first-class deltas in this audit; surface them through [misplaced-artifacts-migration](./references/misplaced-artifacts-migration.md) before any Phase 5 write. Skip Phases 2–4; jump to Phase 5 mechanics for backups + write.138139If the user picked **replicate** → run the [replication procedure](./references/replication.md#3-replication-procedure):1401. `ask_user` for **source** runtime (single-select among detected).1412. `ask_user` for **target** runtimes (multi-select; source excluded).1423. Parse source → AgentIR / SkillIR / MCPServerIR records.1434. Render lossiness report; `ask_user` to approve dropped fields per target.1445. Run **Phase 1.6** before any target write.1456. Re-run **Phase 3.5** MCP approval gate against each new target.1467. Emit per target with `<!-- agents-system-setup:replicated-from: <source> -->` markers.1478. 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).1489. Verify round-trip (re-parse emitted → diff IR → surface drift).149150For **improve**, run Phase 1.6 before applying any selected delta. For both branches, finish with Phase 7 (verify & summarize).151152### Phase 1.6 — Artifact Scope & Tracking153154Run before Phase 1.7 for init/update, and before Phase 5 writes for improve/replicate. Use [local tracking](./references/local-tracking.md).155156Ask:157158> "Should the generated agent system be shared through git or kept local to this checkout?"159> Choices: `["Project files, git-tracked (Recommended for teams)", "Project files, local-only / untracked (Recommended for personal setup)", "Personal/global outside this repo"]`160161Record `artifact_tracking` as `project-tracked | project-local | personal-global`.162163Rules:164- `project-tracked`: use project paths; do not commit unless Phase 6 git actions are explicitly approved.165- `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.166- `personal-global`: use runtime user paths and avoid repo writes unless separately approved.167168### Phase 1.7 — Domain Detection & Spec-Kit Recommendation169170Run after Phase 1 (and 1.5 if branched), before Phase 2. Inspect the project brief gathered during interview against this software-development keyword set:171172`app, application, api, service, microservice, library, sdk, cli, tool, devtool,173backend, frontend, fullstack, web, mobile, ios, android, desktop,174framework, plugin, extension, package, module,175infrastructure, infra, terraform, pulumi, kubernetes, helm,176compiler, parser, runtime, database, orm`.177178If **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).179180If `software-dev`, call `ask_user`:181182> "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?"183> Choices: `["Yes — install for this runtime (Recommended)", "Just print the install command", "No, skip"]`184185On approval, emit the runtime-matched command from [spec-kit](./references/spec-kit.md) (`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".186187Record the choice in the plan so Phase 4 orchestrator output can reference the `/specify` workflow when appropriate.188189### Phase 1.8 — Security, Audit, Architecture Intake190191Run after domain detection and before Phase 2. Use [security-audit-architecture](./references/security-audit-architecture.md) as the source of truth.192193Ask only questions not already answered by detection. Data sensitivity, auth194boundary, and external tools/MCP usage are mandatory. Infer audit evidence,195architecture style, critical qualities, and anti-pattern defaults into the plan196for low-risk projects unless the user asks to configure them explicitly.1971981. Data sensitivity.1992. Auth boundary.2003. External tools / MCP usage.2014. Audit evidence expectations.2025. Deployment / release risk.2036. Architecture style.2047. Critical quality attributes.2058. Known design anti-patterns to avoid.206207Record 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.208209### Phase 1.8a — Security Team Scope210211Run only for dedicated security team / bug-hunting setups; use [security team](./references/security-team.md). 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`.212213### Phase 1.9 — Output Profile & Context Budget + Advanced Agent Behavior214215Run after Phase 1.8 and before Phase 2. Run the grouped216[interview Q9b Advanced agent behavior](./references/interview.md#9b-advanced-agent-behavior)217block explicitly; do not leave model or tool choices as prose-only plan notes.218Group agent-behavior choices together so the user compares tradeoffs once:219optional model overrides, Copilot CLI tool profile when Copilot is selected,220output profile, and Memory & Learning profile. This phase owns those prompts:221ask each advanced behavior choice exactly once and do not re-ask output profile222or memory profile in Phase 1.10. Use [context optimization](./references/context-optimization.md).223224Ask and record the Q9b choices before Phase 2:2252261. **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.2272. **Copilot CLI Tool Profile** — only when Copilot CLI is selected; persist `copilot_tools_profile`.2283. **Output profile / context budget** — `Balanced | Compact | Full`.2294. **Memory & Learning profile** — persist `learning_memory_profile`, `learning_gate_strength`, overwrite policy, and whether native provider memory is only documented or explicitly enabled.230231For Copilot CLI tools, keep prompt choices concise: Standard least-privilege by232role (recommended), Read-only everywhere, Inherit parent tools, or Custom after233generation. Render the full mapping in the plan/reference, not in the question.234235For the output profile choice, ask once:236237> "How much detail should generated agent files include?"238> Choices: `["Balanced (Recommended)", "Compact", "Full"]`239240Record:241242- `output_profile`: `balanced | compact | full`243- `inline_sections`: which sections stay in `AGENTS.md`244- `overflow_targets`: where long details should be written or proposed (for example `docs/agents/security-audit.md`)245- `context_budget_notes`: any user constraints on verbosity246247If 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.248249### Phase 1.10 — Memory & Learning Profile250251Do not call `ask_user` here. Use the Memory & Learning answer already collected252in the Phase 1.9/Q9b advanced-agent-behavior group. This phase normalizes the253recorded choice for planning and rendering. Use [learning memory](./references/learning-memory.md).254255Record:256- `learning_memory_profile`: `project-tracked | project-local | personal-global | disabled`257- `native_learning_surface`: runtime-native memory selected or `document-only | disabled`258- `learning_memory_owner`: `@memory-steward` when the roster includes one, otherwise `@orchestrator`259- `learning_memory_path`: path chosen from [learning memory](./references/learning-memory.md#storage-profiles)260- `learning_gate_strength`: `recommended` by default; do not make it blocking unless the user explicitly asks261- `learning_update_policy`: `overwrite requires orchestrator approval`262263Do not ask a separate blocking Learning Check question by default. Native memory264setup follows [learning memory](./references/learning-memory.md): Copilot Memory265is public-preview, transparent server-side durable repo memory, Claude has266`memory: user|project|local`, OpenCode relies on AGENTS/skills/compaction/plugin267patterns, Codex memories require `[features] memories = true`, and Gemini has268`save_memory`, `GEMINI.md`, `/memory`, and experimental `autoMemory`. Ask269optional hook/script support only when the runtime has a supported hook surface270and this setup has not already handled learning. Render the exact hook/config271proposal and ask before writing it.272273### Phase 1.11 — Requirements Triage274275Before Phase 2 planning, decide `requirements_triage_status`:276277- `separate` — generate `requirements-triage` as its own read-mostly subagent.278- `merged` — merge triage into `planner` for tiny direct setups.279- `skipped` — only when the task is direct, low-risk, single-runtime, and already280 has clear scope.281282Default to `separate` for ambiguous, multi-step, cross-runtime, security-sensitive,283release, MCP, replication, audit, improve, or multi-wave setups. The triage role284returns an intake brief with intent summary, task type, in/out scope, ambiguities,285`question_request` items, risk classification, recommended routing/waves,286acceptance criteria, quality gates, and Learning Check. The orchestrator owns the287final plan, all user-facing questions, and every approval gate.288289### Phase 1.12 — Content Quality Review290291Before Phase 2 planning, decide `content_quality_curator`:292293- `separate` — generate `agent-quality-curator` as its own read-only subagent.294- `merged` — merge content-quality review into `reviewer` for tiny direct setups.295- `skipped` — only when no generated agent, skill, memory, recommendation, or296 output-contract prose is changed.297298Default to `separate` for normal, complex, cross-runtime, audit, improve,299replication, MCP, release, skill-heavy, or multi-wave setups. Use300[content quality](./references/content-quality.md) for signals, status levels,301and boundaries. The curator reports302`Content quality: ok|warn|fail|n/a; signals=<list|none>` and never owns broad303write, MCP config, runtime config, release metadata, or final approval gates.304305### Phase 2 — Plan (Directory Architecture, Roster, Matrix, Waves)306307Build the plan and show it before writing anything. The plan must include:308309- **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.310- **Agent Roster** — table of `name | role | owns | triggers | model (optional) | parallel-safe | wave`. Use [topology guide](./references/topology.md). Compute parallel-safety per [parallelism](./references/parallelism.md): 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.311- **Capability Matrix** — capabilities × agents grid (✅ / 🟡).312- **Wave plan** — grouped list `Wave N → [parallel-safe subagents]`; the orchestrator fans out per wave and awaits each before the next.313- **Requirements triage** — status (`separate | merged | skipped`), intake brief, ambiguities, `question_request` count, risk flags, and recommended first-wave routing.314- **Content quality** — curator status (`separate | merged | skipped`), review scope, expected signals, and output marker from [content quality](./references/content-quality.md).315- **Security team operating model** — for `dedicated|expanded`, include roles,316 authorization scope, evidence contract, read-mostly defaults, and gates from317 [security team](./references/security-team.md).318- **Plan Handoff Contract** — accepted planning sources, HandoffIR fields, per-platform format targets, approval boundaries, and verification evidence. Use [handoff](./references/handoff.md).319- **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](./references/prompt-guidelines.md).320- **Self-update preflight** — status, source path or provider manager, fast-forward evidence, and any `question_request` from [self-update preflight](./references/self-update-preflight.md).321- **Human Input protocol** — selected runtime matrix, native question tool or fallback, allowlist/config syntax, and unresolved `question_request` records from [human input](./references/human-input.md).322- Skills to create.323- Plugin/MCP candidates **per capability** (Phase 3 fills this).324- Per-platform file plan (Copilot/Claude/OpenCode/Codex/Gemini paths the user will actually get).325- **Artifact tracking** — `project-tracked | project-local | personal-global`, plus exclude plan for local-only mode.326- **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.327- Git actions (if any).328- **Output profile & context budget** — `balanced|compact|full`, sections kept inline, overflow targets, and biggest expected agent-memory file.329- **Security & Audit Matrix** — controls, owner agents, affected paths, evidence required, and source reference.330- **Threat Model Summary** — assets, trust boundaries, threats, mitigations, owners, and status.331- **Architecture & Design Pattern Matrix** — selected patterns, alternatives, rationale, risks/guardrails, and ADR refs.332- **ADR plan** — decisions that should become docs if the user approves docs writes.333- **Quality Gates** — build/test/lint/security/supply-chain/architecture evidence required before "done".334335End the phase with `ask_user`: `["Proceed", "Edit plan first"]`.336337### Phase 3 — Marketplace Lookup with per-item Opt-in338339For every capability the user named (e.g., "playwright", "azure", "postgres"):3403411. **Search** the marketplaces in tier order — see [marketplaces](./references/marketplaces.md). Tier 1 first; only fall through if it misses.3422. 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.3433. Render a **comparison table** to the user, then call `ask_user`:344 > "For capability **<x>**, which would you like?"345 > Choices: `["<candidate 1 — short label>", "<candidate 2>", "<candidate 3>", "Show more (Tier-3 fallback search)", "None — skip this capability"]`3464. **Show more** triggers Tier-3 search (capped at +5 additional candidates). Re-render table and re-prompt.3475. Record the user's pick. Skipped capabilities never reach the MCP gate or final write.348349See [plugin discovery](./references/plugin-discovery.md) for the comparison-table format and rationale schema.350351For security-team setups, security plugins or skills remain optional candidates.352Show vendor/license attribution and tradeoffs. Never clone proprietary plugin353workflow text into generated agents, and never auto-install scanners, MCP354servers, or disclosure tooling.355356### Phase 3.5 — MCP Config Approval Gate (mandatory, downstream of Phase 3)357358If any user-selected candidate from Phase 3 includes an MCP server:3593601. Build the proposed config **per platform**:361 - Copilot CLI → `.mcp.json` (`mcpServers` key) and any approved agent-frontmatter `mcp-servers:`362 - Claude Code → `.mcp.json` (`mcpServers` key) and any approved project/user-agent `mcpServers`363 - OpenCode → merge into `opencode.json` (`mcp` key)364 - OpenAI Codex → `.mcp.json` plus any approved per-agent TOML `[mcp_servers.<id>]`365 - Gemini CLI → approved per-agent `mcp_servers:` blocks in `.gemini/agents/*.md`3662. Render each proposed file/config block verbatim (full JSON/YAML/TOML as applicable).3673. For central MCP config files (`.mcp.json` and `opencode.json` with MCP368 blocks), include concrete approval evidence with server names:369 - Prefer a top-level `x-agents-system-setup` object when the runtime schema370 safely tolerates extension keys. Include `mcp_approval.decision`,371 `mcp_approval.servers`, `approved_by` or `approval_ref`, and `evidence`.372 - If extension keys are not schema-safe, write a sibling sidecar named373 `<config>.agents-system-setup.approval.json` with the same metadata.3744. `ask_user`:375 > "I'm about to write the MCP configuration above to `<paths>`. Approve?"376 > Choices: `["Approve all (Recommended)", "Approve selectively (per-server)", "Skip MCP entirely"]`3775. If **selective**, loop per server: `["Include", "Skip"]`.3786. 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.3797. **No MCP write may occur before this gate returns approval.**380381### Phase 4 — Generate Artifacts (per platform, post-approval)382383For each selected platform, look up paths and frontmatter in [platforms.md](./references/platforms.md), then render:384385- `AGENTS.md` at repo root → [template](./assets/AGENTS.md.template). Fill **Read First**, **Context Loading Policy**, **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 from Phase 1.9; summarize long sections and link overflow details instead of dumping exhaustive prose inline.386- `GEMINI.md` when Gemini CLI is selected → [template](./assets/GEMINI.md.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.387- Orchestrator — **never emit as a subagent file** (subagent files are for specialized roles only). The orchestrator role lives in `AGENTS.md` › **Orchestration Operating Model** (Role, Hard Rules, Context Load Order, Lifecycle, Orchestrator Assignment Format, Wave Execution, Memory & Learning, Subagent Routing, Out of Scope) and is read by the host CLI session of any selected runtime — Copilot CLI, Claude Code, OpenCode, OpenAI Codex (CLI + App), and Gemini CLI. `@orchestrator` is a routing alias for that host session. OpenCode's `permission.task` subagent-gating moves to `opencode.json` › `agent.<root>.permission.task` (or equivalent host config) since no orchestrator markdown is emitted; see [platforms](./references/platforms.md) and [agent-format](./references/agent-format.md). Improve mode detects existing orchestrator subagent files and offers deletion/deprecation/manual-review choices via [misplaced-artifacts-migration](./references/misplaced-artifacts-migration.md#deprecated-orchestrator-subagent-files).388- Each subagent — use the **platform-specific template** and fill `{{OWNED_PATHS}}` / `{{READONLY_PATHS}}` from the Directory Architecture:389 - **Copilot CLI** → [subagent.agent.md.template](./assets/subagent.agent.md.template) at `.github/agents/<name>.agent.md`. Frontmatter: `name`, `description`, `tools:` list filled from the [Standard Tool Profile](./references/platforms.md#copilot-cli-standard-tool-profiles) 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.390 - **Claude Code** → [subagent.claude.md.template](./assets/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:`.391 - **OpenCode** → [subagent.opencode.md.template](./assets/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`.392 - **OpenAI Codex (CLI + App)** → [subagent.codex.toml.template](./assets/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](./references/platforms.md) and [openai docs](https://developers.openai.com/codex/subagents). 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 s393394…(truncated)