@yasaswy.nagavolu/agents 0.26.1 → 0.26.2
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/README.md +8 -1
- package/bin/cli.js +102 -36
- package/content/global/hooks/lib/modeDrift.js +152 -0
- package/content/global/hooks/lib/projectHooks.js +429 -0
- package/content/global/hooks/permission_mode_enforce.js +35 -0
- package/content/global/hooks/project_hook_repair.js +25 -0
- package/content/manifest.json +74 -0
- package/lib/modeDrift.js +15 -0
- package/lib/projectHooks.js +9 -278
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -87,7 +87,14 @@ agents-cli install
|
|
|
87
87
|
`settings.local.json` whose script file is missing or that are bare `python <repo>/.claude/hooks/x.py`
|
|
88
88
|
commands (they exit 2 and block a PreToolUse call when the file goes missing). `--fix` rewrites the
|
|
89
89
|
bare ones to `sh ~/.claude/hooks/project_hook.sh .claude/hooks/x.py [args]` (fail-open launcher);
|
|
90
|
-
`--scan-root <dir>` checks every git repo directly under `<dir>` instead of the cwd repo.
|
|
90
|
+
`--scan-root <dir>` checks every git repo directly under `<dir>` instead of the cwd repo. `install` and `update`
|
|
91
|
+
accept the same `--scan-root` plus `--fix-project-hooks` and report (or fix) bare project hooks after the run.
|
|
92
|
+
Paste-ready fix from inside any repo: `npx -y @yasaswy.nagavolu/agents@latest doctor --fix`.
|
|
93
|
+
It also flags a project `permissions.defaultMode` weaker than the global default in `~/.claude/settings.json`
|
|
94
|
+
(for example `dontAsk` under a global `bypassPermissions`); `--fix` removes it from `settings.local.json`
|
|
95
|
+
only, a committed `settings.json` is reported and never edited. The `permission_mode_enforce.js` hook
|
|
96
|
+
(harness-hygiene) does the same repair at SessionStart/UserPromptSubmit and auto-allows permission prompts
|
|
97
|
+
while the global default is `bypassPermissions`.
|
|
91
98
|
- `agents-cli --help` — show usage
|
|
92
99
|
|
|
93
100
|
### The interactive menu
|
package/bin/cli.js
CHANGED
|
@@ -34,6 +34,7 @@ const { envPath, readSecrets, removeSecret } = require('../lib/secretsStore');
|
|
|
34
34
|
const { runSelfProfilePostInstall } = require('../lib/selfProfile');
|
|
35
35
|
const { checkHealth, DoctorError } = require('../lib/doctor');
|
|
36
36
|
const projectHooks = require('../lib/projectHooks');
|
|
37
|
+
const modeDrift = require('../lib/modeDrift');
|
|
37
38
|
const { checkModVersions } = require('../lib/claudeVersion');
|
|
38
39
|
|
|
39
40
|
const PACKAGE_ROOT = path.join(__dirname, '..');
|
|
@@ -62,6 +63,11 @@ Usage:
|
|
|
62
63
|
agents-cli uninstall --bundle <key> --yes Remove a bundle's installed files and settings.json wiring
|
|
63
64
|
agents-cli update --yes Update every installed bundle to the current source
|
|
64
65
|
agents-cli update --bundle <key> --yes Update one installed bundle
|
|
66
|
+
install | update [--scan-root <dir>] [--fix-project-hooks]
|
|
67
|
+
After the run, report bare project hooks of the cwd repo (or every git repo
|
|
68
|
+
under <dir>); --fix-project-hooks rewrites them to the fail-open launcher.
|
|
69
|
+
Also reports a project defaultMode weaker than the global one; with
|
|
70
|
+
--fix-project-hooks it is removed from settings.local.json
|
|
65
71
|
agents-cli secrets Prompt for any missing secrets across all installed bundles
|
|
66
72
|
agents-cli secrets --bundle <key> Prompt for missing secrets for one bundle
|
|
67
73
|
agents-cli secrets --list Show which secrets are set/missing (names only — never values)
|
|
@@ -164,6 +170,11 @@ whose script file is missing, and a bare (non-launcher) project hook command, wh
|
|
|
164
170
|
and so blocks every tool call when it is a PreToolUse hook. A launcher-form hook with a missing file fails open but is still
|
|
165
171
|
reported. Without --fix nothing is modified.
|
|
166
172
|
|
|
173
|
+
doctor also flags a project .claude/settings.json or settings.local.json whose permissions.defaultMode is weaker
|
|
174
|
+
than the global default in <target>/settings.json (for example "dontAsk" under a global "bypassPermissions"), which
|
|
175
|
+
silently downgrades every session in that repo. --fix removes the key from settings.local.json only; a committed
|
|
176
|
+
settings.json is reported, never edited.
|
|
177
|
+
|
|
167
178
|
doctor reports, without changing anything: orphans (files/directories sitting inside
|
|
168
179
|
a path this CLI manages that the ledger does not claim — e.g. a stale file left behind
|
|
169
180
|
by a renamed/retired item), missing (a ledger-tracked file no longer on disk), and
|
|
@@ -1097,10 +1108,80 @@ function describeHookFinding(f) {
|
|
|
1097
1108
|
const where = `${f.file} [${f.event || '-'}]`;
|
|
1098
1109
|
if (f.kind === 'unparseable') return `${f.file}: not valid JSON, hooks not checked`;
|
|
1099
1110
|
if (f.kind === 'bare-project-hook') {
|
|
1100
|
-
return `${where} bare project hook, exits 2
|
|
1111
|
+
return `${where} bare project hook, exits 2 if its file goes missing (${projectHooks.failureEffect(f.event)})${f.fixable ? ' (fixable)' : ' (not auto-fixable)'}: ${f.command}`;
|
|
1101
1112
|
}
|
|
1102
1113
|
if (f.kind === 'missing-launcher') return `${where} launcher not found: ${f.script}`;
|
|
1103
|
-
return `${where} script missing${f.failsOpen ? ' (launcher: fails open, hook does not run)' :
|
|
1114
|
+
return `${where} script missing${f.failsOpen ? ' (launcher: fails open, hook does not run)' : ` (FAILS CLOSED: ${projectHooks.failureEffect(f.event)})`}: ${f.script}`;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function printProjectHookReport(step, { fixRequested }) {
|
|
1118
|
+
if (step.fixed.length > 0) {
|
|
1119
|
+
console.log(`
|
|
1120
|
+
Rewrote ${step.fixed.length} bare project hook command(s) to the fail-open launcher:`);
|
|
1121
|
+
for (const c of step.fixed) console.log(` ${c.file}
|
|
1122
|
+
- ${c.from}
|
|
1123
|
+
+ ${c.to}`);
|
|
1124
|
+
}
|
|
1125
|
+
if (step.findings.length === 0) return;
|
|
1126
|
+
console.log(`
|
|
1127
|
+
Project hooks (${step.findings.length} finding(s), ${step.repos.length} repo(s) checked):`);
|
|
1128
|
+
for (const f of step.findings) console.log(` ${describeHookFinding(f)}`);
|
|
1129
|
+
if (!fixRequested && step.findings.some((f) => f.kind === 'bare-project-hook' && f.fixable)) {
|
|
1130
|
+
console.log(` Fix: ${projectHooks.FIX_COMMAND}`);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
function printModeDriftReport(modes) {
|
|
1135
|
+
if (modes.fixed.length > 0) {
|
|
1136
|
+
console.log(`\nRemoved ${modes.fixed.length} defaultMode override(s) weaker than the global "${modes.globalMode}":`);
|
|
1137
|
+
for (const f of modes.fixed) console.log(` ${f.file} (was "${f.mode}"); a live session needs ctrl+x m once`);
|
|
1138
|
+
}
|
|
1139
|
+
if (modes.findings.length === 0) return;
|
|
1140
|
+
console.log(`\nPermission mode drift (${modes.findings.length} finding(s), ${modes.repos.length} repo(s) checked):`);
|
|
1141
|
+
for (const f of modes.findings) console.log(` ${modeDrift.describeModeFinding(f)}`);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
function splitProjectHookFlags(argv) {
|
|
1145
|
+
const rest = [];
|
|
1146
|
+
const opts = { scanRoot: null, fix: false, targetDir: null };
|
|
1147
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
1148
|
+
const arg = argv[i];
|
|
1149
|
+
if (arg === '--fix-project-hooks') opts.fix = true;
|
|
1150
|
+
else if (arg === '--scan-root' && argv[i + 1]) {
|
|
1151
|
+
opts.scanRoot = argv[i + 1];
|
|
1152
|
+
i += 1;
|
|
1153
|
+
} else {
|
|
1154
|
+
if (arg === '--target-dir') opts.targetDir = argv[i + 1] || null;
|
|
1155
|
+
rest.push(arg);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
return { rest, opts };
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
async function withProjectHookStep(argv, run) {
|
|
1162
|
+
const { rest, opts } = splitProjectHookFlags(argv);
|
|
1163
|
+
const code = await run(rest);
|
|
1164
|
+
try {
|
|
1165
|
+
const step = projectHooks.projectHooksStep({
|
|
1166
|
+
cwd: process.cwd(),
|
|
1167
|
+
scanRoot: opts.scanRoot ? path.resolve(opts.scanRoot) : null,
|
|
1168
|
+
fix: opts.fix,
|
|
1169
|
+
targetBase: opts.targetDir || defaultTargetBase(),
|
|
1170
|
+
});
|
|
1171
|
+
if (step.error) console.error(step.error);
|
|
1172
|
+
printProjectHookReport(step, { fixRequested: opts.fix });
|
|
1173
|
+
printModeDriftReport(
|
|
1174
|
+
modeDrift.checkModeDrift({
|
|
1175
|
+
targetBase: opts.targetDir || defaultTargetBase(),
|
|
1176
|
+
cwd: process.cwd(),
|
|
1177
|
+
scanRoot: opts.scanRoot ? path.resolve(opts.scanRoot) : null,
|
|
1178
|
+
fix: opts.fix,
|
|
1179
|
+
})
|
|
1180
|
+
);
|
|
1181
|
+
} catch (err) {
|
|
1182
|
+
console.error(`project hook scan skipped: ${err.message}`);
|
|
1183
|
+
}
|
|
1184
|
+
return code;
|
|
1104
1185
|
}
|
|
1105
1186
|
|
|
1106
1187
|
function runDoctor(argv) {
|
|
@@ -1118,46 +1199,29 @@ function runDoctor(argv) {
|
|
|
1118
1199
|
targetBase: args.targetDir,
|
|
1119
1200
|
});
|
|
1120
1201
|
|
|
1121
|
-
const
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
return 1;
|
|
1132
|
-
}
|
|
1133
|
-
const launcherCommand = projectHooks.launcherCommandFor(targetBase);
|
|
1134
|
-
for (const repo of hooks.repos) fixed.push(...projectHooks.fixRepo(repo, { launcherCommand }));
|
|
1135
|
-
hooks = projectHooks.checkProjectHooks(hookScope);
|
|
1202
|
+
const scope = {
|
|
1203
|
+
cwd: process.cwd(),
|
|
1204
|
+
scanRoot: args.scanRoot ? path.resolve(args.scanRoot) : null,
|
|
1205
|
+
targetBase: args.targetDir || defaultTargetBase(),
|
|
1206
|
+
};
|
|
1207
|
+
const modes = modeDrift.checkModeDrift({ ...scope, fix: args.fix });
|
|
1208
|
+
const hooks = projectHooks.projectHooksStep({ ...scope, fix: args.fix });
|
|
1209
|
+
if (hooks.error) {
|
|
1210
|
+
console.error(hooks.error);
|
|
1211
|
+
return 1;
|
|
1136
1212
|
}
|
|
1213
|
+
const { fixed } = hooks;
|
|
1137
1214
|
result.projectHooks = { repos: hooks.repos, findings: hooks.findings, fixed };
|
|
1138
|
-
result.
|
|
1215
|
+
result.modeDrift = { globalMode: modes.globalMode, findings: modes.findings, fixed: modes.fixed };
|
|
1216
|
+
result.healthy = result.healthy && hooks.findings.length === 0 && modes.findings.length === 0;
|
|
1139
1217
|
|
|
1140
1218
|
if (args.json) {
|
|
1141
1219
|
console.log(JSON.stringify(result, null, 2));
|
|
1142
1220
|
return result.healthy ? 0 : 1;
|
|
1143
1221
|
}
|
|
1144
1222
|
|
|
1145
|
-
const printProjectHooks = () => {
|
|
1146
|
-
|
|
1147
|
-
console.log(`
|
|
1148
|
-
Rewrote ${fixed.length} bare project hook command(s) to the fail-open launcher:`);
|
|
1149
|
-
for (const c of fixed) console.log(` ${c.file}
|
|
1150
|
-
- ${c.from}
|
|
1151
|
-
+ ${c.to}`);
|
|
1152
|
-
}
|
|
1153
|
-
if (hooks.findings.length === 0) return;
|
|
1154
|
-
console.log(`
|
|
1155
|
-
Project hooks (${hooks.findings.length} finding(s), ${hooks.repos.length} repo(s) checked):`);
|
|
1156
|
-
for (const f of hooks.findings) console.log(` ${describeHookFinding(f)}`);
|
|
1157
|
-
if (hooks.findings.some((f) => f.kind === 'bare-project-hook' && f.fixable) && !args.fix) {
|
|
1158
|
-
console.log(' Run "agents-cli doctor --fix" to rewrite the fixable ones.');
|
|
1159
|
-
}
|
|
1160
|
-
};
|
|
1223
|
+
const printProjectHooks = () => printProjectHookReport(hooks, { fixRequested: args.fix });
|
|
1224
|
+
const printModeDrift = () => printModeDriftReport(modes);
|
|
1161
1225
|
|
|
1162
1226
|
const printModVersions = () => {
|
|
1163
1227
|
if (result.modVersions.length === 0) return;
|
|
@@ -1168,6 +1232,7 @@ Project hooks (${hooks.findings.length} finding(s), ${hooks.repos.length} repo(s
|
|
|
1168
1232
|
if (result.healthy) {
|
|
1169
1233
|
console.log(`${result.targetBase}: healthy — no orphans, no missing files, no drift.`);
|
|
1170
1234
|
printModVersions();
|
|
1235
|
+
printModeDrift();
|
|
1171
1236
|
return 0;
|
|
1172
1237
|
}
|
|
1173
1238
|
|
|
@@ -1186,6 +1251,7 @@ Project hooks (${hooks.findings.length} finding(s), ${hooks.repos.length} repo(s
|
|
|
1186
1251
|
}
|
|
1187
1252
|
printModVersions();
|
|
1188
1253
|
printProjectHooks();
|
|
1254
|
+
printModeDrift();
|
|
1189
1255
|
return 1;
|
|
1190
1256
|
} catch (err) {
|
|
1191
1257
|
if (err instanceof DoctorError || err instanceof ManifestError || err instanceof LedgerError) {
|
|
@@ -1210,7 +1276,7 @@ async function main(argv) {
|
|
|
1210
1276
|
}
|
|
1211
1277
|
|
|
1212
1278
|
if (command === 'install') {
|
|
1213
|
-
return
|
|
1279
|
+
return withProjectHookStep(rest, runInstall);
|
|
1214
1280
|
}
|
|
1215
1281
|
|
|
1216
1282
|
if (command === 'uninstall') {
|
|
@@ -1222,7 +1288,7 @@ async function main(argv) {
|
|
|
1222
1288
|
}
|
|
1223
1289
|
|
|
1224
1290
|
if (command === 'update') {
|
|
1225
|
-
return
|
|
1291
|
+
return withProjectHookStep(rest, runUpdate);
|
|
1226
1292
|
}
|
|
1227
1293
|
|
|
1228
1294
|
if (command === 'doctor') {
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Core for permission_mode_enforce.js and the CLI (doctor/update/install): a repo's defaultMode must not be weaker than the global one.
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { currentRepo, listGitRepos, readSettingsFile, reserialize, writeAtomic } = require('./projectHooks.js');
|
|
6
|
+
|
|
7
|
+
const MODE_RANK = {
|
|
8
|
+
dontAsk: 0,
|
|
9
|
+
plan: 0,
|
|
10
|
+
default: 1,
|
|
11
|
+
manual: 1,
|
|
12
|
+
acceptEdits: 2,
|
|
13
|
+
auto: 3,
|
|
14
|
+
bypassPermissions: 4,
|
|
15
|
+
};
|
|
16
|
+
const BYPASS = 'bypassPermissions';
|
|
17
|
+
const AUTO_ALLOW_LIVE_MODES = new Set(['default', 'dontAsk', 'acceptEdits']);
|
|
18
|
+
const INTERACTIVE_TOOLS = new Set(['AskUserQuestion', 'ExitPlanMode', 'EnterPlanMode']);
|
|
19
|
+
const LOCAL_FILE = 'settings.local.json';
|
|
20
|
+
const SETTINGS_FILES = [LOCAL_FILE, 'settings.json'];
|
|
21
|
+
|
|
22
|
+
function modeOf(settings) {
|
|
23
|
+
const permissions = settings && typeof settings === 'object' ? settings.permissions : null;
|
|
24
|
+
const mode = permissions && typeof permissions === 'object' ? permissions.defaultMode : null;
|
|
25
|
+
return typeof mode === 'string' ? mode : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isWeaker(projectMode, globalMode) {
|
|
29
|
+
return (
|
|
30
|
+
Object.hasOwn(MODE_RANK, projectMode) &&
|
|
31
|
+
Object.hasOwn(MODE_RANK, globalMode) &&
|
|
32
|
+
MODE_RANK[projectMode] < MODE_RANK[globalMode]
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function globalDefaultMode(targetBase) {
|
|
37
|
+
const loaded = readSettingsFile(path.join(targetBase, 'settings.json'));
|
|
38
|
+
const mode = loaded && loaded.settings ? modeOf(loaded.settings) : null;
|
|
39
|
+
return Object.hasOwn(MODE_RANK, mode) ? mode : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Project settings whose defaultMode is weaker than the global default. */
|
|
43
|
+
function scanRepoModes(repoRoot, globalMode) {
|
|
44
|
+
const findings = [];
|
|
45
|
+
for (const name of SETTINGS_FILES) {
|
|
46
|
+
const file = path.join(repoRoot, '.claude', name);
|
|
47
|
+
const loaded = readSettingsFile(file);
|
|
48
|
+
if (!loaded || !loaded.settings) continue;
|
|
49
|
+
const mode = modeOf(loaded.settings);
|
|
50
|
+
if (!isWeaker(mode, globalMode)) continue;
|
|
51
|
+
findings.push({ repo: repoRoot, file, mode, globalMode, local: name === LOCAL_FILE });
|
|
52
|
+
}
|
|
53
|
+
return findings;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Remove a weaker defaultMode from a repo's settings.local.json; the committed settings.json is never edited. */
|
|
57
|
+
function fixRepoModes(repoRoot, globalMode) {
|
|
58
|
+
const file = path.join(repoRoot, '.claude', LOCAL_FILE);
|
|
59
|
+
const loaded = readSettingsFile(file);
|
|
60
|
+
if (!loaded || !loaded.settings) return [];
|
|
61
|
+
const mode = modeOf(loaded.settings);
|
|
62
|
+
if (!isWeaker(mode, globalMode)) return [];
|
|
63
|
+
delete loaded.settings.permissions.defaultMode;
|
|
64
|
+
if (Object.keys(loaded.settings.permissions).length === 0) delete loaded.settings.permissions;
|
|
65
|
+
writeAtomic(file, reserialize(loaded.settings, loaded.raw));
|
|
66
|
+
return [{ repo: repoRoot, file, mode, globalMode, local: true }];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function resolveRepos({ cwd, scanRoot }) {
|
|
70
|
+
return scanRoot ? listGitRepos(scanRoot) : [currentRepo(cwd || process.cwd())].filter(Boolean);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function checkModeDrift({ targetBase, cwd, scanRoot, fix = false }) {
|
|
74
|
+
const globalMode = globalDefaultMode(targetBase);
|
|
75
|
+
const repos = resolveRepos({ cwd, scanRoot });
|
|
76
|
+
if (!globalMode) return { globalMode: null, repos, findings: [], fixed: [] };
|
|
77
|
+
const fixed = fix ? repos.flatMap((repo) => fixRepoModes(repo, globalMode)) : [];
|
|
78
|
+
const findings = repos.flatMap((repo) => scanRepoModes(repo, globalMode));
|
|
79
|
+
return { globalMode, repos, findings, fixed };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function describeModeFinding(f) {
|
|
83
|
+
return f.local
|
|
84
|
+
? `${f.file} sets defaultMode "${f.mode}", weaker than global "${f.globalMode}" (fix: agents-cli doctor --fix)`
|
|
85
|
+
: `${f.file} is committed and sets defaultMode "${f.mode}", weaker than global "${f.globalMode}" (not auto-edited: remove it or ask the owner)`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** SessionStart/UserPromptSubmit: strip weaker local modes, report committed ones at SessionStart. Returns a hook output or null. */
|
|
89
|
+
function guardSession({ event, roots, targetBase }) {
|
|
90
|
+
const globalMode = globalDefaultMode(targetBase);
|
|
91
|
+
if (!globalMode) return null;
|
|
92
|
+
const lines = [];
|
|
93
|
+
const seen = new Set();
|
|
94
|
+
for (const root of roots.filter(Boolean)) {
|
|
95
|
+
const key = path.resolve(root).toLowerCase();
|
|
96
|
+
if (seen.has(key)) continue;
|
|
97
|
+
seen.add(key);
|
|
98
|
+
for (const f of fixRepoModes(root, globalMode)) {
|
|
99
|
+
lines.push(
|
|
100
|
+
`permission-mode: removed defaultMode '${f.mode}' from ${f.file} (global default is ${globalMode}). ` +
|
|
101
|
+
'Press ctrl+x m once to cycle this live session.'
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
if (event !== 'SessionStart') continue;
|
|
105
|
+
for (const f of scanRepoModes(root, globalMode)) {
|
|
106
|
+
lines.push(
|
|
107
|
+
`permission-mode: committed ${f.file} sets defaultMode '${f.mode}', weaker than global ${globalMode}; ` +
|
|
108
|
+
'not edited, remove it or ask the owner.'
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return lines.length > 0 ? { systemMessage: lines.join('\n') } : null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function autoAllowApplies(payload, targetBase) {
|
|
116
|
+
if (globalDefaultMode(targetBase) !== BYPASS) return false;
|
|
117
|
+
if (INTERACTIVE_TOOLS.has(payload.tool_name)) return false;
|
|
118
|
+
const live = payload.permission_mode;
|
|
119
|
+
return live === undefined || live === null || AUTO_ALLOW_LIVE_MODES.has(live);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** PermissionRequest and PreToolUse: allow so no prompt reaches the user. Returns a hook output or null. */
|
|
123
|
+
function decidePermission(payload, targetBase) {
|
|
124
|
+
const event = payload.hook_event_name;
|
|
125
|
+
if (event === 'PermissionRequest') {
|
|
126
|
+
if (!autoAllowApplies(payload, targetBase)) return null;
|
|
127
|
+
return { hookSpecificOutput: { hookEventName: event, decision: { behavior: 'allow' } } };
|
|
128
|
+
}
|
|
129
|
+
if (event === 'PreToolUse') {
|
|
130
|
+
if (payload.permission_mode !== 'dontAsk' || !autoAllowApplies(payload, targetBase)) return null;
|
|
131
|
+
return {
|
|
132
|
+
hookSpecificOutput: {
|
|
133
|
+
hookEventName: event,
|
|
134
|
+
permissionDecision: 'allow',
|
|
135
|
+
permissionDecisionReason: 'global default is bypassPermissions; session is on dontAsk',
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = {
|
|
143
|
+
MODE_RANK,
|
|
144
|
+
checkModeDrift,
|
|
145
|
+
decidePermission,
|
|
146
|
+
describeModeFinding,
|
|
147
|
+
fixRepoModes,
|
|
148
|
+
globalDefaultMode,
|
|
149
|
+
guardSession,
|
|
150
|
+
isWeaker,
|
|
151
|
+
scanRepoModes,
|
|
152
|
+
};
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { spawnSync } = require('node:child_process');
|
|
7
|
+
|
|
8
|
+
const SETTINGS_FILES = ['settings.json', 'settings.local.json'];
|
|
9
|
+
const LAUNCHER_NAME = 'project_hook.sh';
|
|
10
|
+
const EVENT_EFFECT = {
|
|
11
|
+
PreToolUse: 'tool calls are blocked',
|
|
12
|
+
UserPromptSubmit: 'prompts are blocked',
|
|
13
|
+
Stop: 'the session cannot stop cleanly',
|
|
14
|
+
SubagentStop: 'subagents cannot stop cleanly',
|
|
15
|
+
};
|
|
16
|
+
const FIX_COMMAND = 'npx -y @yasaswy.nagavolu/agents@latest doctor --fix';
|
|
17
|
+
const SCRIPT_EXT = /\.(py|sh|js|mjs|cjs|ps1)$/i;
|
|
18
|
+
const INTERPRETERS = new Set(['python', 'python3', 'py', 'node', 'bash', 'sh', 'pwsh', 'powershell']);
|
|
19
|
+
const PROJECT_HOOK_REL = /^\.claude\/hooks\/[^\s]+\.py$/;
|
|
20
|
+
const PROJECT_DIR_VAR = /^(?:\$\{CLAUDE_PROJECT_DIR\}|\$CLAUDE_PROJECT_DIR|%CLAUDE_PROJECT_DIR%)(?=\/|$)/;
|
|
21
|
+
const HOME_VAR = /^(?:~|\$\{HOME\}|\$HOME|%USERPROFILE%)(?=\/|$)/;
|
|
22
|
+
|
|
23
|
+
function failureEffect(event) {
|
|
24
|
+
return EVENT_EFFECT[event] || 'it prints an error every time it runs, without blocking';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function slashes(p) {
|
|
28
|
+
return p.replace(/\\/g, '/');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function normalizeAbs(p) {
|
|
32
|
+
let out = slashes(p).replace(/^\/([a-zA-Z])\//, (_, d) => `${d.toUpperCase()}:/`);
|
|
33
|
+
out = out.replace(/\/+$/, '');
|
|
34
|
+
return /^[a-zA-Z]:/.test(out) ? `${out[0].toUpperCase()}${out.slice(1)}` : out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isAbs(p) {
|
|
38
|
+
return /^[a-zA-Z]:\//.test(p) || p.startsWith('/');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function sameOrUnder(root, p) {
|
|
42
|
+
const caseless = /^[A-Z]:/.test(root) || process.platform === 'win32';
|
|
43
|
+
const a = caseless ? root.toLowerCase() : root;
|
|
44
|
+
const b = caseless ? p.toLowerCase() : p;
|
|
45
|
+
return b === a || b.startsWith(`${a}/`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Split a command into whitespace-separated tokens; quoted spans stay inside one token, quotes removed from `text`. */
|
|
49
|
+
function tokenize(command) {
|
|
50
|
+
const tokens = [];
|
|
51
|
+
const re = /(?:"[^"]*"|'[^']*'|[^\s"'])+/g;
|
|
52
|
+
let m;
|
|
53
|
+
while ((m = re.exec(command)) !== null) {
|
|
54
|
+
tokens.push({ text: bareToken(m[0]), start: m.index, end: m.index + m[0].length });
|
|
55
|
+
}
|
|
56
|
+
return tokens;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function bareToken(raw) {
|
|
60
|
+
return raw.replace(/["']/g, '');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function expandPath(token, repoRoot, home) {
|
|
64
|
+
let t = slashes(bareToken(token));
|
|
65
|
+
if (PROJECT_DIR_VAR.test(t)) t = t.replace(PROJECT_DIR_VAR, repoRoot);
|
|
66
|
+
else if (HOME_VAR.test(t)) t = t.replace(HOME_VAR, home);
|
|
67
|
+
if (/[$%`]/.test(t)) return null;
|
|
68
|
+
if (!isAbs(t)) t = `${repoRoot}/${t.replace(/^\.\//, '')}`;
|
|
69
|
+
return normalizeAbs(t);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Locate the script a hook command runs. Returns null when the command has no
|
|
74
|
+
* script path this function can resolve (inline code, unknown variables, ...).
|
|
75
|
+
*/
|
|
76
|
+
function parseHookCommand(command, repoRoot, home) {
|
|
77
|
+
const tokens = tokenize(command);
|
|
78
|
+
if (tokens.length === 0) return null;
|
|
79
|
+
const first = path.posix.basename(slashes(tokens[0].text)).replace(/\.exe$/i, '').toLowerCase();
|
|
80
|
+
|
|
81
|
+
if (first === 'sh' && tokens[1] && path.posix.basename(slashes(bareToken(tokens[1].text))) === LAUNCHER_NAME) {
|
|
82
|
+
if (!tokens[2]) return null;
|
|
83
|
+
const launcher = expandPath(tokens[1].text, repoRoot, home);
|
|
84
|
+
const script = expandPath(tokens[2].text, repoRoot, home);
|
|
85
|
+
return script ? { launcher: true, launcherPath: launcher, scriptPath: script, scriptToken: tokens[2] } : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (INTERPRETERS.has(first)) {
|
|
89
|
+
for (let i = 1; i < tokens.length; i += 1) {
|
|
90
|
+
const text = bareToken(tokens[i].text);
|
|
91
|
+
if (text.startsWith('-') && !SCRIPT_EXT.test(text)) continue;
|
|
92
|
+
if (!SCRIPT_EXT.test(text)) return null;
|
|
93
|
+
const script = expandPath(tokens[i].text, repoRoot, home);
|
|
94
|
+
return script ? { launcher: false, interpreter: first, scriptPath: script, scriptToken: tokens[i], tokenIndex: i } : null;
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (SCRIPT_EXT.test(bareToken(tokens[0].text))) {
|
|
100
|
+
const script = expandPath(tokens[0].text, repoRoot, home);
|
|
101
|
+
return script ? { launcher: false, interpreter: null, scriptPath: script, scriptToken: tokens[0], tokenIndex: 0 } : null;
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function repoRelative(repoRoot, scriptPath, aliases = []) {
|
|
107
|
+
for (const root of [repoRoot, ...aliases]) {
|
|
108
|
+
if (sameOrUnder(root, scriptPath) && scriptPath.length > root.length) return scriptPath.slice(root.length + 1);
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The main working tree's root when `repoRoot` is a linked git worktree, else nothing. */
|
|
114
|
+
function mainTreeAliases(repoRoot) {
|
|
115
|
+
const res = spawnSync('git', ['-C', repoRoot, 'rev-parse', '--path-format=absolute', '--git-common-dir'], { encoding: 'utf8' });
|
|
116
|
+
if (res.error || res.status !== 0) return [];
|
|
117
|
+
const common = normalizeAbs(res.stdout.trim());
|
|
118
|
+
const root = normalizeAbs(repoRoot);
|
|
119
|
+
if (!common.endsWith('/.git')) return [];
|
|
120
|
+
const main = common.slice(0, -'/.git'.length);
|
|
121
|
+
return main && main.toLowerCase() !== root.toLowerCase() ? [main] : [];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Rewrite `python|python3|py [-u|-3] <repo>/.claude/hooks/x.py [args]` into the
|
|
126
|
+
* launcher form. Returns null when the command is not a bare project hook this
|
|
127
|
+
* function may rewrite.
|
|
128
|
+
*/
|
|
129
|
+
function toLauncherCommand(command, { repoRoot, home, launcherCommand, aliases = [] }) {
|
|
130
|
+
const parsed = parseHookCommand(command, repoRoot, home);
|
|
131
|
+
if (!parsed || parsed.launcher) return null;
|
|
132
|
+
if (!['python', 'python3', 'py'].includes(parsed.interpreter) || parsed.tokenIndex === undefined) return null;
|
|
133
|
+
const tokens = tokenize(command);
|
|
134
|
+
const flagsOk = tokens.slice(1, parsed.tokenIndex).every((t) => /^-(u|3|B)$/.test(t.text));
|
|
135
|
+
if (!flagsOk) return null;
|
|
136
|
+
const rel = repoRelative(repoRoot, parsed.scriptPath, aliases);
|
|
137
|
+
if (!rel || !PROJECT_HOOK_REL.test(rel) || rel.includes('..')) return null;
|
|
138
|
+
const args = command.slice(parsed.scriptToken.end);
|
|
139
|
+
const relArg = /\s/.test(rel) ? `"${rel}"` : rel;
|
|
140
|
+
return `${launcherCommand} ${relArg}${args}`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function launcherCommandFor(targetBase) {
|
|
144
|
+
const home = normalizeAbs(os.homedir());
|
|
145
|
+
const base = normalizeAbs(targetBase);
|
|
146
|
+
const launcher = base === `${home}/.claude` ? `~/.claude/hooks/${LAUNCHER_NAME}` : `${base}/hooks/${LAUNCHER_NAME}`;
|
|
147
|
+
return `sh ${/\s/.test(launcher) ? `"${launcher}"` : launcher}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function* hookCommands(settings) {
|
|
151
|
+
const hooks = settings && typeof settings === 'object' ? settings.hooks : null;
|
|
152
|
+
if (!hooks || typeof hooks !== 'object') return;
|
|
153
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
154
|
+
if (!Array.isArray(groups)) continue;
|
|
155
|
+
for (const group of groups) {
|
|
156
|
+
if (!group || !Array.isArray(group.hooks)) continue;
|
|
157
|
+
for (const hook of group.hooks) {
|
|
158
|
+
if (hook && typeof hook.command === 'string') yield { event, matcher: group.matcher || null, hook };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function readSettingsFile(file) {
|
|
165
|
+
let raw;
|
|
166
|
+
try {
|
|
167
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
168
|
+
} catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
return { raw, settings: JSON.parse(raw.replace(/^/, '')) };
|
|
173
|
+
} catch {
|
|
174
|
+
return { raw, settings: null };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Findings for one repo: hook commands whose script is missing, and bare project hooks that fail closed. */
|
|
179
|
+
function scanRepo(repoRoot, { home = os.homedir() } = {}) {
|
|
180
|
+
const root = normalizeAbs(repoRoot);
|
|
181
|
+
const homeDir = normalizeAbs(home);
|
|
182
|
+
const aliases = mainTreeAliases(repoRoot);
|
|
183
|
+
const findings = [];
|
|
184
|
+
for (const name of SETTINGS_FILES) {
|
|
185
|
+
const file = path.join(repoRoot, '.claude', name);
|
|
186
|
+
const loaded = readSettingsFile(file);
|
|
187
|
+
if (!loaded) continue;
|
|
188
|
+
if (!loaded.settings) {
|
|
189
|
+
findings.push({ repo: root, file, kind: 'unparseable', command: null });
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
for (const { event, matcher, hook } of hookCommands(loaded.settings)) {
|
|
193
|
+
const parsed = parseHookCommand(hook.command, root, homeDir);
|
|
194
|
+
if (!parsed) continue;
|
|
195
|
+
const base = { repo: root, file, event, matcher, command: hook.command };
|
|
196
|
+
const rel = repoRelative(root, parsed.scriptPath, aliases);
|
|
197
|
+
const projectHook = !parsed.launcher && rel !== null && PROJECT_HOOK_REL.test(rel);
|
|
198
|
+
if (projectHook) {
|
|
199
|
+
const fixable = toLauncherCommand(hook.command, { repoRoot: root, home: homeDir, launcherCommand: 'sh L', aliases }) !== null;
|
|
200
|
+
findings.push({ ...base, kind: 'bare-project-hook', script: parsed.scriptPath, fixable });
|
|
201
|
+
}
|
|
202
|
+
if (!fs.existsSync(parsed.scriptPath)) {
|
|
203
|
+
findings.push({ ...base, kind: 'missing-script', script: parsed.scriptPath, failsOpen: parsed.launcher });
|
|
204
|
+
}
|
|
205
|
+
if (parsed.launcher && parsed.launcherPath && !fs.existsSync(parsed.launcherPath)) {
|
|
206
|
+
findings.push({ ...base, kind: 'missing-launcher', script: parsed.launcherPath });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return findings;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Direct children of `root` that are git repos (a `.git` dir or worktree file). */
|
|
214
|
+
function listGitRepos(root) {
|
|
215
|
+
let entries;
|
|
216
|
+
try {
|
|
217
|
+
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
218
|
+
} catch {
|
|
219
|
+
return [];
|
|
220
|
+
}
|
|
221
|
+
return entries
|
|
222
|
+
.filter((e) => e.isDirectory() && fs.existsSync(path.join(root, e.name, '.git')))
|
|
223
|
+
.map((e) => path.join(root, e.name))
|
|
224
|
+
.sort();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function currentRepo(cwd) {
|
|
228
|
+
const res = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
|
|
229
|
+
if (res.error || res.status !== 0) return null;
|
|
230
|
+
const top = res.stdout.trim();
|
|
231
|
+
return top ? path.resolve(top) : null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function detectFormat(raw) {
|
|
235
|
+
const text = raw.replace(/^/, '');
|
|
236
|
+
const indent = /\n([ \t]+)"/.exec(text);
|
|
237
|
+
return {
|
|
238
|
+
bom: raw.startsWith(''),
|
|
239
|
+
eol: text.includes('\r\n') ? '\r\n' : '\n',
|
|
240
|
+
indent: indent ? indent[1] : 2,
|
|
241
|
+
finalNewline: /\n$/.test(text),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function reserialize(settings, raw) {
|
|
246
|
+
const fmt = detectFormat(raw);
|
|
247
|
+
let out = JSON.stringify(settings, null, fmt.indent);
|
|
248
|
+
if (fmt.eol === '\r\n') out = out.replace(/\n/g, '\r\n');
|
|
249
|
+
if (fmt.finalNewline) out += fmt.eol;
|
|
250
|
+
return (fmt.bom ? '' : '') + out;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Replace only the command string literals in the raw text so every other byte stays; fall back to a format-preserving reserialize. */
|
|
254
|
+
function applyRewrites(raw, settings, rewrites) {
|
|
255
|
+
let text = raw;
|
|
256
|
+
for (const [from, to] of rewrites) {
|
|
257
|
+
text = text.split(JSON.stringify(from)).join(JSON.stringify(to));
|
|
258
|
+
}
|
|
259
|
+
const expected = JSON.stringify(settings);
|
|
260
|
+
let actual;
|
|
261
|
+
try {
|
|
262
|
+
actual = JSON.stringify(JSON.parse(text.replace(/^/, '')));
|
|
263
|
+
} catch {
|
|
264
|
+
actual = null;
|
|
265
|
+
}
|
|
266
|
+
return actual === expected ? text : reserialize(settings, raw);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function writeAtomic(file, text) {
|
|
270
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
271
|
+
try {
|
|
272
|
+
fs.writeFileSync(tmp, text);
|
|
273
|
+
fs.renameSync(tmp, file);
|
|
274
|
+
} catch (err) {
|
|
275
|
+
fs.rmSync(tmp, { force: true });
|
|
276
|
+
throw err;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Rewrite fixable bare project hooks in one repo (only those whose file is missing with `onlyMissing`). Returns the rewrites performed. */
|
|
281
|
+
function fixRepo(repoRoot, { launcherCommand, home = os.homedir(), onlyMissing = false, files = SETTINGS_FILES }) {
|
|
282
|
+
const root = normalizeAbs(repoRoot);
|
|
283
|
+
const homeDir = normalizeAbs(home);
|
|
284
|
+
const aliases = mainTreeAliases(repoRoot);
|
|
285
|
+
const changes = [];
|
|
286
|
+
for (const name of files) {
|
|
287
|
+
const file = path.join(repoRoot, '.claude', name);
|
|
288
|
+
const loaded = readSettingsFile(file);
|
|
289
|
+
if (!loaded || !loaded.settings) continue;
|
|
290
|
+
const rewrites = new Map();
|
|
291
|
+
for (const { hook } of hookCommands(loaded.settings)) {
|
|
292
|
+
const next = toLauncherCommand(hook.command, { repoRoot: root, home: homeDir, launcherCommand, aliases });
|
|
293
|
+
if (next === null) continue;
|
|
294
|
+
const script = parseHookCommand(hook.command, root, homeDir).scriptPath;
|
|
295
|
+
const missing = !fs.existsSync(script);
|
|
296
|
+
if (onlyMissing && !missing) continue;
|
|
297
|
+
rewrites.set(hook.command, next);
|
|
298
|
+
changes.push({ repo: root, file, from: hook.command, to: next, script, missing, rel: repoRelative(root, script, aliases) });
|
|
299
|
+
hook.command = next;
|
|
300
|
+
}
|
|
301
|
+
if (rewrites.size === 0) continue;
|
|
302
|
+
writeAtomic(file, applyRewrites(loaded.raw, loaded.settings, rewrites));
|
|
303
|
+
}
|
|
304
|
+
return changes;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function isTracked(repoRoot, rel) {
|
|
308
|
+
const res = spawnSync('git', ['-C', repoRoot, 'ls-files', '--error-unmatch', '--', rel], { stdio: 'ignore' });
|
|
309
|
+
return !res.error && res.status === 0;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function describeRepaired(change) {
|
|
313
|
+
const rel = change.rel || change.script;
|
|
314
|
+
if (!change.missing) return `${rel} (file present, migrated)`;
|
|
315
|
+
return isTracked(change.repo, rel) ? `${rel} (tracked in git, deleted in the working tree: git restore -- ${rel})` : `${rel} (untracked)`;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function projectRootFor(cwd) {
|
|
319
|
+
let dir = path.resolve(cwd);
|
|
320
|
+
for (;;) {
|
|
321
|
+
if (fs.existsSync(path.join(dir, '.git'))) return dir;
|
|
322
|
+
const parent = path.dirname(dir);
|
|
323
|
+
if (parent === dir) return null;
|
|
324
|
+
dir = parent;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Session-start / prompt-submit guard for one session. Repairs bare project hooks whose file is
|
|
330
|
+
* missing (they exit 2 and block every tool call), warns about the ones it cannot repair, and at
|
|
331
|
+
* session start notes the bare hooks that are present. Returns null when there is nothing to say.
|
|
332
|
+
*/
|
|
333
|
+
function guardSession({ event, roots, targetBase, home = os.homedir() }) {
|
|
334
|
+
const launcherFile = path.join(targetBase, 'hooks', LAUNCHER_NAME);
|
|
335
|
+
const repaired = [];
|
|
336
|
+
const stuck = [];
|
|
337
|
+
let bareCount = 0;
|
|
338
|
+
const seen = new Set();
|
|
339
|
+
for (const root of roots.filter(Boolean)) {
|
|
340
|
+
const key = normalizeAbs(root).toLowerCase();
|
|
341
|
+
if (seen.has(key)) continue;
|
|
342
|
+
seen.add(key);
|
|
343
|
+
let findings = scanRepo(root, { home });
|
|
344
|
+
const closed = findings.filter((f) => f.kind === 'missing-script' && !f.failsOpen);
|
|
345
|
+
if (fs.existsSync(launcherFile)) {
|
|
346
|
+
const launcherCommand = launcherCommandFor(targetBase);
|
|
347
|
+
if (closed.length > 0) repaired.push(...fixRepo(root, { launcherCommand, home, onlyMissing: true }));
|
|
348
|
+
repaired.push(...fixRepo(root, { launcherCommand, home, files: ['settings.local.json'] }));
|
|
349
|
+
if (repaired.length > 0) findings = scanRepo(root, { home });
|
|
350
|
+
}
|
|
351
|
+
stuck.push(...findings.filter((f) => f.kind === 'missing-script' && !f.failsOpen));
|
|
352
|
+
bareCount += findings.filter((f) => f.kind === 'bare-project-hook').length;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const lines = [];
|
|
356
|
+
const model = [];
|
|
357
|
+
if (repaired.length > 0) {
|
|
358
|
+
const files = [...new Set(repaired.map((c) => c.file))].join(', ');
|
|
359
|
+
lines.push(
|
|
360
|
+
`project-hook guard: repaired ${repaired.length} hook command(s) in ${files} that pointed at a missing file ` +
|
|
361
|
+
`[${repaired.map(describeRepaired).join('; ')}]; they now run through ${LAUNCHER_NAME} and skip when the file is missing.`
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
if (stuck.length > 0) {
|
|
365
|
+
const names = [...new Set(stuck.map((f) => f.script))].join(', ');
|
|
366
|
+
const effects = [...new Set(stuck.map((f) => failureEffect(f.event)))].join(' and ');
|
|
367
|
+
const msg =
|
|
368
|
+
`project hook ${names} is missing, so ${effects}. Ask the user to type ` +
|
|
369
|
+
`\`! ${FIX_COMMAND}\` (user shell commands are not blocked by hooks).`;
|
|
370
|
+
lines.push(`project-hook guard: ${msg}`);
|
|
371
|
+
model.push(msg);
|
|
372
|
+
}
|
|
373
|
+
if (repaired.length === 0 && stuck.length === 0 && bareCount > 0 && event === 'SessionStart') {
|
|
374
|
+
lines.push(
|
|
375
|
+
`project-hook guard: ${bareCount} bare project hook command(s) would block every tool call if their file went missing. ` +
|
|
376
|
+
`Fix: ${FIX_COMMAND}`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
if (lines.length === 0) return null;
|
|
380
|
+
const out = { systemMessage: lines.join(' ') };
|
|
381
|
+
const context = [...lines.filter((l) => repaired.length > 0 && l.includes('repaired')), ...model];
|
|
382
|
+
if (context.length > 0) out.hookSpecificOutput = { hookEventName: event, additionalContext: context.join(' ') };
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function checkProjectHooks({ cwd, scanRoot, home }) {
|
|
387
|
+
const repos = scanRoot ? listGitRepos(scanRoot) : [currentRepo(cwd || process.cwd())].filter(Boolean);
|
|
388
|
+
const findings = [];
|
|
389
|
+
for (const repo of repos) findings.push(...scanRepo(repo, { home }));
|
|
390
|
+
return { repos, findings };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Scan (cwd repo or every repo under scanRoot) and optionally rewrite bare project hooks; `error` is set when --fix cannot run. */
|
|
394
|
+
function projectHooksStep({ cwd, scanRoot, fix, targetBase, home }) {
|
|
395
|
+
let { repos, findings } = checkProjectHooks({ cwd, scanRoot, home });
|
|
396
|
+
const fixed = [];
|
|
397
|
+
let error = null;
|
|
398
|
+
if (fix && findings.some((f) => f.kind === 'bare-project-hook' && f.fixable)) {
|
|
399
|
+
const launcherFile = path.join(targetBase, 'hooks', LAUNCHER_NAME);
|
|
400
|
+
if (!fs.existsSync(launcherFile)) {
|
|
401
|
+
error = `Cannot fix: ${launcherFile} is not installed. Run: npx -y @yasaswy.nagavolu/agents@latest install --bundle harness-hygiene --yes`;
|
|
402
|
+
} else {
|
|
403
|
+
const launcherCommand = launcherCommandFor(targetBase);
|
|
404
|
+
for (const repo of repos) fixed.push(...fixRepo(repo, { launcherCommand, home }));
|
|
405
|
+
({ findings } = checkProjectHooks({ cwd, scanRoot, home }));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return { repos, findings, fixed, error };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
module.exports = {
|
|
412
|
+
FIX_COMMAND,
|
|
413
|
+
failureEffect,
|
|
414
|
+
projectHooksStep,
|
|
415
|
+
checkProjectHooks,
|
|
416
|
+
currentRepo,
|
|
417
|
+
guardSession,
|
|
418
|
+
projectRootFor,
|
|
419
|
+
fixRepo,
|
|
420
|
+
launcherCommandFor,
|
|
421
|
+
listGitRepos,
|
|
422
|
+
parseHookCommand,
|
|
423
|
+
readSettingsFile,
|
|
424
|
+
reserialize,
|
|
425
|
+
scanRepo,
|
|
426
|
+
toLauncherCommand,
|
|
427
|
+
writeAtomic,
|
|
428
|
+
LAUNCHER_NAME,
|
|
429
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// With a global bypassPermissions default, no repo setting may downgrade a session and no permission prompt may reach the user; never blocks.
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
function readPayload() {
|
|
8
|
+
try {
|
|
9
|
+
const payload = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
10
|
+
return payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
|
|
11
|
+
} catch {
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
if (!process.env.CLAUDE_HOOK_CHILD) {
|
|
18
|
+
const { projectRootFor } = require('./lib/projectHooks.js');
|
|
19
|
+
const { guardSession, decidePermission } = require('./lib/modeDrift.js');
|
|
20
|
+
const payload = readPayload();
|
|
21
|
+
const targetBase = path.dirname(__dirname);
|
|
22
|
+
const event = payload.hook_event_name;
|
|
23
|
+
let out = null;
|
|
24
|
+
if (event === 'SessionStart' || event === 'UserPromptSubmit') {
|
|
25
|
+
const roots = [process.env.CLAUDE_PROJECT_DIR, typeof payload.cwd === 'string' ? projectRootFor(payload.cwd) : null];
|
|
26
|
+
out = guardSession({ event, roots, targetBase });
|
|
27
|
+
} else {
|
|
28
|
+
out = decidePermission(payload, targetBase);
|
|
29
|
+
}
|
|
30
|
+
if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
|
|
31
|
+
}
|
|
32
|
+
} catch (err) {
|
|
33
|
+
process.stderr.write(`permission_mode_enforce: ${err.message}\n`);
|
|
34
|
+
}
|
|
35
|
+
process.exit(0);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// SessionStart/UserPromptSubmit guard: repairs project hooks that point at a missing file; never blocks.
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
function readPayload() {
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
10
|
+
} catch {
|
|
11
|
+
return {};
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
const { guardSession, projectRootFor } = require('./lib/projectHooks.js');
|
|
17
|
+
const payload = readPayload();
|
|
18
|
+
const event = payload.hook_event_name === 'UserPromptSubmit' ? 'UserPromptSubmit' : 'SessionStart';
|
|
19
|
+
const roots = [process.env.CLAUDE_PROJECT_DIR, typeof payload.cwd === 'string' ? projectRootFor(payload.cwd) : null];
|
|
20
|
+
const out = guardSession({ event, roots, targetBase: path.dirname(__dirname) });
|
|
21
|
+
if (out) process.stdout.write(`${JSON.stringify(out)}\n`);
|
|
22
|
+
} catch (err) {
|
|
23
|
+
process.stderr.write(`project_hook_repair: ${err.message}\n`);
|
|
24
|
+
}
|
|
25
|
+
process.exit(0);
|
package/content/manifest.json
CHANGED
|
@@ -682,6 +682,53 @@
|
|
|
682
682
|
"command": "python ~/.claude/hooks/permission_mode_guard.py"
|
|
683
683
|
}
|
|
684
684
|
},
|
|
685
|
+
{
|
|
686
|
+
"path": "global/hooks/permission_mode_enforce.js",
|
|
687
|
+
"targetPath": "hooks/permission_mode_enforce.js",
|
|
688
|
+
"kind": "hook",
|
|
689
|
+
"note": "Founder rule: when the global defaultMode is bypassPermissions, no repo setting may downgrade a session and no permission prompt may reach the user. SessionStart/UserPromptSubmit strip a weaker defaultMode from the repo's settings.local.json (a committed settings.json is only reported); PermissionRequest and, for live dontAsk sessions, PreToolUse answer allow. Deny rules and other PreToolUse guards still apply first. Needs node.",
|
|
690
|
+
"wiring": {
|
|
691
|
+
"event": "SessionStart",
|
|
692
|
+
"type": "command",
|
|
693
|
+
"command": "node ~/.claude/hooks/permission_mode_enforce.js"
|
|
694
|
+
}
|
|
695
|
+
},
|
|
696
|
+
{
|
|
697
|
+
"path": "global/hooks/permission_mode_enforce.js",
|
|
698
|
+
"targetPath": "hooks/permission_mode_enforce.js",
|
|
699
|
+
"kind": "hook",
|
|
700
|
+
"wiring": {
|
|
701
|
+
"event": "UserPromptSubmit",
|
|
702
|
+
"type": "command",
|
|
703
|
+
"command": "node ~/.claude/hooks/permission_mode_enforce.js"
|
|
704
|
+
}
|
|
705
|
+
},
|
|
706
|
+
{
|
|
707
|
+
"path": "global/hooks/permission_mode_enforce.js",
|
|
708
|
+
"targetPath": "hooks/permission_mode_enforce.js",
|
|
709
|
+
"kind": "hook",
|
|
710
|
+
"wiring": {
|
|
711
|
+
"event": "PermissionRequest",
|
|
712
|
+
"type": "command",
|
|
713
|
+
"command": "node ~/.claude/hooks/permission_mode_enforce.js"
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
{
|
|
717
|
+
"path": "global/hooks/permission_mode_enforce.js",
|
|
718
|
+
"targetPath": "hooks/permission_mode_enforce.js",
|
|
719
|
+
"kind": "hook",
|
|
720
|
+
"wiring": {
|
|
721
|
+
"event": "PreToolUse",
|
|
722
|
+
"type": "command",
|
|
723
|
+
"command": "node ~/.claude/hooks/permission_mode_enforce.js"
|
|
724
|
+
}
|
|
725
|
+
},
|
|
726
|
+
{
|
|
727
|
+
"path": "global/hooks/lib/modeDrift.js",
|
|
728
|
+
"targetPath": "hooks/lib/modeDrift.js",
|
|
729
|
+
"kind": "hook",
|
|
730
|
+
"note": "Shared core required by permission_mode_enforce.js; the CLI (packages/cli/lib/modeDrift.js) re-exports this same file for doctor/update/install, so there is one implementation."
|
|
731
|
+
},
|
|
685
732
|
{
|
|
686
733
|
"path": "global/hooks/cloudshell_guard.py",
|
|
687
734
|
"targetPath": "hooks/cloudshell_guard.py",
|
|
@@ -722,6 +769,33 @@
|
|
|
722
769
|
"kind": "hook",
|
|
723
770
|
"note": "No wiring of its own -- a project's own settings.json calls it directly (e.g. `sh ~/.claude/hooks/project_hook.sh .claude/hooks/<hook>.py`) so a hook still runs after CLAUDE_PROJECT_DIR goes stale (worktree/EnterWorktree moves). See global/hooks/README.md."
|
|
724
771
|
},
|
|
772
|
+
{
|
|
773
|
+
"path": "global/hooks/project_hook_repair.js",
|
|
774
|
+
"targetPath": "hooks/project_hook_repair.js",
|
|
775
|
+
"kind": "hook",
|
|
776
|
+
"note": "Repairs project hooks that would fail closed: a bare `python <repo>/.claude/hooks/x.py` whose file is missing exits 2 and blocks every tool call. On SessionStart and UserPromptSubmit it rewrites those commands to the project_hook.sh launcher and prints one systemMessage; never blocks. Needs node.",
|
|
777
|
+
"wiring": {
|
|
778
|
+
"event": "SessionStart",
|
|
779
|
+
"type": "command",
|
|
780
|
+
"command": "node ~/.claude/hooks/project_hook_repair.js"
|
|
781
|
+
}
|
|
782
|
+
},
|
|
783
|
+
{
|
|
784
|
+
"path": "global/hooks/project_hook_repair.js",
|
|
785
|
+
"targetPath": "hooks/project_hook_repair.js",
|
|
786
|
+
"kind": "hook",
|
|
787
|
+
"wiring": {
|
|
788
|
+
"event": "UserPromptSubmit",
|
|
789
|
+
"type": "command",
|
|
790
|
+
"command": "node ~/.claude/hooks/project_hook_repair.js"
|
|
791
|
+
}
|
|
792
|
+
},
|
|
793
|
+
{
|
|
794
|
+
"path": "global/hooks/lib/projectHooks.js",
|
|
795
|
+
"targetPath": "hooks/lib/projectHooks.js",
|
|
796
|
+
"kind": "hook",
|
|
797
|
+
"note": "Shared scan/rewrite core required by project_hook_repair.js; the CLI (packages/cli/lib/projectHooks.js) re-exports this same file for doctor, so there is one implementation."
|
|
798
|
+
},
|
|
725
799
|
{
|
|
726
800
|
"path": "global/rules/context7.md",
|
|
727
801
|
"targetPath": "rules/context7.md",
|
package/lib/modeDrift.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Single source: global/hooks/lib/modeDrift.js (checkout) or its staged copy under content/ (tarball).
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
const REL = ['global', 'hooks', 'lib', 'modeDrift.js'];
|
|
8
|
+
const candidates = [
|
|
9
|
+
path.join(__dirname, '..', '..', '..', ...REL),
|
|
10
|
+
path.join(__dirname, '..', 'content', ...REL),
|
|
11
|
+
];
|
|
12
|
+
const found = candidates.find((p) => fs.existsSync(p));
|
|
13
|
+
if (!found) throw new Error(`modeDrift core not found; looked in ${candidates.join(', ')}`);
|
|
14
|
+
|
|
15
|
+
module.exports = require(found);
|
package/lib/projectHooks.js
CHANGED
|
@@ -1,284 +1,15 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// Single source: global/hooks/lib/projectHooks.js (checkout) or its staged copy under content/ (tarball).
|
|
3
4
|
const fs = require('node:fs');
|
|
4
|
-
const os = require('node:os');
|
|
5
5
|
const path = require('node:path');
|
|
6
|
-
const { spawnSync } = require('node:child_process');
|
|
7
6
|
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
|
|
7
|
+
const REL = ['global', 'hooks', 'lib', 'projectHooks.js'];
|
|
8
|
+
const candidates = [
|
|
9
|
+
path.join(__dirname, '..', '..', '..', ...REL),
|
|
10
|
+
path.join(__dirname, '..', 'content', ...REL),
|
|
11
|
+
];
|
|
12
|
+
const found = candidates.find((p) => fs.existsSync(p));
|
|
13
|
+
if (!found) throw new Error(`projectHooks core not found; looked in ${candidates.join(', ')}`);
|
|
15
14
|
|
|
16
|
-
|
|
17
|
-
return p.replace(/\\/g, '/');
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function normalizeAbs(p) {
|
|
21
|
-
let out = slashes(p).replace(/^\/([a-zA-Z])\//, (_, d) => `${d.toUpperCase()}:/`);
|
|
22
|
-
out = out.replace(/\/+$/, '');
|
|
23
|
-
return /^[a-zA-Z]:/.test(out) ? `${out[0].toUpperCase()}${out.slice(1)}` : out;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function isAbs(p) {
|
|
27
|
-
return /^[a-zA-Z]:\//.test(p) || p.startsWith('/');
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function sameOrUnder(root, p) {
|
|
31
|
-
const caseless = /^[A-Z]:/.test(root) || process.platform === 'win32';
|
|
32
|
-
const a = caseless ? root.toLowerCase() : root;
|
|
33
|
-
const b = caseless ? p.toLowerCase() : p;
|
|
34
|
-
return b === a || b.startsWith(`${a}/`);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** Split a command into whitespace-separated tokens; quoted spans stay inside one token, quotes removed from `text`. */
|
|
38
|
-
function tokenize(command) {
|
|
39
|
-
const tokens = [];
|
|
40
|
-
const re = /(?:"[^"]*"|'[^']*'|[^\s"'])+/g;
|
|
41
|
-
let m;
|
|
42
|
-
while ((m = re.exec(command)) !== null) {
|
|
43
|
-
tokens.push({ text: bareToken(m[0]), start: m.index, end: m.index + m[0].length });
|
|
44
|
-
}
|
|
45
|
-
return tokens;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function bareToken(raw) {
|
|
49
|
-
return raw.replace(/["']/g, '');
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function expandPath(token, repoRoot, home) {
|
|
53
|
-
let t = slashes(bareToken(token));
|
|
54
|
-
if (PROJECT_DIR_VAR.test(t)) t = t.replace(PROJECT_DIR_VAR, repoRoot);
|
|
55
|
-
else if (HOME_VAR.test(t)) t = t.replace(HOME_VAR, home);
|
|
56
|
-
if (/[$%`]/.test(t)) return null;
|
|
57
|
-
if (!isAbs(t)) t = `${repoRoot}/${t.replace(/^\.\//, '')}`;
|
|
58
|
-
return normalizeAbs(t);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Locate the script a hook command runs. Returns null when the command has no
|
|
63
|
-
* script path this function can resolve (inline code, unknown variables, ...).
|
|
64
|
-
*/
|
|
65
|
-
function parseHookCommand(command, repoRoot, home) {
|
|
66
|
-
const tokens = tokenize(command);
|
|
67
|
-
if (tokens.length === 0) return null;
|
|
68
|
-
const first = path.posix.basename(slashes(tokens[0].text)).replace(/\.exe$/i, '').toLowerCase();
|
|
69
|
-
|
|
70
|
-
if (first === 'sh' && tokens[1] && path.posix.basename(slashes(bareToken(tokens[1].text))) === LAUNCHER_NAME) {
|
|
71
|
-
if (!tokens[2]) return null;
|
|
72
|
-
const launcher = expandPath(tokens[1].text, repoRoot, home);
|
|
73
|
-
const script = expandPath(tokens[2].text, repoRoot, home);
|
|
74
|
-
return script ? { launcher: true, launcherPath: launcher, scriptPath: script, scriptToken: tokens[2] } : null;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
if (INTERPRETERS.has(first)) {
|
|
78
|
-
for (let i = 1; i < tokens.length; i += 1) {
|
|
79
|
-
const text = bareToken(tokens[i].text);
|
|
80
|
-
if (text.startsWith('-') && !SCRIPT_EXT.test(text)) continue;
|
|
81
|
-
if (!SCRIPT_EXT.test(text)) return null;
|
|
82
|
-
const script = expandPath(tokens[i].text, repoRoot, home);
|
|
83
|
-
return script ? { launcher: false, interpreter: first, scriptPath: script, scriptToken: tokens[i], tokenIndex: i } : null;
|
|
84
|
-
}
|
|
85
|
-
return null;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
if (SCRIPT_EXT.test(bareToken(tokens[0].text))) {
|
|
89
|
-
const script = expandPath(tokens[0].text, repoRoot, home);
|
|
90
|
-
return script ? { launcher: false, interpreter: null, scriptPath: script, scriptToken: tokens[0], tokenIndex: 0 } : null;
|
|
91
|
-
}
|
|
92
|
-
return null;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function repoRelative(repoRoot, scriptPath) {
|
|
96
|
-
return sameOrUnder(repoRoot, scriptPath) && scriptPath.length > repoRoot.length
|
|
97
|
-
? scriptPath.slice(repoRoot.length + 1)
|
|
98
|
-
: null;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Rewrite `python|python3|py [-u|-3] <repo>/.claude/hooks/x.py [args]` into the
|
|
103
|
-
* launcher form. Returns null when the command is not a bare project hook this
|
|
104
|
-
* function may rewrite.
|
|
105
|
-
*/
|
|
106
|
-
function toLauncherCommand(command, { repoRoot, home, launcherCommand }) {
|
|
107
|
-
const parsed = parseHookCommand(command, repoRoot, home);
|
|
108
|
-
if (!parsed || parsed.launcher) return null;
|
|
109
|
-
if (!['python', 'python3', 'py'].includes(parsed.interpreter) || parsed.tokenIndex === undefined) return null;
|
|
110
|
-
const tokens = tokenize(command);
|
|
111
|
-
const flagsOk = tokens.slice(1, parsed.tokenIndex).every((t) => /^-(u|3|B)$/.test(t.text));
|
|
112
|
-
if (!flagsOk) return null;
|
|
113
|
-
const rel = repoRelative(repoRoot, parsed.scriptPath);
|
|
114
|
-
if (!rel || !PROJECT_HOOK_REL.test(rel) || rel.includes('..')) return null;
|
|
115
|
-
const args = command.slice(parsed.scriptToken.end);
|
|
116
|
-
const relArg = /\s/.test(rel) ? `"${rel}"` : rel;
|
|
117
|
-
return `${launcherCommand} ${relArg}${args}`;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function launcherCommandFor(targetBase) {
|
|
121
|
-
const home = normalizeAbs(os.homedir());
|
|
122
|
-
const base = normalizeAbs(targetBase);
|
|
123
|
-
const launcher = base === `${home}/.claude` ? `~/.claude/hooks/${LAUNCHER_NAME}` : `${base}/hooks/${LAUNCHER_NAME}`;
|
|
124
|
-
return `sh ${/\s/.test(launcher) ? `"${launcher}"` : launcher}`;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function* hookCommands(settings) {
|
|
128
|
-
const hooks = settings && typeof settings === 'object' ? settings.hooks : null;
|
|
129
|
-
if (!hooks || typeof hooks !== 'object') return;
|
|
130
|
-
for (const [event, groups] of Object.entries(hooks)) {
|
|
131
|
-
if (!Array.isArray(groups)) continue;
|
|
132
|
-
for (const group of groups) {
|
|
133
|
-
if (!group || !Array.isArray(group.hooks)) continue;
|
|
134
|
-
for (const hook of group.hooks) {
|
|
135
|
-
if (hook && typeof hook.command === 'string') yield { event, matcher: group.matcher || null, hook };
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function readSettingsFile(file) {
|
|
142
|
-
let raw;
|
|
143
|
-
try {
|
|
144
|
-
raw = fs.readFileSync(file, 'utf8');
|
|
145
|
-
} catch {
|
|
146
|
-
return null;
|
|
147
|
-
}
|
|
148
|
-
try {
|
|
149
|
-
return { raw, settings: JSON.parse(raw.replace(/^/, '')) };
|
|
150
|
-
} catch {
|
|
151
|
-
return { raw, settings: null };
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Findings for one repo: hook commands whose script is missing, and bare project hooks that fail closed. */
|
|
156
|
-
function scanRepo(repoRoot, { home = os.homedir() } = {}) {
|
|
157
|
-
const root = normalizeAbs(repoRoot);
|
|
158
|
-
const homeDir = normalizeAbs(home);
|
|
159
|
-
const findings = [];
|
|
160
|
-
for (const name of SETTINGS_FILES) {
|
|
161
|
-
const file = path.join(repoRoot, '.claude', name);
|
|
162
|
-
const loaded = readSettingsFile(file);
|
|
163
|
-
if (!loaded) continue;
|
|
164
|
-
if (!loaded.settings) {
|
|
165
|
-
findings.push({ repo: root, file, kind: 'unparseable', command: null });
|
|
166
|
-
continue;
|
|
167
|
-
}
|
|
168
|
-
for (const { event, matcher, hook } of hookCommands(loaded.settings)) {
|
|
169
|
-
const parsed = parseHookCommand(hook.command, root, homeDir);
|
|
170
|
-
if (!parsed) continue;
|
|
171
|
-
const base = { repo: root, file, event, matcher, command: hook.command };
|
|
172
|
-
const rel = repoRelative(root, parsed.scriptPath);
|
|
173
|
-
const projectHook = !parsed.launcher && rel !== null && PROJECT_HOOK_REL.test(rel);
|
|
174
|
-
if (projectHook) {
|
|
175
|
-
const fixable = toLauncherCommand(hook.command, { repoRoot: root, home: homeDir, launcherCommand: 'sh L' }) !== null;
|
|
176
|
-
findings.push({ ...base, kind: 'bare-project-hook', script: parsed.scriptPath, fixable });
|
|
177
|
-
}
|
|
178
|
-
if (!fs.existsSync(parsed.scriptPath)) {
|
|
179
|
-
findings.push({ ...base, kind: 'missing-script', script: parsed.scriptPath, failsOpen: parsed.launcher });
|
|
180
|
-
}
|
|
181
|
-
if (parsed.launcher && parsed.launcherPath && !fs.existsSync(parsed.launcherPath)) {
|
|
182
|
-
findings.push({ ...base, kind: 'missing-launcher', script: parsed.launcherPath });
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
return findings;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** Direct children of `root` that are git repos (a `.git` dir or worktree file). */
|
|
190
|
-
function listGitRepos(root) {
|
|
191
|
-
let entries;
|
|
192
|
-
try {
|
|
193
|
-
entries = fs.readdirSync(root, { withFileTypes: true });
|
|
194
|
-
} catch {
|
|
195
|
-
return [];
|
|
196
|
-
}
|
|
197
|
-
return entries
|
|
198
|
-
.filter((e) => e.isDirectory() && fs.existsSync(path.join(root, e.name, '.git')))
|
|
199
|
-
.map((e) => path.join(root, e.name))
|
|
200
|
-
.sort();
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
function currentRepo(cwd) {
|
|
204
|
-
const res = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
|
|
205
|
-
if (res.error || res.status !== 0) return null;
|
|
206
|
-
const top = res.stdout.trim();
|
|
207
|
-
return top ? path.resolve(top) : null;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
function detectFormat(raw) {
|
|
211
|
-
const text = raw.replace(/^/, '');
|
|
212
|
-
const indent = /\n([ \t]+)"/.exec(text);
|
|
213
|
-
return {
|
|
214
|
-
bom: raw.startsWith(''),
|
|
215
|
-
eol: text.includes('\r\n') ? '\r\n' : '\n',
|
|
216
|
-
indent: indent ? indent[1] : 2,
|
|
217
|
-
finalNewline: /\n$/.test(text),
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
function reserialize(settings, raw) {
|
|
222
|
-
const fmt = detectFormat(raw);
|
|
223
|
-
let out = JSON.stringify(settings, null, fmt.indent);
|
|
224
|
-
if (fmt.eol === '\r\n') out = out.replace(/\n/g, '\r\n');
|
|
225
|
-
if (fmt.finalNewline) out += fmt.eol;
|
|
226
|
-
return (fmt.bom ? '' : '') + out;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** Replace only the command string literals in the raw text so every other byte stays; fall back to a format-preserving reserialize. */
|
|
230
|
-
function applyRewrites(raw, settings, rewrites) {
|
|
231
|
-
let text = raw;
|
|
232
|
-
for (const [from, to] of rewrites) {
|
|
233
|
-
text = text.split(JSON.stringify(from)).join(JSON.stringify(to));
|
|
234
|
-
}
|
|
235
|
-
const expected = JSON.stringify(settings);
|
|
236
|
-
let actual;
|
|
237
|
-
try {
|
|
238
|
-
actual = JSON.stringify(JSON.parse(text.replace(/^/, '')));
|
|
239
|
-
} catch {
|
|
240
|
-
actual = null;
|
|
241
|
-
}
|
|
242
|
-
return actual === expected ? text : reserialize(settings, raw);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/** Rewrite fixable bare project hooks in one repo. Returns the list of rewrites performed. */
|
|
246
|
-
function fixRepo(repoRoot, { launcherCommand, home = os.homedir() }) {
|
|
247
|
-
const root = normalizeAbs(repoRoot);
|
|
248
|
-
const homeDir = normalizeAbs(home);
|
|
249
|
-
const changes = [];
|
|
250
|
-
for (const name of SETTINGS_FILES) {
|
|
251
|
-
const file = path.join(repoRoot, '.claude', name);
|
|
252
|
-
const loaded = readSettingsFile(file);
|
|
253
|
-
if (!loaded || !loaded.settings) continue;
|
|
254
|
-
const rewrites = new Map();
|
|
255
|
-
for (const { hook } of hookCommands(loaded.settings)) {
|
|
256
|
-
const next = toLauncherCommand(hook.command, { repoRoot: root, home: homeDir, launcherCommand });
|
|
257
|
-
if (next === null) continue;
|
|
258
|
-
rewrites.set(hook.command, next);
|
|
259
|
-
changes.push({ repo: root, file, from: hook.command, to: next });
|
|
260
|
-
hook.command = next;
|
|
261
|
-
}
|
|
262
|
-
if (rewrites.size === 0) continue;
|
|
263
|
-
fs.writeFileSync(file, applyRewrites(loaded.raw, loaded.settings, rewrites));
|
|
264
|
-
}
|
|
265
|
-
return changes;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
function checkProjectHooks({ cwd, scanRoot, home }) {
|
|
269
|
-
const repos = scanRoot ? listGitRepos(scanRoot) : [currentRepo(cwd || process.cwd())].filter(Boolean);
|
|
270
|
-
const findings = [];
|
|
271
|
-
for (const repo of repos) findings.push(...scanRepo(repo, { home }));
|
|
272
|
-
return { repos, findings };
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
module.exports = {
|
|
276
|
-
checkProjectHooks,
|
|
277
|
-
fixRepo,
|
|
278
|
-
launcherCommandFor,
|
|
279
|
-
listGitRepos,
|
|
280
|
-
parseHookCommand,
|
|
281
|
-
scanRepo,
|
|
282
|
-
toLauncherCommand,
|
|
283
|
-
LAUNCHER_NAME,
|
|
284
|
-
};
|
|
15
|
+
module.exports = require(found);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yasaswy.nagavolu/agents",
|
|
3
|
-
"version": "0.26.
|
|
3
|
+
"version": "0.26.2",
|
|
4
4
|
"description": "CLI for installing the yasaswy.nagavolu agent/skill/hook bundle. `install` opens an interactive bundle menu in a TTY (or `--bundle <key> --yes` for non-interactive installs), with hash-tracked idempotent deploys, automatic hook wiring into settings.json, and masked secret prompting. `update` reconciles installed bundles against the current source (hash-tracked: silent overwrite, conflict diff+prompt, or --theirs/--keep-mine). `uninstall` removes a bundle's files and wiring. `secrets` re-runs secret prompting for already-installed bundles.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "commonjs",
|