t3-auto-build 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,135 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { isObject, parseJson } from '../hooks/_shared.mjs';
5
+ import { CliError } from './paths.mjs';
6
+
7
+ export const ENV_NAME = 'CLAUDE_AUTOCOMPACT_PCT_OVERRIDE';
8
+ export const HOOKS_DIR = 'hooks/t3-auto-build';
9
+ const TAG = '--managed-by=t3-auto-build';
10
+
11
+ export const HOOKS = [
12
+ { event: 'SessionStart', script: 'session-start.mjs' },
13
+ { event: 'PreCompact', script: 'pre-compact.mjs' },
14
+ { event: 'PreToolUse', script: 'pre-tool-use.mjs', matcher: 'Edit|Write|MultiEdit|Bash|delegate_task|mcp__.*__delegate_task' },
15
+ { event: 'PostToolUse', script: 'post-tool-use.mjs', matcher: 'Edit|Write|MultiEdit' },
16
+ ];
17
+
18
+ export const isTagged = (hook) => typeof hook?.command === 'string' && /(^|\s)--managed-by=t3-auto-build(\s|$)/.test(hook.command);
19
+
20
+ export function hookCommand(target, script) {
21
+ let file = path.join(target, ...HOOKS_DIR.split('/'), script);
22
+ if (process.platform === 'win32') file = file.replace(/\\/g, '/');
23
+ // These stay special inside double quotes in sh, cmd or PowerShell.
24
+ if (/["$`%\\\r\n“-„]/.test(file)) {
25
+ throw new CliError(`the target path contains a character that is unsafe in a hook command: ${target}`);
26
+ }
27
+ return `node "${file}" ${TAG}`;
28
+ }
29
+
30
+ /** { file, raw, data }. Throws, before anything is written, on content we cannot merge safely. */
31
+ export function readSettings(target) {
32
+ let file = path.join(target, 'settings.json');
33
+ let raw = null;
34
+ try {
35
+ file = fs.realpathSync(file); // keep a symlinked settings.json a symlink
36
+ raw = fs.readFileSync(file, 'utf8');
37
+ } catch (error) {
38
+ if (error.code !== 'ENOENT') throw new CliError(`cannot read ${file}: ${error.code}`);
39
+ }
40
+ if (raw === null) return { file, raw, data: {} };
41
+ let data;
42
+ try {
43
+ data = parseJson(raw);
44
+ } catch {
45
+ // The parse error is not echoed: it can quote file content, which may hold secrets.
46
+ throw new CliError(`${file} is not valid JSON; nothing was changed`);
47
+ }
48
+ const mergeable =
49
+ isObject(data) &&
50
+ (data.env === undefined || isObject(data.env)) &&
51
+ (data.hooks === undefined || (isObject(data.hooks) && HOOKS.every(({ event }) => data.hooks[event] === undefined || Array.isArray(data.hooks[event]))));
52
+ if (!mergeable) throw new CliError(`${file} has an unexpected structure (settings, env, hooks); nothing was changed`);
53
+ return { file, raw, data };
54
+ }
55
+
56
+ /** Every tagged hook entry as { event, matcher, hook }. */
57
+ export function taggedHooks(data) {
58
+ return Object.entries(isObject(data.hooks) ? data.hooks : {}).flatMap(([event, groups]) =>
59
+ (Array.isArray(groups) ? groups : []).flatMap((group) =>
60
+ (Array.isArray(group?.hooks) ? group.hooks : []).filter(isTagged).map((hook) => ({ event, matcher: group.matcher, hook })),
61
+ ),
62
+ );
63
+ }
64
+
65
+ function removeTagged(data) {
66
+ if (taggedHooks(data).length === 0) return;
67
+ for (const [event, groups] of Object.entries(data.hooks)) {
68
+ if (!Array.isArray(groups)) continue;
69
+ let removed = false;
70
+ const kept = groups.flatMap((group) => {
71
+ if (!Array.isArray(group?.hooks) || !group.hooks.some(isTagged)) return [group];
72
+ removed = true;
73
+ const hooks = group.hooks.filter((hook) => !isTagged(hook));
74
+ return hooks.length ? [{ ...group, hooks }] : [];
75
+ });
76
+ if (!removed) continue;
77
+ if (kept.length) data.hooks[event] = kept;
78
+ else delete data.hooks[event];
79
+ }
80
+ if (Object.keys(data.hooks).length === 0) delete data.hooks;
81
+ }
82
+
83
+ const desiredEntries = (target) =>
84
+ HOOKS.map(({ event, matcher, script }) => ({ event, matcher, hook: { type: 'command', command: hookCommand(target, script) } }));
85
+
86
+ /** Returns { data, env }: new settings plus the manifest record needed to undo the env change. */
87
+ export function mergeSettings(current, target, percent, previous) {
88
+ const data = structuredClone(current);
89
+ const desired = desiredEntries(target);
90
+ const present = taggedHooks(data);
91
+ const correct = present.length === desired.length && desired.every((want) => present.some((have) => isDeepStrictEqual(have, want)));
92
+ if (!correct) {
93
+ removeTagged(data);
94
+ data.hooks ??= {};
95
+ for (const { event, matcher, hook } of desired) {
96
+ data.hooks[event] = [...(data.hooks[event] ?? []), { ...(matcher && { matcher }), hooks: [hook] }];
97
+ }
98
+ }
99
+ const installed = String(percent);
100
+ const had = Object.prototype.hasOwnProperty.call(data.env ?? {}, ENV_NAME);
101
+ // The first recorded prior value wins; a re-run only updates what we installed.
102
+ const env = previous
103
+ ? { ...previous, installed }
104
+ : { had, prior: had ? data.env[ENV_NAME] : null, createdEnv: data.env === undefined, installed };
105
+ data.env = { ...data.env, [ENV_NAME]: installed };
106
+ return { data, env };
107
+ }
108
+
109
+ export function unmergeSettings(current, env) {
110
+ const data = structuredClone(current);
111
+ removeTagged(data);
112
+ if (env && data.env?.[ENV_NAME] === env.installed) {
113
+ if (env.had) data.env[ENV_NAME] = env.prior;
114
+ else delete data.env[ENV_NAME];
115
+ if (env.createdEnv && Object.keys(data.env).length === 0) delete data.env;
116
+ }
117
+ return data;
118
+ }
119
+
120
+ /** Writes (via temp file + rename, keeping a .bak) only when the content really changes. */
121
+ export function writeSettings({ file, raw, data: before }, after) {
122
+ if (isDeepStrictEqual(before, after)) return false;
123
+ const indent = raw?.match(/^[ \t]+(?=")/m)?.[0] ?? 2;
124
+ const mode = raw === null ? 0o600 : fs.statSync(file).mode & 0o777;
125
+ if (raw !== null) fs.copyFileSync(file, `${file}.bak`);
126
+ const temp = `${file}.${process.pid}.tmp`;
127
+ try {
128
+ fs.writeFileSync(temp, `${JSON.stringify(after, null, indent)}\n`, { mode });
129
+ fs.chmodSync(temp, mode);
130
+ fs.renameSync(temp, file);
131
+ } finally {
132
+ fs.rmSync(temp, { force: true });
133
+ }
134
+ return true;
135
+ }
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "t3-auto-build",
3
+ "version": "1.0.0",
4
+ "description": "Cross-platform installer and $auto-build orchestration suite for T3 Code.",
5
+ "type": "module",
6
+ "bin": {
7
+ "t3-auto-build": "bin/cli.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "lib",
12
+ "core",
13
+ "presets",
14
+ "skills",
15
+ "hooks"
16
+ ],
17
+ "scripts": {
18
+ "test": "node --test"
19
+ },
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "license": "MIT"
24
+ }
@@ -0,0 +1,31 @@
1
+ {
2
+ "preset": "claude-codex",
3
+ "allowlist": {
4
+ "Codex": [
5
+ "gpt-5.6-luna",
6
+ "gpt-5.6-terra",
7
+ "gpt-6-luna"
8
+ ],
9
+ "Claude": [
10
+ "Claude Haiku 5.5",
11
+ "Claude Sonnet 5.5",
12
+ "Claude Opus 5.5"
13
+ ]
14
+ },
15
+ "bannedModels": ["Argon", "Fable/Mythos"],
16
+ "defaultModel": "Claude Sonnet 5.5",
17
+ "defaultEffort": "medium",
18
+ "compactionThreshold": 35,
19
+ "ladders": {
20
+ "tier1": ["gpt-5.6-luna", "gpt-5.6-terra", "gpt-6-luna", "Claude Haiku 5.5", "Claude Sonnet 5.5"],
21
+ "commandRunner": ["gpt-6-luna", "gpt-5.6-terra", "Claude Sonnet 5.5", "gpt-5.6-luna", "Claude Haiku 5.5"],
22
+ "builderA": ["Claude Sonnet 5.5", "gpt-6-luna", "Claude Opus 5.5@medium", "gpt-5.6-terra@high", "gpt-5.6-luna@high"],
23
+ "testerA": ["Claude Sonnet 5.5", "gpt-6-luna", "Claude Opus 5.5@medium"],
24
+ "auditorA": ["Claude Opus 5.5", "Claude Sonnet 5.5@high", "gpt-6-luna@high"],
25
+ "builderB": ["Claude Sonnet 5.5", "gpt-6-luna", "Claude Opus 5.5@medium", "gpt-5.6-terra@high", "gpt-5.6-luna@high"],
26
+ "testerB": ["gpt-6-luna", "Claude Sonnet 5.5", "Claude Opus 5.5@medium"],
27
+ "auditorB": ["Claude Opus 5.5", "gpt-6-luna@high", "Claude Sonnet 5.5@high"],
28
+ "architect": ["Claude Opus 5.5@high", "Claude Sonnet 5.5@high", "gpt-6-luna@high", "gpt-5.6-terra@high"],
29
+ "dualAudit": ["Claude Opus 5.5@high", "gpt-6-luna@high"]
30
+ }
31
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "preset": "claude-only",
3
+ "allowlist": {
4
+ "Claude": [
5
+ "Claude Haiku 5.5",
6
+ "Claude Sonnet 5.5",
7
+ "Claude Opus 5.5"
8
+ ]
9
+ },
10
+ "bannedModels": ["Argon", "Fable/Mythos"],
11
+ "defaultModel": "Claude Sonnet 5.5",
12
+ "defaultEffort": "medium",
13
+ "compactionThreshold": 35,
14
+ "ladders": {
15
+ "tier1": ["Claude Haiku 5.5", "Claude Sonnet 5.5"],
16
+ "commandRunner": ["Claude Sonnet 5.5", "Claude Haiku 5.5"],
17
+ "builderA": ["Claude Sonnet 5.5", "Claude Opus 5.5@medium"],
18
+ "testerA": ["Claude Sonnet 5.5", "Claude Opus 5.5@medium"],
19
+ "auditorA": ["Claude Opus 5.5", "Claude Sonnet 5.5@high"],
20
+ "builderB": ["Claude Sonnet 5.5", "Claude Opus 5.5@medium"],
21
+ "testerB": ["Claude Sonnet 5.5", "Claude Opus 5.5@medium"],
22
+ "auditorB": ["Claude Opus 5.5", "Claude Sonnet 5.5@high"],
23
+ "architect": ["Claude Opus 5.5@high", "Claude Sonnet 5.5@high"],
24
+ "dualAudit": ["Claude Opus 5.5@high", "Claude Sonnet 5.5@high"]
25
+ }
26
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "preset": "tri-provider",
3
+ "allowlist": {
4
+ "Codex": [
5
+ "gpt-5.6-luna",
6
+ "gpt-5.6-terra",
7
+ "gpt-6-luna"
8
+ ],
9
+ "Antigravity": [
10
+ "Gemini 4 Hydrogen",
11
+ "Gemini 4 Neon",
12
+ "Gemini 4 Carbon"
13
+ ],
14
+ "Claude": [
15
+ "Claude Haiku 5.5",
16
+ "Claude Sonnet 5.5",
17
+ "Claude Opus 5.5"
18
+ ]
19
+ },
20
+ "bannedModels": ["Argon", "Fable/Mythos"],
21
+ "defaultModel": "Claude Sonnet 5.5",
22
+ "defaultEffort": "medium",
23
+ "compactionThreshold": 35,
24
+ "ladders": {
25
+ "tier1": ["gpt-5.6-luna", "gpt-5.6-terra", "gpt-6-luna", "Gemini 4 Hydrogen", "Claude Haiku 5.5", "Gemini 4 Neon", "Claude Sonnet 5.5"],
26
+ "commandRunner": ["gpt-6-luna", "gpt-5.6-terra", "Claude Sonnet 5.5", "Gemini 4 Hydrogen", "gpt-5.6-luna", "Claude Haiku 5.5", "Gemini 4 Neon"],
27
+ "builderA": ["Gemini 4 Neon", "Claude Sonnet 5.5", "gpt-6-luna", "Gemini 4 Carbon@medium", "Claude Opus 5.5@medium", "gpt-5.6-terra@high", "gpt-5.6-luna@high"],
28
+ "testerA": ["Claude Sonnet 5.5", "gpt-6-luna", "Gemini 4 Neon", "Claude Opus 5.5@medium", "Gemini 4 Carbon@medium"],
29
+ "auditorA": ["Claude Opus 5.5", "Claude Sonnet 5.5@high", "Gemini 4 Carbon", "gpt-6-luna@high", "Gemini 4 Neon@high"],
30
+ "builderB": ["Claude Sonnet 5.5", "Gemini 4 Neon", "gpt-6-luna", "Claude Opus 5.5@medium", "Gemini 4 Carbon@medium", "gpt-5.6-terra@high", "gpt-5.6-luna@high"],
31
+ "testerB": ["Gemini 4 Neon", "gpt-6-luna", "Claude Sonnet 5.5", "Gemini 4 Carbon@medium", "Claude Opus 5.5@medium"],
32
+ "auditorB": ["Gemini 4 Carbon", "Gemini 4 Neon@high", "Claude Opus 5.5", "gpt-6-luna@high", "Claude Sonnet 5.5@high"],
33
+ "architect": ["Gemini 4 Carbon@high", "Claude Opus 5.5@high", "Gemini 4 Neon@high", "Claude Sonnet 5.5@high", "gpt-6-luna@high", "gpt-5.6-terra@high"],
34
+ "dualAudit": ["Claude Opus 5.5@high", "Gemini 4 Carbon@high"]
35
+ }
36
+ }
@@ -0,0 +1,166 @@
1
+ ---
2
+ name: auto-build
3
+ description: Smart-lean multi-model orchestrator for T3 Code using delegate_task with shared REPO_BRIEF and cached repo-profile, task-shape/risk L0-L3 routing, wave-based parallel builds, resumable state, diff-scoped BLOCKER/NIT audits, strict output budgets, targeted-first tests, lint-gated L3 dual audit, opposite-provider blind edge-case tests, evidence-only rejections, oscillation escalation, follow-up auto-scaling, full inline flag controls, cross-thread quota lockouts, and full-spectrum cross-provider failover across {{modelCount}} allowlisted models.
4
+ ---
5
+
6
+ You are the autonomous orchestrator for T3 Code. Execute the full pipeline using native `delegate_task` calls without pausing to ask the user between steps (unless `--plan-only` or `--dry-run` is specified).
7
+
8
+ Rendered by t3-auto-build from `{{configPath}}`. Edit that file and re-run `t3-auto-build init` instead of editing this skill.
9
+
10
+ ## 1. Inline Flags & Follow-Up Auto-Scaling
11
+ Parse all leading `--*` flags from the user's prompt before routing:
12
+
13
+ ### Rigor & Flow Control
14
+ - `--fast`: Cap complexity at `L1` (skips planning, blind tests, and dual audit).
15
+ - `--strict`: Force `L3` rigor (plan cross-check, blind edge-case tests, parallel dual audit).
16
+ - `--plan-only`: Stop after Step 2 and present the plan for user approval without editing code.
17
+ - `--dry-run`: Run Step 0 and Step 1 (`REPO_BRIEF`), then stop and output the planned routing table (`L0`-`L3`, work shape, builder, auditor, effort levels, active lockouts) without delegating planning or code edits.
18
+ - `--audit-only`: Skip Step 2 and Step 3; run Step 1 (`REPO_BRIEF`) + Step 5 (test/lint + cross-provider adversarial audit) directly against current uncommitted `git diff` changes, followed by Step 6 fix rounds if needed.
19
+ - `--resume`: Continue an interrupted run from `.claude/auto-build-state.json` (Step 0), skipping completed waves.
20
+ - `--commit`: At the end of Step 7, automatically stage and create a clean conventional commit (`feat:`, `fix:`, `refactor:`, etc.) ONLY if tests pass AND the audit verdict is `APPROVED`.
21
+
22
+ ### Token & Verification Control
23
+ - `--no-audit`: Skip the code audit in Step 5 (still runs tests/lint unless `--no-tests` is also set).
24
+ - `--no-tests`: Skip writing blind edge-case tests in Step 4 and skip running the test suite in Step 5 (for pure copy, CSS, or config edits).
25
+ - `--budget`: Force minimum-quota routing (`Tier 1` / `low` effort wherever possible, `Tier 2` at `low` effort for `L1`-`L3` implementation, mid-tier Auditor Ladder models at `medium` effort instead of the top-tier auditors).
26
+
27
+ ### Provider & Cooldown Control
28
+ - `--reset-cooldowns`: Run `t3-auto-build quota clear --all` at the start of the run, before routing (CLI not on PATH: delete `{{cooldownsPath}}`).
29
+ {{providerFlags}}
30
+
31
+ ### Follow-Up Refinement Rule (Same Thread Without `$auto-build`)
32
+ If the user sends a follow-up request in an active `$auto-build` thread without re-typing `$auto-build`:
33
+ - **Questions / explanations:** Answer directly from thread context without running the pipeline.
34
+ - **Micro-tweak (`L0`: single-file edit under 20 lines, copy/CSS/rename, zero logic/security risk):** Run Step 0 + `Tier 1 (low)` edit + Step 3.5 diff guard + Step 5.1 targeted test/lint check (skipping full planning and dual audits).
35
+ - **Substantive change (`L1`-`L3`: new logic, multi-file change, bugfix with behavioral impact, or high-risk domain):** Automatically re-run the full `$auto-build` pipeline from Step 0, reusing `.claude/repo-profile.md` and `REPO_BRIEF` if target files have not changed.
36
+
37
+ ## 2. Strict {{modelCount}}-Model Allowlist & Token Discipline
38
+ ONLY these {{modelCount}} models may ever be used (further narrowed if a `--*-only` flag is active):
39
+ {{allowlist}}
40
+
41
+ - **BANNED:** Never use, delegate to, or fall back to {{banned}}any model not listed above.
42
+ - **EXPLICIT PARAMS:** Every `delegate_task` call MUST explicitly specify `provider`, `model`, and `effort` (`low`, `medium`, or `high`). Never omit model or effort.
43
+ - **DEFAULT:** When no ladder below covers a role, use `{{defaultModel}}` at `{{defaultEffort}}` effort.
44
+ - **HARD OUTPUT BUDGETS:** Instruct every sub-agent to stay concise and skip filler:
45
+ - `REPO_BRIEF`: at most 15 lines.
46
+ - `Architecture Plan` (Step 2): at most 25 lines (file list, edge cases, test targets only).
47
+ - `Blind Edge-Case Tests` (Step 4): test code + 5-line summary max.
48
+ - `Code Audit` (Step 5.2): at most 15 lines (`VERDICT: APPROVED` or `VERDICT: REJECTED` + findings tagged `BLOCKER` or `NIT`; zero praise or vague style chatter).
49
+
50
+ - **NO EXTRA ADVISOR CALLS:** Do NOT call any built-in `Advisor` tool between or after pipeline steps—rely solely on `delegate_task` sub-agents defined in this skill.
51
+ - **CONTEXT:** Auto-compaction is configured at {{compactionThreshold}}% context use; keep `REPO_BRIEF` and pipeline state compact.
52
+
53
+ ## 3. Task-Shape Model Routing & Full-Spectrum Failover Ladders
54
+ Select models by **Work Shape** and **Pipeline Role**, walking the full cross-provider failover ladder so no step ever dead-ends unless every eligible allowlisted model is exhausted (subject to active lockouts and `--*-only` flags):
55
+
56
+ - **Tier 1 — Triage, Repo Scans & Mechanical `L0` Edits (`low` effort):**
57
+ {{tier1}}
58
+ - **Work Shape A — Multi-File Feature / Wide-Context / UI & Cross-Module Wiring:**
59
+ - **Builder Ladder (Step 3):** {{builderA}}
60
+ - **Blind Edge-Case Tester (Step 4, prefer opposite provider from builder):** {{testerA}}
61
+ - **Auditor Ladder (Step 5.2, prefer opposite provider from builder):** {{auditorA}}
62
+ - **Work Shape B — Complex State / Algorithms / Regex / Surgical Debugging:**
63
+ - **Builder Ladder (Step 3):** {{builderB}}
64
+ - **Blind Edge-Case Tester (Step 4, prefer opposite provider from builder):** {{testerB}}
65
+ - **Auditor Ladder (Step 5.2, prefer opposite provider from builder):** {{auditorB}}
66
+ - **Tier 3 Architecture Plan (`L2`/`L3` Step 2):**
67
+ {{architect}}
68
+ - **High-Risk `L3` / `--strict` Dual Audit (Step 5.2):**
69
+ {{dualAuditRun}} (security/state/spec and cross-repo/architecture/performance), failing over independently along the Auditor Ladder on lockout or exhaustion.
70
+
71
+ ## 4. Cross-Thread Cooldowns, Quota Failover & Circuit Breaker
72
+ Lockouts persist across threads in `{{cooldownsPath}}`, combined with an in-run `EXHAUSTED` list:
73
+ - **Keys:** `model:<id>` | `provider:<p>` | `tier:<p>:heavy` (that provider's heavy models only). Model ids may be display names.
74
+ - **Entry:** `{ "scope": "model|provider|tier", "window": "burst|5h|weekly|custom", "until": "<ISO-8601 UTC>", "reason": "<short reason>", "source": "<who recorded it>" }`. Legacy entries (bare model/provider key with `scope` and `until_utc`) are still read.
75
+ - **Locked means unavailable:** An unexpired entry removes every model it covers from every ladder (a hook blocks locked models). Never retry or override a lock.
76
+
77
+ 1. **Permanent Plan Errors** (model not in the plan/subscription, not entitled, unknown or unsupported model): Add to `EXHAUSTED`, fail over immediately, record NO cooldown, and advise the user to run `t3-auto-build sync-models`.
78
+ 2. **Quota & Rate Limits:** Classify the error and record it with `t3-auto-build quota set <provider|model> --burst|--5h|--weekly`:
79
+ - `--burst` (HTTP 429, rate limit, transient or unavailable; about 10 min): the model.
80
+ - `--5h` (session or usage limit) or `--weekly` (weekly cap): the provider. If only its heavy models are capped, the lock is `tier:<p>:heavy`.
81
+ - CLI not on PATH: write the entry into `{{cooldownsPath}}` yourself with `source: "orchestrator"` (reset time from the error, else +10 min / +5 h / +7 days).
82
+ 3. **Ladder Failover:** Add everything the lock covers to `EXHAUSTED`, skip those sibling models, and retry the failed step with the next eligible (unlocked, allowed by any `--*-only` flag) model in that role's ladder. Log the failover and lock expiry in the Model Trace.
83
+ 4. **Quota Exhaustion:** If no eligible model is left in a ladder, save state, stop, and report quota exhaustion with the earliest reset time (continue later with `--resume`).
84
+
85
+ ## 5. Execution Pipeline
86
+
87
+ ### Step 0: Lockout Check, Baseline Snapshot & Resume
88
+ 1. **Before any delegation:** Apply `--reset-cooldowns` if present, then run `t3-auto-build quota status` (and `t3-auto-build quota check` if available). CLI not on PATH: read `{{cooldownsPath}}` directly and ignore expired entries. Automatically skip every locked model and every provider at 0% remaining quota.
89
+ 2. Run `git status --short` to record pre-existing modified/untracked files.
90
+ 3. **`--resume`:** Read `.claude/auto-build-state.json`, restore its `flags` (newly typed flags win), skip `completedWaves`, keep `modifiedFiles` in this run's diff scope, and continue with `remaining` and `blockers` (rebuild `REPO_BRIEF` first). If the file is missing or invalid, say so and stop.
91
+ - **State File (runs that edit code, plus `--plan-only`):** After each wave/step, overwrite `.claude/auto-build-state.json` with compact JSON `{"flags":[],"completedWaves":[],"modifiedFiles":[],"remaining":[],"blockers":[]}` (`remaining` names each pending wave/step and its files). Ensure it is gitignored: if `git check-ignore -q` on it fails, append its path to the file printed by `git rev-parse --git-path info/exclude`.
92
+ - **Pre-Flight Warning:** If `--strict` is active without `--budget` and every dual auditor ({{dualAuditNames}}) is locked, note in the run plan immediately that dual audit will fall back.
93
+ - For `--audit-only`, target the current uncommitted `git diff` and untracked files; for all other runs, later diff guards and audits MUST target ONLY files touched by this run.
94
+
95
+ ### Step 1: Cached Repo Profile + Triage & `REPO_BRIEF` (`Tier 1`, effort: `low`)
96
+ Check if `.claude/repo-profile.md` exists in the repo:
97
+ - **If `.claude/repo-profile.md` exists:** Reuse its static test/typecheck/lint commands and repo conventions; delegate only a quick `Tier 1 (low)` scan of files relevant to the current task to write a compact `REPO_BRIEF` (at most 15 lines).
98
+ - **If `.claude/repo-profile.md` does not exist:** Delegate initial repo discovery to `Tier 1 (low)` to save static test/lint/typecheck commands and conventions to `.claude/repo-profile.md`, and emit the `REPO_BRIEF` (at most 15 lines) containing:
99
+ - Exact target files, changed line ranges, and relevant public interfaces/types
100
+ - Exact test, typecheck, and lint commands for this repo
101
+ - Key local conventions
102
+ - **Task Shape & Complexity Level** (overridden to `L1` if `--fast`, or `L3` if `--strict`):
103
+ - `L0`: Trivial 1-file tweak (under 20 lines, typo, config, pure boilerplate)
104
+ - `L1`: Focused bugfix or contained feature (low risk)
105
+ - `L2`: Multi-file feature, cross-module logic, or non-trivial refactor
106
+ - `L3`: High-risk domain (auth, security, permissions, payments, DB schema/migrations, concurrency, crypto) or `--strict`
107
+ - **Work Shape Classification (`A` or `B`):**
108
+ - `Shape A` (Multi-file / wide-context / UI / cross-module wiring) -> Builder: `{{firstBuilderA}}`
109
+ - `Shape B` (Complex state / algorithms / regex / surgical debugging) -> Builder: `{{firstBuilderB}}`
110
+
111
+ - **If `--dry-run` was passed:** Stop here and output `REPO_BRIEF`, complexity tier, Work Shape (`A`/`B`), planned models/efforts, and active lockouts without making edits.
112
+ - **If `--audit-only` was passed:** Jump directly to Step 5.
113
+ - Otherwise, inject `REPO_BRIEF` into every subsequent `delegate_task` prompt.
114
+
115
+ **Handoff Packet (EVERY delegate, including Step 1), 4 parts:** (1) exact files it owns and may edit (`none` if read-only), (2) files to read, (3) interface contract (signatures, data shapes, behavior it must honor), (4) one fast exit-check command (`none` if read-only).
116
+
117
+ ### Step 2: Architecture Plan (`L2` and `L3` ONLY, at most 25 lines)
118
+ - Skip for `L0` and `L1`.
119
+ - Delegate to **Tier 3 Architecture Plan** (`medium` effort if `--budget`, otherwise `high`) with `REPO_BRIEF` to produce a concrete file-by-file plan (at most 25 lines): file-disjoint waves, interface contracts, edge cases, and test strategy.
120
+ - **L3 Plan Cross-Check (`L3` / `--strict` ONLY, skipped if `--budget`, `--*-only`, or only one provider is allowlisted):** Delegate a single fast critique (`medium` effort) of the plan to an opposite-provider model from the Tier 3 ladder to catch missing edge cases or breaking changes before coding begins.
121
+ - If `--plan-only` was passed, stop here and output the finalized plan + Model Trace.
122
+
123
+ ### Step 3: Implementation (Wave-Based Parallel for `L2` / `L3`) + Pre-Computed Commit Message
124
+ - **`L0`:** One builder, first available **Tier 1 (`low`)**.
125
+ - **`L1`:** One builder from the Work-Shape **Builder Ladder** (`low` if `--budget`, otherwise `medium` unless ladder specifies explicit fallback effort).
126
+ - **`L2` / `L3`:** Split the plan into file-disjoint waves: (1) foundations/hooks -> (2) core logic/CLI -> (3) tests/docs. Dispatch each wave's builders in parallel from the Work-Shape **Builder Ladder** (`L2`: effort as `L1`; `L3`: `medium` if `--budget`, otherwise `high`); no file has two owners in one wave. **Shift Left:** after each wave, run Step 3.5, its exit checks, and syntax/typecheck, and fix failures before starting the next wave (with `--no-tests`, skip test suites only).
127
+ - Record `IMPLEMENTER_PROVIDER` (every provider that built) and have each builder include a 1-line `COMMIT_MSG` (`feat|fix|refactor(scope): concise summary`) in its summary so `--commit` needs no extra model call.
128
+
129
+ ### Step 3.5: Scope-Creep & Diff Guard
130
+ Run `git diff --stat` and compare against Step 0's baseline and the planned scope. Revert any unintended edits to unrelated files or weakened/deleted existing tests before verification.
131
+
132
+ ### Step 4: Blind Edge-Case Tests (`L2` and `L3` ONLY — skip if `--no-tests` or `--budget`)
133
+ In the tests/docs wave, delegate writing adversarial and edge-case tests to the first eligible **Blind Edge-Case Tester** from a DIFFERENT provider than `IMPLEMENTER_PROVIDER` when available (effort: `medium` for `L2`, `high` for `L3`):
134
+ - Provide ONLY the task requirements, `REPO_BRIEF`, and public function/API signatures—tell the tester to verify contract behavior, boundary inputs, error paths, and edge cases without assuming the implementation is right.
135
+ - Do not modify production code in this step.
136
+
137
+ ### Step 5: Targeted Tests/Lint Gate + Diff-Only Cross-Provider Audit
138
+ 1. **Test, Typecheck & Lint (skip if `--no-tests`):**
139
+ - The orchestrator runs these shell commands (and syntax checks) itself with quiet flags; do not delegate them.
140
+ - For `L1` or fix rounds, run **targeted tests for touched modules first** plus typecheck/lint. Run the full test suite on `L2`/`L3` final pass or when `--commit` is set.
141
+ - Capture exact pass/fail counts and failing test names/error signatures. Do not edit code.
142
+ 2. **Code Audit (Evidence-Only Rejection Rule — skip if `--no-audit`):**
143
+ - **`L0`:** Orchestrator runs a quick `git diff -U5` sanity check (skip full audit if tests pass).
144
+ - **Lint/Typecheck Gate for `L3`:** If typecheck or lint failed in Step 5.1, fix those errors first before spending dual-audit quota.
145
+ - **`L1` (or any level with `--budget`):** First eligible opposite-provider model on the **Auditor Ladder** at `medium` effort.
146
+ - **`L2`:** First eligible opposite-provider model on the **Auditor Ladder** at `high` effort.
147
+ - **`L3` / `--strict` (Dual-Auditor Panel, unless `--budget` or `--*-only`):** {{dualAuditRun}} (failing over independently along the Auditor Ladder if locked/exhausted).
148
+ - **Diff-Scoped Payload:** Pass `git diff -U5` (plus new untracked files from this run), the changed contracts (signatures, data shapes, flags), and exact `file:start-end` line ranges of modified functions—do NOT ask auditors to read full untouched files unless a symbol definition is missing.
149
+ - **Evidence-Only Verdict (within 15 lines):** Tag every finding `BLOCKER` (exact `file:line`, concrete failure input/condition, real impact) or `NIT` (everything else). Return `VERDICT: REJECTED` only with at least one `BLOCKER`; otherwise `VERDICT: APPROVED`.
150
+
151
+ ### Step 6: Fix Loop With Friction Escalation & Oscillation Detection (Max 2 Rounds)
152
+ If tests/lint failed OR any auditor reported a `BLOCKER` (and fix rounds < 2; `NIT`s never trigger a round):
153
+ - Record exact failing test names and error signatures before each fix round.
154
+ - **Fix Round 1:** Send ONLY `REPO_BRIEF`, `git diff -U5`, exact `file:line` `BLOCKER` list, and failing test lines to the Work-Shape **Builder Ladder** (`low` if `--budget`, `medium` for `L1`/`L2`, `high` for `L3`; or **Tier 1 `low`** for trivial 1-line fixes). Re-run Step 3.5 and Step 5.
155
+ - **Fix Round 2 (Smart Escalation & Oscillation Check):** If the exact same error signature repeats, a previously passing test regresses, or Round 1 still fails, escalate directly to **Tier 3 Architecture Plan (`high`)** (or `Tier 2 medium` if `--budget`) to diagnose root cause before editing, then re-run Step 3.5 and Step 5.
156
+
157
+ ### Step 7: Optional Commit & Final Report
158
+ - **If `--commit` was passed:** Stage ONLY the files touched by this run and commit using the pre-computed `COMMIT_MSG` (or a concise conventional message derived from the diff) ONLY if all active checks passed (`APPROVED` / tests green). Never use `--no-verify` or amend existing commits.
159
+ - **Output Final Report:**
160
+ - **Level, Shape & Flags:** (`L0`-`L3`, `Shape A`/`B`, plus all active flags)
161
+ - **Files Changed:** Production files + blind edge-case tests added (and commit hash if `--commit` ran)
162
+ - **Test / Lint Results:** Exact pass/fail summary (or `Skipped via --no-tests`)
163
+ - **Audit Verdict:** `APPROVED`, `Skipped via --no-audit`, or remaining blockers after 2 fix rounds (list `NIT`s briefly)
164
+ - **Model, Effort & Failover Trace:** Compact table listing every step, provider, model, dispatched effort, lockouts applied/respected, and any automatic quota failovers (confirming zero banned models were used)
165
+
166
+ - **EXECUTED MODEL ECHO:** Require every delegate_task sub-agent to start its response with `Model used: <model>` on line 1 so the orchestrator can confirm the exact model that ran. Log the effort you dispatched; never ask a sub-agent to self-report effort.