t3-auto-build 1.0.0 → 2.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/lib/install.mjs CHANGED
@@ -1,10 +1,15 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
- import { CONFIG_FILE, isAllowlist, isObject, isStringList, readJson } from '../hooks/_shared.mjs';
4
+ import {
5
+ AVAILABILITY_FILE, CONFIG_FILE, canonicalProvider, inferProvider, isAllowlist, isObject, isStringList, isV2,
6
+ normalizeModel, normalizeName, readJson,
7
+ } from '../hooks/_shared.mjs';
5
8
  import { MANIFEST_FILE, fileHash, hashOf, readManifest, writeManifest } from './manifest.mjs';
6
9
  import { CliError, PACKAGE_ROOT, safePath } from './paths.mjs';
7
- import { renderSkill } from './render.mjs';
10
+ import { CATALOG, PROVIDERS, resolveTiers, toConfig } from './plans.mjs';
11
+ import { summaryTable } from './prompt.mjs';
12
+ import { LADDERS, renderSkill } from './render.mjs';
8
13
  import { HOOKS, HOOKS_DIR, hookCommand, mergeSettings, readSettings, taggedHooks, unmergeSettings, writeSettings } from './settings.mjs';
9
14
 
10
15
  export const PRESETS = ['tri-provider', 'claude-codex', 'claude-only'];
@@ -56,6 +61,74 @@ export function completeConfig(config) {
56
61
  return { ...preset, ...config, ladders: isObject(config.ladders ?? {}) ? { ...preset.ladders, ...config.ladders } : config.ladders };
57
62
  }
58
63
 
64
+ /** What a v1 install is assumed to pay for: a low paid tier with a CLI. */
65
+ export const ASSUMED_TIERS = { claude: 'pro', codex: 'plus', antigravity: 'plus' };
66
+ const OLD_DEFAULT_BANS = ['argon', 'fable/mythos'];
67
+
68
+ function inferSubscriptions(config) {
69
+ const present = new Set(Object.entries(config.allowlist)
70
+ .filter(([, models]) => models.length > 0)
71
+ .map(([name]) => canonicalProvider(name)));
72
+ return Object.fromEntries(PROVIDERS.map((p) => [p, present.has(p) ? ASSUMED_TIERS[p] : 'none']));
73
+ }
74
+
75
+ /** The subscription selection to resolve, or null to keep the config as it is. Flags > prompts > existing config. */
76
+ function tierRequest(existing, options) {
77
+ const v2 = isV2(existing);
78
+ const flags = Object.fromEntries(PROVIDERS.map((p) => [p, options[`${p}Tier`]]));
79
+ const prompted = Object.values(options.subscriptions ?? {});
80
+ const wanted = Object.values(flags).some((tier) => tier !== undefined)
81
+ || (v2 ? prompted.length > 0 || Boolean(options.parent) || options.allowUsageCredits !== undefined
82
+ : prompted.some((tier) => tier !== 'none'));
83
+ if (!wanted) {
84
+ if (options.parent) throw new CliError('--parent needs a subscription tier (--claude-tier)', 2);
85
+ return null;
86
+ }
87
+ const base = v2 ? existing.subscriptions : existing && inferSubscriptions(completeConfig(existing));
88
+ return {
89
+ subscriptions: Object.fromEntries(PROVIDERS.map(
90
+ (p) => [p, flags[p] ?? options.subscriptions?.[p] ?? base?.[p] ?? 'none'],
91
+ )),
92
+ allowUsageCredits: options.allowUsageCredits ?? existing?.allowUsageCredits ?? false,
93
+ parent: options.parent ?? undefined,
94
+ };
95
+ }
96
+
97
+ function resolve(subscriptions, settings) {
98
+ try {
99
+ return resolveTiers(subscriptions, settings);
100
+ } catch (error) {
101
+ throw new CliError(error.message, 2);
102
+ }
103
+ }
104
+
105
+ const userBans = (config) => (isV2(config)
106
+ ? union(config.userBannedModels ?? [], config.bannedModels ?? [])
107
+ : (config?.bannedModels ?? []).filter((entry) => !OLD_DEFAULT_BANS.includes(entry.trim().toLowerCase())));
108
+
109
+ /** A v2 config for the request. An unchanged selection keeps the existing ladders and models. */
110
+ function subscriptionConfig(existing, { subscriptions, allowUsageCredits, parent }) {
111
+ const claude = CATALOG.claude[subscriptions.claude];
112
+ const previous = existing?.parent?.model;
113
+ const keepParent = claude?.parentOptions?.includes(previous) && (!claude.usageBilled || allowUsageCredits);
114
+ const resolved = resolve(subscriptions, { parent: parent ?? (keepParent ? previous : undefined), allowUsageCredits });
115
+ if (isV2(existing) && isDeepStrictEqual(subscriptions, existing.subscriptions)
116
+ && allowUsageCredits === (existing.allowUsageCredits ?? false)) {
117
+ return { ...existing, ...(parent && parent !== previous && { parent: resolved.parent }) };
118
+ }
119
+ const config = toConfig(resolved, {
120
+ allowUsageCredits,
121
+ allowFastModes: existing?.allowFastModes,
122
+ verifiedOrg: existing?.verifiedOrg,
123
+ userBannedModels: userBans(existing),
124
+ compactionThreshold: existing?.compactionThreshold,
125
+ });
126
+ for (const key of ['defaultEffort', 'modelIds', 'discovery']) {
127
+ if (existing?.[key] !== undefined) config[key] = existing[key];
128
+ }
129
+ return config;
130
+ }
131
+
59
132
  /** Existing user config is the base; explicit flags override it. */
