@christang/keel 5.112.1 → 5.114.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.
package/README.md CHANGED
@@ -356,7 +356,9 @@ material choice, every gate still runs, and the write guard still binds. In part
356
356
  explicitly.
357
357
 
358
358
  **Keel schedules nothing.** `/loop`, cron, and CI triggers are your runtime's; Keel's part is making
359
- each step decidable with authority. And a run that stops at a real decision has ended the way it was
359
+ each step decidable with authority. The one exception is `keel shift ready --wake`: a one-shot waiter
360
+ that writes a single wake record once that role's next session has started, then exits — a session
361
+ changing its own shift has nobody else to start it. And a run that stops at a real decision has ended the way it was
360
362
  designed to — resist widening the policy until it stops happening.
361
363
 
362
364
  ### Who merges
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.112.1 -->
1
+ <!-- keel:start version=5.114.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.112.1",
3
+ "version": "5.114.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.112.1",
9
+ "version": "5.114.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.112.1",
5
+ "version": "5.114.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.112.1",
3
+ "version": "5.114.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.112.1",
3
+ "version": "5.114.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",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.112.1"
51
- PROTOCOL_VERSION = "5.112.1"
50
+ PACKAGE_VERSION = "5.114.0"
51
+ PROTOCOL_VERSION = "5.114.0"
52
52
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
53
53
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
54
54
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -5439,6 +5439,273 @@ def validate_resource_lock_scenario() -> int:
5439
5439
  return 0
5440
5440
 
5441
5441
 
