@christang/keel 5.156.0 → 5.157.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.156.0",
3
+ "version": "5.157.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,4 +1,4 @@
1
- <!-- keel:start version=5.156.0 -->
1
+ <!-- keel:start version=5.157.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.156.0",
3
+ "version": "5.157.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.156.0",
9
+ "version": "5.157.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.156.0",
5
+ "version": "5.157.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.156.0",
3
+ "version": "5.157.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.156.0",
3
+ "version": "5.157.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",
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.156.0"
53
- PROTOCOL_VERSION = "5.156.0"
52
+ PACKAGE_VERSION = "5.157.0"
53
+ PROTOCOL_VERSION = "5.157.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
@@ -7907,6 +7907,123 @@ def validate_shift_start_desktop_scenario() -> int:
7907
7907
  return 0
7908
7908
 
7909
7909
 
7910
+ def validate_shift_cli_self_shift_scenario() -> int:
7911
+ """Issue #357 on the CLI (owner, 2026-10-19): stop the old session, start a new one.
7912
+
7913
+ A CLI session cannot clear itself. `keel shift ready --wake` there queues
7914
+ the hand-off; `keel tick` waits until the old session is idle, stops it
7915
+ (kept: `claude attach` reopens it), and starts a new session in the role's
7916
+ worktree that runs `keel shift resume`. `keel shift status` shows the
7917
+ queue, and a failed start is a patrol risk.
7918
+ """
7919
+ label = "shift-cli-self-shift:"
7920
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
7921
+ with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
7922
+ base = Path(raw)
7923
+ rtl, verify, env, _ = shift_scratch(base)
7924
+ calls, agents, fail = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start"
7925
+ fake = base / "fake-claude"
7926
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
7927
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
7928
+ f"if sys.argv[1:3] == ['agents', '--json']:\n print(open({str(agents)!r}).read()); sys.exit(0)\n"
7929
+ 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"
7930
+ "if sys.argv[1:2] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
7931
+ "print('stopped')\n")
7932
+ fake.chmod(0o755)
7933
+ env = {**env, "KEEL_CLAUDE": str(fake)}
7934
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
7935
+
7936
+ def agents_status(status: str) -> None:
7937
+ # The measured shape: `sessionId` is the full id, `id` the job id `stop` and `attach` take.
7938
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
7939
+ "pid": os.getpid(), "status": status, "cwd": str(verify)}]))
7940
+
7941
+ def made(kind: str) -> list[dict]:
7942
+ rows = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
7943
+ return [r for r in rows if (r["argv"][:1] == ["stop"] if kind == "stop" else r["argv"][:1] == ["--bg"])]
7944
+
7945
+ def tick() -> subprocess.CompletedProcess[str]:
7946
+ return run_keel(verify, "tick", "--repo", str(rtl), env=env)
7947
+
7948
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
7949
+ if readied.returncode != 0:
7950
+ report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
7951
+ return 1
7952
+ if "keel tick" not in readied.stdout:
7953
+ report(f"{label} ready --wake in a CLI session does not say keel tick will hand over: {readied.stdout!r}")
7954
+ return 1
7955
+ note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
7956
+ if not note:
7957
+ report(f"{label} ready --wake stored no note for verify.")
7958
+ return 1
7959
+ if f"CLI session: {OLD}." not in note.read_text(encoding="utf-8"):
7960
+ report(f"{label} the note does not record the CLI session.")
7961
+ return 1
7962
+
7963
+ agents_status("busy")
7964
+ tick()
7965
+ if made("stop"):
7966
+ report(f"{label} a tick stopped the old session while it was busy: {made('stop')!r}")
7967
+ return 1
7968
+ if made("start"):
7969
+ report(f"{label} a tick started a session while the old one was busy: {made('start')!r}")
7970
+ return 1
7971
+ status = run_keel(rtl, "shift", "status", env=env).stdout
7972
+ if "pending" not in status:
7973
+ report(f"{label} shift status does not show the pending hand-off: {status!r}")
7974
+ return 1
7975
+
7976
+ agents_status("idle")
7977
+ tick()
7978
+ stops, starts = made("stop"), made("start")
7979
+ if [s["argv"] for s in stops] != [["stop", OLD[:8]]]:
7980
+ report(f"{label} the idle old session was not stopped once: {stops!r}")
7981
+ return 1
7982
+ if len(starts) != 1:
7983
+ report(f"{label} the new session was not started once: {starts!r}")
7984
+ return 1
7985
+ if starts[0]["argv"][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]:
7986
+ report(f"{label} the new session was not started as --bg -n verify --permission-mode auto: {starts!r}")
7987
+ return 1
7988
+ if "keel shift resume" not in starts[0]["argv"][-1]:
7989
+ report(f"{label} the new session's prompt does not name keel shift resume: {starts[0]['argv']!r}")
7990
+ return 1
7991
+ if "--resume" in starts[0]["argv"]:
7992
+ report(f"{label} the new session resumes an old one instead of starting fresh: {starts[0]['argv']!r}")
7993
+ return 1
7994
+ if os.path.realpath(starts[0]["cwd"]) != os.path.realpath(verify):
7995
+ report(f"{label} the new session started in {starts[0]['cwd']}, not verify's worktree.")
7996
+ return 1
7997
+ status = run_keel(rtl, "shift", "status", env=env).stdout
7998
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}"):
7999
+ if needle not in status:
8000
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {status!r}")
8001
+ return 1
8002
+ tick()
8003
+ if len(made("start")) != 1:
8004
+ report(f"{label} a second tick started another session.")
8005
+ return 1
8006
+
8007
+ # A start that fails stays visible and is a patrol risk.
8008
+ fail.write_text("x")
8009
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env=cli_env)
8010
+ tick()
8011
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8012
+ for needle in ("failed", "Workspace not trusted"):
8013
+ if needle not in status:
8014
+ report(f"{label} a failed start does not show {needle!r}: {status!r}")
8015
+ return 1
8016
+ patrolled = run_keel(rtl, "patrol", env=env).stdout
8017
+ if not re.search(r"risk: .*verify.*hand-off", patrolled):
8018
+ report(f"{label} the patrol does not report the failed hand-off as a risk: {patrolled!r}")
8019
+ return 1
8020
+ if "shift-cli-self-shift" not in {name for name, _ in SCENARIOS}:
8021
+ report(f"{label} scenario is not registered.")
8022
+ return 1
8023
+ report("shift-cli-self-shift scenario passed.")
8024
+ return 0
8025
+
8026
+
7910
8027
  def validate_shift_desktop_wake_overdue_scenario() -> int:
7911
8028
  """`keel shift status` flags a desktop note whose wake is overdue.
7912
8029
 
@@ -42304,6 +42421,7 @@ SCENARIOS: tuple = (
42304
42421
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
42305
42422
  ("shift-self", validate_shift_self_scenario),
42306
42423
  ("shift-self-wake", validate_shift_self_wake_scenario),
42424
+ ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
42307
42425
  ("owner-language", validate_owner_language_scenario),
42308
42426
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42309
42427
  ("shift-history", validate_shift_history_scenario),
@@ -965,6 +965,16 @@ function readPatrolDeclaration(repo) {
965
965
  return { declared: true, role: block.role, every: block.every, hostTask, model, message, cadence, runner };
966
966
  }
967
967
 
968
+ // `shift: permission_mode:` for the session a CLI hand-off starts (#357 D5).
969
+ const PERMISSION_MODES = ["default", "acceptEdits", "auto", "plan", "bypassPermissions"];
970
+ function readShiftDeclaration(repo) {
971
+ const block = configMap(repo, "shift");
972
+ const mode = block.permission_mode;
973
+ if (mode === undefined) return { permissionMode: "auto", message: null };
974
+ if (PERMISSION_MODES.includes(mode)) return { permissionMode: mode, message: null };
975
+ return { permissionMode: "auto", message: `keel/config.yaml shift: permission_mode \`${mode}\` is not one of ${PERMISSION_MODES.join(", ")}, so it is ignored.` };
976
+ }
977
+
968
978
  function durationSeconds(value) {
969
979
  const match = String(value || "").match(/^(\d+)([smhd])$/);
970
980
  return match ? Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2]] : null;
@@ -987,6 +997,7 @@ module.exports = {
987
997
  readOwnerLanguage,
988
998
  ownerLanguageRule,
989
999
  readPatrolDeclaration,
1000
+ readShiftDeclaration,
990
1001
  durationSeconds,
991
1002
  patrolReminder,
992
1003
  readIssueRoles,
@@ -497,6 +497,8 @@ function runPatrol(argv) {
497
497
  result.risks = [];
498
498
  const quota = quotaRisk(where, options);
499
499
  if (quota) result.risks.push(quota);
500
+ // A CLI hand-off that failed or hangs (#357 D4).
501
+ result.risks.push(...require("./shift").handOffRisks(where));
500
502
  // Near the limit nudges stop, since each wakes a large session (D3).
501
503
  const quiet = options.quota !== null && options.quota >= options.quotaQuietAt;
502
504
  if (options.nudge && quiet) result.paused = `nudges paused: quota at ${options.quota}%`;
package/src/core/shift.js CHANGED
@@ -375,6 +375,14 @@ function desktopSession() {
375
375
  return process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" && id ? id : null;
376
376
  }
377
377
 
378
+ // The Claude Code CLI session's id and process, or null elsewhere (#357 D1).
379
+ function cliSession() {
380
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
381
+ if (process.env.CLAUDE_CODE_ENTRYPOINT !== "cli" || !id) return null;
382
+ const pid = Number(process.env.CLAUDE_PID);
383
+ return { session: id, pid: Number.isInteger(pid) && pid > 1 ? pid : null };
384
+ }
385
+
378
386
  // The desktop session's Claude process: the nearest ancestor whose command's
379
387
  // basename is `claude`. The app's clear stops it, which is what the wake
380
388
  // waits for (D1 of shift-desktop-wake-in-a-minute).
@@ -437,12 +445,15 @@ function ready(where, options) {
437
445
  const stamp = store.isoLocal(new Date());
438
446
  const desktop = desktopSession();
439
447
  const pid = desktop ? desktopProcess() : null;
448
+ const cli = desktop ? null : cliSession();
440
449
  const head = [
441
450
  `# Shift note: ${role || path.basename(where.worktree)}`,
442
451
  "",
443
452
  `Written ${stamp} in ${result.worktree}.`,
444
453
  desktop ? `Desktop session: ${desktop}.` : "",
445
454
  desktop && pid ? `Desktop process: ${pid}.` : "",
455
+ cli ? `CLI session: ${cli.session}.` : "",
456
+ cli && cli.pid ? `CLI process: ${cli.pid}.` : "",
446
457
  // A shift the role started itself; the patrol may nudge it to resume (#307 D4).
447
458
  options.wake ? "Self-initiated: this shift armed `keel shift ready --wake`." : "",
448
459
  !role ? `Started by hand: ${options.forceReason}.` : "",
@@ -464,8 +475,83 @@ function ready(where, options) {
464
475
  store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
465
476
  }
466
477
  }
467
- const waiter = options.wake ? armWake(where, role, since) : null;
468
- return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, startedBy: role ? null : options.forceReason, desktop, pid, worktree: where.worktree };
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.
480
+ const queued = options.wake && cli ? queueHandOff(where, role, cli) : null;
481
+ const waiter = options.wake && !queued ? armWake(where, role, since) : null;
482
+ 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
+
485
+ // --- the CLI hand-off queue (#357) --------------------------------------------------
486
+
487
+ function queueFile(where, role) {
488
+ return path.join(shiftDir(where), "queue", `${role}.json`);
489
+ }
490
+
491
+ function queueHandOff(where, role, cli) {
492
+ const entry = { role, session: cli.session, pid: cli.pid, worktree: where.worktree, requested_at: store.isoLocal(new Date()), state: "pending" };
493
+ store.writeJsonAtomic(where, queueFile(where, role), entry);
494
+ return entry;
495
+ }
496
+
497
+ function handOffs(where) {
498
+ return safeList(path.join(shiftDir(where), "queue")).filter((name) => name.endsWith(".json")).sort()
499
+ .map((name) => store.readJsonFile(path.join(shiftDir(where), "queue", name))).filter((entry) => entry && entry.role);
500
+ }
501
+
502
+ const SHIFT_START_TEXT = (role) => `${role}: your new shift starts now. Run keel context, then keel shift resume.`;
503
+
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 = [];
513
+ try {
514
+ sessions = JSON.parse(listed.stdout);
515
+ } catch {
516
+ sessions = [];
517
+ }
518
+ 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",
528
+ });
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);
539
+ }
540
+ return done;
541
+ }
542
+
543
+ function describeHandOff(entry) {
544
+ const tail = entry.state === "delivered"
545
+ ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
546
+ : 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)}\``;
548
+ }
549
+
550
+ // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
551
+ function handOffRisks(where, now = Date.now()) {
552
+ return handOffs(where).filter((entry) => entry.state === "failed"
553
+ || (entry.state === "pending" && now - Date.parse(entry.requested_at) > 15 * 60 * 1000))
554
+ .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}` : ` since ${entry.requested_at}`}; see \`keel shift status\``);
469
555
  }
470
556
 
471
557
  // --- the one-shot wake (#293) -------------------------------------------------------
@@ -908,6 +994,11 @@ const CLEAR_HINT = [
908
994
  // Who starts the new session (#293 D3): the coordinator that asked, nobody,
909
995
  // or — without a chat role — the person who opens it.
910
996
  function clearHint(result) {
997
+ 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.`;
1001
+ }
911
1002
  let last;
912
1003
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
913
1004
  else if (result.waiter && result.desktop) {
@@ -1073,7 +1164,10 @@ function runShift(argv) {
1073
1164
  }
1074
1165
  case "status": {
1075
1166
  const rows = status(where);
1076
- out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");
1167
+ const queue = handOffs(where);
1168
+ const text = [rows.length ? rows.map(describe).join("\n") : "No shift change recorded.",
1169
+ ...(queue.length ? ["", "Hand-offs (CLI, run by `keel tick`):", ...queue.map(describeHandOff)] : [])].join("\n");
1170
+ out({ roles: rows, handOffs: queue }, text);
1077
1171
  return 0;
1078
1172
  }
1079
1173
  default:
@@ -1100,4 +1194,4 @@ function waitingFor(repo) {
1100
1194
  }
1101
1195
 
1102
1196
  module.exports = {
1103
- desktopProcess, foundTranscripts, check, describe, runShift, shiftStatus: status, waitingFor };
1197
+ desktopProcess, foundTranscripts, handOver, handOffRisks, check, describe, runShift, shiftStatus: status, waitingFor };
package/src/core/tick.js CHANGED
@@ -66,6 +66,7 @@ function tick(where, now = new Date()) {
66
66
  const result = { patrol: null, woken: [] };
67
67
  const wakeState = readState(where);
68
68
  result.woken = wakeEnded(where, wakeState);
69
+ result.handedOver = require("./shift").handOver(where);
69
70
  if (result.woken.length) store.writeJsonAtomic(where, stateFile(where), { ...readState(where), woken: wakeState.woken });
70
71
  const found = patrolWorktree(where);
71
72
  if (!found.worktree) {
@@ -103,7 +104,8 @@ function tick(where, now = new Date()) {
103
104
 
104
105
  function render(result) {
105
106
  const woke = (result.woken || []).map((w) => `keel tick: ${w.ok ? "resumed" : "could not resume"} ${w.role}'s CLI session ${w.session} for ${w.record}`);
106
- return [...woke, renderPatrol(result)].join("\n");
107
+ const handed = (result.handedOver || []).map((h) => `keel tick: ${h.role}'s hand-off ${h.state}${h.new_session ? ` as session ${h.new_session}` : ""}${h.error ? `: ${h.error}` : ""}`);
108
+ return [...handed, ...woke, renderPatrol(result)].join("\n");
107
109
  }
108
110
 
109
111
  function renderPatrol(result) {