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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 t3-auto-build contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,311 @@
1
+ # t3-auto-build
2
+
3
+ Cross-platform installer and `$auto-build` orchestration suite for T3 Code: a coding-discipline
4
+ `CLAUDE.md`, slash commands, an `auto-build` skill rendered from your own model config, and Node
5
+ hooks for guardrails. No dependencies. Node 18 or newer.
6
+
7
+ ## T3 Code quickstart
8
+
9
+ 1. Install into your Claude config directory. From a clone:
10
+
11
+ ```sh
12
+ node bin/cli.mjs init
13
+ ```
14
+
15
+ Once the package is published, `npx t3-auto-build init` does the same.
16
+
17
+ 2. Check the result:
18
+
19
+ ```sh
20
+ node bin/cli.mjs doctor
21
+ ```
22
+
23
+ 3. **Restart T3 Code** (and any running Claude Code session). Hooks and `settings.json` changes
24
+ load only at startup.
25
+
26
+ 4. In a T3 Code thread, run `$auto-build <task>`. See [workflow](#auto-build-workflow) for flags.
27
+
28
+ The skill calls `t3-auto-build quota ...`. From a clone, `npm link` puts that command on `PATH`.
29
+ Without it the skill reads or edits the cooldown file directly.
30
+
31
+ ## Preset matrix
32
+
33
+ | Preset | Models | Codex | Antigravity | Claude | Dual audit |
34
+ |---|---|---|---|---|---|
35
+ | `tri-provider` (default) | 9 | 3 | 3 | 3 | Claude Opus 5.5 + Gemini 4 Carbon |
36
+ | `claude-codex` | 6 | 3 | 0 | 3 | Claude Opus 5.5 + gpt-6-luna |
37
+ | `claude-only` | 3 | 0 | 0 | 3 | Claude Opus 5.5 + Claude Sonnet 5.5 |
38
+
39
+ Every preset bans `Argon` and `Fable/Mythos`, defaults to Claude Sonnet 5.5 at `medium` effort and
40
+ sets the auto-compaction threshold to 35%.
41
+
42
+ ## Provider detection and tiers
43
+
44
+ Interactive `init` on a fresh target picks the default preset from the binaries on `PATH`: `claude`,
45
+ `codex` and `antigravity` give `tri-provider`, `claude` and `codex` give `claude-codex`, anything
46
+ else gives `claude-only`. Provider config folders are only checked for existence and do not change
47
+ the preset. With an existing config its preset is the default. `init --yes` does not detect: a fresh
48
+ install without `--preset` uses `tri-provider`.
49
+
50
+ `--tiers provider:plan[:weekday]`, comma separated (for example `claude:max:monday,codex:plus`),
51
+ records subscription plans. Interactive `init` asks for each detected provider when the flag is
52
+ absent.
53
+
54
+ | Provider | Plan: short-window limit locks the provider | Plan: locks only the heavy model | Heavy model |
55
+ |---|---|---|---|
56
+ | `claude` | `pro` | `max` | Claude Opus 5.5 |
57
+ | `codex` | `plus` | `pro` | gpt-6-luna |
58
+ | `antigravity` | `standard` | `ultra` | Gemini 4 Carbon |
59
+
60
+ The weekday (`monday` or `mon`) is the weekly reset day, taken as 00:00 UTC. A custom `heavyModels`
61
+ list in the config is kept.
62
+
63
+ ## CLI
64
+
65
+ | Command | What it does |
66
+ |---|---|
67
+ | `t3-auto-build init` | Installs or updates. Interactive unless `--yes`. |
68
+ | `t3-auto-build doctor` | Checks files, JSON and hook wiring, runs each hook with mock input, looks for `rg` and `sg`. |
69
+ | `t3-auto-build uninstall` | Removes what `init` installed and keeps files you changed. |
70
+ | `t3-auto-build sync-models` | Probes models with the provider CLIs and updates the allowlist. |
71
+ | `t3-auto-build quota set\|status\|clear\|check` | Manages cooldown locks. |
72
+
73
+ | Option | Applies to | Meaning |
74
+ |---|---|---|
75
+ | `--target <dir>` | all | Config directory. Default: `$CLAUDE_CONFIG_DIR`, else `~/.claude`. |
76
+ | `--preset <name>` | init | `tri-provider`, `claude-codex` or `claude-only`. |
77
+ | `--modules <name>` | init | `full`, `auto-build` or `core`. |
78
+ | `--compaction <n>` | init | Integer from 1 to 100. |
79
+ | `--tiers <list>` | init | `provider:plan[:weekday]`, comma separated. |
80
+ | `--probe` | init | Run `sync-models` after installing. Spends real quota. Ignored for `core`. |
81
+ | `--yes` | init, sync-models | No prompts. Without an interactive terminal, `init` requires it and `sync-models` requires it or `--dry-run`. |
82
+ | `--force` | init, sync-models | Back up your changed files to `<file>.bak`, then overwrite. For `sync-models`, this covers a hand-edited `SKILL.md`. |
83
+ | `--dry-run` | sync-models | Probe and print the result; write nothing. **Still spends real quota.** |
84
+ | `--providers <list>` | sync-models | Only these of `claude`, `codex`, `antigravity`; comma separated. |
85
+ | `--burst`, `--5h`, `--weekly`, `--until <when>`, `--reason <text>` | quota set | See [Quota](#quota). |
86
+ | `--all` | quota clear | Remove every lock. |
87
+
88
+ Exit codes: `0` success, `1` failure (invalid JSON, broken install), `2` usage error.
89
+
90
+ ### Modules
91
+
92
+ | `--modules` | Name | CLAUDE.md, rules, commands | Skill, config, hooks, `settings.json` |
93
+ |---|---|---|---|
94
+ | `full` (default) | Full Suite | yes | yes |
95
+ | `auto-build` | /auto-build Only | no | yes |
96
+ | `core` | Core Discipline + Commands | yes | no (`settings.json` is not written) |
97
+
98
+ A re-run without `--modules` keeps the previous choice. When you change it, `init` removes the files
99
+ that no longer belong and keeps and reports the ones you changed. Switching to `core` also removes
100
+ the hook entries and environment value from `settings.json`. That cleanup is the one case where a
101
+ `core` run writes `settings.json`.
102
+
103
+ ## sync-models
104
+
105
+ > **`sync-models --dry-run` still executes live probes.** It spends real quota and writes nothing.
106
+
107
+ > Probe processes inherit your environment. If an API key variable (such as `ANTHROPIC_API_KEY` or
108
+ > `OPENAI_API_KEY`) is set, the CLI may use it and the probes may be billed to the API.
109
+
110
+ Candidates are the config allowlist, its `planRestricted` models and the preset's models; banned
111
+ models are skipped. Each gets a one-word prompt through `claude -p` or `codex exec`, in an empty temp
112
+ directory with a 20 s timeout. `claude` runs with tools disabled, safe mode and no session
113
+ persistence. `codex` runs read-only and ephemeral with `--ignore-user-config` and `--ignore-rules`,
114
+ so your Codex user config does not apply. Antigravity has no probe support: its models report
115
+ `unavailable` and keep their current membership.
116
+
117
+ | State | Effect on the config |
118
+ |---|---|
119
+ | `available` | Added to or kept in `allowlist`; removed from `planRestricted`. |
120
+ | `rate-limited` | Same as `available`, plus a cooldown. After a provider-wide limit the remaining models of that provider are skipped; a skipped model already in `planRestricted` stays there. |
121
+ | `plan-restricted` | Moved from `allowlist` to `planRestricted`. |
122
+ | `unavailable` | No change (CLI missing, not logged in, timeout, unsupported or other failure). |
123
+
124
+ Without `--yes` it shows the changes and asks before writing. A write backs up a changed config,
125
+ re-renders `SKILL.md` and records cooldowns without shortening longer ones. A hand-edited `SKILL.md`
126
+ is skipped with a warning; `--force` backs it up and overwrites it. An emptied ladder gets a
127
+ fallback model. If no allowed model would remain, nothing is written.
128
+ Writing needs an `auto-build` or `full` install; `--dry-run` needs only the config file.
129
+ `init --probe` runs the same sync after installing, asking first unless `--yes`.
130
+
131
+ ## Quota
132
+
133
+ ```sh
134
+ t3-auto-build quota set <claude|codex|antigravity|model> [--burst|--5h|--weekly|--until <when>] [--reason <text>]
135
+ t3-auto-build quota status
136
+ t3-auto-build quota clear <provider|model> # or --all
137
+ t3-auto-build quota check [provider]
138
+ ```
139
+
140
+ - `set` locks one provider or model. The default `--burst` is 10 minutes; `--5h` is 5 hours;
141
+ `--weekly` runs to the tier's reset day, else 7 days. `--until` takes a future ISO time or a
142
+ duration such as `90m` or `1w2d`. `--5h` on a provider whose tier locks only the heavy model writes
143
+ `tier:<p>:heavy`.
144
+ - Reset times parsed from rate-limit messages are capped at 14 days. A manual `--until` is not capped.
145
+ - `status` drops expired locks and prints the rest.
146
+ - `clear <provider>` removes its provider and heavy-tier locks, not its model locks.
147
+ `clear <model>` removes that model's lock. `--all` deletes the file, even a corrupt one.
148
+ - `check` runs `claude auth status` and `codex login status` (Antigravity has no status command). It
149
+ reports login state only, unless the output explicitly says usage is exhausted; only then does it
150
+ record a lock.
151
+
152
+ ### Cooldown file
153
+
154
+ `<config dir>/auto-build-cooldowns.json` is a JSON object keyed `model:<id>`, `provider:<p>` or
155
+ `tier:<p>:heavy`:
156
+
157
+ ```json
158
+ {
159
+ "provider:codex": {
160
+ "scope": "provider",
161
+ "window": "5h",
162
+ "until": "2030-01-01T05:00:00.000Z",
163
+ "reason": "manual lock (5h)",
164
+ "source": "manual"
165
+ }
166
+ }
167
+ ```
168
+
169
+ `scope` is `model`, `provider` or `tier` (written tier entries also carry `"tier": "heavy"`).
170
+ `window` is `burst`, `5h`, `weekly` or `custom`. Legacy `until_utc` is read. A key without a prefix
171
+ needs a `scope` field, or it locks nothing. A malformed entry (such as one without a valid time) is
172
+ skipped with a warning and kept in the file until it is overwritten or cleared (`quota clear <name>`
173
+ or `--all`). A file that is not a JSON object is unreadable: hooks warn and ignore it. A write that
174
+ leaves no entries removes the file.
175
+
176
+ ## auto-build workflow
177
+
178
+ 1. **Step 0:** check lockouts, record the `git status` baseline, resume if asked.
179
+ 2. **Triage:** write a short `REPO_BRIEF` (using the cached `.claude/repo-profile.md`) and pick the
180
+ level `L0` to `L3` and work shape `A` (multi-file, UI) or `B` (algorithms, debugging).
181
+ 3. **Plan** (`L2`/`L3`), cross-checked by another provider on `L3` when available.
182
+ 4. **Build:** `L2`/`L3` run in file-disjoint waves: foundations, core, tests/docs. Builders in a wave
183
+ run in parallel; the diff guard and exit checks pass before the next wave.
184
+ 5. **Verify:** blind edge-case tests (`L2`/`L3`), tests and lint, a diff-only audit preferring
185
+ another provider (two auditors on `L3`), at most 2 fix rounds, then an optional commit and a
186
+ report.
187
+
188
+ Runs that edit code, and `--plan-only` runs, save `.claude/auto-build-state.json` (`flags`,
189
+ `completedWaves`, `modifiedFiles`, `remaining`, `blockers`) after each wave or step and keep it
190
+ gitignored. `$auto-build --resume` restores it, lets newly typed flags win and skips completed waves.
191
+ It stops if the file is missing or invalid. When quota runs out, the run saves state so you can
192
+ resume later.
193
+
194
+ | Flag | Effect |
195
+ |---|---|
196
+ | `--fast` / `--strict` | Cap at `L1` / force `L3`. |
197
+ | `--plan-only` | Stop after the plan. |
198
+ | `--dry-run` | Stop after triage and show the routing. |
199
+ | `--audit-only` | Test and audit the uncommitted diff, then fix if needed. |
200
+ | `--resume` | Continue an interrupted run. |
201
+ | `--commit` | Commit only if the active checks pass. |
202
+ | `--no-audit`, `--no-tests` | Skip the audit / tests. |
203
+ | `--budget` | Cheaper routing; no plan cross-check, blind tests or dual audit. |
204
+ | `--reset-cooldowns` | Clear all locks first. |
205
+ | `--<provider>-only` | Use only that provider's models. |
206
+
207
+ ## Configuration
208
+
209
+ `<config dir>/auto-build.config.json` holds `allowlist` (provider to model names), `bannedModels`,
210
+ `defaultModel`, `defaultEffort`, `ladders` and `compactionThreshold`, plus optional `tiers`,
211
+ `modelIds` (display name to CLI model id) and `planRestricted`. Edit it, then run `init` again to
212
+ re-render the skill. The hooks read it when they need it.
213
+
214
+ - The existing file is always the base. `--compaction` overrides its value. A `--preset` that differs
215
+ from the file's `preset` replaces the allowlist, ladders and default model and effort, and keeps
216
+ your banned models and threshold. Banned models typed at the prompt are added.
217
+ - To reset to a preset, delete the file and run `init`.
218
+ - Banned entries match as case-insensitive substrings, and `A/B` bans both. A short entry such as
219
+ `Claude` bans every model whose name contains it.
220
+ - Model names ignore case and punctuation runs, so `claude-sonnet-5-5` matches `Claude Sonnet 5.5`.
221
+ Model cooldown keys may use either form. Provider cooldowns match the config provider name or the
222
+ T3 provider id (`claudeAgent`, `codex`, `antigravity`). `provider:codex` also covers a custom
223
+ instance such as `codex-2`; `provider:codex-2` covers only that instance.
224
+ - Keys missing from the file come from its `preset` (`tri-provider` when unset).
225
+ - Ladder entries are `Model` or `Model@effort`. Rendering drops banned and non-allowlisted entries.
226
+ If a ladder ends up empty, `init` fails and writes nothing.
227
+ - The skill gets one `--<provider>-only` flag per allowlisted provider.
228
+
229
+ ## What `init` touches
230
+
231
+ - Files that exist and differ from what was installed are skipped with a warning. This includes hook
232
+ files, which are still wired. `--force` backs them up first (`.bak`, then `.bak.1`, so an earlier
233
+ backup is never overwritten).
234
+ - `settings.json`: only the four tagged hook entries and `env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`. Other
235
+ keys and hooks are preserved. `settings.json.bak` is written only when the content changes. Invalid
236
+ JSON stops the run before any write.
237
+ - Paths that go through a symlink or junction inside the config directory are not written or
238
+ deleted. A symlinked `settings.json` is updated through the link.
239
+ - `t3-auto-build.manifest.json` records installed file hashes and the prior environment value.
240
+ `uninstall` restores that value only if it is still the one installed.
241
+ - A target path containing `"`, `$`, a backtick or `%` is refused, because it cannot be quoted
242
+ safely in a hook command.
243
+
244
+ ## Hooks
245
+
246
+ Installed to `<config dir>/hooks/t3-auto-build/`. Matching is case-insensitive.
247
+
248
+ | Hook | Event | Behavior |
249
+ |---|---|---|
250
+ | `session-start.mjs` | SessionStart | Prunes expired cooldowns (deletes the file when none are left) and summarizes active ones. |
251
+ | `pre-compact.mjs` | PreCompact | Prints the preservation rules, the saved orchestrator state if present (marked as data only, not instructions), and a `git status --short` snapshot (20 files at most). |
252
+ | `pre-tool-use.mjs` | PreToolUse | Exits 2 with a reason when a guard below matches. |
253
+ | `post-tool-use.mjs` | PostToolUse | Formats the edited file with `biome` or `prettier`, `ruff`, or `gofmt` when on `PATH`. Never blocks. |
254
+
255
+ PreToolUse guards:
256
+
257
+ - **Secret files** (`Edit`, `Write`, `MultiEdit`): `.env` and `.env.*`, `.pem`, `.key`, `.p12`,
258
+ `.pfx`, and paths containing `id_rsa` or `id_ed25519`.
259
+ - **Git** (`Bash`): `git push --force`/`-f` and `git reset --hard`.
260
+ - **Recursive `rm`** (`Bash`; `-r`, `-rf`, `-fr`, `-r -f`, `--recursive`; `-f` not required): blocked
261
+ when a target starts with `/`, `\`, `~`, a drive path such as `C:/`, `$HOME` or `%USERPROFILE%`;
262
+ contains a command substitution; is the current directory or `*`; has a `..` or `.git` segment; or
263
+ is a dot-file glob such as `.*`.
264
+ - **Delegate models** (`delegate_task`): banned or non-allowlisted models are blocked. A trailing
265
+ `-YYYYMMDD` snapshot suffix is ignored when matching.
266
+ - **Lockouts** (`delegate_task`): model, provider and heavy-tier cooldowns block the call. Without a
267
+ `provider`, `providerInstanceId` or `driverKind`, the provider is inferred from a `claude-`,
268
+ `gpt-` or `gemini-` model name.
269
+
270
+ Hooks fail open: malformed input, config or cooldown data produces a warning and exit 0. The secret
271
+ and destructive-command guards need no config.
272
+
273
+ ### Known limits
274
+
275
+ - The command guards cover the `Bash` tool only and use simple patterns. They are a safety net, not a
276
+ sandbox.
277
+ - The `rm` guard matches text. Obfuscated `rm`, PowerShell removal commands such as `Remove-Item`, and
278
+ `find -delete` are **not** caught. Other variables are not expanded. Harmless text can match:
279
+ `echo rm -rf .` is blocked. A very long command with many `rm` calls is blocked unchecked; split it up.
280
+ - Any `-f` text after `git push` matches, including a branch name such as `bug-fix`.
281
+ `--force-with-lease` is blocked too.
282
+ - The delegate guard reads `model` and the provider fields at the top level of `tool_input` and under
283
+ `target` (T3 Code's shape). A call without a model skips the allowlist check; provider cooldowns
284
+ still apply if it names a provider.
285
+
286
+ Not ported from the PowerShell hooks: `stop-verify.js`, `bash-guard.js`, `tsc-check.js`, the caveman status line and
287
+ skillspector. No Stop hook is installed.
288
+
289
+ If you already run the PowerShell versions, remove them from `settings.json`. `doctor` warns while
290
+ they are still wired.
291
+
292
+ ## Optional tools
293
+
294
+ `doctor` warns when these are missing:
295
+
296
+ | Tool | Windows | macOS | Linux |
297
+ |---|---|---|---|
298
+ | ripgrep (`rg`) | `winget install BurntSushi.ripgrep.MSVC` | `brew install ripgrep` | `apt install ripgrep` |
299
+ | ast-grep (`sg`) | `winget install ast-grep.ast-grep` | `brew install ast-grep` | `npm i -g @ast-grep/cli` |
300
+
301
+ ## Development
302
+
303
+ ```sh
304
+ node --test
305
+ ```
306
+
307
+ Tests run in temporary directories with `HOME`, `USERPROFILE` and `CLAUDE_CONFIG_DIR` overridden.
308
+
309
+ ## License
310
+
311
+ MIT
package/bin/cli.mjs ADDED
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ import { HEAVY_MODELS } from '../lib/detect.mjs';
3
+ import { doctor } from '../lib/doctor.mjs';
4
+ import { PRESETS, install, uninstall, wantsAuto } from '../lib/install.mjs';
5
+ import { MODULES, readManifest } from '../lib/manifest.mjs';
6
+ import { CliError, resolveTarget } from '../lib/paths.mjs';
7
+ import { syncModels } from '../lib/probe.mjs';
8
+ import { confirmYes, initPrompts, parseChoice, parsePercent, parseTierSpec } from '../lib/prompt.mjs';
9
+ import { QUOTA_WINDOWS, quotaCheck, quotaClear, quotaSet, quotaStatus } from '../lib/quota.mjs';
10
+
11
+ const USAGE = `Usage: t3-auto-build <command> [options]
12
+
13
+ Commands:
14
+ init install or update (interactive unless --yes)
15
+ doctor check an installation
16
+ uninstall remove what init installed, keeping your edits
17
+ sync-models probe the models and update the allowlist
18
+ quota set <subject> lock a provider (claude, codex, antigravity) or a model
19
+ quota status show active locks and drop expired ones
20
+ quota clear [subject] remove the locks of a provider or model (or --all)
21
+ quota check [provider] run the official login status commands
22
+
23
+ Options:
24
+ --target <dir> config dir (default: $CLAUDE_CONFIG_DIR, else ~/.claude)
25
+ -h, --help show this help
26
+ init only:
27
+ --preset <name> ${PRESETS.join(' | ')}
28
+ --modules <name> ${MODULES.join(' | ')}
29
+ --compaction <n> auto-compaction threshold, 1-100
30
+ --tiers <list> provider:plan[:weekday], comma separated, e.g. claude:max,codex:pro
31
+ --probe run sync-models after installing (spends real quota)
32
+ --yes do not prompt
33
+ sync-models only:
34
+ --dry-run show the result without writing. Note: sync-models --dry-run
35
+ still executes live probes (spends real quota) but writes nothing.
36
+ --providers <list> only these providers, comma separated
37
+ --yes write without asking
38
+ init and sync-models:
39
+ --force back up your edited files to .bak, then overwrite. sync-models applies it
40
+ to a hand-edited SKILL.md (default: skip it with a warning)
41
+ quota set only (one window, default --burst):
42
+ --burst 10 minutes
43
+ --5h 5 hours
44
+ --weekly until the tier's weekly reset day, else 7 days
45
+ --until <when> ISO time, or a duration such as 90m or 1w2d
46
+ --reason <text> note shown by quota status
47
+ quota clear only:
48
+ --all remove every lock`;
49
+
50
+ const VALUE_FLAGS = ['target', 'preset', 'modules', 'compaction', 'tiers', 'providers', 'until', 'reason'];
51
+ const SWITCHES = ['yes', 'force', 'help', 'probe', 'dry-run', 'all', ...QUOTA_WINDOWS];
52
+ const COMMAND_FLAGS = {
53
+ init: ['preset', 'modules', 'compaction', 'tiers', 'probe', 'yes', 'force'],
54
+ doctor: [],
55
+ uninstall: [],
56
+ 'sync-models': ['dry-run', 'providers', 'yes', 'force'],
57
+ 'quota set': [...QUOTA_WINDOWS, 'until', 'reason'],
58
+ 'quota status': [],
59
+ 'quota clear': ['all'],
60
+ 'quota check': [],
61
+ };
62
+ // [min, max] positional arguments after the command.
63
+ const ARGUMENTS = { 'quota set': [1, 1], 'quota clear': [0, 1], 'quota check': [0, 1] };
64
+
65
+ function parseArgs(argv) {
66
+ const flags = {};
67
+ const positional = [];
68
+ for (let i = 0; i < argv.length; i += 1) {
69
+ const argument = argv[i] === '-h' ? '--help' : argv[i];
70
+ if (!argument.startsWith('-')) {
71
+ positional.push(argument);
72
+ continue;
73
+ }
74
+ const [, name, inline] = argument.match(/^--([^=]+)(?:=(.*))?$/s) ?? [];
75
+ if (SWITCHES.includes(name) && inline === undefined) {
76
+ flags[name] = true;
77
+ } else if (VALUE_FLAGS.includes(name)) {
78
+ const value = inline ?? argv[(i += 1)];
79
+ if (!value || (inline === undefined && value.startsWith('--'))) throw new CliError(`--${name} needs a value`, 2);
80
+ flags[name] = value;
81
+ } else {
82
+ throw new CliError(`unknown option ${argument}`, 2);
83
+ }
84
+ }
85
+ return { flags, positional };
86
+ }
87
+
88
+ function parseProviders(value) {
89
+ const names = value.split(',').map((name) => name.trim()).filter(Boolean);
90
+ if (!names.length) throw new CliError('--providers needs a value', 2);
91
+ return names.map((name) => parseChoice(name, Object.keys(HEAVY_MODELS), 'provider'));
92
+ }
93
+
94
+ async function sync(target, { yes = false, dryRun = false, force = false, providers }) {
95
+ if (!yes && !dryRun && !process.stdin.isTTY) {
96
+ throw new CliError('no interactive terminal; re-run with --yes (or --dry-run); nothing was written', 2);
97
+ }
98
+ // Checked before probing, so quota is not spent on results that cannot be saved.
99
+ const manifest = readManifest(target);
100
+ if (!dryRun && !(manifest && wantsAuto(manifest.modules))) {
101
+ throw new CliError(`no auto-build installation in ${target}; run init first`);
102
+ }
103
+ let declined = false;
104
+ const confirm = async ({ allowlist, planRestricted, cooldowns, changed }) => {
105
+ if (force || changed || Object.keys(cooldowns).length) {
106
+ console.log(JSON.stringify({ allowlist, planRestricted, cooldowns }, null, 2));
107
+ if (await confirmYes(`Write these changes to ${target}? [y/N] `)) return true;
108
+ }
109
+ declined = true;
110
+ return false;
111
+ };
112
+ const summary = await syncModels(target, { providers, dryRun, yes, force, confirm });
113
+ if (dryRun) {
114
+ const { allowlist, planRestricted, cooldowns, changed } = summary;
115
+ console.log(JSON.stringify({ allowlist, planRestricted, cooldowns, changed }, null, 2));
116
+ }
117
+ console.log(dryRun || declined ? 'nothing was written' : 'done: models synced');
118
+ }
119
+
120
+ async function init(target, flags) {
121
+ let options = {
122
+ force: flags.force,
123
+ preset: flags.preset === undefined ? undefined : parseChoice(flags.preset, PRESETS, 'preset'),
124
+ modules: flags.modules === undefined ? undefined : parseChoice(flags.modules, MODULES, 'modules'),
125
+ compaction: flags.compaction === undefined ? undefined : parsePercent(flags.compaction),
126
+ tiers: flags.tiers === undefined ? undefined : parseTierSpec(flags.tiers),
127
+ };
128
+ if (!flags.yes) {
129
+ if (!process.stdin.isTTY) throw new CliError('no interactive terminal; re-run with --yes (and --preset/--modules/--compaction)', 2);
130
+ options = await initPrompts(target, options);
131
+ }
132
+ install(target, options);
133
+ if (!flags.probe) return;
134
+ if (wantsAuto(readManifest(target).modules)) await sync(target, { yes: flags.yes });
135
+ else console.log('warning: --probe does not apply to the core module; ignored');
136
+ }
137
+
138
+ function quota(action, target, subject, flags) {
139
+ if (action === 'status') return quotaStatus(target);
140
+ if (action === 'check') return quotaCheck(target, { providers: subject === undefined ? undefined : [subject] });
141
+ if (action === 'clear') {
142
+ if ((subject === undefined) !== Boolean(flags.all)) throw new CliError('quota clear needs a provider, a model or --all (not both)', 2);
143
+ return quotaClear(target, flags.all ? { all: true } : subject);
144
+ }
145
+ const chosen = [...QUOTA_WINDOWS, 'until'].filter((name) => flags[name] !== undefined);
146
+ if (chosen.length > 1) throw new CliError(`use only one of ${chosen.map((name) => `--${name}`).join(', ')}`, 2);
147
+ return quotaSet(target, subject, {
148
+ window: chosen[0] === 'until' ? undefined : chosen[0], until: flags.until, reason: flags.reason,
149
+ });
150
+ }
151
+
152
+ async function main(argv) {
153
+ const { flags, positional } = parseArgs(argv);
154
+ if (flags.help) return console.log(USAGE);
155
+ const [first, ...rest] = positional;
156
+ const command = first === 'quota' ? `quota ${rest.shift()}` : first;
157
+ const [min, max] = ARGUMENTS[command] ?? [0, 0];
158
+ if (!Object.hasOwn(COMMAND_FLAGS, command) || rest.length < min || rest.length > max) throw new CliError(USAGE, 2);
159
+ const stray = Object.keys(flags).find((name) => name !== 'target' && !COMMAND_FLAGS[command].includes(name));
160
+ if (stray) throw new CliError(`--${stray} is not valid with ${command}`, 2);
161
+ const target = resolveTarget(flags.target);
162
+
163
+ if (command === 'init') await init(target, flags);
164
+ else if (command === 'doctor') process.exitCode = doctor(target);
165
+ else if (command === 'uninstall') uninstall(target);
166
+ else if (command === 'sync-models') {
167
+ const providers = flags.providers === undefined ? undefined : parseProviders(flags.providers);
168
+ await sync(target, { yes: flags.yes, dryRun: flags['dry-run'], force: flags.force, providers });
169
+ } else await quota(command.slice('quota '.length), target, rest[0], flags);
170
+ }
171
+
172
+ main(process.argv.slice(2)).catch((error) => {
173
+ process.stderr.write(`${error instanceof CliError ? error.message : `unexpected error: ${error.stack}`}\n`);
174
+ process.exitCode = error.exitCode ?? 1;
175
+ });
package/core/CLAUDE.md ADDED
@@ -0,0 +1,23 @@
1
+ # Global Coding & Token Discipline
2
+
3
+ ## Search & Read Rules
4
+ - Do not re-read files or re-run searches already present in the current context unless a file was modified since the last read.
5
+ - Never read entire files over 200 lines upfront. Locate symbols first with `rg -n` or `rg --files`, then read targeted 80-120 line windows using `offset` and `limit`.
6
+ - Batch independent read-only searches/reads in parallel instead of sequential single-file turns.
7
+ - Check `.claude/repo-profile.md` first if it exists in the repo before scanning directory trees.
8
+
9
+ ## Shell & Test Output Rules
10
+ - Always pass quiet/concise flags to test, lint, and build commands so passing logs do not flood context:
11
+ - Python: `pytest -q --tb=short`, `ruff check --output-format=concise`, `mypy --no-error-summary`
12
+ - Node/TS: `npm test -- --silent` or `vitest run --reporter=dot`, `tsc --noEmit --pretty false`
13
+ - Go/Rust: `go test ./...` (avoid `-v` unless debugging a failure), `cargo test -q`
14
+ - Never pipe large logs to stdout without `| Select-Object -Last 40` (PowerShell) or `| tail -n 40` (bash) when debugging noisy builds.
15
+
16
+ ## Editing & Diff Discipline
17
+ - Keep diffs minimal and scoped strictly to the requested change. Do not reformat unrelated lines.
18
+ - Use `git diff -U5` when reviewing changes.
19
+ - Respect `.gitignore` and never read or edit `.env`, credentials, keys, or secrets.
20
+
21
+ ## Communication Style
22
+ - Lead directly with the answer, action, or diff summary. Skip filler intros and restating the prompt.
23
+ - Report findings as `file:line` bullets. Keep explanations under 5 lines unless asked for depth.
@@ -0,0 +1,5 @@
1
+ Fix the issue described in `$ARGUMENTS`:
2
+ 1. Locate the root cause using `rg -n` and targeted line-range reads.
3
+ 2. Add or run a targeted failing test first if none exists.
4
+ 3. Apply the smallest scoped fix without touching unrelated code.
5
+ 4. Run targeted tests + linter/typechecker with concise flags (`-q --tb=short`) and report `file:line` changes.
@@ -0,0 +1,6 @@
1
+ Summarize the current thread state in 12 lines or fewer so I can run `/clear` safely:
2
+ - **Goal:** 1-line objective
3
+ - **Decisions:** key architectural or constraint choices made
4
+ - **Files touched:** bullet list with 1-phrase summary each
5
+ - **Verification:** latest test/lint/typecheck status
6
+ - **Next step:** exact next action to resume cleanly
@@ -0,0 +1,4 @@
1
+ Review current uncommitted changes (`git diff -U5` and untracked code files).
2
+ - Do not modify files.
3
+ - Check for logic bugs, edge cases, missing validation, type errors, and unintended scope creep.
4
+ - Output ONLY `file:line` findings grouped by severity (Blocker / Warning / Nit), or `No issues found.` if clean.
@@ -0,0 +1,14 @@
1
+ ---
2
+ paths:
3
+ - "**/*.py"
4
+ - "**/*.ts"
5
+ - "**/*.tsx"
6
+ - "**/*.js"
7
+ - "**/*.jsx"
8
+ - "**/*.go"
9
+ - "**/*.rs"
10
+ ---
11
+ # Source Code Standards
12
+ - Match existing project style, imports, and error-handling conventions.
13
+ - Add or update focused unit/edge-case tests alongside behavioral changes, and run targeted tests for modified files before broad suites.
14
+ - Remove any temporary debug prints or unused imports before finishing.