@christang/keel 5.198.0 → 5.199.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.198.0",
3
+ "version": "5.199.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.198.0 -->
1
+ <!-- keel:start version=5.199.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.198.0",
3
+ "version": "5.199.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.198.0",
9
+ "version": "5.199.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.198.0",
5
+ "version": "5.199.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.198.0",
3
+ "version": "5.199.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.198.0",
3
+ "version": "5.199.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",
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.198.0"
38
+ PACKAGE_VERSION = "5.199.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.198.0"
41
+ PROTOCOL_VERSION = "5.199.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -416,6 +416,7 @@ SCENARIOS: tuple = (
416
416
  ("shift-self-wake", shift.validate_shift_self_wake_scenario),
417
417
  ("shift-cli-self-shift", shift.validate_shift_cli_self_shift_scenario),
418
418
  ("shift-cli-keeps-old-sessions", shift.validate_shift_cli_keeps_old_sessions_scenario),
419
+ ("shift-resume-removes-old-sessions", shift.validate_shift_resume_removes_old_sessions_scenario),
419
420
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
420
421
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
421
422
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
@@ -3742,9 +3742,20 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
3742
3742
  # #418 (owner, 2026-10-21): no declaration keeps none, so the shift just handed over leaves the
3743
3743
  # session list too; a value that is not a whole number is named and none are kept.
3744
3744
  for keep in (None, "many"):
3745
- olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"])]
3745
+ # #462: after a rename a session's working directory names no bound worktree; Keel's copy of its
3746
+ # transcript under verify still makes it verify's, and one kept under no role stays.
3747
+ moved, stray = old_row(7, str(base / "renamed-away" / "verify")), old_row(8, str(base / "renamed-away" / "other"))
3748
+ (kept_dir / f"{moved['sessionId']}.jsonl.gz").write_bytes(gzip.compress(b'{"type": "user"}\n'))
3749
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"]), moved, stray]
3746
3750
  setup(keep, olds)
3747
3751
  ids = sorted(r["argv"][1] for r in removed())
3752
+ if "07070707" not in ids:
3753
+ report(f"{label} a session of verify's from a missing worktree stayed: {ids!r}")
3754
+ return 1
3755
+ if "08080808" in ids:
3756
+ report(f"{label} a session from a missing worktree kept under no role was removed: {ids!r}")
3757
+ return 1
3758
+ ids = [i for i in ids if i != "07070707"]
3748
3759
  if ids != sorted(["01010101", "02020202", "04040404", OLD[:8]]):
3749
3760
  report(f"{label} the default keeps the wrong number of old sessions (keep_old_sessions {keep!r}): removed {ids!r}")
3750
3761
  return 1
@@ -3764,6 +3775,139 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
3764
3775
  return 0
3765
3776
 
3766
3777
 
