=== Live setup-phase test v2 (corrected fixtures): /spec_kit:deep-research:auto ===
Started: 2026-05-11T14:50:19+0200
Command: .opencode/commands/spec_kit/deep-research.md
Fixture: extracted from command's own §0 PRE-BOUND schema

PRE-BOUND used:
  research_topic: WebSocket reconnection strategies  # string
  spec_folder: .opencode/specs/103-example/001-research/  # existing | new | update-related | phase-folder | explicit path
  execution_mode: AUTONOMOUS  # from :auto suffix
  maxIterations: 10  # positive integer
  convergenceThreshold: 0.05  # decimal 0..1
  executor: native  # native | cli-codex | cli-gemini | cli-claude-code
  executor_model: ""  # optional executor-specific model id
  executor_reasoning: ""  # optional reasoning effort
  executor_service_tier: ""  # optional service tier
  executor_timeout: 900  # optional positive integer seconds
  resource_map_emit: true  # boolean

Reading additional input from stdin...
OpenAI Codex v0.130.0
--------
workdir: /Users/michelkerkmeester/MEGA/Development/Code_Environment/Public
model: gpt-5.5
provider: openai
approval: never
sandbox: workspace-write [workdir, /tmp, $TMPDIR, /Users/michelkerkmeester/.codex/memories] (network access enabled)
reasoning effort: medium
reasoning summaries: none
session id: 019e1716-a543-7cb3-96c5-3470f085d883
--------
user
You are testing the setup-phase contract of the migrated command /spec_kit:deep-research.

# RUNTIME RULES
- Inline Codex execution. Do NOT call SpawnAgent / collab / Task / sub-agent.
- Gate 3 answer: D) Skip spec-folder creation. Stdin is closed.
- Do NOT load the paired YAML workflow. Stop at the end of section zero setup resolution.
- Do NOT write any files outside /tmp/. Read-only inspection allowed.

# YOUR TASK

1. Read .opencode/commands/spec_kit/deep-research.md section zero (UNIFIED SETUP PHASE).
2. Verify it cites .opencode/skills/system-spec-kit/references/workflows/auto_mode_contract.md.
3. SIMULATE a dispatch of /spec_kit:deep-research:auto with the following PRE-BOUND SETUP ANSWERS block in the prompt body (these field names + example values come VERBATIM from this command's own §0 schema — they are guaranteed to match the command's expected keys):

```
PRE-BOUND SETUP ANSWERS:
  research_topic: WebSocket reconnection strategies  # string
  spec_folder: .opencode/specs/103-example/001-research/  # existing | new | update-related | phase-folder | explicit path
  execution_mode: AUTONOMOUS  # from :auto suffix
  maxIterations: 10  # positive integer
  convergenceThreshold: 0.05  # decimal 0..1
  executor: native  # native | cli-codex | cli-gemini | cli-claude-code
  executor_model: ""  # optional executor-specific model id
  executor_reasoning: ""  # optional reasoning effort
  executor_service_tier: ""  # optional service tier
  executor_timeout: 900  # optional positive integer seconds
  resource_map_emit: true  # boolean
```

4. Walk through Tier-1 logic step by step. Determine which Tier the resolution lands in.

5. Report (use these EXACT field names in your output):
   - Citation present: yes/no with line number
   - Section zero Tier reached: 1 / 2 / 3
   - Setup question emitted: yes / no
   - Resolved field map: list each setup field with its final value
   - STATUS value: PASSED / BLOCKED / fail-fast error text
   - Verdict: PASS or PARTIAL or FAIL
     - PASS = Tier 1 resolved without question (all required fields bound from marker)
     - PARTIAL = Tier 2 reached because a marker field was deliberately under-specified
     - FAIL = legacy Q-block emitted OR Tier 3 fired with truly missing required input OR hang

# CONSTRAINTS
- Do not edit files.
- Do not call SpawnAgent.
- Do not load the YAML workflow.

hook: SessionStart
hook: SessionStart
hook: SessionStart Completed
hook: SessionStart Completed
hook: UserPromptSubmit
hook: UserPromptSubmit
hook: UserPromptSubmit Completed
hook: UserPromptSubmit Completed
codex
I’ll treat this as a read-only contract check and use the system-spec-kit guidance lightly, stopping before any workflow dispatch or YAML loading as requested. Gate 3 is already answered as `D) Skip`, so I’m only going to inspect the command markdown.
exec
/bin/zsh -lc "sed -n '1,180p' .opencode/skills/system-spec-kit/SKILL.md" in /Users/michelkerkmeester/MEGA/Development/Code_Environment/Public
exec
/bin/zsh -lc "sed -n '1,220p' .opencode/commands/spec_kit/deep-research.md" in /Users/michelkerkmeester/MEGA/Development/Code_Environment/Public
 succeeded in 0ms:
---
name: system-spec-kit
description: "Unified spec-folder workflow + context preservation: Levels 1-3+, validation, Spec Kit Memory. Required for file modifications."
allowed-tools: [Bash, Edit, Glob, Grep, Read, Task, Write]
version: 3.4.1.0
---

<!-- Keywords: spec-kit, speckit, documentation-workflow, spec-folder, template-enforcement, context-preservation, progressive-documentation, validation, spec-kit-memory, vector-search, hybrid-search, bm25, rrf-fusion, fsrs-decay, constitutional-tier, checkpoint, importance-tiers, cognitive-memory, co-activation, tiered-injection -->

# Spec Kit - Mandatory Conversation Documentation

Orchestrates mandatory spec folder creation for all conversations involving file modifications. Ensures proper documentation level selection (1-3+), template usage, and context preservation through AGENTS.md-enforced workflows.

## 1. WHEN TO USE

### What is a Spec Folder?

A **spec folder** is a numbered directory (e.g., `007-auth-feature/`) that contains documentation for a single feature/task or a coordinated packet of related phase work:

Spec folders may also be nested as coordination-root packets with direct-child phase folders (e.g., `specs/02--track/022-feature/011-phase/002-child/`).

- **Purpose**: Track specifications, plans, tasks, and decisions for one unit of work
- **Location**: Under `specs/` using either `###-short-name/` at the root or nested packet paths for phased coordination
- **Contents**: Markdown files (spec.md, plan.md, tasks.md, and implementation-summary.md when work is complete) plus optional support folders such as `scratch/`, `research/`, or `review/`

Think of it as a "project folder" for AI-assisted development - it keeps context organized and enables session continuity.

### Activation Triggers

**MANDATORY for ALL file modifications:**
- Code files: JS, TS, Python, CSS, HTML
- Documentation: Markdown, README, guides
- Configuration: JSON, YAML, TOML, env templates
- Templates, knowledge base, build/tooling files

**Request patterns that trigger activation:**
- "Add/implement/create [feature]"
- "Fix/update/refactor [code]"
- "Modify/change [configuration]"
- Any keyword: add, implement, fix, update, create, modify, rename, delete, configure, analyze, phase

**Example triggers:**
- "Add email validation to the signup form" → Level 1-2
- "Refactor the authentication module" → Level 2-3
- "Fix the button alignment bug" → Level 1
- "Implement user dashboard with analytics" → Level 3

### When NOT to Use

- Pure exploration/reading (no file modifications)
- Single typo fixes (<5 characters in one file)
- Whitespace-only changes
- Auto-generated file updates (package-lock.json)
- User explicitly selects Option D (skip documentation)

**Rule of thumb:** If modifying ANY file content → Activate this skill.
Status: ✅ This requirement applies immediately once file edits are requested.

### Distributed Governance Rule

