@yasaswy.nagavolu/agents 0.26.2 → 0.26.4

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
@@ -94,7 +94,12 @@ agents-cli install
94
94
  (for example `dontAsk` under a global `bypassPermissions`); `--fix` removes it from `settings.local.json`
95
95
  only, a committed `settings.json` is reported and never edited. The `permission_mode_enforce.js` hook
96
96
  (harness-hygiene) does the same repair at SessionStart/UserPromptSubmit and auto-allows permission prompts
97
- while the global default is `bypassPermissions`.
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.
98
103
  - `agents-cli --help` — show usage
99
104
 
100
105
  ### The interactive menu
package/bin/cli.js CHANGED
@@ -35,6 +35,7 @@ const { runSelfProfilePostInstall } = require('../lib/selfProfile');
35
35
  const { checkHealth, DoctorError } = require('../lib/doctor');
36
36
  const projectHooks = require('../lib/projectHooks');
37
37
  const modeDrift = require('../lib/modeDrift');
38
+ const permissionRules = require('../lib/permissionRules');
38
39
  const { checkModVersions } = require('../lib/claudeVersion');
39
40
 
40
41
  const PACKAGE_ROOT = path.join(__dirname, '..');
@@ -1134,13 +1135,28 @@ Project hooks (${step.findings.length} finding(s), ${step.repos.length} repo(s)
1134
1135
  function printModeDriftReport(modes) {
1135
1136
  if (modes.fixed.length > 0) {
1136
1137
  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
+ 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)}`);
1138
1139
  }
1139
1140
  if (modes.findings.length === 0) return;
1140
1141
  console.log(`\nPermission mode drift (${modes.findings.length} finding(s), ${modes.repos.length} repo(s) checked):`);
1141
1142
  for (const f of modes.findings) console.log(` ${modeDrift.describeModeFinding(f)}`);
1142
1143
  }
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
+
1144
1160
  function splitProjectHookFlags(argv) {
1145
1161
  const rest = [];
1146
1162
  const opts = { scanRoot: null, fix: false, targetDir: null };
@@ -1178,6 +1194,13 @@ async function withProjectHookStep(argv, run) {
1178
1194
  fix: opts.fix,
1179
1195
  })
1180
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
+ );
1181
1204
  } catch (err) {
1182
1205
  console.error(`project hook scan skipped: ${err.message}`);
1183
1206
  }
@@ -1205,6 +1228,7 @@ function runDoctor(argv) {
1205
1228
  targetBase: args.targetDir || defaultTargetBase(),
1206
1229
  };
1207
1230
  const modes = modeDrift.checkModeDrift({ ...scope, fix: args.fix });
1231
+ const rules = permissionRules.checkRuleMigration({ ...scope, fix: args.fix });
1208
1232
  const hooks = projectHooks.projectHooksStep({ ...scope, fix: args.fix });
1209
1233
  if (hooks.error) {
1210
1234
  console.error(hooks.error);
@@ -1213,7 +1237,8 @@ function runDoctor(argv) {
1213
1237
  const { fixed } = hooks;
1214
1238
  result.projectHooks = { repos: hooks.repos, findings: hooks.findings, fixed };
1215
1239
  result.modeDrift = { globalMode: modes.globalMode, findings: modes.findings, fixed: modes.fixed };
1216
- result.healthy = result.healthy && hooks.findings.length === 0 && modes.findings.length === 0;
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;
1217
1242
 
1218
1243
  if (args.json) {
1219
1244
  console.log(JSON.stringify(result, null, 2));
@@ -1221,7 +1246,10 @@ function runDoctor(argv) {
1221
1246
  }
1222
1247
 
1223
1248
  const printProjectHooks = () => printProjectHookReport(hooks, { fixRequested: args.fix });
1224
- const printModeDrift = () => printModeDriftReport(modes);
1249
+ const printModeDrift = () => {
1250
+ printModeDriftReport(modes);
1251
+ printRuleMigrationReport(rules);
1252
+ };
1225
1253
 
1226
1254
  const printModVersions = () => {
1227
1255
  if (result.modVersions.length === 0) return;
@@ -66,6 +66,12 @@ function fixRepoModes(repoRoot, globalMode) {
66
66
  return [{ repo: repoRoot, file, mode, globalMode, local: true }];
67
67
  }
68
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
+
69
75
  function resolveRepos({ cwd, scanRoot }) {
70
76
  return scanRoot ? listGitRepos(scanRoot) : [currentRepo(cwd || process.cwd())].filter(Boolean);
71
77
  }
@@ -86,7 +92,7 @@ function describeModeFinding(f) {
86
92
  }
87
93
 
88
94
  /** SessionStart/UserPromptSubmit: strip weaker local modes, report committed ones at SessionStart. Returns a hook output or null. */
89
- function guardSession({ event, roots, targetBase }) {
95
+ function guardSession({ event, roots, targetBase, sessionId }) {
90
96
  const globalMode = globalDefaultMode(targetBase);
91
97
  if (!globalMode) return null;
92
98
  const lines = [];
@@ -98,7 +104,7 @@ function guardSession({ event, roots, targetBase }) {
98
104
  for (const f of fixRepoModes(root, globalMode)) {
99
105
  lines.push(
100
106
  `permission-mode: removed defaultMode '${f.mode}' from ${f.file} (global default is ${globalMode}). ` +
101
- 'Press ctrl+x m once to cycle this live session.'
107
+ `A live session already on the weaker mode needs: ${resumeCommand(sessionId, globalMode)}`
102
108
  );
103
109
  }
104
110
  if (event !== 'SessionStart') continue;
@@ -148,5 +154,6 @@ module.exports = {
148
154
  globalDefaultMode,
149
155
  guardSession,
150
156
  isWeaker,
157
+ resumeCommand,
151
158
  scanRepoModes,
152
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
+ };
@@ -410,6 +410,7 @@ function projectHooksStep({ cwd, scanRoot, fix, targetBase, home }) {
410
410
 
411
411
  module.exports = {
412
412
  FIX_COMMAND,
413
+ applyRewrites,
413
414
  failureEffect,
414
415
  projectHooksStep,
415
416
  checkProjectHooks,
@@ -23,7 +23,7 @@ try {
23
23
  let out = null;
24
24
  if (event === 'SessionStart' || event === 'UserPromptSubmit') {
25
25
  const roots = [process.env.CLAUDE_PROJECT_DIR, typeof payload.cwd === 'string' ? projectRootFor(payload.cwd) : null];
26
- out = guardSession({ event, roots, targetBase });
26
+ out = guardSession({ event, roots, targetBase, sessionId: payload.session_id });
27
27
  } else {
28
28
  out = decidePermission(payload, targetBase);
29
29
  }
@@ -112,11 +112,13 @@ def _handle_stop(data: dict) -> None:
112
112
  if not mode or mode == "bypassPermissions":
113
113
  return
114
114
 
115
+ resume_id = session_id if isinstance(session_id, str) and _SAFE_ID_RE.match(session_id) else "<session-id>"
115
116
  print(json.dumps({
116
117
  "systemMessage": (
117
118
  f"This session's live permission mode is '{mode}', but your "
118
- "configured default is bypassPermissions. Press ctrl+x m to cycle "
119
- "modes, or run /permissions, to get back to bypassPermissions."
119
+ "configured default is bypassPermissions. Exit and run "
120
+ f"`claude --resume {resume_id} --permission-mode bypassPermissions` "
121
+ "to get back to bypassPermissions."
120
122
  )
121
123
  }))
122
124
 
@@ -1,22 +1,47 @@
1
1
  #!/bin/sh
2
2
  # Runs a project hook from the session cwd's repo, not the session-pinned CLAUDE_PROJECT_DIR.
3
3
  # Usage: project_hook.sh <repo-relative or CLAUDE_PROJECT_DIR-absolute hook path> [args...]
4
- payload="$(cat)"
4
+ # Hot path uses shell builtins only: no cat/tr/sed/python/git spawn unless a submodule or a .py hook needs one.
5
+ payload=""
6
+ nl='
7
+ '
8
+ dq='"'
9
+ bs='\'
10
+ while IFS= read -r line || [ -n "$line" ]; do
11
+ if [ -z "$payload" ]; then payload="$line"; else payload="$payload$nl$line"; fi
12
+ done
5
13
 
14
+ # Result in $SL (a command substitution would fork).
15
+ slashes() {
16
+ SL=""
17
+ s="$1"
18
+ while :; do
19
+ case "$s" in
20
+ *"$bs"*) SL="$SL${s%%"$bs"*}/"; s="${s#*"$bs"}" ;;
21
+ *) SL="$SL$s"; break ;;
22
+ esac
23
+ done
24
+ }
25
+
26
+ # A real interpreter first; the WindowsApps python3 stub only as a last resort.
6
27
  find_python() {
7
- for cand in python3 python py; do
8
- cmd="$(command -v "$cand" 2>/dev/null)" || continue
9
- "$cmd" -c "import sys" >/dev/null 2>&1 && { echo "$cmd"; return 0; }
28
+ for pass in real stub; do
29
+ for cand in python3 python py; do
30
+ cmd="$(command -v "$cand" 2>/dev/null)" || continue
31
+ case "$cmd" in
32
+ *WindowsApps*) [ "$pass" = stub ] || continue ;;
33
+ *) [ "$pass" = real ] || continue ;;
34
+ esac
35
+ echo "$cmd"
36
+ return 0
37
+ done
10
38
  done
11
39
  return 1
12
40
  }
13
- py="$(find_python)"
14
41
 
15
- slashes() { printf '%s' "$1" | tr '\\' '/'; }
16
- hook_arg="$(slashes "$1")"
42
+ slashes "$1"; hook_arg="$SL"
17
43
  shift
18
- project_dir="$(slashes "$CLAUDE_PROJECT_DIR")"
19
- project_dir="${project_dir%/}"
44
+ slashes "$CLAUDE_PROJECT_DIR"; project_dir="${SL%/}"
20
45
  rel_hook="$hook_arg"
21
46
  # Back-compat: an absolute path under CLAUDE_PROJECT_DIR reduces to its repo-relative part.
22
47
  if [ -n "$project_dir" ]; then
@@ -25,16 +50,46 @@ if [ -n "$project_dir" ]; then
25
50
  esac
26
51
  fi
27
52
 
53
+ # cwd from the JSON payload; a JSON-escaped backslash collapses to "/" like any other separator.
28
54
  cwd=""
29
- [ -n "$py" ] && cwd="$(printf '%s' "$payload" | "$py" -c 'import json,sys; print(json.load(sys.stdin).get("cwd",""))' 2>/dev/null)"
55
+ case "$payload" in
56
+ *'"cwd"'*)
57
+ rest="${payload#*"${dq}cwd${dq}"}"
58
+ rest="${rest#*:}"
59
+ rest="${rest#*"$dq"}"
60
+ slashes "${rest%%"$dq"*}"
61
+ cwd="$SL"
62
+ while :; do case "$cwd" in *//*) cwd="${cwd%%//*}/${cwd#*//}" ;; *) break ;; esac; done
63
+ ;;
64
+ esac
30
65
 
31
66
  has_hook() { [ -n "$1" ] && [ -f "$1/$2" ]; }
32
67
 
68
+ # Nearest ancestor of cwd holding .git (dir, or file for a worktree/submodule).
69
+ find_toplevel() {
70
+ d="$1"
71
+ while [ -n "$d" ]; do
72
+ [ -e "$d/.git" ] && { echo "$d"; return 0; }
73
+ case "$d" in */*) d="${d%/*}" ;; *) return 1 ;; esac
74
+ done
75
+ [ -e "/.git" ] && { echo "/"; return 0; }
76
+ return 1
77
+ }
78
+
33
79
  target_dir=""
34
80
  if [ -n "$cwd" ]; then
81
+ top="$(find_toplevel "$cwd")"
82
+ super=""
83
+ # Only a submodule (.git file whose gitdir is not under worktrees/) can have a superproject.
84
+ if [ -n "$top" ] && [ -f "$top/.git" ]; then
85
+ gitdir_line=""
86
+ IFS= read -r gitdir_line < "$top/.git" || :
87
+ case "$gitdir_line" in
88
+ */worktrees/*) ;;
89
+ *) super="$(git -C "$cwd" rev-parse --show-superproject-working-tree 2>/dev/null)" ;;
90
+ esac
91
+ fi
35
92
  # A cwd inside a submodule resolves to its superproject, which owns .claude/hooks.
36
- super="$(git -C "$cwd" rev-parse --show-superproject-working-tree 2>/dev/null)"
37
- top="$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null)"
38
93
  if has_hook "$super" "$rel_hook"; then target_dir="$super"
39
94
  elif has_hook "$top" "$rel_hook"; then target_dir="$top"
40
95
  fi
@@ -55,6 +110,7 @@ case "$hook_path" in
55
110
  printf '%s' "$payload" | sh "$run_python_sh" "$hook_path" "$@"
56
111
  exit $?
57
112
  fi
113
+ py="$(find_python)"
58
114
  if [ -n "$py" ]; then
59
115
  printf '%s' "$payload" | "$py" "$hook_path" "$@"
60
116
  exit $?
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
- // SessionStart/UserPromptSubmit guard: repairs project hooks that point at a missing file; never blocks.
3
+ // SessionStart/UserPromptSubmit guard: repairs project hooks that point at a missing file and path-scoped Write/NotebookEdit permission rules; never blocks.
4
4
  const fs = require('node:fs');
5
5
  const path = require('node:path');
6
6
 
@@ -12,14 +12,27 @@ function readPayload() {
12
12
  }
13
13
  }
14
14
 
15
- try {
15
+ function attempt(label, fn) {
16
+ try {
17
+ return fn();
18
+ } catch (err) {
19
+ process.stderr.write(`project_hook_repair (${label}): ${err.message}\n`);
20
+ return null;
21
+ }
22
+ }
23
+
24
+ const payload = readPayload();
25
+ const event = payload.hook_event_name === 'UserPromptSubmit' ? 'UserPromptSubmit' : 'SessionStart';
26
+ let roots = [process.env.CLAUDE_PROJECT_DIR];
27
+ const hooksOut = attempt('hooks', () => {
16
28
  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`);
