@yasaswy.nagavolu/agents 0.26.1 → 0.26.3

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 CHANGED
@@ -87,7 +87,19 @@ 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`. A live session already on the weaker mode is switched with
98
+ `claude --resume <session-id> --permission-mode bypassPermissions` (`ctrl+x m` is swallowed by the VS Code terminal).
99
+ It also flags path-scoped `Write(<path>)` and `NotebookEdit(<path>)` rules in `permissions.allow/deny/ask`
100
+ (Claude Code only matches `Edit(<path>)` for file writes); `--fix`, the `project_hook_repair.js` hook and the
101
+ `--fix-project-hooks` flag of `install`/`update` rewrite them to `Edit(<path>)` in `settings.local.json` with duplicates
102
+ dropped, a committed `settings.json` is reported and never edited, bare `Write`/`NotebookEdit` are left alone.
91
103
  - `agents-cli --help` — show usage
92
104
 
93
105
  ### The interactive menu
package/bin/cli.js CHANGED
@@ -34,6 +34,8 @@ 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');
38
+ const permissionRules = require('../lib/permissionRules');
37
39
  const { checkModVersions } = require('../lib/claudeVersion');
38
40
 
39
41
  const PACKAGE_ROOT = path.join(__dirname, '..');
@@ -62,6 +64,11 @@ Usage:
62
64
  agents-cli uninstall --bundle <key> --yes Remove a bundle's installed files and settings.json wiring
63
65
  agents-cli update --yes Update every installed bundle to the current source
64
66
  agents-cli update --bundle <key> --yes Update one installed bundle
67
+ install | update [--scan-root <dir>] [--fix-project-hooks]
68
+ After the run, report bare project hooks of the cwd repo (or every git repo
69
+ under <dir>); --fix-project-hooks rewrites them to the fail-open launcher.
70
+ Also reports a project defaultMode weaker than the global one; with
71
+ --fix-project-hooks it is removed from settings.local.json
65
72
  agents-cli secrets Prompt for any missing secrets across all installed bundles
66
73
  agents-cli secrets --bundle <key> Prompt for missing secrets for one bundle
67
74
  agents-cli secrets --list Show which secrets are set/missing (names only — never values)
@@ -164,6 +171,11 @@ whose script file is missing, and a bare (non-launcher) project hook command, wh
164
171
  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
172
  reported. Without --fix nothing is modified.
166
173
 
174
+ doctor also flags a project .claude/settings.json or settings.local.json whose permissions.defaultMode is weaker
175
+ than the global default in <target>/settings.json (for example "dontAsk" under a global "bypassPermissions"), which
176
+ silently downgrades every session in that repo. --fix removes the key from settings.local.json only; a committed
177
+ settings.json is reported, never edited.
178
+
167
179
  doctor reports, without changing anything: orphans (files/directories sitting inside
168
180
  a path this CLI manages that the ledger does not claim — e.g. a stale file left behind
169
181
  by a renamed/retired item), missing (a ledger-tracked file no longer on disk), and
@@ -1097,10 +1109,102 @@ function describeHookFinding(f) {
1097
1109
  const where = `${f.file} [${f.event || '-'}]`;
1098
1110
  if (f.kind === 'unparseable') return `${f.file}: not valid JSON, hooks not checked`;
1099
1111
  if (f.kind === 'bare-project-hook') {
1100
- return `${where} bare project hook, exits 2 (blocks a PreToolUse call) if its file goes missing${f.fixable ? ' (fixable)' : ' (not auto-fixable)'}: ${f.command}`;
1112
+ 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
1113
  }
1102
1114
  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)' : ' (FAILS CLOSED: blocks tool calls)'}: ${f.script}`;