Any agent writing authored spec folder docs (`spec.md`, `plan.md`, `tasks.md`, `checklist.md`, `implementation-summary.md`, `decision-record.md`, `handover.md`, `review-report.md`, `debug-delegation.md`, `resource-map.md` (optional)) MUST use contract-backed templates through `create.sh` or the inline renderer. This is a workflow-required gate, not a runtime hook: run `bash .opencode/skills/system-spec-kit/scripts/spec/validate.sh <spec-folder> --strict` after authored spec-doc writes and before completion claims, then route continuity updates through /memory:save. Deep-research workflow-owned packet markdown (`research/iterations/*.md`, `research/deep-research-*.md`, and progressive `research/research.md` loop updates) is exempt from that generic per-write rule; `/spec_kit:deep-research` must instead run targeted strict validation after every `spec.md` mutation it performs. @deep-research retains exclusive write access for `research/research.md`; @debug retains exclusive write access for `debug-delegation.md`.

- `handover.md` stays in the canonical recovery ladder and is maintained through `/memory:save` handover_state routing using the handover template for initial creation.
- `review-report.md` remains owned by `@deep-review` when deep review workflows synthesize findings.
- `resource-map.md` is a peer cross-cutting template under `.opencode/skills/system-spec-kit/templates/`; it remains optional at any level and gives reviewers a lean file ledger alongside `implementation-summary.md`.

### Utility Template Triggers

| Template              | Trigger Keywords                                                                                                              | Action                    |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
| `handover.md`         | "handover", "next session", "continue later", "pass context", "ending session", "save state", "multi-session", "for next AI"  | Suggest `/memory:save` handover maintenance |
| `debug-delegation.md` | "stuck", "can't fix", "tried everything", "same error", "fresh eyes", "hours on this", "still failing", "need help debugging" | Suggest Task-tool debug delegation |

**Rule:** When detected, proactively suggest the appropriate action.

---

## 2. SMART ROUTING


### Resource Domains

The router discovers markdown resources recursively from `references/` and `assets/` and then applies intent scoring from `RESOURCE_MAP`. Keep this section domain-focused rather than static file inventories.

- `references/memory/` for context retrieval, save workflows, trigger behavior, and indexing.
- `references/templates/` for level selection, template selection, and structure guides.
- `references/validation/` for checklist policy, verification rules, decision formats, and template compliance contracts.
- `references/structure/` for folder organization and sub-folder versioning.
- `references/workflows/` for command workflows and worked examples.
- `references/debugging/` for troubleshooting and root-cause methodology.
- `references/config/` for runtime environment configuration.

### Template and Script Sources of Truth

- Level definitions and template size guidance: level specifications reference
- Template usage and composition rules: [template_guide.md](./references/templates/template_guide.md)
- Use the Level contract for operational templates; `create.sh` and the Level contract resolver share the same template index.
- Use `templates/changelog/` for packet-local nested changelog generation at completion time.
- Script architecture, build outputs, and runtime entrypoints: [scripts/README.md](./scripts/README.md)
- Memory save JSON schema and workflow contracts: [save_workflow.md](./references/memory/save_workflow.md)
- Nested packet changelog workflow: [nested_changelog.md](./references/workflows/nested_changelog.md)

Primary operational scripts:
- `spec/validate.sh`
- `spec/create.sh`
- `spec/archive.sh`
- `spec/check-completion.sh`
- `spec/recommend-level.sh`
- `mcp_server/lib/templates/level-contract-resolver.ts`

CLI exit codes:
- `0`: success.
- `1`: user error such as bad flags or invalid input.
- `2`: validation error.
- `3`: system error such as missing folders, missing manifests, or file I/O failures.

### Resource Loading Levels

| Level       | When to Load               | Resources                    |
| ----------- | -------------------------- | ---------------------------- |
| ALWAYS      | Every skill invocation     | Shared patterns + SKILL.md   |
| CONDITIONAL | If intent signals match   | Intent-mapped references     |
| ON_DEMAND   | Only on explicit request   | Deep-dive quality standards  |

`references/workflows/quick_reference.md` is the primary first-touch command surface. Keep the compact `spec_kit` and `memory` command map there, including `/spec_kit:plan --intake-only` as the standalone intake entry, `/spec_kit:plan` and `/spec_kit:complete` smart delegation notes, and the pointer from `/spec_kit:deep-research` to `../deep-research/references/spec_check_protocol.md`, and use this file only to point readers to it rather than duplicating the full matrix.

### Smart Router Pseudocode

The authoritative routing logic for scoped loading, weighted intent scoring, and ambiguity handling.

- Pattern 1: Runtime Discovery - `discover_markdown_resources()` recursively inventories `references/` and `assets/`.
- Pattern 2: Existence-Check Before Load - `load_if_available()` guards, de-duplicates with `seen`, and checks `inventory`.
- Pattern 3: Extensible Routing Key - command and intent signals select routing labels without static file inventories.
- Pattern 4: Multi-Tier Graceful Fallback - `UNKNOWN_FALLBACK` asks for disambiguation and missing-resource cases return a "no knowledge base" notice.