60
133
  function planConfig(file, options) {
61
134
  let existing = null;
@@ -74,8 +147,12 @@ function planConfig(file, options) {
74
147
  if (invalid) existing = null;
75
148
  }
76
149
 
77
- let config = existing ? { ...existing } : loadPreset(options.preset ?? PRESETS[0]);
78
- if (existing && options.preset && options.preset !== existing.preset) {
150
+ const request = tierRequest(existing, options);
151
+ let config = request ? subscriptionConfig(existing, request)
152
+ : existing ? { ...existing } : loadPreset(options.preset ?? PRESETS[0]);
153
+ // A rebuilt roster replaces the user's ladders, so it is always backed up.
154
+ const rebuilt = Boolean(request && existing) && !isDeepStrictEqual(config.ladders, existing.ladders);
155
+ if (!isV2(config) && existing && options.preset && options.preset !== existing.preset) {
79
156
  const preset = loadPreset(options.preset);
80
157
  config = {
81
158
  ...preset,
@@ -89,8 +166,14 @@ function planConfig(file, options) {
89
166
  };
90
167
  }
91
168
  if (options.compaction !== undefined) config.compactionThreshold = options.compaction;
92
- if (options.banned?.length) config.bannedModels = union(completeConfig(config).bannedModels, options.banned);
93
- for (const [name, tier] of Object.entries(options.tiers ?? {})) {
169
+ if (options.banned?.length) {
170
+ config.bannedModels = union(completeConfig(config).bannedModels, options.banned);
171
+ if (isV2(config)) config.userBannedModels = union(config.userBannedModels ?? [], options.banned);
172
+ }
173
+ if (isV2(config)) {
174
+ for (const key of ['allowFastModes', 'verifiedOrg']) if (options[key] !== undefined) config[key] = options[key];
175
+ }
176
+ for (const [name, tier] of Object.entries(isV2(config) ? {} : options.tiers ?? {})) {
94
177
  const old = config.tiers?.[name];
95
178
  config.tiers = { ...config.tiers, [name]: { ...old, ...tier, heavyModels: old?.heavyModels ?? tier.heavyModels } };
96
179
  }
@@ -99,7 +182,8 @@ function planConfig(file, options) {
99
182
  const problem = configProblem(complete);
100
183
  if (problem) throw new CliError(`${file}: ${problem}`);
101
184
  const changed = !existing || !isDeepStrictEqual(config, existing);
102
- return { complete, invalid, text: changed ? `${JSON.stringify(config, null, 2)}\n` : null };
185
+ const text = changed ? `${JSON.stringify(config, null, 2)}\n` : null;
186
+ return { complete, invalid, rebuilt, selected: Boolean(request), text };
103
187
  }
104
188
 
105
189
  /** First of <file>.bak, .bak.1, ... that is free or already holds this content, so no backup is lost. */
@@ -118,6 +202,16 @@ function writeFile(file, content) {
118
202
  fs.writeFileSync(file, content);
119
203
  }
120
204
 
205
+ function writeAtomic(file, content) {
206
+ const temp = `${file}.${process.pid}.tmp`;
207
+ try {
208
+ writeFile(temp, content);
209
+ fs.renameSync(temp, file);
210
+ } finally {
211
+ fs.rmSync(temp, { force: true });
212
+ }
213
+ }
214
+
121
215
  /** Writes managed files, keeping the user's edits unless forced. Updates the hashes in "files". */
122
216
  export function writeManaged(target, desired, files, { force = false, log = console.log } = {}) {
123
217
  for (const [relative, content] of desired) {
@@ -150,10 +244,12 @@ export function writeManaged(target, desired, files, { force = false, log = cons
150
244
  function writeConfig(file, text, files, { invalid = false, alwaysBackUp = false, log }) {
151
245
  const exists = fs.existsSync(file);
152
246
  const ours = !exists || invalid || files[CONFIG_FILE] === fileHash(file);
153
- if (exists && (alwaysBackUp || invalid || !ours)) log(`backed up: ${backUp(file)}`);
154
- writeFile(file, text);
247
+ const backup = exists && (alwaysBackUp || invalid || !ours) ? backUp(file) : null;
248
+ if (backup) log(`backed up: ${backup}`);
249
+ writeAtomic(file, text);
155
250
  if (ours) files[CONFIG_FILE] = hashOf(text);
156
251
  log(`wrote: ${CONFIG_FILE}`);
252
+ return backup;
157
253
  }
158
254
 
159
255
  const renderInstalledSkill = (config, target) => Buffer.from(renderSkill(
@@ -215,11 +311,38 @@ function removeManaged(target, entries, log) {
215
311
  return kept;
216
312
  }
217
313
 
314
+ /** Contents of every managed file of a module selection, except the config. */
315
+ function desiredFiles(target, modules, config) {
316
+ const desired = new Map();
317
+ const source = (...parts) => fs.readFileSync(path.join(PACKAGE_ROOT, ...parts));
318
+ if (wantsCore(modules)) for (const file of CORE_FILES) desired.set(file, source('core', file));
319
+ if (wantsAuto(modules)) {
320
+ desired.set(SKILL, renderInstalledSkill(config, target));
321
+ for (const file of HOOK_FILES) {
322
+ if (!safePath(target, file)) throw new CliError(`${file} goes through a symlink; refusing to install hooks there`);
323
+ desired.set(file, source('hooks', path.posix.basename(file)));
324
+ }
325
+ }
326
+ return desired;
327
+ }
328
+
329
+ /** Writes the planned settings.json, warning when a hand-set compaction value is replaced. */
330
+ function applySettings(settings, merged, manifest, log) {
331
+ const next = merged ? merged.data : unmergeSettings(settings.data, manifest.env);
332
+ const previous = manifest?.env?.installed;
333
+ const current = settings.data.env?.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE;
334
+ if (merged && previous !== undefined && current !== undefined && current !== previous && current !== merged.env.installed) {
335
+ log('warning: CLAUDE_AUTOCOMPACT_PCT_OVERRIDE was changed by hand; replaced with the configured value');
336
+ }
337
+ if (writeSettings(settings, next)) log('updated: settings.json');
338
+ }
339
+
218
340
  export function install(target, options, log = console.log) {
219
341
  const manifest = readManifest(target);
220
342
  const modules = options.modules ?? manifest?.modules ?? 'full';
221
343
  const auto = wantsAuto(modules);
222
- if (!auto && (options.preset || options.compaction !== undefined || options.banned?.length || options.tiers)) {
344
+ const tierOptions = ['claudeTier', 'codexTier', 'antigravityTier', 'parent'].some((key) => options[key]);
345
+ if (!auto && (options.preset || options.compaction !== undefined || options.banned?.length || options.tiers || tierOptions)) {
223
346
  log('warning: preset, compaction, banned models and tiers do not apply to the core module; ignored');
224
347
  }
225
348
 
@@ -234,38 +357,35 @@ export function install(target, options, log = console.log) {
234
357
  }
235
358
  const config = auto ? planConfig(configPath, options) : null;
236
359
 
237
- const desired = new Map();
238
- const source = (...parts) => fs.readFileSync(path.join(PACKAGE_ROOT, ...parts));
239
- if (wantsCore(modules)) for (const file of CORE_FILES) desired.set(file, source('core', file));
240
- if (auto) {
241
- desired.set(SKILL, renderInstalledSkill(config.complete, target));
242
- for (const file of HOOK_FILES) {
243
- if (!safePath(target, file)) throw new CliError(`${file} goes through a symlink; refusing to install hooks there`);
244
- desired.set(file, source('hooks', path.posix.basename(file)));
360
+ const desired = desiredFiles(target, modules, config?.complete);
361
+ const v2 = auto && isV2(config.complete);
362
+ const merged = auto
363
+ ? mergeSettings(settings.data, target, config.complete.compactionThreshold, manifest?.env, v2 ? config.complete.parent : undefined)
364
+ : null;
365
+ if (v2) {
366
+ if (options.preset && options.preset !== config.complete.preset) {
367
+ log('warning: --preset does not apply to a v2 config; subscription tiers decide the providers');
245
368
  }
369
+ if (options.tiers) log('warning: --tiers does not apply to a v2 config; use --claude-tier, --codex-tier, --antigravity-tier');
370
+ if (config.selected) log(summaryTable(config.complete));
371
+ } else if (auto && (options.allowFastModes || options.verifiedOrg || options.allowUsageCredits)) {
372
+ log('warning: fast modes, verified org and usage credits need a subscription tier; ignored');
246
373
  }
247
- const merged = auto ? mergeSettings(settings.data, target, config.complete.compactionThreshold, manifest?.env) : null;
248
374
 
249
375
  fs.mkdirSync(target, { recursive: true });
250
376
  const files = { ...manifest?.files };
251
377
 
252
378
  writeManaged(target, desired, files, { force: options.force, log });
253
379
 
254
- if (config?.text) writeConfig(configPath, config.text, files, { invalid: config.invalid, log });
380
+ if (config?.text) {
381
+ writeConfig(configPath, config.text, files, { invalid: config.invalid, alwaysBackUp: config.rebuilt, log });
382
+ }
255
383
 
256
384
  const record = () => writeManifest(target, { version: 1, modules, files, ...(merged && { env: merged.env }) });
257
385
  // Wiring: put the prior env value on record before settings.json changes.
258
386
  if (merged) record();
259
387
 
260
- if (settings) {
261
- const next = merged ? merged.data : unmergeSettings(settings.data, manifest.env);
262
- const previous = manifest?.env?.installed;
263
- const current = settings.data.env?.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE;
264
- if (merged && previous !== undefined && current !== undefined && current !== previous && current !== merged.env.installed) {
265
- log('warning: CLAUDE_AUTOCOMPACT_PCT_OVERRIDE was changed by hand; replaced with the configured value');
266
- }
267
- if (writeSettings(settings, next)) log('updated: settings.json');
268
- }
388
+ if (settings) applySettings(settings, merged, manifest, log);
269
389
 
270
390
  // Stale files go after settings.json, so hooks never point at deleted scripts.
271
391
  const owned = new Set(moduleFiles(modules));
@@ -277,6 +397,85 @@ export function install(target, options, log = console.log) {
277
397
  if (auto) log('Restart T3 Code (and any running Claude Code session) so hooks and settings load.');
278
398
  }
279
399
 
400
+ /** v1 ladder slots keep roster models (as canonical ids); the rest are filled from the resolved ladder. */
401
+ function migrateLadders(old, { models, ladders }) {
402
+ const key = (name) => normalizeName(normalizeModel(name.trim()));
403
+ const base = (entry) => entry.split('@')[0];
404
+ const canonical = (entry) => {
405
+ const [ref, effort] = entry.split('@');
406
+ const colon = ref.indexOf(':');
407
+ const provider = colon < 0 ? null : canonicalProvider(ref.slice(0, colon));
408
+ const found = models.find((m) => key(m.model) === key(ref.slice(colon + 1))
409
+ && m.provider === (colon < 0 ? inferProvider(m.model) : provider));
410
+ if (!found) return null;
411
+ const id = found.provider === inferProvider(found.model) ? found.model : `${found.provider}:${found.model}`;
412
+ return effort ? `${id}@${effort.trim()}` : id;
413
+ };
414
+ return Object.fromEntries(LADDERS.map((name) => {
415
+ const kept = (old?.[name] ?? []).map(canonical);
416
+ if (!kept.some(Boolean)) return [name, ladders[name]];
417
+ const used = new Set(kept.filter(Boolean).map(base));
418
+ const spare = ladders[name].filter((entry) => !used.has(base(entry)));
419
+ return [name, kept.map((entry) => entry ?? spare.shift()).filter(Boolean)];
420
+ }));
421
+ }
422
+
423
+ /** Converts a v1 config to schema 2: backup, atomic write, then re-render of the files the manifest owns. */
424
+ export function upgrade(target, { log = console.log } = {}) {
425
+ const manifest = readManifest(target);
426
+ const file = path.join(target, CONFIG_FILE);
427
+ if (!fs.existsSync(file)) throw new CliError(`${file}: nothing to upgrade; run t3-auto-build init`);
428
+ if (!safePath(target, CONFIG_FILE)) throw new CliError(`${file} is a symlink; refusing to manage it`);
429
+ let existing;
430
+ try {
431
+ existing = readJson(file);
432
+ } catch {
433
+ throw new CliError(`${file}: not valid JSON; fix it, then run upgrade again`);
434
+ }
435
+ if (!isObject(existing)) throw new CliError(`${file}: not a JSON object`);
436
+ if (isV2(existing)) {
437
+ log(`${CONFIG_FILE} is already schema version 2; nothing to do`);
438
+ return { upgraded: false, backup: null, config: existing };
439
+ }
440
+ if (existing.schemaVersion !== undefined) {
441
+ throw new CliError(`${file}: unknown schemaVersion ${JSON.stringify(existing.schemaVersion)}; not upgrading`);
442
+ }
443
+ const old = completeConfig(existing);
444
+ const problem = configProblem(old);
445
+ if (problem) throw new CliError(`${file}: ${problem}`);
446
+
447
+ const resolved = resolve(inferSubscriptions(old));
448
+ const config = toConfig(resolved, { userBannedModels: userBans(existing), compactionThreshold: old.compactionThreshold });
449
+ config.ladders = migrateLadders(existing.ladders, resolved);
450
+ config.defaultEffort = old.defaultEffort;
451
+ for (const key of ['modelIds', 'discovery']) if (existing[key] !== undefined) config[key] = existing[key];
452
+
453
+ // Plan and validate everything before the first write.
454
+ const auto = manifest !== null && wantsAuto(manifest.modules);
455
+ if (auto) HOOKS.forEach((hook) => hookCommand(target, hook.script));
456
+ const settings = auto ? readSettings(target) : null;
457
+ renderInstalledSkill(config, target);
458
+ const desired = new Map(manifest
459
+ ? [...desiredFiles(target, manifest.modules, config)].filter(([relative]) => Object.hasOwn(manifest.files, relative))
460
+ : []);
461
+ const merged = auto
462
+ ? mergeSettings(settings.data, target, config.compactionThreshold, manifest.env, config.parent)
463
+ : null;
464
+
465
+ log(summaryTable(config));
466
+ log('note: tiers are assumed from your v1 providers; run init with --claude-tier, --codex-tier, --antigravity-tier to set yours');
467
+ const files = { ...manifest?.files };
468
+ const backup = writeConfig(file, `${JSON.stringify(config, null, 2)}\n`, files, { alwaysBackUp: true, log });
469
+ writeManaged(target, desired, files, { log });
470
+ // As in install: the prior settings values are on record before settings.json changes.
471
+ if (manifest) writeManifest(target, { ...manifest, files, ...(merged && { env: merged.env }) });
472
+ if (merged) {
473
+ applySettings(settings, merged, manifest, log);
474
+ log('Restart T3 Code (and any running Claude Code session) so hooks and settings load.');
475
+ }
476
+ return { upgraded: true, backup, config };
477
+ }
478
+
280
479
  export function uninstall(target, log = console.log) {
281
480
  const manifest = readManifest(target);
282
481
  const settingsExists = fs.existsSync(path.join(target, 'settings.json'));
@@ -292,6 +491,12 @@ export function uninstall(target, log = console.log) {
292
491
  return;
293
492
  }
294
493
  removeManaged(target, Object.entries(manifest.files), log);
494
+ // A generated cache, never listed in the manifest.
495
+ const cache = safePath(target, AVAILABILITY_FILE);
496
+ if (cache && fs.existsSync(cache) && fs.statSync(cache).isFile()) {
497
+ fs.rmSync(cache);
498
+ log(`removed: ${AVAILABILITY_FILE}`);
499
+ }
295
500
  fs.rmSync(path.join(target, MANIFEST_FILE));
296
501
  log(`done: uninstalled from ${target}`);
297
502
  }
package/lib/plans.mjs ADDED
@@ -0,0 +1,309 @@
1
+ // Subscription catalog and ladder resolution. Pure: no fs, no child_process.
2
+ import { RETIRED_MODELS, matchRetired } from '../hooks/_shared.mjs';
3
+
4
+ export { RETIRED_MODELS, matchRetired };
5
+
6
+ export const PROVIDERS = ['claude', 'codex', 'antigravity'];
7
+ export const POOLS = ['standard', 'fable', 'astra', 'third-party-claude'];
8
+ export const PARENTS = { sonnet: 'claude-sonnet-5-5', opus: 'claude-opus-5-5', fable: 'claude-fable-5-2' };
9
+
10
+ const ROLES = ['triage', 'planner', 'builder', 'tester', 'auditor'];
11
+ const DISPLAY = { claude: 'Claude', codex: 'Codex', antigravity: 'Antigravity' };
12
+ const PARENT_EFFORT = 'medium';
13
+ const MAX_BUILDERS = 6;
14
+
15
+ function deepFreeze(value) {
16
+ if (value !== null && typeof value === 'object') Object.values(value).forEach(deepFreeze);
17
+ return Object.freeze(value);
18
+ }
19
+
20
+ const model = (provider, family, version, pool = 'standard') =>
21
+ ({ provider, family, version, pool, scarceQuota: pool !== 'standard' });
22
+
23
+ export const MODELS = deepFreeze({
24
+ 'claude-haiku-5-5': model('claude', 'claude-haiku', '5.5'),
25
+ 'claude-sonnet-5-5': model('claude', 'claude-sonnet', '5.5'),
26
+ 'claude-opus-5-5': model('claude', 'claude-opus', '5.5'),
27
+ 'claude-fable-5-2': model('claude', 'claude-fable', '5.2', 'fable'),
28
+ 'gpt-6-luna': model('codex', 'gpt-luna', '6'),
29
+ 'gpt-6.1-terra': model('codex', 'gpt-terra', '6.1'),
30
+ 'gpt-6.1-sol': model('codex', 'gpt-sol', '6.1'),
31
+ 'gpt-6-astra': model('codex', 'gpt-astra', '6', 'astra'),
32
+ 'gemini-4-hydrogen': model('antigravity', 'gemini-hydrogen', '4'),
33
+ 'gemini-4-neon': model('antigravity', 'gemini-neon', '4'),
34
+ 'gemini-4-carbon': model('antigravity', 'gemini-carbon', '4'),
35
+ });
36
+
37
+ // Role preference per hosting; a tier keeps the ids it has.
38
+ const PREFERENCE = {
39
+ claude: {
40
+ triage: ['claude-haiku-5-5', 'claude-sonnet-5-5'],
41
+ planner: ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-2'],
42
+ builder: ['claude-sonnet-5-5', 'claude-opus-5-5', 'claude-fable-5-2'],
43
+ tester: ['claude-sonnet-5-5', 'claude-opus-5-5', 'claude-fable-5-2'],
44
+ auditor: ['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-2'],
45
+ },
46
+ codex: {
47
+ triage: ['gpt-6-luna', 'gpt-6.1-terra'],
48
+ planner: ['gpt-6.1-sol', 'gpt-6.1-terra', 'gpt-6-luna', 'gpt-6-astra'],
49
+ builder: ['gpt-6.1-terra', 'gpt-6.1-sol', 'gpt-6-luna', 'gpt-6-astra'],
50
+ tester: ['gpt-6-luna', 'gpt-6.1-terra', 'gpt-6.1-sol', 'gpt-6-astra'],
51
+ auditor: ['gpt-6.1-sol', 'gpt-6.1-terra', 'gpt-6-luna', 'gpt-6-astra'],
52
+ },
53
+ antigravity: {
54
+ triage: ['gemini-4-hydrogen', 'gemini-4-neon'],
55
+ planner: ['gemini-4-carbon', 'gemini-4-neon', 'gemini-4-hydrogen', 'claude-opus-5-5', 'claude-sonnet-5-5'],
56
+ builder: ['gemini-4-neon', 'gemini-4-carbon', 'gemini-4-hydrogen', 'claude-sonnet-5-5', 'claude-opus-5-5'],
57
+ tester: ['gemini-4-neon', 'gemini-4-hydrogen', 'gemini-4-carbon', 'claude-sonnet-5-5', 'claude-opus-5-5'],
58
+ auditor: ['gemini-4-carbon', 'gemini-4-neon', 'gemini-4-hydrogen', 'claude-opus-5-5', 'claude-sonnet-5-5'],
59
+ },
60
+ };
61
+
62
+ const NO_WINDOWS = { fiveHour: false, weekly: false, subCaps: {} };
63
+
64
+ /** Cross-hosted, or from a capped pool: overflow/escalation only. Takes "provider:model[@effort]". */
65
+ function isOverflow(ref) {
66
+ const [provider, rest] = ref.split(':');
67
+ const { provider: native, scarceQuota } = MODELS[rest.split('@')[0]];
68
+ return native !== provider || scarceQuota;
69
+ }
70
+
71
+ function tierLadders(provider, models) {
72
+ const ids = new Set(models.map((m) => m.model));
73
+ return Object.fromEntries(ROLES.map((role) => {
74
+ const refs = PREFERENCE[provider][role].filter((id) => ids.has(id)).map((id) => `${provider}:${id}`);
75
+ const ordered = [...refs.filter((ref) => !isOverflow(ref)), ...refs.filter(isOverflow)];
76
+ return [role, ordered.map((ref, index) => {
77
+ if (isOverflow(ref)) return `${ref}@medium`;
78
+ return role === 'planner' || (role === 'auditor' && index === 0) ? `${ref}@high` : ref;
79
+ })];
80
+ }));
81
+ }
82
+
83
+ function tier(provider, id, label, {
84
+ ids = [], cross = [], builders = 0, warning, usageBilled = false, windows, subCaps = {}, parent, parentOptions = [],
85
+ } = {}) {
86
+ const entry = (name, overrides) => {
87
+ const { family, version, pool, scarceQuota } = MODELS[name];
88
+ return { provider, model: name, pool, scarceQuota, family, version, ...overrides };
89
+ };
90
+ const models = [
91
+ ...ids.map((name) => entry(name)),
92
+ ...cross.map((name) => entry(name, { pool: 'third-party-claude', scarceQuota: true })),
93
+ ];
94
+ const cliSupported = models.length > 0;
95
+ return {
96
+ id,
97
+ label,
98
+ cliSupported,
99
+ warning: warning ?? (cliSupported ? null : `no ${DISPLAY[provider]} subscription selected`),
100
+ usageBilled,
101
+ windows: windows ?? (cliSupported ? { fiveHour: true, weekly: true, subCaps } : NO_WINDOWS),
102
+ parentDefault: parent ? { model: parent, effort: PARENT_EFFORT } : null,
103
+ parentOptions,
104
+ models,
105
+ maxParallelBuilders: builders,
106
+ ladders: tierLadders(provider, models),
107
+ };
108
+ }
109
+
110
+ const API = { usageBilled: true, windows: NO_WINDOWS, warning: 'API usage is billed per token' };
111
+
112
+ // shortcut: builder counts and quota windows are estimates, tune when providers publish per-tier limits.
113
+ function claudeTiers() {
114
+ const base = ['claude-haiku-5-5', 'claude-sonnet-5-5', 'claude-opus-5-5'];
115
+ const all = [...base, 'claude-fable-5-2'];
116
+ const two = ['sonnet', 'opus'];
117
+ const three = [...two, 'fable'];
118
+ const make = (id, label, options) => tier('claude', id, label, options);
119
+ return [
120
+ make('none', 'No Claude plan'),
121
+ make('free', 'Claude Free', { warning: 'Claude Code requires Pro or higher (or api)' }),
122
+ make('pro', 'Claude Pro', { ids: base, parent: 'sonnet', parentOptions: two, builders: 1 }),
123
+ make('max', 'Claude Max', { ids: base, parent: 'opus', parentOptions: two, builders: 2 }),
124
+ make('ultra', 'Claude Ultra', { ids: all, parent: 'opus', parentOptions: three, builders: 3, subCaps: { fable: 'weekly' } }),
125
+ make('team-standard', 'Claude Team Standard', { ids: base, parent: 'sonnet', parentOptions: two, builders: 1 }),
126
+ make('team-premium', 'Claude Team Premium', { ids: base, parent: 'opus', parentOptions: two, builders: 2 }),
127
+ make('api', 'Claude API', { ...API, ids: all, parent: 'opus', parentOptions: three, builders: 3 }),
128
+ ];
129
+ }
130
+
131
+ function codexTiers() {
132
+ const base = ['gpt-6-luna', 'gpt-6.1-terra'];
133
+ const all = [...base, 'gpt-6.1-sol', 'gpt-6-astra'];
134
+ const desktopOnly = 'desktop-only; Codex CLI unavailable';
135
+ const make = (id, label, options) => tier('codex', id, label, options);
136
+ const full = (id, label, builders) => make(id, label, { ids: all, builders, subCaps: { astra: 'weekly' } });
137
+ return [
138
+ make('none', 'No Codex plan'),
139
+ make('free', 'ChatGPT Free', { warning: desktopOnly }),
140
+ make('go', 'ChatGPT Go', { warning: desktopOnly }),
141
+ make('plus', 'ChatGPT Plus', { ids: base, builders: 1 }),
142
+ full('pro-100', 'ChatGPT Pro $100', 2),
143
+ full('pro-200', 'ChatGPT Pro $200', 2),
144
+ full('pro-500', 'ChatGPT Pro $500', 3),
145
+ full('business', 'ChatGPT Business', 2),
146
+ make('api', 'OpenAI API', { ...API, ids: all, builders: 3 }),
147
+ ];
148
+ }
149
+
150
+ function antigravityTiers() {
151
+ const base = ['gemini-4-hydrogen', 'gemini-4-neon'];
152
+ const all = [...base, 'gemini-4-carbon'];
153
+ const make = (id, label, options) => tier('antigravity', id, label, options);
154
+ const withClaude = (id, label, builders) => make(id, label, {
155
+ ids: all, cross: ['claude-sonnet-5-5', 'claude-opus-5-5'], builders, subCaps: { 'third-party-claude': 'weekly' },
156
+ });
157
+ return [
158
+ make('none', 'No Antigravity plan'),
159
+ make('free', 'Antigravity Free', { ids: base, builders: 1 }),
160
+ make('plus', 'Google AI Plus', { ids: all, builders: 1 }),
161
+ make('pro-trial', 'Google AI Pro (trial)', { ids: all, builders: 1 }),
162
+ withClaude('pro', 'Google AI Pro', 2),
163
+ withClaude('ultra-5x', 'Google AI Ultra 5x', 2),
164
+ withClaude('ultra-20x', 'Google AI Ultra 20x', 3),
165
+ ];
166
+ }
167
+
168
+ const byId = (tiers) => Object.fromEntries(tiers.map((t) => [t.id, t]));
169
+
170
+ export const CATALOG = deepFreeze({ claude: byId(claudeTiers()), codex: byId(codexTiers()), antigravity: byId(antigravityTiers()) });
171
+
172
+ export function getTier(provider, tierId) {
173
+ if (!PROVIDERS.includes(provider)) throw new Error(`unknown provider "${provider}"; expected one of ${PROVIDERS.join(', ')}`);
174
+ if (!Object.hasOwn(CATALOG[provider], tierId)) {
175
+ throw new Error(`unknown ${provider} tier "${tierId}"; expected one of ${Object.keys(CATALOG[provider]).join(', ')}`);
176
+ }
177
+ return CATALOG[provider][tierId];
178
+ }
179
+
180
+ /** Native ids are bare in resolved ladders; cross-hosted ones keep their "provider:" prefix. */
181
+ function ladderEntry(ref) {
182
+ const [provider, rest] = ref.split(':');
183
+ return MODELS[rest.split('@')[0]].provider === provider ? rest : ref;
184
+ }
185
+
186
+ /** Round-robin over providers beginning at lists[start]; overflow entries go last. */
187
+ function interleave(lists, start) {
188
+ const rotated = lists.map((_, i) => lists[(i + start) % lists.length]);
189
+ const roundRobin = (groups) => Array.from(
190
+ { length: Math.max(...groups.map((g) => g.length)) },
191
+ (_, i) => groups.flatMap((g) => g.slice(i, i + 1)),
192
+ ).flat();
193
+ return [
194
+ ...roundRobin(rotated.map((list) => list.filter((ref) => !isOverflow(ref)))),
195
+ ...roundRobin(rotated.map((list) => list.filter(isOverflow))),
196
+ ];
197
+ }
198
+
199
+ function resolveLadders(tiers) {
200
+ const slot = (role, start) => interleave(tiers.map((t) => t.ladders[role]), start).map(ladderEntry);
201
+ // Every provider's top auditor carries @high in the catalog; a merged ladder keeps it on its first entry only.
202
+ const auditor = (start) => slot('auditor', start).map((entry, index) => {
203
+ const [ref, effort] = entry.split('@');
204
+ if (index === 0) return `${ref}@high`;
205
+ return effort === 'high' ? ref : entry;
206
+ });
207
+ return {
208
+ tier1: slot('triage', 0),
209
+ commandRunner: slot('triage', 0),
210
+ builderA: slot('builder', 0),
211
+ testerA: slot('tester', 1),
212
+ auditorA: auditor(1),
213
+ builderB: slot('builder', 1),
214
+ testerB: slot('tester', 2),
215
+ auditorB: auditor(0),
216
+ architect: slot('planner', 0),
217
+ dualAudit: tiers.slice(0, 2).map((t) => ladderEntry(t.ladders.auditor[0])),
218
+ };
219
+ }
220
+
221
+ function resolveParent(claude, requested) {
222
+ if (requested == null) return claude ? { ...claude.parentDefault } : null;
223
+ if (!claude?.parentOptions.includes(requested)) {
224
+ const options = claude?.parentOptions.join(', ') ?? 'none (needs an eligible Claude tier)';
225
+ throw new Error(`--parent ${requested} is not available on the selected Claude tier; options: ${options}`);
226
+ }
227
+ return { model: requested, effort: claude.parentDefault.effort };
228
+ }
229
+
230
+ export function resolveTiers({ claude = 'none', codex = 'none', antigravity = 'none' } = {}, { parent, allowUsageCredits = false } = {}) {
231
+ const subscriptions = { claude, codex, antigravity };
232
+ const warnings = [];
233
+ const planRestrictedModels = [];
234
+ const eligible = new Map();
235
+ for (const provider of PROVIDERS) {
236
+ const selected = getTier(provider, subscriptions[provider]);
237
+ if (selected.warning) warnings.push(`${provider} ${selected.id}: ${selected.warning}`);
238
+ if (selected.usageBilled && !allowUsageCredits) {
239
+ warnings.push(`${provider} ${selected.id}: models excluded; pass --allow-usage-credits to use them`);
240
+ planRestrictedModels.push(...selected.models.map((m) => `${provider}:${m.model}`));
241
+ } else if (selected.cliSupported) {
242
+ eligible.set(provider, selected);
243
+ }
244
+ }
245
+ if (eligible.size === 0) throw new Error(`no CLI-capable subscription (${warnings.join('; ')})`);
246
+
247
+ const tiers = [...eligible.values()];
248
+ const models = tiers.flatMap((t) => t.models.map((m) => ({ ...m })));
249
+ const allowlist = Object.fromEntries(PROVIDERS.map(
250
+ (provider) => [DISPLAY[provider], models.filter((m) => m.provider === provider).map((m) => m.model)],
251
+ ));
252
+ return {
253
+ subscriptions,
254
+ parent: resolveParent(eligible.get('claude'), parent),
255
+ models,
256
+ allowlist,
257
+ ladders: resolveLadders(tiers),
258
+ maxParallelBuilders: Math.min(MAX_BUILDERS, tiers.reduce((sum, t) => sum + t.maxParallelBuilders, 0)),
259
+ planRestrictedModels,
260
+ warnings,
261
+ };
262
+ }
263
+
264
+ function presetFor(allowlist) {
265
+ const active = PROVIDERS.filter((p) => allowlist[DISPLAY[p]].length > 0).join(',');
266
+ return { 'claude,codex,antigravity': 'tri-provider', 'claude,codex': 'claude-codex', claude: 'claude-only' }[active] ?? 'custom';
267
+ }
268
+
269
+ export function toConfig(resolved, {
270
+ preset, allowFastModes = false, allowUsageCredits = false, verifiedOrg = false, userBannedModels = [], compactionThreshold = 35,
271
+ } = {}) {
272
+ const { subscriptions, parent, models, allowlist, planRestrictedModels, ladders, maxParallelBuilders } = structuredClone(resolved);
273
+ const banned = [...userBannedModels];
274
+ return {
275
+ schemaVersion: 2,
276
+ preset: preset ?? presetFor(allowlist),
277
+ subscriptions,
278
+ parent,
279
+ allowFastModes,
280
+ allowUsageCredits,
281
+ verifiedOrg,
282
+ models,
283
+ allowlist,
284
+ retiredModels: [...RETIRED_MODELS],
285
+ planRestrictedModels,
286
+ userBannedModels: banned,
287
+ bannedModels: banned,
288
+ ladders,
289
+ maxParallelBuilders,
290
+ defaultModel: allowlist.Claude.includes(PARENTS.sonnet) ? PARENTS.sonnet : ladders.builderA[0].split('@')[0],
291
+ defaultEffort: 'medium',
292
+ compactionThreshold,
293
+ modelIds: {},
294
+ discovery: {},
295
+ };
296
+ }
297
+
298
+ const versionOf = (value) => String(value?.version ?? value).split('.').map(Number);
299
+
300
+ /** Numerically newer dotted version; objects must also share a family. */
301
+ export function supersedes(a, b) {
302
+ if (a?.family !== b?.family) return false;
303
+ const [left, right] = [versionOf(a), versionOf(b)];
304
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
305
+ const difference = (left[i] ?? 0) - (right[i] ?? 0);
306
+ if (difference !== 0) return difference > 0;
307
+ }
308
+ return false;
309
+ }