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 +21 -0
- package/README.md +311 -0
- package/bin/cli.mjs +175 -0
- package/core/CLAUDE.md +23 -0
- package/core/commands/fix.md +5 -0
- package/core/commands/handover.md +6 -0
- package/core/commands/review.md +4 -0
- package/core/rules/code-quality.md +14 -0
- package/hooks/_quota.mjs +213 -0
- package/hooks/_shared.mjs +208 -0
- package/hooks/post-tool-use.mjs +33 -0
- package/hooks/pre-compact.mjs +82 -0
- package/hooks/pre-tool-use.mjs +134 -0
- package/hooks/session-start.mjs +15 -0
- package/lib/detect.mjs +52 -0
- package/lib/doctor.mjs +140 -0
- package/lib/install.mjs +297 -0
- package/lib/manifest.mjs +38 -0
- package/lib/paths.mjs +41 -0
- package/lib/probe.mjs +251 -0
- package/lib/prompt.mjs +114 -0
- package/lib/quota.mjs +204 -0
- package/lib/render.mjs +59 -0
- package/lib/settings.mjs +135 -0
- package/package.json +24 -0
- package/presets/claude-codex.json +31 -0
- package/presets/claude-only.json +26 -0
- package/presets/tri-provider.json +36 -0
- package/skills/auto-build/SKILL.md.tmpl +166 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// SessionStart: report the active lockouts and prune expired cooldowns.
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { prune, readCooldowns, summarize, writeCooldowns } from './_quota.mjs';
|
|
4
|
+
import { COOLDOWN_FILE, configDirOf, warn } from './_shared.mjs';
|
|
5
|
+
|
|
6
|
+
try {
|
|
7
|
+
const file = path.join(configDirOf(import.meta.url), COOLDOWN_FILE);
|
|
8
|
+
// A malformed file throws here, so it is never overwritten.
|
|
9
|
+
const { kept, removed } = prune(readCooldowns(file));
|
|
10
|
+
const lines = summarize(kept);
|
|
11
|
+
if (lines.length) process.stdout.write(`${lines.join('\n')}\n`);
|
|
12
|
+
if (Object.keys(removed).length) writeCooldowns(file, kept);
|
|
13
|
+
} catch (error) {
|
|
14
|
+
warn(`ignoring ${COOLDOWN_FILE} (${error.name})`);
|
|
15
|
+
}
|
package/lib/detect.mjs
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Which provider CLIs are installed, and how their subscription tiers share limits. Node >=18, node:* only.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { which as findOnPath } from '../hooks/_shared.mjs';
|
|
6
|
+
import { CliError } from './paths.mjs';
|
|
7
|
+
|
|
8
|
+
// Config directories under the home folder. Only their existence is checked; nothing inside is opened.
|
|
9
|
+
const MARKERS = { claude: ['.claude'], codex: ['.codex'], antigravity: ['.antigravity', '.gemini/antigravity'] };
|
|
10
|
+
|
|
11
|
+
/** A provider counts as installed only when its binary is on PATH; the marker is informational. */
|
|
12
|
+
export function detect({ which = findOnPath, exists = fs.existsSync, home = os.homedir() } = {}) {
|
|
13
|
+
const providers = Object.fromEntries(Object.entries(MARKERS).map(([name, dirs]) => [name, {
|
|
14
|
+
binary: which(name) ?? null,
|
|
15
|
+
marker: dirs.some((dir) => Boolean(exists(path.join(home, dir)))),
|
|
16
|
+
}]));
|
|
17
|
+
const { claude, codex, antigravity } = providers;
|
|
18
|
+
let preset = 'claude-only';
|
|
19
|
+
if (claude.binary && codex.binary) preset = antigravity.binary ? 'tri-provider' : 'claude-codex';
|
|
20
|
+
return { providers, preset };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// sharing: what a short-window limit locks, as _quota.parseRateLimit understands it.
|
|
24
|
+
const PLANS = {
|
|
25
|
+
claude: { pro: 'provider', max: 'heavy-tier-only' },
|
|
26
|
+
codex: { plus: 'provider', pro: 'heavy-tier-only' },
|
|
27
|
+
antigravity: { standard: 'provider', ultra: 'heavy-tier-only' },
|
|
28
|
+
};
|
|
29
|
+
export const HEAVY_MODELS = { claude: ['Claude Opus 5.5'], codex: ['gpt-6-luna'], antigravity: ['Gemini 4 Carbon'] };
|
|
30
|
+
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
|
31
|
+
|
|
32
|
+
/** "claude:max,codex:pro:monday" to { claude: { plan, sharing, resetDay?, heavyModels }, ... }. */
|
|
33
|
+
export function parseTiers(spec) {
|
|
34
|
+
const tiers = {};
|
|
35
|
+
for (const item of String(spec ?? '').split(',')) {
|
|
36
|
+
const [provider, plan, day, ...extra] = item.split(':').map((part) => part.trim().toLowerCase());
|
|
37
|
+
if (!Object.hasOwn(PLANS, provider) || !Object.hasOwn(PLANS[provider], plan ?? '') || extra.length) {
|
|
38
|
+
const valid = Object.entries(PLANS).map(([name, plans]) => `${name}:${Object.keys(plans).join('|')}`).join(', ');
|
|
39
|
+
throw new CliError(`invalid tier "${item.trim()}"; expected provider:plan[:weekday] with ${valid}`);
|
|
40
|
+
}
|
|
41
|
+
if (Object.hasOwn(tiers, provider)) throw new CliError(`tier for "${provider}" is given twice`);
|
|
42
|
+
const resetDay = day === undefined ? undefined : WEEKDAYS.find((name) => day === name || day === name.slice(0, 3));
|
|
43
|
+
if (day !== undefined && !resetDay) throw new CliError(`invalid reset day "${day}"; use a weekday such as monday`);
|
|
44
|
+
tiers[provider] = {
|
|
45
|
+
plan,
|
|
46
|
+
sharing: PLANS[provider][plan],
|
|
47
|
+
...(resetDay && { resetDay }),
|
|
48
|
+
heavyModels: [...HEAVY_MODELS[provider]],
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
return tiers;
|
|
52
|
+
}
|
package/lib/doctor.mjs
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { CONFIG_FILE, COOLDOWN_FILE, isObject, readJson, run, which } from '../hooks/_shared.mjs';
|
|
6
|
+
import { completeConfig, configProblem, moduleFiles, wantsAuto } from './install.mjs';
|
|
7
|
+
import { fileHash, readManifest } from './manifest.mjs';
|
|
8
|
+
import { safePath } from './paths.mjs';
|
|
9
|
+
import { HOOKS, HOOKS_DIR, readSettings, taggedHooks } from './settings.mjs';
|
|
10
|
+
|
|
11
|
+
const TOOLS = [
|
|
12
|
+
{
|
|
13
|
+
name: 'rg',
|
|
14
|
+
hint: 'winget install BurntSushi.ripgrep.MSVC | brew install ripgrep | apt install ripgrep',
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: 'sg',
|
|
18
|
+
// Linux ships an unrelated "sg" (newgrp), so the version text must name ast-grep.
|
|
19
|
+
mustMention: /ast-grep/i,
|
|
20
|
+
hint: 'winget install ast-grep.ast-grep | brew install ast-grep | npm i -g @ast-grep/cli',
|
|
21
|
+
},
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
// Each hook runs with mock stdin from a temporary copy, so the real cooldown file is never touched.
|
|
25
|
+
function smokeTest(target, report) {
|
|
26
|
+
const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 't3ab-doctor-'));
|
|
27
|
+
try {
|
|
28
|
+
const hooks = path.join(sandbox, ...HOOKS_DIR.split('/'));
|
|
29
|
+
fs.mkdirSync(hooks, { recursive: true });
|
|
30
|
+
const installed = path.join(target, ...HOOKS_DIR.split('/'));
|
|
31
|
+
for (const name of fs.readdirSync(installed)) {
|
|
32
|
+
if (name.endsWith('.mjs')) fs.copyFileSync(path.join(installed, name), path.join(hooks, name));
|
|
33
|
+
}
|
|
34
|
+
const config = path.join(target, CONFIG_FILE);
|
|
35
|
+
if (fs.existsSync(config)) fs.copyFileSync(config, path.join(sandbox, CONFIG_FILE));
|
|
36
|
+
|
|
37
|
+
const check = (script, label, payload, expected) => {
|
|
38
|
+
const result = spawnSync(process.execPath, [path.join(hooks, script)], {
|
|
39
|
+
input: JSON.stringify(payload),
|
|
40
|
+
cwd: sandbox,
|
|
41
|
+
encoding: 'utf8',
|
|
42
|
+
timeout: 20_000,
|
|
43
|
+
});
|
|
44
|
+
const good = result.status === expected && (expected !== 2 || result.stderr.trim() !== '');
|
|
45
|
+
report(good ? 'ok' : 'fail', `${script} ${label}: exit ${result.status}, expected ${expected}`);
|
|
46
|
+
};
|
|
47
|
+
check('session-start.mjs', 'benign', {}, 0);
|
|
48
|
+
check('pre-compact.mjs', 'benign', { cwd: sandbox }, 0);
|
|
49
|
+
check('pre-tool-use.mjs', 'benign', { tool_name: 'Bash', tool_input: { command: 'echo ok' } }, 0);
|
|
50
|
+
check('pre-tool-use.mjs', 'secret path', { tool_name: 'Write', tool_input: { file_path: '.env' } }, 2);
|
|
51
|
+
check('post-tool-use.mjs', 'benign', { tool_name: 'Write', tool_input: { file_path: path.join(sandbox, 'missing.txt') } }, 0);
|
|
52
|
+
} finally {
|
|
53
|
+
fs.rmSync(sandbox, { recursive: true, force: true });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Returns the exit code: 1 when something installed is broken, 0 otherwise (warnings allowed). */
|
|
58
|
+
export function doctor(target, log = console.log) {
|
|
59
|
+
let failures = 0;
|
|
60
|
+
const report = (level, message) => {
|
|
61
|
+
if (level === 'fail') failures += 1;
|
|
62
|
+
log(`${level.padEnd(4)} ${message}`);
|
|
63
|
+
};
|
|
64
|
+
const attempt = (action) => {
|
|
65
|
+
try {
|
|
66
|
+
return action();
|
|
67
|
+
} catch (error) {
|
|
68
|
+
report('fail', error.message);
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const manifest = attempt(() => readManifest(target));
|
|
74
|
+
if (manifest) {
|
|
75
|
+
for (const relative of new Set([...moduleFiles(manifest.modules), ...Object.keys(manifest.files)])) {
|
|
76
|
+
const file = safePath(target, relative);
|
|
77
|
+
if (!file) report('fail', `unsafe path or symlink: ${relative}`);
|
|
78
|
+
else if (!fs.existsSync(file)) report('fail', `missing: ${relative}`);
|
|
79
|
+
else if (manifest.files[relative] !== fileHash(file)) report('warn', `differs from the installed version: ${relative}`);
|
|
80
|
+
else report('ok', relative);
|
|
81
|
+
}
|
|
82
|
+
} else if (failures === 0) {
|
|
83
|
+
report('fail', `not installed: no manifest in ${target}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const settings = attempt(() => readSettings(target));
|
|
87
|
+
if (manifest && wantsAuto(manifest.modules)) {
|
|
88
|
+
const configPath = path.join(target, CONFIG_FILE);
|
|
89
|
+
if (fs.existsSync(configPath)) {
|
|
90
|
+
attempt(() => {
|
|
91
|
+
let config;
|
|
92
|
+
try {
|
|
93
|
+
config = readJson(configPath);
|
|
94
|
+
} catch {
|
|
95
|
+
throw new Error(`${CONFIG_FILE} is not valid JSON`);
|
|
96
|
+
}
|
|
97
|
+
const problem = isObject(config) ? configProblem(completeConfig(config)) : 'not a JSON object';
|
|
98
|
+
if (problem) throw new Error(`${CONFIG_FILE}: ${problem}`);
|
|
99
|
+
report('ok', `${CONFIG_FILE} is valid`);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (settings) {
|
|
103
|
+
const tagged = taggedHooks(settings.data);
|
|
104
|
+
for (const { event, script } of HOOKS) {
|
|
105
|
+
const entry = tagged.find((t) => t.event === event && t.hook.command.includes(`/${script}"`));
|
|
106
|
+
const file = entry?.hook.command.match(/"([^"]+)"/)?.[1];
|
|
107
|
+
if (!file) report('fail', `settings.json does not wire ${script} on ${event}`);
|
|
108
|
+
else if (!fs.existsSync(file)) report('fail', `hook path does not exist: ${file}`);
|
|
109
|
+
else report('ok', `${event} wired`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (fs.existsSync(path.join(target, ...HOOKS_DIR.split('/')))) attempt(() => smokeTest(target, report));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const cooldowns = path.join(target, COOLDOWN_FILE);
|
|
116
|
+
if (fs.existsSync(cooldowns)) {
|
|
117
|
+
try {
|
|
118
|
+
readJson(cooldowns);
|
|
119
|
+
} catch {
|
|
120
|
+
report('warn', `${COOLDOWN_FILE} is not valid JSON`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const commands = Object.values(settings?.data.hooks ?? {})
|
|
125
|
+
.flat()
|
|
126
|
+
.flatMap((group) => group?.hooks ?? [])
|
|
127
|
+
.map((hook) => String(hook?.command));
|
|
128
|
+
const legacy = ['safety-guard', 'post-format', 'pre-compact', 'session-start'].filter((name) =>
|
|
129
|
+
commands.some((command) => command.toLowerCase().includes(`${name}.ps1`)),
|
|
130
|
+
);
|
|
131
|
+
if (legacy.length) report('warn', `old PowerShell hooks are still wired (${legacy.join(', ')}); remove them to avoid running both`);
|
|
132
|
+
|
|
133
|
+
for (const { name, mustMention, hint } of TOOLS) {
|
|
134
|
+
const executable = which(name);
|
|
135
|
+
const result = executable && run(executable, ['--version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000 });
|
|
136
|
+
const good = result?.status === 0 && (!mustMention || mustMention.test(`${result.stdout}${result.stderr}`));
|
|
137
|
+
report(good ? 'ok' : 'warn', good ? `${name} available` : `${name} not found. Install: ${hint}`);
|
|
138
|
+
}
|
|
139
|
+
return failures ? 1 : 0;
|
|
140
|
+
}
|
package/lib/install.mjs
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { CONFIG_FILE, isAllowlist, isObject, isStringList, readJson } from '../hooks/_shared.mjs';
|
|
5
|
+
import { MANIFEST_FILE, fileHash, hashOf, readManifest, writeManifest } from './manifest.mjs';
|
|
6
|
+
import { CliError, PACKAGE_ROOT, safePath } from './paths.mjs';
|
|
7
|
+
import { renderSkill } from './render.mjs';
|
|
8
|
+
import { HOOKS, HOOKS_DIR, hookCommand, mergeSettings, readSettings, taggedHooks, unmergeSettings, writeSettings } from './settings.mjs';
|
|
9
|
+
|
|
10
|
+
export const PRESETS = ['tri-provider', 'claude-codex', 'claude-only'];
|
|
11
|
+
const EFFORTS = ['low', 'medium', 'high'];
|
|
12
|
+
const SKILL = 'skills/auto-build/SKILL.md';
|
|
13
|
+
const CORE_FILES = ['CLAUDE.md', 'rules/code-quality.md', 'commands/fix.md', 'commands/review.md', 'commands/handover.md'];
|
|
14
|
+
const HOOK_FILES = ['_shared.mjs', '_quota.mjs', ...HOOKS.map((hook) => hook.script)].map((name) => `${HOOKS_DIR}/${name}`);
|
|
15
|
+
|
|
16
|
+
export const wantsCore = (modules) => modules !== 'auto-build';
|
|
17
|
+
export const wantsAuto = (modules) => modules !== 'core';
|
|
18
|
+
|
|
19
|
+
/** Every file a module selection owns, relative to the target. */
|
|
20
|
+
export const moduleFiles = (modules) => [
|
|
21
|
+
...(wantsCore(modules) ? CORE_FILES : []),
|
|
22
|
+
...(wantsAuto(modules) ? [SKILL, ...HOOK_FILES, CONFIG_FILE] : []),
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
export const loadPreset = (name) => readJson(path.join(PACKAGE_ROOT, 'presets', `${name}.json`));
|
|
26
|
+
const union = (a, b) => [...new Map([...a, ...b].map((item) => [item.toLowerCase(), item])).values()];
|
|
27
|
+
|
|
28
|
+
const SHARING = ['provider', 'heavy-tier-only'];
|
|
29
|
+
const optional = (value, valid) => value === undefined || valid(value);
|
|
30
|
+
const isTier = (tier) => isObject(tier)
|
|
31
|
+
&& optional(tier.plan, (v) => typeof v === 'string')
|
|
32
|
+
&& optional(tier.sharing, (v) => SHARING.includes(v))
|
|
33
|
+
&& optional(tier.resetDay, (v) => typeof v === 'string' || Number.isInteger(v))
|
|
34
|
+
&& optional(tier.heavyModels, isStringList);
|
|
35
|
+
|
|
36
|
+
export function configProblem(config) {
|
|
37
|
+
if (!isAllowlist(config.allowlist)) return '"allowlist" must map provider names to lists of model names';
|
|
38
|
+
if (!isStringList(config.bannedModels)) return '"bannedModels" must be a list of model names';
|
|
39
|
+
if (!isObject(config.ladders) || !Object.values(config.ladders).every(isStringList)) return '"ladders" must map ladder names to lists';
|
|
40
|
+
const percent = config.compactionThreshold;
|
|
41
|
+
if (!Number.isInteger(percent) || percent < 1 || percent > 100) return '"compactionThreshold" must be an integer from 1 to 100';
|
|
42
|
+
if (!EFFORTS.includes(config.defaultEffort)) return `"defaultEffort" must be one of ${EFFORTS.join(', ')}`;
|
|
43
|
+
if (typeof config.defaultModel !== 'string') return '"defaultModel" must be a model name';
|
|
44
|
+
if (!optional(config.tiers, (v) => isObject(v) && Object.values(v).every(isTier))) {
|
|
45
|
+
return `"tiers" must map provider names to settings (sharing: ${SHARING.join(' or ')}; heavyModels: list of model names)`;
|
|
46
|
+
}
|
|
47
|
+
if (!optional(config.modelIds, (v) => isObject(v) && isStringList(Object.values(v)))) {
|
|
48
|
+
return '"modelIds" must map model names to CLI model ids';
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The config with missing fields filled from its preset. */
|
|
54
|
+
export function completeConfig(config) {
|
|
55
|
+
const preset = loadPreset(PRESETS.includes(config.preset) ? config.preset : PRESETS[0]);
|
|
56
|
+
return { ...preset, ...config, ladders: isObject(config.ladders ?? {}) ? { ...preset.ladders, ...config.ladders } : config.ladders };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Existing user config is the base; explicit flags override it. */
|
|
60
|
+
function planConfig(file, options) {
|
|
61
|
+
let existing = null;
|
|
62
|
+
let invalid = false;
|
|
63
|
+
if (fs.existsSync(file)) {
|
|
64
|
+
try {
|
|
65
|
+
existing = readJson(file);
|
|
66
|
+
invalid = !isObject(existing) || configProblem(completeConfig(existing)) !== null;
|
|
67
|
+
} catch {
|
|
68
|
+
invalid = true;
|
|
69
|
+
}
|
|
70
|
+
if (invalid && !options.force) {
|
|
71
|
+
const reason = isObject(existing) ? configProblem(completeConfig(existing)) : 'not a JSON object';
|
|
72
|
+
throw new CliError(`${file}: ${reason}. Fix it, or use --force to back it up and replace it`);
|
|
73
|
+
}
|
|
74
|
+
if (invalid) existing = null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let config = existing ? { ...existing } : loadPreset(options.preset ?? PRESETS[0]);
|
|
78
|
+
if (existing && options.preset && options.preset !== existing.preset) {
|
|
79
|
+
const preset = loadPreset(options.preset);
|
|
80
|
+
config = {
|
|
81
|
+
...preset,
|
|
82
|
+
...existing,
|
|
83
|
+
preset: preset.preset,
|
|
84
|
+
allowlist: preset.allowlist,
|
|
85
|
+
ladders: preset.ladders,
|
|
86
|
+
defaultModel: preset.defaultModel,
|
|
87
|
+
defaultEffort: preset.defaultEffort,
|
|
88
|
+
bannedModels: union(existing.bannedModels ?? [], preset.bannedModels),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
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 ?? {})) {
|
|
94
|
+
const old = config.tiers?.[name];
|
|
95
|
+
config.tiers = { ...config.tiers, [name]: { ...old, ...tier, heavyModels: old?.heavyModels ?? tier.heavyModels } };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const complete = completeConfig(config);
|
|
99
|
+
const problem = configProblem(complete);
|
|
100
|
+
if (problem) throw new CliError(`${file}: ${problem}`);
|
|
101
|
+
const changed = !existing || !isDeepStrictEqual(config, existing);
|
|
102
|
+
return { complete, invalid, text: changed ? `${JSON.stringify(config, null, 2)}\n` : null };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** First of <file>.bak, .bak.1, ... that is free or already holds this content, so no backup is lost. */
|
|
106
|
+
function backUp(file) {
|
|
107
|
+
const content = fs.readFileSync(file);
|
|
108
|
+
for (let i = 0; ; i += 1) {
|
|
109
|
+
const backup = `${file}.bak${i ? `.${i}` : ''}`;
|
|
110
|
+
if (fs.existsSync(backup) && !fs.readFileSync(backup).equals(content)) continue;
|
|
111
|
+
fs.writeFileSync(backup, content);
|
|
112
|
+
return backup;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function writeFile(file, content) {
|
|
117
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
118
|
+
fs.writeFileSync(file, content);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Writes managed files, keeping the user's edits unless forced. Updates the hashes in "files". */
|
|
122
|
+
export function writeManaged(target, desired, files, { force = false, log = console.log } = {}) {
|
|
123
|
+
for (const [relative, content] of desired) {
|
|
124
|
+
const file = safePath(target, relative);
|
|
125
|
+
if (!file) {
|
|
126
|
+
log(`warning: skipped ${relative} (symlink in its path)`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (fs.existsSync(file)) {
|
|
130
|
+
const current = fileHash(file);
|
|
131
|
+
if (current === hashOf(content)) {
|
|
132
|
+
if (files[relative]) files[relative] = current;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (current !== files[relative]) {
|
|
136
|
+
if (!force) {
|
|
137
|
+
log(`warning: skipped ${relative} (existing file with your changes; --force backs it up and overwrites)`);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
log(`backed up: ${backUp(file)}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
writeFile(file, content);
|
|
144
|
+
files[relative] = hashOf(content);
|
|
145
|
+
log(`installed: ${relative}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A config you edited stays "yours": it keeps the old hash, so uninstall will not delete it. */
|
|
150
|
+
function writeConfig(file, text, files, { invalid = false, alwaysBackUp = false, log }) {
|
|
151
|
+
const exists = fs.existsSync(file);
|
|
152
|
+
const ours = !exists || invalid || files[CONFIG_FILE] === fileHash(file);
|
|
153
|
+
if (exists && (alwaysBackUp || invalid || !ours)) log(`backed up: ${backUp(file)}`);
|
|
154
|
+
writeFile(file, text);
|
|
155
|
+
if (ours) files[CONFIG_FILE] = hashOf(text);
|
|
156
|
+
log(`wrote: ${CONFIG_FILE}`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const renderInstalledSkill = (config, target) => Buffer.from(renderSkill(
|
|
160
|
+
fs.readFileSync(path.join(PACKAGE_ROOT, 'skills', 'auto-build', 'SKILL.md.tmpl'), 'utf8'), config, target,
|
|
161
|
+
));
|
|
162
|
+
|
|
163
|
+
/** Persists a changed config into an existing installation and re-renders SKILL.md. Nothing else is touched. */
|
|
164
|
+
export async function syncConfig(target, config, { force = false, log = console.log } = {}) {
|
|
165
|
+
const manifest = readManifest(target);
|
|
166
|
+
if (!manifest || !wantsAuto(manifest.modules)) {
|
|
167
|
+
throw new CliError(`no auto-build installation in ${target}; run init first`);
|
|
168
|
+
}
|
|
169
|
+
const complete = isObject(config) ? completeConfig(config) : null;
|
|
170
|
+
const problem = complete ? configProblem(complete) : 'not a JSON object';
|
|
171
|
+
if (problem) throw new CliError(`${CONFIG_FILE}: ${problem}`);
|
|
172
|
+
const configPath = safePath(target, CONFIG_FILE);
|
|
173
|
+
if (!configPath) throw new CliError(`${path.join(target, CONFIG_FILE)} is a symlink; refusing to manage it`);
|
|
174
|
+
const skill = renderInstalledSkill(complete, target); // renders before the first write
|
|
175
|
+
|
|
176
|
+
const files = { ...manifest.files };
|
|
177
|
+
let current;
|
|
178
|
+
try {
|
|
179
|
+
current = readJson(configPath);
|
|
180
|
+
} catch {
|
|
181
|
+
current = undefined;
|
|
182
|
+
}
|
|
183
|
+
if (!isDeepStrictEqual(current, config)) {
|
|
184
|
+
writeConfig(configPath, `${JSON.stringify(config, null, 2)}\n`, files, { alwaysBackUp: true, log });
|
|
185
|
+
}
|
|
186
|
+
writeManaged(target, new Map([[SKILL, skill]]), files, { force, log });
|
|
187
|
+
writeManifest(target, { ...manifest, files });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Delete managed files that are still exactly as installed. Returns the entries that were kept. */
|
|
191
|
+
function removeManaged(target, entries, log) {
|
|
192
|
+
const kept = {};
|
|
193
|
+
for (const [relative, hash] of entries) {
|
|
194
|
+
const file = safePath(target, relative);
|
|
195
|
+
if (!file) {
|
|
196
|
+
log(`warning: ignored unsafe manifest path ${JSON.stringify(relative)}`);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (!fs.existsSync(file)) continue;
|
|
200
|
+
if (!fs.statSync(file).isFile() || fileHash(file) !== hash) {
|
|
201
|
+
kept[relative] = hash;
|
|
202
|
+
log(`kept (modified since install): ${relative}`);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
fs.rmSync(file);
|
|
206
|
+
log(`removed: ${relative}`);
|
|
207
|
+
for (let dir = path.dirname(file); dir !== path.resolve(target); dir = path.dirname(dir)) {
|
|
208
|
+
try {
|
|
209
|
+
fs.rmdirSync(dir); // only succeeds when empty
|
|
210
|
+
} catch {
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return kept;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function install(target, options, log = console.log) {
|
|
219
|
+
const manifest = readManifest(target);
|
|
220
|
+
const modules = options.modules ?? manifest?.modules ?? 'full';
|
|
221
|
+
const auto = wantsAuto(modules);
|
|
222
|
+
if (!auto && (options.preset || options.compaction !== undefined || options.banned?.length || options.tiers)) {
|
|
223
|
+
log('warning: preset, compaction, banned models and tiers do not apply to the core module; ignored');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Plan and validate everything before the first write.
|
|
227
|
+
if (auto) HOOKS.forEach((hook) => hookCommand(target, hook.script));
|
|
228
|
+
// settings.json is only opened when we wire hooks now, or have to unwire an earlier install.
|
|
229
|
+
const unwire = !auto && manifest !== null && (manifest.env !== undefined || wantsAuto(manifest.modules));
|
|
230
|
+
const settings = auto || unwire ? readSettings(target) : null;
|
|
231
|
+
const configPath = path.join(target, CONFIG_FILE);
|
|
232
|
+
if (auto && fs.existsSync(configPath) && !safePath(target, CONFIG_FILE)) {
|
|
233
|
+
throw new CliError(`${configPath} is a symlink; refusing to manage it`);
|
|
234
|
+
}
|
|
235
|
+
const config = auto ? planConfig(configPath, options) : null;
|
|
236
|
+
|
|
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)));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const merged = auto ? mergeSettings(settings.data, target, config.complete.compactionThreshold, manifest?.env) : null;
|
|
248
|
+
|
|
249
|
+
fs.mkdirSync(target, { recursive: true });
|
|
250
|
+
const files = { ...manifest?.files };
|
|
251
|
+
|
|
252
|
+
writeManaged(target, desired, files, { force: options.force, log });
|
|
253
|
+
|
|
254
|
+
if (config?.text) writeConfig(configPath, config.text, files, { invalid: config.invalid, log });
|
|
255
|
+
|
|
256
|
+
const record = () => writeManifest(target, { version: 1, modules, files, ...(merged && { env: merged.env }) });
|
|
257
|
+
// Wiring: put the prior env value on record before settings.json changes.
|
|
258
|
+
if (merged) record();
|
|
259
|
+
|
|
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
|
+
}
|
|
269
|
+
|
|
270
|
+
// Stale files go after settings.json, so hooks never point at deleted scripts.
|
|
271
|
+
const owned = new Set(moduleFiles(modules));
|
|
272
|
+
const stale = Object.entries(files).filter(([relative]) => !owned.has(relative));
|
|
273
|
+
const kept = removeManaged(target, stale, log);
|
|
274
|
+
for (const [relative] of stale) if (!(relative in kept)) delete files[relative];
|
|
275
|
+
record();
|
|
276
|
+
log(`done: ${modules} installed in ${target}`);
|
|
277
|
+
if (auto) log('Restart T3 Code (and any running Claude Code session) so hooks and settings load.');
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function uninstall(target, log = console.log) {
|
|
281
|
+
const manifest = readManifest(target);
|
|
282
|
+
const settingsExists = fs.existsSync(path.join(target, 'settings.json'));
|
|
283
|
+
const touchesSettings = manifest ? manifest.env !== undefined || wantsAuto(manifest.modules) : settingsExists;
|
|
284
|
+
const settings = touchesSettings ? readSettings(target) : null;
|
|
285
|
+
|
|
286
|
+
// Unwire before deleting, so a failure never leaves hooks pointing at missing files.
|
|
287
|
+
if (settings && (manifest || taggedHooks(settings.data).length)) {
|
|
288
|
+
if (writeSettings(settings, unmergeSettings(settings.data, manifest?.env))) log('updated: settings.json');
|
|
289
|
+
}
|
|
290
|
+
if (!manifest) {
|
|
291
|
+
log(`nothing to uninstall: no ${MANIFEST_FILE} in ${target}`);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
removeManaged(target, Object.entries(manifest.files), log);
|
|
295
|
+
fs.rmSync(path.join(target, MANIFEST_FILE));
|
|
296
|
+
log(`done: uninstalled from ${target}`);
|
|
297
|
+
}
|
package/lib/manifest.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { isObject, readJson } from '../hooks/_shared.mjs';
|
|
5
|
+
import { CliError } from './paths.mjs';
|
|
6
|
+
|
|
7
|
+
export const MANIFEST_FILE = 't3-auto-build.manifest.json';
|
|
8
|
+
export const MODULES = ['full', 'auto-build', 'core'];
|
|
9
|
+
|
|
10
|
+
export const hashOf = (content) => createHash('sha256').update(content).digest('hex');
|
|
11
|
+
export const fileHash = (file) => hashOf(fs.readFileSync(file));
|
|
12
|
+
|
|
13
|
+
/** The manifest is untrusted input: validate its shape here and every path with safePath(). */
|
|
14
|
+
export function readManifest(target) {
|
|
15
|
+
const file = path.join(target, MANIFEST_FILE);
|
|
16
|
+
if (!fs.existsSync(file)) return null;
|
|
17
|
+
let data;
|
|
18
|
+
try {
|
|
19
|
+
data = readJson(file);
|
|
20
|
+
} catch {
|
|
21
|
+
data = null;
|
|
22
|
+
}
|
|
23
|
+
const valid =
|
|
24
|
+
isObject(data) &&
|
|
25
|
+
MODULES.includes(data.modules) &&
|
|
26
|
+
isObject(data.files) &&
|
|
27
|
+
Object.values(data.files).every((hash) => typeof hash === 'string') &&
|
|
28
|
+
(data.env === undefined || (isObject(data.env) && typeof data.env.installed === 'string'));
|
|
29
|
+
if (!valid) throw new CliError(`${file} is not a valid manifest; fix or remove it`);
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function writeManifest(target, manifest) {
|
|
34
|
+
const files = Object.fromEntries(Object.entries(manifest.files).sort(([a], [b]) => (a < b ? -1 : 1)));
|
|
35
|
+
const text = `${JSON.stringify({ ...manifest, files }, null, 2)}\n`;
|
|
36
|
+
const file = path.join(target, MANIFEST_FILE);
|
|
37
|
+
if (!fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== text) fs.writeFileSync(file, text);
|
|
38
|
+
}
|
package/lib/paths.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
export const PACKAGE_ROOT = fileURLToPath(new URL('..', import.meta.url));
|
|
7
|
+
|
|
8
|
+
export class CliError extends Error {
|
|
9
|
+
constructor(message, exitCode = 1) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.exitCode = exitCode;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** --target > CLAUDE_CONFIG_DIR > <home>/.claude */
|
|
16
|
+
export function resolveTarget(flag, env = process.env) {
|
|
17
|
+
return path.resolve(flag || env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Absolute path for a target-relative file, or null when it could leave the target: absolute,
|
|
22
|
+
* "..", drive or stream syntax, or any symlink/junction on the way down.
|
|
23
|
+
*/
|
|
24
|
+
export function safePath(target, relative) {
|
|
25
|
+
if (typeof relative !== 'string' || relative.includes(':') || relative.includes('\0')) return null;
|
|
26
|
+
if (path.posix.isAbsolute(relative) || path.win32.isAbsolute(relative)) return null;
|
|
27
|
+
const parts = relative.split(/[\\/]/);
|
|
28
|
+
// Empty, ".", "..", and Windows look-alikes such as ".. " are all rejected.
|
|
29
|
+
if (parts.some((part) => /^[. ]*$/.test(part))) return null;
|
|
30
|
+
let current = target;
|
|
31
|
+
for (const part of parts) {
|
|
32
|
+
current = path.join(current, part);
|
|
33
|
+
try {
|
|
34
|
+
if (fs.lstatSync(current).isSymbolicLink()) return null;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error.code !== 'ENOENT') return null;
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return path.join(target, ...parts);
|
|
41
|
+
}
|