@christang/keel 5.168.0 → 5.170.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.168.0",
3
+ "version": "5.170.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.168.0 -->
1
+ <!-- keel:start version=5.170.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.168.0",
3
+ "version": "5.170.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.168.0",
9
+ "version": "5.170.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.168.0",
5
+ "version": "5.170.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.168.0",
3
+ "version": "5.170.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.168.0",
3
+ "version": "5.170.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",
@@ -51,8 +51,8 @@ REQUIRED_SCRIPTS = [
51
51
  "scripts/validate_plugin.py",
52
52
  ]
53
53
 
54
- PACKAGE_VERSION = "5.168.0"
55
- PROTOCOL_VERSION = "5.168.0"
54
+ PACKAGE_VERSION = "5.170.0"
55
+ PROTOCOL_VERSION = "5.170.0"
56
56
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
57
57
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
58
58
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8454,8 +8454,9 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
8454
8454
  After a delivered hand-over, the newest `shift: keep_old_sessions:`
8455
8455
  (default 3) stopped background sessions in the role's bound worktrees stay
8456
8456
  listed; each older one is removed with `claude rm` once Keel's store holds
8457
- a copy of its transcript. One whose transcript is nowhere stays, and so do
8458
- another role's sessions and the new one.
8457
+ a copy of its transcript. Only a session with a transcript, the host's or
8458
+ Keel's copy, counts (#401): one whose transcript is nowhere takes no slot and
8459
+ stays, and so do another role's sessions and the new one.
8459
8460
  """
8460
8461
  label = "shift-cli-keeps-old-sessions:"
8461
8462
  OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
@@ -8529,22 +8530,28 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
8529
8530
  def removed() -> list[dict]:
8530
8531
  return [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
8531
8532
 
8532
- olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(3, bound["verify"], with_transcript=False),
8533
- old_row(4, bound["verify"]), old_row(5, bound["rtl"])]
8533
+ # #401: a session never given a prompt has no transcript and is not a shift, so it takes no kept slot even
8534
+ # when it is newer than the others; one whose host transcript is gone but Keel holds a copy still counts.
8535
+ copy_only = old_row(1, bound["verify"], with_transcript=False)
8536
+ kept_dir.mkdir(parents=True, exist_ok=True)
8537
+ (kept_dir / f"{copy_only['sessionId']}.jsonl.gz").write_bytes(gzip.compress(b'{"type": "user"}\n'))
8538
+ olds = [copy_only, old_row(2, bound["verify"]), old_row(3, bound["verify"]), old_row(4, bound["verify"]),
8539
+ old_row(6, bound["verify"], with_transcript=False), old_row(5, bound["rtl"])]
8534
8540
  setup("2", olds)
8535
8541
  gone = removed()
8536
8542
  if not gone:
8537
8543
  report(f"{label} the hand-over removed no old session: {calls.read_text()!r}")
8538
8544
  return 1
8539
8545
  ids = sorted(r["argv"][1] for r in gone)
8540
- if ids != ["01010101", "02020202"]:
8541
- report(f"{label} with keep_old_sessions 2 the removed sessions are {ids!r}, not the two oldest with a transcript.")
8546
+ if ids != ["01010101", "02020202", "03030303"]:
8547
+ report(f"{label} with keep_old_sessions 2 the removed sessions are {ids!r}, "
8548
+ "not the oldest beyond the two newest with a transcript.")
8542
8549
  return 1
8543
8550
  if not all(r["kept"] for r in gone):
8544
8551
  report(f"{label} a session was removed before Keel's store held its transcript: {gone!r}")
8545
8552
  return 1
8546
8553
  left = {row["id"] for row in json.loads(agents.read_text())}
8547
- for keep_id, why in (("03030303", "the session with no transcript"), ("05050505", "rtl's session"),
8554
+ for keep_id, why in (("06060606", "the session with no transcript"), ("05050505", "rtl's session"),
8548
8555
  ("newsess1", "the new session"), (OLD[:8], "the shift just handed over"), ("04040404", "the second newest old session")):
8549
8556
  if keep_id not in left:
8550
8557
  report(f"{label} {why} ({keep_id}) was removed: {sorted(left)!r}")
@@ -9530,6 +9537,163 @@ def validate_chat_notice_check_scenario() -> int:
9530
9537
  return 0
9531
9538
 
9532
9539
 
9540
+ def validate_chat_dm_long_role_names_scenario() -> int:
9541
+ """Issue #403 (kaiwu-ip, 2026-10-20): two long role names could not share a direct group.
9542
+
9543
+ `dm-<a>--<b>` of two 32-character-at-most role names can be up to 69
9544
+ characters, and the group-name check stopped at 32, so `keel chat dm`
9545
+ between `kaiwu-design-iecc` and `kaiwu-pm-iecc` failed. A direct group's
9546
+ name is valid when it is two different valid role names in sorted order,
9547
+ wherever a group is named, listed or authorized; any other name still
9548
+ follows the role-name pattern.
9549
+ """
9550
+ label = "chat-dm-long-role-names:"
9551
+ group = "dm-kaiwu-design-iecc--kaiwu-pm-iecc"
9552
+ with tempfile.TemporaryDirectory(prefix="keel-chat-403-") as raw:
9553
+ base = Path(raw)
9554
+ design = mailbox_repository(base / "design")
9555
+ pm = chat_worktree(design, base / "pm")
9556
+ env = chat_environment()
9557
+ for cwd, role in ((design, "kaiwu-design-iecc"), (pm, "kaiwu-pm-iecc")):
9558
+ bound = run_keel(cwd, "chat", "role", "--set", role, env=env)
9559
+ if bound.returncode != 0:
9560
+ report(f"{label} could not bind {role}: {bound.stderr!r}")
9561
+ return 1
9562
+
9563
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
9564
+ return run_keel(cwd, "chat", *args, env=env)
9565
+
9566
+ sent = chat(design, "dm", "kaiwu-pm-iecc", "lease freed")
9567
+ if sent.returncode != 0:
9568
+ report(f"{label} a direct message between long role names failed: {sent.stderr.strip()!r}")
9569
+ return 1
9570
+ unread = chat(pm, "unread").stdout
9571
+ if "lease freed" not in unread:
9572
+ report(f"{label} kaiwu-pm-iecc does not have the message unread: {unread!r}")
9573
+ return 1
9574
+ peeked = chat(pm, group, "--peek")
9575
+ if peeked.returncode != 0:
9576
+ report(f"{label} `keel chat {group} --peek` failed: {peeked.stderr!r}")
9577
+ return 1
9578
+ if "lease freed" not in peeked.stdout:
9579
+ report(f"{label} `keel chat {group} --peek` does not print the message: {peeked.stdout!r}")
9580
+ return 1
9581
+ listed = chat(pm, "group", "list", "--json")
9582
+ groups = {row["name"]: row for row in json.loads(listed.stdout or "{}").get("groups", [])} if listed.returncode == 0 else {}
9583
+ if not groups.get(group, {}).get("direct"):
9584
+ report(f"{label} group list does not list {group} as direct: {listed.stdout!r} {listed.stderr!r}")
9585
+ return 1
9586
+ for cwd in (design, pm):
9587
+ write_text(cwd / "keel" / "config.yaml", f"authorize:\n - chat-reply:{group}\n")
9588
+ doctor = run_keel(design, "--doctor", env=env).stdout or ""
9589
+ if not re.search(r"chat-reply: authorized.*" + re.escape(group), doctor):
9590
+ report(f"{label} doctor does not read chat-reply:{group}: {[l for l in doctor.splitlines() if 'chat-reply' in l or 'authoriz' in l]!r}")
9591
+ return 1
9592
+ for bad in ("dm-kaiwu-pm-iecc--kaiwu-design-iecc", "Not_A_Group", "x" * 33):
9593
+ refused = chat(design, bad, "--peek")
9594
+ if refused.returncode == 0:
9595
+ report(f"{label} the group name {bad!r} was accepted: {refused.stdout!r}")
9596
+ return 1
9597
+ if "is not a valid name" not in refused.stderr:
9598
+ report(f"{label} the group name {bad!r} was refused, but not as an invalid name: {refused.stderr!r}")
9599
+ return 1
9600
+ if "chat-dm-long-role-names" not in {name for name, _ in SCENARIOS}:
9601
+ report(f"{label} scenario is not registered.")
9602
+ return 1
9603
+ report("chat-dm-long-role-names scenario passed.")
9604
+ return 0
9605
+
9606
+
9607
+ def validate_lock_notice_best_effort_scenario() -> int:
9608
+ """Issue #403 (kaiwu-ip, 2026-10-20): a lease could not be freed while its notice failed.
9609
+
9610
+ Release and the expiry sweep posted to the waiters before removing the
9611
+ lease, so a notice that could not be posted failed the command and kept
9612
+ the lease until a different role's command freed it. A lease is freed
9613
+ first; a notice that cannot be posted is a warning naming the role.
9614
+ """
9615
+ label = "lock-notice-best-effort:"
9616
+ with tempfile.TemporaryDirectory(prefix="keel-lock-403-") as raw:
9617
+ base = Path(raw)
9618
+ a, b, env = chat_scratch_group(base)
9619
+ c = chat_worktree(a, base / "design")
9620
+ d = chat_worktree(a, base / "pm")
9621
+ for tree, role in ((a, "integ"), (b, "sweep"), (c, "kaiwu-design-iecc"), (d, "kaiwu-pm-iecc")):
9622
+ bound = run_keel(tree, "chat", "role", "--set", role, env=env)
9623
+ if bound.returncode != 0:
9624
+ report(f"{label} could not bind {role}: {bound.stderr!r}")
9625
+ return 1
9626
+ lease_file = mailbox_common_dir(a) / "keel-chat" / "locks" / "main-checkout.json"
9627
+
9628
+ def lock(tree: Path, *args: str) -> subprocess.CompletedProcess[str]:
9629
+ return run_keel(tree, "lock", *args, env=env)
9630
+
9631
+ def hold_with_waiter() -> None:
9632
+ for tree, note in ((a, "integration run"), (b, "formal sweep")):
9633
+ lock(tree, "acquire", "main-checkout", "--for", "2h", "--note", note)
9634
+ if "sweep" not in lease_file.read_text():
9635
+ raise RuntimeError(f"sweep was not recorded as a waiter: {lease_file.read_text()!r}")
9636
+
9637
+ # The holder–waiter direct group is archived, so no message can be posted to it.
9638
+ run_keel(a, "chat", "dm", "sweep", "before the archive", env=env)
9639
+ archived = run_keel(a, "chat", "group", "archive", "dm-integ--sweep", env=env)
9640
+ if archived.returncode != 0:
9641
+ report(f"{label} could not archive dm-integ--sweep: {archived.stderr!r}")
9642
+ return 1
9643
+ hold_with_waiter()
9644
+ released = lock(a, "release", "main-checkout")
9645
+ if released.returncode != 0 or lease_file.exists():
9646
+ report(f"{label} a notice that could not be posted kept the lease: exit {released.returncode}, {released.stderr.strip()!r}")
9647
+ return 1
9648
+ if "warning" not in released.stderr or "sweep" not in released.stderr:
9649
+ report(f"{label} release did not warn naming sweep: {released.stderr!r}")
9650
+ return 1
9651
+ listed = lock(b, "list")
9652
+ if listed.returncode != 0:
9653
+ report(f"{label} keel lock list after the release failed: {listed.stderr!r}")
9654
+ return 1
9655
+ if "main-checkout" in listed.stdout:
9656
+ report(f"{label} keel lock list still shows the released lease: {listed.stdout!r}")
9657
+ return 1
9658
+
9659
+ hold_with_waiter()
9660
+ expired = json.loads(lease_file.read_text())
9661
+ expired["expires"] = "2000-01-01T00:00:00+00:00"
9662
+ lease_file.write_text(json.dumps(expired))
9663
+ swept = lock(a, "list")
9664
+ if swept.returncode != 0 or lease_file.exists():
9665
+ report(f"{label} an expired lease whose notice could not be posted was kept: exit {swept.returncode}, {swept.stderr.strip()!r}")
9666
+ return 1
9667
+ if "warning" not in swept.stderr or "sweep" not in swept.stderr:
9668
+ report(f"{label} the expiry sweep did not warn naming sweep: {swept.stderr!r}")
9669
+ return 1
9670
+
9671
+ lock(c, "acquire", "cpu-heavy", "--for", "10m", "--note", "heavy run")
9672
+ lock(d, "acquire", "cpu-heavy", "--for", "10m", "--note", "queued")
9673
+ released = lock(c, "release", "cpu-heavy")
9674
+ if released.returncode != 0:
9675
+ report(f"{label} release between long role names failed: {released.stderr.strip()!r}")
9676
+ return 1
9677
+ if "warning" in released.stderr:
9678
+ report(f"{label} release between long role names warned: {released.stderr.strip()!r}")
9679
+ return 1
9680
+ listed = lock(d, "list")
9681
+ if listed.returncode != 0:
9682
+ report(f"{label} keel lock list after the long-name release failed: {listed.stderr!r}")
9683
+ return 1
9684
+ if "cpu-heavy" in listed.stdout:
9685
+ report(f"{label} keel lock list still shows cpu-heavy after its release: {listed.stdout!r}")
9686
+ return 1
9687
+ if len(chat_records_with(a, "dm-kaiwu-design-iecc--kaiwu-pm-iecc", "lock cpu-heavy released by kaiwu-design-iecc")) != 1:
9688
+ report(f"{label} the waiter kaiwu-pm-iecc was not told of the release.")
9689
+ return 1
9690
+ if "lock-notice-best-effort" not in {name for name, _ in SCENARIOS}:
9691
+ report(f"{label} scenario is not registered.")
9692
+ return 1
9693
+ report("lock-notice-best-effort scenario passed.")
9694
+ return 0
9695
+
9696
+
9533
9697
  def validate_chat_reply_authorization_scenario() -> int:
9534
9698
  """Issue #195: answering in a declared group needs no per-session grant.
