architecture-harness 0.23.1 → 0.25.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/package.json +3 -1
- package/src/cli/budget-guard.mjs +1 -0
- package/src/cli/budget-guard.test.mjs +7 -1
- package/src/cli/budget.mjs +3 -4
- package/src/cli/budget.test.mjs +5 -5
- package/src/cli/ci-template.test.mjs +17 -27
- package/src/cli/cli.test.mjs +22 -2
- package/src/cli/commit-msg.mjs +7 -10
- package/src/cli/commit-msg.test.mjs +10 -7
- package/src/cli/generated-file-guard.mjs +1 -1
- package/src/cli/generated-file-guard.test.mjs +4 -2
- package/src/cli/init.mjs +70 -25
- package/src/cli/lint-changed.mjs +157 -0
- package/src/cli/lint-changed.test.mjs +102 -0
- package/src/cli/plugin-agents.test.mjs +1 -1
- package/src/cli/post-edit-gate.test.mjs +3 -1
- package/src/cli/qc.mjs +23 -3
- package/src/cli/scaffold.mjs +23 -2
- package/src/cli/scaffold.test.mjs +51 -0
- package/src/cli/stop-gate.test.mjs +32 -128
- package/src/cli/typecheck.mjs +46 -0
- package/src/cli/typecheck.test.mjs +43 -0
- package/src/cli/user-config-package.mjs +16 -0
- package/src/cli/user-config-toml.mjs +144 -0
- package/src/cli/user-config.mjs +155 -0
- package/src/cli/user-config.test.mjs +274 -0
- package/src/cli/worktree-gate.mjs +11 -12
- package/src/cli/worktree-gate.test.mjs +28 -29
- package/src/cli/worktree-isolation.mjs +3 -3
- package/src/cli/worktree-isolation.test.mjs +1 -1
- package/src/cli/worktree.mjs +9 -1
- package/src/cli/worktree.test.mjs +16 -1
- package/src/config.mjs +13 -11
- package/src/eslint/preset.mjs +8 -3
- package/src/eslint/preset.test.mjs +15 -8
- package/src/vale-style.test.mjs +5 -5
- package/templates/CLAUDE.md +2 -2
- package/templates/githooks/pre-commit +7 -10
- package/templates/github/workflows/ci.yml +22 -89
- package/templates/github/workflows/pr-policy.yml +36 -0
- package/user-config/claude/settings.shared.json +74 -0
- package/user-config/claude/statusline.js +323 -0
- package/user-config/codex/config.shared.toml +19 -0
- package/src/cli/edit-batch-guard.mjs +0 -77
- package/src/cli/edit-batch-guard.test.mjs +0 -131
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// A fragment that edits shared TOML assignments without rewriting other text.
|
|
2
|
+
|
|
3
|
+
export const CODEX_KEYS = Object.freeze([
|
|
4
|
+
"approval_policy", "default_permissions", "model", "model_reasoning_effort",
|
|
5
|
+
"model_auto_compact_token_limit", "model_post_turn_compact_threshold_percent", "service_tier",
|
|
6
|
+
]);
|
|
7
|
+
|
|
8
|
+
function unquote(value) {
|
|
9
|
+
if (value.startsWith('"')) return JSON.parse(value);
|
|
10
|
+
if (value.startsWith("'")) return value.slice(1, -1);
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function scanValue(text, start) {
|
|
15
|
+
let quote = "";
|
|
16
|
+
let depth = 0;
|
|
17
|
+
for (let i = start; i < text.length; i += 1) {
|
|
18
|
+
const char = text[i];
|
|
19
|
+
if (quote) {
|
|
20
|
+
if (quote.includes('"') && char === "\\") { i += 1; continue; }
|
|
21
|
+
if (text.startsWith(quote, i)) { i += quote.length - 1; quote = ""; }
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (char === '"' || char === "'") {
|
|
25
|
+
quote = text.startsWith(char.repeat(3), i) ? char.repeat(3) : char;
|
|
26
|
+
i += quote.length - 1;
|
|
27
|
+
} else if (char === "[" || char === "{") depth += 1;
|
|
28
|
+
else if (char === "]" || char === "}") depth -= 1;
|
|
29
|
+
else if (char === "#") {
|
|
30
|
+
if (depth === 0) return { end: i, next: text.indexOf("\n", i) < 0 ? text.length : text.indexOf("\n", i) + 1 };
|
|
31
|
+
const newline = text.indexOf("\n", i);
|
|
32
|
+
if (newline < 0) break;
|
|
33
|
+
i = newline - 1;
|
|
34
|
+
} else if (char === "\n" && depth === 0) return { end: i, next: i + 1 };
|
|
35
|
+
}
|
|
36
|
+
if (quote || depth !== 0) throw new Error("Unterminated TOML value");
|
|
37
|
+
return { end: text.length, next: text.length };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function documentOf(text) {
|
|
41
|
+
const sections = [{ name: "", start: 0, end: text.length, fields: new Map() }];
|
|
42
|
+
let section = sections[0];
|
|
43
|
+
let offset = 0;
|
|
44
|
+
while (offset < text.length) {
|
|
45
|
+
const newline = text.indexOf("\n", offset);
|
|
46
|
+
const next = newline < 0 ? text.length : newline + 1;
|
|
47
|
+
const line = text.slice(offset, next).trimEnd();
|
|
48
|
+
const header = /^\s*(\[\[?.*?\]\]?)\s*(?:#.*)?$/.exec(line);
|
|
49
|
+
if (header) {
|
|
50
|
+
section.end = offset;
|
|
51
|
+
const named = /^\[\s*(plugins|marketplaces)\s*\.\s*("(?:[^"\\]|\\.)*"|'[^']*'|[\w-]+)\s*\]$/.exec(header[1]);
|
|
52
|
+
section = { name: header[1], kind: named?.[1], plugin: named && unquote(named[2]), start: offset, end: text.length, fields: new Map() };
|
|
53
|
+
sections.push(section);
|
|
54
|
+
} else {
|
|
55
|
+
const assignment = /^\s*("(?:[^"\\]|\\.)*"|'[^']*'|[\w-]+)((?:\s*\.\s*(?:"(?:[^"\\]|\\.)*"|'[^']*'|[\w-]+))*)\s*=\s*/.exec(line);
|
|
56
|
+
if (assignment) {
|
|
57
|
+
const key = assignment[2] ? `${assignment[1]}${assignment[2]}` : unquote(assignment[1]);
|
|
58
|
+
const start = offset + assignment[0].length;
|
|
59
|
+
const value = scanValue(text, start);
|
|
60
|
+
const raw = text.slice(start, value.end).trimEnd();
|
|
61
|
+
if (section.fields.has(key)) throw new Error(`Duplicate TOML key: ${key}`);
|
|
62
|
+
section.fields.set(key, { start, end: start + raw.length, raw });
|
|
63
|
+
offset = value.next;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
offset = next;
|
|
68
|
+
}
|
|
69
|
+
return sections;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function sharedFields(text) {
|
|
73
|
+
const sections = documentOf(text);
|
|
74
|
+
const top = new Map([...sections[0].fields].filter(([key]) => CODEX_KEYS.includes(key)));
|
|
75
|
+
const local = new Set(sections.filter((s) => s.kind === "marketplaces" && (
|
|
76
|
+
s.fields.get("source_type")?.raw.match(/^["']local["']$/)
|
|
77
|
+
|| s.fields.get("source")?.raw.match(/^["'](?:[A-Za-z]:|[\\/~.])/)
|
|
78
|
+
)).map((s) => s.plugin));
|
|
79
|
+
const plugins = sections.filter((s) => s.kind === "plugins" && !local.has(s.plugin.split("@").at(-1)))
|
|
80
|
+
.map((s) => ({ ...s, fields: new Map([...s.fields].filter(([key]) => key === "enabled")) }))
|
|
81
|
+
.filter((s) => s.fields.size);
|
|
82
|
+
for (const [key, field] of top) {
|
|
83
|
+
if (!/^(?:"(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*'|\d+)$/.test(field.raw)) {
|
|
84
|
+
throw new Error(`Expected a scalar shared TOML value: ${key}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
for (const plugin of plugins) {
|
|
88
|
+
if (!/^(true|false)$/.test(plugin.fields.get("enabled").raw)) throw new Error(`Expected a plugin boolean: ${plugin.plugin}`);
|
|
89
|
+
}
|
|
90
|
+
return { top, plugins };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function captureCodexConfig(text) {
|
|
94
|
+
const { top, plugins } = sharedFields(text);
|
|
95
|
+
const rows = [...top].map(([key, value]) => `${key} = ${value.raw}`);
|
|
96
|
+
for (const plugin of plugins) rows.push("", `[plugins.${JSON.stringify(plugin.plugin)}]`, `enabled = ${plugin.fields.get("enabled").raw}`);
|
|
97
|
+
return rows.length ? `${rows.join("\n")}\n` : "";
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function mergeCodexConfig(local, shared) {
|
|
101
|
+
const sections = documentOf(local);
|
|
102
|
+
if (sections[0].fields.get("plugins")?.raw.startsWith("{")) {
|
|
103
|
+
throw new Error('Inline TOML plugins tables are unsupported; use [plugins."name"] tables.');
|
|
104
|
+
}
|
|
105
|
+
const desired = sharedFields(shared);
|
|
106
|
+
const edits = [];
|
|
107
|
+
const additions = new Map();
|
|
108
|
+
const newTables = [];
|
|
109
|
+
const changed = [];
|
|
110
|
+
const eol = local.includes("\r\n") ? "\r\n" : "\n";
|
|
111
|
+
function add(section, line) {
|
|
112
|
+
additions.set(section, [...(additions.get(section) ?? []), line]);
|
|
113
|
+
}
|
|
114
|
+
function merge(section, fields, label) {
|
|
115
|
+
for (const [key, value] of fields) {
|
|
116
|
+
const previous = section.fields.get(key);
|
|
117
|
+
if (previous && unquote(previous.raw) === unquote(value.raw)) continue;
|
|
118
|
+
changed.push(`${label}${key}`);
|
|
119
|
+
if (previous) edits.push({ start: previous.start, end: previous.end, text: value.raw });
|
|
120
|
+
else add(section, `${key} = ${value.raw}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
merge(sections[0], desired.top, "");
|
|
124
|
+
for (const plugin of desired.plugins) {
|
|
125
|
+
const matches = sections.filter((s) => s.kind === "plugins" && s.plugin === plugin.plugin);
|
|
126
|
+
if (matches.length > 1) throw new Error(`Duplicate plugin table: ${plugin.plugin}`);
|
|
127
|
+
if (matches.length) merge(matches[0], plugin.fields, `plugins.${plugin.plugin}.`);
|
|
128
|
+
else {
|
|
129
|
+
const section = { fields: new Map() };
|
|
130
|
+
newTables.push(section);
|
|
131
|
+
add(section, `[plugins.${JSON.stringify(plugin.plugin)}]`);
|
|
132
|
+
merge(section, plugin.fields, `plugins.${plugin.plugin}.`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
for (const section of sections) {
|
|
136
|
+
const lines = additions.get(section);
|
|
137
|
+
if (lines) edits.push({ start: section.end, end: section.end,
|
|
138
|
+
text: `${section.end && local[section.end - 1] !== "\n" ? eol : ""}${lines.join(eol)}${eol}` });
|
|
139
|
+
}
|
|
140
|
+
let text = local;
|
|
141
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
142
|
+
for (const section of newTables) text += `${text && !text.endsWith("\n") ? eol : ""}${eol}${additions.get(section).join(eol)}${eol}`;
|
|
143
|
+
return { text, changed };
|
|
144
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// A pipeline that synchronizes the kit's shared user settings.
|
|
2
|
+
|
|
3
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { constants } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
import { isDeepStrictEqual } from "node:util";
|
|
10
|
+
import { captureCodexConfig, mergeCodexConfig } from "./user-config-toml.mjs";
|
|
11
|
+
|
|
12
|
+
export { captureCodexConfig, mergeCodexConfig } from "./user-config-toml.mjs";
|
|
13
|
+
|
|
14
|
+
export const CLAUDE_KEYS = Object.freeze([
|
|
15
|
+
"cleanupPeriodDays", "syncClaudeAiPlugins", "env", "permissions", "model", "skillOverrides",
|
|
16
|
+
"statusLine", "enabledPlugins", "extraKnownMarketplaces", "effortLevel", "modelSettings",
|
|
17
|
+
"awaySummaryEnabled", "autoUpdatesChannel", "tui", "skipWorkflowUsageWarning", "theme",
|
|
18
|
+
"autoCompactEnabled", "autoContinueAtUsageLimit", "agentPushNotifEnabled", "skipAutoPermissionPrompt",
|
|
19
|
+
]);
|
|
20
|
+
const ENV_KEYS = ["CLAUDE_CODE_DISABLE_MOUSE", "CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP"];
|
|
21
|
+
const MAP_KEYS = ["enabledPlugins", "extraKnownMarketplaces", "env"];
|
|
22
|
+
const STATUS_COMMAND = 'node "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/statusline.js"';
|
|
23
|
+
const USAGE = "qc user-config apply|check|capture [--dry-run] [--kit-dir <path>] [--claude-dir <path>] [--codex-dir <path>]";
|
|
24
|
+
|
|
25
|
+
export function assertSafePath(file) {
|
|
26
|
+
const name = file.replaceAll("\\", "/").split("/").at(-1).toLowerCase();
|
|
27
|
+
if ([".claude.json", ".credentials.json", "auth.json"].includes(name) || /token|secret|credential|auth/i.test(name)) {
|
|
28
|
+
throw new Error(`Refusing credential file: ${file}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function safeFile(file) {
|
|
33
|
+
assertSafePath(file);
|
|
34
|
+
if (existsSync(file)) {
|
|
35
|
+
assertSafePath(realpathSync(file));
|
|
36
|
+
if (!statSync(file).isFile()) throw new Error(`Expected a regular file: ${file}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function configPaths(home = os.homedir(), env = process.env) {
|
|
41
|
+
const paths = /^[A-Za-z]:[\\/]|^\\\\/.test(home) ? path.win32 : path.posix;
|
|
42
|
+
const claudeDir = env.CLAUDE_CONFIG_DIR || paths.join(home, ".claude");
|
|
43
|
+
const codexDir = env.CODEX_HOME || paths.join(home, ".codex");
|
|
44
|
+
return { claude: paths.join(claudeDir, "settings.json"), statusline: paths.join(claudeDir, "statusline.js"), codex: paths.join(codexDir, "config.toml") };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function objectOf(text) {
|
|
48
|
+
const value = JSON.parse(text);
|
|
49
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a JSON settings object");
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sharedClaude(text) {
|
|
54
|
+
const source = objectOf(text);
|
|
55
|
+
const shared = Object.fromEntries(CLAUDE_KEYS.filter((key) => Object.hasOwn(source, key)).map((key) => [key, source[key]]));
|
|
56
|
+
if (shared.env) shared.env = Object.fromEntries(ENV_KEYS.filter((key) => Object.hasOwn(shared.env, key)).map((key) => [key, shared.env[key]]));
|
|
57
|
+
if (shared.permissions) shared.permissions = Object.fromEntries(["defaultMode"].filter((key) => Object.hasOwn(shared.permissions, key)).map((key) => [key, shared.permissions[key]]));
|
|
58
|
+
if (shared.statusLine) shared.statusLine = { type: "command", command: STATUS_COMMAND };
|
|
59
|
+
const local = new Set(["skills-dir"]);
|
|
60
|
+
if (shared.extraKnownMarketplaces) {
|
|
61
|
+
shared.extraKnownMarketplaces = Object.fromEntries(Object.entries(shared.extraKnownMarketplaces).filter(([name, entry]) => {
|
|
62
|
+
const remote = ["github", "git"].includes(entry?.source?.source);
|
|
63
|
+
if (!remote) local.add(name);
|
|
64
|
+
return remote;
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
if (shared.enabledPlugins) shared.enabledPlugins = Object.fromEntries(Object.entries(shared.enabledPlugins).filter(([name]) => !local.has(name.split("@").at(-1))));
|
|
68
|
+
return shared;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function mergeClaudeSettings(local, shared) {
|
|
72
|
+
const target = objectOf(local);
|
|
73
|
+
const source = sharedClaude(shared);
|
|
74
|
+
const changed = [];
|
|
75
|
+
for (const [key, value] of Object.entries(source)) {
|
|
76
|
+
if ([...MAP_KEYS, "permissions"].includes(key)) {
|
|
77
|
+
const before = target[key] ?? {};
|
|
78
|
+
const merged = { ...before };
|
|
79
|
+
for (const [name, entry] of Object.entries(value)) {
|
|
80
|
+
if (!isDeepStrictEqual(before[name], entry)) { changed.push(`${key}.${name}`); Object.defineProperty(merged, name, { value: entry, enumerable: true, writable: true, configurable: true }); }
|
|
81
|
+
}
|
|
82
|
+
target[key] = merged;
|
|
83
|
+
} else if (!isDeepStrictEqual(target[key], value)) { changed.push(key); target[key] = value; }
|
|
84
|
+
}
|
|
85
|
+
return { text: changed.length ? `${JSON.stringify(target, null, 2)}\n` : local, changed };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function kitUserConfigDir(moduleUrl = import.meta.url) {
|
|
89
|
+
const packageDir = fileURLToPath(new URL("../../user-config/", moduleUrl));
|
|
90
|
+
const checkoutDir = fileURLToPath(new URL("../../../../user-config/", moduleUrl));
|
|
91
|
+
const plugin = fileURLToPath(new URL("../../../../.claude-plugin/plugin.json", moduleUrl));
|
|
92
|
+
return existsSync(plugin) && existsSync(checkoutDir) ? checkoutDir : packageDir;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function readOptional(file, fallback) {
|
|
96
|
+
try { return readFileSync(file, "utf8"); } catch (error) {
|
|
97
|
+
if (error.code === "ENOENT") return fallback;
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function stamp(now) {
|
|
103
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
104
|
+
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function backupFile(file, now) {
|
|
108
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
109
|
+
if (existsSync(file)) copyFileSync(file, `${file}.bak-${stamp(now)}`, constants.COPYFILE_EXCL);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function runUserConfig(args, options = {}) {
|
|
113
|
+
const log = options.log ?? console.log;
|
|
114
|
+
try {
|
|
115
|
+
for (const arg of args) assertSafePath(arg);
|
|
116
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
|
|
117
|
+
"dry-run": { type: "boolean" }, "kit-dir": { type: "string" }, "claude-dir": { type: "string" }, "codex-dir": { type: "string" },
|
|
118
|
+
} });
|
|
119
|
+
const [verb] = positionals;
|
|
120
|
+
if (positionals.length !== 1 || !["apply", "check", "capture"].includes(verb)) throw new Error(USAGE);
|
|
121
|
+
const env = { ...(options.env ?? process.env) };
|
|
122
|
+
if (values["claude-dir"]) env.CLAUDE_CONFIG_DIR = values["claude-dir"];
|
|
123
|
+
if (values["codex-dir"]) env.CODEX_HOME = values["codex-dir"];
|
|
124
|
+
const paths = configPaths(options.home ?? os.homedir(), env);
|
|
125
|
+
const kit = values["kit-dir"] ?? options.kitDir ?? kitUserConfigDir();
|
|
126
|
+
const files = [
|
|
127
|
+
{ machine: paths.claude, kit: path.join(kit, "claude/settings.shared.json"), fallback: "{}", merge: mergeClaudeSettings, capture: (text) => `${JSON.stringify(sharedClaude(text), null, 2)}\n` },
|
|
128
|
+
{ machine: paths.codex, kit: path.join(kit, "codex/config.shared.toml"), fallback: "", merge: mergeCodexConfig, capture: captureCodexConfig },
|
|
129
|
+
{ machine: paths.statusline, kit: path.join(kit, "claude/statusline.js"), fallback: "", merge: (local, shared) => ({ text: shared, changed: local === shared ? [] : ["statusline.js"] }), capture: (text) => text },
|
|
130
|
+
];
|
|
131
|
+
for (const file of files) { safeFile(file.machine); safeFile(file.kit); }
|
|
132
|
+
const plans = files.map((file) => {
|
|
133
|
+
const target = verb === "capture" ? file.kit : file.machine;
|
|
134
|
+
const local = readOptional(target, file.fallback);
|
|
135
|
+
const source = readFileSync(verb === "capture" ? file.machine : file.kit, "utf8");
|
|
136
|
+
const result = verb === "capture" ? { text: file.capture(source), changed: [path.basename(file.kit)] } : file.merge(local, source);
|
|
137
|
+
return { target, ...result, changed: result.text === local ? [] : result.changed };
|
|
138
|
+
});
|
|
139
|
+
for (const plan of plans) {
|
|
140
|
+
for (const key of plan.changed) log(`${values["dry-run"] ? "Would change" : verb === "check" ? "Drift" : "Change"} ${plan.target}: ${key}`);
|
|
141
|
+
}
|
|
142
|
+
if (verb !== "check" && !values["dry-run"]) {
|
|
143
|
+
const changes = plans.filter((plan) => plan.changed.length);
|
|
144
|
+
const now = options.now ?? new Date();
|
|
145
|
+
for (const plan of changes) backupFile(plan.target, now);
|
|
146
|
+
for (const plan of changes) writeFileSync(plan.target, plan.text, { mode: 0o600 });
|
|
147
|
+
}
|
|
148
|
+
const drift = plans.some((plan) => plan.changed.length);
|
|
149
|
+
if (!drift) log("Shared user configuration matches.");
|
|
150
|
+
return verb === "check" && drift ? 1 : 0;
|
|
151
|
+
} catch (error) {
|
|
152
|
+
(options.log ?? console.error)(`qc user-config: ${error.message}`);
|
|
153
|
+
return 2;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, readdirSync, rmSync, symlinkSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
|
+
import vm from "node:vm";
|
|
9
|
+
import { packageUserConfig } from "./user-config-package.mjs";
|
|
10
|
+
import { mergeClaudeSettings, mergeCodexConfig, captureCodexConfig, configPaths, assertSafePath, kitUserConfigDir, runUserConfig } from "./user-config.mjs";
|
|
11
|
+
|
|
12
|
+
function fixture(t) {
|
|
13
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-user-config-"));
|
|
14
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
15
|
+
const kitDir = path.join(root, "kit");
|
|
16
|
+
for (const dir of ["claude", "codex"]) mkdirSync(path.join(kitDir, dir), { recursive: true });
|
|
17
|
+
writeFileSync(path.join(kitDir, "claude/settings.shared.json"), '{"model":"opus","enabledPlugins":{"kit@remote":true}}\n');
|
|
18
|
+
writeFileSync(path.join(kitDir, "claude/statusline.js"), "console.log('status');\n");
|
|
19
|
+
writeFileSync(path.join(kitDir, "codex/config.shared.toml"), 'model = "shared"\n[plugins."kit@remote"]\nenabled = true\n');
|
|
20
|
+
const lines = [];
|
|
21
|
+
return { root, kitDir, home: path.join(root, "home"), env: {}, log: (line) => lines.push(line), lines, now: new Date(2026, 0, 2, 3, 4, 5) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
test("JSON merges listed plugin and marketplace keys, preserving local keys and omitted shared keys", () => {
|
|
25
|
+
const local = { model: "old", effortLevel: "high", local: 7, enabledPlugins: { local: true, kit: false }, extraKnownMarketplaces: { local: {} } };
|
|
26
|
+
const shared = { model: "opus", local: 9, enabledPlugins: { kit: true }, extraKnownMarketplaces: { remote: { source: { source: "github", repo: "a/b" } } } };
|
|
27
|
+
const result = mergeClaudeSettings(JSON.stringify(local), JSON.stringify(shared));
|
|
28
|
+
assert.deepEqual(JSON.parse(result.text), { ...local, model: "opus", enabledPlugins: { local: true, kit: true }, extraKnownMarketplaces: { ...local.extraKnownMarketplaces, ...shared.extraKnownMarketplaces } });
|
|
29
|
+
assert.deepEqual(result.changed, ["model", "enabledPlugins.kit", "extraKnownMarketplaces.remote"]);
|
|
30
|
+
assert.deepEqual(mergeClaudeSettings(result.text, JSON.stringify(shared)).changed, []);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("TOML merges top-level keys and plugin fields while preserving comments and unrelated lines", () => {
|
|
34
|
+
const local = '# keep\r\nmodel = "old" # model comment\r\nnotify = ["local"]\r\n\r\n[desktop]\r\nmodel = "desktop"\r\n[plugins."kit@remote"] # plugin comment\r\nenabled = false # enabled comment\r\nlocal = 42\r\n[plugins."local@private"]\r\nenabled = true\r\n';
|
|
35
|
+
const shared = 'model = "new"\nservice_tier = "default"\nnotify = ["wrong"]\n[desktop]\nmodel = "wrong"\n[plugins."kit@remote"]\nenabled = true\n[plugins."new@remote"]\nenabled = false\n';
|
|
36
|
+
const result = mergeCodexConfig(local, shared);
|
|
37
|
+
assert.ok(result.text.includes('model = "new" # model comment\r\n'));
|
|
38
|
+
assert.ok(result.text.includes('notify = ["local"]\r\n'));
|
|
39
|
+
assert.ok(result.text.includes('[desktop]\r\nmodel = "desktop"\r\n'));
|
|
40
|
+
assert.ok(result.text.includes('[plugins."kit@remote"] # plugin comment\r\nenabled = true # enabled comment\r\nlocal = 42'));
|
|
41
|
+
assert.ok(result.text.includes('[plugins."local@private"]\r\nenabled = true'));
|
|
42
|
+
assert.ok(result.text.includes('service_tier = "default"\r\n'));
|
|
43
|
+
assert.ok(result.text.includes('[plugins."new@remote"]\r\nenabled = false'));
|
|
44
|
+
assert.deepEqual(mergeCodexConfig(result.text, shared).changed, []);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("TOML preserves multiline local values and ignores fake headers inside strings", () => {
|
|
48
|
+
const local = 'notify = [\n "keep",\n]\nmodel = "old"\n[desktop]\ntext = """\n[plugins."fake@local"]\nenabled = false\n"""\n';
|
|
49
|
+
const result = mergeCodexConfig(local, 'model = "new"\n');
|
|
50
|
+
assert.equal(result.text, local.replace('model = "old"', 'model = "new"'));
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("TOML consumes multiline values of bare and quoted dotted keys", () => {
|
|
54
|
+
for (const key of ["x.y", '"x" . \'y\'', '\'x\' . "y" . z']) {
|
|
55
|
+
for (const quote of ['"""', "'''"]) {
|
|
56
|
+
const local = `${key} = ${quote}\nmodel = "inner"\n[plugins."fake@r"]\nenabled = false\n${quote}\n`;
|
|
57
|
+
assert.equal(mergeCodexConfig(local, 'model = "new"\n').text, `${local}model = "new"\n`);
|
|
58
|
+
assert.equal(captureCodexConfig(local), "");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("TOML handles a final value without a newline and compares string values", () => {
|
|
64
|
+
assert.equal(mergeCodexConfig('model = "old"', 'model = "new"').text, 'model = "new"');
|
|
65
|
+
const local = "model = 'same' # keep quotes\n";
|
|
66
|
+
assert.equal(mergeCodexConfig(local, 'model = "same"\n').text, local);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("a shared plugin field keeps local fields and adds the missing enabled field", () => {
|
|
70
|
+
const local = '[plugins."kit@remote"]\nlocal = true';
|
|
71
|
+
const merged = mergeCodexConfig(local, '[plugins."kit@remote"]\nenabled = true\n');
|
|
72
|
+
assert.equal(merged.text, `${local}\nenabled = true\n`);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("TOML fills existing plugin sections before appending new tables", () => {
|
|
76
|
+
const shared = '[plugins."A@r"]\nenabled = true\n[plugins."B@r"]\nenabled = true\n';
|
|
77
|
+
for (const eol of ["\n", "\r\n"]) {
|
|
78
|
+
for (const suffix of ["", eol]) {
|
|
79
|
+
const local = `# keep${eol}[plugins."B@r"]${suffix}`;
|
|
80
|
+
const expected = '# keep\n[plugins."B@r"]\nenabled = true\n\n[plugins."A@r"]\nenabled = true\n'.replaceAll("\n", eol);
|
|
81
|
+
assert.equal(mergeCodexConfig(local, shared).text, expected);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("TOML refuses inline plugin tables before adding a plugin section", () => {
|
|
87
|
+
for (const key of ["plugins", '"plugins"', "'plugins'"]) {
|
|
88
|
+
const local = `${key} = { "A@r" = { enabled = false } }\n`;
|
|
89
|
+
assert.throws(() => mergeCodexConfig(local, '[plugins."A@r"]\nenabled = true\n'), /inline.*plugins.*table/i);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("malformed shared configuration fails before any target changes", async (t) => {
|
|
94
|
+
const f = fixture(t);
|
|
95
|
+
writeFileSync(path.join(f.kitDir, "codex/config.shared.toml"), 'model = "unterminated');
|
|
96
|
+
assert.equal(await runUserConfig(["apply"], f), 2);
|
|
97
|
+
assert.deepEqual(readdirSync(f.root), ["kit"]);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("backup collisions fail without overwriting the backup or original file", async (t) => {
|
|
101
|
+
const f = fixture(t);
|
|
102
|
+
const paths = configPaths(f.home, f.env);
|
|
103
|
+
mkdirSync(path.dirname(paths.claude), { recursive: true });
|
|
104
|
+
writeFileSync(paths.claude, '{"model":"local"}');
|
|
105
|
+
const backup = `${paths.claude}.bak-20260102-030405`;
|
|
106
|
+
writeFileSync(backup, "keep backup");
|
|
107
|
+
assert.equal(await runUserConfig(["apply"], f), 2);
|
|
108
|
+
assert.equal(readFileSync(backup, "utf8"), "keep backup");
|
|
109
|
+
assert.equal(readFileSync(paths.claude, "utf8"), '{"model":"local"}');
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("a later backup collision stops all target writes", async (t) => {
|
|
113
|
+
const f = fixture(t);
|
|
114
|
+
const paths = configPaths(f.home, f.env);
|
|
115
|
+
mkdirSync(path.dirname(paths.claude), { recursive: true });
|
|
116
|
+
mkdirSync(path.dirname(paths.codex), { recursive: true });
|
|
117
|
+
const originals = new Map([
|
|
118
|
+
[paths.claude, '{"model":"local"}\n'],
|
|
119
|
+
[paths.codex, 'model = "local"\n'],
|
|
120
|
+
[paths.statusline, "local status\n"],
|
|
121
|
+
]);
|
|
122
|
+
for (const [file, text] of originals) writeFileSync(file, text);
|
|
123
|
+
const backup = `${paths.codex}.bak-20260102-030405`;
|
|
124
|
+
writeFileSync(backup, "keep backup");
|
|
125
|
+
assert.equal(await runUserConfig(["apply"], f), 2);
|
|
126
|
+
assert.match(f.lines.at(-1), /EEXIST/);
|
|
127
|
+
for (const [file, text] of originals) assert.equal(readFileSync(file, "utf8"), text);
|
|
128
|
+
assert.equal(readFileSync(backup, "utf8"), "keep backup");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("capture excludes local marketplaces, their plugins, notify, and desktop settings", () => {
|
|
132
|
+
const source = 'model = "shared"\nnotify = ["private"]\n[marketplaces.local]\nsource_type = "local"\nsource = "C:/private"\n[marketplaces.remote]\nsource_type = "git"\nsource = "https://example.com/kit.git"\n[plugins."keep@remote"]\nenabled = true\n[plugins."skip@local"]\nenabled = true\n[desktop]\nsecret = "private"\n';
|
|
133
|
+
assert.equal(captureCodexConfig(source), 'model = "shared"\n\n[plugins."keep@remote"]\nenabled = true\n');
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test("apply backs up changed files, lists keys, and leaves matching files untouched", async (t) => {
|
|
137
|
+
const f = fixture(t);
|
|
138
|
+
const paths = configPaths(f.home, f.env);
|
|
139
|
+
mkdirSync(path.dirname(paths.claude), { recursive: true });
|
|
140
|
+
writeFileSync(paths.claude, '{"model":"local","outside":true}\n');
|
|
141
|
+
assert.equal(await runUserConfig(["apply"], f), 0);
|
|
142
|
+
assert.equal(readFileSync(`${paths.claude}.bak-20260102-030405`, "utf8"), '{"model":"local","outside":true}\n');
|
|
143
|
+
assert.equal(JSON.parse(readFileSync(paths.claude)).outside, true);
|
|
144
|
+
assert.ok(f.lines.some((line) => line.includes("model")));
|
|
145
|
+
const before = readdirSync(path.dirname(paths.claude));
|
|
146
|
+
assert.equal(await runUserConfig(["apply"], f), 0);
|
|
147
|
+
assert.deepEqual(readdirSync(path.dirname(paths.claude)), before);
|
|
148
|
+
assert.equal(await runUserConfig(["check"], f), 0);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("check returns one for drift and dry-run changes no files", async (t) => {
|
|
152
|
+
const f = fixture(t);
|
|
153
|
+
assert.equal(await runUserConfig(["check"], f), 1);
|
|
154
|
+
assert.equal(await runUserConfig(["apply", "--dry-run"], f), 0);
|
|
155
|
+
assert.deepEqual(readdirSync(f.root).sort(), ["kit"]);
|
|
156
|
+
assert.ok(f.lines.some((line) => line.includes("statusline.js")));
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("capture writes shared data only and supports dry-run", async (t) => {
|
|
160
|
+
const f = fixture(t);
|
|
161
|
+
const paths = configPaths(f.home, f.env);
|
|
162
|
+
mkdirSync(path.dirname(paths.claude), { recursive: true });
|
|
163
|
+
mkdirSync(path.dirname(paths.codex), { recursive: true });
|
|
164
|
+
writeFileSync(paths.claude, '{"model":"local","outside":"private","env":{"TOKEN":"private","CLAUDE_CODE_DISABLE_MOUSE":"1"}}');
|
|
165
|
+
writeFileSync(paths.codex, 'model = "local"\nnotify = ["private"]\n');
|
|
166
|
+
writeFileSync(paths.statusline, "status source\n");
|
|
167
|
+
assert.equal(await runUserConfig(["capture", "--dry-run"], f), 0);
|
|
168
|
+
assert.equal(JSON.parse(readFileSync(path.join(f.kitDir, "claude/settings.shared.json"))).model, "opus");
|
|
169
|
+
assert.equal(await runUserConfig(["capture"], f), 0);
|
|
170
|
+
const captured = JSON.parse(readFileSync(path.join(f.kitDir, "claude/settings.shared.json")));
|
|
171
|
+
assert.deepEqual(captured, { model: "local", env: { CLAUDE_CODE_DISABLE_MOUSE: "1" } });
|
|
172
|
+
assert.equal(readFileSync(path.join(f.kitDir, "claude/statusline.js"), "utf8"), "status source\n");
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
for (const filename of [".claude.json", ".credentials.json", "auth.json", "api-token.json", "service-secret.toml", "my-credential.txt", "oauth-cache.json"]) {
|
|
176
|
+
test(`refuses credential filename ${filename} on Windows and POSIX paths`, async (t) => {
|
|
177
|
+
const f = fixture(t);
|
|
178
|
+
for (const name of [`/home/a/${filename}`, `C:\\Users\\a\\${filename.toUpperCase()}`]) {
|
|
179
|
+
assert.throws(() => assertSafePath(name), /credential/i);
|
|
180
|
+
for (const verb of ["apply", "capture"]) {
|
|
181
|
+
f.lines.length = 0;
|
|
182
|
+
assert.equal(await runUserConfig([verb, "--dry-run", "--codex-dir", name], f), 2);
|
|
183
|
+
assert.match(f.lines.at(-1), /Refusing credential file:/);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
assert.deepEqual(readdirSync(f.root), ["kit"]);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
test("refuses credential symlinks before changing another file", async (t) => {
|
|
191
|
+
const f = fixture(t);
|
|
192
|
+
const paths = configPaths(f.home, f.env);
|
|
193
|
+
mkdirSync(path.dirname(paths.codex), { recursive: true });
|
|
194
|
+
const secret = path.join(f.root, "auth.json");
|
|
195
|
+
writeFileSync(secret, "credential sentinel");
|
|
196
|
+
try { symlinkSync(secret, paths.codex); } catch (error) {
|
|
197
|
+
if (error.code === "EPERM") return t.skip("Windows requires symlink privileges");
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
assert.equal(await runUserConfig(["apply"], f), 2);
|
|
201
|
+
assert.deepEqual(readdirSync(f.home), [".codex"]);
|
|
202
|
+
assert.equal(readFileSync(secret, "utf8"), "credential sentinel");
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
test("home paths use the host path style and respect config environment overrides", () => {
|
|
206
|
+
assert.equal(configPaths("/home/person", {}).claude, "/home/person/.claude/settings.json");
|
|
207
|
+
assert.equal(configPaths("C:\\Users\\person", {}).codex, "C:\\Users\\person\\.codex\\config.toml");
|
|
208
|
+
assert.equal(configPaths("/home/person", { CLAUDE_CONFIG_DIR: "/config/claude", CODEX_HOME: "/config/codex" }).statusline, "/config/claude/statusline.js");
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test("CLI dispatch runs outside a repository and returns usage errors", () => {
|
|
212
|
+
const cli = fileURLToPath(new URL("./qc.mjs", import.meta.url));
|
|
213
|
+
const result = spawnSync(process.execPath, [cli, "user-config", "invalid"], { cwd: os.tmpdir(), encoding: "utf8" });
|
|
214
|
+
assert.equal(result.status, 2);
|
|
215
|
+
assert.match(result.stderr, /user-config/);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("CLI check returns drift, matching, and error exit codes", (t) => {
|
|
219
|
+
const f = fixture(t);
|
|
220
|
+
const paths = configPaths(f.home, f.env);
|
|
221
|
+
const cli = fileURLToPath(new URL("./qc.mjs", import.meta.url));
|
|
222
|
+
const args = [cli, "user-config", "check", "--kit-dir", f.kitDir, "--claude-dir", path.dirname(paths.claude), "--codex-dir", path.dirname(paths.codex)];
|
|
223
|
+
const run = () => spawnSync(process.execPath, args, { cwd: os.tmpdir(), encoding: "utf8" });
|
|
224
|
+
assert.equal(run().status, 1);
|
|
225
|
+
mkdirSync(path.dirname(paths.claude), { recursive: true });
|
|
226
|
+
mkdirSync(path.dirname(paths.codex), { recursive: true });
|
|
227
|
+
writeFileSync(paths.claude, readFileSync(path.join(f.kitDir, "claude/settings.shared.json")));
|
|
228
|
+
writeFileSync(paths.codex, readFileSync(path.join(f.kitDir, "codex/config.shared.toml")));
|
|
229
|
+
writeFileSync(paths.statusline, readFileSync(path.join(f.kitDir, "claude/statusline.js")));
|
|
230
|
+
assert.equal(run().status, 0);
|
|
231
|
+
writeFileSync(paths.claude, "invalid JSON");
|
|
232
|
+
assert.equal(run().status, 2);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test("package staging includes all three shared files and resolves them outside the checkout", async (t) => {
|
|
236
|
+
const f = fixture(t);
|
|
237
|
+
const target = path.join(f.root, "node_modules/architecture-harness/user-config");
|
|
238
|
+
packageUserConfig(f.kitDir, target);
|
|
239
|
+
assert.equal(readFileSync(path.join(target, "claude/statusline.js"), "utf8"), "console.log('status');\n");
|
|
240
|
+
assert.equal(readFileSync(path.join(target, "codex/config.shared.toml"), "utf8"), readFileSync(path.join(f.kitDir, "codex/config.shared.toml"), "utf8"));
|
|
241
|
+
assert.equal(readFileSync(path.join(target, "claude/settings.shared.json"), "utf8"), readFileSync(path.join(f.kitDir, "claude/settings.shared.json"), "utf8"));
|
|
242
|
+
mkdirSync(path.join(f.root, "user-config"));
|
|
243
|
+
const moduleUrl = pathToFileURL(path.join(f.root, "node_modules/architecture-harness/src/cli/user-config.mjs"));
|
|
244
|
+
assert.equal(kitUserConfigDir(moduleUrl), `${target}${path.sep}`);
|
|
245
|
+
mkdirSync(path.join(f.root, ".claude-plugin"));
|
|
246
|
+
writeFileSync(path.join(f.root, ".claude-plugin/plugin.json"), "{}");
|
|
247
|
+
assert.equal(kitUserConfigDir(moduleUrl), `${path.join(f.root, "user-config")}${path.sep}`);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
for (const home of ["/home/person", "C:\\Users\\person"]) {
|
|
251
|
+
test(`seeded status line keeps its three rows with home ${home}`, () => {
|
|
252
|
+
const source = readFileSync(new URL("../../../../user-config/claude/statusline.js", import.meta.url), "utf8");
|
|
253
|
+
let input;
|
|
254
|
+
let output = "";
|
|
255
|
+
const fakeFs = { readFileSync: () => { throw new Error("No cache or account"); }, readdirSync: () => [], writeFileSync: () => {} };
|
|
256
|
+
const fakeProcess = {
|
|
257
|
+
env: { CLAUDE_CONFIG_DIR: `${home}/custom-claude` }, cwd: () => `${home}/project`,
|
|
258
|
+
stdin: { on: (event, fn) => { if (event === "data") input = fn; return { on: (_event, end) => { input(JSON.stringify({ model: { display_name: "Test model" }, context_window: { used_percentage: 20, context_window_size: 1000000 }, rate_limits: { five_hour: { used_percentage: 10, resets_at: 9999999999 }, seven_day: { used_percentage: 20, resets_at: 9999999999 } } })); end(); } }; } },
|
|
259
|
+
stdout: { write: (value) => { output += value; } },
|
|
260
|
+
};
|
|
261
|
+
vm.runInNewContext(source, { process: fakeProcess, Buffer, require: (name) => {
|
|
262
|
+
if (name === "fs" || name === "node:fs") return fakeFs;
|
|
263
|
+
if (name === "os" || name === "node:os") return { homedir: () => home };
|
|
264
|
+
if (name === "path" || name === "node:path") return home.startsWith("C:") ? path.win32 : path.posix;
|
|
265
|
+
if (name === "child_process" || name === "node:child_process") return { execFileSync: () => { throw new Error("No repository"); } };
|
|
266
|
+
throw new Error(`Unexpected module ${name}`);
|
|
267
|
+
} });
|
|
268
|
+
assert.equal(output.split("\n").length, 3);
|
|
269
|
+
assert.match(output, /~\/project/);
|
|
270
|
+
assert.match(output, /Test model/);
|
|
271
|
+
assert.match(output, /custom-claude/);
|
|
272
|
+
assert.match(output, /weekly 20%/);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The Stop trigger of QC-015:
|
|
3
|
-
// head. It
|
|
2
|
+
// The Stop trigger of QC-015: it names the worktree, local branch, or remote branch that a PR this session merged
|
|
3
|
+
// leaves on its head. It advises and never blocks, since a developer can keep a merged branch on purpose. It reads
|
|
4
|
+
// the merge records of the ledger, and runs git only for a merge of this session.
|
|
4
5
|
|
|
5
6
|
import { spawnSync } from "node:child_process";
|
|
6
7
|
import { createHash } from "node:crypto";
|
|
@@ -52,7 +53,7 @@ function cleanupOf(merge, { main, folder }) {
|
|
|
52
53
|
const memoryOf = (tmp, session) => path.join(tmp, "qc-worktree-gate", `${fileSafe(session)}.last`);
|
|
53
54
|
const hashOf = (text) => createHash("sha256").update(text).digest("hex");
|
|
54
55
|
|
|
55
|
-
function
|
|
56
|
+
function lastNote(file) {
|
|
56
57
|
try {
|
|
57
58
|
return readFileSync(file, "utf8");
|
|
58
59
|
} catch {
|
|
@@ -60,7 +61,7 @@ function lastBlock(file) {
|
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
/** The
|
|
64
|
+
/** The note on one Stop. @returns the hook output, or null to let the turn end with no message. */
|
|
64
65
|
export function decide(call, { tmp = os.tmpdir(), projectDir = process.env.CLAUDE_PROJECT_DIR } = {}) {
|
|
65
66
|
if (call.hook_event_name !== "Stop") return null;
|
|
66
67
|
const rule = worktreeRuleAt(call.cwd ?? process.cwd()) ?? (projectDir ? worktreeRuleAt(projectDir) : null);
|
|
@@ -81,21 +82,19 @@ export function decide(call, { tmp = os.tmpdir(), projectDir = process.env.CLAUD
|
|
|
81
82
|
rmSync(memory, { force: true });
|
|
82
83
|
return null;
|
|
83
84
|
}
|
|
84
|
-
const
|
|
85
|
+
const message = [
|
|
85
86
|
`Worktree check: a PR this session merged leaves its worktree or its branch. From the main checkout (${rule.main}), run:`,
|
|
86
87
|
...lines,
|
|
87
88
|
].join("\n");
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
if (call.stop_hook_active === true && lastBlock(memory) === hashOf(reason)) return note;
|
|
89
|
+
// The note names one set of leftovers once, so a branch kept on purpose costs one line.
|
|
90
|
+
if (lastNote(memory) === hashOf(message)) return null;
|
|
91
91
|
try {
|
|
92
92
|
mkdirSync(path.dirname(memory), { recursive: true });
|
|
93
|
-
writeFileSync(memory, hashOf(
|
|
93
|
+
writeFileSync(memory, hashOf(message));
|
|
94
94
|
} catch {
|
|
95
|
-
// With no memory,
|
|
96
|
-
if (call.stop_hook_active === true) return note;
|
|
95
|
+
// With no memory, the note repeats at each stop.
|
|
97
96
|
}
|
|
98
|
-
return {
|
|
97
|
+
return { systemMessage: message };
|
|
99
98
|
}
|
|
100
99
|
|
|
101
100
|
async function readStdin() {
|