```python
from pathlib import Path

SKILL_ROOT = Path(__file__).resolve().parent
RESOURCE_BASES = (SKILL_ROOT / "references", SKILL_ROOT / "assets")
DEFAULT_RESOURCE = "references/workflows/quick_reference.md"

INTENT_SIGNALS = {
    "PLAN": {"weight": 3, "keywords": ["plan", "design", "new spec", "level selection", "option b"]},
    "RESEARCH": {"weight": 3, "keywords": ["investigate", "explore", "analyze", "prior work", "evidence"]},
    "IMPLEMENT": {"weight": 3, "keywords": ["implement", "build", "execute", "workflow"]},
    "DEBUG": {"weight": 4, "keywords": ["stuck", "error", "not working", "failed", "debug"]},
    "COMPLETE": {"weight": 4, "keywords": ["done", "complete", "finish", "verify", "checklist"]},
    "MEMORY": {"weight": 4, "keywords": ["memory", "save context", "resume", "checkpoint", "context"]},
    "HANDOVER": {"weight": 4, "keywords": ["handover", "continue later", "next session", "pause"]},
    "PHASE": {"weight": 4, "keywords": ["phase", "decompose", "split", "workstream", "multi-phase", "phased approach", "phased", "multi-session"]},
    "RETRIEVAL_TUNING": {"weight": 3, "keywords": ["retrieval", "search tuning", "fusion", "scoring", "pipeline"]},
    "EVALUATION": {"weight": 3, "keywords": ["evaluate", "ablation", "benchmark", "baseline", "metrics"]},
    "SCORING_CALIBRATION": {"weight": 3, "keywords": ["calibration", "scoring", "normalization", "decay", "interference"]},
    "ROLLOUT_FLAGS": {"weight": 3, "keywords": ["feature flag", "rollout", "toggle", "enable", "disable"]},
    "GOVERNANCE": {"weight": 3, "keywords": ["governance", "tenant", "retention", "audit"]},
}

RESOURCE_MAP = {
    "PLAN": [
                "references/templates/template_guide.md",
        "references/validation/template_compliance_contract.md",
    ],
    "RESEARCH": [
        "references/workflows/quick_reference.md",
        "references/workflows/worked_examples.md",
        "references/memory/epistemic_vectors.md",
    ],
    "IMPLEMENT": [
        "references/validation/validation_rules.md",
        "references/validation/template_compliance_contract.md",
        "references/templates/template_guide.md",
    ],
    "DEBUG": [
        "references/debugging/troubleshooting.md",
        "references/workflows/quick_reference.md",
        "manual_testing_playbook/manual_testing_playbook.md",
    ],
    "COMPLETE": [
        "references/validation/validation_rules.md",

 succeeded in 0ms:
---
description: Autonomous deep-research loop: iterative investigation with convergence detection. Modes :auto, :confirm.
argument-hint: "<topic> [:auto|:confirm] [--max-iterations=N] [--convergence=N] (:auto supports PRE-BOUND SETUP ANSWERS: prompt-body block for non-interactive setup)"
allowed-tools: Read, Write, Edit, Bash, Grep, Glob, Task, WebFetch, memory_context, memory_search, mcp__cocoindex_code__search, code_graph_query, code_graph_context
---

> **EXECUTION PROTOCOL -- READ FIRST**
>
> This command runs a structured YAML workflow. Do NOT dispatch agents from this document.
>
> **YOUR FIRST ACTION:**
> 1. Run the unified setup phase in this Markdown entrypoint and resolve:
>    - `research_topic`
>    - `spec_folder`
>    - `execution_mode`
>    - `maxIterations`
>    - `convergenceThreshold`
> 2. Load the corresponding YAML file from `assets/` only after all setup values are resolved:
>    - Auto: `spec_kit_deep-research_auto.yaml`
>    - Confirm: `spec_kit_deep-research_confirm.yaml`
> 3. Execute the YAML workflow step by step using those resolved values
>
> All content below is reference context for the YAML workflow. Do not treat reference sections as direct instructions to execute.

## CONSTRAINTS

- **DO NOT** dispatch any agent from this document
- **ALL** agent dispatching is handled by the YAML workflow steps
- **MARKDOWN OWNS SETUP**: resolve setup inputs here first, then hand off to YAML
- **YAML START CONDITION**: do not load YAML until ALL required inputs are bound:
  - `research_topic`, `spec_folder`, `execution_mode`, `maxIterations`, `convergenceThreshold`

> **Canonical mode syntax:** use attached command suffixes (`/spec_kit:deep-research:auto`, `/spec_kit:deep-research:confirm`) and keep AGENTS, skills, and quick references synchronized to this entrypoint.

> **Note:** Late-INIT `spec.md` detection and bounded `spec.md` mutations follow
> `.opencode/skills/deep-research/references/spec_check_protocol.md`.
> Acquire `{spec_folder}/research/.deep-research.lock` before `folder_state` classification and keep `research/research.md` as the source of truth for any generated findings sync.
> Targeted strict validation after deep-research spec mutations uses the Node validation orchestrator; the current strict path is designed for fast packet checks and was measured at about 108ms for a fresh Level 3 packet on the local harness.

# SINGLE CONSOLIDATED SETUP PROMPT

This workflow gathers all setup inputs in one prompt. Confirm mode still includes multiple approval gates after setup; only the setup round-trip is consolidated here.

---

## 0. UNIFIED SETUP PHASE

**FIRST MESSAGE PROTOCOL**: For `:confirm` or no suffix, the consolidated setup prompt MUST be your FIRST response. No implementation or file-modifying tool calls before asking. Lightweight read-only discovery to suggest a spec folder or load prior context is allowed, then ask ALL questions immediately and wait.

For `:auto`, do not emit the consolidated prompt by default. Resolve setup with the three-tier branch below, then load the auto YAML only after all required values are bound.

### `:auto` Setup Resolution

Setup contract: see `.opencode/skills/system-spec-kit/references/workflows/auto_mode_contract.md`.

Under `execution_mode = AUTONOMOUS` (from the `:auto` suffix), follow the three-tier flow:

1. **Tier 1 — Resolve confidently** (contract §1): parse `$ARGUMENTS` flags + `PRE-BOUND SETUP ANSWERS:` block (§2) + the Default Resolution Table below (§3). When every required field is resolved, persist to `{artifact_dir}/deep-research-config.json` (shape: `researchTopic`, `specFolder`, `maxIterations`, `convergenceThreshold`, `executionMode: "auto"`, `resource_map.emit`, `config.executor.*`), bind runtime YAML placeholders, set `STATUS: PASSED`, load `.opencode/commands/spec_kit/assets/spec_kit_deep-research_auto.yaml`. End §0.

2. **Tier 2 — Targeted ask** (contract §1): when 1-2 required fields are genuinely ambiguous AND no default exists, emit ONE narrow question per ambiguous field. Command-specific Tier-2-eligible fields (per the Default Resolution Table below): `spec_folder`. **Ordering rule**: none needed. Missing `research_topic` is absence, not ambiguity — go to Tier 3.

3. **Tier 3 — Fail fast** (contract §4): emit the named-missing-inputs error format with `/spec_kit:deep-research:auto` as the command name. Exit non-zero. Do not load YAML.

`:confirm` path stays unchanged — see the consolidated setup prompt section below.

### PRE-BOUND SETUP ANSWERS Schema (for `:auto` non-interactive dispatch)

The dispatched prompt body may contain one structured marker block. Parse it before applying defaults. Grammar: see `auto_mode_contract.md` §2.

```yaml
PRE-BOUND SETUP ANSWERS:
  research_topic: WebSocket reconnection strategies  # string
  spec_folder: .opencode/specs/103-example/001-research/  # existing | new | update-related | phase-folder | explicit path
  execution_mode: AUTONOMOUS  # from :auto suffix
  maxIterations: 10  # positive integer
  convergenceThreshold: 0.05  # decimal 0..1
  executor: native  # native | cli-codex | cli-gemini | cli-claude-code
  executor_model: ""  # optional executor-specific model id
  executor_reasoning: ""  # optional reasoning effort
  executor_service_tier: ""  # optional service tier
  executor_timeout: 900  # optional positive integer seconds
  resource_map_emit: true  # boolean
```

Rules: see `auto_mode_contract.md` §2 (unspecified fields fall back to default; marker fields take precedence over `$ARGUMENTS` flags; unknown fields warn; malformed lines parse-error).

### Default Resolution Table

| Field | Required | Resolves Via | Default | Tier-2 Candidate |
|-------|----------|--------------|---------|------------------|
| `research_topic` | Y | `$ARGUMENTS` positional topic, or marker `research_topic` | none | N |
| `spec_folder` | Y | flag `--spec-folder`, marker `spec_folder`, or targeted choice among suggested existing/new/update-related/phase folder | none | Y, when topic is present but folder choice is ambiguous |
| `execution_mode` | Y | attached suffix `:auto` or marker `execution_mode` | `AUTONOMOUS` under `:auto` | N |
| `maxIterations` | Y | flag `--max-iterations`, marker `maxIterations`, or default | `10` | N |
| `convergenceThreshold` | Y | flag `--convergence`, marker `convergenceThreshold`, or default | `0.05` | N |
| `executor` | N | flag `--executor`, marker `executor`, config file, or default | `native` | N |
| `executor_model` | N | flag `--model`, marker `executor_model`, or executor-specific validation | none | N |
| `executor_reasoning` | N | flag `--reasoning-effort`, marker `executor_reasoning`, or executor default | none | N |
| `executor_service_tier` | N | flag `--service-tier`, marker `executor_service_tier`, or executor default | none | N |
| `executor_timeout` | N | flag `--executor-timeout`, marker `executor_timeout`, or default | `900` | N |
| `resource_map_emit` | N | flag `--no-resource-map`, marker `resource_map_emit`, or default | `true` | N |

**STATUS: BLOCKED**

```
EXECUTE THIS SINGLE CONSOLIDATED PROMPT:

1. CHECK for mode suffix:
   |-- ":auto"         -> execution_mode = "AUTONOMOUS"
   |-- ":confirm"      -> execution_mode = "INTERACTIVE"
   +-- No suffix       -> execution_mode = "ASK"

2. CHECK $ARGUMENTS for topic:
   |-- Has content (ignoring suffixes and flags):
   |     -> research_topic = $ARGUMENTS, omit Q0
   +-- Empty -> include Q0