9535
9699
 
@@ -43169,6 +43333,8 @@ SCENARIOS: tuple = (
43169
43333
  ("shift-restore-authorization", validate_shift_restore_authorization_scenario),
43170
43334
  ("self-shift-authorization", validate_self_shift_authorization_scenario),
43171
43335
  ("resource-lock", validate_resource_lock_scenario),
43336
+ ("chat-dm-long-role-names", validate_chat_dm_long_role_names_scenario),
43337
+ ("lock-notice-best-effort", validate_lock_notice_best_effort_scenario),
43172
43338
  ("chat-supersedes", validate_chat_supersedes_scenario),
43173
43339
  ("chat-mention-skips-code", validate_chat_mention_skips_code_scenario),
43174
43340
  ("two-live-sessions-on-one-role", validate_two_live_sessions_on_one_role_scenario),
@@ -417,7 +417,7 @@ function dispatch(where, options) {
417
417
  const threshold = parseSince(options.since);
418
418
  if (threshold === null) throw new ChatError(`--since ${JSON.stringify(options.since)} is not a time; use 90s, 15m, 2h, 3d, or a date.`);
419
419
  const role = store.requireRole(where);
420
- if (options.group !== null) store.checkName(options.group, "Group");
420
+ if (options.group !== null) store.checkGroup(options.group);
421
421
  const digest = store.summary(where, role, threshold, { group: options.group });
422
422
  const sinceText = store.isoLocal(new Date(threshold));
423
423
  if (options.json) out(JSON.stringify({ since: sinceText, ...digest }));
@@ -116,6 +116,21 @@ function checkName(name, what) {
116
116
  }
117
117
  }
118
118
 
119
+ // A direct group is named for its two sorted roles, so its name can run to
120
+ // 69 characters (#403); any other group name follows the role-name pattern.
121
+ function validGroup(name) {
122
+ if (validName(name)) return true;
123
+ if (typeof name !== "string" || !isDirect(name)) return false;
124
+ const members = name.slice(3).split("--");
125
+ return members.length === 2 && members.every(validName) && members[0] < members[1];
126
+ }
127
+
128
+ function checkGroup(name) {
129
+ if (!validGroup(name)) {
130
+ throw new ChatError(`Group ${JSON.stringify(name)} is not a valid name: use ${NAME_PATTERN_TEXT}, or dm-<role>--<role> with the two roles sorted for a direct group.`);
131
+ }
132
+ }
133
+
119
134
  // --- roles and aliases ------------------------------------------------------
120
135
 
121
136
  function readRoles(root) {
@@ -341,7 +356,7 @@ function groupDir(where, group) {
341
356
 
342
357
  function listGroupNames(where) {
343
358
  try {
344
- return fs.readdirSync(path.join(where.root, "groups")).filter(validName).sort();
359
+ return fs.readdirSync(path.join(where.root, "groups")).filter(validGroup).sort();
345
360
  } catch {
346
361
  return [];
347
362
  }
@@ -513,7 +528,7 @@ function requireSpeaker(group, state, role) {
513
528
  }
514
529
 
515
530
  function createGroup(where, actor, group, members, { direct = false } = {}) {
516
- checkName(group, "Group");
531
+ checkGroup(group);
517
532
  if (RESERVED_GROUPS.has(group)) {
518
533
  throw new ChatError(`Group name ${group} is a keel chat subcommand; choose another.`);
519
534
  }
@@ -620,7 +635,7 @@ function findRecord(where, id) {
620
635
  function post(where, options) {
621
636
  const from = requireRole(where);
622
637
  const group = options.group;
623
- checkName(group, "Group");
638
+ checkGroup(group);
624
639
  const text = String(options.text || "");
625
640
  if (!text.trim()) throw new ChatError("A post needs text: give it after the group, or on stdin.");
626
641
  const { records, state } = loadGroup(where, group);
@@ -879,7 +894,7 @@ const WAIT_FORMS = "`--commit <sha> [--remote <name>]` or `--issue <n> --closed`
879
894
  function wait(where, options) {
880
895
  const from = requireRole(where);
881
896
  const group = options.group;
882
- checkName(group, "Group");
897
+ checkGroup(group);
883
898
  const byCommit = options.commit !== null && options.commit !== undefined;
884
899
  const byIssue = options.issue !== null && options.issue !== undefined;
885
900
  if (byCommit === byIssue) {
@@ -1027,7 +1042,7 @@ function unread(where, role) {
1027
1042
  }
1028
1043
 
1029
1044
  function view(where, role, group, { peek = false } = {}) {
1030
- checkName(group, "Group");
1045
+ checkGroup(group);
1031
1046
  const { records, state } = loadGroup(where, group);
1032
1047
  if (!peek && role && records.length) advanceCursor(where, role, group, records[records.length - 1].id);
1033
1048
  return { records, state };
@@ -1078,11 +1093,13 @@ module.exports = {
1078
1093
  changeMember,
1079
1094
  createGroup,
1080
1095
  currentRole,
1096
+ checkGroup,
1081
1097
  directName,
1082
1098
  directPost,
1083
1099
  findRecord,
1084
1100
  groupState,
1085
1101
  isDirect,
1102
+ validGroup,
1086
1103
  isoLocal,
1087
1104
  listGroups,
1088
1105
  listGroupNames,
@@ -62,10 +62,11 @@ const OPTIONALLY_SCOPED_AUTHORIZATION_ACTIONS = new Set(["push"]);
62
62
  const AUTHORIZATION_SCOPE_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
63
63
 
64
64
  // Each scoped action's form and shape. `chat-reply` names a chat group, whose
65
- // names follow the chat's own pattern (src/core/chat/store.js).
65
+ // names follow the chat's own pattern (src/core/chat/store.js), a direct
66
+ // group's included (#403).
66
67
  const AUTHORIZATION_SCOPES = {
67
68
  issue: { form: "<owner>/<repo>", pattern: AUTHORIZATION_SCOPE_PATTERN },
68
- "chat-reply": { form: "<group>", pattern: /^[a-z0-9][a-z0-9-]{0,31}$/ },
69
+ "chat-reply": { form: "<group>", pattern: /^(?:[a-z0-9][a-z0-9-]{0,31}|dm-[a-z0-9][a-z0-9-]{0,31}--[a-z0-9][a-z0-9-]{0,31})$/ },
69
70
  "issue-close": { form: "<owner>/<repo>", pattern: AUTHORIZATION_SCOPE_PATTERN },
70
71
  cleanup: { form: "scratch", pattern: /^scratch$/ },
71
72
  // Branch-name characters and `*`; `*` matches within one `/` segment and
package/src/core/lock.js CHANGED
@@ -119,25 +119,36 @@ function withMutation(where, action) {
119
119
 
120
120
  // Posts from the running worktree's role to every other role among the
121
121
  // targets. The running role is not messaged: it is the one reading the output.
122
+ // A message that cannot be posted is returned as a warning (#403): the lease
123
+ // is already freed, and a failed notice must not undo that.
122
124
  function notify(where, targets, text) {
123
125
  const from = store.currentRole(where);
124
- if (!from) return;
126
+ if (!from) return [];
127
+ const warnings = [];
125
128
  for (const role of new Set(targets.map((target) => target.role).filter(Boolean))) {
126
- if (role !== from) store.directPost(where, role, text);
129
+ if (role === from) continue;
130
+ try {
131
+ store.directPost(where, role, text);
132
+ } catch (error) {
133
+ if (!(error instanceof store.ChatError)) throw error;
134
+ warnings.push("warning: could not tell " + role + " that " + text + ": " + error.message);
135
+ }
127
136
  }
137
+ return warnings;
128
138
  }
129
139
 
130
140
  // Every freed lease is printed, whether or not anyone was messaged (D4).
131
141
  function reap(where) {
132
142
  const freed = [];
143
+ const warnings = [];
133
144
  for (const lease of readLeases(where)) {
134
145
  if (Date.parse(lease.expires) > Date.now()) continue;
135
146
  const text = "lock " + lease.resource + " expired at " + lease.expires + " (held by " + lease.holder + ": " + lease.note + ")";
136
- notify(where, [lease, ...lease.waiters], text);
137
- freed.push(text);
138
147
  fs.unlinkSync(path.join(lockDir(where), lease.resource + ".json"));
148
+ freed.push(text);
149
+ warnings.push(...notify(where, [lease, ...lease.waiters], text));
139
150
  }
140
- return freed;
151
+ return { freed, warnings };
141
152
  }
142
153
 
143
154
  function acquire(where, resource, expires, note) {
@@ -165,9 +176,8 @@ function release(where, resource) {
165
176
  const lease = readLeases(where).find((row) => row.resource === resource);
166
177
  if (!lease) throw new LockError("No live lease for " + resource + ".");
167
178
  if (lease.holder !== identity(where).holder) throw new LockError("Only " + lease.holder + " can release " + resource + " (" + lease.worktree + ").");
168
- notify(where, lease.waiters, "lock " + resource + " released by " + lease.holder);
169
179
  fs.unlinkSync(path.join(lockDir(where), resource + ".json"));
170
- return lease;
180
+ return { lease, warnings: notify(where, lease.waiters, "lock " + resource + " released by " + lease.holder) };
171
181
  }
172
182
 
173
183
  function runLock(argv) {
@@ -193,10 +203,12 @@ function runLock(argv) {
193
203
  }
194
204
  const where = store.requireLocation(options.repo);
195
205
  return withMutation(where, () => {
196
- for (const text of reap(where)) {
206
+ const reaped = reap(where);
207
+ for (const text of reaped.freed) {
197
208
  // Keep --json parseable, including when a command is later refused.
198
209
  (options.json ? process.stderr : process.stdout).write(text + "\n");
199
210
  }
211
+ for (const warning of reaped.warnings) process.stderr.write("keel lock: " + warning + "\n");
200
212
  if (extra.length || (action === "list" && resource)) throw new LockError("Unexpected argument for " + action + ".");
201
213
  if (action !== "acquire" && (options.duration !== null || options.note !== null)) throw new LockError("--for and --note are only valid for acquire.");
202
214
  const out = (data, text) => process.stdout.write((options.json ? JSON.stringify(data, null, 2) : text) + "\n");
@@ -206,8 +218,9 @@ function runLock(argv) {
206
218
  } else {
207
219
  checkResource(resource);
208
220
  if (action === "release") {
209
- const lease = release(where, resource);
221
+ const { lease, warnings } = release(where, resource);
210
222
  out({ released: lease }, "lock " + resource + " released by " + lease.holder);
223
+ for (const warning of warnings) process.stderr.write("keel lock: " + warning + "\n");
211
224
  } else {
212
225
  if (options.duration === null) throw new LockError("acquire requires --for <duration>.");
213
226
  if (!options.note || !options.note.trim()) throw new LockError("acquire requires a non-empty --note <why>.");
package/src/core/shift.js CHANGED
@@ -563,21 +563,26 @@ function keptCopyOf(where, role, transcript) {
563
563
 
564
564
  // After a delivered hand-over, the newest `keep` stopped background sessions in
565
565
  // the role's bound worktrees stay listed; each older one is removed with
566
- // `claude rm` once Keel's store holds its transcript, and one whose transcript
567
- // is nowhere stays (#397 D2). `claude rm` leaves the host's transcript (F4).
566
+ // `claude rm` once Keel's store holds its transcript (#397 D2). `claude rm`
567
+ // leaves the host's transcript (F4). Only a session with a transcript, the
568
+ // host's or Keel's copy, is a shift: one never given a prompt has neither, so
569
+ // it takes no slot and stays (#401).
568
570
  function removeOldSessions(claude, where, entry, keep) {
569
571
  const bound = new Set(Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
570
572
  .filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
571
573
  const listed = listAgents(claude);
572
574
  if (!listed) return [];
575
+ const { keptFile } = require("./chat/notice");
573
576
  const old = listed
574
577
  .filter((row) => row && row.kind === "background" && !row.status && row.cwd && bound.has(realpath(row.cwd))
575
578
  && row.sessionId && row.id !== entry.new_session)
576
- .sort((a, b) => (Number(b.startedAt) || 0) - (Number(a.startedAt) || 0));
579
+ .map((row) => ({ row, transcript: hostTranscript(row.cwd, row.sessionId),
580
+ kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) }))
581
+ .filter(({ transcript, kept }) => transcript || fs.existsSync(kept))
582
+ .sort((a, b) => (Number(b.row.startedAt) || 0) - (Number(a.row.startedAt) || 0));
577
583
  const removed = [];
578
- for (const row of old.slice(keep)) {
579
- const transcript = hostTranscript(row.cwd, row.sessionId);
580
- if (!transcript || !keptCopyOf(where, entry.role, transcript)) continue;
584
+ for (const { row, transcript } of old.slice(keep)) {
585
+ if (transcript && !keptCopyOf(where, entry.role, transcript)) continue;
581
586
  const gone = spawnSync(claude, ["rm", row.id || row.sessionId.slice(0, 8)], { encoding: "utf8" });
582
587
  if (!gone.error && gone.status === 0) removed.push(row.id || row.sessionId.slice(0, 8));
583
588
  }