3778
+ def validate_shift_resume_removes_old_sessions_scenario() -> int:
3779
+ """Issue #462 (owner, 2026-10-25): a takeover Keel did not carry out left the old shift listed.
3780
+
3781
+ After the workspace rename the owner opened a session by hand and it ran
3782
+ `keel shift resume`; only a delivered hand-over removed old sessions, and it
3783
+ matched them by a working directory the rename had moved. `resume` of a
3784
+ note a CLI session wrote, in a Claude Code session, now removes them as a
3785
+ hand-over does, and a session whose transcript Keel keeps under the role is
3786
+ the role's wherever it ran. It asks the host only when it may remove
3787
+ something.
3788
+ """
3789
+ label = "shift-resume-removes-old-sessions:"
3790
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
3791
+ NEW = "c0ffee00-1111-2222-3333-444444444444"
3792
+ MOVED = "07070707-0000-0000-0000-000000000007"
3793
+ with tempfile.TemporaryDirectory(prefix="keel-shift-462-") as raw:
3794
+ base = Path(raw)
3795
+ rtl, verify, env, _ = shift_scratch(base)
3796
+ calls, agents = base / "claude-calls.jsonl", base / "agents.json"
3797
+ config_dir = base / "claude-config"
3798
+ shift_root = mailbox_common_dir(rtl) / "keel-chat" / "shift"
3799
+ kept_dir = shift_root / "transcripts" / "verify"
3800
+ fake = base / "fake-claude"
3801
+ # The row shapes of shift-cli-keeps-old-sessions: a stopped row has no `status`; `rm` drops the row and
3802
+ # logs whether Keel's copy was there when it ran.
3803
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
3804
+ f"agents, kept = {str(agents)!r}, {str(kept_dir)!r}\n"
3805
+ "argv = sys.argv[1:]\n"
3806
+ "rows = json.loads(open(agents).read())\n"
3807
+ "record = {'argv': argv}\n"
3808
+ "if argv[:1] == ['rm']:\n"
3809
+ " gone = [row for row in rows if row['id'] == argv[1]]\n"
3810
+ " record['kept'] = bool(gone) and os.path.exists(os.path.join(kept, gone[0]['sessionId'] + '.jsonl.gz'))\n"
3811
+ " rows = [row for row in rows if row['id'] != argv[1]]\n"
3812
+ f"open({str(calls)!r}, 'a').write(json.dumps(record) + '\\n')\n"
3813
+ "if argv[:2] == ['agents', '--json']:\n print(json.dumps(rows)); sys.exit(0)\n"
3814
+ "open(agents, 'w').write(json.dumps(rows)); print('ok'); sys.exit(0)\n")
3815
+ fake.chmod(0o755)
3816
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir)}
3817
+ exited = subprocess.Popen(["true"])
3818
+ exited.wait()
3819
+ old_cli = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(exited.pid)}
3820
+ new_cli = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": NEW, "CLAUDE_PID": str(os.getpid())}
3821
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
3822
+ bound = {role: path for path, role in roles.items()}
3823
+ moved_cwd = str(base / "renamed-away" / "verify")
3824
+
3825
+ def transcript(cwd: str, session: str) -> None:
3826
+ project = config_dir / "projects" / re.sub(r"[^A-Za-z0-9]", "-", cwd)
3827
+ project.mkdir(parents=True, exist_ok=True)
3828
+ (project / f"{session}.jsonl").write_text(json.dumps(
3829
+ {"type": "user", "timestamp": "2026-10-21T01:00:00.000Z", "cwd": cwd, "message": {"role": "user", "content": "carry on"}}) + "\n",
3830
+ encoding="utf-8")
3831
+
3832
+ def row(session: str, cwd: str, n: int, **extra: object) -> dict:
3833
+ return {"kind": "background", "name": "verify", "sessionId": session, "id": session[:8], "state": "stopped",
3834
+ "cwd": cwd, "startedAt": 1792400000000 + n * 1000, **extra}
3835
+
3836
+ def readied(text: str) -> None:
3837
+ calls.write_text("")
3838
+ done = run_keel(verify, "shift", "ready", text, env=old_cli)
3839
+ if done.returncode != 0:
3840
+ raise RuntimeError(f"ready failed: {done.stdout} {done.stderr}")
3841
+
3842
+ def host_calls() -> list[list[str]]:
3843
+ return [json.loads(line)["argv"] for line in calls.read_text().splitlines()]
3844
+
3845
+ # The old shift and a pre-rename one Keel kept under verify are verify's; rtl's stopped session is not,
3846
+ # and the session running resume is live.
3847
+ transcript(bound["verify"], OLD)
3848
+ transcript(bound["rtl"], "05050505-0000-0000-0000-000000000005")
3849
+ kept_dir.mkdir(parents=True, exist_ok=True)
3850
+ (kept_dir / f"{MOVED}.jsonl.gz").write_bytes(gzip.compress(b'{"type": "user"}\n'))
3851
+ agents.write_text(json.dumps([
3852
+ row(MOVED, moved_cwd, 1), row("05050505-0000-0000-0000-000000000005", bound["rtl"], 5),
3853
+ row(OLD, bound["verify"], 8),
3854
+ row(NEW, bound["verify"], 9, status="busy", state="working", pid=os.getpid()),
3855
+ ]))
3856
+ readied("next: rerun R021")
3857
+ resumed = run_keel(verify, "shift", "resume", env=new_cli)
3858
+ if resumed.returncode != 0:
3859
+ report(f"{label} resume exited {resumed.returncode}: {resumed.stderr!r}")
3860
+ return 1
3861
+ if "next: rerun R021" not in resumed.stdout:
3862
+ report(f"{label} resume did not print the note: {resumed.stdout!r}")
3863
+ return 1
3864
+ gone = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
3865
+ if not gone:
3866
+ report(f"{label} resume removed no old session: {calls.read_text()!r}")
3867
+ return 1
3868
+ ids = sorted(r["argv"][1] for r in gone)
3869
+ if ids != sorted([OLD[:8], MOVED[:8]]):
3870
+ report(f"{label} resume removed {ids!r}, not the shift handed over and verify's session from a missing worktree.")
3871
+ return 1
3872
+ if not all(r["kept"] for r in gone):
3873
+ report(f"{label} a session was removed before Keel's store held its transcript: {gone!r}")
3874
+ return 1
3875
+ left = {r["id"] for r in json.loads(agents.read_text())}
3876
+ if left != {"05050505", NEW[:8]}:
3877
+ report(f"{label} rtl's session and the current one should stay, and the listed ones are {sorted(left)!r}")
3878
+ return 1
3879
+ for needle in (OLD[:8], MOVED[:8], "keel shift history verify --show"):
3880
+ if needle not in resumed.stdout:
3881
+ report(f"{label} resume does not name {needle!r}: {resumed.stdout!r}")
3882
+ return 1
3883
+
3884
+ # Outside a Claude Code host, and in the session Keel's own delivered hand-over started, there is nothing to
3885
+ # ask the host: the first runs no `claude`, and the hand-over already removed them.
3886
+ readied("next: rerun R022")
3887
+ plain = run_keel(verify, "shift", "resume", env=env)
3888
+ if "next: rerun R022" not in plain.stdout:
3889
+ report(f"{label} resume outside a Claude Code host did not print the note: {plain.stdout!r}")
3890
+ return 1
3891
+ if host_calls():
3892
+ report(f"{label} resume outside a Claude Code host called claude: {host_calls()!r}")
3893
+ return 1
3894
+ readied("next: rerun R023")
3895
+ write_text(shift_root / "queue" / "verify.json", json.dumps(
3896
+ {"role": "verify", "session": OLD, "worktree": bound["verify"], "state": "delivered", "new_session": NEW[:8]}))
3897
+ handed = run_keel(verify, "shift", "resume", env=new_cli)
3898
+ if "next: rerun R023" not in handed.stdout:
3899
+ report(f"{label} resume after a delivered hand-over did not print the note: {handed.stdout!r}")
3900
+ return 1
3901
+ if host_calls():
3902
+ report(f"{label} resume after a delivered hand-over called claude: {host_calls()!r}")
3903
+ return 1
3904
+ if "shift-resume-removes-old-sessions" not in {name for name, _ in registry.SCENARIOS}:
3905
+ report(f"{label} scenario is not registered.")
3906
+ return 1
3907
+ report("shift-resume-removes-old-sessions scenario passed.")
3908
+ return 0
3909
+
3910
+
3767
3911
  def validate_shift_history_show_scenario() -> int:
3768
3912
  """Issue #397 (owner, 2026-10-20): a shift no longer in `claude agents` can be read in full.
3769
3913
 
package/src/core/shift.js CHANGED
@@ -612,21 +612,24 @@ function keptCopyOf(where, role, transcript) {
612
612
  }
613
613
  }
614
614
 
615
- // After a delivered hand-over, the newest `keep` stopped background sessions in
616
- // the role's bound worktrees stay listed; each older one is removed with
617
- // `claude rm` once Keel's store holds its transcript (#397 D2). `claude rm`
618
- // leaves the host's transcript (F4). Only a session with a transcript, the
619
- // host's or Keel's copy, is a shift: one never given a prompt has neither, so
620
- // it takes no slot and stays (#401).
615
+ // After a delivered hand-over or a resume, the newest `keep` stopped background
616
+ // sessions of the role stay listed; each older one is removed with `claude rm`
617
+ // once Keel's store holds its transcript (#397 D2). `claude rm` leaves the
618
+ // host's transcript (F4). Only a session with a transcript, the host's or
619
+ // Keel's copy, is a shift: one never given a prompt has neither, so it takes no
620
+ // slot and stays (#401). A session is the role's when it ran in a bound
621
+ // worktree, or when Keel keeps its transcript under the role: a renamed or
622
+ // moved worktree leaves a `cwd` no binding names (#462 D2).
621
623
  function removeOldSessions(claude, where, entry, keep) {
622
624
  const bound = new Set(Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
623
625
  .filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
624
626
  const listed = listAgents(claude);
625
627
  if (!listed) return [];
626
628
  const { keptFile } = require("./chat/notice");
629
+ const roles = (row) => bound.has(realpath(row.cwd)) || fs.existsSync(keptFile(where, entry.role, `${row.sessionId}.jsonl`));
627
630
  const old = listed
628
- .filter((row) => row && row.kind === "background" && !row.status && row.cwd && bound.has(realpath(row.cwd))
629
- && row.sessionId && row.id !== entry.new_session)
631
+ .filter((row) => row && row.kind === "background" && !row.status && row.cwd && row.sessionId && roles(row)
632
+ && row.id !== entry.new_session)
630
633
  .map((row) => ({ row, transcript: hostTranscript(row.cwd, row.sessionId),
631
634
  kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) }))
632
635
  .filter(({ transcript, kept }) => transcript || fs.existsSync(kept))
@@ -1064,6 +1067,23 @@ function lastFetch(cwd) {
1064
1067
  }
1065
1068
  }
1066
1069
 
1070
+ // A takeover Keel did not carry out — a session opened by hand — removes the
1071
+ // old shift's sessions at resume, as a delivered hand-over does (#462 D1). It
1072
+ // asks the host only from a Claude Code session, for a note a CLI session
1073
+ // wrote, and not in the session a delivered hand-over started, which already
1074
+ // removed them.
1075
+ function removeAtResume(where, role, text) {
1076
+ const old = String(text).match(/^CLI session: (\S+)\.$/m);
1077
+ const current = process.env.CLAUDE_CODE_SESSION_ID || "";
1078
+ if (!old || !process.env.CLAUDE_CODE_ENTRYPOINT) return [];
1079
+ const queued = store.readJsonFile(queueFile(where, role));
1080
+ if (queued && queued.state === "delivered" && queued.new_session && current.startsWith(queued.new_session)) return [];
1081
+ const pid = String(text).match(/^CLI process: (\d+)\.$/m);
1082
+ const entry = { role, session: old[1], pid: pid ? Number(pid[1]) : null, new_session: current.slice(0, 8) || null };
1083
+ const { readShiftDeclaration } = require("./config");
1084
+ return removeOldSessions(process.env.KEEL_CLAUDE || "claude", where, entry, readShiftDeclaration(where.worktree).keepOldSessions);
1085
+ }
1086
+
1067
1087
  function resume(where, named = null) {
1068
1088
  const role = resumeRole(where, named);
1069
1089
  const note = waitingNote(where, role);
@@ -1087,7 +1107,7 @@ function resume(where, named = null) {
1087
1107
  ? store.post(where, { group, text, refs: [REF] })
1088
1108
  : store.writeRecord(where, { group, kind: "message", from: role, refs: [REF], text })).id;
1089
1109
  }
1090
- return { role, note: history, text, told, waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree) };
1110
+ return { role, note: history, text, told, removed: removeAtResume(where, role, text), waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree) };
1091
1111
  }
1092
1112
 
1093
1113
  function status(where) {
@@ -1557,7 +1577,10 @@ function runShift(argv) {
1557
1577
  ? `\n\nThis worktree is on ${merged.branch ? `\`${merged.branch}\`` : "a detached HEAD"}, already in ${merged.base} and `
1558
1578
  + `${merged.behind} commit${merged.behind === 1 ? "" : "s"} behind it: start new work from ${merged.base}.`
1559
1579
  : "";
1560
- out(result, `${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1580
+ const removed = (result.removed || []).length
1581
+ ? `\n\nRemoved old sessions from claude agents: ${result.removed.join(", ")}; \`keel shift history ${result.role} --show <id>\` prints each.`
1582
+ : "";
1583
+ out(result, `${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${removed}${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1561
1584
  return 0;
1562
1585
  }
1563
1586
  case "history": {