1115
+ return `${where} script missing${f.failsOpen ? ' (launcher: fails open, hook does not run)' : ` (FAILS CLOSED: ${projectHooks.failureEffect(f.event)})`}: ${f.script}`;
1116
+ }
1117
+
1118
+ function printProjectHookReport(step, { fixRequested }) {
1119
+ if (step.fixed.length > 0) {
1120
+ console.log(`
1121
+ Rewrote ${step.fixed.length} bare project hook command(s) to the fail-open launcher:`);
1122
+ for (const c of step.fixed) console.log(` ${c.file}
1123
+ - ${c.from}
1124
+ + ${c.to}`);
1125
+ }
1126
+ if (step.findings.length === 0) return;
1127
+ console.log(`
1128
+ Project hooks (${step.findings.length} finding(s), ${step.repos.length} repo(s) checked):`);
1129
+ for (const f of step.findings) console.log(` ${describeHookFinding(f)}`);
1130
+ if (!fixRequested && step.findings.some((f) => f.kind === 'bare-project-hook' && f.fixable)) {
1131
+ console.log(` Fix: ${projectHooks.FIX_COMMAND}`);
1132
+ }
1133
+ }
1134
+
1135
+ function printModeDriftReport(modes) {
1136
+ if (modes.fixed.length > 0) {
1137
+ console.log(`\nRemoved ${modes.fixed.length} defaultMode override(s) weaker than the global "${modes.globalMode}":`);
1138
+ for (const f of modes.fixed) console.log(` ${f.file} (was "${f.mode}"); a live session already on it needs: ${modeDrift.resumeCommand(null, modes.globalMode)}`);
1139
+ }
1140
+ if (modes.findings.length === 0) return;
1141
+ console.log(`\nPermission mode drift (${modes.findings.length} finding(s), ${modes.repos.length} repo(s) checked):`);
1142
+ for (const f of modes.findings) console.log(` ${modeDrift.describeModeFinding(f)}`);
1143
+ }
1144
+
1145
+ function printRuleMigrationReport(rules) {
1146
+ if (rules.fixed.length > 0) {
1147
+ console.log(`
1148
+ Rewrote path-scoped Write/NotebookEdit permission rules to Edit in ${rules.fixed.length} file(s):`);
1149
+ for (const f of rules.fixed) {
1150
+ console.log(` ${f.file}`);
1151
+ for (const c of f.changes) console.log(` ${c.from} -> ${c.to}${c.deduped ? ' (duplicate dropped)' : ''}`);
1152
+ }
1153
+ }
1154
+ if (rules.findings.length === 0) return;
1155
+ console.log(`
1156
+ Permission rules Claude Code ignores (${rules.findings.length} file(s), ${rules.repos.length} repo(s) checked):`);
1157
+ for (const f of rules.findings) console.log(` ${permissionRules.describeRuleFinding(f)}`);
1158
+ }
1159
+
1160
+ function splitProjectHookFlags(argv) {
1161
+ const rest = [];
1162
+ const opts = { scanRoot: null, fix: false, targetDir: null };
1163
+ for (let i = 0; i < argv.length; i += 1) {
1164
+ const arg = argv[i];
1165
+ if (arg === '--fix-project-hooks') opts.fix = true;
1166
+ else if (arg === '--scan-root' && argv[i + 1]) {
1167
+ opts.scanRoot = argv[i + 1];
1168
+ i += 1;
1169
+ } else {
1170
+ if (arg === '--target-dir') opts.targetDir = argv[i + 1] || null;
1171
+ rest.push(arg);
1172
+ }
1173
+ }
1174
+ return { rest, opts };
1175
+ }
1176
+
1177
+ async function withProjectHookStep(argv, run) {
1178
+ const { rest, opts } = splitProjectHookFlags(argv);
1179
+ const code = await run(rest);
1180
+ try {
1181
+ const step = projectHooks.projectHooksStep({
1182
+ cwd: process.cwd(),
1183
+ scanRoot: opts.scanRoot ? path.resolve(opts.scanRoot) : null,
1184
+ fix: opts.fix,
1185
+ targetBase: opts.targetDir || defaultTargetBase(),
1186
+ });
1187
+ if (step.error) console.error(step.error);
1188
+ printProjectHookReport(step, { fixRequested: opts.fix });
1189
+ printModeDriftReport(
1190
+ modeDrift.checkModeDrift({
1191
+ targetBase: opts.targetDir || defaultTargetBase(),
1192
+ cwd: process.cwd(),
1193
+ scanRoot: opts.scanRoot ? path.resolve(opts.scanRoot) : null,
1194
+ fix: opts.fix,
1195
+ })
1196
+ );
1197
+ printRuleMigrationReport(
1198
+ permissionRules.checkRuleMigration({
1199
+ cwd: process.cwd(),
1200
+ scanRoot: opts.scanRoot ? path.resolve(opts.scanRoot) : null,
1201
+ fix: opts.fix,
1202
+ })
1203
+ );
1204
+ } catch (err) {
1205
+ console.error(`project hook scan skipped: ${err.message}`);
1206
+ }
1207
+ return code;
1104
1208
  }
