[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71RDXG1GYKGTS1264033AKQ":3,"skill-same:01M71RDXG1GYKGTS1264033AKQ":107},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":31,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":6,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M71RDXG1GYKGTS1264033AKQ","autospec-define",null,"Use when the user wants to plan a feature — bootstrap repo if missing, brainstorm a design spec, decompose into linked GitHub issues, or split an existing spec into issues. Stops after Phase 3 and hands off to \u002Fautospec-run for autonomous implementation.","berlinguyinca\u002Fautospec","berlinguyinca","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F16364?v=4","01M71R7C0SWBG05FNHQE4XQ7Y3","Gert Wohlgemuth","01M71R7C1VY5K3Q715RNDDBVGQ",3,"MIT","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"autospec","define","autospec define","brainstorm","user","implementation","github","to plan","bootstrap","split","Existing","use","repo","for","bootstrap repo","run","plan","design spec","phase","design","2026-11-10 13:02:02",false,"---\nname: autospec-define\ndescription: Use when the user wants to plan a feature — bootstrap repo if missing, brainstorm a design spec, decompose into linked GitHub issues, or split an existing spec into issues. Stops after Phase 3 and hands off to \u002Fautospec-run for autonomous implementation.\n---\n\n# autospec-define workflow (harness-neutral)\n\nTake the following feature request and run the planning half of the autospec pipeline:\n**bootstrap repo (if missing) → investigate → design → spec → decomposed GitHub issues.** Stop after Phase 3; the implementation half is handed off to `\u002Fautospec-run`.\n\nIf the request asks to split, materialize, roadmap, decompose, or turn an\nalready-written spec into GitHub issues, use **Existing spec mode** below:\nselect a tracked `docs\u002Fspecs\u002F*.md` file, skip Phases 1-2, run Phase 3 and\nPhase 3.5 against that spec, then continue to the Phase 3 pre-impl gate.\n\nManage your own context — never exceed 60%. Delegate to subagents whenever your harness supports it; do not investigate, write code, or design directly in the main conversation when a subagent can do it.\n\n\u003C!-- autospec-block:startup-self-update SKILL_NAME=autospec-define -->\n\n## Self-update mode\n\nIf the feature-request argument matches the regex `^\\s*update\\s*$` (case-insensitive, whitespace-padded), this skill enters self-update mode and does not run the normal pipeline:\n\n1. **Detect harness** by checking which install path exists for this skill:\n   - Claude Code: `~\u002F.claude\u002Fskills\u002Fautospec-define\u002FSKILL.md`\n   - OpenCode:    `~\u002F.config\u002Fopencode\u002Fagent\u002Fautospec-define.md`\n   - Codex CLI:   `~\u002F.codex\u002Fprompts\u002Fautospec-define.md`\n2. **Re-install the full autospec suite from `main`** by piping the canonical installer:\n   ```bash\n   curl -fsSL https:\u002F\u002Fraw.githubusercontent.com\u002Fberlinguyinca\u002Fautospec\u002Fmain\u002Fbootstrap.sh | bash -s -- --skill all --harness all --update\n   ```\n   Run this one-liner once; it refreshes all autospec skills across all harnesses.\n3. **Show the diff** between the prior installed file(s) and the freshly fetched copy (e.g. `diff \u003C(cat \u003Cprior>) \u003C(curl -fsSL ...SKILL.md)` or the equivalent recorded by the installer).\n4. **Stop.** Do not enter Phase 0 \u002F Phase 1 \u002F any pipeline phase. Print the upgrade summary and return to the user.\n\nIf no install path is detected, print `Self-update: no installed copy of autospec-define found; run install.sh first.` and exit.\n\n## Feature request\n\n{FEATURE_DESCRIPTION}\n\n---\n\n## Existing spec mode\n\nUse this mode when the request asks to split, materialize, roadmap, decompose,\nor turn an existing spec into GitHub issues. Examples:\n`split existing spec`, `split latest spec`, `turn this spec into GitHub issues`,\n`roadmap docs\u002Fspecs\u002F2026-05-01-example-design.md`, or\n`materialize the newest spec`.\n\nDo not run Phase 1 or Phase 2 in this mode. The design already exists; this\nmode is a shortcut into Phase 3 using the same issue decomposition and Phase 3.5\nclassification path as the normal pipeline.\n\n1. **Verify repo.** Run the Phase 0 repo probes. If the current directory is\n   not a git repo with a GitHub remote, use Phase 0 bootstrap before selecting\n   a spec.\n2. **Resolve candidate specs.**\n   - If the request contains an explicit `docs\u002Fspecs\u002F*.md` path, use that file.\n   - Otherwise list tracked and untracked local files matching `docs\u002Fspecs\u002F*.md`.\n   - Sort by ISO date in the filename (`YYYY-MM-DD-...`) descending. For files\n     without a date prefix, sort after dated files by filesystem modified time.\n   - The first item is the default \"newest\" spec.\n3. **Ask on ambiguity.**\n   - If zero specs exist, stop with: `No docs\u002Fspecs\u002F*.md files found. Create or\n     point me at a spec before running existing spec mode.`\n   - If exactly one spec exists and no explicit path was provided, use it.\n   - If more than one spec exists and no explicit path was provided, ask the user\n     to confirm the default newest spec or choose another path. Show at most the\n     five newest candidates with relative paths. Do not file issues until the\n     user answers.\n4. **Verify selected spec is filed.**\n   - The selected path must be under `docs\u002Fspecs\u002F` and end in `.md`.\n   - This mode accepts an optional `--base \u003Cbranch>` flag (default `main`). The\n     base names the branch the spec must already be tracked on before Phase 3,\n     so child issues can cite a stable GitHub URL. With no flag the base is\n     `main` and every check below is byte-identical to the current behavior;\n     explore passes a sandbox branch as `--base \u003Csandbox-branch>`.\n   - The selected file must be tracked on `\u003Cbase>` before Phase 3. Verify with:\n     `git fetch origin` and `git cat-file -e \u003Cbase>:\u003Cspec-path>`.\n   - If the selected file is missing from `\u003Cbase>`, stop and tell the user:\n     `Selected spec is not on \u003Cbase> yet: \u003Cspec-path>. Land the spec first,\n     or run normal \u002Fautospec-define so Phase 2 can create and merge the spec PR.`\n   - Guardrail: under a non-main `--base \u003Cbranch>`, no PR or issue targets\n     `main` — child issues link the `\u003Cbase>` blob and the decomposer files\n     against `\u003Cbase>` only.\n5. **Continue at Phase 3.** Capture `{selected_spec_path}` and its GitHub URL as\n   `https:\u002F\u002Fgithub.com\u002F{repo}\u002Fblob\u002F\u003Cbase>\u002F{selected_spec_path}` (with the default\n   base this is `...\u002Fblob\u002Fmain\u002F...`, byte-unchanged). Run Phase 3 and\n   Phase 3.5 using that selected spec. Then proceed to the existing Phase 3\n   pre-impl gate.\n\n## Required capabilities & harness adapter\n\nThis workflow assumes five capabilities. Map each one to your harness's actual tool. If a capability is missing, use the listed fallback.\n\n| Capability                  | Claude Code                          | OpenCode                                 | Codex CLI                                | Fallback if missing                                |\n|-----------------------------|--------------------------------------|------------------------------------------|------------------------------------------|----------------------------------------------------|\n| Read-only codebase research | `Agent` (subagent_type=Explore)      | `task` agent in read-only mode           | `apply_patch` read-only \u002F shell `grep`   | Do the search in-thread with `rg`\u002F`grep`           |\n| Foreground delegation       | `Agent` (subagent_type=general-purpose) | nested `task` agent, await output     | spawn nested CLI session                 | Do the work in-thread (more context cost)          |\n| Background delegation       | `Agent` with `run_in_background: true` | detached `task` agent                  | nohup'd CLI session writing to a logfile | Run the monitor in a separate terminal\u002Ftmux pane   |\n| Ask the user a question     | `AskUserQuestion`                    | inline prompt                            | inline prompt                            | Ask in the response and wait for the next turn     |\n| Self-paced future wakeup    | `ScheduleWakeup` inside a `\u002Floop`    | a recurring `task` or local `cron`       | local `cron`\u002F`launchd` calling the CLI   | The user runs a status-update prompt manually      |\n| Subagent model tier         | Tier A: `opus` + `ultrathink`; Tier B: `sonnet` + medium thinking | Tier A: top `task` model + high reasoning; Tier B: smaller-tier `task` + medium reasoning | Tier A: top GPT + `reasoning_effort=high`; Tier B: current spark\u002Fcost-optimized Codex + `reasoning_effort=medium` | Honor the per-phase tier mapping in AGENTS.md; retry the same subagent UP on unavailability |\n\u003C!-- autospec-block:harness-adapter-core -->\n\n**Persistent project notes**: write durable preferences to **`AGENTS.md`** in the repo root — this is the de-facto standard recognized by Claude Code (also reads `CLAUDE.md`), OpenCode, and Codex. If your harness has its own private memory (e.g. Claude Code's `~\u002F.claude\u002F...\u002Fmemory\u002F`), mirror the same content there. Per AGENTS.md, subagent dispatches use a **two-tier policy**: Tier A (top model + extended thinking) for spec work (research, decompose, review\u002Flabel); Tier B (cheaper model + medium thinking) for implementation work (Phase 4 implementer + LGTM review — not used by this skill). The orchestrator keeps the user's invoked model. Fall back UP the tier on quota\u002Fcapacity or other unavailability by retrying the same subagent with the stronger tier while preserving parent context.\n\n---\n\n## Harness detection (run once at skill start, before Phase 0)\n\nDetect your harness by checking available tools before any phase:\n\n1. **Claude Code** — the `Agent` tool with a `subagent_type` parameter is available.\n   - `TIER_A` = `opus` + `ultrathink`  (the alias, which resolves to the current Claude Opus generation)\n   - `TIER_B` = `sonnet`               (the alias, which resolves to the current Claude Sonnet generation)\n\n2. **OpenCode** — a `task` tool with model\u002Ftier configuration is available (no `subagent_type`).\n   - `TIER_A` = top-tier task model + high reasoning\n   - `TIER_B` = smaller-tier task model + medium reasoning\n\n3. **Codex CLI** — neither `Agent` nor a configurable `task` tool is available; `apply_patch` is the primary edit tool.\n   - `TIER_A` = current top GPT model + `reasoning_effort=high`\n   - `TIER_B` = the spark \u002F cost-optimized variant of the configured model when one exists, else the configured model + `reasoning_effort=medium`\n\n**Fallback rule:** If `TIER_B` is not available in your harness (model unknown, quota\u002Fcapacity failure, authorization failure, or tool call returns an error for that model), silently retry the same subagent dispatch with `TIER_A`. Preserve the parent context on retry; for Codex native subagents, fork\u002Finherit the current conversation context and use the latest top GPT model instead of moving the work into the main session. Never ask the user.\n\nHold `TIER_A` and `TIER_B` for the entire skill run. Every \"Tier A\" and \"Tier B\" reference below resolves to these harness-specific values.\n\n## Relevant memory injection (run-start, once)\n\nBefore executing the main pipeline phases, call the injector to surface relevant saved lessons:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Finject-relevant-memory.sh\" \\\n  --context \"\u003Cskill-relevant keywords from request\u002Fissue\u002Fspec>\" \\\n  --top-k 5\n```\n\nPrepend the output block (if non-empty) to your working context. This surfaces lessons like\n`feedback_bash_return_trap_leak.md` that prevent re-occurrence of known pitfalls.\n\n## Phase 0 — Bootstrap repo (if missing)\n\nVerify `gh auth status` is authenticated. If not, ask the user to run `gh auth login` and stop until they confirm.\n\nProbe the working directory:\n```bash\ngit rev-parse --is-inside-work-tree 2>\u002Fdev\u002Fnull\ngit remote get-url origin 2>\u002Fdev\u002Fnull   # must contain github.com\n```\n\nIf **either** check fails — no git repo, or no GitHub remote — bootstrap a new repo:\n\n1. **Resolve the language.** Write the feature description to a temp file and call `${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fclassify-language.sh \u003Ctemp-file> --json`. Parse the JSON: `lang`, `source`, `rationale`, `deterministic`, `confidence`. If `lang` is not `unknown` and `deterministic` is `true`, the language is unambiguous — pre-fill it in the bootstrap question below. If `lang` is `unknown` or `deterministic` is `false`, ask the operator which language to use. If `classify-language.sh` is missing or exits non-zero, fail closed: do not bootstrap; tell the user the classifier is unavailable and stop.\n\n2. **Suggest a name.** Slugify the feature description: lowercase, hyphens, drop stop-words, prefix with the resolved language if present (e.g. `go` → `go-tui-x`; `python` → `py-ml-y`). Offer 1–2 candidates.\n\n3. **Ask the user once** (single interactive question; combine the three sub-questions if your harness supports it, otherwise ask sequentially):\n   - **Name** (your top suggestion as default, pre-filled with the resolved language prefix).\n   - **Visibility**: `private` | `public` (default: private).\n   - **Owner**: enumerate via `gh org list`; default to the user's personal account.\n\n4. **Initialize locally**:\n   - If `.git` is absent: `git init -b main`.\n   - Write a `.gitignore` matching the resolved language (Go: `bin\u002F vendor\u002F *.exe *.test`; Node: `node_modules\u002F dist\u002F .next\u002F .env*`; Python: `__pycache__\u002F .venv\u002F *.egg-info\u002F build\u002F dist\u002F`; Rust: `target\u002F`; mixed\u002Funknown: skip).\n   - Write a one-line `README.md` containing the feature description.\n   - Write a starter `AGENTS.md` listing the project's coding standards (TDD non-negotiable, no DB mocks, conventional commits, branch-per-issue, no force-push) — this is the source of truth every agent reads.\n   - `git add -A && git commit -m \"chore: initial scaffold\"`.\n\n5. **Create the remote and push**:\n   ```bash\n   gh repo create \u003Cowner>\u002F\u003Cname> --\u003Cprivate|public> --source=. --remote=origin --push\n   ```\n\n6. **Verify and register**: first run `gh repo view \u003Cowner>\u002F\u003Cname> --json url,defaultBranchRef`.\n   Only after that succeeds, capture the exact slug and record verified creation evidence:\n   ```bash\n   REPO=\"\u003Cowner>\u002F\u003Cname>\"\n   SPAWNED_FROM=\"${SOURCE_SPEC_URL:-${AUTOSPEC_RUN_ID:-bootstrap:$REPO}}\"\n   REGISTRATION_JSON=$(\"${AUTOSPEC_BIN:-autospec}\" project onboard --repo-dir \"$PWD\" --repo \"$REPO\" --spawned-from \"$SPAWNED_FROM\") || {\n     printf '%s\\n' 'ERROR: managed Project repository registration failed before durable admission' >&2\n     exit 1\n   }\n   case \"$(printf '%s' \"$REGISTRATION_JSON\" | jq -r '.outcome \u002F\u002F empty')\" in\n     reconciled) ;;\n     journaled_projection_pending)\n       printf '%s\\n' 'WARNING: managed Project repository projection is durably journaled and pending' >&2 ;;\n     *) printf '%s\\n' 'ERROR: managed Project repository registration returned no supported typed outcome' >&2; exit 1 ;;\n   esac\n   ```\n   Never register when read-back fails. A typed pending outcome does not roll\n   back or recreate the verified repository; reconciliation retries the\n   journaled projection. Propagate every hard registration failure. Capture\n   `\u003Cowner>\u002F\u003Cname>` as `{repo}` for every later phase.\n\nIf a repo already exists (cwd is in a git tree with a `github.com:\u003Cowner>\u002F\u003Cname>` remote), capture that as `{repo}` and skip the bootstrap.\n\n## Phase 1 — Investigate (delegate)\n\nSpawn a **read-only research subagent** to map relevant files, schema, services. Get back a 300-word summary with file paths and line numbers. Do NOT read files directly from the main thread.\n\n> **Model tier:** `TIER_A` (spec work) — top model with extended thinking; resolved at startup.\n\n> **Phase 1 bounded-context rule.** Launch the research subagent with a fresh,\n> bounded handoff. Do NOT fork, inherit, or compact the full parent conversation into Phase 1. The handoff may contain only: the feature request,\n> repo slug\u002Froot, a short git status summary, relevant memory-injection output,\n> explicit user-mentioned paths\u002Fsurfaces, and these Phase 1 instructions. For\n> Codex native subagents, set `fork_context=false`; for Claude\u002FOpenCode, use the\n> equivalent fresh\u002Fno-history task mode when available. If the harness cannot\n> start a fresh subagent, or returns a context window or remote compact failure,\n> do not retry with inherited context. Fall back to bounded local read-only `rg`\u002Ffile-read investigation, label the result as `Phase 1 fallback`, and\n> continue to Phase 2 with the best evidence gathered.\n\nIf the feature touches a remote system (DB, server, S3), run a real query against the actual data to confirm the problem statement before designing. Surface the concrete numbers in the design.\n\nClassify the request before returning the investigation. Select\n`feature_profile: security_database` when it combines a database or remote data\nboundary with security, authorization, destructive-operation, confidentiality,\nor production-availability constraints. For that profile, return an evidence\nledger whose entries are explicitly `verified`, `assumed`, or `blocking`; name\nthe source for every verified fact and never execute a command merely because\nit appears in evidence text. All other requests use the **ordinary profile** and\ncontinue through the existing flow without security-only sections.\n\nFor a freshly-bootstrapped empty repo, Phase 1 may be a no-op — proceed to Phase 2.\n\n## Phase 2 — Brainstorm + design\n\n> **Spec quality is the bottleneck.** Phase 2's output drives every downstream cycle's cost; if you care about spec quality, invoke this skill with your top-tier model (Claude Code: `claude-code --model opus`; Codex: top GPT). Phase 2 itself runs in the orchestrator (no subagent dispatch) — your invocation model IS the spec model. Subagents in Phases 1, 3, 3.5 follow this lead by selecting Tier A; Phase 4 implementation work uses Tier B. See AGENTS.md.\n\n### Security\u002Fdatabase profile contract\n\nWhen Phase 1 selected `feature_profile: security_database`, the design must\ninclude evidence and open assumptions, explicit priority ordering, threats,\ncontrols with owner and authority, negative tests, blocking prerequisites,\ndependency order, atomic contracts, residual risks, and acceptance criteria.\nControls whose failure consequence is data loss or unauthorized disclosure must\nbe owned authoritatively by the database\u002Fplatform layer, never only by an AST or\napplication check.\n\nWrite `.autospec\u002Fspec-artifacts\u002F\u003Cslug>.security-database.yml` using schema\n`autospec.security_database.v1`. Include provisional issue keys and complete\nProduces\u002FConsumes\u002FCovers, evidence, prerequisite, control, negative-test,\ndependency, and atomic-group mappings before GitHub issue numbers exist. Run\n`python3 \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fvalidate-security-artifact.py\" \u003Cartifact>`\nbefore opening the spec PR. Any finding, including\n`AUTHORITATIVE_CONTROL_MISSING`, blocks the PR; repair the design and artifact,\nnever fall back to free-form generation. The ordinary profile does not create\nor validate this sidecar. Commit the Markdown spec and sidecar together; use\n`git add -f` for the sidecar if the target repository ignores `.autospec\u002F`.\nEvery prerequisite must declare a non-empty `gates` list and every gated issue\nmust repeat that prerequisite ID. Every control must have an issue owner. Each\natomic-group member must appear in exactly one issue's `produces` list, with all\nmembers of that group owned by the same issue.\n\n## Team personality selection\n\nBefore the Architecture question, decide what kind of team should solve this\nrequest. Infer the team personality from the user's request, Phase 1 evidence,\nrepository labels, relevant memory files, and past specs under `docs\u002Fspecs\u002F`.\nThe goal is to shape the design as a fitting team would reason about it, not to\ntreat every request as a generic \"fix this bug\" task.\n\nWrite a **Team personality** section into the design spec with:\n- the selected team name,\n- 3-6 roles,\n- why this team fits the request,\n- the risks this team is expected to notice,\n- any team emphasis that should carry into child issues.\n\nAlso write a **Review counter-team** subsection. It must be a different\nemphasis from the implementation team and should challenge likely blind spots,\nnot duplicate the same perspective. Include:\n- the counter-team name,\n- 2-5 roles,\n- which assumptions or failure modes this team should challenge,\n- how review should stay inside the issue scope while applying that lens.\n\nIf confidence is low, ask the user explicitly: `What kind of team should solve this problem?`\nOffer exactly these five starter combinations:\n1. **Core product engineering** — product manager, architect, backend developer, frontend developer, test engineer.\n2. **Reliability\u002Fbackend** — backend developer, platform engineer, sysadmin\u002FSRE, database engineer, security advisor.\n3. **Frontend\u002Fproduct** — frontend developer, UX designer, accessibility reviewer, API\u002Fbackend developer, QA engineer.\n4. **Security-sensitive** — security advisor, architect, backend developer, platform engineer, test engineer.\n5. **Legacy\u002Frefactor** — architect, maintainer, backend\u002Ffrontend developer as needed, test engineer, documentation owner.\n\nIf one option is clearly best, proceed without asking and record the confidence\nand evidence in the spec. If two or more options are plausible and would change\nthe architecture, tests, or decomposition, ask before continuing.\n\nDerive the Review counter-team after choosing the implementation team:\n- Frontend\u002Fproduct implementation teams should be reviewed by accessibility, API contract, and QA perspectives.\n- Reliability\u002Fbackend implementation teams should be reviewed by security, operations, and data-integrity perspectives.\n- Security-sensitive implementation teams should be reviewed by product\u002FUX, maintainer, and test perspectives.\n- Legacy\u002Frefactor implementation teams should be reviewed by maintainer, regression-test, and architecture perspectives.\n- Core product engineering implementation teams should be reviewed by security, operations, accessibility, and maintainability perspectives.\n\nRun a structured brainstorm — one question at a time, get explicit approval after each section:\n\n1. **Architecture** — where does new code live, what existing patterns does it follow.\n2. **Interactivity \u002F API shape** — how does the user\u002Fcaller drive it; commands, keys, endpoints, fields.\n3. **Data model** — types, columns, persistence boundary.\n4. **Error handling** — failure modes, recovery, user-visible signals.\n5. **Testing** — unit \u002F integration \u002F e2e split, real services vs anything else (rule per AGENTS.md: real services). For app\u002FUI work, include an `autospec-qa` revalidation plan that maps each spec requirement to running-app checks for text inputs, validation, selects\u002Fdropdowns, buttons, forms, API effects, accessibility, responsive behavior, negative paths, regenerated automated tests, proof artifacts, reliability contract, control intent ledger, no-mock minimum coverage, mutation\u002Fbreakage proof, duplicate-code review, post-merge canary, new-code intent checks, artifact freshness, evidence provenance, console\u002Fnetwork error gates, spec contradiction detection, data lifecycle proof, observability, flake quarantine, legacy removal\u002Fspec cleanup, and reliability exhaustion loop.\n\nWrite the agreed design to `docs\u002Fspecs\u002FYYYY-MM-DD-\u003Ctopic>-design.md`, then run a **fresh-eyes self-review** before any issue is filed:\n\n1. **Placeholders** — grep the spec for `TBD`, `TODO`, `later`, `fixme`, `tbd`, `XXX`. Fill in or surface to the operator as an open question; do not file issues against an undecided spec.\n2. **Internal consistency** — re-read each section in order. Do any two sections contradict each other? Does the architecture match the feature descriptions? Fix inline.\n3. **Ambiguity** — could any requirement be interpreted two different ways? Pick one and make it explicit in the spec text.\n4. **Scope** — is this focused enough for a single multi-issue pipeline, or does it span independent subsystems that each need their own `\u002Fautospec-define` run? If the latter, stop and ask the operator to decompose before proceeding.\n5. **Critical improvement** — ask: \"What else could fail even if this spec and its obvious tests pass, and how could this be better?\" Add the highest-risk answer to Testing, Acceptance Criteria, or Review counter-team. For app\u002FUI work, explicitly consider mocked-vs-deployed behavior, backend fallbacks, user-visible outcomes, and no-mock smoke coverage.\n\nThe spec must be implementable end-to-end by an agent reading only the spec.\n\n### Epistemic gates (issue #3718)\n\nSeventy classified incidents reduced to five shapes, and all five are cheap and\nmechanical — none require a larger model. The spec must carry these gates so\nevery downstream implementer and reviewer applies them:\n\n1. **Name the producer of every value.** For each value a gate or test reads,\n   the spec names the process or step that computes it, and the gate must\n   verify the value is current and complete, not merely present.\n2. **State what the gate examined, not just its verdict.** Each \"pass\" must\n   name the inputs, version\u002Frevision, and scope it actually checked. A \"passed\"\n   verdict with nothing named is a defect.\n3. **Re-baseline immediately before judging.** The gate must observe the\n   system in its current state at decision time, not rely on a measurement\n   taken earlier or a value another step recorded.\n4. **Declare the shared foundation.** When one input feeds several gates or\n   tests, the spec names it as shared state and requires every consumer to read\n   the same instance, so the consumers cannot diverge silently.\n5. **Derive limits from the real constraint, not from observed history.**\n   Thresholds, caps, and budgets are computed from the resource or time budget\n   they protect, not tuned to fit past runs. An observed value is never a\n   specification.\n\n### Diagnostic assistant\n\nWhen the request describes a chat or assistant that answers questions about\ndomain entities backed by real data, such as jobs, samples, logs, or incidents,\nrequire the design spec to capture the current page and entity scope before\nopening a full-page assistant view. The assistant must preserve that scope\nacross pop-out and full-page routes so a navigation change cannot silently\nwiden or replace the entity being diagnosed.\n\nRequire a server-side session runner to admit the user's input together with\ncaptured context, plan registered tool calls, execute them, settle sanitized\nevidence, and only then call the provider, even for a small in-repo\nimplementation. Store context-source metadata alongside every assistant turn,\ncovering the page, entity, job, and sample scope used for that turn so the\nanswer's diagnostic boundary remains explainable.\n\nRequire a backend tool registry that defines named tools, input and output\nschemas, authorization rules, a bounded per-turn call cap, and how sanitized\ntool evidence is injected into the final provider prompt. Each typed tool\nregistry entry must declare a name, schema, execution mode, permission scope,\nand bounded output size. Separate\ndeterministic keyword-triggered tool plans from a bounded model-planned\ndiagnostic step; the model-planned step may run only when deterministic routing\nfinds no plan. Reject stale or unknown model-proposed tool calls before\nexecution, and enforce the bounded tool-call cap on every turn. Keep provider\nsecrets and all tool execution server-side; the frontend must never receive\nprovider keys or direct diagnostic tool access. When a question maps to a\nregistered tool, the final assistant answer must be grounded in tool evidence,\nnot retrieval citations alone.\n\nRequire the spec's Testing section to cover nested-context extraction,\ndeterministic intent-keyword coverage, scoped-entity diagnostics, and provider\nrefusal and fallback behavior.\n\n### Documentation visualization\n\nWhen the requested work creates or regenerates documentation, the design spec\nMUST require Mermaid diagrams and charts where acceptable. Add a concrete visual\nplan for queues, routers, state machines, data flow, control flow, algorithms,\narchitecture boundaries, timelines, ownership relationships, decision spaces,\nroadmaps, or metric trends whenever one of those structures exists in the target\nfeature. Select the Mermaid type that fits the explanation: flowchart, sequence\ndiagram, state diagram, class\u002Fentity diagram, Gantt, timeline, journey, quadrant\nchart, gitGraph, mindmap, block, architecture, Sankey, XY, pie, kanban, or\nanother Mermaid-supported diagram type. Prefer Mermaid blocks in Markdown for\nreviewer-visible explanations; use `docs\u002Fassets\u002Fdiagrams\u002F` only when a generated\nasset is needed outside a Markdown page. If no diagram is useful, the spec must\nstate `Mermaid: not applicable` with the reason, so omission is explicit rather\nthan accidental.\n\n### Design cohesion\n\nWhen the requested work creates a website, app, dashboard, portal, or other UI,\nthe design spec MUST define app-wide design guidelines instead of letting each\npage improvise. Require page structure rules for the page header, constrained\ncontent width, section rhythm, and clear action hierarchy. Name the reusable\nprimitives the spec expects agents to reuse — forms, filter bars, segmented\ncontrols, tables, stat cards, empty states, charts, and navbars — and state\nwhere each primitive applies.\n\n**Artifact cleanup.** Require the spec to remove inline styles, duplicate class\nattributes, and legacy table or card chrome that bypasses the shared design\nsystem.\n\n**Positive design-system adoption.** Require the spec to name the project's\ncanonical primitives and classes for page shells, filter panels, segmented\ncontrols, date ranges, tables, empty states, and notices, then require agents to\nuse them instead of raw page-local layouts. The Acceptance Criteria MUST include\nan executable positive guard that fails when a raw toggle, date, or table\ncontrol does not use the project's design-system classes. Cross-reference the\n`autospec-qa` revalidation plan's **UI and UX Behavior** item and require it to\ncheck both artifact absence and canonical primitive presence.\n\nThe spec MUST flag full-document horizontal overflow as a defect unless the\noverflow is inside an intentional bounded scroller such as a table or chart\nviewport. Empty states must be visually lighter than data-rich panels so missing\ndata reads as lower emphasis, not as a primary card competing with real content.\nThe Testing section MUST include desktop and mobile visual QA that reports\nspacing, alignment, overflow, table density, toolbar grouping, and chart defaults\nas explicit checks.\n\n### Threat model, before mechanism (authentication, signing, encryption, credentials)\n\nWhen any requirement touches authentication, token or signature verification,\nencryption, or credential handling, the design spec MUST state the threat\nmodel before choosing a mechanism. State what property is needed, who the\nuntrusted party is, and which existing layer already provides it. If TLS to a\nnamed host, a process boundary, or an existing gate already establishes the\nproperty, say so and do not re-establish it. A token signature exists so a\nthird party handed a token by an untrusted caller can establish the issuer\nproduced it; a confidential client that receives tokens as the response body\nof a request it made, to a host it named, over a connection TLS already\nauthenticated has already had the property established, and adding JWKS\nfetch plus signature verification protects against nothing (identity can\ninstead come from the provider's `userinfo` endpoint). Only then choose a\nmechanism.\n\nThe same reasoning cuts the other way and the spec must state it too: if a\ntoken could ever arrive by another route — forwarded by a client, read from a\nheader — none of that holds and the token must be verified properly. That\nboundary belongs in a comment at the code, so a later reader cannot copy the\npattern somewhere it is wrong.\n\nIf this is a fresh repo, commit the spec to `main` directly (`git add docs\u002F... && git commit -m \"docs: \u003Ctopic> design spec\" && git push`) so subsequent issues can reference it as a tracked file. This is the ONLY exemption from `autospec-guarded-merge.sh` (T16 H3): a brand-new repo has no reviewed base and no PR to gate, and the commit is the spec document alone. Every later change merges through a PR and the guarded merge.\n\nFor an existing repo, land the spec via a short-lived PR so CI can validate it.\nThe spec commit happens in a temp worktree (`\u002Ftmp\u002Fwt-spec-\u003Cslug>`), never in the\nprimary checkout (see §D4 of `docs\u002Fspecs\u002F2026-06-03-worktree-guard-design.md` and\n`## Git hygiene (agents)` in `AGENTS.md`).\n\n\u003C!-- define-spec-pr:begin -->\n```bash\nSLUG=\"\u003Ctopic>\"\nBRANCH=\"feat\u002Fspec-${SLUG}\"\nWT=\"\u002Ftmp\u002Fwt-spec-${SLUG}\"\n\n# resolve → create → assert (D4 pattern)\nVERDICT=\"$(bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n    resolve-branch --branch \"$BRANCH\" --repo {repo})\"\nSTATE=\"$(printf '%s' \"$VERDICT\" | jq -r .state)\"\n\ncase \"$STATE\" in\n  open-pr)\n    PR_NUM=\"$(printf '%s' \"$VERDICT\" | jq -r .pr)\"\n    # Spec PR already open — validate CI + merge; skip re-commit.\n    gh pr checks \"$PR_NUM\" --repo {repo} --watch\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fautospec-guarded-merge.sh\" --pr \"$PR_NUM\" --repo {repo}\n    ;;\n  branch-only)\n    # Branch exists but no PR — adopt in a fresh worktree and continue.\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        create --branch \"$BRANCH\" --path \"$WT\" --adopt\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        assert  # MUST exit 0 before any edit\n    # Push + open PR then fall through to the wait\u002Fmerge step below.\n    git -C \"$WT\" push -u origin \"$BRANCH\"\n    gh pr create --base main --head \"$BRANCH\" --repo {repo} \\\n        --title \"docs: ${SLUG} design spec\" \\\n        --body \"Source spec: docs\u002Fspecs\u002F${SLUG}-design.md\"\n    gh pr checks --watch --repo {repo} \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fautospec-guarded-merge.sh\" --repo {repo} \\\n        --pr \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    git worktree remove \"$WT\" 2>\u002Fdev\u002Fnull || true\n    git worktree prune\n    ;;\n  fresh)\n    # Happy path: create a clean worktree, commit spec there, push, PR.\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        create --branch \"$BRANCH\" --path \"$WT\"\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        assert  # MUST exit 0 before any edit; non-zero → stop, restore auto-implement\n    cp \"docs\u002Fspecs\u002F${SLUG}-design.md\" \"$WT\u002Fdocs\u002Fspecs\u002F${SLUG}-design.md\"\n    git -C \"$WT\" add \"docs\u002Fspecs\u002F${SLUG}-design.md\"\n    git -C \"$WT\" commit -m \"docs: ${SLUG} design spec\"\n    git -C \"$WT\" push -u origin \"$BRANCH\"\n    gh pr create --base main --head \"$BRANCH\" --repo {repo} \\\n        --title \"docs: ${SLUG} design spec\" \\\n        --body \"Source spec: docs\u002Fspecs\u002F${SLUG}-design.md\"\n    gh pr checks --watch --repo {repo} \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    if [ \"${AUTOSPEC_NO_AUTOMERGE_SPEC:-0}\" != \"1\" ]; then\n        bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fautospec-guarded-merge.sh\" --repo {repo} \\\n            --pr \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    else\n        # Env var set — pause and ask user to merge before continuing.\n        echo \"AUTOSPEC_NO_AUTOMERGE_SPEC=1: merge the spec PR manually, then continue.\"\n    fi\n    git worktree remove \"$WT\" 2>\u002Fdev\u002Fnull || true\n    git worktree prune\n    ;;\nesac\n```\n\u003C!-- define-spec-pr:end -->\n\n6. Verify the spec is reachable at `https:\u002F\u002Fgithub.com\u002F{repo}\u002Fblob\u002Fmain\u002Fdocs\u002Fspecs\u002F...` before dispatching Phase 3.\n\n## Phase 3 — Decompose into linked GitHub issues (delegate)\n\nIf Existing spec mode is active, use `{selected_spec_path}` and its GitHub URL.\nOtherwise use the spec path written and merged in Phase 2.\n\nDispatch a **foreground subagent** with this prompt (substitute the spec path and `{repo}`):\n\n> **Model tier:** `TIER_A` (spec work) — top model with extended thinking; resolved at startup.\n>\n> Read the selected design spec at `\u003Cspec-path>` (`\u003Cspec-github-url>`) and split it into linked GitHub issues for {repo}.\n>\n> **Portfolio validation gate (security\u002Fdatabase only):** Load\n> `.autospec\u002Fspec-artifacts\u002F\u003Cslug>.security-database.yml`, update every planned\n> issue mapping after decomposition, and run\n> `python3 \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fvalidate-security-artifact.py\" \u003Cartifact>`.\n> Validation must pass before creating labels or calling `gh issue create`.\n\n> **Managed Project projection (mandatory):** Immediately after every successful issue\n> creation or issue edit, capture the verified URL as `ISSUE_URL` and run:\n> `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fproject-sync-issue.sh\" \"$ISSUE_URL\" \"$PWD\"`.\n> Never run this command in dry-run mode. If sync fails, print\n> `WARNING: managed Project sync failed for $ISSUE_URL` only for a verified journaled-pending outcome. A hard pre-journal failure stops decomposition after preserving the already-created issue; never create a replacement issue.\n> Then perform a Tier-A portfolio review: confirm every threat has a control,\n> every control has both a negative test and an issue owner, every required spec\n> section is covered, dependencies are acyclic, every prerequisite names its\n> gated issues, and atomic-group members resolve to one issue's `produces` list.\n> Do not weaken controls to make decomposition pass. An issue with an unresolved\n> prerequisite receives `autospec:blocked-prerequisite` instead of\n> `auto-implement`; it may be filed for visibility but is not queued. The\n> ordinary profile skips this gate.\n>\n> Create labels (idempotent with `--force`): `auto-implement` (#0e8a16), `autospec:blocked-prerequisite` (#d4c5f9), `epic` (#b60205), `autospec:v2-flow` (#0e8a16, description: \"Routes to absorbed-discipline Phase 4 implementer\"), plus any domain labels the spec calls for. Then create exactly N issues — first an EPIC umbrella (no `auto-implement` label, just `epic` + domain), then N-1 children carrying `auto-implement` and `autospec:v2-flow` unless the portfolio gate marked them blocked. The `autospec:v2-flow` label routes the child to the Phase 4 implementer that absorbs turbo's expand → implement → finalize → peer-review → evaluate discipline; children filed without it fall back to the legacy implementer path. After creating children, edit the umbrella body with a checklist linking them. Return JSON: `{umbrella, children:[…], labels_created:[…]}`. Use `gh` CLI only. Do NOT modify code. Do NOT push branches. Do NOT create PRs.\n>\n> Before drafting each candidate child issue, ask yourself three shell-structure questions (internal — do NOT write them into the issue body):\n>\n> - **Produces** — What new files, exports, or behavior does this issue create? If the answer is \"edits scattered across many existing files with no clear new contract\", reconsider the boundary.\n> - **Consumes** — What existing files or outputs of earlier issues does this depend on? Each named dependency on an earlier issue translates to a `Depends on issue #N` line in the body.\n> - **Covers** — Which sections of the spec does this issue implement? If multiple unrelated sections, split. If no spec section, reconsider whether the issue belongs.\n>\n> If two adjacent candidate issues have heavy mutual Consumes\u002FProduces overlap, they probably want to be merged. If one issue has more than ~5 named Produces, it probably wants to be split.\n>\n> Each child body must be a **self-contained mini-spec** sized for execution by a 32B-class local LLM, with these sections in order:\n>\n> - **Goal** — 1 sentence outcome.\n> - **Source spec** — `\u003Cspec-path>` + `\u003Cspec-github-url>` of the design doc this issue derives from.\n> - **Team personality** — copy the spec's selected team name, roles, and issue-relevant emphasis. If the selected spec lacks this section, infer it from the request, past specs, repository labels, and memory; if confidence is low, stop and ask the operator to choose from the five starter combinations in Phase 2 before filing issues.\n> - **Review counter-team** — copy the spec's counter-team name, roles, and issue-relevant blind spots to challenge. If the selected spec lacks this section, derive a different review emphasis from the Team personality and issue risk before filing.\n> - **Files to read first** — 3–7 entries. Each entry is one of: a path with **section anchors** (do not say \"read the whole spec\"), the closest existing-file analogue to mirror, the test file or fixture pattern to follow, or a dependency issue with a one-line summary so the LLM doesn't fetch its body. Bias toward sectional anchors over full files.\n> - **Local-LLM execution notes** — one-line context-window recommendation (`32k routine`, `64k stretch`, or `split into N subagents along \u003Ccriterion>` for issues exceeding ~30k tokens of staged context) and whether single-pass or subagent-split is recommended.\n> - **Implementation scope** and **Out of scope** as separate subsections (replaces the prior single \"Scope\" section).\n> - **Files touched** — machine-parseable: one repo-relative path per line, ≤3 logical units. The authoritative scope source the linter (`TOO_MANY_FILES`) and reviewers check; keep it in sync with the outline. A skill trio (`SKILL.md` + `codex\u002Fprompt.md` + `opencode\u002Fagent.md`) plus its derived `tests\u002Ffixtures\u002Fskill-goldens\u002F*.sha256` counts as ONE unit, so a single-trio edit may list all six paths and still be in-cap.\n> - **Implementation outline** — file paths + function signatures + data flow.\n> - **Tests required** — TDD per AGENTS.md, real services, no DB mocks, 80%+ coverage.\n> - **Acceptance criteria** — checkbox list `[ ]` only, no prose. Each item machine-checkable.\n> - **Verification** — split into a **Primary smoke test (inner loop)** with exactly one fast command, and **Operator\u002Ffull verification** listing the remaining commands.\n> - **Branch name** — `feat\u002F\u003Cslug>`.\n> - **Dependencies** — `Depends on issue #N` lines (parsed by the monitor).\n> - For `security_database` only: **Evidence consumed**, **Controls covered**, and **Prerequisites**, copied exactly from the validated artifact. Every prerequisite starts with `verified:` or the child is blocked.\n>\n> Never hand-author the final body. Populate structured YAML with\n> `files_touched`, `local_llm_notes`, `dependencies`, and conditional security\n> lists, then render it with\n> `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fgen-issue-skeleton.sh\" --input \u003Cissue.yml>`.\n> Pass the renderer output to the lint and safety checks.\n>\n> **Sizing caps (hard, per spec §3.4):**\n>\n> - **Body ≤400 words** including all sections.\n> - **Implementation outline ≤30 lines** (file paths + function signatures).\n> - **Files touched ≤3** per child issue, counted as distinct **logical units** — not raw paths. A multi-harness skill **trio** (`skills\u002F\u003Cx>\u002FSKILL.md` + `codex\u002Fprompt.md` + `opencode\u002Fagent.md`) plus its derived `tests\u002Ffixtures\u002Fskill-goldens\u002F\u003Cx>.*.sha256` is **ONE** logical unit: with `derive-trio.sh` shipped, the edit is \"edit `SKILL.md` → derive the mirrors with `derive-trio.sh --in-place skills\u002F\u003Cx>` → regenerate goldens with `gen-skill-goldens.sh \u003Cx>`\" in a **single commit**, so the cap must not split a trio's prose from its golden regen into separate issues. `lint-issue.sh` and `sizing-check.sh` collapse trio members to one unit and exclude the derived goldens — keep a trio edit (and its goldens) inside one child.\n> - If a candidate child would exceed any cap, split into a parent + child pair with a `Depends on` edge.\n> - The whole spec + a single child issue body must fit comfortably in a 60–120k context window.\n>\n> Self-check each issue against the caps **before** calling `gh issue create`. If a cap is violated and a split is not feasible, surface the issue inline (print the over-cap body to the operator) instead of filing it.\n>\n> **Pre-filing lint loop (adaptive, MAX_LINT_RETRIES=5):** For each candidate child body, before calling `gh issue create`, write the body to `\u002Ftmp\u002Fdraft-\u003Cslug>.md` and run `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Flint-issue.sh\" \u002Ftmp\u002Fdraft-\u003Cslug>.md`. If the exit code is non-zero, map each `RULE_ID: \u003Cdesc>` finding to an actionable directive using the table below, append all directives to the next generation prompt as cumulative context, and regenerate. Repeat up to `MAX_LINT_RETRIES=5` attempts. If attempt 5 still fails, print all 5 drafts plus accumulated findings inline and **skip** that child (do not file); continue to the next child. On pass (exit 0), proceed to the safety loop and only call `gh issue create` after safety passes.\n>\n> | Finding | Directive appended to next prompt |\n> |---|---|\n> | `GOAL_VAGUE: \"improve\" used without concrete object` | `AVOID: bare verb \\`improve\\` without naming a file path, command, label, or number in the same sentence.` |\n> | `GOAL_HEDGE: \"should probably\"` | `AVOID: hedging words \\`should\u002Fmight\u002Fcould try\u002Ftry to\\`. State the outcome flatly.` |\n> | `GOAL_NOT_ONE_SENTENCE: N terminals` | `REWRITE: Goal must be exactly one sentence ending with a single . ? or !` |\n> | `AC_PROSE: line N not a checkbox` | `FORMAT: every AC line must start with \\`- [ ] \\` followed by content.` |\n> | `AC_SUBJECTIVE: \"looks clean\"` | `AVOID: subjective adjectives \\`looks\u002Ffeels\u002Fseems\u002Fclean\u002Felegant\\` in AC items. Use a \\`grep\\`\u002F\\`test\\`\u002F\\`diff\\`\u002F\\`bats\\` command instead.` |\n> | `AC_TOO_LONG: N chars` | `SHORTEN: AC item exceeds 120 chars; split into two items or compress to one assertion.` |\n> | `AC_EMPTY` | `ADD: Acceptance criteria section must contain at least one \\`- [ ] \\` checkbox item.` |\n> | `AC_NOT_CHECKABLE` | `REWRITE: each AC item must include a path, backtick-quoted identifier, integer, or regex literal.` |\n> | `SMOKE_MULTI_LINE: N lines` | `COLLAPSE: Primary smoke test must be exactly one command line. Use \\`&&\\` to chain or move setup to Operator\u002Ffull verification.` |\n> | `SMOKE_PLACEHOLDER: contains \"\u003CTODO>\"` | `RESOLVE: Replace placeholders \\`\u003CTODO>\u002FTBD\u002FXXX\u002F...\\` with the actual command before filing.` |\n> | `SMOKE_NOT_FENCED` | `ADD: Primary smoke test section must contain exactly one fenced code block.` |\n> | `MISSING_SECTION_FILES_TO_READ` | `ADD: a \\`## Files to read first\\` section with 3-7 anchored entries (path#section or dep #N).` |\n> | `MISSING_SECTION_IMPL_OUTLINE` | `ADD: a \\`## Implementation outline\\` section (file paths + signatures + data flow).` |\n> | `MISSING_SECTION_TESTS` | `ADD: a \\`## Tests required\\` section (TDD per AGENTS.md, real services, no DB mocks).` |\n> | `MISSING_SECTION_DEPENDENCIES` | `ADD: a \\`## Dependencies\\` section containing \\`Depends on issue #N\\` lines or exactly \\`none\\`.` |\n> | `DEPS_MALFORMED` | `FIX: each \\`## Dependencies\\` line must be \\`Depends on issue #N\\` or exactly \\`none\\`.` |\n> | `TOO_MANY_FILES` | `SPLIT: \\`## Files touched\\` exceeds 3 logical units; split into a parent + child with a \\`Depends on\\` edge. NOTE: a skill trio (SKILL.md + codex\u002Fprompt.md + opencode\u002Fagent.md) plus its derived skill-goldens is ONE unit — keep them together, do not split a trio from its golden regen.` |\n> | `BODY_TOO_LONG` | `SHORTEN: body exceeds 400 words; cut prose or split the issue into a \\`Depends on\\` pair.` |\n> | `OUTLINE_TOO_LONG` | `SHORTEN: \\`## Implementation outline\\` exceeds 30 lines; compress signatures or split the issue.` |\n> | `UI_SECTIONS_INCOMPLETE` | `ADD: this is a UI feature — include \\`## Design reference\\`, \\`## Interaction states\\`, \\`## UX flows\\`, \\`## Motion & feedback\\`, and \\`## Device & viewport\\` (all five).` |\n\n> **Pre-filing safety loop (adaptive, MAX_SAFETY_RETRIES=5):** For each candidate child body, after the issue-quality lint passes and before `gh issue create`, run `\"${AUTOSPEC_BIN:-autospec}\" lint issue safety --title \"\u003Ccandidate title>\" \u002Ftmp\u002Fdraft-\u003Cslug>.md`. If the exit code is `1` or `2`, append the safety findings to the next generation prompt as cumulative directives:\n>\n> | Finding | Directive appended to next prompt |\n> |---|---|\n> | `SAFETY_BLOCK: production-data-destruction` | `BLOCKED: remove production data destruction from scope; rewrite for test\u002Fdev data only or split to human-reviewed production plan.` |\n> | `SAFETY_BLOCK: secret-exfiltration` | `BLOCKED: never request printing, dumping, sending, or exposing secrets or tokens.` |\n> | `SAFETY_BLOCK: instruction-bypass` | `BLOCKED: never ask the implementer to ignore AGENTS.md, system\u002Fdeveloper instructions, CI, review, hooks, or guardian checks.` |\n> | `SAFETY_AMBIGUOUS` | `CLARIFY: add explicit non-production scope, affected paths, guardrails, and verification command; otherwise skip filing.` |\n>\n> Repeat up to `MAX_SAFETY_RETRIES=5`. If attempt 5 still returns non-zero, print all drafts plus safety findings inline and skip that child. Do not file unsafe or ambiguous child issues.\n\n### UI-feature decomposition (only for user-facing UI issues)\n\nWhen a child issue builds or changes user-facing UI, treat it as more than generic\ncode: a small-LLM implementer needs the design and the behavior spelled out, and\nthe visual-fidelity QA loop needs something to judge against. Mark such issues with\na `\u003C!-- ui-feature -->` comment and add these five sections (the linter's\n`UI_SECTIONS_INCOMPLETE` rule enforces them as a group once any one is present):\n\n- **Design reference** — the `DESIGN.md` section\u002Ftokens (or mockup link) the screen\n  must match. Pairs with the implementer's `DESIGN_DRIFT` directive and the QA\n  visual-fidelity judge.\n- **Interaction states** — the relevant subset of default \u002F hover \u002F focus \u002F loading\n  \u002F empty \u002F error \u002F disabled, plus responsive breakpoints if they change layout.\n- **UX flows** — the happy path, the failure scenarios, and the edge cases (one\n  line each; this is where most UI defects hide).\n- **Motion & feedback** — which catalog motion patterns this screen uses, and its\n  reduced-motion fallback, one line per item, e.g.\n  `Motion: fade-in + 40ms stagger; reduced: opacity-only`. Pairs with the\n  implementer's `MOTION_DRIFT` directive.\n- **Device & viewport** — which device profiles must pass, plus reflow-at-320 and\n  200%-zoom expectations, one line per item, e.g.\n  `Devices: iPhone SE, Pixel 7, 1280×800 laptop; reflow-320: no h-scroll; zoom-200%: no clipped text`.\n\nNon-UI issues omit all five (the rule never fires without the marker or a section).\nThe five `ui-feature` sections are **excluded from the ≤400-word body count** (they\nstill count toward the ≤3-files cap where relevant) — Phase 3.5\u002F3.75 append\nModel-fit and Shared-contracts blocks after the trim, so a body that spent its\nwhole budget on prose would systematically trip `needs-quality-bar` once these two\nmandatory sections were added. The word cap continues to apply to the rest of the\nbody unchanged. Split a large screen into a parent + per-component children with\n`Depends on` edges rather than one giant issue.\n\n### Fab-feature decomposition (only for 3D-printable \u002F fab projects)\n\nWhen the feature is a 3D-printable \u002F fab project — `.autospec\u002Ffab.yml` is present, or\nthe request is about STL geometry, printing, vacuum\u002Fdust\u002Fgasket parts — apply the fab\nlens. CAD changes are high-risk and only verifiable through the autospec-fab\nrelease-gate, so decompose them small and gate every change:\n\n- **Regression-test-first.** Every CAD child issue starts with a focused regression\n  test (a release-gate run, or a single stage's check) that pins the geometry\u002Fmetadata\n  invariant being changed, written and failing before the model edit. No geometry change\n  ships without a test that would have caught its regression.\n- **STL Modeling Rules are HARD constraints, not advice.** State them in the issue body\n  so the implementer treats them as acceptance gates: ≥5 mm gasket surrounding wall;\n  NPT tap access + ≥5 mm fitting clearance preserved (no standalone towers); intended\n  vacuum-path \u002F inlet→gasket connectivity reachable; no relief\u002Fbleed on low-flow pumps;\n  full-size dust openings; the body stays watertight and single-body; never hand-edit\n  anything under `build\u002F` (generated artifacts are regenerated, not patched).\n- **Pre-stage per-model metadata + sidecars.** Each model child issue pre-stages its\n  metadata sidecar (`material`, `print_orientation`, `load_critical`, `flow_critical`,\n  `dims`) and any ports\u002Fgaskets sidecar entries the gate needs, so the metadata \u002F\n  vacuum-fitting \u002F gasket stages have inputs to validate. A part with no vacuum circuit\n  or dust duct simply omits those sidecars — the corresponding stages skip, they do not\n  fail.\n\nKeep fab children within the same ≤400-word \u002F ≤3-files caps; split a multi-feature model\ninto per-feature children chained by `Depends on`, each with its own regression test.\n\n### Small-LLM friendliness (applies to every child issue)\n\nChildren are written assuming the implementer is a 32B-class local model with **pre-staged context**, not a search-driven cloud agent:\n\n- Every file the implementer needs is named in **Files to read first** with a sectional anchor or a one-line reason. Do not assume the model will grep the codebase.\n- Spec docs are cited by section heading, not as \"read this 20 KB doc\".\n- Acceptance criteria are checkbox-only so the model can self-verify line-by-line.\n- One **Primary smoke test** runs in the inner loop; the heavier verification list runs once at the end.\n- If the work fans out across many tables\u002Fpackages, split it. Two 3 KB children chained by `Depends on` beat one 7 KB child a 32B model garbles at 60k tokens of working context.\n\n## Phase 3A — Freeze the spec portfolio plan (pure validation)\n\n**Capability probe (run first, before any filing).** Binaries older than the\nportfolio commands (#3432) do not expose `portfolio`; a missing subcommand\nis a degraded capability, not a Phase 3 blocker, and the fallback must stay\nopen while the primary is unavailable:\n\n```bash\nif \"${AUTOSPEC_BIN:-autospec}\" portfolio --help >\u002Fdev\u002Fnull 2>&1; then\n  PORTFOLIO_AVAILABLE=1\nelse\n  PORTFOLIO_AVAILABLE=0\n  printf '%s\\n' 'NOTE: autospec portfolio unavailable; using gh issue create path' >&2\nfi\n```\n\nWhen `PORTFOLIO_AVAILABLE=1`, Phases 3A and 3B run as written below. When\nit is 0, skip both: file the planned issues through the `gh issue create`\npath used for draft issues (each starts as `needs-classify`, never\n`auto-implement`), and the `## Delivery portfolio` section is omitted for\nthat run.\n\nPhase 3 creates or adopts a typed spec portfolio before it files any planned\nissue. The decomposer renders a frozen `autospec.portfolio-plan.v1` manifest to\n`$MANIFEST` — source spec, `project_owner` (the verified portfolio binding),\ntarget repositories, planned local trackers, implementation\u002Fprerequisite\nchildren, the source-repository Phase 5.5 audit node, and the\ncross-repository dependency edges, every edge keyed by a stable `item_key`. The\nper-issue `gh issue create` calls in the lint\u002Fsafety loops above are the\ndraft-quality gate; the **actual filing of planned issues goes through the\napply transaction in Phase 3B** — never a bare `gh issue create` fallback\nwhile the probe in this section passes.\n\nPhase 3A is pure planning over the full multi-repository manifest — issue\nlint, safety lint, security-artifact validation when applicable, supersession\nresolution, DAG validation, and read\u002Fwrite capability probes against every\ntarget repository. No remote mutation happens here. A repository that cannot\naccept issues is a blocking prerequisite, never a silently omitted lane; the\naudit logically depends on every implementation\u002Fprerequisite deliverable.\n`--dry-run` ends here: it emits the frozen plan and reports each capability as\n`verified`, `unavailable`, or `unknown`, and it never claims a write permission\nwas proven by a read. A non-zero exit here (the probe passed, so this is a\nvalidation failure, not a missing command) blocks Phase 3 — fix the manifest\nand re-run.\n\n```bash\nPLAN_JSON=$(\"${AUTOSPEC_BIN:-autospec}\" portfolio validate --manifest \"$MANIFEST\" --dry-run) || {\n  printf '%s\\n' 'ERROR: Phase 3A portfolio validate failed (pure planning, no remote mutation)' >&2\n  exit 1\n}\n```\n\n## Phase 3B — Apply the spec portfolio (provision the primary Project, then file the planned issues)\n\nThe apply transaction is the **sole provisioning\u002Fmaterialization entry point**:\nit exposes no separate public record or add commands that could let Project\nidentity, issue creation, membership, and recovery ordering diverge. It\nprovisions the primary spec Project (verified **before** any issue is filed)\nand then files the frozen plan in this order — primary umbrella; secondary\nrepository trackers; implementation\u002Fprerequisite children; the source-repository\nPhase 5.5 audit. Implementation and audit issues start as `needs-classify`,\nnever `auto-implement`, so an external runner cannot claim a partially\nprepared portfolio; blocked prerequisites keep their blocking label. After\nevery issue URL exists, the transaction creates the complete repository-local\nparent records and persists the cross-repository graph — a parent- or\ngraph-persistence failure blocks admission. Re-running for the same source-spec\nblob and plan digest adopts and reconciles the existing Project; a changed plan\ndigest stops for explicit plan-revision reconciliation.\n\n```bash\nAPPLY_JSON=$(\"${AUTOSPEC_BIN:-autospec}\" portfolio apply --manifest \"$MANIFEST\") || {\n  printf '%s\\n' 'ERROR: primary portfolio provisioning failed before issue filing; no issue is admitted' >&2\n  exit 1\n}\n```\n\nEvery issue-definition command prints the Project URL **before** the issue URLs\nand carries it in its JSON result (`portfolio_id`, `project`, `umbrellas`,\n`children`). Child bodies gain a `## Delivery portfolio` section with the\ncanonical Project URL and portfolio ID; repository-local umbrellas keep\n`autospec parent record` relationships, and cross-repository dependencies use\n`Depends on \u003Ccanonical-issue-url>`. Phase 3 may report success only when every\nplanned key is bound exactly once, every initial Project membership\u002Ffield\nprojection is acknowledged, all local parent records and graph edges are\ndurable, and each required child is admitted or explicitly blocked. Resume uses\nthe frozen manifest and checkpoints — it never re-decomposes a partially\napplied plan.\n\nCapture the umbrella + child issue numbers.\n\nPersist the relationship on GitHub and in the shared per-repository parent-state\ncache before classification. This command also posts a trusted typed\nparent-marker lifecycle comment on every child and the idempotent decomposition\ncomment on the parent. Append `--quarantined` when the umbrella's authoritative\ntyped safety decision is `SAFETY_AMBIGUOUS` or `SAFETY_BLOCK`; otherwise omit\nit. A failure is blocking because an unlinked child could merge without ever\nreconciling its parent.\n\n```bash\n_parent_slug=$(bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Frepo-slug.sh\" --canonical \"{repo}\")\nexport AUTOSPEC_PARENT_STATE_ROOT=\"${AUTOSPEC_PARENT_STATE_ROOT:-$HOME\u002F.autospec\u002Fparent-state\u002F$_parent_slug}\"\n\"${AUTOSPEC_BIN:-autospec}\" parent record --repo {repo} --parent \"\u003CUMBRELLA>\" --children \"\u003CCHILDREN_CSV>\"\n```\n\n## Phase 3.5 — Review and label (delegate)\n\nDispatch a **foreground subagent** to retro-review the child issues just\ncreated in Phase 3 and apply the model-fit rubric. The subagent must NOT modify\nissue titles or remove existing labels; it only adds `ctx:*` and `reasoning:*`\nlabels and patches each body with a `## Model fit` block.\n\n> **Model tier:** `TIER_A` (spec work) — top model with extended thinking; resolved at startup.\n>\n> Walk every child issue created in Phase 3 (skip any issue carrying the\n> `type:tracker` label). For each:\n>\n> 1. **Stage context.** Read `gh issue view \u003CN> --repo {repo} --json title,body,labels`. The\n>    body should already contain `## Files to read first`, `## Implementation scope`, `## Team personality`, and `## Review counter-team`. If any is missing, add label\n>    `needs-autospec-template` (idempotent `gh label create --force` once at run\n>    start) and skip — do not classify or patch.\n>\n> 2. **Apply the rubric.** Pick the smallest `ctx:*` tier that holds the\n>    staged context (issue body + every file in `## Files to read first` +\n>    cited spec sections). Pick the `reasoning:*` depth required to derive\n>    (not just transcribe) the implementation.\n>\n>    **`ctx:*` — context-window axis**\n>\n>    | Label | Trigger |\n>    |---|---|\n>    | `ctx:32k`  | One canonical table or shell script; ≤3 files in *Files to read first*; short spec anchors. |\n>    | `ctx:64k`  | Multi-file change; 4-7 files staged; one trio + one installer; medium spec sections (~1-3 KB). |\n>    | `ctx:120k` | Cross-skill or cross-package; 8+ files; long spec excerpts; deep call graphs. |\n>\n>    **`reasoning:*` — reasoning-depth axis**\n>\n>    | Label | Trigger |\n>    |---|---|\n>    | `reasoning:shallow` | Mechanical: copy-and-rename, regex-replace, README transcription, runbook authoring. Verbs: *copy*, *rename*, *transcribe*, *list*. |\n>    | `reasoning:medium`  | Template-following with judgment: synthesize a SKILL.md mirroring an existing one, modify a script with new flags, write tests for a documented contract. Verbs: *mirror*, *adapt*, *integrate*, *wire*. |\n>    | `reasoning:deep`    | Novel design choices: pick a new abstraction, resolve a contradiction in the spec, reconcile cross-cutting concerns. Verbs: *design*, *reconcile*, *resolve*, *redesign*. |\n>\n>    Default for issues that lack any of these signals: `ctx:64k`,\n>    `reasoning:medium`. If unsure between two ctx tiers, prefer the larger.\n>\n> 3. **Sibling normalization.** When 5+ split children share a structural\n>    criterion (e.g. all per-source-table writers, all per-skill installers),\n>    harmonize their `ctx:*`\u002F`reasoning:*` labels so the operator can run a\n>    single profile across the whole group. Override individual classifications\n>    only when the difference is a true outlier (e.g. one sibling pulls in a\n>    schema-wide refactor that no other sibling touches).\n>\n>\n> ### Issue intent safety gate\n>\n> Phase 3.5 may only persist model-fit, quality, board, and dependency\n> metadata. It must not manufacture a safety decision. Defer Rust admission\n> until the final issue body is persisted by step 8 below.\n>\n> 4. **Apply labels.** Idempotent at run start:\n>    `gh label create ctx:32k  --color c5def5 --force --repo {repo}`,\n>    `gh label create ctx:64k  --color c5def5 --force --repo {repo}`,\n>    `gh label create ctx:120k --color c5def5 --force --repo {repo}`,\n>    `gh label create reasoning:shallow --color c2e0c6 --force --repo {repo}`,\n>    `gh label create reasoning:medium  --color c2e0c6 --force --repo {repo}`,\n>    `gh label create reasoning:deep    --color c2e0c6 --force --repo {repo}`,\n>    `gh label create needs-quality-bar --color fbca04 --force --repo {repo}`.\n>    Then per issue:\n>    `gh issue edit \u003CN> --add-label \"ctx:\u003Ctier>,reasoning:\u003Cdepth>\" --repo {repo}`.\n>\n> 5. **Patch body — `## Model fit` block.** Insert immediately before the first\n>    `## Dependencies` line (or at end of body if absent):\n>\n>    ```markdown\n>    \u003C!-- autospec-classify:begin -->\n>    ## Model fit\n>\n>    - **ctx:** `ctx:\u003Ctier>` — \u003C1-line rationale>.\n>    - **reasoning:** `reasoning:\u003Cdepth>` — \u003C1-line rationale>.\n>\n>    *Auto-classified by Phase 3.5 on YYYY-MM-DD.*\n>    \u003C!-- autospec-classify:end -->\n>    ```\n>\n>    **Idempotency:** if a `## Model fit` block already exists between the\n>    `\u003C!-- autospec-classify:begin -->` and `\u003C!-- autospec-classify:end -->`\n>    markers, replace it in place. Never stack duplicates. Apply via\n>    `gh issue edit \u003CN> --body-file \u003Ctmp>`.\n>    Legacy blocks have `## Model fit` ABOVE\n>    `\u003C!-- autospec-classify:begin -->`. Replacing only the marker-delimited\n>    region orphans that heading outside the markers, where it still counts\n>    against the budget, and adds a second one. Delete the legacy heading\n>    and everything up to the begin marker first.\n>\n> 6. **Board assignment** — read `~\u002F.autospec\u002Fproject-map.yml` and assign each\n>    just-classified child to the GitHub Projects mapped from its labels.\n>\n>    **File schema** (auto-init if missing — see below):\n>    ```yaml\n>    # ~\u002F.autospec\u002Fproject-map.yml\n>    multi_match: union          # `union` (assign to every match) or `first`\n>    mappings:\n>      ctx:32k: \u003Cproject_number>\n>      ctx:64k: \u003Cproject_number>\n>      ctx:120k: \u003Cproject_number>\n>      reasoning:shallow: \u003Cproject_number>\n>      reasoning:medium:  \u003Cproject_number>\n>      reasoning:deep:    \u003Cproject_number>\n>      \u003Cany-other-label>: \u003Cproject_number>\n>    ```\n>\n>    **Reader procedure** for each issue I:\n>    - For each label L on I, look up `mappings[L]`. Skip null \u002F missing entries.\n>    - With `multi_match: union` (default), collect all matching project numbers and assign to every one of them. With `multi_match: first`, take the first match in label-order and assign to that single project.\n>    - For each chosen `\u003CP>`: `gh project item-add \u003CP> --owner \u003Cowner> --url \u003Cissue-url>`. The `gh` command is idempotent — repeated calls do not duplicate items, so re-running Phase 3.5 is safe.\n>\n>    **Auto-init when the file is missing.** Probe `gh project list --owner \u003Cowner> --format json` to confirm the user can author projects. Probe `gh label list --repo {repo} --json name -q '.[].name'` to enumerate the repo's labels. Write a starter file with every label as a `mappings:` key and `null` project numbers, plus `multi_match: union` at the top. Print:\n>    ```\n>    Wrote ~\u002F.autospec\u002Fproject-map.yml. Edit project numbers (currently null) and re-run.\n>    ```\n>    Then **exit Phase 3.5** without assigning any boards (the labels and `## Model fit` blocks remain applied — only the assign step is deferred).\n>\n>    **Hard rules.**\n>    - Never call `gh project item-add` in `--dry-run`.\n>    - Missing file in `autospec` \u002F `autospec-define` is non-fatal at run time once auto-init has populated it; if auto-init itself fails (e.g. `gh project list` denied), warn and skip board assignment for the rest of the run.\n>\n> 7. **Dependency-edge sanity checks.** After labeling, validate the dep graph\n>    of the just-created children:\n>    - **closed-dep warning** — emit `WARN: child #\u003CN> depends on closed issue #\u003CM>` for each `Depends on #M` line where `gh issue view #\u003CM> --json state` is `CLOSED`.\n>    - **child-less tracker dep warning** — emit `WARN: child #\u003CN> depends on tracker #\u003CM> with no children` when `#\u003CM>` carries `type:tracker` and has no other open `auto-implement` deps pointing at it.\n>    - **circular sibling-dep hard fail** — exit non-zero if any cycle exists among the just-created children's `Depends on #N` edges.\n>\n> 8. **Post-filing quality audit.** For each child issue (skip `type:tracker`):\n>    - Pull body: `gh issue view \u003CN> --repo {repo} --json body -q .body > \u002Ftmp\u002Faudit-\u003CN>.md`\n>    - Run: `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Flint-issue.sh\" \u002Ftmp\u002Faudit-\u003CN>.md`\n>    - On non-zero exit (lint fails):\n>      - Apply label: `gh issue edit \u003CN> --add-label needs-quality-bar --repo {repo}`\n>      - Insert `## Quality lint` block (idempotent, between `\u003C!-- autospec-quality:begin -->` and `\u003C!-- autospec-quality:end -->` markers) via `gh issue edit \u003CN> --body-file \u003Ctmp>`. A legacy block has the heading ABOVE the begin marker: delete the legacy heading and everything up to that marker first, or it keeps counting and a duplicate is added. Block format:\n>        ```markdown\n>        \u003C!-- autospec-quality:begin -->\n>        ## Quality lint\n>\n>        - **GOAL** — \u003C1-line finding>.\n>        - **AC#\u003Cn>** — \u003C1-line finding>.\n>        - **SMOKE** — \u003C1-line finding>.\n>\n>        *Auto-linted by Phase 3.5 on YYYY-MM-DD.*\n>        \u003C!-- autospec-quality:end -->\n>        ```\n>      - Comment findings: `gh issue comment \u003CN> --body \"\u003Cfindings>\" --repo {repo}`\n>    - Do NOT remove `auto-implement` label. Operator decides whether to proceed.\n>\n> 9. **Rust safety admission.** After all prior body writes complete, make each\n>    child an interim candidate (if it is not already one) and review that exact\n>    issue:\n>\n>    ```bash\n>    gh issue edit \u003CN> --add-label auto-implement --remove-label needs-classify --repo {repo}\n>    \"${AUTOSPEC_BIN:-autospec}\" queue review-safety --repo {repo} --limit 1 --issue \u003CN>\n>    ```\n>\n>    Read the JSON totals. Only `pass: 1` admits this invocation. Any other\n>    result is already recorded by Rust and must be skipped without manual\n>    labels, comments, body patches, or a semantic safety override. The Rust\n>    command is the only automatic writer of issue-intent safety outcomes.\n>\n> 10. **Run-end summary.** Print to stdout:\n>    ```\n>    Phase 3.5 summary on {repo}\n>    - classified: N\n>    - skipped (needs-autospec-template): M\n>    - ctx:32k=A  ctx:64k=B  ctx:120k=C\n>    - reasoning:shallow=X  reasoning:medium=Y  reasoning:deep=Z\n>    - boards assigned: \u003CK> (or \"skipped — no project-map.yml\")\n>    - dep warnings: \u003Ccount>; circular cycles: \u003Ccount>\n>    ```\n\n---\n\n## Phase 3.75 — Architectural alignment (deterministic scan + reconcile)\n\nAfter Phase 3.5 has applied `ctx:*` \u002F `reasoning:*` labels and before the\npre-impl gate, build a `Shared contracts` summary so child issues don't invent\nincompatible type signatures, file-layout conventions, and naming schemes —\nintegration mismatches that are otherwise caught only in Phase 5.5.\n\nThe former standalone Tier-A (opus) pass is **replaced** by a deterministic\nscan plus an optional small Tier-B reconcile. Mechanically extracting\nsignatures \u002F file paths \u002F naming tokens is not reasoning work — a grep does it\nexactly and for free.\n\n1. **Deterministic extract (no LLM).** Dump each child issue body\n   (skip the umbrella\u002Ftracker) to a temp dir, read every child's `lang:*`\n   label into a CSV (one value per child), then run the shared scanner with\n   `--languages`:\n\n   ```bash\n   langs=\"$(for n in \"${children[@]}\"; do\n     gh issue view \"$n\" --repo {repo} --json labels -q '.labels[].name | select(startswith(\"lang:\"))'\n   done | paste -sd, -)\"\n   bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fextract-shared-contracts.sh\" --dir \"$bodies_dir\" --languages \"$langs\" > \u002Ftmp\u002Fshared-contracts.md\n   ```\n\n   It greps every file path, `name(...)` signature, and ALL-CAPS naming\u002Fenv-var\n   token that appears in **≥2 distinct** issues and emits a `## Shared\n   contracts` block (file paths, signatures, names). Identical inputs produce\n   byte-identical output. `--languages` normalizes its values (trims,\n   strips the `lang:` prefix, de-dupes) and decides the boundary trigger:\n   when the labels span **2 or more distinct `lang:*` labels**, or when a\n   child carries `lang:mixed`, the emitted block also contains the\n   `## Cross-language boundaries` table (step 4) and the script runs its\n   own fail-closed schema check before writing anything to stdout. If it\n   reports `_No cross-issue contracts detected_` and no boundary table was\n   triggered, there is no cross-issue interface — skip the rest of Phase 3.75\n   and log `\"Phase 3.75: skipped (no cross-issue contracts)\"`.\n\n2. **Tier-B reconcile (small, only for genuine conflicts).** Skip unless the\n   scan surfaced an actual contradiction — the same path\u002Fname used with\n   **incompatible** shapes across issues (e.g. one issue declares\n   `bundle_static_context(role)` and another `bundle_static_context(role, dir)`).\n   When that happens, dispatch a small Tier-B subagent with ONLY the scanner\n   output plus the conflicting bodies and ask it to pick the authoritative\n   shape and note it in the block. Do **not** re-read every body or re-derive\n   the whole summary — the deterministic scan already did steps 1-2.\n\n3. **Patch each child issue body** by inserting the (possibly reconciled) block\n   **immediately before the first `## Dependencies` line** (append at end of body\n   only when the body has no `## Dependencies` heading):\n\n```\n\u003Cthe extract-shared-contracts.sh output verbatim, plus any Tier-B reconcile\nnotes inserted before its closing marker>\n```\n\n   Never plain-append: the block's HTML markers and `## Shared contracts` heading\n   must not land inside the `## Dependencies` section — `scripts\u002Flint-issue.sh`\n   reads that section until the next `## ` heading and reports `DEPS_MALFORMED`\n   for every line that is not `Depends on issue #N` or `none` (that append\n   placement is what broke the 13 `#3112`-generation bodies). Write the block to\n   `\u002Ftmp\u002Fshared-contracts-\u003CN>.md`, splice it in deterministically, and apply:\n\n   ```bash\n   body=\"$(gh issue view \u003CN> --json body -q .body)\"\n   printf '%s\\n' \"$body\" > \u002Ftmp\u002Fbody-\u003CN>.orig\n   if grep -q '\u003C!-- autospec-shared-contracts:begin -->' \u002Ftmp\u002Fbody-\u003CN>.orig; then\n     # Case B: the body already carries the marker region — replace the whole\n     # region (from `:begin -->` to `:end -->`, inclusive of both marker lines)\n     # with the freshly generated block so re-runs never stack a second heading.\n     awk -v f=\u002Ftmp\u002Fshared-contracts-\u003CN>.md '\n       !replaced && \u002F^\u003C!-- autospec-shared-contracts:begin -->$\u002F {\n         while ((getline line \u003C f) > 0) print line\n         skip = 1\n         replaced = 1\n         close(f)\n         next\n       }\n       skip && \u002F^\u003C!-- autospec-shared-contracts:end -->$\u002F { skip = 0; next }\n       !skip { print }\n     ' \u002Ftmp\u002Fbody-\u003CN>.orig > \u002Ftmp\u002Fbody-\u003CN>.md\n   else\n     # Case A: no marker yet — insert before the first `## Dependencies` line\n     # (append at end of body only when there is no `## Dependencies` heading).\n     awk -v f=\u002Ftmp\u002Fshared-contracts-\u003CN>.md '\n       !done && \u002F^## Dependencies$\u002F { while ((getline line \u003C f) > 0) print line; print \"\"; close(f); done = 1 }\n       { print }\n       END { if (!done) while ((getline line \u003C f) > 0) print line }\n     ' \u002Ftmp\u002Fbody-\u003CN>.orig > \u002Ftmp\u002Fbody-\u003CN>.md\n   fi\n   gh issue edit \u003CN> --body-file \u002Ftmp\u002Fbody-\u003CN>.md\n   ```\n\n   After the patch, `Depends on issue #N` must remain the last line under\n   `## Dependencies`.\n   The patch is idempotent in the strong sense: **re-running it replaces the\n   entire marker region** with the freshly generated block — it never stacks a\n   second `## Shared contracts` heading, a second boundary table, or a second\n   marker pair.\n\n   Do NOT add your own `\u003C!-- autospec-shared-contracts:begin -->` wrapper or\n   `## Shared contracts` heading: the script emits both. Nesting a second pair\n   leaves the outer marker and heading outside the region\n    `lint-issue.sh` strips, so they count against the word budget.\n\n4. **Cross-language boundaries (conditional, fail closed).** The scanner\n   decides the trigger from `--languages`: when the siblings span 2 or\n   more distinct `lang:*` labels (after the `lang:` prefixes are normalized\n   away) — or when any child carries `lang:mixed` — the block already\n   contains a `## Cross-language boundaries` table **between the\n   `\u003C!-- autospec-shared-contracts:begin -->` \u002F `:end -->` markers**. It has\n   one row per `schemas\u002F*.schema.json` path shared by ≥2 child bodies — the\n   scanner fills the `Schema (source of truth)` column with that path and\n   leaves every other cell as `-`; it never invents boundary names, and it\n   never emits an empty `Schema` cell or a `TBD` placeholder:\n\n   ```markdown\n   ## Cross-language boundaries\n\n   | Boundary | Transport | Schema (source of truth) | Owner | Golden fixture |\n   |---|---|---|---|---|\n   | cli→worker | subprocess + JSON stdout | schemas\u002Fautospec-x.schema.json | lang:rust | tests\u002Ffixtures\u002Fboundary\u002Fx.json |\n   ```\n\n   Fill the `-` cells (Boundary, Transport, Owner, Golden fixture) in each\n   affected child body from the child bodies before you edit. `Owner` is the\n   `lang:*` label of the side that owns the schema. The completed table\n   encodes three rules: the owning side lands the schema **first**; the consuming\n   issue carries `Depends on issue #N` against it; each boundary gets one golden\n   fixture under `tests\u002Ffixtures\u002F` asserted by **both** sides' own test runners —\n   that two-sided assertion is the only thing that catches drift.\n\n   **Fail-closed schema rule.** Every `Schema` cell must name a file that exists\n   under `schemas\u002F`. The scanner enforces this before it writes anything: when\n   a row's schema file is missing, it prints\n   `PHASE_3_75_FAILED rule=boundary-schema-missing path=\u003Cschema>` to stderr,\n   writes nothing to stdout, and exits 1. Re-run the same check on the\n   **filled** block before editing (a filled cell may point at a path the\n   scanner did not see) rather than emitting an unbacked table:\n\n   ```bash\n   boundaries=\u002Ftmp\u002Fshared-contracts.md   # the block, after filling the cells\n   missing=0\n   while read -r schema; do\n     [ -f \"$schema\" ] || { echo \"PHASE_3_75_FAILED rule=boundary-schema-missing path=$schema\"; missing=1; }\n   done \u003C \u003C(grep -oE 'schemas\u002F[A-Za-z0-9._\u002F-]+\\.json' \"$boundaries\" | sort -u)\n   [ \"$missing\" -eq 0 ] || exit 1\n   ```\n\n   On failure: do not patch any child body with the boundary table, leave\n   `auto-implement` off the children of that boundary, and comment the missing\n   schema paths on the owning issue so the schema can land first. An unbacked\n   row is the exact failure this rule exists to prevent. When the check passes,\n   log `\"Phase 3.75: cross-language boundaries verified (\u003Ccount>)\"`.\n\nIf there are fewer than 2 child issues, or all child issues are in the same\nfile (no cross-issue interface), skip Phase 3.75 and log:\n`\"Phase 3.75: skipped (single-file scope)\"`\n\n---\n\n## Spec supersession (recency)\n\nSpecs in `docs\u002Fspecs\u002F` accumulate over time. When a newer spec adds, modifies, or\nremoves behavior that an earlier spec described, autospec applies\n**implicit-by-recency supersession** (issue #635): the spec whose\nlast-modifying commit on the current branch is most recent wins for any\noverlapping behavior (untracked specs fall back to filesystem mtime).\nOperators do NOT write `Supersedes:` frontmatter — recency alone decides.\n\nDuring Phase 3 decomposition, before filing a candidate child issue, resolve\nthe authoritative spec for each behavior the issue touches. Use the shared\nhelper:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fresolve-spec-supersession.sh\" \"\u003Cbehavior-key>\"\n```\n\nIf the resolver prints a spec path other than the one currently being\ndecomposed, the candidate behavior has already been overridden by a newer\nspec — skip filing the issue (it would re-introduce removed behavior) and\nnote the supersession in the decompose run log. If the resolver exits 1 (no\noverlap), proceed normally: the behavior is new to this spec.\n\nSee `tests\u002Fresolve-spec-supersession.bats` for the resolver contract:\nno-overlap → exit 1, single overlap → that spec wins, two\u002Fthree-way overlap\n→ most recent wins, deleted specs are excluded.\n\n## Phase 3 pre-impl gate\n\nAfter Phase 3 decomposition completes (and Phase 3.5 review-and-label has\napplied `ctx:*` \u002F `reasoning:*` labels), end Phase 3 by asking the user\nthis verbatim question (no auto-launch — always ask explicitly, per spec\n§3.3):\n\n> `\"Spec written, N issues filed. Start \u002Fautospec-run now, defer to your external daemon, or keep refining? [run \u002F defer \u002F refine]\"`\n\nSubstitute `N` with the actual issue count from Phase 3. Default highlight\nis **`defer`** for `\u002Fautospec-define` (the plan-only skill — the user\ninvoked `\u002Fautospec-define` expecting plan-only behavior, so the gate\ndefaults to `defer`).\n\n- **`run`** — invoke `\u002Fautospec-run` in the current session.\n- **`defer`** (default for `\u002Fautospec-define`) — print\n  `\"Issues are ready. Your external monitor will pick them up. Exiting.\"`\n  and stop without launching `\u002Fautospec-run`. The just-filed `auto-implement`\n  queue persists on the GitHub side so an external daemon (or a later\n  `\u002Fautospec-run` invocation) can pick it up.\n- **`refine`** — re-enter Phase 2 from question 1 (Architecture).\n\nNo daemon auto-detection — always ask explicitly.\n\nAfter all decomposition issues are filed (and before asking the gate question),\nfile one additional child issue titled\n`\"Phase 5.5 audit + remediation — \u003Cfeature-name>\"` with labels\n`auto-implement,priority:high,audit`, then post a comment on the umbrella issue\nlinking it: `\"Phase 5.5 audit tracker: #\u003CN>\"`.\n\nAfter the user answers `run` or `defer` (i.e. the design is locked and issues\nare filed), call `diary-write.sh` to record the brainstorm decision:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fdiary-write.sh\" \\\n  --phase 1 \\\n  --event brainstorm-locked \\\n  --body \"Spec locked: ${SPEC_PATH}. Gate answer: ${GATE_ANSWER}. Issues filed: ${ISSUE_COUNT}.\" \\\n  2>\u002Fdev\u002Fnull || true\n```\n\n(Best-effort — never blocks the gate flow.)\n\n## Handoff\n\nIf the gate answer was `run`, hand off to `\u002Fautospec-run --profile \u003Cname>`\nto begin implementation. If the answer was `defer`, the run ends here and\nthe queue is left for an external monitor.\n\n## Init mode\n\nTriggered by `--init` flag or auto-detected when code exists but `docs\u002Fspecs\u002F` is empty or no doc carries an `autospec-doc-scope` annotation.\n\n### Auto-detect prompt\n\nWhen auto-detecting, ask once:\n\n> This repo has source code but no autospec docs. Run reverse-engineer first?\n> **[yes \u002F no \u002F always-this-repo]**\n\n- `yes` — run `--init` once for this invocation.\n- `no` — skip; proceed to Phase 1 normally.\n- `always-this-repo` — run `--init` and write `.autospec\u002Finit-done.flag`; future invocations skip this prompt.\n\nIf `.autospec\u002Finit-done.flag` exists, skip the prompt entirely.\n\n### --init execution\n\n1. Run tree-sitter scan across the repo source tree to enumerate modules, public symbols, and entry points.\n2. Emit one ARCHITECTURE-level spec to `docs\u002Fspecs\u002F\u003Crepo-slug>-architecture.md`.\n3. Emit per-module specs to `docs\u002Fspecs\u002F\u003Cmodule>-spec.md` for each discovered module.\n4. Generate initial docs via `gen-docs-from-spec.mjs`:\n   - `docs\u002FUSER_MANUAL.md`\n   - `docs\u002FAPI_REFERENCE.md`\n   - `docs\u002FARCHITECTURE.md`\n   - `llms.txt`\n   - `.llm-manifest.json`\n5. Open a `feat\u002Fspec-reverse-engineer-init` PR with all generated artifacts.\n6. Admin-merge the doc PR before proceeding to Phase 3 decomposition.\n\n### Auto-docs step (after spec PR merges)\n\nAfter any spec PR merges in normal `autospec-define` flow, regenerate\ndocumentation through the single doc engine — invoke `\u002Fautospec-doc`\n(incremental, scoped to the docs the merged spec affects), routed via\n`doc-orchestrator.mjs`:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fdoc-orchestrator.mjs\"\n```\n\n`\u002Fautospec-doc` is the only documentation-generation path; there is no\nparallel generator. Open a `docs\u002F` update PR and admin-merge it before Phase 3\nbegins. Skip if the spec change touches only non-public implementation details\n(no change to public API surface, no new CLI flags, no new env vars).\n\n## Autonomous mode\n\nWhen `\u002Fautospec-define --autonomous \"\u003Crequest>\"` runs, or when\n`~\u002F.autospec\u002Fautonomous.flag` exists at run start, Phase 2 and the Phase 3\npre-impl gate skip user-facing confirmations.\n\nBranches taken in autonomous mode:\n\n- **Phase 2 brainstorm** — do NOT ask the Architecture \u002F Interactivity \u002F\n  Data model \u002F Error handling \u002F Testing questions one at a time. Synthesize\n  the entire spec from (a) the user's request text, (b) the last ~10\n  conversation turns, (c) `git log --since=\"7 days ago\"` recent commits,\n  and (d) similar prior work in `docs\u002Fspecs\u002F**`. For each unverifiable\n  inference, mark the line in the spec body with a\n  `> AUTONOMOUS ASSUMPTION:` blockquote.\n- **Phase 3 pre-impl gate** — default to `run`. Do NOT ask\n  `[run \u002F defer \u002F refine]`. Proceed to issue filing without confirmation.\n- **Issue body confirmation** — `gh issue create` runs without per-issue\n  approval. The existing lint loop, sizing caps, and Phase 3.5 model-fit\n  classification still apply unchanged.\n\nIf the orchestrator cannot generate a coherent spec from available context\n(e.g. \"make it better\" with no surface evidence), autonomous mode FAILS\nLOUDLY with `code_health:autonomous_input_insufficient` and prints the\nspecific missing fields plus a recommended interactive command to retry.\nDo not silently pick arbitrary defaults.\n\nSafety guardrails are NOT bypassed. Before each would-have-asked decision,\nthe orchestrator invokes `autospec-autonomy-gate.sh` with\n`--check all`. Exit 1 surfaces the confirmation even in autonomous mode:\n\n- Destructive remote actions (force-push, repo archive\u002Fdelete, mass label\n  changes, prod DB writes).\n- Out-of-scope planned files (extend beyond Goal + Implementation outline).\n- Cost gate (`AUTOSPEC_AUTONOMOUS_TOKEN_CAP`, default 500k).\n- Existing `feedback_autospec_autonomy_scope.md` rules.\n\nThe handoff to `\u002Fautospec-run` preserves the `--autonomous` flag so the\nimplementation half honors the same telemetry tagging.\n","# autospec-define workflow (harness-neutral)\n\nTake the following feature request and run the planning half of the autospec pipeline:\n**bootstrap repo (if missing) → investigate → design → spec → decomposed GitHub issues.** Stop after Phase 3; the implementation half is handed off to `\u002Fautospec-run`.\n\nIf the request asks to split, materialize, roadmap, decompose, or turn an\nalready-written spec into GitHub issues, use **Existing spec mode** below:\nselect a tracked `docs\u002Fspecs\u002F*.md` file, skip Phases 1-2, run Phase 3 and\nPhase 3.5 against that spec, then continue to the Phase 3 pre-impl gate.\n\nManage your own context — never exceed 60%. Delegate to subagents whenever your harness supports it; do not investigate, write code, or design directly in the main conversation when a subagent can do it.\n\n\u003C!-- autospec-block:startup-self-update SKILL_NAME=autospec-define -->\n\n## Self-update mode\n\nIf the feature-request argument matches the regex `^\\s*update\\s*$` (case-insensitive, whitespace-padded), this skill enters self-update mode and does not run the normal pipeline:\n\n1. **Detect harness** by checking which install path exists for this skill:\n   - Claude Code: `~\u002F.claude\u002Fskills\u002Fautospec-define\u002FSKILL.md`\n   - OpenCode:    `~\u002F.config\u002Fopencode\u002Fagent\u002Fautospec-define.md`\n   - Codex CLI:   `~\u002F.codex\u002Fprompts\u002Fautospec-define.md`\n2. **Re-install the full autospec suite from `main`** by piping the canonical installer:\n   ```bash\n   curl -fsSL https:\u002F\u002Fraw.githubusercontent.com\u002Fberlinguyinca\u002Fautospec\u002Fmain\u002Fbootstrap.sh | bash -s -- --skill all --harness all --update\n   ```\n   Run this one-liner once; it refreshes all autospec skills across all harnesses.\n3. **Show the diff** between the prior installed file(s) and the freshly fetched copy (e.g. `diff \u003C(cat \u003Cprior>) \u003C(curl -fsSL ...SKILL.md)` or the equivalent recorded by the installer).\n4. **Stop.** Do not enter Phase 0 \u002F Phase 1 \u002F any pipeline phase. Print the upgrade summary and return to the user.\n\nIf no install path is detected, print `Self-update: no installed copy of autospec-define found; run install.sh first.` and exit.\n\n## Feature request\n\n{FEATURE_DESCRIPTION}\n\n---\n\n## Existing spec mode\n\nUse this mode when the request asks to split, materialize, roadmap, decompose,\nor turn an existing spec into GitHub issues. Examples:\n`split existing spec`, `split latest spec`, `turn this spec into GitHub issues`,\n`roadmap docs\u002Fspecs\u002F2026-05-01-example-design.md`, or\n`materialize the newest spec`.\n\nDo not run Phase 1 or Phase 2 in this mode. The design already exists; this\nmode is a shortcut into Phase 3 using the same issue decomposition and Phase 3.5\nclassification path as the normal pipeline.\n\n1. **Verify repo.** Run the Phase 0 repo probes. If the current directory is\n   not a git repo with a GitHub remote, use Phase 0 bootstrap before selecting\n   a spec.\n2. **Resolve candidate specs.**\n   - If the request contains an explicit `docs\u002Fspecs\u002F*.md` path, use that file.\n   - Otherwise list tracked and untracked local files matching `docs\u002Fspecs\u002F*.md`.\n   - Sort by ISO date in the filename (`YYYY-MM-DD-...`) descending. For files\n     without a date prefix, sort after dated files by filesystem modified time.\n   - The first item is the default \"newest\" spec.\n3. **Ask on ambiguity.**\n   - If zero specs exist, stop with: `No docs\u002Fspecs\u002F*.md files found. Create or\n     point me at a spec before running existing spec mode.`\n   - If exactly one spec exists and no explicit path was provided, use it.\n   - If more than one spec exists and no explicit path was provided, ask the user\n     to confirm the default newest spec or choose another path. Show at most the\n     five newest candidates with relative paths. Do not file issues until the\n     user answers.\n4. **Verify selected spec is filed.**\n   - The selected path must be under `docs\u002Fspecs\u002F` and end in `.md`.\n   - This mode accepts an optional `--base \u003Cbranch>` flag (default `main`). The\n     base names the branch the spec must already be tracked on before Phase 3,\n     so child issues can cite a stable GitHub URL. With no flag the base is\n     `main` and every check below is byte-identical to the current behavior;\n     explore passes a sandbox branch as `--base \u003Csandbox-branch>`.\n   - The selected file must be tracked on `\u003Cbase>` before Phase 3. Verify with:\n     `git fetch origin` and `git cat-file -e \u003Cbase>:\u003Cspec-path>`.\n   - If the selected file is missing from `\u003Cbase>`, stop and tell the user:\n     `Selected spec is not on \u003Cbase> yet: \u003Cspec-path>. Land the spec first,\n     or run normal \u002Fautospec-define so Phase 2 can create and merge the spec PR.`\n   - Guardrail: under a non-main `--base \u003Cbranch>`, no PR or issue targets\n     `main` — child issues link the `\u003Cbase>` blob and the decomposer files\n     against `\u003Cbase>` only.\n5. **Continue at Phase 3.** Capture `{selected_spec_path}` and its GitHub URL as\n   `https:\u002F\u002Fgithub.com\u002F{repo}\u002Fblob\u002F\u003Cbase>\u002F{selected_spec_path}` (with the default\n   base this is `...\u002Fblob\u002Fmain\u002F...`, byte-unchanged). Run Phase 3 and\n   Phase 3.5 using that selected spec. Then proceed to the existing Phase 3\n   pre-impl gate.\n\n## Required capabilities & harness adapter\n\nThis workflow assumes five capabilities. Map each one to your harness's actual tool. If a capability is missing, use the listed fallback.\n\n| Capability                  | Claude Code                          | OpenCode                                 | Codex CLI                                | Fallback if missing                                |\n|-----------------------------|--------------------------------------|------------------------------------------|------------------------------------------|----------------------------------------------------|\n| Read-only codebase research | `Agent` (subagent_type=Explore)      | `task` agent in read-only mode           | `apply_patch` read-only \u002F shell `grep`   | Do the search in-thread with `rg`\u002F`grep`           |\n| Foreground delegation       | `Agent` (subagent_type=general-purpose) | nested `task` agent, await output     | spawn nested CLI session                 | Do the work in-thread (more context cost)          |\n| Background delegation       | `Agent` with `run_in_background: true` | detached `task` agent                  | nohup'd CLI session writing to a logfile | Run the monitor in a separate terminal\u002Ftmux pane   |\n| Ask the user a question     | `AskUserQuestion`                    | inline prompt                            | inline prompt                            | Ask in the response and wait for the next turn     |\n| Self-paced future wakeup    | `ScheduleWakeup` inside a `\u002Floop`    | a recurring `task` or local `cron`       | local `cron`\u002F`launchd` calling the CLI   | The user runs a status-update prompt manually      |\n| Subagent model tier         | Tier A: `opus` + `ultrathink`; Tier B: `sonnet` + medium thinking | Tier A: top `task` model + high reasoning; Tier B: smaller-tier `task` + medium reasoning | Tier A: top GPT + `reasoning_effort=high`; Tier B: current spark\u002Fcost-optimized Codex + `reasoning_effort=medium` | Honor the per-phase tier mapping in AGENTS.md; retry the same subagent UP on unavailability |\n\u003C!-- autospec-block:harness-adapter-core -->\n\n**Persistent project notes**: write durable preferences to **`AGENTS.md`** in the repo root — this is the de-facto standard recognized by Claude Code (also reads `CLAUDE.md`), OpenCode, and Codex. If your harness has its own private memory (e.g. Claude Code's `~\u002F.claude\u002F...\u002Fmemory\u002F`), mirror the same content there. Per AGENTS.md, subagent dispatches use a **two-tier policy**: Tier A (top model + extended thinking) for spec work (research, decompose, review\u002Flabel); Tier B (cheaper model + medium thinking) for implementation work (Phase 4 implementer + LGTM review — not used by this skill). The orchestrator keeps the user's invoked model. Fall back UP the tier on quota\u002Fcapacity or other unavailability by retrying the same subagent with the stronger tier while preserving parent context.\n\n---\n\n## Harness detection (run once at skill start, before Phase 0)\n\nDetect your harness by checking available tools before any phase:\n\n1. **Claude Code** — the `Agent` tool with a `subagent_type` parameter is available.\n   - `TIER_A` = `opus` + `ultrathink`  (the alias, which resolves to the current Claude Opus generation)\n   - `TIER_B` = `sonnet`               (the alias, which resolves to the current Claude Sonnet generation)\n\n2. **OpenCode** — a `task` tool with model\u002Ftier configuration is available (no `subagent_type`).\n   - `TIER_A` = top-tier task model + high reasoning\n   - `TIER_B` = smaller-tier task model + medium reasoning\n\n3. **Codex CLI** — neither `Agent` nor a configurable `task` tool is available; `apply_patch` is the primary edit tool.\n   - `TIER_A` = current top GPT model + `reasoning_effort=high`\n   - `TIER_B` = the spark \u002F cost-optimized variant of the configured model when one exists, else the configured model + `reasoning_effort=medium`\n\n**Fallback rule:** If `TIER_B` is not available in your harness (model unknown, quota\u002Fcapacity failure, authorization failure, or tool call returns an error for that model), silently retry the same subagent dispatch with `TIER_A`. Preserve the parent context on retry; for Codex native subagents, fork\u002Finherit the current conversation context and use the latest top GPT model instead of moving the work into the main session. Never ask the user.\n\nHold `TIER_A` and `TIER_B` for the entire skill run. Every \"Tier A\" and \"Tier B\" reference below resolves to these harness-specific values.\n\n## Relevant memory injection (run-start, once)\n\nBefore executing the main pipeline phases, call the injector to surface relevant saved lessons:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Finject-relevant-memory.sh\" \\\n  --context \"\u003Cskill-relevant keywords from request\u002Fissue\u002Fspec>\" \\\n  --top-k 5\n```\n\nPrepend the output block (if non-empty) to your working context. This surfaces lessons like\n`feedback_bash_return_trap_leak.md` that prevent re-occurrence of known pitfalls.\n\n## Phase 0 — Bootstrap repo (if missing)\n\nVerify `gh auth status` is authenticated. If not, ask the user to run `gh auth login` and stop until they confirm.\n\nProbe the working directory:\n```bash\ngit rev-parse --is-inside-work-tree 2>\u002Fdev\u002Fnull\ngit remote get-url origin 2>\u002Fdev\u002Fnull   # must contain github.com\n```\n\nIf **either** check fails — no git repo, or no GitHub remote — bootstrap a new repo:\n\n1. **Resolve the language.** Write the feature description to a temp file and call `${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fclassify-language.sh \u003Ctemp-file> --json`. Parse the JSON: `lang`, `source`, `rationale`, `deterministic`, `confidence`. If `lang` is not `unknown` and `deterministic` is `true`, the language is unambiguous — pre-fill it in the bootstrap question below. If `lang` is `unknown` or `deterministic` is `false`, ask the operator which language to use. If `classify-language.sh` is missing or exits non-zero, fail closed: do not bootstrap; tell the user the classifier is unavailable and stop.\n\n2. **Suggest a name.** Slugify the feature description: lowercase, hyphens, drop stop-words, prefix with the resolved language if present (e.g. `go` → `go-tui-x`; `python` → `py-ml-y`). Offer 1–2 candidates.\n\n3. **Ask the user once** (single interactive question; combine the three sub-questions if your harness supports it, otherwise ask sequentially):\n   - **Name** (your top suggestion as default, pre-filled with the resolved language prefix).\n   - **Visibility**: `private` | `public` (default: private).\n   - **Owner**: enumerate via `gh org list`; default to the user's personal account.\n\n4. **Initialize locally**:\n   - If `.git` is absent: `git init -b main`.\n   - Write a `.gitignore` matching the resolved language (Go: `bin\u002F vendor\u002F *.exe *.test`; Node: `node_modules\u002F dist\u002F .next\u002F .env*`; Python: `__pycache__\u002F .venv\u002F *.egg-info\u002F build\u002F dist\u002F`; Rust: `target\u002F`; mixed\u002Funknown: skip).\n   - Write a one-line `README.md` containing the feature description.\n   - Write a starter `AGENTS.md` listing the project's coding standards (TDD non-negotiable, no DB mocks, conventional commits, branch-per-issue, no force-push) — this is the source of truth every agent reads.\n   - `git add -A && git commit -m \"chore: initial scaffold\"`.\n\n5. **Create the remote and push**:\n   ```bash\n   gh repo create \u003Cowner>\u002F\u003Cname> --\u003Cprivate|public> --source=. --remote=origin --push\n   ```\n\n6. **Verify and register**: first run `gh repo view \u003Cowner>\u002F\u003Cname> --json url,defaultBranchRef`.\n   Only after that succeeds, capture the exact slug and record verified creation evidence:\n   ```bash\n   REPO=\"\u003Cowner>\u002F\u003Cname>\"\n   SPAWNED_FROM=\"${SOURCE_SPEC_URL:-${AUTOSPEC_RUN_ID:-bootstrap:$REPO}}\"\n   REGISTRATION_JSON=$(\"${AUTOSPEC_BIN:-autospec}\" project onboard --repo-dir \"$PWD\" --repo \"$REPO\" --spawned-from \"$SPAWNED_FROM\") || {\n     printf '%s\\n' 'ERROR: managed Project repository registration failed before durable admission' >&2\n     exit 1\n   }\n   case \"$(printf '%s' \"$REGISTRATION_JSON\" | jq -r '.outcome \u002F\u002F empty')\" in\n     reconciled) ;;\n     journaled_projection_pending)\n       printf '%s\\n' 'WARNING: managed Project repository projection is durably journaled and pending' >&2 ;;\n     *) printf '%s\\n' 'ERROR: managed Project repository registration returned no supported typed outcome' >&2; exit 1 ;;\n   esac\n   ```\n   Never register when read-back fails. A typed pending outcome does not roll\n   back or recreate the verified repository; reconciliation retries the\n   journaled projection. Propagate every hard registration failure. Capture\n   `\u003Cowner>\u002F\u003Cname>` as `{repo}` for every later phase.\n\nIf a repo already exists (cwd is in a git tree with a `github.com:\u003Cowner>\u002F\u003Cname>` remote), capture that as `{repo}` and skip the bootstrap.\n\n## Phase 1 — Investigate (delegate)\n\nSpawn a **read-only research subagent** to map relevant files, schema, services. Get back a 300-word summary with file paths and line numbers. Do NOT read files directly from the main thread.\n\n> **Model tier:** `TIER_A` (spec work) — top model with extended thinking; resolved at startup.\n\n> **Phase 1 bounded-context rule.** Launch the research subagent with a fresh,\n> bounded handoff. Do NOT fork, inherit, or compact the full parent conversation into Phase 1. The handoff may contain only: the feature request,\n> repo slug\u002Froot, a short git status summary, relevant memory-injection output,\n> explicit user-mentioned paths\u002Fsurfaces, and these Phase 1 instructions. For\n> Codex native subagents, set `fork_context=false`; for Claude\u002FOpenCode, use the\n> equivalent fresh\u002Fno-history task mode when available. If the harness cannot\n> start a fresh subagent, or returns a context window or remote compact failure,\n> do not retry with inherited context. Fall back to bounded local read-only `rg`\u002Ffile-read investigation, label the result as `Phase 1 fallback`, and\n> continue to Phase 2 with the best evidence gathered.\n\nIf the feature touches a remote system (DB, server, S3), run a real query against the actual data to confirm the problem statement before designing. Surface the concrete numbers in the design.\n\nClassify the request before returning the investigation. Select\n`feature_profile: security_database` when it combines a database or remote data\nboundary with security, authorization, destructive-operation, confidentiality,\nor production-availability constraints. For that profile, return an evidence\nledger whose entries are explicitly `verified`, `assumed`, or `blocking`; name\nthe source for every verified fact and never execute a command merely because\nit appears in evidence text. All other requests use the **ordinary profile** and\ncontinue through the existing flow without security-only sections.\n\nFor a freshly-bootstrapped empty repo, Phase 1 may be a no-op — proceed to Phase 2.\n\n## Phase 2 — Brainstorm + design\n\n> **Spec quality is the bottleneck.** Phase 2's output drives every downstream cycle's cost; if you care about spec quality, invoke this skill with your top-tier model (Claude Code: `claude-code --model opus`; Codex: top GPT). Phase 2 itself runs in the orchestrator (no subagent dispatch) — your invocation model IS the spec model. Subagents in Phases 1, 3, 3.5 follow this lead by selecting Tier A; Phase 4 implementation work uses Tier B. See AGENTS.md.\n\n### Security\u002Fdatabase profile contract\n\nWhen Phase 1 selected `feature_profile: security_database`, the design must\ninclude evidence and open assumptions, explicit priority ordering, threats,\ncontrols with owner and authority, negative tests, blocking prerequisites,\ndependency order, atomic contracts, residual risks, and acceptance criteria.\nControls whose failure consequence is data loss or unauthorized disclosure must\nbe owned authoritatively by the database\u002Fplatform layer, never only by an AST or\napplication check.\n\nWrite `.autospec\u002Fspec-artifacts\u002F\u003Cslug>.security-database.yml` using schema\n`autospec.security_database.v1`. Include provisional issue keys and complete\nProduces\u002FConsumes\u002FCovers, evidence, prerequisite, control, negative-test,\ndependency, and atomic-group mappings before GitHub issue numbers exist. Run\n`python3 \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fvalidate-security-artifact.py\" \u003Cartifact>`\nbefore opening the spec PR. Any finding, including\n`AUTHORITATIVE_CONTROL_MISSING`, blocks the PR; repair the design and artifact,\nnever fall back to free-form generation. The ordinary profile does not create\nor validate this sidecar. Commit the Markdown spec and sidecar together; use\n`git add -f` for the sidecar if the target repository ignores `.autospec\u002F`.\nEvery prerequisite must declare a non-empty `gates` list and every gated issue\nmust repeat that prerequisite ID. Every control must have an issue owner. Each\natomic-group member must appear in exactly one issue's `produces` list, with all\nmembers of that group owned by the same issue.\n\n## Team personality selection\n\nBefore the Architecture question, decide what kind of team should solve this\nrequest. Infer the team personality from the user's request, Phase 1 evidence,\nrepository labels, relevant memory files, and past specs under `docs\u002Fspecs\u002F`.\nThe goal is to shape the design as a fitting team would reason about it, not to\ntreat every request as a generic \"fix this bug\" task.\n\nWrite a **Team personality** section into the design spec with:\n- the selected team name,\n- 3-6 roles,\n- why this team fits the request,\n- the risks this team is expected to notice,\n- any team emphasis that should carry into child issues.\n\nAlso write a **Review counter-team** subsection. It must be a different\nemphasis from the implementation team and should challenge likely blind spots,\nnot duplicate the same perspective. Include:\n- the counter-team name,\n- 2-5 roles,\n- which assumptions or failure modes this team should challenge,\n- how review should stay inside the issue scope while applying that lens.\n\nIf confidence is low, ask the user explicitly: `What kind of team should solve this problem?`\nOffer exactly these five starter combinations:\n1. **Core product engineering** — product manager, architect, backend developer, frontend developer, test engineer.\n2. **Reliability\u002Fbackend** — backend developer, platform engineer, sysadmin\u002FSRE, database engineer, security advisor.\n3. **Frontend\u002Fproduct** — frontend developer, UX designer, accessibility reviewer, API\u002Fbackend developer, QA engineer.\n4. **Security-sensitive** — security advisor, architect, backend developer, platform engineer, test engineer.\n5. **Legacy\u002Frefactor** — architect, maintainer, backend\u002Ffrontend developer as needed, test engineer, documentation owner.\n\nIf one option is clearly best, proceed without asking and record the confidence\nand evidence in the spec. If two or more options are plausible and would change\nthe architecture, tests, or decomposition, ask before continuing.\n\nDerive the Review counter-team after choosing the implementation team:\n- Frontend\u002Fproduct implementation teams should be reviewed by accessibility, API contract, and QA perspectives.\n- Reliability\u002Fbackend implementation teams should be reviewed by security, operations, and data-integrity perspectives.\n- Security-sensitive implementation teams should be reviewed by product\u002FUX, maintainer, and test perspectives.\n- Legacy\u002Frefactor implementation teams should be reviewed by maintainer, regression-test, and architecture perspectives.\n- Core product engineering implementation teams should be reviewed by security, operations, accessibility, and maintainability perspectives.\n\nRun a structured brainstorm — one question at a time, get explicit approval after each section:\n\n1. **Architecture** — where does new code live, what existing patterns does it follow.\n2. **Interactivity \u002F API shape** — how does the user\u002Fcaller drive it; commands, keys, endpoints, fields.\n3. **Data model** — types, columns, persistence boundary.\n4. **Error handling** — failure modes, recovery, user-visible signals.\n5. **Testing** — unit \u002F integration \u002F e2e split, real services vs anything else (rule per AGENTS.md: real services). For app\u002FUI work, include an `autospec-qa` revalidation plan that maps each spec requirement to running-app checks for text inputs, validation, selects\u002Fdropdowns, buttons, forms, API effects, accessibility, responsive behavior, negative paths, regenerated automated tests, proof artifacts, reliability contract, control intent ledger, no-mock minimum coverage, mutation\u002Fbreakage proof, duplicate-code review, post-merge canary, new-code intent checks, artifact freshness, evidence provenance, console\u002Fnetwork error gates, spec contradiction detection, data lifecycle proof, observability, flake quarantine, legacy removal\u002Fspec cleanup, and reliability exhaustion loop.\n\nWrite the agreed design to `docs\u002Fspecs\u002FYYYY-MM-DD-\u003Ctopic>-design.md`, then run a **fresh-eyes self-review** before any issue is filed:\n\n1. **Placeholders** — grep the spec for `TBD`, `TODO`, `later`, `fixme`, `tbd`, `XXX`. Fill in or surface to the operator as an open question; do not file issues against an undecided spec.\n2. **Internal consistency** — re-read each section in order. Do any two sections contradict each other? Does the architecture match the feature descriptions? Fix inline.\n3. **Ambiguity** — could any requirement be interpreted two different ways? Pick one and make it explicit in the spec text.\n4. **Scope** — is this focused enough for a single multi-issue pipeline, or does it span independent subsystems that each need their own `\u002Fautospec-define` run? If the latter, stop and ask the operator to decompose before proceeding.\n5. **Critical improvement** — ask: \"What else could fail even if this spec and its obvious tests pass, and how could this be better?\" Add the highest-risk answer to Testing, Acceptance Criteria, or Review counter-team. For app\u002FUI work, explicitly consider mocked-vs-deployed behavior, backend fallbacks, user-visible outcomes, and no-mock smoke coverage.\n\nThe spec must be implementable end-to-end by an agent reading only the spec.\n\n### Epistemic gates (issue #3718)\n\nSeventy classified incidents reduced to five shapes, and all five are cheap and\nmechanical — none require a larger model. The spec must carry these gates so\nevery downstream implementer and reviewer applies them:\n\n1. **Name the producer of every value.** For each value a gate or test reads,\n   the spec names the process or step that computes it, and the gate must\n   verify the value is current and complete, not merely present.\n2. **State what the gate examined, not just its verdict.** Each \"pass\" must\n   name the inputs, version\u002Frevision, and scope it actually checked. A \"passed\"\n   verdict with nothing named is a defect.\n3. **Re-baseline immediately before judging.** The gate must observe the\n   system in its current state at decision time, not rely on a measurement\n   taken earlier or a value another step recorded.\n4. **Declare the shared foundation.** When one input feeds several gates or\n   tests, the spec names it as shared state and requires every consumer to read\n   the same instance, so the consumers cannot diverge silently.\n5. **Derive limits from the real constraint, not from observed history.**\n   Thresholds, caps, and budgets are computed from the resource or time budget\n   they protect, not tuned to fit past runs. An observed value is never a\n   specification.\n\n### Diagnostic assistant\n\nWhen the request describes a chat or assistant that answers questions about\ndomain entities backed by real data, such as jobs, samples, logs, or incidents,\nrequire the design spec to capture the current page and entity scope before\nopening a full-page assistant view. The assistant must preserve that scope\nacross pop-out and full-page routes so a navigation change cannot silently\nwiden or replace the entity being diagnosed.\n\nRequire a server-side session runner to admit the user's input together with\ncaptured context, plan registered tool calls, execute them, settle sanitized\nevidence, and only then call the provider, even for a small in-repo\nimplementation. Store context-source metadata alongside every assistant turn,\ncovering the page, entity, job, and sample scope used for that turn so the\nanswer's diagnostic boundary remains explainable.\n\nRequire a backend tool registry that defines named tools, input and output\nschemas, authorization rules, a bounded per-turn call cap, and how sanitized\ntool evidence is injected into the final provider prompt. Each typed tool\nregistry entry must declare a name, schema, execution mode, permission scope,\nand bounded output size. Separate\ndeterministic keyword-triggered tool plans from a bounded model-planned\ndiagnostic step; the model-planned step may run only when deterministic routing\nfinds no plan. Reject stale or unknown model-proposed tool calls before\nexecution, and enforce the bounded tool-call cap on every turn. Keep provider\nsecrets and all tool execution server-side; the frontend must never receive\nprovider keys or direct diagnostic tool access. When a question maps to a\nregistered tool, the final assistant answer must be grounded in tool evidence,\nnot retrieval citations alone.\n\nRequire the spec's Testing section to cover nested-context extraction,\ndeterministic intent-keyword coverage, scoped-entity diagnostics, and provider\nrefusal and fallback behavior.\n\n### Documentation visualization\n\nWhen the requested work creates or regenerates documentation, the design spec\nMUST require Mermaid diagrams and charts where acceptable. Add a concrete visual\nplan for queues, routers, state machines, data flow, control flow, algorithms,\narchitecture boundaries, timelines, ownership relationships, decision spaces,\nroadmaps, or metric trends whenever one of those structures exists in the target\nfeature. Select the Mermaid type that fits the explanation: flowchart, sequence\ndiagram, state diagram, class\u002Fentity diagram, Gantt, timeline, journey, quadrant\nchart, gitGraph, mindmap, block, architecture, Sankey, XY, pie, kanban, or\nanother Mermaid-supported diagram type. Prefer Mermaid blocks in Markdown for\nreviewer-visible explanations; use `docs\u002Fassets\u002Fdiagrams\u002F` only when a generated\nasset is needed outside a Markdown page. If no diagram is useful, the spec must\nstate `Mermaid: not applicable` with the reason, so omission is explicit rather\nthan accidental.\n\n### Design cohesion\n\nWhen the requested work creates a website, app, dashboard, portal, or other UI,\nthe design spec MUST define app-wide design guidelines instead of letting each\npage improvise. Require page structure rules for the page header, constrained\ncontent width, section rhythm, and clear action hierarchy. Name the reusable\nprimitives the spec expects agents to reuse — forms, filter bars, segmented\ncontrols, tables, stat cards, empty states, charts, and navbars — and state\nwhere each primitive applies.\n\n**Artifact cleanup.** Require the spec to remove inline styles, duplicate class\nattributes, and legacy table or card chrome that bypasses the shared design\nsystem.\n\n**Positive design-system adoption.** Require the spec to name the project's\ncanonical primitives and classes for page shells, filter panels, segmented\ncontrols, date ranges, tables, empty states, and notices, then require agents to\nuse them instead of raw page-local layouts. The Acceptance Criteria MUST include\nan executable positive guard that fails when a raw toggle, date, or table\ncontrol does not use the project's design-system classes. Cross-reference the\n`autospec-qa` revalidation plan's **UI and UX Behavior** item and require it to\ncheck both artifact absence and canonical primitive presence.\n\nThe spec MUST flag full-document horizontal overflow as a defect unless the\noverflow is inside an intentional bounded scroller such as a table or chart\nviewport. Empty states must be visually lighter than data-rich panels so missing\ndata reads as lower emphasis, not as a primary card competing with real content.\nThe Testing section MUST include desktop and mobile visual QA that reports\nspacing, alignment, overflow, table density, toolbar grouping, and chart defaults\nas explicit checks.\n\n### Threat model, before mechanism (authentication, signing, encryption, credentials)\n\nWhen any requirement touches authentication, token or signature verification,\nencryption, or credential handling, the design spec MUST state the threat\nmodel before choosing a mechanism. State what property is needed, who the\nuntrusted party is, and which existing layer already provides it. If TLS to a\nnamed host, a process boundary, or an existing gate already establishes the\nproperty, say so and do not re-establish it. A token signature exists so a\nthird party handed a token by an untrusted caller can establish the issuer\nproduced it; a confidential client that receives tokens as the response body\nof a request it made, to a host it named, over a connection TLS already\nauthenticated has already had the property established, and adding JWKS\nfetch plus signature verification protects against nothing (identity can\ninstead come from the provider's `userinfo` endpoint). Only then choose a\nmechanism.\n\nThe same reasoning cuts the other way and the spec must state it too: if a\ntoken could ever arrive by another route — forwarded by a client, read from a\nheader — none of that holds and the token must be verified properly. That\nboundary belongs in a comment at the code, so a later reader cannot copy the\npattern somewhere it is wrong.\n\nIf this is a fresh repo, commit the spec to `main` directly (`git add docs\u002F... && git commit -m \"docs: \u003Ctopic> design spec\" && git push`) so subsequent issues can reference it as a tracked file. This is the ONLY exemption from `autospec-guarded-merge.sh` (T16 H3): a brand-new repo has no reviewed base and no PR to gate, and the commit is the spec document alone. Every later change merges through a PR and the guarded merge.\n\nFor an existing repo, land the spec via a short-lived PR so CI can validate it.\nThe spec commit happens in a temp worktree (`\u002Ftmp\u002Fwt-spec-\u003Cslug>`), never in the\nprimary checkout (see §D4 of `docs\u002Fspecs\u002F2026-06-03-worktree-guard-design.md` and\n`## Git hygiene (agents)` in `AGENTS.md`).\n\n\u003C!-- define-spec-pr:begin -->\n```bash\nSLUG=\"\u003Ctopic>\"\nBRANCH=\"feat\u002Fspec-${SLUG}\"\nWT=\"\u002Ftmp\u002Fwt-spec-${SLUG}\"\n\n# resolve → create → assert (D4 pattern)\nVERDICT=\"$(bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n    resolve-branch --branch \"$BRANCH\" --repo {repo})\"\nSTATE=\"$(printf '%s' \"$VERDICT\" | jq -r .state)\"\n\ncase \"$STATE\" in\n  open-pr)\n    PR_NUM=\"$(printf '%s' \"$VERDICT\" | jq -r .pr)\"\n    # Spec PR already open — validate CI + merge; skip re-commit.\n    gh pr checks \"$PR_NUM\" --repo {repo} --watch\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fautospec-guarded-merge.sh\" --pr \"$PR_NUM\" --repo {repo}\n    ;;\n  branch-only)\n    # Branch exists but no PR — adopt in a fresh worktree and continue.\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        create --branch \"$BRANCH\" --path \"$WT\" --adopt\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        assert  # MUST exit 0 before any edit\n    # Push + open PR then fall through to the wait\u002Fmerge step below.\n    git -C \"$WT\" push -u origin \"$BRANCH\"\n    gh pr create --base main --head \"$BRANCH\" --repo {repo} \\\n        --title \"docs: ${SLUG} design spec\" \\\n        --body \"Source spec: docs\u002Fspecs\u002F${SLUG}-design.md\"\n    gh pr checks --watch --repo {repo} \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fautospec-guarded-merge.sh\" --repo {repo} \\\n        --pr \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    git worktree remove \"$WT\" 2>\u002Fdev\u002Fnull || true\n    git worktree prune\n    ;;\n  fresh)\n    # Happy path: create a clean worktree, commit spec there, push, PR.\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        create --branch \"$BRANCH\" --path \"$WT\"\n    bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fworktree-guard.sh\" \\\n        assert  # MUST exit 0 before any edit; non-zero → stop, restore auto-implement\n    cp \"docs\u002Fspecs\u002F${SLUG}-design.md\" \"$WT\u002Fdocs\u002Fspecs\u002F${SLUG}-design.md\"\n    git -C \"$WT\" add \"docs\u002Fspecs\u002F${SLUG}-design.md\"\n    git -C \"$WT\" commit -m \"docs: ${SLUG} design spec\"\n    git -C \"$WT\" push -u origin \"$BRANCH\"\n    gh pr create --base main --head \"$BRANCH\" --repo {repo} \\\n        --title \"docs: ${SLUG} design spec\" \\\n        --body \"Source spec: docs\u002Fspecs\u002F${SLUG}-design.md\"\n    gh pr checks --watch --repo {repo} \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    if [ \"${AUTOSPEC_NO_AUTOMERGE_SPEC:-0}\" != \"1\" ]; then\n        bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fautospec-guarded-merge.sh\" --repo {repo} \\\n            --pr \"$( gh pr list --head \"$BRANCH\" --repo {repo} --json number -q '.[0].number')\"\n    else\n        # Env var set — pause and ask user to merge before continuing.\n        echo \"AUTOSPEC_NO_AUTOMERGE_SPEC=1: merge the spec PR manually, then continue.\"\n    fi\n    git worktree remove \"$WT\" 2>\u002Fdev\u002Fnull || true\n    git worktree prune\n    ;;\nesac\n```\n\u003C!-- define-spec-pr:end -->\n\n6. Verify the spec is reachable at `https:\u002F\u002Fgithub.com\u002F{repo}\u002Fblob\u002Fmain\u002Fdocs\u002Fspecs\u002F...` before dispatching Phase 3.\n\n## Phase 3 — Decompose into linked GitHub issues (delegate)\n\nIf Existing spec mode is active, use `{selected_spec_path}` and its GitHub URL.\nOtherwise use the spec path written and merged in Phase 2.\n\nDispatch a **foreground subagent** with this prompt (substitute the spec path and `{repo}`):\n\n> **Model tier:** `TIER_A` (spec work) — top model with extended thinking; resolved at startup.\n>\n> Read the selected design spec at `\u003Cspec-path>` (`\u003Cspec-github-url>`) and split it into linked GitHub issues for {repo}.\n>\n> **Portfolio validation gate (security\u002Fdatabase only):** Load\n> `.autospec\u002Fspec-artifacts\u002F\u003Cslug>.security-database.yml`, update every planned\n> issue mapping after decomposition, and run\n> `python3 \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fvalidate-security-artifact.py\" \u003Cartifact>`.\n> Validation must pass before creating labels or calling `gh issue create`.\n\n> **Managed Project projection (mandatory):** Immediately after every successful issue\n> creation or issue edit, capture the verified URL as `ISSUE_URL` and run:\n> `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fproject-sync-issue.sh\" \"$ISSUE_URL\" \"$PWD\"`.\n> Never run this command in dry-run mode. If sync fails, print\n> `WARNING: managed Project sync failed for $ISSUE_URL` only for a verified journaled-pending outcome. A hard pre-journal failure stops decomposition after preserving the already-created issue; never create a replacement issue.\n> Then perform a Tier-A portfolio review: confirm every threat has a control,\n> every control has both a negative test and an issue owner, every required spec\n> section is covered, dependencies are acyclic, every prerequisite names its\n> gated issues, and atomic-group members resolve to one issue's `produces` list.\n> Do not weaken controls to make decomposition pass. An issue with an unresolved\n> prerequisite receives `autospec:blocked-prerequisite` instead of\n> `auto-implement`; it may be filed for visibility but is not queued. The\n> ordinary profile skips this gate.\n>\n> Create labels (idempotent with `--force`): `auto-implement` (#0e8a16), `autospec:blocked-prerequisite` (#d4c5f9), `epic` (#b60205), `autospec:v2-flow` (#0e8a16, description: \"Routes to absorbed-discipline Phase 4 implementer\"), plus any domain labels the spec calls for. Then create exactly N issues — first an EPIC umbrella (no `auto-implement` label, just `epic` + domain), then N-1 children carrying `auto-implement` and `autospec:v2-flow` unless the portfolio gate marked them blocked. The `autospec:v2-flow` label routes the child to the Phase 4 implementer that absorbs turbo's expand → implement → finalize → peer-review → evaluate discipline; children filed without it fall back to the legacy implementer path. After creating children, edit the umbrella body with a checklist linking them. Return JSON: `{umbrella, children:[…], labels_created:[…]}`. Use `gh` CLI only. Do NOT modify code. Do NOT push branches. Do NOT create PRs.\n>\n> Before drafting each candidate child issue, ask yourself three shell-structure questions (internal — do NOT write them into the issue body):\n>\n> - **Produces** — What new files, exports, or behavior does this issue create? If the answer is \"edits scattered across many existing files with no clear new contract\", reconsider the boundary.\n> - **Consumes** — What existing files or outputs of earlier issues does this depend on? Each named dependency on an earlier issue translates to a `Depends on issue #N` line in the body.\n> - **Covers** — Which sections of the spec does this issue implement? If multiple unrelated sections, split. If no spec section, reconsider whether the issue belongs.\n>\n> If two adjacent candidate issues have heavy mutual Consumes\u002FProduces overlap, they probably want to be merged. If one issue has more than ~5 named Produces, it probably wants to be split.\n>\n> Each child body must be a **self-contained mini-spec** sized for execution by a 32B-class local LLM, with these sections in order:\n>\n> - **Goal** — 1 sentence outcome.\n> - **Source spec** — `\u003Cspec-path>` + `\u003Cspec-github-url>` of the design doc this issue derives from.\n> - **Team personality** — copy the spec's selected team name, roles, and issue-relevant emphasis. If the selected spec lacks this section, infer it from the request, past specs, repository labels, and memory; if confidence is low, stop and ask the operator to choose from the five starter combinations in Phase 2 before filing issues.\n> - **Review counter-team** — copy the spec's counter-team name, roles, and issue-relevant blind spots to challenge. If the selected spec lacks this section, derive a different review emphasis from the Team personality and issue risk before filing.\n> - **Files to read first** — 3–7 entries. Each entry is one of: a path with **section anchors** (do not say \"read the whole spec\"), the closest existing-file analogue to mirror, the test file or fixture pattern to follow, or a dependency issue with a one-line summary so the LLM doesn't fetch its body. Bias toward sectional anchors over full files.\n> - **Local-LLM execution notes** — one-line context-window recommendation (`32k routine`, `64k stretch`, or `split into N subagents along \u003Ccriterion>` for issues exceeding ~30k tokens of staged context) and whether single-pass or subagent-split is recommended.\n> - **Implementation scope** and **Out of scope** as separate subsections (replaces the prior single \"Scope\" section).\n> - **Files touched** — machine-parseable: one repo-relative path per line, ≤3 logical units. The authoritative scope source the linter (`TOO_MANY_FILES`) and reviewers check; keep it in sync with the outline. A skill trio (`SKILL.md` + `codex\u002Fprompt.md` + `opencode\u002Fagent.md`) plus its derived `tests\u002Ffixtures\u002Fskill-goldens\u002F*.sha256` counts as ONE unit, so a single-trio edit may list all six paths and still be in-cap.\n> - **Implementation outline** — file paths + function signatures + data flow.\n> - **Tests required** — TDD per AGENTS.md, real services, no DB mocks, 80%+ coverage.\n> - **Acceptance criteria** — checkbox list `[ ]` only, no prose. Each item machine-checkable.\n> - **Verification** — split into a **Primary smoke test (inner loop)** with exactly one fast command, and **Operator\u002Ffull verification** listing the remaining commands.\n> - **Branch name** — `feat\u002F\u003Cslug>`.\n> - **Dependencies** — `Depends on issue #N` lines (parsed by the monitor).\n> - For `security_database` only: **Evidence consumed**, **Controls covered**, and **Prerequisites**, copied exactly from the validated artifact. Every prerequisite starts with `verified:` or the child is blocked.\n>\n> Never hand-author the final body. Populate structured YAML with\n> `files_touched`, `local_llm_notes`, `dependencies`, and conditional security\n> lists, then render it with\n> `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fgen-issue-skeleton.sh\" --input \u003Cissue.yml>`.\n> Pass the renderer output to the lint and safety checks.\n>\n> **Sizing caps (hard, per spec §3.4):**\n>\n> - **Body ≤400 words** including all sections.\n> - **Implementation outline ≤30 lines** (file paths + function signatures).\n> - **Files touched ≤3** per child issue, counted as distinct **logical units** — not raw paths. A multi-harness skill **trio** (`skills\u002F\u003Cx>\u002FSKILL.md` + `codex\u002Fprompt.md` + `opencode\u002Fagent.md`) plus its derived `tests\u002Ffixtures\u002Fskill-goldens\u002F\u003Cx>.*.sha256` is **ONE** logical unit: with `derive-trio.sh` shipped, the edit is \"edit `SKILL.md` → derive the mirrors with `derive-trio.sh --in-place skills\u002F\u003Cx>` → regenerate goldens with `gen-skill-goldens.sh \u003Cx>`\" in a **single commit**, so the cap must not split a trio's prose from its golden regen into separate issues. `lint-issue.sh` and `sizing-check.sh` collapse trio members to one unit and exclude the derived goldens — keep a trio edit (and its goldens) inside one child.\n> - If a candidate child would exceed any cap, split into a parent + child pair with a `Depends on` edge.\n> - The whole spec + a single child issue body must fit comfortably in a 60–120k context window.\n>\n> Self-check each issue against the caps **before** calling `gh issue create`. If a cap is violated and a split is not feasible, surface the issue inline (print the over-cap body to the operator) instead of filing it.\n>\n> **Pre-filing lint loop (adaptive, MAX_LINT_RETRIES=5):** For each candidate child body, before calling `gh issue create`, write the body to `\u002Ftmp\u002Fdraft-\u003Cslug>.md` and run `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Flint-issue.sh\" \u002Ftmp\u002Fdraft-\u003Cslug>.md`. If the exit code is non-zero, map each `RULE_ID: \u003Cdesc>` finding to an actionable directive using the table below, append all directives to the next generation prompt as cumulative context, and regenerate. Repeat up to `MAX_LINT_RETRIES=5` attempts. If attempt 5 still fails, print all 5 drafts plus accumulated findings inline and **skip** that child (do not file); continue to the next child. On pass (exit 0), proceed to the safety loop and only call `gh issue create` after safety passes.\n>\n> | Finding | Directive appended to next prompt |\n> |---|---|\n> | `GOAL_VAGUE: \"improve\" used without concrete object` | `AVOID: bare verb \\`improve\\` without naming a file path, command, label, or number in the same sentence.` |\n> | `GOAL_HEDGE: \"should probably\"` | `AVOID: hedging words \\`should\u002Fmight\u002Fcould try\u002Ftry to\\`. State the outcome flatly.` |\n> | `GOAL_NOT_ONE_SENTENCE: N terminals` | `REWRITE: Goal must be exactly one sentence ending with a single . ? or !` |\n> | `AC_PROSE: line N not a checkbox` | `FORMAT: every AC line must start with \\`- [ ] \\` followed by content.` |\n> | `AC_SUBJECTIVE: \"looks clean\"` | `AVOID: subjective adjectives \\`looks\u002Ffeels\u002Fseems\u002Fclean\u002Felegant\\` in AC items. Use a \\`grep\\`\u002F\\`test\\`\u002F\\`diff\\`\u002F\\`bats\\` command instead.` |\n> | `AC_TOO_LONG: N chars` | `SHORTEN: AC item exceeds 120 chars; split into two items or compress to one assertion.` |\n> | `AC_EMPTY` | `ADD: Acceptance criteria section must contain at least one \\`- [ ] \\` checkbox item.` |\n> | `AC_NOT_CHECKABLE` | `REWRITE: each AC item must include a path, backtick-quoted identifier, integer, or regex literal.` |\n> | `SMOKE_MULTI_LINE: N lines` | `COLLAPSE: Primary smoke test must be exactly one command line. Use \\`&&\\` to chain or move setup to Operator\u002Ffull verification.` |\n> | `SMOKE_PLACEHOLDER: contains \"\u003CTODO>\"` | `RESOLVE: Replace placeholders \\`\u003CTODO>\u002FTBD\u002FXXX\u002F...\\` with the actual command before filing.` |\n> | `SMOKE_NOT_FENCED` | `ADD: Primary smoke test section must contain exactly one fenced code block.` |\n> | `MISSING_SECTION_FILES_TO_READ` | `ADD: a \\`## Files to read first\\` section with 3-7 anchored entries (path#section or dep #N).` |\n> | `MISSING_SECTION_IMPL_OUTLINE` | `ADD: a \\`## Implementation outline\\` section (file paths + signatures + data flow).` |\n> | `MISSING_SECTION_TESTS` | `ADD: a \\`## Tests required\\` section (TDD per AGENTS.md, real services, no DB mocks).` |\n> | `MISSING_SECTION_DEPENDENCIES` | `ADD: a \\`## Dependencies\\` section containing \\`Depends on issue #N\\` lines or exactly \\`none\\`.` |\n> | `DEPS_MALFORMED` | `FIX: each \\`## Dependencies\\` line must be \\`Depends on issue #N\\` or exactly \\`none\\`.` |\n> | `TOO_MANY_FILES` | `SPLIT: \\`## Files touched\\` exceeds 3 logical units; split into a parent + child with a \\`Depends on\\` edge. NOTE: a skill trio (SKILL.md + codex\u002Fprompt.md + opencode\u002Fagent.md) plus its derived skill-goldens is ONE unit — keep them together, do not split a trio from its golden regen.` |\n> | `BODY_TOO_LONG` | `SHORTEN: body exceeds 400 words; cut prose or split the issue into a \\`Depends on\\` pair.` |\n> | `OUTLINE_TOO_LONG` | `SHORTEN: \\`## Implementation outline\\` exceeds 30 lines; compress signatures or split the issue.` |\n> | `UI_SECTIONS_INCOMPLETE` | `ADD: this is a UI feature — include \\`## Design reference\\`, \\`## Interaction states\\`, \\`## UX flows\\`, \\`## Motion & feedback\\`, and \\`## Device & viewport\\` (all five).` |\n\n> **Pre-filing safety loop (adaptive, MAX_SAFETY_RETRIES=5):** For each candidate child body, after the issue-quality lint passes and before `gh issue create`, run `\"${AUTOSPEC_BIN:-autospec}\" lint issue safety --title \"\u003Ccandidate title>\" \u002Ftmp\u002Fdraft-\u003Cslug>.md`. If the exit code is `1` or `2`, append the safety findings to the next generation prompt as cumulative directives:\n>\n> | Finding | Directive appended to next prompt |\n> |---|---|\n> | `SAFETY_BLOCK: production-data-destruction` | `BLOCKED: remove production data destruction from scope; rewrite for test\u002Fdev data only or split to human-reviewed production plan.` |\n> | `SAFETY_BLOCK: secret-exfiltration` | `BLOCKED: never request printing, dumping, sending, or exposing secrets or tokens.` |\n> | `SAFETY_BLOCK: instruction-bypass` | `BLOCKED: never ask the implementer to ignore AGENTS.md, system\u002Fdeveloper instructions, CI, review, hooks, or guardian checks.` |\n> | `SAFETY_AMBIGUOUS` | `CLARIFY: add explicit non-production scope, affected paths, guardrails, and verification command; otherwise skip filing.` |\n>\n> Repeat up to `MAX_SAFETY_RETRIES=5`. If attempt 5 still returns non-zero, print all drafts plus safety findings inline and skip that child. Do not file unsafe or ambiguous child issues.\n\n### UI-feature decomposition (only for user-facing UI issues)\n\nWhen a child issue builds or changes user-facing UI, treat it as more than generic\ncode: a small-LLM implementer needs the design and the behavior spelled out, and\nthe visual-fidelity QA loop needs something to judge against. Mark such issues with\na `\u003C!-- ui-feature -->` comment and add these five sections (the linter's\n`UI_SECTIONS_INCOMPLETE` rule enforces them as a group once any one is present):\n\n- **Design reference** — the `DESIGN.md` section\u002Ftokens (or mockup link) the screen\n  must match. Pairs with the implementer's `DESIGN_DRIFT` directive and the QA\n  visual-fidelity judge.\n- **Interaction states** — the relevant subset of default \u002F hover \u002F focus \u002F loading\n  \u002F empty \u002F error \u002F disabled, plus responsive breakpoints if they change layout.\n- **UX flows** — the happy path, the failure scenarios, and the edge cases (one\n  line each; this is where most UI defects hide).\n- **Motion & feedback** — which catalog motion patterns this screen uses, and its\n  reduced-motion fallback, one line per item, e.g.\n  `Motion: fade-in + 40ms stagger; reduced: opacity-only`. Pairs with the\n  implementer's `MOTION_DRIFT` directive.\n- **Device & viewport** — which device profiles must pass, plus reflow-at-320 and\n  200%-zoom expectations, one line per item, e.g.\n  `Devices: iPhone SE, Pixel 7, 1280×800 laptop; reflow-320: no h-scroll; zoom-200%: no clipped text`.\n\nNon-UI issues omit all five (the rule never fires without the marker or a section).\nThe five `ui-feature` sections are **excluded from the ≤400-word body count** (they\nstill count toward the ≤3-files cap where relevant) — Phase 3.5\u002F3.75 append\nModel-fit and Shared-contracts blocks after the trim, so a body that spent its\nwhole budget on prose would systematically trip `needs-quality-bar` once these two\nmandatory sections were added. The word cap continues to apply to the rest of the\nbody unchanged. Split a large screen into a parent + per-component children with\n`Depends on` edges rather than one giant issue.\n\n### Fab-feature decomposition (only for 3D-printable \u002F fab projects)\n\nWhen the feature is a 3D-printable \u002F fab project — `.autospec\u002Ffab.yml` is present, or\nthe request is about STL geometry, printing, vacuum\u002Fdust\u002Fgasket parts — apply the fab\nlens. CAD changes are high-risk and only verifiable through the autospec-fab\nrelease-gate, so decompose them small and gate every change:\n\n- **Regression-test-first.** Every CAD child issue starts with a focused regression\n  test (a release-gate run, or a single stage's check) that pins the geometry\u002Fmetadata\n  invariant being changed, written and failing before the model edit. No geometry change\n  ships without a test that would have caught its regression.\n- **STL Modeling Rules are HARD constraints, not advice.** State them in the issue body\n  so the implementer treats them as acceptance gates: ≥5 mm gasket surrounding wall;\n  NPT tap access + ≥5 mm fitting clearance preserved (no standalone towers); intended\n  vacuum-path \u002F inlet→gasket connectivity reachable; no relief\u002Fbleed on low-flow pumps;\n  full-size dust openings; the body stays watertight and single-body; never hand-edit\n  anything under `build\u002F` (generated artifacts are regenerated, not patched).\n- **Pre-stage per-model metadata + sidecars.** Each model child issue pre-stages its\n  metadata sidecar (`material`, `print_orientation`, `load_critical`, `flow_critical`,\n  `dims`) and any ports\u002Fgaskets sidecar entries the gate needs, so the metadata \u002F\n  vacuum-fitting \u002F gasket stages have inputs to validate. A part with no vacuum circuit\n  or dust duct simply omits those sidecars — the corresponding stages skip, they do not\n  fail.\n\nKeep fab children within the same ≤400-word \u002F ≤3-files caps; split a multi-feature model\ninto per-feature children chained by `Depends on`, each with its own regression test.\n\n### Small-LLM friendliness (applies to every child issue)\n\nChildren are written assuming the implementer is a 32B-class local model with **pre-staged context**, not a search-driven cloud agent:\n\n- Every file the implementer needs is named in **Files to read first** with a sectional anchor or a one-line reason. Do not assume the model will grep the codebase.\n- Spec docs are cited by section heading, not as \"read this 20 KB doc\".\n- Acceptance criteria are checkbox-only so the model can self-verify line-by-line.\n- One **Primary smoke test** runs in the inner loop; the heavier verification list runs once at the end.\n- If the work fans out across many tables\u002Fpackages, split it. Two 3 KB children chained by `Depends on` beat one 7 KB child a 32B model garbles at 60k tokens of working context.\n\n## Phase 3A — Freeze the spec portfolio plan (pure validation)\n\n**Capability probe (run first, before any filing).** Binaries older than the\nportfolio commands (#3432) do not expose `portfolio`; a missing subcommand\nis a degraded capability, not a Phase 3 blocker, and the fallback must stay\nopen while the primary is unavailable:\n\n```bash\nif \"${AUTOSPEC_BIN:-autospec}\" portfolio --help >\u002Fdev\u002Fnull 2>&1; then\n  PORTFOLIO_AVAILABLE=1\nelse\n  PORTFOLIO_AVAILABLE=0\n  printf '%s\\n' 'NOTE: autospec portfolio unavailable; using gh issue create path' >&2\nfi\n```\n\nWhen `PORTFOLIO_AVAILABLE=1`, Phases 3A and 3B run as written below. When\nit is 0, skip both: file the planned issues through the `gh issue create`\npath used for draft issues (each starts as `needs-classify`, never\n`auto-implement`), and the `## Delivery portfolio` section is omitted for\nthat run.\n\nPhase 3 creates or adopts a typed spec portfolio before it files any planned\nissue. The decomposer renders a frozen `autospec.portfolio-plan.v1` manifest to\n`$MANIFEST` — source spec, `project_owner` (the verified portfolio binding),\ntarget repositories, planned local trackers, implementation\u002Fprerequisite\nchildren, the source-repository Phase 5.5 audit node, and the\ncross-repository dependency edges, every edge keyed by a stable `item_key`. The\nper-issue `gh issue create` calls in the lint\u002Fsafety loops above are the\ndraft-quality gate; the **actual filing of planned issues goes through the\napply transaction in Phase 3B** — never a bare `gh issue create` fallback\nwhile the probe in this section passes.\n\nPhase 3A is pure planning over the full multi-repository manifest — issue\nlint, safety lint, security-artifact validation when applicable, supersession\nresolution, DAG validation, and read\u002Fwrite capability probes against every\ntarget repository. No remote mutation happens here. A repository that cannot\naccept issues is a blocking prerequisite, never a silently omitted lane; the\naudit logically depends on every implementation\u002Fprerequisite deliverable.\n`--dry-run` ends here: it emits the frozen plan and reports each capability as\n`verified`, `unavailable`, or `unknown`, and it never claims a write permission\nwas proven by a read. A non-zero exit here (the probe passed, so this is a\nvalidation failure, not a missing command) blocks Phase 3 — fix the manifest\nand re-run.\n\n```bash\nPLAN_JSON=$(\"${AUTOSPEC_BIN:-autospec}\" portfolio validate --manifest \"$MANIFEST\" --dry-run) || {\n  printf '%s\\n' 'ERROR: Phase 3A portfolio validate failed (pure planning, no remote mutation)' >&2\n  exit 1\n}\n```\n\n## Phase 3B — Apply the spec portfolio (provision the primary Project, then file the planned issues)\n\nThe apply transaction is the **sole provisioning\u002Fmaterialization entry point**:\nit exposes no separate public record or add commands that could let Project\nidentity, issue creation, membership, and recovery ordering diverge. It\nprovisions the primary spec Project (verified **before** any issue is filed)\nand then files the frozen plan in this order — primary umbrella; secondary\nrepository trackers; implementation\u002Fprerequisite children; the source-repository\nPhase 5.5 audit. Implementation and audit issues start as `needs-classify`,\nnever `auto-implement`, so an external runner cannot claim a partially\nprepared portfolio; blocked prerequisites keep their blocking label. After\nevery issue URL exists, the transaction creates the complete repository-local\nparent records and persists the cross-repository graph — a parent- or\ngraph-persistence failure blocks admission. Re-running for the same source-spec\nblob and plan digest adopts and reconciles the existing Project; a changed plan\ndigest stops for explicit plan-revision reconciliation.\n\n```bash\nAPPLY_JSON=$(\"${AUTOSPEC_BIN:-autospec}\" portfolio apply --manifest \"$MANIFEST\") || {\n  printf '%s\\n' 'ERROR: primary portfolio provisioning failed before issue filing; no issue is admitted' >&2\n  exit 1\n}\n```\n\nEvery issue-definition command prints the Project URL **before** the issue URLs\nand carries it in its JSON result (`portfolio_id`, `project`, `umbrellas`,\n`children`). Child bodies gain a `## Delivery portfolio` section with the\ncanonical Project URL and portfolio ID; repository-local umbrellas keep\n`autospec parent record` relationships, and cross-repository dependencies use\n`Depends on \u003Ccanonical-issue-url>`. Phase 3 may report success only when every\nplanned key is bound exactly once, every initial Project membership\u002Ffield\nprojection is acknowledged, all local parent records and graph edges are\ndurable, and each required child is admitted or explicitly blocked. Resume uses\nthe frozen manifest and checkpoints — it never re-decomposes a partially\napplied plan.\n\nCapture the umbrella + child issue numbers.\n\nPersist the relationship on GitHub and in the shared per-repository parent-state\ncache before classification. This command also posts a trusted typed\nparent-marker lifecycle comment on every child and the idempotent decomposition\ncomment on the parent. Append `--quarantined` when the umbrella's authoritative\ntyped safety decision is `SAFETY_AMBIGUOUS` or `SAFETY_BLOCK`; otherwise omit\nit. A failure is blocking because an unlinked child could merge without ever\nreconciling its parent.\n\n```bash\n_parent_slug=$(bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Frepo-slug.sh\" --canonical \"{repo}\")\nexport AUTOSPEC_PARENT_STATE_ROOT=\"${AUTOSPEC_PARENT_STATE_ROOT:-$HOME\u002F.autospec\u002Fparent-state\u002F$_parent_slug}\"\n\"${AUTOSPEC_BIN:-autospec}\" parent record --repo {repo} --parent \"\u003CUMBRELLA>\" --children \"\u003CCHILDREN_CSV>\"\n```\n\n## Phase 3.5 — Review and label (delegate)\n\nDispatch a **foreground subagent** to retro-review the child issues just\ncreated in Phase 3 and apply the model-fit rubric. The subagent must NOT modify\nissue titles or remove existing labels; it only adds `ctx:*` and `reasoning:*`\nlabels and patches each body with a `## Model fit` block.\n\n> **Model tier:** `TIER_A` (spec work) — top model with extended thinking; resolved at startup.\n>\n> Walk every child issue created in Phase 3 (skip any issue carrying the\n> `type:tracker` label). For each:\n>\n> 1. **Stage context.** Read `gh issue view \u003CN> --repo {repo} --json title,body,labels`. The\n>    body should already contain `## Files to read first`, `## Implementation scope`, `## Team personality`, and `## Review counter-team`. If any is missing, add label\n>    `needs-autospec-template` (idempotent `gh label create --force` once at run\n>    start) and skip — do not classify or patch.\n>\n> 2. **Apply the rubric.** Pick the smallest `ctx:*` tier that holds the\n>    staged context (issue body + every file in `## Files to read first` +\n>    cited spec sections). Pick the `reasoning:*` depth required to derive\n>    (not just transcribe) the implementation.\n>\n>    **`ctx:*` — context-window axis**\n>\n>    | Label | Trigger |\n>    |---|---|\n>    | `ctx:32k`  | One canonical table or shell script; ≤3 files in *Files to read first*; short spec anchors. |\n>    | `ctx:64k`  | Multi-file change; 4-7 files staged; one trio + one installer; medium spec sections (~1-3 KB). |\n>    | `ctx:120k` | Cross-skill or cross-package; 8+ files; long spec excerpts; deep call graphs. |\n>\n>    **`reasoning:*` — reasoning-depth axis**\n>\n>    | Label | Trigger |\n>    |---|---|\n>    | `reasoning:shallow` | Mechanical: copy-and-rename, regex-replace, README transcription, runbook authoring. Verbs: *copy*, *rename*, *transcribe*, *list*. |\n>    | `reasoning:medium`  | Template-following with judgment: synthesize a SKILL.md mirroring an existing one, modify a script with new flags, write tests for a documented contract. Verbs: *mirror*, *adapt*, *integrate*, *wire*. |\n>    | `reasoning:deep`    | Novel design choices: pick a new abstraction, resolve a contradiction in the spec, reconcile cross-cutting concerns. Verbs: *design*, *reconcile*, *resolve*, *redesign*. |\n>\n>    Default for issues that lack any of these signals: `ctx:64k`,\n>    `reasoning:medium`. If unsure between two ctx tiers, prefer the larger.\n>\n> 3. **Sibling normalization.** When 5+ split children share a structural\n>    criterion (e.g. all per-source-table writers, all per-skill installers),\n>    harmonize their `ctx:*`\u002F`reasoning:*` labels so the operator can run a\n>    single profile across the whole group. Override individual classifications\n>    only when the difference is a true outlier (e.g. one sibling pulls in a\n>    schema-wide refactor that no other sibling touches).\n>\n>\n> ### Issue intent safety gate\n>\n> Phase 3.5 may only persist model-fit, quality, board, and dependency\n> metadata. It must not manufacture a safety decision. Defer Rust admission\n> until the final issue body is persisted by step 8 below.\n>\n> 4. **Apply labels.** Idempotent at run start:\n>    `gh label create ctx:32k  --color c5def5 --force --repo {repo}`,\n>    `gh label create ctx:64k  --color c5def5 --force --repo {repo}`,\n>    `gh label create ctx:120k --color c5def5 --force --repo {repo}`,\n>    `gh label create reasoning:shallow --color c2e0c6 --force --repo {repo}`,\n>    `gh label create reasoning:medium  --color c2e0c6 --force --repo {repo}`,\n>    `gh label create reasoning:deep    --color c2e0c6 --force --repo {repo}`,\n>    `gh label create needs-quality-bar --color fbca04 --force --repo {repo}`.\n>    Then per issue:\n>    `gh issue edit \u003CN> --add-label \"ctx:\u003Ctier>,reasoning:\u003Cdepth>\" --repo {repo}`.\n>\n> 5. **Patch body — `## Model fit` block.** Insert immediately before the first\n>    `## Dependencies` line (or at end of body if absent):\n>\n>    ```markdown\n>    \u003C!-- autospec-classify:begin -->\n>    ## Model fit\n>\n>    - **ctx:** `ctx:\u003Ctier>` — \u003C1-line rationale>.\n>    - **reasoning:** `reasoning:\u003Cdepth>` — \u003C1-line rationale>.\n>\n>    *Auto-classified by Phase 3.5 on YYYY-MM-DD.*\n>    \u003C!-- autospec-classify:end -->\n>    ```\n>\n>    **Idempotency:** if a `## Model fit` block already exists between the\n>    `\u003C!-- autospec-classify:begin -->` and `\u003C!-- autospec-classify:end -->`\n>    markers, replace it in place. Never stack duplicates. Apply via\n>    `gh issue edit \u003CN> --body-file \u003Ctmp>`.\n>    Legacy blocks have `## Model fit` ABOVE\n>    `\u003C!-- autospec-classify:begin -->`. Replacing only the marker-delimited\n>    region orphans that heading outside the markers, where it still counts\n>    against the budget, and adds a second one. Delete the legacy heading\n>    and everything up to the begin marker first.\n>\n> 6. **Board assignment** — read `~\u002F.autospec\u002Fproject-map.yml` and assign each\n>    just-classified child to the GitHub Projects mapped from its labels.\n>\n>    **File schema** (auto-init if missing — see below):\n>    ```yaml\n>    # ~\u002F.autospec\u002Fproject-map.yml\n>    multi_match: union          # `union` (assign to every match) or `first`\n>    mappings:\n>      ctx:32k: \u003Cproject_number>\n>      ctx:64k: \u003Cproject_number>\n>      ctx:120k: \u003Cproject_number>\n>      reasoning:shallow: \u003Cproject_number>\n>      reasoning:medium:  \u003Cproject_number>\n>      reasoning:deep:    \u003Cproject_number>\n>      \u003Cany-other-label>: \u003Cproject_number>\n>    ```\n>\n>    **Reader procedure** for each issue I:\n>    - For each label L on I, look up `mappings[L]`. Skip null \u002F missing entries.\n>    - With `multi_match: union` (default), collect all matching project numbers and assign to every one of them. With `multi_match: first`, take the first match in label-order and assign to that single project.\n>    - For each chosen `\u003CP>`: `gh project item-add \u003CP> --owner \u003Cowner> --url \u003Cissue-url>`. The `gh` command is idempotent — repeated calls do not duplicate items, so re-running Phase 3.5 is safe.\n>\n>    **Auto-init when the file is missing.** Probe `gh project list --owner \u003Cowner> --format json` to confirm the user can author projects. Probe `gh label list --repo {repo} --json name -q '.[].name'` to enumerate the repo's labels. Write a starter file with every label as a `mappings:` key and `null` project numbers, plus `multi_match: union` at the top. Print:\n>    ```\n>    Wrote ~\u002F.autospec\u002Fproject-map.yml. Edit project numbers (currently null) and re-run.\n>    ```\n>    Then **exit Phase 3.5** without assigning any boards (the labels and `## Model fit` blocks remain applied — only the assign step is deferred).\n>\n>    **Hard rules.**\n>    - Never call `gh project item-add` in `--dry-run`.\n>    - Missing file in `autospec` \u002F `autospec-define` is non-fatal at run time once auto-init has populated it; if auto-init itself fails (e.g. `gh project list` denied), warn and skip board assignment for the rest of the run.\n>\n> 7. **Dependency-edge sanity checks.** After labeling, validate the dep graph\n>    of the just-created children:\n>    - **closed-dep warning** — emit `WARN: child #\u003CN> depends on closed issue #\u003CM>` for each `Depends on #M` line where `gh issue view #\u003CM> --json state` is `CLOSED`.\n>    - **child-less tracker dep warning** — emit `WARN: child #\u003CN> depends on tracker #\u003CM> with no children` when `#\u003CM>` carries `type:tracker` and has no other open `auto-implement` deps pointing at it.\n>    - **circular sibling-dep hard fail** — exit non-zero if any cycle exists among the just-created children's `Depends on #N` edges.\n>\n> 8. **Post-filing quality audit.** For each child issue (skip `type:tracker`):\n>    - Pull body: `gh issue view \u003CN> --repo {repo} --json body -q .body > \u002Ftmp\u002Faudit-\u003CN>.md`\n>    - Run: `bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Flint-issue.sh\" \u002Ftmp\u002Faudit-\u003CN>.md`\n>    - On non-zero exit (lint fails):\n>      - Apply label: `gh issue edit \u003CN> --add-label needs-quality-bar --repo {repo}`\n>      - Insert `## Quality lint` block (idempotent, between `\u003C!-- autospec-quality:begin -->` and `\u003C!-- autospec-quality:end -->` markers) via `gh issue edit \u003CN> --body-file \u003Ctmp>`. A legacy block has the heading ABOVE the begin marker: delete the legacy heading and everything up to that marker first, or it keeps counting and a duplicate is added. Block format:\n>        ```markdown\n>        \u003C!-- autospec-quality:begin -->\n>        ## Quality lint\n>\n>        - **GOAL** — \u003C1-line finding>.\n>        - **AC#\u003Cn>** — \u003C1-line finding>.\n>        - **SMOKE** — \u003C1-line finding>.\n>\n>        *Auto-linted by Phase 3.5 on YYYY-MM-DD.*\n>        \u003C!-- autospec-quality:end -->\n>        ```\n>      - Comment findings: `gh issue comment \u003CN> --body \"\u003Cfindings>\" --repo {repo}`\n>    - Do NOT remove `auto-implement` label. Operator decides whether to proceed.\n>\n> 9. **Rust safety admission.** After all prior body writes complete, make each\n>    child an interim candidate (if it is not already one) and review that exact\n>    issue:\n>\n>    ```bash\n>    gh issue edit \u003CN> --add-label auto-implement --remove-label needs-classify --repo {repo}\n>    \"${AUTOSPEC_BIN:-autospec}\" queue review-safety --repo {repo} --limit 1 --issue \u003CN>\n>    ```\n>\n>    Read the JSON totals. Only `pass: 1` admits this invocation. Any other\n>    result is already recorded by Rust and must be skipped without manual\n>    labels, comments, body patches, or a semantic safety override. The Rust\n>    command is the only automatic writer of issue-intent safety outcomes.\n>\n> 10. **Run-end summary.** Print to stdout:\n>    ```\n>    Phase 3.5 summary on {repo}\n>    - classified: N\n>    - skipped (needs-autospec-template): M\n>    - ctx:32k=A  ctx:64k=B  ctx:120k=C\n>    - reasoning:shallow=X  reasoning:medium=Y  reasoning:deep=Z\n>    - boards assigned: \u003CK> (or \"skipped — no project-map.yml\")\n>    - dep warnings: \u003Ccount>; circular cycles: \u003Ccount>\n>    ```\n\n---\n\n## Phase 3.75 — Architectural alignment (deterministic scan + reconcile)\n\nAfter Phase 3.5 has applied `ctx:*` \u002F `reasoning:*` labels and before the\npre-impl gate, build a `Shared contracts` summary so child issues don't invent\nincompatible type signatures, file-layout conventions, and naming schemes —\nintegration mismatches that are otherwise caught only in Phase 5.5.\n\nThe former standalone Tier-A (opus) pass is **replaced** by a deterministic\nscan plus an optional small Tier-B reconcile. Mechanically extracting\nsignatures \u002F file paths \u002F naming tokens is not reasoning work — a grep does it\nexactly and for free.\n\n1. **Deterministic extract (no LLM).** Dump each child issue body\n   (skip the umbrella\u002Ftracker) to a temp dir, read every child's `lang:*`\n   label into a CSV (one value per child), then run the shared scanner with\n   `--languages`:\n\n   ```bash\n   langs=\"$(for n in \"${children[@]}\"; do\n     gh issue view \"$n\" --repo {repo} --json labels -q '.labels[].name | select(startswith(\"lang:\"))'\n   done | paste -sd, -)\"\n   bash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fextract-shared-contracts.sh\" --dir \"$bodies_dir\" --languages \"$langs\" > \u002Ftmp\u002Fshared-contracts.md\n   ```\n\n   It greps every file path, `name(...)` signature, and ALL-CAPS naming\u002Fenv-var\n   token that appears in **≥2 distinct** issues and emits a `## Shared\n   contracts` block (file paths, signatures, names). Identical inputs produce\n   byte-identical output. `--languages` normalizes its values (trims,\n   strips the `lang:` prefix, de-dupes) and decides the boundary trigger:\n   when the labels span **2 or more distinct `lang:*` labels**, or when a\n   child carries `lang:mixed`, the emitted block also contains the\n   `## Cross-language boundaries` table (step 4) and the script runs its\n   own fail-closed schema check before writing anything to stdout. If it\n   reports `_No cross-issue contracts detected_` and no boundary table was\n   triggered, there is no cross-issue interface — skip the rest of Phase 3.75\n   and log `\"Phase 3.75: skipped (no cross-issue contracts)\"`.\n\n2. **Tier-B reconcile (small, only for genuine conflicts).** Skip unless the\n   scan surfaced an actual contradiction — the same path\u002Fname used with\n   **incompatible** shapes across issues (e.g. one issue declares\n   `bundle_static_context(role)` and another `bundle_static_context(role, dir)`).\n   When that happens, dispatch a small Tier-B subagent with ONLY the scanner\n   output plus the conflicting bodies and ask it to pick the authoritative\n   shape and note it in the block. Do **not** re-read every body or re-derive\n   the whole summary — the deterministic scan already did steps 1-2.\n\n3. **Patch each child issue body** by inserting the (possibly reconciled) block\n   **immediately before the first `## Dependencies` line** (append at end of body\n   only when the body has no `## Dependencies` heading):\n\n```\n\u003Cthe extract-shared-contracts.sh output verbatim, plus any Tier-B reconcile\nnotes inserted before its closing marker>\n```\n\n   Never plain-append: the block's HTML markers and `## Shared contracts` heading\n   must not land inside the `## Dependencies` section — `scripts\u002Flint-issue.sh`\n   reads that section until the next `## ` heading and reports `DEPS_MALFORMED`\n   for every line that is not `Depends on issue #N` or `none` (that append\n   placement is what broke the 13 `#3112`-generation bodies). Write the block to\n   `\u002Ftmp\u002Fshared-contracts-\u003CN>.md`, splice it in deterministically, and apply:\n\n   ```bash\n   body=\"$(gh issue view \u003CN> --json body -q .body)\"\n   printf '%s\\n' \"$body\" > \u002Ftmp\u002Fbody-\u003CN>.orig\n   if grep -q '\u003C!-- autospec-shared-contracts:begin -->' \u002Ftmp\u002Fbody-\u003CN>.orig; then\n     # Case B: the body already carries the marker region — replace the whole\n     # region (from `:begin -->` to `:end -->`, inclusive of both marker lines)\n     # with the freshly generated block so re-runs never stack a second heading.\n     awk -v f=\u002Ftmp\u002Fshared-contracts-\u003CN>.md '\n       !replaced && \u002F^\u003C!-- autospec-shared-contracts:begin -->$\u002F {\n         while ((getline line \u003C f) > 0) print line\n         skip = 1\n         replaced = 1\n         close(f)\n         next\n       }\n       skip && \u002F^\u003C!-- autospec-shared-contracts:end -->$\u002F { skip = 0; next }\n       !skip { print }\n     ' \u002Ftmp\u002Fbody-\u003CN>.orig > \u002Ftmp\u002Fbody-\u003CN>.md\n   else\n     # Case A: no marker yet — insert before the first `## Dependencies` line\n     # (append at end of body only when there is no `## Dependencies` heading).\n     awk -v f=\u002Ftmp\u002Fshared-contracts-\u003CN>.md '\n       !done && \u002F^## Dependencies$\u002F { while ((getline line \u003C f) > 0) print line; print \"\"; close(f); done = 1 }\n       { print }\n       END { if (!done) while ((getline line \u003C f) > 0) print line }\n     ' \u002Ftmp\u002Fbody-\u003CN>.orig > \u002Ftmp\u002Fbody-\u003CN>.md\n   fi\n   gh issue edit \u003CN> --body-file \u002Ftmp\u002Fbody-\u003CN>.md\n   ```\n\n   After the patch, `Depends on issue #N` must remain the last line under\n   `## Dependencies`.\n   The patch is idempotent in the strong sense: **re-running it replaces the\n   entire marker region** with the freshly generated block — it never stacks a\n   second `## Shared contracts` heading, a second boundary table, or a second\n   marker pair.\n\n   Do NOT add your own `\u003C!-- autospec-shared-contracts:begin -->` wrapper or\n   `## Shared contracts` heading: the script emits both. Nesting a second pair\n   leaves the outer marker and heading outside the region\n    `lint-issue.sh` strips, so they count against the word budget.\n\n4. **Cross-language boundaries (conditional, fail closed).** The scanner\n   decides the trigger from `--languages`: when the siblings span 2 or\n   more distinct `lang:*` labels (after the `lang:` prefixes are normalized\n   away) — or when any child carries `lang:mixed` — the block already\n   contains a `## Cross-language boundaries` table **between the\n   `\u003C!-- autospec-shared-contracts:begin -->` \u002F `:end -->` markers**. It has\n   one row per `schemas\u002F*.schema.json` path shared by ≥2 child bodies — the\n   scanner fills the `Schema (source of truth)` column with that path and\n   leaves every other cell as `-`; it never invents boundary names, and it\n   never emits an empty `Schema` cell or a `TBD` placeholder:\n\n   ```markdown\n   ## Cross-language boundaries\n\n   | Boundary | Transport | Schema (source of truth) | Owner | Golden fixture |\n   |---|---|---|---|---|\n   | cli→worker | subprocess + JSON stdout | schemas\u002Fautospec-x.schema.json | lang:rust | tests\u002Ffixtures\u002Fboundary\u002Fx.json |\n   ```\n\n   Fill the `-` cells (Boundary, Transport, Owner, Golden fixture) in each\n   affected child body from the child bodies before you edit. `Owner` is the\n   `lang:*` label of the side that owns the schema. The completed table\n   encodes three rules: the owning side lands the schema **first**; the consuming\n   issue carries `Depends on issue #N` against it; each boundary gets one golden\n   fixture under `tests\u002Ffixtures\u002F` asserted by **both** sides' own test runners —\n   that two-sided assertion is the only thing that catches drift.\n\n   **Fail-closed schema rule.** Every `Schema` cell must name a file that exists\n   under `schemas\u002F`. The scanner enforces this before it writes anything: when\n   a row's schema file is missing, it prints\n   `PHASE_3_75_FAILED rule=boundary-schema-missing path=\u003Cschema>` to stderr,\n   writes nothing to stdout, and exits 1. Re-run the same check on the\n   **filled** block before editing (a filled cell may point at a path the\n   scanner did not see) rather than emitting an unbacked table:\n\n   ```bash\n   boundaries=\u002Ftmp\u002Fshared-contracts.md   # the block, after filling the cells\n   missing=0\n   while read -r schema; do\n     [ -f \"$schema\" ] || { echo \"PHASE_3_75_FAILED rule=boundary-schema-missing path=$schema\"; missing=1; }\n   done \u003C \u003C(grep -oE 'schemas\u002F[A-Za-z0-9._\u002F-]+\\.json' \"$boundaries\" | sort -u)\n   [ \"$missing\" -eq 0 ] || exit 1\n   ```\n\n   On failure: do not patch any child body with the boundary table, leave\n   `auto-implement` off the children of that boundary, and comment the missing\n   schema paths on the owning issue so the schema can land first. An unbacked\n   row is the exact failure this rule exists to prevent. When the check passes,\n   log `\"Phase 3.75: cross-language boundaries verified (\u003Ccount>)\"`.\n\nIf there are fewer than 2 child issues, or all child issues are in the same\nfile (no cross-issue interface), skip Phase 3.75 and log:\n`\"Phase 3.75: skipped (single-file scope)\"`\n\n---\n\n## Spec supersession (recency)\n\nSpecs in `docs\u002Fspecs\u002F` accumulate over time. When a newer spec adds, modifies, or\nremoves behavior that an earlier spec described, autospec applies\n**implicit-by-recency supersession** (issue #635): the spec whose\nlast-modifying commit on the current branch is most recent wins for any\noverlapping behavior (untracked specs fall back to filesystem mtime).\nOperators do NOT write `Supersedes:` frontmatter — recency alone decides.\n\nDuring Phase 3 decomposition, before filing a candidate child issue, resolve\nthe authoritative spec for each behavior the issue touches. Use the shared\nhelper:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fresolve-spec-supersession.sh\" \"\u003Cbehavior-key>\"\n```\n\nIf the resolver prints a spec path other than the one currently being\ndecomposed, the candidate behavior has already been overridden by a newer\nspec — skip filing the issue (it would re-introduce removed behavior) and\nnote the supersession in the decompose run log. If the resolver exits 1 (no\noverlap), proceed normally: the behavior is new to this spec.\n\nSee `tests\u002Fresolve-spec-supersession.bats` for the resolver contract:\nno-overlap → exit 1, single overlap → that spec wins, two\u002Fthree-way overlap\n→ most recent wins, deleted specs are excluded.\n\n## Phase 3 pre-impl gate\n\nAfter Phase 3 decomposition completes (and Phase 3.5 review-and-label has\napplied `ctx:*` \u002F `reasoning:*` labels), end Phase 3 by asking the user\nthis verbatim question (no auto-launch — always ask explicitly, per spec\n§3.3):\n\n> `\"Spec written, N issues filed. Start \u002Fautospec-run now, defer to your external daemon, or keep refining? [run \u002F defer \u002F refine]\"`\n\nSubstitute `N` with the actual issue count from Phase 3. Default highlight\nis **`defer`** for `\u002Fautospec-define` (the plan-only skill — the user\ninvoked `\u002Fautospec-define` expecting plan-only behavior, so the gate\ndefaults to `defer`).\n\n- **`run`** — invoke `\u002Fautospec-run` in the current session.\n- **`defer`** (default for `\u002Fautospec-define`) — print\n  `\"Issues are ready. Your external monitor will pick them up. Exiting.\"`\n  and stop without launching `\u002Fautospec-run`. The just-filed `auto-implement`\n  queue persists on the GitHub side so an external daemon (or a later\n  `\u002Fautospec-run` invocation) can pick it up.\n- **`refine`** — re-enter Phase 2 from question 1 (Architecture).\n\nNo daemon auto-detection — always ask explicitly.\n\nAfter all decomposition issues are filed (and before asking the gate question),\nfile one additional child issue titled\n`\"Phase 5.5 audit + remediation — \u003Cfeature-name>\"` with labels\n`auto-implement,priority:high,audit`, then post a comment on the umbrella issue\nlinking it: `\"Phase 5.5 audit tracker: #\u003CN>\"`.\n\nAfter the user answers `run` or `defer` (i.e. the design is locked and issues\nare filed), call `diary-write.sh` to record the brainstorm decision:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fdiary-write.sh\" \\\n  --phase 1 \\\n  --event brainstorm-locked \\\n  --body \"Spec locked: ${SPEC_PATH}. Gate answer: ${GATE_ANSWER}. Issues filed: ${ISSUE_COUNT}.\" \\\n  2>\u002Fdev\u002Fnull || true\n```\n\n(Best-effort — never blocks the gate flow.)\n\n## Handoff\n\nIf the gate answer was `run`, hand off to `\u002Fautospec-run --profile \u003Cname>`\nto begin implementation. If the answer was `defer`, the run ends here and\nthe queue is left for an external monitor.\n\n## Init mode\n\nTriggered by `--init` flag or auto-detected when code exists but `docs\u002Fspecs\u002F` is empty or no doc carries an `autospec-doc-scope` annotation.\n\n### Auto-detect prompt\n\nWhen auto-detecting, ask once:\n\n> This repo has source code but no autospec docs. Run reverse-engineer first?\n> **[yes \u002F no \u002F always-this-repo]**\n\n- `yes` — run `--init` once for this invocation.\n- `no` — skip; proceed to Phase 1 normally.\n- `always-this-repo` — run `--init` and write `.autospec\u002Finit-done.flag`; future invocations skip this prompt.\n\nIf `.autospec\u002Finit-done.flag` exists, skip the prompt entirely.\n\n### --init execution\n\n1. Run tree-sitter scan across the repo source tree to enumerate modules, public symbols, and entry points.\n2. Emit one ARCHITECTURE-level spec to `docs\u002Fspecs\u002F\u003Crepo-slug>-architecture.md`.\n3. Emit per-module specs to `docs\u002Fspecs\u002F\u003Cmodule>-spec.md` for each discovered module.\n4. Generate initial docs via `gen-docs-from-spec.mjs`:\n   - `docs\u002FUSER_MANUAL.md`\n   - `docs\u002FAPI_REFERENCE.md`\n   - `docs\u002FARCHITECTURE.md`\n   - `llms.txt`\n   - `.llm-manifest.json`\n5. Open a `feat\u002Fspec-reverse-engineer-init` PR with all generated artifacts.\n6. Admin-merge the doc PR before proceeding to Phase 3 decomposition.\n\n### Auto-docs step (after spec PR merges)\n\nAfter any spec PR merges in normal `autospec-define` flow, regenerate\ndocumentation through the single doc engine — invoke `\u002Fautospec-doc`\n(incremental, scoped to the docs the merged spec affects), routed via\n`doc-orchestrator.mjs`:\n\n```bash\nbash \"${AUTOSPEC_SCRIPTS_DIR:-$HOME\u002F.autospec\u002Fscripts}\u002Fdoc-orchestrator.mjs\"\n```\n\n`\u002Fautospec-doc` is the only documentation-generation path; there is no\nparallel generator. Open a `docs\u002F` update PR and admin-merge it before Phase 3\nbegins. Skip if the spec change touches only non-public implementation details\n(no change to public API surface, no new CLI flags, no new env vars).\n\n## Autonomous mode\n\nWhen `\u002Fautospec-define --autonomous \"\u003Crequest>\"` runs, or when\n`~\u002F.autospec\u002Fautonomous.flag` exists at run start, Phase 2 and the Phase 3\npre-impl gate skip user-facing confirmations.\n\nBranches taken in autonomous mode:\n\n- **Phase 2 brainstorm** — do NOT ask the Architecture \u002F Interactivity \u002F\n  Data model \u002F Error handling \u002F Testing questions one at a time. Synthesize\n  the entire spec from (a) the user's request text, (b) the last ~10\n  conversation turns, (c) `git log --since=\"7 days ago\"` recent commits,\n  and (d) similar prior work in `docs\u002Fspecs\u002F**`. For each unverifiable\n  inference, mark the line in the spec body with a\n  `> AUTONOMOUS ASSUMPTION:` blockquote.\n- **Phase 3 pre-impl gate** — default to `run`. Do NOT ask\n  `[run \u002F defer \u002F refine]`. Proceed to issue filing without confirmation.\n- **Issue body confirmation** — `gh issue create` runs without per-issue\n  approval. The existing lint loop, sizing caps, and Phase 3.5 model-fit\n  classification still apply unchanged.\n\nIf the orchestrator cannot generate a coherent spec from available context\n(e.g. \"make it better\" with no surface evidence), autonomous mode FAILS\nLOUDLY with `code_health:autonomous_input_insufficient` and prints the\nspecific missing fields plus a recommended interactive command to retry.\nDo not silently pick arbitrary defaults.\n\nSafety guardrails are NOT bypassed. Before each would-have-asked decision,\nthe orchestrator invokes `autospec-autonomy-gate.sh` with\n`--check all`. Exit 1 surfaces the confirmation even in autonomous mode:\n\n- Destructive remote actions (force-push, repo archive\u002Fdelete, mass label\n  changes, prod DB writes).\n- Out-of-scope planned files (extend beyond Goal + Implementation outline).\n- Cost gate (`AUTOSPEC_AUTONOMOUS_TOKEN_CAP`, default 500k).\n- Existing `feedback_autospec_autonomy_scope.md` rules.\n\nThe handoff to `\u002Fautospec-run` preserves the `--autonomous` flag so the\nimplementation half honors the same telemetry tagging.\n",{"name":5,"description":7},"main","9e7f04357ff46ab731d4f56a4ac5ca5449c13bb0","skills\u002Fautospec-define",1,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec","https:\u002F\u002Fgithub.com\u002Fberlinguyinca","Love to lead, code, cook and contribute to open source and believe that you can learn anything you set your mind too.\r\n","2026-11-11 07:09:35",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add berlinguyinca\u002Fautospec --skill autospec-define",{"tool":71,"command":72},"bunx","bunx skills add berlinguyinca\u002Fautospec --skill autospec-define",{"tool":74,"command":75},"pnpm","pnpm dlx skills add berlinguyinca\u002Fautospec --skill autospec-define","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002FSKILL.md",true,[79,85,91,95,99,103],{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"codex\u002Fprompt.md","REFERENCE","参考文档",83810,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002Fcodex\u002Fprompt.md",{"path":86,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":89,"sourceHtmlUrl":90},"install.sh","SCRIPT","脚本",11507,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002Finstall.sh",{"path":92,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":93,"sourceHtmlUrl":94},"opencode\u002Fagent.md",84124,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002Fopencode\u002Fagent.md",{"path":96,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":97,"sourceHtmlUrl":98},"prompts\u002Fdecomposer-contract.md",20436,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002Fprompts\u002Fdecomposer-contract.md",{"path":100,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":101,"sourceHtmlUrl":102},"README.md",4431,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002FREADME.md",{"path":104,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":105,"sourceHtmlUrl":106},"uninstall.sh",3940,"https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-define\u002Funinstall.sh",[108,117,126,135,157,181],{"skillNo":109,"name":110,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":114,"publishedAt":52},"01M71RJHYMKPTC9AAPXWQ6F4RT","trio-pass-skill","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Flockstep-trio-pass\u002FSKILL.md",[113],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[115,116],"trio","trio pass skill",{"skillNo":118,"name":119,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":123,"publishedAt":52},"01M71RJFBQ1KAF9XM3T3Y4VMSK","duo-pass-skill","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Flockstep-duo-pass\u002FSKILL.md",[122],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[124,125],"duo pass skill","duo",{"skillNo":127,"name":128,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":132,"publishedAt":52},"01M71RJDT1TB3P9TRWR6A534FB","duo-divergence-skill","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Flockstep-duo-divergence\u002FSKILL.md",[131],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[133,125,134],"duo divergence skill","divergence",{"skillNo":136,"name":32,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":141,"publishedAt":52},"01M71RJAC4NNEQSYBDSY3NZS73","Use when the user wants to ship a feature end-to-end across multiple commits — bootstraps repo if missing, brainstorms a design spec, decomposes into linked GitHub issues, or splits an existing spec into issues, then runs an autonomous implementation loop with auto-merge.","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec\u002FSKILL.md",[140],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[32,142,143,144,51,145,146,147,148,149,49,150,151,152,153,154,155,44,156,43],"ship a feature","end","issues","autonomous","auto","loop","when","across","merge","ship","implementation loop","github issues","feature","commits","missing",{"skillNo":158,"name":159,"nameZh":6,"description":160,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":161,"categories":162,"keywords":163,"publishedAt":52},"01M71RJ4F9HT8PT26CKNM9XE1M","autospec-upgrade","Use when the user wants to upgrade an Angular, Next.js, or React project to the latest official versions safely — by locking observable behavior before touching versions, upgrading one major at a time with official codemods, and gating completion on mutation score rather than coverage theater.","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-upgrade\u002FSKILL.md",[],[164,32,165,166,167,168,169,170,171,148,172,173,174,175,43,176,177,178,179,180],"autospec upgrade","upgrade","mutation","coverage","official","project","time","gating","angular","react","next","at","Next.js","one","with","behavior","latest",{"skillNo":182,"name":183,"nameZh":6,"description":184,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":185,"categories":186,"keywords":188,"publishedAt":52},"01M71RJ28FJ4PM6DXHB7T5CF8H","autospec-ui-audit","Use when a React Router application needs a deterministic whole-site route inventory before UI, UX, navigation, or evidence auditing begins.","https:\u002F\u002Fgithub.com\u002Fberlinguyinca\u002Fautospec\u002Fblob\u002Fmain\u002Fskills\u002Fautospec-ui-audit\u002FSKILL.md",[187],{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},[189,32,190,191,192,43,193,194,195,196,197,198,199,200,201,173,202,148,203],"ui audit","audit","autospec ui audit","ui","inventory","evidence","deterministic","route","ux","site","react router","navigation","application","needs","router"]