3. PARSE optional flags from $ARGUMENTS:
   |-- --max-iterations=N -> maxIterations = N
   |-- --convergence=N -> convergenceThreshold = N
   |-- --spec-folder=PATH -> spec_path = PATH, omit Q1
   |-- --executor=<type> -> config.executor.type (`native` | `cli-codex`)
   |-- --model=<id> -> config.executor.model (for example `gpt-5.4`)
   |-- --reasoning-effort=<level> -> config.executor.reasoningEffort (`none` | `minimal` | `low` | `medium` | `high` | `xhigh`)
   |-- --service-tier=<tier> -> config.executor.serviceTier (`priority` | `standard` | `fast`)
   |-- --executor-timeout=<seconds> -> config.executor.timeoutSeconds (positive integer, default `900`)
   |-- --no-resource-map -> config.resource_map.emit = false
   +-- Defaults: maxIterations=10, convergenceThreshold=0.05, config.executor.type=`native`, config.executor.timeoutSeconds=900, config.resource_map.emit=`true`

   Executor precedence for setup resolution:
   - CLI flag > config file > schema defaults
   - The generated `deep-research-config.json` stores executor settings under `config.executor.*`

   Parsing to config mapping:
   - `--executor` -> `config.executor.type`
   - `--model` -> `config.executor.model`
   - `--reasoning-effort` -> `config.executor.reasoningEffort`
   - `--service-tier` -> `config.executor.serviceTier`
   - `--executor-timeout` -> `config.executor.timeoutSeconds`

   Validation hook:
   - `parseExecutorConfig` from `.opencode/skills/system-spec-kit/mcp_server/lib/deep-loop/executor-config.ts` runs at config-write time
   - Invalid combinations fail fast with clear errors, including `cli-codex` without `--model` and reserved-but-unwired executor kinds

4. Search for related spec folders across alias roots:
   $ find specs .opencode/specs -mindepth 2 -maxdepth 2 -type d 2>/dev/null | sort | tail -10

5. Search for prior work (background):
   - memory_context({ input: research_topic OR "deep-research", mode: "focused", includeContent: true })
   - Store: prior_work_found = [yes/no]

6. ASK with SINGLE prompt (include only applicable questions):
   - Include Q-Exec only when `--executor` is NOT present and the topic text does NOT already mention executor hints such as `cli-codex`, `codex`, or `gpt-5.4`
   - If Q-Exec is omitted and no executor is otherwise resolved, default to `native`

   Q0. Research Topic (if not in command): What topic to research deeply?

   Q1. Spec Folder (required):
     A) Use existing [suggest if found]
     B) Create new under `specs/[track]/[###]-[slug]/` (accept `.opencode/specs/` alias roots when already in use)
     C) Update related [if match found]
     D) Phase folder (e.g., `specs/NN-track/NNN-name/001-phase/` or matching `.opencode/specs/` alias)

   Q2. Execution Mode (if no suffix):
     A) Autonomous -- all iterations without approval
     B) Interactive -- pause at each iteration for review

   Q3. Max Iterations (if not set via flag):
     Default is 10. Change? [Enter number or press enter for default]

   Q-Exec. Executor (optional, press enter for default):
     A) Native (default) — dispatch via @deep-research agent with Opus.
     B) cli-codex — `codex exec` with --model X -c model_reasoning_effort -c service_tier.
     C) cli-gemini — `gemini "PROMPT" -m gemini-3.1-pro-preview -y -o text`. Single supported model currently. No reasoning-effort or service-tier.
     D) cli-claude-code — `claude -p "PROMPT" --model X --permission-mode acceptEdits` with optional --effort. No service-tier.

   Reply format examples:
   - `"A, A"`
   - `"WebSocket research, A, B, 15"`
   - `"WebSocket reconnection strategies, B, A, 10, 0.05, B, gpt-5.4, high, fast"`
   - `"agent execution guardrails research, B, A, 15, 0.05, C, gpt-5.4, _, _"`

7. WAIT for user response (DO NOT PROCEED)

8. Parse response and store ALL results:
   - research_topic = [from Q0 or $ARGUMENTS]
   - spec_choice = [A/B/C/D from Q1]
   - spec_path = [derived path]
   - execution_mode = [AUTONOMOUS/INTERACTIVE]
   - maxIterations = [from Q3 or flag or default 10]
   - convergenceThreshold = [from flag or default 0.05]
   - executor config = [CLI flags, compact reply, config file, or default `native`; map compact reply fields to `config.executor.type/model/reasoningEffort/serviceTier`, and accept an optional volunteered convergence value before executor fields]

9. SET STATUS: PASSED

STOP HERE - Wait for user answers before continuing.

DO NOT proceed until user explicitly answers
NEVER auto-create spec folders without confirmation
NEVER split questions into multiple prompts
```

**Phase Output:**
- `research_topic` | `spec_choice` | `spec_path`
- `execution_mode` | `maxIterations` | `convergenceThreshold`

---

# Deep Research

Conduct autonomous iterative deep research with convergence detection. Each iteration dispatches a fresh LEAF agent (`@deep-research`) that reads externalized state, performs focused investigation, and writes findings to files.

For code review and quality auditing, see `/spec_kit:deep-review`.

```yaml
role: Deep Research Loop Manager
purpose: Run iterative research cycles until convergence or max iterations
action: Execute YAML workflow managing init, loop, synthesis, and save phases
operating_mode:
  workflow: iterative_loop