29
+ roots = [process.env.CLAUDE_PROJECT_DIR, typeof payload.cwd === 'string' ? projectRootFor(payload.cwd) : null];
30
+ return guardSession({ event, roots, targetBase: path.dirname(__dirname) });
31
+ });
32
+ const rulesOut = attempt('rules', () => require('./lib/permissionRules.js').guardSession({ event, roots }));
33
+
34
+ if (hooksOut || rulesOut) {
35
+ const systemMessage = [hooksOut && hooksOut.systemMessage, rulesOut && rulesOut.systemMessage].filter(Boolean).join('\n');
36
+ process.stdout.write(`${JSON.stringify({ ...(hooksOut || {}), systemMessage })}\n`);
24
37
  }
25
38
  process.exit(0);
@@ -773,7 +773,7 @@
773
773
  "path": "global/hooks/project_hook_repair.js",
774
774
  "targetPath": "hooks/project_hook_repair.js",
775
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.",
776
+ "note": "Also rewrites Write(path)/NotebookEdit(path) permission rules in settings.local.json to Edit(path) and reports committed ones. 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
777
  "wiring": {
778
778
  "event": "SessionStart",
779
779
  "type": "command",
@@ -790,6 +790,12 @@
790
790
  "command": "node ~/.claude/hooks/project_hook_repair.js"
791
791
  }