1105
1209
 
1106
1210
  function runDoctor(argv) {
@@ -1118,45 +1222,33 @@ function runDoctor(argv) {
1118
1222
  targetBase: args.targetDir,
1119
1223
  });
1120
1224
 
1121
- const targetBase = args.targetDir || defaultTargetBase();
1122
- const hookScope = { cwd: process.cwd(), scanRoot: args.scanRoot ? path.resolve(args.scanRoot) : null };
1123
- let hooks = projectHooks.checkProjectHooks(hookScope);
1124
- const fixed = [];
1125
- if (args.fix && hooks.findings.some((f) => f.kind === 'bare-project-hook' && f.fixable)) {
1126
- if (!fs.existsSync(path.join(targetBase, 'hooks', projectHooks.LAUNCHER_NAME))) {
1127
- console.error(
1128
- `Cannot fix: ${path.join(targetBase, 'hooks', projectHooks.LAUNCHER_NAME)} is not installed. ` +
1129
- 'Run "agents-cli update" (or install the harness-hygiene bundle) first.'
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);
1225
+ const scope = {
1226
+ cwd: process.cwd(),
1227
+ scanRoot: args.scanRoot ? path.resolve(args.scanRoot) : null,
1228
+ targetBase: args.targetDir || defaultTargetBase(),
1229
+ };
1230
+ const modes = modeDrift.checkModeDrift({ ...scope, fix: args.fix });
1231
+ const rules = permissionRules.checkRuleMigration({ ...scope, fix: args.fix });
1232
+ const hooks = projectHooks.projectHooksStep({ ...scope, fix: args.fix });
1233
+ if (hooks.error) {
1234
+ console.error(hooks.error);
1235
+ return 1;
1136
1236
  }
1237
+ const { fixed } = hooks;
1137
1238
  result.projectHooks = { repos: hooks.repos, findings: hooks.findings, fixed };
1138
- result.healthy = result.healthy && hooks.findings.length === 0;
1239
+ result.modeDrift = { globalMode: modes.globalMode, findings: modes.findings, fixed: modes.fixed };
1240
+ result.permissionRules = { findings: rules.findings, fixed: rules.fixed };
1241
+ result.healthy = result.healthy && hooks.findings.length === 0 && modes.findings.length === 0 && rules.findings.length === 0;
1139
1242
 
1140
1243
  if (args.json) {
1141
1244
  console.log(JSON.stringify(result, null, 2));
1142
1245
  return result.healthy ? 0 : 1;
1143
1246
  }
1144
1247
 
1145
- const printProjectHooks = () => {
1146
- if (fixed.length > 0) {
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
- }
1248
+ const printProjectHooks = () => printProjectHookReport(hooks, { fixRequested: args.fix });
1249
+ const printModeDrift = () => {
1250
+ printModeDriftReport(modes);
1251
+ printRuleMigrationReport(rules);
1160
1252
  };
1161
1253
 
1162
1254
  const printModVersions = () => {
@@ -1168,6 +1260,7 @@ Project hooks (${hooks.findings.length} finding(s), ${hooks.repos.length} repo(s
1168
1260
  if (result.healthy) {
1169
1261
  console.log(`${result.targetBase}: healthy — no orphans, no missing files, no drift.`);
1170
1262
  printModVersions();
1263
+ printModeDrift();
1171
1264
  return 0;
1172
1265
  }
1173
1266
 
@@ -1186,6 +1279,7 @@ Project hooks (${hooks.findings.length} finding(s), ${hooks.repos.length} repo(s
1186
1279
  }
1187
1280
  printModVersions();
1188
1281
  printProjectHooks();
1282
+ printModeDrift();
1189
1283
  return 1;
1190
1284
  } catch (err) {
1191
1285
  if (err instanceof DoctorError || err instanceof ManifestError || err instanceof LedgerError) {
@@ -1210,7 +1304,7 @@ async function main(argv) {
1210
1304
  }
1211
1305
 
1212
1306
  if (command === 'install') {
1213
- return runInstall(rest);
1307
+ return withProjectHookStep(rest, runInstall);
1214
1308
  }
1215
1309
 
1216
1310
  if (command === 'uninstall') {
@@ -1222,7 +1316,7 @@ async function main(argv) {
1222
1316
  }
1223
1317
 
1224
1318
  if (command === 'update') {
1225
- return runUpdate(rest);
1319
+ return withProjectHookStep(rest, runUpdate);
1226
1320
  }
1227
1321
 
1228
1322
  if (command === 'doctor') {
@@ -0,0 +1,159 @@
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
+ /** The one mode switch that works in terminals that swallow ctrl+x chords (VS Code integrated terminal). */
70
+ function resumeCommand(sessionId, mode = BYPASS) {
71
+ const id = typeof sessionId === 'string' && /^[A-Za-z0-9_.-]+$/.test(sessionId) ? sessionId : '<session-id>';
72
+ return `claude --resume ${id} --permission-mode ${mode}`;
73
+ }
74
+
75
+ function resolveRepos({ cwd, scanRoot }) {
76
+ return scanRoot ? listGitRepos(scanRoot) : [currentRepo(cwd || process.cwd())].filter(Boolean);
77
+ }
78
+
79
+ function checkModeDrift({ targetBase, cwd, scanRoot, fix = false }) {
80
+ const globalMode = globalDefaultMode(targetBase);
81
+ const repos = resolveRepos({ cwd, scanRoot });
82
+ if (!globalMode) return { globalMode: null, repos, findings: [], fixed: [] };
83
+ const fixed = fix ? repos.flatMap((repo) => fixRepoModes(repo, globalMode)) : [];
84
+ const findings = repos.flatMap((repo) => scanRepoModes(repo, globalMode));
85
+ return { globalMode, repos, findings, fixed };
86
+ }
87
+
88
+ function describeModeFinding(f) {
89
+ return f.local
90
+ ? `${f.file} sets defaultMode "${f.mode}", weaker than global "${f.globalMode}" (fix: agents-cli doctor --fix)`
91
+ : `${f.file} is committed and sets defaultMode "${f.mode}", weaker than global "${f.globalMode}" (not auto-edited: remove it or ask the owner)`;
92
+ }
93
+
94
+ /** SessionStart/UserPromptSubmit: strip weaker local modes, report committed ones at SessionStart. Returns a hook output or null. */
95
+ function guardSession({ event, roots, targetBase, sessionId }) {
96
+ const globalMode = globalDefaultMode(targetBase);
97
+ if (!globalMode) return null;
98
+ const lines = [];
99
+ const seen = new Set();
100
+ for (const root of roots.filter(Boolean)) {
101
+ const key = path.resolve(root).toLowerCase();
102
+ if (seen.has(key)) continue;
103
+ seen.add(key);
104
+ for (const f of fixRepoModes(root, globalMode)) {
105
+ lines.push(
106
+ `permission-mode: removed defaultMode '${f.mode}' from ${f.file} (global default is ${globalMode}). ` +
107
+ `A live session already on the weaker mode needs: ${resumeCommand(sessionId, globalMode)}`
108
+ );
109
+ }
110
+ if (event !== 'SessionStart') continue;
111
+ for (const f of scanRepoModes(root, globalMode)) {
112
+ lines.push(
113
+ `permission-mode: committed ${f.file} sets defaultMode '${f.mode}', weaker than global ${globalMode}; ` +
114
+ 'not edited, remove it or ask the owner.'
115
+ );
116
+ }
117
+ }
118
+ return lines.length > 0 ? { systemMessage: lines.join('\n') } : null;
119
+ }
120
+
121
+ function autoAllowApplies(payload, targetBase) {
122
+ if (globalDefaultMode(targetBase) !== BYPASS) return false;
123
+ if (INTERACTIVE_TOOLS.has(payload.tool_name)) return false;
124
+ const live = payload.permission_mode;
125
+ return live === undefined || live === null || AUTO_ALLOW_LIVE_MODES.has(live);
126
+ }
127
+
128
+ /** PermissionRequest and PreToolUse: allow so no prompt reaches the user. Returns a hook output or null. */
129
+ function decidePermission(payload, targetBase) {
130
+ const event = payload.hook_event_name;
131
+ if (event === 'PermissionRequest') {
132
+ if (!autoAllowApplies(payload, targetBase)) return null;
133
+ return { hookSpecificOutput: { hookEventName: event, decision: { behavior: 'allow' } } };
134
+ }
135
+ if (event === 'PreToolUse') {
136
+ if (payload.permission_mode !== 'dontAsk' || !autoAllowApplies(payload, targetBase)) return null;
137
+ return {
138
+ hookSpecificOutput: {
139
+ hookEventName: event,
140
+ permissionDecision: 'allow',
141
+ permissionDecisionReason: 'global default is bypassPermissions; session is on dontAsk',
142
+ },
143
+ };
144
+ }
145
+ return null;
146
+ }
147
+
148
+ module.exports = {
149
+ MODE_RANK,
150
+ checkModeDrift,
151
+ decidePermission,
152
+ describeModeFinding,
153
+ fixRepoModes,
154
+ globalDefaultMode,
155
+ guardSession,
156
+ isWeaker,
157
+ resumeCommand,
158
+ scanRepoModes,
159
+ };
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+
3
+ // Core for project_hook_repair.js and the CLI (doctor/update/install): Write(<path>) and NotebookEdit(<path>) permission rules never match; only Edit(<path>) does.
4
+ const path = require('node:path');
5
+ const { applyRewrites, currentRepo, listGitRepos, readSettingsFile, writeAtomic } = require('./projectHooks.js');
6
+
7
+ const LOCAL_FILE = 'settings.local.json';
8
+ const SETTINGS_FILES = [LOCAL_FILE, 'settings.json'];
9
+ const RULE_LISTS = ['allow', 'deny', 'ask'];
10
+ const PATH_RULE = /^(Write|NotebookEdit)\((.+)\)$/;
11
+
12
+ function toEditRule(rule) {
13
+ if (typeof rule !== 'string') return null;
14
+ const m = PATH_RULE.exec(rule);
15
+ return m ? `Edit(${m[2]})` : null;
16
+ }
17
+
18
+ function ruleLists(settings) {
19
+ const permissions = settings && typeof settings === 'object' ? settings.permissions : null;
20
+ if (!permissions || typeof permissions !== 'object') return [];
21
+ return RULE_LISTS.filter((name) => Array.isArray(permissions[name])).map((name) => [name, permissions[name]]);
22
+ }
23
+
24
+ /** Rewrite path-scoped Write/NotebookEdit rules to Edit in place, dropping duplicates inside each list. Returns the changes. */
25
+ function migrateRules(settings) {
26
+ const changes = [];
27
+ for (const [list, rules] of ruleLists(settings)) {
28
+ if (!rules.some((r) => toEditRule(r) !== null)) continue;
29
+ const seen = new Set();
30
+ const next = [];
31
+ for (const rule of rules) {
32
+ const edit = toEditRule(rule);
33
+ const value = edit === null ? rule : edit;
34
+ if (typeof value === 'string') {
35
+ if (seen.has(value)) {
36
+ if (edit !== null) changes.push({ list, from: rule, to: edit, deduped: true });
37
+ continue;
38
+ }
39
+ seen.add(value);
40
+ }
41
+ if (edit !== null) changes.push({ list, from: rule, to: edit, deduped: false });
42
+ next.push(value);
43
+ }
44
+ rules.splice(0, rules.length, ...next);
45
+ }
46
+ return changes;
47
+ }
48
+
49
+ /** Findings for one repo: every file holding a Write(path)/NotebookEdit(path) rule. */
50
+ function scanRepoRules(repoRoot) {
51
+ const findings = [];
52
+ for (const name of SETTINGS_FILES) {
53
+ const file = path.join(repoRoot, '.claude', name);
54
+ const loaded = readSettingsFile(file);
55
+ if (!loaded || !loaded.settings) continue;
56
+ const rules = ruleLists(loaded.settings).flatMap(([list, items]) =>
57
+ items.filter((r) => toEditRule(r) !== null).map((rule) => ({ list, rule, to: toEditRule(rule) }))
58
+ );
59
+ if (rules.length > 0) findings.push({ repo: repoRoot, file, local: name === LOCAL_FILE, rules });
60
+ }
61
+ return findings;
62
+ }
63
+
64
+ /** Rewrite the rules in a repo's settings.local.json; the tracked settings.json is never edited. */
65
+ function fixRepoRules(repoRoot) {
66
+ const file = path.join(repoRoot, '.claude', LOCAL_FILE);
67
+ const loaded = readSettingsFile(file);
68
+ if (!loaded || !loaded.settings) return [];
69
+ const changes = migrateRules(loaded.settings);
70
+ if (changes.length === 0) return [];
71
+ const textRewrites = new Map(changes.filter((c) => !c.deduped).map((c) => [c.from, c.to]));
72
+ writeAtomic(file, applyRewrites(loaded.raw, loaded.settings, textRewrites));
73
+ return [{ repo: repoRoot, file, local: true, changes }];
74
+ }
75
+
76
+ function checkRuleMigration({ cwd, scanRoot, fix = false }) {
77
+ const repos = scanRoot ? listGitRepos(scanRoot) : [currentRepo(cwd || process.cwd())].filter(Boolean);
78
+ const fixed = fix ? repos.flatMap((repo) => fixRepoRules(repo)) : [];
79
+ const findings = repos.flatMap((repo) => scanRepoRules(repo));
80
+ return { repos, findings, fixed };
81
+ }
82
+
83
+ function describeRuleFinding(f) {
84
+ const shown = f.rules.map((r) => `${r.rule} -> ${r.to}`).join(', ');
85
+ return f.local
86
+ ? `${f.file}: ${shown} (fix: agents-cli doctor --fix)`
87
+ : `${f.file} is committed and has ${shown}; Claude Code ignores these (not auto-edited: change them to Edit(path) or ask the owner)`;
88
+ }
89
+
90
+ /** SessionStart/UserPromptSubmit: migrate local rules, report committed ones at SessionStart. Returns a hook output or null. */
91
+ function guardSession({ event, roots }) {
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 fixRepoRules(root)) {
99
+ const shown = f.changes.map((c) => `${c.from} -> ${c.to}${c.deduped ? ' (duplicate dropped)' : ''}`).join(', ');
100
+ lines.push(`permission-rules: rewrote ${shown} in ${f.file}; Claude Code only matches Edit(path) rules for file writes.`);
101
+ }
102
+ if (event !== 'SessionStart') continue;
103
+ for (const f of scanRepoRules(root).filter((x) => !x.local)) {
104
+ lines.push(`permission-rules: committed ${describeRuleFinding(f)}`);
105
+ }
106
+ }
107
+ return lines.length > 0 ? { systemMessage: lines.join('\n') } : null;
108
+ }
109
+
110
+ module.exports = {
111
+ checkRuleMigration,
112
+ describeRuleFinding,
113
+ fixRepoRules,
114
+ guardSession,
115
+ migrateRules,
116
+ scanRepoRules,
117
+ };