5442
+ def shift_scratch(base: Path) -> tuple[Path, Path, dict, Path]:
5443
+ """`rtl` and `verify` worktrees pushed to a bare remote, for shift scenarios."""
5444
+ rtl, verify, env = chat_scratch_group(base)
5445
+ remote = base / "remote.git"
5446
+ subprocess.run(["git", "init", "-q", "--bare", str(remote)], check=True, capture_output=True)
5447
+ subprocess.run(["git", "remote", "add", "origin", str(remote)], cwd=rtl, check=True, capture_output=True)
5448
+ for tree in (rtl, verify):
5449
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
5450
+ return rtl, verify, env, remote
5451
+
5452
+
5453
+ def validate_shift_role_elsewhere_scenario() -> int:
5454
+ """Issues #290, #291: a note filed under the role from another worktree.
5455
+
5456
+ `ready --role` files it under the role; an unbound worktree refuses to
5457
+ misfile while role requests are open; status names what works for a
5458
+ worktree note.
5459
+ """
5460
+ label = "shift-role-elsewhere:"
5461
+ with tempfile.TemporaryDirectory(prefix="keel-shift-elsewhere-") as raw:
5462
+ base = Path(raw)
5463
+ rtl, verify, env, _ = shift_scratch(base)
5464
+ loose = chat_worktree(rtl, base / "loose")
5465
+ loose2 = chat_worktree(rtl, base / "loose2")
5466
+ for tree in (loose, loose2):
5467
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
5468
+
5469
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
5470
+ return run_keel(cwd, "shift", *args, env=env)
5471
+
5472
+ shift(rtl, "request", "verify")
5473
+ common = mailbox_common_dir(rtl) / "keel-chat" / "shift"
5474
+ misfiled = shift(loose, "ready", "worked on R008 here")
5475
+ if misfiled.returncode == 0:
5476
+ report(f"{label} ready in an unbound worktree with verify's request open was accepted.")
5477
+ return 1
5478
+ if "--role verify" not in misfiled.stderr:
5479
+ report(f"{label} the refusal does not name --role verify: {misfiled.stderr}")
5480
+ return 1
5481
+ if list((common / "worktree").glob("*.md")) if (common / "worktree").exists() else []:
5482
+ report(f"{label} a refused ready still wrote a worktree note.")
5483
+ return 1
5484
+ wrong = shift(loose, "ready", "--role", "rtl", "x")
5485
+ if wrong.returncode == 0:
5486
+ report(f"{label} ready --role rtl, which has no open request, was accepted.")
5487
+ return 1
5488
+ filed = shift(loose, "ready", "--role", "verify", "worked on R008 in loose")
5489
+ if filed.returncode != 0:
5490
+ report(f"{label} ready --role verify failed: {filed.stdout} {filed.stderr}")
5491
+ return 1
5492
+ if not (common / "verify.md").exists():
5493
+ report(f"{label} ready --role verify did not file the note under verify.")
5494
+ return 1
5495
+ started = shift(rtl, "start", "verify")
5496
+ if started.returncode != 0:
5497
+ report(f"{label} keel shift start verify was refused: {started.stderr}")
5498
+ return 1
5499
+ lone = shift(loose2, "ready", "nothing requested here")
5500
+ if lone.returncode != 0:
5501
+ report(f"{label} ready in an unbound worktree with no open request failed: {lone.stderr}")
5502
+ return 1
5503
+ status = shift(rtl, "status").stdout
5504
+ line = next((l for l in status.splitlines() if "loose2" in l), "")
5505
+ if str(loose2.resolve()) not in line or "keel shift resume" not in line:
5506
+ report(f"{label} the worktree note's status line does not name its path and keel shift resume: {line!r}")
5507
+ return 1
5508
+ if "keel shift start worktree" in status:
5509
+ report(f"{label} status still suggests keel shift start for a worktree note: {status!r}")
5510
+ return 1
5511
+ report("shift-role-elsewhere scenario passed.")
5512
+ return 0
5513
+
5514
+
5515
+ def validate_shift_self_scenario() -> int:
5516
+ """Issue #293: a role with no coordinator changes its own shift.
5517
+
5518
+ It cannot start itself, `ready` says nobody will start the new session,
5519
+ status says its own next session resumes the note, and a new session in
5520
+ an unbound worktree resumes it with `--role`.
5521
+ """
5522
+ label = "shift-self:"
5523
+ with tempfile.TemporaryDirectory(prefix="keel-shift-self-") as raw:
5524
+ base = Path(raw)
5525
+ rtl, _verify, env, _ = shift_scratch(base)
5526
+ pm = chat_worktree(rtl, base / "pm")
5527
+ other = chat_worktree(rtl, base / "other")
5528
+ for tree in (pm, other):
5529
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
5530
+ run_keel(pm, "chat", "role", "--set", "pm", env=env)
5531
+
5532
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
5533
+ return run_keel(cwd, "shift", *args, env=env)
5534
+
5535
+ readied = shift(pm, "ready", "pm note: next is R009")
5536
+ if readied.returncode != 0:
5537
+ report(f"{label} pm's ready failed: {readied.stderr}")
5538
+ return 1
5539
+ if "nobody" not in readied.stdout:
5540
+ report(f"{label} ready does not say nobody is set to start the new session: {readied.stdout!r}")
5541
+ return 1
5542
+ if "--wake" not in readied.stdout:
5543
+ report(f"{label} ready does not name --wake: {readied.stdout!r}")
5544
+ return 1
5545
+ if "The coordinator's `keel shift start` then wakes" in readied.stdout:
5546
+ report(f"{label} ready still promises a coordinator's start to a role nobody asked: {readied.stdout!r}")
5547
+ return 1
5548
+ itself = shift(pm, "start", "pm")
5549
+ if itself.returncode == 0:
5550
+ report(f"{label} keel shift start pm by pm was accepted.")
5551
+ return 1
5552
+ if "ready --wake" not in itself.stderr:
5553
+ report(f"{label} the refusal does not name ready --wake: {itself.stderr}")
5554
+ return 1
5555
+ if chat_log(rtl, "dm-pm--pm").exists():
5556
+ report(f"{label} a refused self-start still created dm-pm--pm.")
5557
+ return 1
5558
+ status = shift(rtl, "status").stdout
5559
+ line = next((l for l in status.splitlines() if l.startswith("pm:")), "")
5560
+ if "own next session" not in line:
5561
+ report(f"{label} status does not say pm's own next session resumes its note: {line!r}")
5562
+ return 1
5563
+ misbound = shift(rtl, "resume", "--role", "pm")
5564
+ if misbound.returncode == 0:
5565
+ report(f"{label} resume --role pm in rtl's worktree was accepted.")
5566
+ return 1
5567
+ resumed = shift(other, "resume", "--role", "pm")
5568
+ if resumed.returncode != 0:
5569
+ report(f"{label} resume --role pm in an unbound worktree failed: {resumed.stderr}")
5570
+ return 1
5571
+ if "next is R009" not in resumed.stdout:
5572
+ report(f"{label} resume --role pm did not print pm's note: {resumed.stdout!r}")
5573
+ return 1
5574
+ if (mailbox_common_dir(rtl) / "keel-chat" / "shift" / "pm.md").exists():
5575
+ report(f"{label} pm's note still waits after resume --role pm.")
5576
+ return 1
5577
+ report("shift-self scenario passed.")
5578
+ return 0
5579
+
5580
+
5581
+ def validate_shift_self_wake_scenario() -> int:
5582
+ """Issue #293: `ready --wake` wakes the role's next session, once.
5583
+
5584
+ A `compact` start does not trigger the waiter; a `clear` start does, and
5585
+ the role then has exactly one waking record from `keel-shift`. Without a
5586
+ chat role, `--wake` is refused.
5587
+ """
5588
+ label = "shift-self-wake:"
5589
+ protocol = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
5590
+ line = next((l for l in protocol.splitlines() if l.startswith("- Keel schedules nothing")), "")
5591
+ if "keel shift ready --wake" not in line:
5592
+ report(f"{label} the protocol's scheduling line does not name the keel shift ready --wake exception: {line!r}")
5593
+ return 1
5594
+ with tempfile.TemporaryDirectory(prefix="keel-shift-wake-") as raw:
5595
+ base = Path(raw)
5596
+ rtl, verify, env, _ = shift_scratch(base)
5597
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
5598
+ loose = chat_worktree(rtl, base / "loose")
5599
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=loose, check=True, capture_output=True)
5600
+
5601
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
5602
+ return run_keel(cwd, "shift", *args, env=env)
5603
+
5604
+ def session_start(source: str) -> None:
5605
+ subprocess.run(
5606
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"],
5607
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
5608
+ input=json.dumps({"cwd": str(verify), "source": source, "hook_event_name": "SessionStart"}),
5609
+ )
5610
+
5611
+ def wakes() -> list[str]:
5612
+ return chat_records_with(rtl, "dm-keel-shift--verify", "keel shift resume")
5613
+
5614
+ unbound = shift(loose, "ready", "--wake", "loose note")
5615
+ if unbound.returncode == 0:
5616
+ report(f"{label} ready --wake in an unbound worktree with no --role was accepted.")
5617
+ return 1
5618
+ armed = shift(verify, "ready", "--wake", "verify note: next is R010")
5619
+ if armed.returncode != 0:
5620
+ report(f"{label} ready --wake failed: {armed.stderr}")
5621
+ return 1
5622
+ session_start("compact")
5623
+ time.sleep(1)
5624
+ if wakes():
5625
+ report(f"{label} a compact start triggered the wake.")
5626
+ return 1
5627
+ session_start("clear")
5628
+ deadline = time.time() + 5
5629
+ while time.time() < deadline and not wakes():
5630
+ time.sleep(0.1)
5631
+ found = wakes()
5632
+ if len(found) != 1:
5633
+ report(f"{label} expected exactly one wake record from keel-shift after the clear start, found {len(found)}.")
5634
+ return 1
5635
+ if "from: keel-shift" not in found[0]:
5636
+ report(f"{label} the wake record is not from keel-shift: {found[0]!r}")
5637
+ return 1
5638
+ time.sleep(0.5)
5639
+ if len(wakes()) != 1:
5640
+ report(f"{label} the waiter wrote more than one wake record.")
5641
+ return 1
5642
+ checked = run_keel(verify, "chat", "notice", "--check", env=env)
5643
+ if checked.returncode != 0:
5644
+ report(f"{label} keel chat notice --check for verify does not see the wake (exit {checked.returncode}).")
5645
+ return 1
5646
+ report("shift-self-wake scenario passed.")
5647
+ return 0
5648
+
5649
+
5650
+ def validate_shift_coordinator_last_scenario() -> int:
5651
+ """Issue #289: the coordinator starts the others before its own shift ends.
5652
+
5653
+ Its check reports a waiting, unstarted note and its ready is refused until
5654
+ it starts that role; a successor's resume lists who still waits; the
5655
+ request and ready name session state a clear destroys.
5656
+ """
5657
+ label = "shift-coordinator-last:"
5658
+ with tempfile.TemporaryDirectory(prefix="keel-shift-coordinator-") as raw:
5659
+ base = Path(raw)
5660
+ rtl, verify, env, _ = shift_scratch(base)
5661
+
5662
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
5663
+ return run_keel(cwd, "shift", *args, env=env)
5664
+
5665
+ shift(rtl, "request", "verify")
5666
+ request_text = "\n".join(chat_records_with(rtl, "dm-rtl--verify", "Shift change requested"))
5667
+ if "scheduled jobs" not in request_text:
5668
+ report(f"{label} the request does not name scheduled jobs: {request_text!r}")
5669
+ return 1
5670
+ readied = shift(verify, "ready", "verify note")
5671
+ if readied.returncode != 0:
5672
+ report(f"{label} verify's ready failed: {readied.stderr}")
5673
+ return 1
5674
+ if "scheduled jobs" not in readied.stdout:
5675
+ report(f"{label} ready's output does not name scheduled jobs: {readied.stdout!r}")
5676
+ return 1
5677
+ checked = shift(rtl, "check", "--json")
5678
+ items = json.loads(checked.stdout).get("items", [])
5679
+ if checked.returncode != 1:
5680
+ report(f"{label} rtl's check exited {checked.returncode} with verify unstarted, not 1.")
5681
+ return 1
5682
+ if not any(i.get("kind") == "unstarted" and "verify" in i.get("detail", "") for i in items):
5683
+ report(f"{label} rtl's check has no unstarted item for verify: {items!r}")
5684
+ return 1
5685
+ if shift(rtl, "ready", "rtl note").returncode == 0:
5686
+ report(f"{label} rtl's ready was accepted with verify unstarted.")
5687
+ return 1
5688
+ shift(rtl, "start", "verify")
5689
+ after = json.loads(shift(rtl, "check", "--json").stdout).get("items", [])
5690
+ if any(i.get("kind") == "unstarted" for i in after):
5691
+ report(f"{label} rtl's check still reports unstarted after start: {after!r}")
5692
+ return 1
5693
+
5694
+ shift(verify, "resume")
5695
+ shift(rtl, "request", "verify")
5696
+ shift(verify, "ready", "verify note, second round")
5697
+ forced = shift(rtl, "ready", "--force-reason", "user is away", "rtl note")
5698
+ if forced.returncode != 0:
5699
+ report(f"{label} rtl's ready --force-reason failed: {forced.stderr}")
5700
+ return 1
5701
+ resumed = shift(rtl, "resume")
5702
+ if "verify" not in resumed.stdout or "keel shift start" not in resumed.stdout:
5703
+ report(f"{label} rtl's resume does not list verify as waiting for keel shift start: {resumed.stdout!r}")
5704
+ return 1
5705
+ report("shift-coordinator-last scenario passed.")
5706
+ return 0
5707
+
5708
+
5442
5709
  def validate_shift_change_scenario() -> int:
5443
5710
  """Owner's decision of 2026-10-05: a role's session changes shift through Keel.
5444
5711
 
@@ -39051,6 +39318,10 @@ SCENARIOS: tuple = (
39051
39318
  ("context-names-the-protocol-refresh", validate_context_names_the_protocol_refresh_scenario),
39052
39319
  ("collected-feedback-is-recorded", validate_collected_feedback_is_recorded_scenario),
39053
39320
  ("shift-change", validate_shift_change_scenario),
39321
+ ("shift-role-elsewhere", validate_shift_role_elsewhere_scenario),
39322
+ ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39323
+ ("shift-self", validate_shift_self_scenario),
39324
+ ("shift-self-wake", validate_shift_self_wake_scenario),
39054
39325
  ("shift-without-role", validate_shift_without_role_scenario),
39055
39326
  ("resource-lock", validate_resource_lock_scenario),
39056
39327
  ("chat-supersedes", validate_chat_supersedes_scenario),
@@ -80,12 +80,17 @@ function presenceFile(where, role) {
80
80
  }
81
81
 
82
82
  // Presence is written only by its own role, so it never conflicts (D1).
83
- function touchPresence(where, role, state = "online", host = null) {
83
+ function touchPresence(where, role, state = "online", host = null, started = null) {
84
84
  const previous = store.readJsonFile(presenceFile(where, role));
85
85
  const record = {
86
86
  state,
87
87
  last_active: store.isoLocal(new Date()),
88
88
  host: host || previous.host || null,
89
+ // When and how the role's current session started, for the one-shot
90
+ // waiter `keel shift ready --wake` leaves (#293 D1); millisecond UTC so a
91
+ // start in the same second as the `ready` still orders after it.
92
+ session_started: started ? new Date().toISOString() : previous.session_started || null,
93
+ session_source: started ? started.source : previous.session_source || null,
89
94
  };
90
95
  try {
91
96
  store.writeJsonAtomic(where, presenceFile(where, role), record);
@@ -193,7 +198,8 @@ function hook(event, input, { mail = false } = {}) {
193
198
  touchPresence(where, role, "offline");
194
199
  return { code: 0 };
195
200
  }
196
- touchPresence(where, role, "online", mail ? null : "claude-code");
201
+ const started = event === "session-start" ? { source: typeof payload.source === "string" ? payload.source : null } : null;
202
+ touchPresence(where, role, "online", mail ? null : "claude-code", started);
197
203
  const chatText = noticeText(where, role);
198
204
  const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
199
205
  if (event === "session-start") {
@@ -237,6 +243,7 @@ module.exports = {
237
243
  bridgeLine,
238
244
  hook,
239
245
  noticeText,
246
+ presenceFile,
240
247
  presenceOf,
241
248
  signalPath,
242
249
  touchPresence,
package/src/core/shift.js CHANGED
@@ -14,7 +14,7 @@
14
14
  const fs = require("fs");
15
15
  const os = require("os");
16
16
  const path = require("path");
17
- const { spawnSync } = require("child_process");
17
+ const { spawn, spawnSync } = require("child_process");
18
18
  const store = require("./chat/store");
19
19
  const locks = require("./lock");
20
20
 
@@ -23,9 +23,11 @@ const USAGE = [
23
23
  "keel shift request <role> [text] ask a role to change shift (wakes it)",
24
24
  "keel shift check [--json] readiness check of this worktree; exit 1 if anything is loose",
25
25
  "keel shift ready [text | --file f] store the shift note, close the request (refused while loose)",
26
+ " [--role r] ...under role r, from a worktree bound to no role (#290)",
26
27
  " [--force-reason r] ...or state why the loose ends may stay",
28
+ " [--wake] ...and wake the role's next session once it starts (#293)",
27
29
  "keel shift start <role> [text] wake the cleared role to resume (once its note waits)",
28
- "keel shift resume [--json] print and consume this role's note",
30
+ "keel shift resume [--role r] [--json] print and consume this role's note (--role: from an unbound worktree)",
29
31
  "keel shift status [--json] each role's shift state",
30
32
  "Options: --repo <path>. See docs/shift-change.md.",
31
33
  ].join("\n");
@@ -201,6 +203,14 @@ function check(where, role) {
201
203
  }
202
204
 
203
205
  if (role) {
206
+ // A coordinator does not leave notes waiting unstarted (#289 D1): once it
207
+ // clears, nobody is left to start them.
208
+ for (const waiting of unstarted(where, role)) {
209
+ items.push({
210
+ kind: "unstarted",
211
+ detail: `${waiting.role}: note waiting since ${waiting.since}; run \`keel shift start ${waiting.role}\` before your own shift ends`,
212
+ });
213
+ }
204
214
  for (const todo of store.openTodos(where, { assignee: role })) {
205
215
  if (isShift(todo)) continue;
206
216
  items.push({ kind: "open-todo", detail: `${todo.id} in ${todo.group}: ${firstLine(todo.text)}` });
@@ -216,6 +226,36 @@ function check(where, role) {
216
226
  return { ready: items.length === 0, worktree: where.worktree, role: role || null, items, notes };
217
227
  }
218
228
 
229
+ // The UTC millisecond a chat record id was written at (`20261012T093944609Z-…`).
230
+ function idTime(id) {
231
+ const m = String(id || "").match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\d{3})Z/);
232
+ return m ? Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6], +m[7]) : 0;
233
+ }
234
+
235
+ // Roles whose note waits, whose latest shift request came from `coordinator`,
236
+ // and that `coordinator` has not started since the note was written.
237
+ function unstarted(where, coordinator) {
238
+ const result = [];
239
+ for (const file of safeList(shiftDir(where))) {
240
+ if (!file.endsWith(".md")) continue;
241
+ const role = file.slice(0, -3);
242
+ if (role === coordinator || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(role)) continue;
243
+ const requests = shiftRequests(where, role);
244
+ const latest = requests[requests.length - 1];
245
+ if (!latest || latest.from !== coordinator) continue;
246
+ const written = fs.statSync(path.join(shiftDir(where), file)).mtime;
247
+ // A record's id carries its UTC time to the millisecond; `created` only to
248
+ // the second, which lets a start from the previous round read as later
249
+ // than a note written in the same second.
250
+ const started = store.readLog(where, store.directName(coordinator, role)).some(
251
+ (record) => record.from === coordinator && record.kind === "message" && isShift(record)
252
+ && /your new shift starts now/.test(record.text || "") && idTime(record.id) > written.getTime()
253
+ );
254
+ if (!started) result.push({ role, since: store.isoLocal(written) });
255
+ }
256
+ return result.sort((a, b) => (a.role < b.role ? -1 : 1));
257
+ }
258
+
219
259
  function firstLine(text) {
220
260
  const line = String(text || "").split("\n")[0];
221
261
  return line.length > 100 ? `${line.slice(0, 100)}…` : line;
@@ -265,8 +305,9 @@ function request(where, role, text) {
265
305
  `Shift change requested by ${from}. Wrap up, then hand over:`,
266
306
  "1. `keel shift check` until it reports ready (or decide what may stay).",
267
307
  "2. Put follow-ups where the project tracks them, and update long-lived memory you own.",
268
- "3. `keel shift ready \"<what you were doing, next step, what you wait on, where>\"`.",
269
- "4. Clear this session as `keel shift ready` says.",
308
+ "3. Note in the shift note any session state a clear destroys and Keel cannot see — scheduled jobs, Remote Control — so the next shift can re-create it.",
309
+ "4. `keel shift ready \"<what you were doing, next step, what you wait on, where>\"`.",
310
+ "5. Clear this session as `keel shift ready` says.",
270
311
  text ? `\n${text}` : "",
271
312
  ].join("\n").trim();
272
313
  return store.todo(where, { group, assignee: role, text: body, refs: [REF] });
@@ -292,8 +333,41 @@ function readNoteText(options) {
292
333
  return "";
293
334
  }
294
335
 
336
+ // The role a note is filed under (#290 D4, D5): the worktree's, or `--role`
337
+ // when this worktree has none and that role has an open request. An unbound
338
+ // worktree refuses to file under itself while role requests are open, since
339
+ // such a note would answer none of them.
340
+ function readyRole(where, options) {
341
+ const bound = store.currentRole(where);
342
+ if (options.role) {
343
+ store.checkName(options.role, "Role");
344
+ if (bound && bound !== options.role) {
345
+ throw new ShiftError(`This worktree is bound to role ${bound}; --role ${options.role} names another role.`);
346
+ }
347
+ if (!shiftRequests(where, options.role).some((r) => r.open)) {
348
+ throw new ShiftError(`--role ${options.role}: no shift change is requested of ${options.role}, so there is no request for this note to answer.`);
349
+ }
350
+ return options.role;
351
+ }
352
+ if (!bound) {
353
+ const open = [...new Set(shiftRequests(where).filter((r) => r.open).map((r) => r.assignee))].sort();
354
+ if (open.length) {
355
+ throw new ShiftError(
356
+ `This worktree has no chat role, and shift changes are requested of ${open.join(", ")}. `
357
+ + `If this session is one of them, run ${open.map((r) => `\`keel shift ready --role ${r} …\``).join(" or ")}; `
358
+ + "a note filed under this worktree would answer none of the requests."
359
+ );
360
+ }
361
+ }
362
+ return bound;
363
+ }
364
+
295
365
  function ready(where, options) {
296
- const role = store.currentRole(where);
366
+ const role = readyRole(where, options);
367
+ if (options.wake && !role) {
368
+ throw new ShiftError("--wake wakes a chat role, and this worktree has none: bind one with `keel chat role --set <name>`, or name it with --role.");
369
+ }
370
+ const since = Date.now();
297
371
  const result = check(where, role);
298
372
  if (!result.ready && !options.forceReason) {
299
373
  throw new ShiftError(`${renderCheck(result)}\nResolve these, or give --force-reason "<why they may stay>".`);
@@ -312,20 +386,88 @@ function ready(where, options) {
312
386
  writeFileAtomic(note, `${head}\n${text}\n`);
313
387
  // Requests are chat records; without a role there is none to close (D2).
314
388
  const open = role ? shiftRequests(where, role).filter((r) => r.open) : [];
389
+ const doneText = (todo) => `done — ${role} is ready for the shift change; the note waits for \`keel shift resume\`.${options.forceReason ? ` Left as is: ${options.forceReason}.` : ""}`;
315
390
  for (const todo of open) {
316
- store.post(where, {
317
- group: todo.group,
318
- replyTo: todo.id,
319
- refs: [REF],
320
- text: `done — ${role} is ready for the shift change; the note waits for \`keel shift resume\`.${options.forceReason ? ` Left as is: ${options.forceReason}.` : ""}`,
321
- });
391
+ if (store.currentRole(where) === role) {
392
+ store.post(where, { group: todo.group, replyTo: todo.id, refs: [REF], text: doneText(todo) });
393
+ } else {
394
+ // Filed with --role from a worktree bound to no role (#290 D4): the
395
+ // reply and the closing record are the role's own.
396
+ store.writeRecord(where, { group: todo.group, kind: "message", from: role, reply_to: todo.id, refs: [REF], text: doneText(todo) });
397
+ store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
398
+ }
322
399
  }
323
- return { role: role || null, note, closed: open.map((todo) => todo.id) };
400
+ const waiter = options.wake ? armWake(where, role, since) : null;
401
+ return { role: role || null, note, closed: open.map((todo) => todo.id), waiter };
402
+ }
403
+
404
+ // --- the one-shot wake (#293) -------------------------------------------------------
405
+ //
406
+ // The one exception to "Keel schedules nothing" (D7): `ready --wake` leaves a
407
+ // detached waiter that writes a single wake record once the role's next
408
+ // session has started, then exits. Its working directory is `/`, so `check`
409
+ // never counts it as this worktree's process.
410
+
411
+ const WAKE_SENDER = "keel-shift";
412
+ const WAKE_SOURCES = new Set(["clear", "startup"]);
413
+
414
+ function envMs(name, fallback) {
415
+ const value = Number(process.env[name]);
416
+ return Number.isFinite(value) && value > 0 ? value : fallback;
417
+ }
418
+
419
+ function armWake(where, role, since) {
420
+ const keel = path.resolve(__dirname, "..", "..", "bin", "keel.js");
421
+ const child = spawn(
422
+ process.execPath,
423
+ [keel, "shift", "wake-wait", "--role", role, "--since", String(since), "--repo", where.worktree],
424
+ { detached: true, stdio: "ignore", cwd: path.parse(where.worktree).root },
425
+ );
426
+ child.unref();
427
+ return child.pid;
428
+ }
429
+
430
+ // The role's current session started after `since`, from a clear or a fresh start.
431
+ function startedSince(where, role, since) {
432
+ const { presenceFile } = require("./chat/notice");
433
+ const presence = store.readJsonFile(presenceFile(where, role));
434
+ const started = Date.parse(presence.session_started || "");
435
+ return !Number.isNaN(started) && started >= since && WAKE_SOURCES.has(presence.session_source);
436
+ }
437
+
438
+ function writeWake(where, role) {
439
+ const group = directGroup(where, WAKE_SENDER, role);
440
+ return store.writeRecord(where, {
441
+ group,
442
+ kind: "message",
443
+ from: WAKE_SENDER,
444
+ refs: [REF],
445
+ text: `${role}: your new shift starts now (woken by the \`keel shift ready --wake\` you ran). First run \`keel context\`, then \`keel shift resume\`.`,
446
+ });
447
+ }
448
+
449
+ function waitForWake(where, role, since) {
450
+ const poll = envMs("KEEL_SHIFT_WAKE_POLL_MS", 5000);
451
+ const deadline = Date.now() + envMs("KEEL_SHIFT_WAKE_TIMEOUT_MS", 2 * 60 * 60 * 1000);
452
+ const tick = () => {
453
+ // A note resumed by hand needs no wake; give up after the time limit.
454
+ if (!fs.existsSync(notePath(where, role)) || Date.now() > deadline) return;
455
+ if (startedSince(where, role, since)) {
456
+ writeWake(where, role);
457
+ return;
458
+ }
459
+ setTimeout(tick, poll);
460
+ };
461
+ tick();
324
462
  }
325
463
 
326
464
  function start(where, role, text) {
327
465
  const from = requireRole(where);
328
466
  store.checkName(role, "Role");
467
+ // A role's own start would address itself and wake nothing (#293 D4).
468
+ if (role === from) {
469
+ throw new ShiftError("A role does not start its own new shift; use `keel shift ready --wake`, which wakes it once the new session starts.");
470
+ }
329
471
  if (!fs.existsSync(notePath(where, role))) {
330
472
  throw new ShiftError(`No shift note waits for ${role}: it has not run \`keel shift ready\`, or already resumed.`);
331
473
  }
@@ -337,8 +479,19 @@ function start(where, role, text) {
337
479
  return store.post(where, { group, text: body, refs: [REF] });
338
480
  }
339
481
 
340
- function resume(where) {
341
- const role = store.currentRole(where);
482
+ // `--role` reads a role's note from a worktree bound to no other role (#293 D5).
483
+ function resumeRole(where, named) {
484
+ const bound = store.currentRole(where);
485
+ if (!named) return bound;
486
+ store.checkName(named, "Role");
487
+ if (bound && bound !== named) {
488
+ throw new ShiftError(`This worktree is bound to role ${bound}; --role ${named} names another role.`);
489
+ }
490
+ return named;
491
+ }
492
+
493
+ function resume(where, named = null) {
494
+ const role = resumeRole(where, named);
342
495
  const note = waitingNote(where, role);
343
496
  if (!note) return { role: role || null, note: null, text: null };
344
497
  const text = fs.readFileSync(note, "utf8");
@@ -355,9 +508,12 @@ function resume(where) {
355
508
  let told = null;
356
509
  if (latest && latest.from !== role) {
357
510
  const group = directGroup(where, role, latest.from);
358
- told = store.post(where, { group, text: `${role} is on shift, resumed from its shift note.`, refs: [REF] }).id;
511
+ const text = `${role} is on shift, resumed from its shift note.`;
512
+ told = (store.currentRole(where) === role
513
+ ? store.post(where, { group, text, refs: [REF] })
514
+ : store.writeRecord(where, { group, kind: "message", from: role, refs: [REF], text })).id;
359
515
  }
360
- return { role, note: history, text, told };
516
+ return { role, note: history, text, told, waiting: role ? unstarted(where, role) : [] };
361
517
  }
362
518
 
363
519
  function status(where) {
@@ -370,13 +526,28 @@ function status(where) {
370
526
  entry(todo.assignee).request = { id: todo.id, from: todo.from, created: todo.created, open: todo.open };
371
527
  }
372
528
  const dir = shiftDir(where);
529
+ const worktreeNotes = [];
373
530
  for (const [folder, prefix] of [[dir, ""], [path.join(dir, "worktree"), "worktree "]]) {
374
531
  for (const file of safeList(folder)) {
375
532
  if (!file.endsWith(".md")) continue;
376
533
  const stat = fs.statSync(path.join(folder, file));
377
- entry(`${prefix}${file.slice(0, -3)}`).note = store.isoLocal(stat.mtime);
534
+ const row = entry(`${prefix}${file.slice(0, -3)}`);
535
+ row.note = store.isoLocal(stat.mtime);
536
+ if (prefix) {
537
+ // The note's header names the worktree it was written in (#291 D6).
538
+ const header = fs.readFileSync(path.join(folder, file), "utf8").match(/^Written \S+ in (.+)\.$/m);
539
+ row.path = header ? header[1] : null;
540
+ worktreeNotes.push({ name: file.slice(0, -3), written: stat.mtime.getTime() });
541
+ }
378
542
  }
379
543
  }
544
+ // A role still requested may have handed over from another worktree (#290 D6).
545
+ for (const row of roles.values()) {
546
+ if (row.note || !row.request || !row.request.open) continue;
547
+ const since = Date.parse(row.request.created);
548
+ const later = worktreeNotes.filter((n) => !Number.isNaN(since) && n.written >= since).map((n) => n.name);
549
+ if (later.length) row.worktreeNotesSince = later;
550
+ }
380
551
  for (const file of safeList(path.join(dir, "history"))) {
381
552
  const match = file.match(/^(.+)-(\d{4}-\d{2}-\d{2}T\d+)\.md$/);
382
553
  if (!match) continue;
@@ -395,8 +566,20 @@ function safeList(dir) {
395
566
  }
396
567
 
397
568
  function describe(row) {
398
- if (row.note) return `${row.role}: note waiting since ${row.note}; \`keel shift start ${row.role}\` wakes it to resume`;
399
- if (row.request && row.request.open) return `${row.role}: change requested by ${row.request.from} at ${row.request.created}; not ready yet`;
569
+ if (row.note && row.role.startsWith("worktree ")) {
570
+ return `${row.role}: note waiting since ${row.note}; no chat role there, so tell the session in ${row.path || "that worktree"} to run \`keel shift resume\``;
571
+ }
572
+ // A note no request asked for is its own role's to resume (#293 D6).
573
+ if (row.note && !row.request) {
574
+ return `${row.role}: note waiting since ${row.note}; its own next session resumes it — woken by \`keel shift ready --wake\`, or by typing into it`;
575
+ }
576
+ if (row.note) return `${row.role}: note waiting since ${row.note}; another role's \`keel shift start ${row.role}\` wakes it to resume`;
577
+ if (row.request && row.request.open) {
578
+ const elsewhere = row.worktreeNotesSince
579
+ ? `; a worktree note was written since (${row.worktreeNotesSince.join(", ")}) — if it is ${row.role}'s, file it with \`keel shift ready --role ${row.role}\``
580
+ : "";
581
+ return `${row.role}: change requested by ${row.request.from} at ${row.request.created}; not ready yet${elsewhere}`;
582
+ }
400
583
  if (row.resumed) return `${row.role}: on shift, resumed ${row.resumed}`;
401
584
  return `${row.role}: ready was recorded without a note`;
402
585
  }
@@ -404,21 +587,39 @@ function describe(row) {
404
587
  // --- the command line --------------------------------------------------------------
405
588
 
406
589
  const CLEAR_HINT = [
590
+ "Session state a clear destroys — scheduled jobs, Remote Control — is not in Keel; if the note does not say how to re-create it, add that first.",
407
591
  "Now clear this session:",
408
592
  "- Claude desktop app: call `clear_session(\"self\")` (the owner approves it), or type /clear;",
409
593
  "- Claude Code CLI: /clear;",
410
594
  "- Codex: start a new session in this worktree.",
411
- "The coordinator's `keel shift start` then wakes the new shift; without chat roles, tell the new session to run `keel shift resume`.",
412
595
  ].join("\n");
413
596
 
597
+ // Who starts the new session (#293 D3): the coordinator that asked, nobody,
598
+ // or — without a chat role — the person who opens it.
599
+ function clearHint(result) {
600
+ let last;
601
+ if (!result.role) last = "Without a chat role, tell the new session to run `keel shift resume`.";
602
+ else if (result.waiter) {
603
+ last = `The wake is armed: once ${result.role}'s next session starts (after a clear or a fresh start), it gets one message to run \`keel shift resume\`. The waiter gives up after two hours.`;
604
+ } else if (result.closed.length) last = "The coordinator's `keel shift start` then wakes the new shift.";
605
+ else {
606
+ last = `No request named ${result.role}, so nobody is set to start the new session: type into it, `
607
+ + "or run `keel shift ready --wake` again with this note, which wakes it once it starts.";
608
+ }
609
+ return `${CLEAR_HINT}\n${last}`;
610
+ }
611
+
414
612
  function runShift(argv) {
415
- const options = { json: false, repo: process.cwd(), positionals: [], file: null, forceReason: null };
613
+ const options = { json: false, repo: process.cwd(), positionals: [], file: null, forceReason: null, role: null };
416
614
  for (let index = 0; index < argv.length; index += 1) {
417
615
  const arg = argv[index];
418
616
  if (arg === "--json") options.json = true;
419
617
  else if (arg === "--repo") options.repo = argv[++index] || "";
420
618
  else if (arg === "--file") options.file = argv[++index] || "";
421
619
  else if (arg === "--force-reason") options.forceReason = argv[++index] || "";
620
+ else if (arg === "--role") options.role = argv[++index] || "";
621
+ else if (arg === "--since") options.since = Number(argv[++index]);
622
+ else if (arg === "--wake") options.wake = true;
422
623
  else if (arg === "--help" || arg === "-h") {
423
624
  process.stdout.write(`${USAGE}\n`);
424
625
  return 0;
@@ -443,7 +644,15 @@ function runShift(argv) {
443
644
  case "ready": {
444
645
  const result = ready(where, { ...options, text: rest.join(" ") });
445
646
  const whose = result.role || "this worktree (no chat role, so no request to close)";
446
- out({ ...result, clear: CLEAR_HINT }, `Stored the shift note for ${whose} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${CLEAR_HINT}`);
647
+ const hint = clearHint(result);
648
+ out({ ...result, clear: hint }, `Stored the shift note for ${whose} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${hint}`);
649
+ return 0;
650
+ }
651
+ case "wake-wait": {
652
+ // Internal: the detached waiter `ready --wake` spawns.
653
+ if (!options.role || !Number.isFinite(options.since)) throw new ShiftError("keel shift wake-wait needs --role and --since.");
654
+ store.checkName(options.role, "Role");
655
+ waitForWake(where, options.role, options.since);
447
656
  return 0;
448
657
  }
449
658
  case "start": {
@@ -453,7 +662,7 @@ function runShift(argv) {
453
662
  return 0;
454
663
  }
455
664
  case "resume": {
456
- const result = resume(where);
665
+ const result = resume(where, options.role);
457
666
  if (!result.note) {
458
667
  out(result, `No shift note waits for ${result.role || "this worktree"}.`);
459
668
  return 0;
@@ -463,7 +672,10 @@ function runShift(argv) {
463
672
  const patrol = readPatrolDeclaration(where.worktree);
464
673
  const remind = patrol.role && result.role === patrol.role;
465
674
  if (remind) result.patrol = { role: patrol.role, every: patrol.every };
466
- out(result, `${result.text.replace(/\s+$/, "")}\n\n(The note moved to ${result.note}.)${remind ? `\n\n${patrolReminder(patrol)}` : ""}`);
675
+ // A new coordinator learns whom its previous shift left unstarted (#289 D2).
676
+ const waiting = (result.waiting || []).map((w) => w.role);
677
+ const still = waiting.length ? `\n\nStill waiting for \`keel shift start\`: ${waiting.join(", ")}.` : "";
678
+ out(result, `${result.text.replace(/\s+$/, "")}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}`);
467
679
  return 0;
468
680
  }
469
681
  case "status": {