@christang/keel 5.160.0 → 5.162.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.160.0",
3
+ "version": "5.162.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
package/README.md CHANGED
@@ -210,7 +210,7 @@ because a permission granted in conversation does not survive a context reset. D
210
210
  `keel/config.yaml` instead:
211
211
 
212
212
  ```yaml
213
- authorize: # accepted names: commit, push, push:<branch glob>, release, archive, continuation, issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch, push-protected:<branch glob>[@<role>], shift-restore, self-shift
213
+ authorize: # accepted names: commit, push, push:<branch glob>[@<role>], release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift
214
214
  - commit
215
215
  - push
216
216
  ```
@@ -262,6 +262,17 @@ refused. A permission mode that cannot be relied on to ask, `bypassPermissions`
262
262
  refused too. Declaring it turns the push check on by itself, and a bare `push` beside it is
263
263
  refused.
264
264
 
265
+ Every scoped entry — `push:`, `issue:`, `issue-close:`, `cleanup:`, `chat-reply:` and
266
+ `push-protected:` — may end in `@<role>`, or a role pattern such as `@kaiwu-design-*`, where `*`
267
+ matches any run of role characters (#378). Such an entry reaches only a session whose chat role
268
+ matches. A session reads the grants for its own role in the capsule, `keel context`,
269
+ `keel --doctor` and its chat-reply groups, and `keel --doctor` lists, for each bound role, the
270
+ scoped entries that reach it. On push, the Claude write guard allows a branch only through an
271
+ entry for the session's role, and refuses a branch another role's entry covers by naming that role.
272
+ The check stays on for every session while any push entry is declared, so a role that no entry
273
+ names is limited, not unlimited. The tracker, chat and scratchpad scopes stay carried rather than
274
+ enforced: the role decides only which session reads them.
275
+
265
276
  `shift-restore` (#319) covers the two things a session started by a shift change on the Claude
266
277
  desktop app must do right after `keel shift resume`: turn its own Remote Control back on if it came
267
278
  back off, and rename itself back to its working title. A clear there keeps no title. Without the declaration, the woken
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.160.0 -->
1
+ <!-- keel:start version=5.162.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
package/bin/keel.js CHANGED
@@ -48,6 +48,7 @@ const {
48
48
  STANDING_AUTHORIZATION_ACTIONS,
49
49
  readPrecedentStore,
50
50
  readStandingAuthorization,
51
+ roleMatches,
51
52
  readFullModePaths,
52
53
  readExecutorTier,
53
54
  readMergeDeclaration,
@@ -2378,7 +2379,7 @@ function gitConfigHooksPath(repo) {
2378
2379
 
2379
2380
  function printStandingAuthorizationSurface(repo) {
2380
2381
  process.stdout.write("\nStanding authorization:\n");
2381
- const { declared, scopes, unknown, message } = readStandingAuthorization(repo);
2382
+ const { declared, scopes, unknown, message, otherRoles, entries, role } = readStandingAuthorization(repo);
2382
2383
  if (unknown.length > 0) {
2383
2384
  printDoctorLine("authorize", "failed", message);
2384
2385
  return false;
@@ -2386,9 +2387,10 @@ function printStandingAuthorizationSurface(repo) {
2386
2387
  printDoctorLine(
2387
2388
  "authorize",
2388
2389
  declared.length > 0 ? "ok" : "none",
2389
- declared.length > 0
2390
+ (declared.length > 0
2390
2391
  ? `declared in keel/config.yaml: ${declared.join(", ")}`
2391
- : "undeclared; every action stays hard-stop"
2392
+ : "undeclared; every action stays hard-stop")
2393
+ + (otherRoles.length ? `; for other roles than ${role || "this unbound session"}: ${otherRoles.join(", ")}` : "")
2392
2394
  );
2393
2395
  for (const action of STANDING_AUTHORIZATION_ACTIONS) {
2394
2396
  // Keyed on the action, never on the declared string. A scoped entry is
@@ -2431,6 +2433,21 @@ function printStandingAuthorizationSurface(repo) {
2431
2433
  + "asked, and a mode that cannot ask (bypassPermissions, dontAsk) is refused"
2432
2434
  );
2433
2435
  }
2436
+ // Per bound role, the scoped entries that reach it (#378 D4).
2437
+ if (entries.some((entry) => entry.role)) {
2438
+ let bound = [];
2439
+ try {
2440
+ const store = require("../src/core/chat/store");
2441
+ const where = store.locate(repo);
2442
+ if (where) bound = [...new Set(Object.values(store.readRoles(where.root)).map((name) => store.canonicalRole(where.root, name)))].sort();
2443
+ } catch {
2444
+ bound = [];
2445
+ }
2446
+ for (const name of bound) {
2447
+ const reach = entries.filter((entry) => entry.scope !== null && (!entry.role || roleMatches(entry.role, name))).map((entry) => entry.entry);
2448
+ printDoctorLine("roles", name, reach.length ? reach.join(", ") : "no scoped grant");
2449
+ }
2450
+ }
2434
2451
  if (scopes.get("push")) {
2435
2452
  printDoctorLine(
2436
2453
  "push scope",
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.160.0",
3
+ "version": "5.162.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.160.0",
9
+ "version": "5.162.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.160.0",
5
+ "version": "5.162.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.160.0",
3
+ "version": "5.162.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.160.0",
3
+ "version": "5.162.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -187,7 +187,8 @@ function gitOut(cwd, args) {
187
187
  return result.status === 0 ? String(result.stdout || "").trim() : null;
188
188
  }
189
189
 
190
- // `push:` globs and `push-protected:` entries ({ glob, role }) of `authorize:`.
190
+ // `push:` and `push-protected:` entries ({ glob, role }) of `authorize:`; a
191
+ // role pattern after `@` limits either to matching sessions (#378).
191
192
  function readPushGlobs(top) {
192
193
  let text = "";
193
194
  try {
@@ -207,8 +208,8 @@ function readPushGlobs(top) {
207
208
  if (!inBlock) continue;
208
209
  if (!/^\s/.test(line)) break;
209
210
  const bare = line.replace(/\s+#.*$/, "");
210
- const entry = bare.match(/^\s+-\s*push:(\S+)\s*$/);
211
- if (entry) globs.push(entry[1]);
211
+ const entry = bare.match(/^\s+-\s*push:([^@\s]+)(?:@(\S+))?\s*$/);
212
+ if (entry) globs.push({ glob: entry[1], role: entry[2] || null });
212
213
  const guarded = bare.match(/^\s+-\s*push-protected:([^@\s]+)(?:@(\S+))?\s*$/);
213
214
  if (guarded) protectedEntries.push({ glob: guarded[1], role: guarded[2] || null });
214
215
  }
@@ -225,13 +226,29 @@ function sessionRole(top) {
225
226
  const common = gitOut(top, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
226
227
  if (!common) return null;
227
228
  try {
228
- const roles = JSON.parse(fs.readFileSync(path.join(fs.realpathSync(common), "keel-chat", "roles.json"), "utf8"));
229
- return roles[fs.realpathSync(top)] || null;
229
+ const root = path.join(fs.realpathSync(common), "keel-chat");
230
+ const roles = JSON.parse(fs.readFileSync(path.join(root, "roles.json"), "utf8"));
231
+ let role = roles[fs.realpathSync(top)] || null;
232
+ // A renamed role reads as its new name (#376).
233
+ let renames = {};
234
+ try {
235
+ renames = JSON.parse(fs.readFileSync(path.join(root, "renames.json"), "utf8")) || {};
236
+ } catch {
237
+ renames = {};
238
+ }
239
+ for (let hops = 0; role && renames[role] && hops < 32; hops += 1) role = renames[role];
240
+ return role;
230
241
  } catch {
231
242
  return null;
232
243
  }
233
244
  }
234
245
 
246
+ // A role pattern: chat-role characters, `*` matching any run of them (#378).
247
+ function roleMatches(pattern, role) {
248
+ if (!role) return false;
249
+ return new RegExp(`^${String(pattern).split("*").join("[a-z0-9-]*")}$`).test(role);
250
+ }
251
+
235
252
  // Modes in which the host cannot be relied on to ask (#280 D3, F2).
236
253
  const MODES_THAT_CANNOT_ASK = new Set(["bypassPermissions", "dontAsk"]);
237
254
 
@@ -533,7 +550,7 @@ function checkPushes(event) {
533
550
  const { globs, protectedEntries } = readPushGlobs(top);
534
551
  if (!globs.length && !protectedEntries.length) continue;
535
552
  const declared = [
536
- ...globs.map((glob) => `\`push:${glob}\``),
553
+ ...globs.map((e) => `\`push:${e.glob}${e.role ? `@${e.role}` : ""}\``),
537
554
  ...protectedEntries.map((e) => `\`push-protected:${e.glob}${e.role ? `@${e.role}` : ""}\``),
538
555
  ].join(", ");
539
556
  const result = pushTargets(push);
@@ -556,19 +573,30 @@ function checkPushes(event) {
556
573
  return 0;
557
574
  }
558
575
  if (result.tags) carriesTags = true;
576
+ let role;
577
+ const roleOf = () => (role === undefined ? (role = sessionRole(top)) : role);
578
+ const mine = (e) => !e.role || roleMatches(e.role, roleOf());
559
579
  const unlisted = result.tags
560
580
  ? result.targets
561
- : result.targets.filter((branch) => !globs.some((glob) => globPattern(glob).test(branch)));
581
+ : result.targets.filter((branch) => !globs.some((e) => mine(e) && globPattern(e.glob).test(branch)));
562
582
  const outside = [];
563
583
  for (const branch of unlisted) {
564
584
  const entry = protectedEntries.find((e) => globPattern(e.glob).test(branch));
565
585
  if (!entry) {
586
+ // Another role's grant (#378): name who may push it.
587
+ const theirs = globs.filter((e) => e.role && globPattern(e.glob).test(branch)).map((e) => e.role);
588
+ if (theirs.length && !result.tags) {
589
+ deny(
590
+ `Keel push guard: \`${branch}\` may be pushed by role ${theirs.join(" or ")} (keel/config.yaml), and this `
591
+ + `session is ${roleOf() ? `role ${roleOf()}` : "bound to no chat role"}.`
592
+ );
593
+ return 0;
594
+ }
566
595
  outside.push(branch);
567
596
  continue;
568
597
  }
569
598
  if (entry.role) {
570
- const role = sessionRole(top);
571
- if (role !== entry.role) {
599
+ if (!roleMatches(entry.role, roleOf())) {
572
600
  deny(
573
601
  `Keel push guard: \`${branch}\` is protected for role ${entry.role}, and this `
574
602
  + `session is ${role ? `role ${role}` : "bound to no chat role"}; only an ${entry.role} `
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.160.0"
53
- PROTOCOL_VERSION = "5.160.0"
52
+ PACKAGE_VERSION = "5.162.0"
53
+ PROTOCOL_VERSION = "5.162.0"
54
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8077,49 +8077,84 @@ def validate_shift_start_desktop_scenario() -> int:
8077
8077
 
8078
8078
 
8079
8079
  def validate_shift_cli_self_shift_scenario() -> int:
8080
- """Issue #357 on the CLI (owner, 2026-10-19): stop the old session, start a new one.
8080
+ """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
8081
8081
 
8082
8082
  A CLI session cannot clear itself. `keel shift ready --wake` there queues
8083
- the hand-off; `keel tick` waits until the old session is idle, stops it
8084
- (kept: `claude attach` reopens it), and starts a new session in the role's
8085
- worktree that runs `keel shift resume`. `keel shift status` shows the
8086
- queue, and a failed start is a patrol risk.
8083
+ the hand-off and leaves a waiter that, once the old session has finished,
8084
+ retires it (stop, rename by resuming it with `/rename`, stop) and starts a
8085
+ new session in the role's worktree that runs `keel shift resume`. `keel
8086
+ tick` carries out a queued hand-off too, and the two start one session. A
8087
+ session that is busy, or blocked on a question (idle, but its job state is
8088
+ still `working`), is left alone. `keel shift status` shows the queue, and a
8089
+ failed start is a patrol risk.
8087
8090
  """
8088
8091
  label = "shift-cli-self-shift:"
8089
8092
  OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8090
8093
  with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
8091
8094
  base = Path(raw)
8092
8095
  rtl, verify, env, _ = shift_scratch(base)
8093
- calls, agents, fail = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start"
8096
+ calls, agents, fail, norename = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start", base / "no-rename"
8094
8097
  fake = base / "fake-claude"
8098
+ # The fake answers with the shapes measured on Claude Code 2.1.303: a live row has `status` and `state`; a stopped one has `state: stopped` and no `status`.
8095
8099
  write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8096
- f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
8097
- f"if sys.argv[1:3] == ['agents', '--json']:\n print(open({str(agents)!r}).read()); sys.exit(0)\n"
8098
- f"if sys.argv[1:2] == ['--bg'] and os.path.exists({str(fail)!r}):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8099
- "if sys.argv[1:2] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8100
+ f"agents, fail, norename = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}\n"
8101
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd(), 'claude_env': sorted(k for k in os.environ if k.startswith('CLAUDE'))}}) + '\\n')\n"
8102
+ "argv = sys.argv[1:]\n"
8103
+ "if argv[:2] == ['agents', '--json']:\n print(open(agents).read()); sys.exit(0)\n"
8104
+ "rows = json.loads(open(agents).read())\n"
8105
+ "if argv[:1] == ['stop']:\n"
8106
+ " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row['state'] = 'stopped'\n"
8107
+ " open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)\n"
8108
+ "if argv[:2] == ['--bg', '--resume']:\n"
8109
+ " for row in rows:\n if row['sessionId'] == argv[2] and not os.path.exists(norename):\n row['name'] = argv[3].split(None, 1)[1]\n"
8110
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + argv[2][:8]); sys.exit(0)\n"
8111
+ "if argv[:1] == ['--bg'] and os.path.exists(fail):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8112
+ "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8100
8113
  "print('stopped')\n")
8101
8114
  fake.chmod(0o755)
8102
- env = {**env, "KEEL_CLAUDE": str(fake)}
8115
+ env = {**env, "KEEL_CLAUDE": str(fake), "KEEL_SHIFT_HANDOVER_POLL_MS": "200", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "20000",
8116
+ "KEEL_SHIFT_RENAME_WAIT_MS": "1500"}
8117
+ # With the waiter given no time, a hand-over is the tick's alone.
8118
+ tick_only = {**env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
8103
8119
  cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8120
+ queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue"
8121
+
8122
+ def agents_row(status: str | None, state: str, name: str = "verify") -> None:
8123
+ row = {"kind": "background", "name": name, "sessionId": OLD, "id": OLD[:8], "pid": os.getpid(), "state": state, "cwd": str(verify)}
8124
+ if status:
8125
+ row["status"] = status
8126
+ agents.write_text(json.dumps([row]))
8127
+
8128
+ def rows() -> list[dict]:
8129
+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8104
8130
 
8105
- def agents_status(status: str) -> None:
8106
- # The measured shape: `sessionId` is the full id, `id` the job id `stop` and `attach` take.
8107
- agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
8108
- "pid": os.getpid(), "status": status, "cwd": str(verify)}]))
8131
+ def acted() -> list[list[str]]:
8132
+ return [r["argv"] for r in rows() if r["argv"][:2] != ["agents", "--json"]]
8109
8133
 
8110
- def made(kind: str) -> list[dict]:
8111
- rows = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8112
- return [r for r in rows if (r["argv"][:1] == ["stop"] if kind == "stop" else r["argv"][:1] == ["--bg"])]
8134
+ def starts() -> list[dict]:
8135
+ return [r for r in rows() if r["argv"][:1] == ["--bg"] and "--resume" not in r["argv"]]
8113
8136
 
8114
8137
  def tick() -> subprocess.CompletedProcess[str]:
8115
- return run_keel(verify, "tick", "--repo", str(rtl), env=env)
8138
+ return run_keel(verify, "tick", "--repo", str(rtl), env=tick_only)
8116
8139
 
8140
+ def status_text() -> str:
8141
+ return run_keel(rtl, "shift", "status", env=env).stdout
8142
+
8143
+ def wait_for(condition, seconds: float = 10.0) -> bool:
8144
+ deadline = time.time() + seconds
8145
+ while time.time() < deadline:
8146
+ if condition():
8147
+ return True
8148
+ time.sleep(0.2)
8149
+ return condition()
8150
+
8151
+ agents_row("busy", "working")
8117
8152
  readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
8118
8153
  if readied.returncode != 0:
8119
8154
  report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
8120
8155
  return 1
8121
- if "keel tick" not in readied.stdout:
8122
- report(f"{label} ready --wake in a CLI session does not say keel tick will hand over: {readied.stdout!r}")
8156
+ if "claude attach" not in readied.stdout or "--wake" in readied.stderr:
8157
+ report(f"{label} ready --wake in a CLI session does not say how the old session is reopened: {readied.stdout!r}")
8123
8158
  return 1
8124
8159
  note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
8125
8160
  if not note:
@@ -8129,58 +8164,100 @@ def validate_shift_cli_self_shift_scenario() -> int:
8129
8164
  report(f"{label} the note does not record the CLI session.")
8130
8165
  return 1
8131
8166
 
8132
- agents_status("busy")
8133
- tick()
8134
- if made("stop"):
8135
- report(f"{label} a tick stopped the old session while it was busy: {made('stop')!r}")
8167
+ # A busy session, and one blocked on a question, are left alone.
8168
+ time.sleep(1.0)
8169
+ if acted():
8170
+ report(f"{label} the hand-over acted while the old session was busy: {acted()!r}")
8136
8171
  return 1
8137
- if made("start"):
8138
- report(f"{label} a tick started a session while the old one was busy: {made('start')!r}")
8172
+ if "pending" not in status_text():
8173
+ report(f"{label} shift status does not show the pending hand-off: {status_text()!r}")
8139
8174
  return 1
8140
- status = run_keel(rtl, "shift", "status", env=env).stdout
8141
- if "pending" not in status:
8142
- report(f"{label} shift status does not show the pending hand-off: {status!r}")
8175
+ agents_row("idle", "working")
8176
+ time.sleep(1.0)
8177
+ if acted():
8178
+ report(f"{label} the hand-over cut off a session blocked on a question (idle, state working): {acted()!r}")
8143
8179
  return 1
8144
8180
 
8145
- agents_status("idle")
8146
- tick()
8147
- stops, starts = made("stop"), made("start")
8148
- if [s["argv"] for s in stops] != [["stop", OLD[:8]]]:
8149
- report(f"{label} the idle old session was not stopped once: {stops!r}")
8181
+ # Finished: the waiter retires it and starts the next, with no tick.
8182
+ agents_row("idle", "done")
8183
+ if not wait_for(lambda: len(starts()) >= 1):
8184
+ report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
8150
8185
  return 1
8151
- if len(starts) != 1:
8152
- report(f"{label} the new session was not started once: {starts!r}")
8186
+ order = acted()
8187
+ shifted = re.compile(r"^/rename verify · shifted \d{4}-\d{2}-\d{2} \d{2}:\d{2}$")
8188
+ if (order[0] != ["stop", OLD[:8]] or order[1][:3] != ["--bg", "--resume", OLD] or len(order[1]) != 4
8189
+ or not shifted.match(order[1][3]) or order[2] != ["stop", OLD[:8]] or order[3][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]
8190
+ or len(order) != 4):
8191
+ report(f"{label} the old session was not retired as stop, rename-by-resume, stop, then the new start: {order!r}")
8153
8192
  return 1
8154
- if starts[0]["argv"][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]:
8155
- report(f"{label} the new session was not started as --bg -n verify --permission-mode auto: {starts!r}")
8193
+ if "keel shift resume" not in order[3][-1] or "--resume" in order[3]:
8194
+ report(f"{label} the new session does not start fresh with a keel shift resume prompt: {order[3]!r}")
8156
8195
  return 1
8157
- if "keel shift resume" not in starts[0]["argv"][-1]:
8158
- report(f"{label} the new session's prompt does not name keel shift resume: {starts[0]['argv']!r}")
8196
+ if os.path.realpath(starts()[0]["cwd"]) != os.path.realpath(verify):
8197
+ report(f"{label} the new session started in {starts()[0]['cwd']}, not verify's worktree.")
8159
8198
  return 1
8160
- if "--resume" in starts[0]["argv"]:
8161
- report(f"{label} the new session resumes an old one instead of starting fresh: {starts[0]['argv']!r}")
8162
- return 1
8163
- if os.path.realpath(starts[0]["cwd"]) != os.path.realpath(verify):
8164
- report(f"{label} the new session started in {starts[0]['cwd']}, not verify's worktree.")
8199
+ leaked = [r for r in rows() if r["claude_env"]]
8200
+ if leaked:
8201
+ report(f"{label} a claude the hand-over ran inherited the old session's {leaked[0]['claude_env']!r}.")
8165
8202
  return 1
8166
- status = run_keel(rtl, "shift", "status", env=env).stdout
8167
- for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}"):
8168
- if needle not in status:
8169
- report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {status!r}")
8203
+ text = status_text()
8204
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}", "shifted"):
8205
+ if needle not in text:
8206
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {text!r}")
8170
8207
  return 1
8171
8208
  tick()
8172
- if len(made("start")) != 1:
8209
+ if len(starts()) != 1 or len(acted()) != 4:
8210
+ report(f"{label} a tick after the hand-over acted again: {acted()!r}")
8211
+ return 1
8212
+
8213
+ # The tick and the waiter start one session: a fresh lock holds the tick off.
8214
+ calls.write_text("")
8215
+ agents_row("idle", "done")
8216
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R014", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8217
+ lock = queue / "verify.lock"
8218
+ write_text(lock, "held")
8219
+ tick()
8220
+ if acted():
8221
+ report(f"{label} a tick acted while another hand-over held the lock: {acted()!r}")
8222
+ return 1
8223
+ lock.unlink()
8224
+ tick()
8225
+ if len(starts()) != 1:
8226
+ report(f"{label} the tick did not start one session once the lock was gone: {acted()!r}")
8227
+ return 1
8228
+ tick()
8229
+ if len(starts()) != 1:
8173
8230
  report(f"{label} a second tick started another session.")
8174
8231
  return 1
8175
8232
 
8233
+ # A rename that never shows is recorded, and the new session still starts.
8234
+ calls.write_text("")
8235
+ agents_row("idle", "done")
8236
+ write_text(norename, "x")
8237
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R015", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8238
+ ticked = tick()
8239
+ text = status_text()
8240
+ if len(starts()) != 1:
8241
+ report(f"{label} a rename that did not show stopped the new session from starting: {acted()!r} {ticked.stderr!r}")
8242
+ return 1
8243
+ if "delivered" not in text:
8244
+ report(f"{label} a rename that did not show kept the hand-off from being delivered: {text!r}")
8245
+ return 1
8246
+ if "rename not shown" not in text:
8247
+ report(f"{label} shift status does not say the rename did not show: {text!r}")
8248
+ return 1
8249
+ norename.unlink()
8250
+
8176
8251
  # A start that fails stays visible and is a patrol risk.
8177
- fail.write_text("x")
8178
- run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env=cli_env)
8252
+ calls.write_text("")
8253
+ agents_row("idle", "done")
8254
+ write_text(fail, "x")
8255
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8179
8256
  tick()
8180
- status = run_keel(rtl, "shift", "status", env=env).stdout
8257
+ text = status_text()
8181
8258
  for needle in ("failed", "Workspace not trusted"):
8182
- if needle not in status:
8183
- report(f"{label} a failed start does not show {needle!r}: {status!r}")
8259
+ if needle not in text:
8260
+ report(f"{label} a failed start does not show {needle!r}: {text!r}")
8184
8261
  return 1
8185
8262
  patrolled = run_keel(rtl, "patrol", env=env).stdout
8186
8263
  if not re.search(r"risk: .*verify.*hand-off", patrolled):
@@ -30941,9 +31018,9 @@ def validate_continuation_authorization_scenario() -> int:
30941
31018
 
30942
31019
 
30943
31020
  ACCEPTED_AUTHORIZE_NAMES = (
30944
- "commit, push, push:<branch glob>, release, archive, continuation, "
30945
- "issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, "
30946
- "issue-close:<owner>/<repo>, cleanup:scratch, push-protected:<branch glob>[@<role>], shift-restore, self-shift"
31021
+ "commit, push, push:<branch glob>[@<role>], release, archive, continuation, "
31022
+ "issue:<owner>/<repo>[@<role>], protocol-refresh, chat-reply:<group>[@<role>], "
31023
+ "issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>], push-protected:<branch glob>[@<role>], shift-restore, self-shift"
30947
31024
  )
30948
31025
 
30949
31026
 
@@ -31005,7 +31082,7 @@ def validate_continuation_docs_scenario() -> int:
31005
31082
  return 1
31006
31083
 
31007
31084
  config_text = (ROOT / "keel/config.yaml").read_text(encoding="utf-8")
31008
- if "commit, push, push:<branch glob>,\n# release, archive, continuation, issue:<owner>/<repo>, protocol-refresh,\n# chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch,\n# push-protected:<branch glob>[@<role>], shift-restore, self-shift" not in config_text:
31085
+ if "commit, push, push:<branch glob>[@<role>],\n# release, archive, continuation, issue:<owner>/<repo>[@<role>], protocol-refresh,\n# chat-reply:<group>[@<role>], issue-close:<owner>/<repo>[@<role>], cleanup:scratch[@<role>],\n# push-protected:<branch glob>[@<role>], shift-restore, self-shift" not in config_text:
31009
31086
  report(
31010
31087
  f"{label}: keel/config.yaml's comment lacks: protocol-refresh in the "
31011
31088
  "seven-name vocabulary."
@@ -33470,6 +33547,101 @@ def validate_push_branch_guard_scenario() -> int:
33470
33547
  return 0
33471
33548
 
33472
33549
 
33550
+ def validate_authorize_role_scoped_scenario() -> int:
33551
+ """Issue #378: a scoped grant may name the roles it applies to.
33552
+
33553
+ kaiwu-ip split its standing authorization by capability, one session per
33554
+ capability, and could only write the split as comments: every scoped grant
33555
+ but `push-protected` applied to every session. `@<role pattern>` limits an
33556
+ entry to matching roles; the push guard stays on for a role no entry names.
33557
+ """
33558
+ label = "authorize-role-scoped:"
33559
+ with tempfile.TemporaryDirectory(prefix="keel-authorize-378-") as raw:
33560
+ base = Path(raw)
33561
+ repo = mailbox_repository(base / "repo")
33562
+ rtl = chat_worktree(repo, base / "rtl")
33563
+ verify = chat_worktree(repo, base / "verify")
33564
+ env = chat_environment()
33565
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
33566
+ run_keel(verify, "chat", "role", "--set", "verify", env=env)
33567
+ entries = ["commit", "push:design-*@rtl", "push:review-*@ver*", "issue:acme/widgets@rtl",
33568
+ "chat-reply:soc@verify", "push-protected:main@rt*"]
33569
+ for cwd in (rtl, verify):
33570
+ write_authorize_config(cwd, "authorize:\n" + "".join(f" - {e}\n" for e in entries))
33571
+
33572
+ def line(stdout: str, name: str) -> str:
33573
+ return next((l for l in stdout.splitlines() if l.strip().startswith(f"{name}:")), "")
33574
+
33575
+ for cwd, role, granted, withheld in ((rtl, "rtl", "issue", "chat-reply"), (verify, "verify", "chat-reply", "issue")):
33576
+ doctor = run_keel(cwd, "--doctor", env=env)
33577
+ if not line(doctor.stdout, granted):
33578
+ report(f"{label} {role}'s doctor has no {granted} line: {doctor.stdout}")
33579
+ return 1
33580
+ if "not authorized" in line(doctor.stdout, granted):
33581
+ report(f"{label} {role}'s doctor does not report {granted} authorized: {doctor.stdout}")
33582
+ return 1
33583
+ if "not authorized" not in line(doctor.stdout, withheld):
33584
+ report(f"{label} {role}'s doctor reports {withheld}, another role's grant: {line(doctor.stdout, withheld)!r}")
33585
+ return 1
33586
+ roles = [l for l in doctor.stdout.splitlines() if l.startswith("roles:")]
33587
+ if not any("rtl" in l and "issue:acme/widgets@rtl" in l for l in roles):
33588
+ report(f"{label} {role}'s doctor lists no roles line for rtl's grants: {roles!r}")
33589
+ return 1
33590
+ if not any("verify" in l and "chat-reply:soc@verify" in l for l in roles):
33591
+ report(f"{label} {role}'s doctor lists no roles line for verify's grants: {roles!r}")
33592
+ return 1
33593
+
33594
+ hook_env = {k: v for k, v in os.environ.items() if k not in ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")}
33595
+ hook_env["CLAUDE_PLUGIN_ROOT"] = str(ROOT / PLUGIN_ROOT)
33596
+
33597
+ def decide(cwd: Path, command: str, role: str | None = None) -> dict:
33598
+ event = {"tool_name": "Bash", "tool_input": {"command": command}, "cwd": str(cwd), "permission_mode": "default"}
33599
+ run_env = {**hook_env, **({"KEEL_CHAT_ROLE": role} if role else {})}
33600
+ result = subprocess.run(
33601
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/pretooluse-guard.js")],
33602
+ cwd=cwd, env=run_env, input=json.dumps(event), text=True, capture_output=True, check=False,
33603
+ )
33604
+ return pretooluse_decision(result) or {"permissionDecision": "pass"}
33605
+
33606
+ if decide(rtl, "git push origin design-x").get("permissionDecision") != "pass":
33607
+ report(f"{label} rtl's own design branch was not allowed: {decide(rtl, 'git push origin design-x')!r}")
33608
+ return 1
33609
+ other = decide(verify, "git push origin design-x")
33610
+ if other.get("permissionDecision") != "deny":
33611
+ report(f"{label} verify pushing rtl's design branch was {other!r}, not deny.")
33612
+ return 1
33613
+ if "rtl" not in other.get("permissionDecisionReason", ""):
33614
+ report(f"{label} the refusal does not name the role that may push it: {other!r}")
33615
+ return 1
33616
+ if decide(verify, "git push origin review-x").get("permissionDecision") != "pass":
33617
+ report(f"{label} verify's review branch, granted by the ver* pattern, was not allowed.")
33618
+ return 1
33619
+ unnamed = decide(verify, "git push origin design-x", role="spec")
33620
+ if unnamed.get("permissionDecision") != "deny":
33621
+ report(f"{label} a role no entry names was left unlimited: {unnamed!r}")
33622
+ return 1
33623
+ if decide(rtl, "git push origin HEAD:main").get("permissionDecision") != "ask":
33624
+ report(f"{label} rtl, matching main@rt*, was not asked about main.")
33625
+ return 1
33626
+ if decide(verify, "git push origin HEAD:main").get("permissionDecision") != "deny":
33627
+ report(f"{label} verify's push to main@rt* was not refused.")
33628
+ return 1
33629
+
33630
+ write_authorize_config(rtl, "authorize:\n - issue:acme/widgets@Not A Role\n")
33631
+ bad = run_keel(rtl, "--doctor", env=env)
33632
+ if bad.returncode == 0:
33633
+ report(f"{label} a malformed role pattern was accepted: {bad.stdout}")
33634
+ return 1
33635
+ if "issue:acme/widgets@Not A Role" not in bad.stdout:
33636
+ report(f"{label} the refusal does not name the entry: {bad.stdout}")
33637
+ return 1
33638
+ if "authorize-role-scoped" not in {name for name, _ in SCENARIOS}:
33639
+ report(f"{label} scenario is not registered.")
33640
+ return 1
33641
+ report("authorize-role-scoped scenario passed.")
33642
+ return 0
33643
+
33644
+
33473
33645
  def validate_push_protected_guard_scenario() -> int:
33474
33646
  """Issue #280: a protected push is asked, never stored, and role-limited.
33475
33647
 
@@ -42649,6 +42821,7 @@ SCENARIOS: tuple = (
42649
42821
  ("push-guard-redirects", validate_push_guard_redirects_scenario),
42650
42822
  ("push-guard-follow-tags", validate_push_guard_follow_tags_scenario),
42651
42823
  ("push-protected-guard", validate_push_protected_guard_scenario),
42824
+ ("authorize-role-scoped", validate_authorize_role_scoped_scenario),
42652
42825
  ("touch-guard-record-layer", validate_touch_guard_record_layer_scenario),
42653
42826
  ("repo-action-mode", validate_repo_action_mode_scenario),
42654
42827
  ("runner-skip-accounting", validate_runner_skip_accounting_scenario),
@@ -71,17 +71,27 @@ const AUTHORIZATION_SCOPES = {
71
71
  // Branch-name characters and `*`; `*` matches within one `/` segment and
72
72
  // `**` across them, as Touch globs do.
73
73
  push: { form: "<branch glob>", pattern: /^[A-Za-z0-9._/*-]+$/ },
74
- "push-protected": { form: "<branch glob>[@<role>]", pattern: /^[A-Za-z0-9._/*-]+(?:@[a-z0-9][a-z0-9-]{0,31})?$/ },
74
+ "push-protected": { form: "<branch glob>", pattern: /^[A-Za-z0-9._/*-]+$/ },
75
75
  };
76
76
 
77
+ // `@<role pattern>` after any scope (#378): chat-role characters and `*`,
78
+ // which matches any run of them. Only a session of a matching role reads it.
79
+ const AUTHORIZATION_ROLE_PATTERN = /^[a-z0-9*][a-z0-9*-]{0,31}$/;
80
+
81
+ function roleMatches(pattern, role) {
82
+ if (!role) return false;
83
+ // The pattern is checked to hold only `[a-z0-9-]` and `*`, so each part is a literal.
84
+ return new RegExp(`^${String(pattern).split("*").join("[a-z0-9-]*")}$`).test(role);
85
+ }
86
+
77
87
  // How the accepted names are spelled back to an author: the scoped ones carry
78
88
  // their form, so the list is copyable rather than a name the next message
79
89
  // refuses.
80
90
  const STANDING_AUTHORIZATION_ACCEPTED_FORMS = STANDING_AUTHORIZATION_ACTIONS.flatMap(
81
91
  (action) => {
82
- if (SCOPED_AUTHORIZATION_ACTIONS.has(action)) return [`${action}:${AUTHORIZATION_SCOPES[action].form}`];
92
+ if (SCOPED_AUTHORIZATION_ACTIONS.has(action)) return [`${action}:${AUTHORIZATION_SCOPES[action].form}[@<role>]`];
83
93
  if (OPTIONALLY_SCOPED_AUTHORIZATION_ACTIONS.has(action)) {
84
- return [action, `${action}:${AUTHORIZATION_SCOPES[action].form}`];
94
+ return [action, `${action}:${AUTHORIZATION_SCOPES[action].form}[@<role>]`];
85
95
  }
86
96
  return [action];
87
97
  }
@@ -105,10 +115,35 @@ function classifyAuthorizationEntry(entry) {
105
115
  return { ok: true, entry, action, scope: null };
106
116
  }
107
117
  if (scope === null) return { ok: false, entry, action, reason: "missing-scope" };
108
- if (!AUTHORIZATION_SCOPES[action].pattern.test(scope)) {
118
+ const at = scope.lastIndexOf("@");
119
+ const bare = at === -1 ? scope : scope.slice(0, at);
120
+ const role = at === -1 ? null : scope.slice(at + 1);
121
+ if (!AUTHORIZATION_SCOPES[action].pattern.test(bare)) {
109
122
  return { ok: false, entry, action, reason: "malformed-scope" };
110
123
  }
111
- return { ok: true, entry, action, scope };
124
+ if (role !== null && !AUTHORIZATION_ROLE_PATTERN.test(role)) {
125
+ return { ok: false, entry, action, reason: "malformed-role" };
126
+ }
127
+ // `push-protected` keeps its role in the scope it prints, as before (#280).
128
+ return { ok: true, entry, action, scope: action === "push-protected" ? scope : bare, role };
129
+ }
130
+
131
+ // The chat role of the session reading the declaration (#378 D2): the
132
+ // override, else the worktree's binding, read through any rename.
133
+ function sessionChatRole(repo) {
134
+ for (const variable of ["KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE"]) {
135
+ const value = (process.env[variable] || "").trim();
136
+ if (value) return value;
137
+ }
138
+ try {
139
+ const store = require("./chat/store");
140
+ const where = store.locate(repo);
141
+ if (!where) return null;
142
+ const bound = store.readRoles(where.root)[where.worktree];
143
+ return bound ? store.canonicalRole(where.root, bound) : null;
144
+ } catch {
145
+ return null;
146
+ }
112
147
  }
113
148
 
114
149
  // The closed vocabulary of capability tiers a repository may declare for a
@@ -301,6 +336,13 @@ function standingAuthorizationUnknownMessage(unknown, problems = []) {
301
336
  // names are ... issue" beside "unrecognized action: issue" would contradict
302
337
  // itself. Name what is missing instead, and why this one name carries it.
303
338
  for (const problem of problems) {
339
+ if (problem.reason === "malformed-role") {
340
+ notes.push(
341
+ `\`${problem.entry}\` ends in a role pattern that is not chat-role characters — `
342
+ + "lowercase letters, digits, and hyphens — with `*` matching any run of them."
343
+ );
344
+ continue;
345
+ }
304
346
  if (problem.reason === "mixed-push") {
305
347
  notes.push(
306
348
  `\`push\` and ${problem.scoped.map((entry) => `\`${entry}\``).join(", ")} are `
@@ -365,7 +407,12 @@ function standingAuthorizationUnknownMessage(unknown, problems = []) {
365
407
  return notes.length === 0 ? base : `${base} ${notes.join(" ")}`;
366
408
  }
367
409
 
368
- function readStandingAuthorization(repo) {
410
+ function readStandingAuthorization(repo, options = {}) {
411
+ const role = Object.prototype.hasOwnProperty.call(options, "role") ? options.role : sessionChatRole(repo);
412
+ // Entries for other roles (#378 D2): read, checked, and left out of what
413
+ // this session is granted; `push-protected` prints its own role instead.
414
+ const otherRoles = [];
415
+ const entries = [];
369
416
  const declared = [];
370
417
  const unknown = [];
371
418
  const problems = [];
@@ -379,6 +426,11 @@ function readStandingAuthorization(repo) {
379
426
  for (const entry of configList(repo, "authorize")) {
380
427
  const classified = classifyAuthorizationEntry(entry);
381
428
  if (classified.ok) {
429
+ entries.push(classified);
430
+ if (classified.role && classified.action !== "push-protected" && !roleMatches(classified.role, role)) {
431
+ otherRoles.push(entry);
432
+ continue;
433
+ }
382
434
  declared.push(entry);
383
435
  if (!scopes.has(classified.action)) scopes.set(classified.action, classified.scope);
384
436
  if (classified.action === "chat-reply" && !chatReplyGroups.includes(classified.scope)) {
@@ -403,11 +455,12 @@ function readStandingAuthorization(repo) {
403
455
  protectedPushes.push(classified.scope);
404
456
  }
405
457
  }
406
- if ((pushGlobs.length || protectedPushes.length) && declared.includes("push")) {
458
+ const anyScopedPush = entries.some((e) => (e.action === "push" && e.scope !== null) || e.action === "push-protected");
459
+ if (anyScopedPush && declared.includes("push")) {
407
460
  unknown.push("push");
408
461
  problems.push({
409
462
  reason: "mixed-push", entry: "push", action: "push",
410
- scoped: [...pushGlobs.map((glob) => `push:${glob}`), ...protectedPushes.map((scope) => `push-protected:${scope}`)],
463
+ scoped: entries.filter((e) => (e.action === "push" && e.scope !== null) || e.action === "push-protected").map((e) => e.entry),
411
464
  });
412
465
  }
413
466
  if (unknown.length > 0) {
@@ -417,6 +470,9 @@ function readStandingAuthorization(repo) {
417
470
  chatReplyGroups: [],
418
471
  pushGlobs: [],
419
472
  protectedPushes: [],
473
+ otherRoles: [],
474
+ entries: [],
475
+ role,
420
476
  unknown,
421
477
  message: standingAuthorizationUnknownMessage(unknown, problems),
422
478
  };
@@ -424,7 +480,7 @@ function readStandingAuthorization(repo) {
424
480
  if (chatReplyGroups.length) scopes.set("chat-reply", chatReplyGroups.join(", "));
425
481
  if (pushGlobs.length) scopes.set("push", pushGlobs.join(", "));
426
482
  if (protectedPushes.length) scopes.set("push-protected", protectedPushes.join(", "));
427
- return { declared, scopes, chatReplyGroups, pushGlobs, protectedPushes, unknown, message: null };
483
+ return { declared, scopes, chatReplyGroups, pushGlobs, protectedPushes, otherRoles, entries, role, unknown, message: null };
428
484
  }
429
485
 
430
486
  // `full_mode_paths:` — the paths whose change always routes Full, whatever the
@@ -1018,6 +1074,7 @@ module.exports = {
1018
1074
  executorTierUnreadableMessage,
1019
1075
  readPrecedentStore,
1020
1076
  readStandingAuthorization,
1077
+ roleMatches,
1021
1078
  readTriagePolicy,
1022
1079
  triageIssue,
1023
1080
  };
package/src/core/shift.js CHANGED
@@ -475,14 +475,16 @@ function ready(where, options) {
475
475
  store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
476
476
  }
477
477
  }
478
- // A CLI session cannot clear itself: `keel tick` stops it once idle and
479
- // starts the next (#357 D1), so nothing waits for a clear.
478
+ // A CLI session cannot clear itself: its hand-over stops it once it has
479
+ // finished and starts the next (#357 D1), so nothing waits for a clear. A
480
+ // waiter carries it out within seconds; `keel tick` stays as the fallback (#388 D1).
480
481
  const queued = options.wake && cli ? queueHandOff(where, role, cli) : null;
481
- const waiter = options.wake && !queued ? armWake(where, role, since) : null;
482
+ const waiter = options.wake && !queued ? armWake(where, role, since) : queued ? armHandOver(where, role) : null;
482
483
  return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, queued, startedBy: role ? null : options.forceReason, desktop, pid, cli, worktree: where.worktree };
483
484
  }
484
485
 
485
486
  // --- the CLI hand-off queue (#357) --------------------------------------------------
487
+ // `ready --wake` queues an entry; the waiter it leaves and `keel tick` both carry it out (#388).
486
488
 
487
489
  function queueFile(where, role) {
488
490
  return path.join(shiftDir(where), "queue", `${role}.json`);
@@ -501,50 +503,146 @@ function handOffs(where) {
501
503
 
502
504
  const SHIFT_START_TEXT = (role) => `${role}: your new shift starts now. Run keel context, then keel shift resume.`;
503
505
 
504
- // One step of the waker (#357 D2): a busy old session waits; an idle or gone
505
- // one is stopped (kept: \`claude attach\` reopens it) and a new session starts.
506
- function handOver(where) {
507
- const { readShiftDeclaration } = require("./config");
508
- const claude = process.env.KEEL_CLAUDE || "claude";
509
- const pending = handOffs(where).filter((entry) => entry.state === "pending");
510
- if (!pending.length) return [];
511
- const listed = spawnSync(claude, ["agents", "--json"], { encoding: "utf8" });
512
- let sessions = [];
506
+ // The old session has finished when it is gone, or is not busy and its job
507
+ // state is not a turn in progress: a session blocked on a question to the owner
508
+ // reads `idle` with state `working`, and stopping it cuts the conversation off (#388).
509
+ function finished(row) {
510
+ if (!row) return true;
511
+ if (row.status === "busy") return false;
512
+ return !row.state || ["done", "idle", "stopped"].includes(row.state);
513
+ }
514
+
515
+ function listAgents(claude) {
516
+ const listed = spawnSync(claude, ["agents", "--json", "--all"], { encoding: "utf8" });
517
+ try {
518
+ const parsed = JSON.parse(listed.stdout);
519
+ return listed.status === 0 && Array.isArray(parsed) ? parsed : null;
520
+ } catch {
521
+ return null;
522
+ }
523
+ }
524
+
525
+ // Stop the old session, give it a name that says it shifted, stop it again. The
526
+ // rename is a resume with `/rename` and no other flag, which keeps the session id
527
+ // and shows in `claude agents` (measured 2026-10-19); it is best effort (#388 D4).
528
+ function retire(claude, entry, row) {
529
+ const id = row.id || entry.session.slice(0, 8);
530
+ if (row.state !== "stopped") spawnSync(claude, ["stop", id], { encoding: "utf8" });
531
+ const stamp = store.isoLocal(new Date()).slice(0, 16).replace("T", " ");
532
+ const name = `${entry.role} · shifted ${stamp}`;
533
+ spawnSync(claude, ["--bg", "--resume", entry.session, `/rename ${name}`], { encoding: "utf8", cwd: row.cwd || entry.worktree });
534
+ const deadline = Date.now() + envMs("KEEL_SHIFT_RENAME_WAIT_MS", 30000);
535
+ const pause = new Int32Array(new SharedArrayBuffer(4));
536
+ let shown = false;
537
+ for (;;) {
538
+ const now = (listAgents(claude) || []).find((item) => item && item.sessionId === entry.session);
539
+ shown = Boolean(now && now.name === name);
540
+ if (shown || Date.now() >= deadline) break;
541
+ Atomics.wait(pause, 0, 0, 500);
542
+ }
543
+ spawnSync(claude, ["stop", id], { encoding: "utf8" });
544
+ return shown ? name : null;
545
+ }
546
+
547
+ // One runner at a time per role (#388 D2): the waiter and the tick both carry
548
+ // hand-overs out, and a lock younger than two minutes is the other's.
549
+ function withHandOverLock(where, role, fn) {
550
+ const file = path.join(shiftDir(where), "queue", `${role}.lock`);
513
551
  try {
514
- sessions = JSON.parse(listed.stdout);
552
+ if (Date.now() - fs.statSync(file).mtimeMs > 2 * 60 * 1000) fs.unlinkSync(file);
515
553
  } catch {
516
- sessions = [];
554
+ // no lock yet
555
+ }
556
+ let fd;
557
+ try {
558
+ fd = fs.openSync(file, "wx");
559
+ } catch {
560
+ return null;
561
+ }
562
+ try {
563
+ return fn();
564
+ } finally {
565
+ fs.closeSync(fd);
566
+ try {
567
+ fs.unlinkSync(file);
568
+ } catch {
569
+ // already gone
570
+ }
517
571
  }
572
+ }
573
+
574
+ // One step of the waker (#357 D2): a busy or unfinished old session waits; a
575
+ // finished or gone one is retired (kept: \`claude attach\` reopens it) and a new
576
+ // session starts. `only` limits the step to one role (the waiter's).
577
+ function handOver(where, only = null) {
578
+ const { readShiftDeclaration } = require("./config");
579
+ const claude = process.env.KEEL_CLAUDE || "claude";
580
+ const pending = handOffs(where).filter((entry) => entry.state === "pending" && (!only || entry.role === only));
581
+ if (!pending.length) return [];
582
+ const sessions = listAgents(claude);
583
+ // A listing that failed says nothing about the old session: wait for the next step.
584
+ if (!sessions) return [];
518
585
  const done = [];
519
- for (const entry of pending) {
520
- const row = (Array.isArray(sessions) ? sessions : []).find((item) => item && item.sessionId === entry.session);
521
- if (row && row.status === "busy") continue;
522
- // `stop`, `attach` and `logs` take the 8-character job id, not the full
523
- // session id (`No job matching`, measured 2026-10-19).
524
- if (row) spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8" });
525
- const mode = readShiftDeclaration(entry.worktree).permissionMode;
526
- const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
527
- cwd: entry.worktree, encoding: "utf8",
586
+ for (const queued of pending) {
587
+ const ran = withHandOverLock(where, queued.role, () => {
588
+ const entry = store.readJsonFile(queueFile(where, queued.role));
589
+ if (!entry || entry.state !== "pending") return null;
590
+ const row = sessions.find((item) => item && item.sessionId === entry.session);
591
+ if (!finished(row)) return null;
592
+ // `stop`, `attach` and `logs` take the 8-character job id, not the full
593
+ // session id (`No job matching`, measured 2026-10-19).
594
+ if (row) entry.renamed = retire(claude, entry, row);
595
+ const mode = readShiftDeclaration(entry.worktree).permissionMode;
596
+ const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
597
+ cwd: entry.worktree, encoding: "utf8",
598
+ });
599
+ const output = `${started.stdout || ""}`;
600
+ if (!started.error && started.status === 0) {
601
+ const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
602
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
603
+ } else {
604
+ const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
605
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
606
+ }
607
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
608
+ return entry;
528
609
  });
529
- const output = `${started.stdout || ""}`;
530
- if (!started.error && started.status === 0) {
531
- const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
532
- Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
533
- } else {
534
- const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
535
- Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
536
- }
537
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
538
- done.push(entry);
610
+ if (ran) done.push(ran);
539
611
  }
540
612
  return done;
541
613
  }
542
614
 
615
+ // `ready --wake` on the CLI leaves this waiter (#388 D1). Its working directory
616
+ // is `/`, so `check` never counts it, and its environment has none of the old
617
+ // session's `CLAUDE*` variables, which the claude it starts must not inherit.
618
+ function armHandOver(where, role) {
619
+ const keel = path.resolve(__dirname, "..", "..", "bin", "keel.js");
620
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("CLAUDE")));
621
+ const child = spawn(process.execPath, [keel, "shift", "handover-wait", "--role", role, "--repo", where.worktree],
622
+ { detached: true, stdio: "ignore", cwd: path.parse(where.worktree).root, env });
623
+ child.unref();
624
+ return child.pid;
625
+ }
626
+
627
+ function waitForHandOver(where, role) {
628
+ const poll = envMs("KEEL_SHIFT_HANDOVER_POLL_MS", 3000);
629
+ const deadline = Date.now() + envMs("KEEL_SHIFT_HANDOVER_TIMEOUT_MS", 2 * 60 * 60 * 1000);
630
+ const step = () => {
631
+ const entry = store.readJsonFile(queueFile(where, role));
632
+ if (!entry || entry.state !== "pending" || Date.now() > deadline) return;
633
+ handOver(where, role);
634
+ setTimeout(step, poll);
635
+ };
636
+ // `ready` has just run, so the session is still finishing its turn: look first after one interval.
637
+ setTimeout(step, poll);
638
+ }
639
+
543
640
  function describeHandOff(entry) {
544
641
  const tail = entry.state === "delivered"
545
642
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
546
643
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
547
- return `- ${entry.role}: ${tail}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
644
+ const renamed = entry.state === "delivered" ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
645
+ return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
548
646
  }
549
647
 
550
648
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
@@ -995,9 +1093,9 @@ const CLEAR_HINT = [
995
1093
  // or — without a chat role — the person who opens it.
996
1094
  function clearHint(result) {
997
1095
  if (result.queued) {
998
- return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session is idle, "
999
- + `\`keel tick\` stops it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1000
- + `in ${result.worktree} that runs \`keel shift resume\`. \`keel shift status\` shows the hand-off.`;
1096
+ return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session has finished, "
1097
+ + `a waiter stops it and renames it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1098
+ + `in ${result.worktree} that runs \`keel shift resume\`; \`keel tick\` does the same if the waiter is gone. \`keel shift status\` shows the hand-off.`;
1001
1099
  }
1002
1100
  let last;
1003
1101
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
@@ -1100,6 +1198,13 @@ function runShift(argv) {
1100
1198
  waitForWake(where, options.role, options.since);
1101
1199
  return 0;
1102
1200
  }
1201
+ case "handover-wait": {
1202
+ // Internal: the detached waiter `ready --wake` spawns in a CLI session.
1203
+ if (!options.role) throw new ShiftError("keel shift handover-wait needs --role.");
1204
+ store.checkName(options.role, "Role");
1205
+ waitForHandOver(where, options.role);
1206
+ return 0;
1207
+ }
1103
1208
  case "start": {
1104
1209
  if (!rest[0]) throw new ShiftError("keel shift start needs the role.");
1105
1210
  const { record, body, desktop } = start(where, rest[0], rest.slice(1).join(" "));