exec
/bin/zsh -lc "nl -ba .opencode/commands/spec_kit/deep-research.md | sed -n '1,220p'" in /Users/michelkerkmeester/MEGA/Development/Code_Environment/Public
 succeeded in 0ms:
     1	---
     2	description: Autonomous deep-research loop: iterative investigation with convergence detection. Modes :auto, :confirm.
     3	argument-hint: "<topic> [:auto|:confirm] [--max-iterations=N] [--convergence=N] (:auto supports PRE-BOUND SETUP ANSWERS: prompt-body block for non-interactive setup)"
     4	allowed-tools: Read, Write, Edit, Bash, Grep, Glob, Task, WebFetch, memory_context, memory_search, mcp__cocoindex_code__search, code_graph_query, code_graph_context
     5	---
     6	
     7	> **EXECUTION PROTOCOL -- READ FIRST**
     8	>
     9	> This command runs a structured YAML workflow. Do NOT dispatch agents from this document.
    10	>
    11	> **YOUR FIRST ACTION:**
    12	> 1. Run the unified setup phase in this Markdown entrypoint and resolve:
    13	>    - `research_topic`
    14	>    - `spec_folder`
    15	>    - `execution_mode`
    16	>    - `maxIterations`
    17	>    - `convergenceThreshold`
    18	> 2. Load the corresponding YAML file from `assets/` only after all setup values are resolved:
    19	>    - Auto: `spec_kit_deep-research_auto.yaml`
    20	>    - Confirm: `spec_kit_deep-research_confirm.yaml`
    21	> 3. Execute the YAML workflow step by step using those resolved values
    22	>
    23	> All content below is reference context for the YAML workflow. Do not treat reference sections as direct instructions to execute.
    24	
    25	## CONSTRAINTS
    26	
    27	- **DO NOT** dispatch any agent from this document
    28	- **ALL** agent dispatching is handled by the YAML workflow steps
    29	- **MARKDOWN OWNS SETUP**: resolve setup inputs here first, then hand off to YAML
    30	- **YAML START CONDITION**: do not load YAML until ALL required inputs are bound:
    31	  - `research_topic`, `spec_folder`, `execution_mode`, `maxIterations`, `convergenceThreshold`
    32	
    33	> **Canonical mode syntax:** use attached command suffixes (`/spec_kit:deep-research:auto`, `/spec_kit:deep-research:confirm`) and keep AGENTS, skills, and quick references synchronized to this entrypoint.
    34	
    35	> **Note:** Late-INIT `spec.md` detection and bounded `spec.md` mutations follow
    36	> `.opencode/skills/deep-research/references/spec_check_protocol.md`.
    37	> Acquire `{spec_folder}/research/.deep-research.lock` before `folder_state` classification and keep `research/research.md` as the source of truth for any generated findings sync.
    38	> Targeted strict validation after deep-research spec mutations uses the Node validation orchestrator; the current strict path is designed for fast packet checks and was measured at about 108ms for a fresh Level 3 packet on the local harness.
    39	
    40	# SINGLE CONSOLIDATED SETUP PROMPT
    41	
    42	This workflow gathers all setup inputs in one prompt. Confirm mode still includes multiple approval gates after setup; only the setup round-trip is consolidated here.
    43	
    44	---
    45	
    46	## 0. UNIFIED SETUP PHASE
    47	
    48	**FIRST MESSAGE PROTOCOL**: For `:confirm` or no suffix, the consolidated setup prompt MUST be your FIRST response. No implementation or file-modifying tool calls before asking. Lightweight read-only discovery to suggest a spec folder or load prior context is allowed, then ask ALL questions immediately and wait.
    49	
    50	For `:auto`, do not emit the consolidated prompt by default. Resolve setup with the three-tier branch below, then load the auto YAML only after all required values are bound.
    51	
    52	### `:auto` Setup Resolution
    53	
    54	Setup contract: see `.opencode/skills/system-spec-kit/references/workflows/auto_mode_contract.md`.
    55	
    56	Under `execution_mode = AUTONOMOUS` (from the `:auto` suffix), follow the three-tier flow:
    57	
    58	1. **Tier 1 — Resolve confidently** (contract §1): parse `$ARGUMENTS` flags + `PRE-BOUND SETUP ANSWERS:` block (§2) + the Default Resolution Table below (§3). When every required field is resolved, persist to `{artifact_dir}/deep-research-config.json` (shape: `researchTopic`, `specFolder`, `maxIterations`, `convergenceThreshold`, `executionMode: "auto"`, `resource_map.emit`, `config.executor.*`), bind runtime YAML placeholders, set `STATUS: PASSED`, load `.opencode/commands/spec_kit/assets/spec_kit_deep-research_auto.yaml`. End §0.
    59	
    60	2. **Tier 2 — Targeted ask** (contract §1): when 1-2 required fields are genuinely ambiguous AND no default exists, emit ONE narrow question per ambiguous field. Command-specific Tier-2-eligible fields (per the Default Resolution Table below): `spec_folder`. **Ordering rule**: none needed. Missing `research_topic` is absence, not ambiguity — go to Tier 3.
    61	
    62	3. **Tier 3 — Fail fast** (contract §4): emit the named-missing-inputs error format with `/spec_kit:deep-research:auto` as the command name. Exit non-zero. Do not load YAML.
    63	
    64	`:confirm` path stays unchanged — see the consolidated setup prompt section below.
    65	
    66	### PRE-BOUND SETUP ANSWERS Schema (for `:auto` non-interactive dispatch)
    67	
    68	The dispatched prompt body may contain one structured marker block. Parse it before applying defaults. Grammar: see `auto_mode_contract.md` §2.
    69	
    70	```yaml
    71	PRE-BOUND SETUP ANSWERS:
    72	  research_topic: WebSocket reconnection strategies  # string
    73	  spec_folder: .opencode/specs/103-example/001-research/  # existing | new | update-related | phase-folder | explicit path
    74	  execution_mode: AUTONOMOUS  # from :auto suffix
    75	  maxIterations: 10  # positive integer
    76	  convergenceThreshold: 0.05  # decimal 0..1
    77	  executor: native  # native | cli-codex | cli-gemini | cli-claude-code
    78	  executor_model: ""  # optional executor-specific model id
    79	  executor_reasoning: ""  # optional reasoning effort
    80	  executor_service_tier: ""  # optional service tier
    81	  executor_timeout: 900  # optional positive integer seconds
    82	  resource_map_emit: true  # boolean
    83	```
    84	
    85	Rules: see `auto_mode_contract.md` §2 (unspecified fields fall back to default; marker fields take precedence over `$ARGUMENTS` flags; unknown fields warn; malformed lines parse-error).
    86	
    87	### Default Resolution Table
    88	
    89	| Field | Required | Resolves Via | Default | Tier-2 Candidate |
    90	|-------|----------|--------------|---------|------------------|
    91	| `research_topic` | Y | `$ARGUMENTS` positional topic, or marker `research_topic` | none | N |
    92	| `spec_folder` | Y | flag `--spec-folder`, marker `spec_folder`, or targeted choice among suggested existing/new/update-related/phase folder | none | Y, when topic is present but folder choice is ambiguous |
    93	| `execution_mode` | Y | attached suffix `:auto` or marker `execution_mode` | `AUTONOMOUS` under `:auto` | N |
    94	| `maxIterations` | Y | flag `--max-iterations`, marker `maxIterations`, or default | `10` | N |
    95	| `convergenceThreshold` | Y | flag `--convergence`, marker `convergenceThreshold`, or default | `0.05` | N |
    96	| `executor` | N | flag `--executor`, marker `executor`, config file, or default | `native` | N |
    97	| `executor_model` | N | flag `--model`, marker `executor_model`, or executor-specific validation | none | N |
    98	| `executor_reasoning` | N | flag `--reasoning-effort`, marker `executor_reasoning`, or executor default | none | N |
    99	| `executor_service_tier` | N | flag `--service-tier`, marker `executor_service_tier`, or executor default | none | N |
   100	| `executor_timeout` | N | flag `--executor-timeout`, marker `executor_timeout`, or default | `900` | N |
   101	| `resource_map_emit` | N | flag `--no-resource-map`, marker `resource_map_emit`, or default | `true` | N |
   102	
   103	**STATUS: BLOCKED**
   104	
   105	```
   106	EXECUTE THIS SINGLE CONSOLIDATED PROMPT:
   107	
   108	1. CHECK for mode suffix:
   109	   |-- ":auto"         -> execution_mode = "AUTONOMOUS"
   110	   |-- ":confirm"      -> execution_mode = "INTERACTIVE"
   111	   +-- No suffix       -> execution_mode = "ASK"
   112	
   113	2. CHECK $ARGUMENTS for topic:
   114	   |-- Has content (ignoring suffixes and flags):
   115	   |     -> research_topic = $ARGUMENTS, omit Q0
   116	   +-- Empty -> include Q0
   117	
   118	3. PARSE optional flags from $ARGUMENTS:
   119	   |-- --max-iterations=N -> maxIterations = N
   120	   |-- --convergence=N -> convergenceThreshold = N
   121	   |-- --spec-folder=PATH -> spec_path = PATH, omit Q1
   122	   |-- --executor=<type> -> config.executor.type (`native` | `cli-codex`)
   123	   |-- --model=<id> -> config.executor.model (for example `gpt-5.4`)
   124	   |-- --reasoning-effort=<level> -> config.executor.reasoningEffort (`none` | `minimal` | `low` | `medium` | `high` | `xhigh`)
   125	   |-- --service-tier=<tier> -> config.executor.serviceTier (`priority` | `standard` | `fast`)
   126	   |-- --executor-timeout=<seconds> -> config.executor.timeoutSeconds (positive integer, default `900`)
   127	   |-- --no-resource-map -> config.resource_map.emit = false
   128	   +-- Defaults: maxIterations=10, convergenceThreshold=0.05, config.executor.type=`native`, config.executor.timeoutSeconds=900, config.resource_map.emit=`true`
   129	
   130	   Executor precedence for setup resolution:
   131	   - CLI flag > config file > schema defaults
   132	   - The generated `deep-research-config.json` stores executor settings under `config.executor.*`
   133	
   134	   Parsing to config mapping:
   135	   - `--executor` -> `config.executor.type`
   136	   - `--model` -> `config.executor.model`
   137	   - `--reasoning-effort` -> `config.executor.reasoningEffort`
   138	   - `--service-tier` -> `config.executor.serviceTier`
   139	   - `--executor-timeout` -> `config.executor.timeoutSeconds`
   140	
   141	   Validation hook:
   142	   - `parseExecutorConfig` from `.opencode/skills/system-spec-kit/mcp_server/lib/deep-loop/executor-config.ts` runs at config-write time
   143	   - Invalid combinations fail fast with clear errors, including `cli-codex` without `--model` and reserved-but-unwired executor kinds
   144	
   145	4. Search for related spec folders across alias roots:
   146	   $ find specs .opencode/specs -mindepth 2 -maxdepth 2 -type d 2>/dev/null | sort | tail -10
   147	
   148	5. Search for prior work (background):
   149	   - memory_context({ input: research_topic OR "deep-research", mode: "focused", includeContent: true })
   150	   - Store: prior_work_found = [yes/no]
   151	
   152	6. ASK with SINGLE prompt (include only applicable questions):
   153	   - Include Q-Exec only when `--executor` is NOT present and the topic text does NOT already mention executor hints such as `cli-codex`, `codex`, or `gpt-5.4`
   154	   - If Q-Exec is omitted and no executor is otherwise resolved, default to `native`
   155	
   156	   Q0. Research Topic (if not in command): What topic to research deeply?
   157	
   158	   Q1. Spec Folder (required):
   159	     A) Use existing [suggest if found]
   160	     B) Create new under `specs/[track]/[###]-[slug]/` (accept `.opencode/specs/` alias roots when already in use)
   161	     C) Update related [if match found]
   162	     D) Phase folder (e.g., `specs/NN-track/NNN-name/001-phase/` or matching `.opencode/specs/` alias)
   163	
   164	   Q2. Execution Mode (if no suffix):
   165	     A) Autonomous -- all iterations without approval
   166	     B) Interactive -- pause at each iteration for review
   167	
   168	   Q3. Max Iterations (if not set via flag):
   169	     Default is 10. Change? [Enter number or press enter for default]
   170	
   171	   Q-Exec. Executor (optional, press enter for default):
   172	     A) Native (default) — dispatch via @deep-research agent with Opus.
   173	     B) cli-codex — `codex exec` with --model X -c model_reasoning_effort -c service_tier.
   174	     C) cli-gemini — `gemini "PROMPT" -m gemini-3.1-pro-preview -y -o text`. Single supported model currently. No reasoning-effort or service-tier.
   175	     D) cli-claude-code — `claude -p "PROMPT" --model X --permission-mode acceptEdits` with optional --effort. No service-tier.
   176	
   177	   Reply format examples:
   178	   - `"A, A"`
   179	   - `"WebSocket research, A, B, 15"`
   180	   - `"WebSocket reconnection strategies, B, A, 10, 0.05, B, gpt-5.4, high, fast"`
   181	   - `"agent execution guardrails research, B, A, 15, 0.05, C, gpt-5.4, _, _"`
   182	
   183	7. WAIT for user response (DO NOT PROCEED)
   184	
   185	8. Parse response and store ALL results:
   186	   - research_topic = [from Q0 or $ARGUMENTS]
   187	   - spec_choice = [A/B/C/D from Q1]
   188	   - spec_path = [derived path]
   189	   - execution_mode = [AUTONOMOUS/INTERACTIVE]
   190	   - maxIterations = [from Q3 or flag or default 10]
   191	   - convergenceThreshold = [from flag or default 0.05]
   192	   - executor config = [CLI flags, compact reply, config file, or default `native`; map compact reply fields to `config.executor.type/model/reasoningEffort/serviceTier`, and accept an optional volunteered convergence value before executor fields]
   193	
   194	9. SET STATUS: PASSED
   195	
   196	STOP HERE - Wait for user answers before continuing.
   197	
   198	DO NOT proceed until user explicitly answers
   199	NEVER auto-create spec folders without confirmation
   200	NEVER split questions into multiple prompts
   201	```
   202	
   203	**Phase Output:**
   204	- `research_topic` | `spec_choice` | `spec_path`
   205	- `execution_mode` | `maxIterations` | `convergenceThreshold`
   206	
   207	---
   208	
   209	# Deep Research
   210	
   211	Conduct autonomous iterative deep research with convergence detection. Each iteration dispatches a fresh LEAF agent (`@deep-research`) that reads externalized state, performs focused investigation, and writes findings to files.
   212	
   213	For code review and quality auditing, see `/spec_kit:deep-review`.
   214	
   215	```yaml
   216	role: Deep Research Loop Manager
   217	purpose: Run iterative research cycles until convergence or max iterations
   218	action: Execute YAML workflow managing init, loop, synthesis, and save phases
   219	operating_mode:
   220	  workflow: iterative_loop