792
792
  },
793
+ {
794
+ "path": "global/hooks/lib/permissionRules.js",
795
+ "targetPath": "hooks/lib/permissionRules.js",
796
+ "kind": "hook",
797
+ "note": "Shared core required by project_hook_repair.js; rewrites path-scoped Write(...)/NotebookEdit(...) permission rules to the Edit(...) form Claude Code actually matches. The CLI (packages/cli/lib/permissionRules.js) re-exports this same file for doctor/update/install, so there is one implementation."
798
+ },
793
799
  {
794
800
  "path": "global/hooks/lib/projectHooks.js",
795
801
  "targetPath": "hooks/lib/projectHooks.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "handoff",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "One-click session handoff: prepares the work, writes a lean handoff file, verifies it, clears the session and submits the handoff as the first message",
5
5
  "author": { "name": "Yasaswy Nagavolu" },
6
6
  "metadata": { "minClaudeCodeVersion": "2.1.287" }
@@ -28,27 +28,27 @@ an unattended session's prompt cache warm. Needs Claude Code 2.1.287 or later (m
28
28
  chord shows the toast `handoff already running (<phase>)` and starts nothing.
29
29
  - Busy chat (a turn runs, a user prompt waits, or a nudge is in flight): the handoff queues. The band reads
30
30
  `Handoff queued: waiting for the current turn to finish...` with a `Cancel` button. The prep prompt is submitted
31
- when the turn ends (or at the next keep-warm tick), after the running-work gate runs again.
31
+ when the turn ends (or at the next keep-warm tick), and the running-work note shows then.
32
32
  - The prep prompt opens with `[Handoff prep - this is not the handoff itself]` and a one-line note, so the
33
33
  chat shows it is not the handoff. The label is added by code (`lib/prep.mjs`), not by the prompt file.
34
34
  - The prep reply is the turn whose start text carries that label and this session's handoff path; only its turn id
35
35
  is scored, so an earlier queued message or nudge cannot cause "no HANDOFF_READY line". A prep that never starts aborts after 30 min.
36
36
  - Phase A: `prompts/handoff-prep.md` syncs tasks and PRD, fixes docs, runs tests, commits and pushes,
37
37
  writes `~/.claude/handoffs/<session_id>.md`, then prints `HANDOFF_READY <path>` or `HANDOFF_ABORT <reason>`.
38
- - Phase B (turn complete): sentinel, `lib/validate.mjs`, git gate (`lib/gitgate.mjs`), running-work gate.
38
+ - Phase B (turn complete): sentinel, `lib/validate.mjs`, git gate (`lib/gitgate.mjs`).
39
39
  Only then: clipboard, `/clear`, submit the handoff. Any failed check keeps the session and the file.
40
40
  - Git gate: no dirty tracked files, and nothing unpushed. With an upstream it counts `@{upstream}..HEAD`.
41
41
  Without one (or on a detached HEAD) it counts commits not on the remote default branch (`origin/HEAD`,
42
42
  else `origin/main`, else `origin/master`). A repo with a remote but no resolvable default branch aborts;
43
43
  a repo with no remote, or no repo at all, passes.
44
- - Running-work gate: before Phase A and again before `/clear`, the mod counts running subagents (`$.agent.list()`, live) and background
45
- tasks (the `background_tasks` of the last `classic.Stop`, a snapshot: if stale, send any message and retry). Any running work aborts with a
46
- toast and log line; it never stops anything. Step 0 of `prompts/handoff-prep.md` also tells the model not to go on.
44
+ - Running work never blocks: when the handoff starts (or a queued one is released) the mod counts running subagents (`$.agent.list()`, live) and
45
+ background tasks (the `background_tasks` of the last `classic.Stop`, a snapshot) and shows one toast if any run. Nothing is stopped or waited for;
46
+ step 0 of `prompts/handoff-prep.md` lists them in the handoff's open risks.
47
47
 
48
48
  ## Auto-handoff
49
49
 
50
50
  - On by default. When context is at 65% or more and the chat is idle, the mod runs the same flow as `Alt+H`
51
- (same git gate, running-work gate and validator) and shows the toast `Auto-handoff: context is at N% ...`.
51
+ (same git gate and validator) and shows the toast `Auto-handoff: context is at N% ...`.
52
52
  - Idle means: no running turn, no user prompt waiting, no nudge in flight, no handoff running, and an
53
53
  empty prompt box. A busy chat defers to the next idle tick (15 s). Unknown context never fires.
54
54
  - After an auto run aborts, auto waits until context has grown 5 points past the level at the abort. A new
@@ -6,7 +6,7 @@ import { copyViaSystem } from '../lib/clipboard.mjs'
6
6
  import { TONES, busyBand, idleBand, textBand } from '../lib/band.mjs'
7
7
  import { renderPrep, isPrepTurn, prepStartExpired } from '../lib/prep.mjs'
8
8
  import { evaluateGitState, collectGitState } from '../lib/gitgate.mjs'
9
- import { summarizeActiveWork, activeWorkReason } from '../lib/activework.mjs'
9
+ import { summarizeActiveWork, activeWorkNote } from '../lib/activework.mjs'
10
10
  import { claudeSubdir, sessionFilePath, cacheInfoFromState, cacheRemainingMs } from '../lib/cache.mjs'
11
11
  import { AUTO_THRESHOLD_PERCENT, AUTO_STORE_KEY, HANDOFF_USAGE, newAuto, storedEnabled, onAutoAbort, settleAuto, decideAuto, autoLabel, autoStatusText, parseHandoffArgs } from '../lib/auto.mjs'
12
12
  import {
@@ -83,7 +83,6 @@ async function startHandoff($, autoLevel = null) {
83
83
  setPhase($, 'starting')
84
84
  try {
85
85
  const work = await activeWork($)
86
- if (work.total > 0) return fail($, activeWorkReason(work))
87
86
  const sessionId = await $.session.id()
88
87
  const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
89
88
  const dir = (await $.env.get('HANDOFF_DIR')) || defaultHandoffDir(home)
@@ -98,12 +97,17 @@ async function startHandoff($, autoLevel = null) {
98
97
  $.ui.toast('Handoff queued - waiting for the current turn to finish', { timeoutMs: TOAST_MS })
99
98
  return
100
99
  }
100
+ noteActiveWork($, work)
101
101
  await submitPrep($)
102
102
  } catch (err) {
103
103
  return fail($, 'could not start (' + err + ')')
104
104
  }
105
105
  }
106
106
 
107
+ function noteActiveWork($, work) {
108
+ if (work.total > 0) $.ui.toast(activeWorkNote(work), { timeoutMs: TOAST_MS })
109
+ }
110
+
107
111
  async function submitPrep($) {
108
112
  flow.turnId = null
109
113
  flow.submittedAt = await $.clock.now()
@@ -115,8 +119,7 @@ async function releaseQueued($) {
115
119
  if (flow.phase !== 'queued' || isBusy(state, await $.clock.now())) return
116
120
  flow.phase = 'prep'
117
121
  try {
118
- const work = await activeWork($)
119
- if (work.total > 0) return fail($, activeWorkReason(work))
122
+ noteActiveWork($, await activeWork($))
120
123
  await submitPrep($)
121
124
  } catch (err) {
122
125
  return fail($, 'could not start (' + err + ')')
@@ -146,9 +149,6 @@ async function finishHandoff($, reason) {
146
149
  const gate = evaluateGitState(await collectGitState((argv) => $.process.run(argv)))
147
150
  if (!gate.ok) return fail($, gate.reason)
148
151
 
149
- const work = await activeWork($)
150
- if (work.total > 0) return fail($, activeWorkReason(work))
151
-
152
152
  const submission = prepareSubmission(handoff)
153
153
  const copied = await copyToClipboard($, handoff, flow.path)
154
154
  await $.command.run({ command: 'clear', args: '' })
@@ -7,9 +7,9 @@ export function summarizeActiveWork(agents, background) {
7
7
  return { subagents, tasks: others, total: subagents + others }
8
8
  }
9
9
 
10
- export function activeWorkReason({ subagents, tasks }) {
10
+ export function activeWorkNote({ subagents, tasks }) {
11
11
  const parts = []
12
12
  if (subagents > 0) parts.push(subagents + ' subagent(s)')
13
13
  if (tasks > 0) parts.push(tasks + ' background task(s)')
14
- return parts.join(' and ') + ' still running: stop or wait for them first'
14
+ return 'Handoff continues with ' + parts.join(' and ') + ' still running; they are not stopped'
15
15
  }
@@ -1,6 +1,6 @@
1
1
  Prepare this session for a handoff. The session is cleared after you finish, so leave nothing only in this conversation. Do the steps in order. Do not ask questions.
2
2
 
3
- 0. Running work. List running subagents and background tasks. Do not go on until each has finished or you stopped it with TaskStop (only work you started). If one cannot finish, print `HANDOFF_ABORT` naming it.
3
+ 0. Running work. List any running subagents and background tasks (name and goal) in the open risks of the handoff file. Do not wait for them, stop them or abort because of them. Running work never blocks the handoff.
4
4
  1. Tasks. Use TaskList and TaskUpdate so every task matches reality (done, in progress, pending).
5
5
  2. PRD issue. Find the single open PRD issue for this session (task metadata or this conversation). Update its description (TODO mirror and status) and post one status comment, using the issue-tracker access this project already uses (a repo script or the tracker's CLI). Never print the token. If no PRD issue exists, write "none" in the PRD section.
6
6
  3. Docs. Update only the markdown docs, README rows and memory that this session touched or made stale.
@@ -9,4 +9,4 @@ Prepare this session for a handoff. The session is cleared after you finish, so
9
9
  6. Check. Run `{{validator_cmd}}`. Fix the file until it exits 0.
10
10
  7. Finish. Print exactly one final line: `HANDOFF_READY {{handoff_path}}`.
11
11
 
12
- Abort rule: if tests fail or the push fails, do not write the ready line. Print one final line `HANDOFF_ABORT <short reason>` instead. Keep the handoff file if you wrote it.
12
+ Abort rule: only if tests fail or the push fails, do not write the ready line. Print one final line `HANDOFF_ABORT <short reason>` instead. Keep the handoff file if you wrote it.
@@ -1,6 +1,6 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
- import { summarizeActiveWork, activeWorkReason } from '../lib/activework.mjs'
3
+ import { summarizeActiveWork, activeWorkNote } from '../lib/activework.mjs'
4
4
 
5
5
  test('only running agents count', () => {
6
6
  const agents = [{ status: 'running' }, { status: 'completed' }, { status: 'killed' }, { status: 'running' }]
@@ -17,10 +17,10 @@ test('bad input counts as nothing', () => {
17
17
  assert.deepEqual(summarizeActiveWork(undefined, null), { subagents: 0, tasks: 0, total: 0 })
18
18
  })
19
19
 
20
- test('reason names the counts and says stop or wait', () => {
20
+ test('note names the counts and says the work is not stopped', () => {
21
21
  assert.equal(
22
- activeWorkReason({ subagents: 2, tasks: 1 }),
23
- '2 subagent(s) and 1 background task(s) still running: stop or wait for them first',
22
+ activeWorkNote({ subagents: 2, tasks: 1 }),
23
+ 'Handoff continues with 2 subagent(s) and 1 background task(s) still running; they are not stopped',
24
24
  )
25
- assert.equal(activeWorkReason({ subagents: 0, tasks: 3 }), '3 background task(s) still running: stop or wait for them first')
25
+ assert.equal(activeWorkNote({ subagents: 0, tasks: 3 }), 'Handoff continues with 3 background task(s) still running; they are not stopped')
26
26
  })