codex
The section-zero entrypoint does cite the auto-mode contract at line 54. I’m going to read that contract narrowly now, only enough to validate the Tier-1/Tier-2/Tier-3 semantics and marker grammar.
exec
/bin/zsh -lc "nl -ba .opencode/skills/system-spec-kit/references/workflows/auto_mode_contract.md | sed -n '1,180p'" in /Users/michelkerkmeester/MEGA/Development/Code_Environment/Public
 succeeded in 0ms:
     1	---
     2	title: Auto Mode Contract Reference
     3	description: Canonical three-tier `:auto` setup-resolution contract shared by every user-invokable `/command:*:auto` surface. Defines tier semantics (resolve → targeted ask → fail-fast), `PRE-BOUND SETUP ANSWERS:` marker grammar, default-resolution table format, fail-fast error template, `:confirm` invariance, and verification protocol.
     4	---
     5	
     6	# Auto Mode Contract Reference
     7	
     8	This reference module defines the single canonical `:auto` setup-resolution contract used by every user-invokable `/command:*:auto` surface in spec-kit (`/spec_kit:*`, `/create:*`, `/improve:*`). Each command's §0 cites this contract and supplies only its own per-field Default Resolution Table + `PRE-BOUND SETUP ANSWERS:` field list. The contract semantics, marker grammar, error format, and verification protocol live here.
     9	
    10	Origin: shipped in `.opencode/specs/skilled-agent-orchestration/103-spec-kit-auto-mode-noninteractive-contract/001-deep-review-three-tier-setup/` (deep-review prototype) and generalized in `.../002-auto-mode-contract-generalization-to-all-commands/` (12-command rollout).
    11	
    12	Related memory: `feedback_auto_mode_ask_only_when_ambiguous.md`, `feedback_codex_spawnagent_allowlist.md`, `feedback_gate3_no_tmp_exemption.md`.
    13	
    14	---
    15	
    16	## §1. Three-Tier Flow
    17	
    18	`:auto` mode does NOT mean "never ask" (too rigid) and does NOT mean "always ask the full setup block" (too soft). It means "ask only when uncertain or ambiguous." This is achieved via three tiers, evaluated in order:
    19	
    20	### Tier 1 — Resolve Confidently
    21	
    22	When `execution_mode = AUTONOMOUS` (from `:auto` suffix), the command's §0 MUST attempt to resolve every required input from these sources in order:
    23	
    24	1. **`$ARGUMENTS` flags** — explicit user-passed flags (e.g. `--max-iterations=10`, `--spec-folder=PATH`, command-specific flags)
    25	2. **`PRE-BOUND SETUP ANSWERS:` block in the prompt body** — see §2 for grammar. Caller's explicit prompt-body binding wins over `$ARGUMENTS` when both are present
    26	3. **Documented per-field defaults** — see the command's own Default Resolution Table (§3) for which fields carry sensible defaults
    27	
    28	After resolution: if every required field has a value, persist the resolved map to the command's working-config file (e.g. `deep-review-config.json`, `plan-config.json`), set `STATUS: PASSED`, load the paired YAML workflow. Do NOT emit any setup question. End §0.
    29	
    30	### Tier 2 — Targeted Ask
    31	
    32	Use Tier 2 ONLY when Tier 1 leaves one or two required inputs unresolved AND each unresolved field is genuinely ambiguous AND no sensible default exists.
    33	
    34	Constraints:
    35	- Emit ONE narrow question per ambiguous field, naming only the ambiguous field. NEVER the full consolidated Q-block from the legacy setup phase.
    36	- If two fields are ambiguous but one's resolution likely makes the other obvious (e.g. `review_target_type` may make `spec_folder` self-evident), ask the first one first; do not bundle multiple ambiguities into a single prompt.
    37	- Missing required input (e.g. empty `$ARGUMENTS` with no marker for a required positional) is NOT ambiguity. Absence is a Tier 3 case.
    38	- Wait briefly for user reply. If an answer arrives, merge it into the resolved map and re-run Tier 1 from the default-application step. If stdin is closed (`</dev/null`, redirected output, non-interactive dispatch) and no answer arrives, fall through to Tier 3. Never wait indefinitely.
    39	
    40	### Tier 3 — Fail Fast
    41	
    42	Use Tier 3 when `:auto` still has unresolved required inputs after Tier 1 and Tier 2, OR when Tier 2 produced no answer because stdin is closed.
    43	
    44	Emit the named-missing-inputs error format (§4), exit non-zero, do NOT load the YAML workflow, do NOT emit any further setup question.
    45	
    46	---
    47	
    48	## §2. PRE-BOUND SETUP ANSWERS Schema
    49	
    50	The `PRE-BOUND SETUP ANSWERS:` block is a structured marker the dispatched AI parses out of the prompt body. It allows callers to pre-bind setup field values without using individual `$ARGUMENTS` flags.
    51	
    52	Grammar (YAML-style key/value, one field per line):
    53	
    54	```
    55	PRE-BOUND SETUP ANSWERS:
    56	  <field_name>: <value>  # optional inline comment
    57	  <field_name>: <value>
    58	  ...
    59	```
    60	
    61	Rules:
    62	
    63	- The block opens with `PRE-BOUND SETUP ANSWERS:` (exact case-sensitive heading, followed by colon). Indentation MAY be inside a markdown fenced code block or inline in the prompt text.
    64	- Each field is `  <key>: <value>` indented two spaces, one per line.
    65	- Values are interpreted by the command's Default Resolution Table (§3). Field types and value enums are command-specific.
    66	- Comments after `#` on a value line are ignored.
    67	- Unknown fields produce a warning (do not abort), so callers may include forward-compatible fields.
    68	- Fields not specified fall back to: command-specific Default Resolution Table → command-specific default value → unresolved (triggers Tier 2 or Tier 3 per §1).
    69	- Malformed lines (e.g. missing `:`, malformed value type) emit a parse error naming the line. Known fields parsed before the error may still be used; remaining unresolved fields continue to Tier 2 or Tier 3.
    70	- A second `PRE-BOUND SETUP ANSWERS:` block in the same prompt body produces a duplicate-block error.
    71	
    72	The marker block applies ONLY under `:auto`. Under `:confirm`, the block is informational and does not skip the consolidated question prompt.
    73	
    74	---
    75	
    76	## §3. Default Resolution Table
    77	
    78	Every command MUST publish a Default Resolution Table in its §0 (after citing this contract). The table lists each setup field with the following columns:
    79	
    80	| Field | Required | Resolves Via | Default | Tier-2 Candidate |
    81	|-------|----------|--------------|---------|------------------|
    82	
    83	Column meanings:
    84	
    85	- **Field**: the field name (matches the schema in §2 and the question label in the legacy consolidated Q-block).
    86	- **Required**: `Y` (must be resolved before YAML load) or `N` (optional).
    87	- **Resolves Via**: ordered list of resolution sources, e.g. `flag → $ARGUMENTS` / `marker → PRE-BOUND` / `default → "<value>"` / `auto-detect from <other field>` / `requires-ask`.
    88	- **Default**: the documented default value when no flag, marker, or auto-detection applies. May be `none` (no default — Tier 2 or Tier 3 candidate).
    89	- **Tier-2 Candidate**: `Y` if a missing value can be resolved by ONE targeted question (per §1); `N` if absence triggers fail-fast (Tier 3).
    90	
    91	A field is a Tier-2 candidate only when ALL of:
    92	- No flag exists for it.
    93	- No marker is provided.
    94	- No sensible default exists.
    95	- The field is genuinely required (Required=`Y`).
    96	- A user choice is the only resolution path (ambiguity, not absence).
    97	
    98	---
    99	
   100	## §4. Tier 3 Fail-Fast Error Template
   101	
   102	When Tier 3 fires, the command emits this exact format and exits non-zero:
   103	
   104	```
   105	[ERROR] /<command>:auto — required inputs unresolved under autonomous mode:
   106	  - <field>: <why-unresolved>
   107	  - <field>: <why-unresolved>
   108	Resolution: provide via $ARGUMENTS flags, PRE-BOUND SETUP ANSWERS: block, or switch to :confirm mode for interactive setup.
   109	```
   110	
   111	Rules:
   112	
   113	- Replace `<command>` with the canonical command name (e.g. `spec_kit:deep-review`).
   114	- One bulleted line per unresolved required field.
   115	- `<why-unresolved>` is one short phrase: "missing — no flag, no marker, no default" or "ambiguous — Tier 2 received no answer (stdin closed)".
   116	- Final line cites the three resolution paths verbatim.
   117	- Do NOT load the YAML workflow.
   118	- Do NOT emit setup questions in Tier 3.
   119	- Exit code: non-zero (1 is the convention).
   120	
   121	---
   122	
   123	## §5. `:confirm` Invariance
   124	
   125	The `:confirm` mode (interactive, with full consolidated Q-block) is unaffected by this contract. Commands MUST preserve their existing `:confirm` behavior exactly. The contract applies ONLY when `execution_mode = AUTONOMOUS` (from `:auto` suffix or explicit `--mode=AUTONOMOUS` flag).
   126	
   127	Test invariant: a `:confirm` dispatch against any contract-adopting command MUST emit the original consolidated Q-block (Q0..Qn). Regression-check this per command after migration.
   128	
   129	---
   130	
   131	## §6. Verification Protocol
   132	
   133	Each contract-adopting command requires four verification traces (dry-run mental dispatch traces against the command's §0):
   134	
   135	### Trace A — Tier 1 pass
   136	Dispatch with all required inputs resolvable (flags + markers + defaults). Expected: STATUS PASSED, YAML loaded, no question emitted.
   137	
   138	### Trace B — Tier 2 targeted ask
   139	Dispatch with exactly one ambiguous required field. Expected: ONE narrow question naming only that field; NEVER the full consolidated block.
   140	
   141	### Trace C — Tier 3 fail fast
   142	Dispatch with one or more truly missing required inputs (and stdin closed in non-interactive runtimes). Expected: error format from §4, exit non-zero, no YAML load.
   143	
   144	### Trace D — `:confirm` regression
   145	Dispatch with `:confirm` suffix and any inputs. Expected: existing full consolidated Q-block emitted.
   146	
   147	Live verification (when feasible) extends the dry-run traces with actual non-interactive dispatches (codex `exec </dev/null`, opencode `run --pure ... </dev/null`, claude `--print`) capturing transcripts as evidence. Live verification confirms the contract works under real runtime stdin-closure conditions.
   148	
   149	Evidence schema (one file per dispatch):
   150	- Command invocation verbatim
   151	- Full transcript
   152	- Verdict footer: PASS / PARTIAL / FAIL / SKIP
   153	- Optional: timing, model, runtime gotchas observed
   154	
   155	Stored under `<packet>/evidence/<command-slug>-<trace>.txt`.
   156	
   157	---
   158	
   159	## §7. Adoption Checklist
   160	
   161	For each command adopting this contract, the §0 of the command markdown:
   162	
   163	- [ ] Adds a one-line citation: `Setup contract: see references/workflows/auto_mode_contract.md`
   164	- [ ] Provides its own per-field Default Resolution Table (§3) listing every Q-block field with the four columns
   165	- [ ] Provides its own `PRE-BOUND SETUP ANSWERS:` field list (one row per setup field, matching the Default Resolution Table)
   166	- [ ] Documents any command-specific Tier-2 ordering rule (e.g. "ask review_target_type before spec_folder")
   167	- [ ] Updates frontmatter `argument-hint` to reference the new bypass capability
   168	- [ ] Preserves the existing `:confirm` consolidated Q-block path untouched
   169	- [ ] Authors §0 dry-run traces (A/B/C/D) and stores them under the adopting packet's `evidence/`
   170	
   171	Commands that have adopted this contract:
   172	
   173	- `/spec_kit:deep-review` (prototype) — see `.../103/001-deep-review-three-tier-setup/`
   174	- (to be appended as `.../103/002-...` rolls out)
   175	
   176	---
   177	
   178	## §8. Out of Scope
   179	
   180	- Commands without paired YAML workflows (`/improve:prompt`, `agent_router`, etc.) — they have no setup-phase surface where the contract applies.

exec
/bin/zsh -lc "sed -n '220,320p' .opencode/commands/spec_kit/deep-research.md" in /Users/michelkerkmeester/MEGA/Development/Code_Environment/Public
 succeeded in 0ms:
  workflow: iterative_loop
  compliance: MANDATORY
  execution: autonomous_or_interactive
  validation: convergence_detection
```

---

## 1. PURPOSE

Run an iterative loop for deep research: Initialize state under `{artifact_dir}` (resolved via `resolveArtifactRoot()` — root specs use `{spec_folder}/research/`; child phases and sub-phases use `{spec_folder}/research/{packet}-pt-{NN}/`), dispatch `@deep-research` agent per iteration, evaluate convergence, synthesize findings into `{artifact_dir}/research.md`, and emit `{artifact_dir}/resource-map.md` at convergence unless `--no-resource-map` disables it. Use when deep investigation requiring multiple rounds of discovery.

---

## 2. CONTRACT

**Inputs:** `$ARGUMENTS` -- Research topic with optional flags and mode suffix
**Outputs:** Spec folder with `{artifact_dir}/` packet (`{spec_folder}/research/` for root specs or `{spec_folder}/research/{packet}-pt-{NN}/` for nested phases), `research.md`, optional `resource-map.md`, state files, and `STATUS=<OK|FAIL|CANCELLED>`

---

## 3. WORKFLOW OVERVIEW

| Phase | Name | Purpose | Outputs |
|-------|------|---------|---------|
| Init | Initialize | Create config, strategy (with research charter), state files | State files in `research/` |
| Loop | Iterate | Dispatch @deep-research agent, evaluate convergence + quality guards, generate dashboard | iteration-NNN.md files, deep-research-dashboard.md |
| Synth | Synthesize | Emit `research/resource-map.md` and compile final research/research.md | research/resource-map.md, research/research.md (17 sections) |
| Save | Preserve | Refresh continuity update in canonical spec docs | canonical spec doc updated via `generate-context.js` |

### Execution Modes

| Mode | Invocation | Behavior |
|------|-----------|----------|
| `:auto` | `/spec_kit:deep-research:auto "topic"` | All iterations without approval |
| `:confirm` | `/spec_kit:deep-research:confirm "topic"` | Multi-gate review at setup, iteration, and synthesis |
| (default) | `/spec_kit:deep-research "topic"` | Ask user to choose mode during setup |

---

## 4. INSTRUCTIONS

After setup phase passes, load and execute the appropriate YAML prompt based on execution_mode:

- **AUTONOMOUS**: `.opencode/commands/spec_kit/assets/spec_kit_deep-research_auto.yaml`
- **INTERACTIVE**: `.opencode/commands/spec_kit/assets/spec_kit_deep-research_confirm.yaml`

The YAML contains the full loop workflow: initialization, iteration dispatch, convergence detection, synthesis, and memory save.

---

## 5. OUTPUT FORMATS

**Success:**
```
Deep research complete.
Iterations: [N] | Stop reason: [converged|max_iterations|all_answered]
Artifacts: research/research.md, research/resource-map.md (unless `--no-resource-map`), [N] iteration files, continuity update in canonical spec docs refreshed
Ready for: /spec_kit:plan [feature-description]
STATUS=OK PATH=[spec-folder-path]
```

**Failure:**
```
Error: [error description]  Phase: [phase name]
STATUS=FAIL ERROR="[message]"
```

---

## 6. MEMORY INTEGRATION

### Before Starting
- `memory_context({ input: topic, intent: "understand" })` -- Load prior research
- Inject results into strategy.md "Known Context" section

### Code Context Bootstrap
- Use CocoIndex (`mcp__cocoindex_code__search`) to find relevant code examples before starting research
- Query: 2-5 word concept descriptions related to the research topic
- Inject discovered code patterns into strategy.md "Known Context" section alongside memory findings

### After Completing
- `node .opencode/skills/system-spec-kit/scripts/dist/memory/generate-context.js /tmp/save-context-data-<session-id>.json [spec-folder]`
- Verify that the canonical save routed continuity into the expected packet doc (decision-record.md / implementation-summary.md / handover.md)

### Anchor Tags (Automatic)
`ANCHOR:deep-research-[topic]`, `ANCHOR:findings`, `ANCHOR:convergence-report`

---

## 7. SKILL REFERENCE

Full protocol documentation: `.opencode/skills/deep-research/SKILL.md`

Key references:
- Loop protocol: `deep-research/references/loop_protocol.md`
- Spec check protocol: `deep-research/references/spec_check_protocol.md`
- State formats: `deep-research/references/state_format.md`
- Convergence: `deep-research/references/convergence.md`
- Quick reference: `deep-research/references/quick_reference.md`


codex
Citation present: yes, line 54

Section zero Tier reached: 1

Setup question emitted: no

Resolved field map:
- `research_topic`: `WebSocket reconnection strategies`
- `spec_folder`: `.opencode/specs/103-example/001-research/`
- `execution_mode`: `AUTONOMOUS`
- `maxIterations`: `10`
- `convergenceThreshold`: `0.05`
- `executor`: `native`
- `executor_model`: `""`
- `executor_reasoning`: `""`
- `executor_service_tier`: `""`
- `executor_timeout`: `900`
- `resource_map_emit`: `true`

STATUS value: PASSED

Verdict: PASS

Tier-1 walkthrough: `:auto` binds `execution_mode = AUTONOMOUS`; the `PRE-BOUND SETUP ANSWERS:` block is valid per the cited contract grammar; all required fields are present from the marker or suffix; optional executor/resource-map fields are also bound. No required field remains ambiguous or missing, so Tier 2 and Tier 3 are not reached. I did not load the paired YAML workflow or write files.
hook: Stop
hook: Stop Completed
tokens used
48,639
Citation present: yes, line 54

Section zero Tier reached: 1

Setup question emitted: no

Resolved field map:
- `research_topic`: `WebSocket reconnection strategies`
- `spec_folder`: `.opencode/specs/103-example/001-research/`
- `execution_mode`: `AUTONOMOUS`
- `maxIterations`: `10`
- `convergenceThreshold`: `0.05`
- `executor`: `native`
- `executor_model`: `""`
- `executor_reasoning`: `""`
- `executor_service_tier`: `""`
- `executor_timeout`: `900`
- `resource_map_emit`: `true`

STATUS value: PASSED

Verdict: PASS

Tier-1 walkthrough: `:auto` binds `execution_mode = AUTONOMOUS`; the `PRE-BOUND SETUP ANSWERS:` block is valid per the cited contract grammar; all required fields are present from the marker or suffix; optional executor/resource-map fields are also bound. No required field remains ambiguous or missing, so Tier 2 and Tier 3 are not reached. I did not load the paired YAML workflow or write files.


=== EXIT 0; WALL 37s ===
