@christang/keel 5.113.0 → 5.115.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
@@ -788,6 +790,15 @@ fetches nothing, schedules nothing, calls no model, and writes nothing when noth
788
790
  0 then, 2 when it sent something, and 1 on an error, so a cheap scheduler — cron, `/loop`, CI — can
789
791
  wake the model only on 2. `keel chat waits` lists what is still awaited.
790
792
 
793
+ A patrol on an hourly schedule should report change, not state, or it wakes the coordinator every
794
+ hour for a note deliberately left parked (#295). `keel patrol --since-last` keeps a snapshot per role
795
+ — shift status, the remote default branch tip, the main checkout's uncommitted paths, each role's
796
+ idleness and open todos, and the coordinator's addressed records unread beyond `--idle` — and prints
797
+ only `changed:` lines for what differs from the previous run; the first run records a baseline. It
798
+ writes that snapshot on every run, and exits 2 only when something changed. Add `--notify` and the
799
+ changes go to the coordinator as one direct message from `keel-patrol`, which wakes its session, so
800
+ the scheduled run needs no model judgment and no session id.
801
+
791
802
  With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
792
803
  maps a label to a role, and each role gets one direct message per update of an issue carrying its
793
804
  label — so a handoff labelled `role:verify` reaches `verify` without a second message.
@@ -807,6 +818,15 @@ patrol:
807
818
  every: 30m
808
819
  ```
809
820
 
821
+ Better, run the patrol outside the coordinator's session altogether, as a host scheduled task on a
822
+ small model, which survives the coordinator clearing itself (#295). Add `host_task: <id>` (and, if
823
+ you like, `model: <id>`, which Keel passes through and never chooses) and run `keel patrol task`: it
824
+ prints the task — id, a cron from `every:`, the model, and a self-contained prompt that runs
825
+ `keel patrol --since-last --notify` against the coordinator's worktree by path. Keel creates
826
+ nothing; the session's model installs it with the host's own scheduled-task tool, since a host keeps
827
+ the schedule itself. With `host_task:` declared, the reminder asks only to confirm the task is still
828
+ enabled.
829
+
810
830
  ## Commands
811
831
 
812
832
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.113.0 -->
1
+ <!-- keel:start version=5.115.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.113.0",
3
+ "version": "5.115.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.113.0",
9
+ "version": "5.115.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.113.0",
5
+ "version": "5.115.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.113.0",
3
+ "version": "5.115.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.113.0",
3
+ "version": "5.115.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",
@@ -661,7 +661,13 @@ function main() {
661
661
  );
662
662
  }
663
663
  // The patrolling role re-arms its schedule after a shift change (#260).
664
- if (context.patrol && context.patrol.role) {
664
+ if (context.patrol && context.patrol.role && context.patrol.hostTask) {
665
+ // A host scheduled task outlives the session (#295 D3).
666
+ lines.push(
667
+ `- patrol: role ${context.patrol.role} runs \`keel patrol\` every ${context.patrol.every} through host scheduled task `
668
+ + `${context.patrol.hostTask}, which outlives this session; confirm it is still enabled rather than creating a schedule in this session.`
669
+ );
670
+ } else if (context.patrol && context.patrol.role) {
665
671
  lines.push(
666
672
  `- patrol: role ${context.patrol.role} runs \`keel patrol\` every ${context.patrol.every}; `
667
673
  + "a session's schedule ends with the session, so re-create it with the host "
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.113.0"
51
- PROTOCOL_VERSION = "5.113.0"
50
+ PACKAGE_VERSION = "5.115.0"
51
+ PROTOCOL_VERSION = "5.115.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
@@ -2649,6 +2649,151 @@ def validate_patrol_rearm_scenario() -> int:
2649
2649
  return 0
2650
2650
 
2651
2651
 
2652
+ def validate_patrol_host_task_scenario() -> int:
2653
+ """Issue #295: `patrol:` names the host task; `keel patrol task` renders it.
2654
+
2655
+ The rendered task carries the id, a cron from `every:`, the declared model
2656
+ or none, and a prompt running the change-based patrol by path; it writes
2657
+ nothing. A declared host task changes the reminder.
2658
+ """
2659
+ label = "patrol-host-task:"
2660
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-host-") as raw:
2661
+ base = Path(raw)
2662
+ repo = mailbox_repository(base / "repo")
2663
+ write_text(repo / "openspec/specs/.keep", "")
2664
+ declaration = "patrol:\n role: rtl\n every: 30m\n host_task: soc-patrol\n"
2665
+ write_authorize_config(repo, declaration)
2666
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
2667
+ subprocess.run(["git", "commit", "-q", "-m", "patrol"], cwd=repo, check=True, capture_output=True)
2668
+ rtl = chat_worktree(repo, base / "rtl")
2669
+ env = chat_environment()
2670
+
2671
+ unbound = run_keel(rtl, "patrol", "task", env=env)
2672
+ if unbound.returncode == 0:
2673
+ report(f"{label} keel patrol task was accepted with no worktree bound to rtl.")
2674
+ return 1
2675
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
2676
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
2677
+ task = run_keel(rtl, "patrol", "task", env=env)
2678
+ if task.returncode != 0:
2679
+ report(f"{label} keel patrol task failed: {task.stdout} {task.stderr}")
2680
+ return 1
2681
+ for needle in ("soc-patrol", "*/30 * * * *", "no model is declared",
2682
+ f"keel patrol --repo {rtl.resolve()} --since-last --notify"):
2683
+ if needle not in task.stdout:
2684
+ report(f"{label} the rendered task does not carry {needle!r}: {task.stdout!r}")
2685
+ return 1
2686
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
2687
+ if before != after:
2688
+ report(f"{label} keel patrol task changed the worktree: {after!r}")
2689
+ return 1
2690
+ write_authorize_config(rtl, declaration + " model: small-model\n")
2691
+ modelled = run_keel(rtl, "patrol", "task", env=env)
2692
+ if "small-model" not in modelled.stdout:
2693
+ report(f"{label} the declared model is not rendered: {modelled.stdout!r}")
2694
+ return 1
2695
+ if "no model is declared" in modelled.stdout:
2696
+ report(f"{label} a declared model is still reported as undeclared: {modelled.stdout!r}")
2697
+ return 1
2698
+
2699
+ context = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
2700
+ if (context.get("patrol") or {}).get("hostTask") != "soc-patrol":
2701
+ report(f"{label} keel context carries patrol {context.get('patrol')!r}.")
2702
+ return 1
2703
+ session = run_session_start_hook(
2704
+ rtl, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(rtl)},
2705
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
2706
+ )
2707
+ note = session_start_context(session) or ""
2708
+ if "soc-patrol" not in note or "still enabled" not in note:
2709
+ report(f"{label} the session-start note does not name the host task: {note!r}")
2710
+ return 1
2711
+ if "re-create it with the host" in note:
2712
+ report(f"{label} the note still asks to re-create a session schedule: {note!r}")
2713
+ return 1
2714
+
2715
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 30m\n host_task: Bad_Id\n")
2716
+ broken = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
2717
+ if not any("host_task" in w and "Bad_Id" in w for w in broken.get("warnings", [])):
2718
+ report(f"{label} a malformed host_task is not reported by name: {broken.get('warnings')!r}")
2719
+ return 1
2720
+ report("patrol-host-task scenario passed.")
2721
+ return 0
2722
+
2723
+
2724
+ def validate_patrol_since_last_scenario() -> int:
2725
+ """Issue #295: a scheduled patrol reports only what changed, once.
2726
+
2727
+ `--since-last` records a baseline, then reports changed entries and exits
2728
+ 2; `--notify` sends them to the coordinator as one message from
2729
+ `keel-patrol`; an unchanged run is quiet. `--notify` alone is refused.
2730
+ """
2731
+ label = "patrol-since-last:"
2732
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-since-") as raw:
2733
+ base = Path(raw)
2734
+ rtl, verify, env, _ = shift_scratch(base)
2735
+
2736
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
2737
+ return run_keel(rtl, "patrol", *args, env=env)
2738
+
2739
+ def notices() -> list[str]:
2740
+ return chat_records_with(rtl, "dm-keel-patrol--rtl", "changed")
2741
+
2742
+ alone = patrol("--notify")
2743
+ if alone.returncode != 1:
2744
+ report(f"{label} --notify without --since-last exited {alone.returncode}.")
2745
+ return 1
2746
+ first = patrol("--since-last", "--notify")
2747
+ if first.returncode != 0:
2748
+ report(f"{label} the first run exited {first.returncode}: {first.stdout!r} {first.stderr!r}")
2749
+ return 1
2750
+ if "baseline recorded" not in first.stdout:
2751
+ report(f"{label} the first run did not record a baseline: {first.stdout!r}")
2752
+ return 1
2753
+ if notices():
2754
+ report(f"{label} the baseline run sent a notice.")
2755
+ return 1
2756
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
2757
+ if readied.returncode != 0:
2758
+ report(f"{label} verify's ready failed: {readied.stderr}")
2759
+ return 1
2760
+ for args in (["commit", "-q", "--allow-empty", "-m", "landed"], ["push", "-q", "origin", "HEAD"]):
2761
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
2762
+ second = patrol("--since-last", "--notify")
2763
+ if second.returncode != 2:
2764
+ report(f"{label} the run after a change exited {second.returncode}: {second.stdout!r} {second.stderr!r}")
2765
+ return 1
2766
+ changed = [line for line in second.stdout.splitlines() if line.startswith("changed:")]
2767
+ if not any("shift" in line and "verify" in line for line in changed):
2768
+ report(f"{label} the shift status change is not reported: {second.stdout!r}")
2769
+ return 1
2770
+ if not any("remote" in line for line in changed):
2771
+ report(f"{label} the remote tip change is not reported: {second.stdout!r}")
2772
+ return 1
2773
+ if len(notices()) != 1:
2774
+ report(f"{label} expected one keel-patrol notice after the change, found {len(notices())}.")
2775
+ return 1
2776
+ if "from: keel-patrol" not in notices()[0]:
2777
+ report(f"{label} the notice is not from keel-patrol: {notices()[0]!r}")
2778
+ return 1
2779
+ woken = run_keel(rtl, "chat", "notice", "--check", env=env)
2780
+ if woken.returncode != 0:
2781
+ report(f"{label} the notice does not wake rtl (notice --check exit {woken.returncode}).")
2782
+ return 1
2783
+ third = patrol("--since-last", "--notify")
2784
+ if third.returncode != 0:
2785
+ report(f"{label} an unchanged run exited {third.returncode}: {third.stdout!r}")
2786
+ return 1
2787
+ if "changed:" in third.stdout:
2788
+ report(f"{label} an unchanged run reported a change: {third.stdout!r}")
2789
+ return 1
2790
+ if len(notices()) != 1:
2791
+ report(f"{label} an unchanged run sent another notice.")
2792
+ return 1
2793
+ report("patrol-since-last scenario passed.")
2794
+ return 0
2795
+
2796
+
2652
2797
  def validate_coordinator_patrol_scenario() -> int:
2653
2798
  """Issue #260: declared waits, and a patrol that notifies once.
2654
2799
 
@@ -5512,6 +5657,141 @@ def validate_shift_role_elsewhere_scenario() -> int:
5512
5657
  return 0
5513
5658
 
5514
5659
 
5660
+ def validate_shift_self_scenario() -> int:
5661
+ """Issue #293: a role with no coordinator changes its own shift.
5662
+
5663
+ It cannot start itself, `ready` says nobody will start the new session,
5664
+ status says its own next session resumes the note, and a new session in
5665
+ an unbound worktree resumes it with `--role`.
5666
+ """
5667
+ label = "shift-self:"
5668
+ with tempfile.TemporaryDirectory(prefix="keel-shift-self-") as raw:
5669
+ base = Path(raw)
5670
+ rtl, _verify, env, _ = shift_scratch(base)
5671
+ pm = chat_worktree(rtl, base / "pm")
5672
+ other = chat_worktree(rtl, base / "other")
5673
+ for tree in (pm, other):
5674
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
5675
+ run_keel(pm, "chat", "role", "--set", "pm", env=env)
5676
+
5677
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
5678
+ return run_keel(cwd, "shift", *args, env=env)
5679
+
5680
+ readied = shift(pm, "ready", "pm note: next is R009")
5681
+ if readied.returncode != 0:
5682
+ report(f"{label} pm's ready failed: {readied.stderr}")
5683
+ return 1
5684
+ if "nobody" not in readied.stdout:
5685
+ report(f"{label} ready does not say nobody is set to start the new session: {readied.stdout!r}")
5686
+ return 1
5687
+ if "--wake" not in readied.stdout:
5688
+ report(f"{label} ready does not name --wake: {readied.stdout!r}")
5689
+ return 1
5690
+ if "The coordinator's `keel shift start` then wakes" in readied.stdout:
5691
+ report(f"{label} ready still promises a coordinator's start to a role nobody asked: {readied.stdout!r}")
5692
+ return 1
5693
+ itself = shift(pm, "start", "pm")
5694
+ if itself.returncode == 0:
5695
+ report(f"{label} keel shift start pm by pm was accepted.")
5696
+ return 1
5697
+ if "ready --wake" not in itself.stderr:
5698
+ report(f"{label} the refusal does not name ready --wake: {itself.stderr}")
5699
+ return 1
5700
+ if chat_log(rtl, "dm-pm--pm").exists():
5701
+ report(f"{label} a refused self-start still created dm-pm--pm.")
5702
+ return 1
5703
+ status = shift(rtl, "status").stdout
5704
+ line = next((l for l in status.splitlines() if l.startswith("pm:")), "")
5705
+ if "own next session" not in line:
5706
+ report(f"{label} status does not say pm's own next session resumes its note: {line!r}")
5707
+ return 1
5708
+ misbound = shift(rtl, "resume", "--role", "pm")
5709
+ if misbound.returncode == 0:
5710
+ report(f"{label} resume --role pm in rtl's worktree was accepted.")
5711
+ return 1
5712
+ resumed = shift(other, "resume", "--role", "pm")
5713
+ if resumed.returncode != 0:
5714
+ report(f"{label} resume --role pm in an unbound worktree failed: {resumed.stderr}")
5715
+ return 1
5716
+ if "next is R009" not in resumed.stdout:
5717
+ report(f"{label} resume --role pm did not print pm's note: {resumed.stdout!r}")
5718
+ return 1
5719
+ if (mailbox_common_dir(rtl) / "keel-chat" / "shift" / "pm.md").exists():
5720
+ report(f"{label} pm's note still waits after resume --role pm.")
5721
+ return 1
5722
+ report("shift-self scenario passed.")
5723
+ return 0
5724
+
5725
+
5726
+ def validate_shift_self_wake_scenario() -> int:
5727
+ """Issue #293: `ready --wake` wakes the role's next session, once.
5728
+
5729
+ A `compact` start does not trigger the waiter; a `clear` start does, and
5730
+ the role then has exactly one waking record from `keel-shift`. Without a
5731
+ chat role, `--wake` is refused.
5732
+ """
5733
+ label = "shift-self-wake:"
5734
+ protocol = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
5735
+ line = next((l for l in protocol.splitlines() if l.startswith("- Keel schedules nothing")), "")
5736
+ if "keel shift ready --wake" not in line:
5737
+ report(f"{label} the protocol's scheduling line does not name the keel shift ready --wake exception: {line!r}")
5738
+ return 1
5739
+ with tempfile.TemporaryDirectory(prefix="keel-shift-wake-") as raw:
5740
+ base = Path(raw)
5741
+ rtl, verify, env, _ = shift_scratch(base)
5742
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
5743
+ loose = chat_worktree(rtl, base / "loose")
5744
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=loose, check=True, capture_output=True)
5745
+
5746
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
5747
+ return run_keel(cwd, "shift", *args, env=env)
5748
+
5749
+ def session_start(source: str) -> None:
5750
+ subprocess.run(
5751
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"],
5752
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
5753
+ input=json.dumps({"cwd": str(verify), "source": source, "hook_event_name": "SessionStart"}),
5754
+ )
5755
+
5756
+ def wakes() -> list[str]:
5757
+ return chat_records_with(rtl, "dm-keel-shift--verify", "keel shift resume")
5758
+
5759
+ unbound = shift(loose, "ready", "--wake", "loose note")
5760
+ if unbound.returncode == 0:
5761
+ report(f"{label} ready --wake in an unbound worktree with no --role was accepted.")
5762
+ return 1
5763
+ armed = shift(verify, "ready", "--wake", "verify note: next is R010")
5764
+ if armed.returncode != 0:
5765
+ report(f"{label} ready --wake failed: {armed.stderr}")
5766
+ return 1
5767
+ session_start("compact")
5768
+ time.sleep(1)
5769
+ if wakes():
5770
+ report(f"{label} a compact start triggered the wake.")
5771
+ return 1
5772
+ session_start("clear")
5773
+ deadline = time.time() + 5
5774
+ while time.time() < deadline and not wakes():
5775
+ time.sleep(0.1)
5776
+ found = wakes()
5777
+ if len(found) != 1:
5778
+ report(f"{label} expected exactly one wake record from keel-shift after the clear start, found {len(found)}.")
5779
+ return 1
5780
+ if "from: keel-shift" not in found[0]:
5781
+ report(f"{label} the wake record is not from keel-shift: {found[0]!r}")
5782
+ return 1
5783
+ time.sleep(0.5)
5784
+ if len(wakes()) != 1:
5785
+ report(f"{label} the waiter wrote more than one wake record.")
5786
+ return 1
5787
+ checked = run_keel(verify, "chat", "notice", "--check", env=env)
5788
+ if checked.returncode != 0:
5789
+ report(f"{label} keel chat notice --check for verify does not see the wake (exit {checked.returncode}).")
5790
+ return 1
5791
+ report("shift-self-wake scenario passed.")
5792
+ return 0
5793
+
5794
+
5515
5795
  def validate_shift_coordinator_last_scenario() -> int:
5516
5796
  """Issue #289: the coordinator starts the others before its own shift ends.
5517
5797
 
@@ -39185,11 +39465,15 @@ SCENARIOS: tuple = (
39185
39465
  ("shift-change", validate_shift_change_scenario),
39186
39466
  ("shift-role-elsewhere", validate_shift_role_elsewhere_scenario),
39187
39467
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39468
+ ("shift-self", validate_shift_self_scenario),
39469
+ ("shift-self-wake", validate_shift_self_wake_scenario),
39188
39470
  ("shift-without-role", validate_shift_without_role_scenario),
39189
39471
  ("resource-lock", validate_resource_lock_scenario),
39190
39472
  ("chat-supersedes", validate_chat_supersedes_scenario),
39191
39473
  ("chat-ack", validate_chat_ack_scenario),
39192
39474
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39475
+ ("patrol-since-last", validate_patrol_since_last_scenario),
39476
+ ("patrol-host-task", validate_patrol_host_task_scenario),
39193
39477
  ("patrol-rearm", validate_patrol_rearm_scenario),
39194
39478
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
39195
39479
  ("chat-listen-only", validate_chat_listen_only_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,
@@ -876,22 +876,41 @@ function readIssueRoles(repo) {
876
876
  // `patrol:` — which role runs `keel patrol`, and how often (#260). Keel only
877
877
  // reminds that role to re-create its host schedule; it schedules nothing. A
878
878
  // declaration missing a value, or with a malformed one, reminds nobody.
879
+ // `host_task:` names the host scheduled task that runs it and `model:` the
880
+ // model that task declares (#295 D3); Keel passes a model through and never
881
+ // chooses one, and a malformed one of these is ignored by name.
879
882
  function readPatrolDeclaration(repo) {
880
883
  const block = configMap(repo, "patrol");
881
- if (!Object.keys(block).length) return { declared: false, role: null, every: null, message: null };
884
+ if (!Object.keys(block).length) return { declared: false, role: null, every: null, hostTask: null, model: null, message: null };
882
885
  const problems = [];
883
886
  if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(block.role || "")) problems.push(`role \`${block.role || ""}\` is not a chat role name`);
884
887
  if (!/^\d+[smhd]$/.test(block.every || "")) problems.push(`every \`${block.every || ""}\` is not a duration such as 30m`);
885
888
  if (problems.length) {
886
889
  return {
887
- declared: true, role: null, every: null,
890
+ declared: true, role: null, every: null, hostTask: null, model: null,
888
891
  message: `keel/config.yaml patrol: ${problems.join("; ")}, so no session is reminded to run \`keel patrol\`.`,
889
892
  };
890
893
  }
891
- return { declared: true, role: block.role, every: block.every, message: null };
894
+ const ignored = [];
895
+ let hostTask = null;
896
+ let model = null;
897
+ if (block.host_task !== undefined) {
898
+ if (/^[a-z0-9][a-z0-9-]{0,63}$/.test(block.host_task)) hostTask = block.host_task;
899
+ else ignored.push(`host_task \`${block.host_task}\` is not a task id such as soc-patrol`);
900
+ }
901
+ if (block.model !== undefined) {
902
+ if (/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(block.model)) model = block.model;
903
+ else ignored.push(`model \`${block.model}\` is not a model id`);
904
+ }
905
+ const message = ignored.length ? `keel/config.yaml patrol: ${ignored.join("; ")}, so it is ignored.` : null;
906
+ return { declared: true, role: block.role, every: block.every, hostTask, model, message };
892
907
  }
893
908
 
894
909
  function patrolReminder(patrol) {
910
+ if (patrol.hostTask) {
911
+ return `Patrol: role ${patrol.role} runs \`keel patrol\` every ${patrol.every} through host scheduled task `
912
+ + `${patrol.hostTask}, which outlives this session; confirm it is still enabled rather than creating a schedule in this session.`;
913
+ }
895
914
  return `Patrol: role ${patrol.role} runs \`keel patrol\` every ${patrol.every}; a session's schedule ends with `
896
915
  + "the session, so re-create it with the host if this session has none, and wake the model only on exit 2.";
897
916
  }
@@ -851,7 +851,10 @@ function resolveContext(repo, options) {
851
851
  // The patrolling role is reminded to re-arm its schedule (#260).
852
852
  const patrol = readPatrolDeclaration(repo);
853
853
  if (patrol.message) context.warnings.push(patrol.message);
854
- if (patrol.role && context.role === patrol.role) context.patrol = { role: patrol.role, every: patrol.every };
854
+ if (patrol.role && context.role === patrol.role) {
855
+ context.patrol = { role: patrol.role, every: patrol.every };
856
+ if (patrol.hostTask) context.patrol.hostTask = patrol.hostTask;
857
+ }
855
858
  context.warnings.push(...gitWarnings(repo));
856
859
  // A broken `authorize:` declaration is otherwise reported only by
857
860
  // `keel --doctor`, an explicitly-invoked diagnostic — surfaced here too so a
@@ -12,7 +12,8 @@ const store = require("./chat/store");
12
12
  const notice = require("./chat/notice");
13
13
  const { parseSince } = require("./chat/view");
14
14
 
15
- const USAGE = "keel patrol [--issues <file>] [--idle <90s|15m|2h|3d>] [--json] [--repo <path>]";
15
+ const USAGE = "keel patrol [--issues <file>] [--idle <90s|15m|2h|3d>] [--since-last [--notify]] [--json] [--repo <path>]\n keel patrol task [--json] [--repo <path>] print the host scheduled task for `patrol:`";
16
+ const NOTIFY_SENDER = "keel-patrol";
16
17
  const EXIT_QUIET = 0;
17
18
  const EXIT_ERROR = 1;
18
19
  const EXIT_WROTE = 2;
@@ -121,25 +122,183 @@ function routeIssues(where, role, options) {
121
122
  return { notices, warnings };
122
123
  }
123
124
 
125
+ // --- what changed since the last run (#295 D1, D2) ------------------------------------
126
+
127
+ function snapshotFile(where, role) {
128
+ return path.join(where.root, "patrol", `${role}.json`);
129
+ }
130
+
131
+ function primaryWorktree(where) {
132
+ const list = git(where.worktree, ["worktree", "list", "--porcelain"]);
133
+ const first = list && list.split("\n").find((line) => line.startsWith("worktree "));
134
+ return first ? first.slice("worktree ".length) : null;
135
+ }
136
+
137
+ // The entries a scheduled run compares, keyed so a change names its subject.
138
+ function currentSnapshot(where, role, result, options) {
139
+ const shift = require("./shift");
140
+ const entries = {};
141
+ for (const row of shift.shiftStatus(where)) entries[`shift ${row.role}`] = shift.describe(row);
142
+ const base = require("./worktrees").defaultBranch(where.worktree);
143
+ if (base) {
144
+ const ref = `refs/remotes/origin/${base.replace(/^origin\//, "")}`;
145
+ entries[`remote ${ref.replace(/^refs\/remotes\//, "")}`] = git(where.worktree, ["rev-parse", "--verify", "--quiet", ref]) || "none";
146
+ }
147
+ const primary = primaryWorktree(where);
148
+ if (primary) {
149
+ const status = git(primary, ["status", "--porcelain"]);
150
+ if (status !== null) entries[`checkout ${primary}`] = `${status ? status.split("\n").length : 0} uncommitted paths`;
151
+ }
152
+ for (const row of result.roles) {
153
+ entries[`role ${row.role}`] = `${row.idle ? "idle" : "active"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`;
154
+ }
155
+ const threshold = parseSince(options.idle);
156
+ const unread = store.unread(where, role)
157
+ .filter((record) => store.wakes(record, role) && Date.parse(record.created || "") < threshold)
158
+ .map((record) => ({ id: record.id, from: record.from, created: record.created }));
159
+ return { entries, unread };
160
+ }
161
+
162
+ function sinceLast(where, role, result, options) {
163
+ const file = snapshotFile(where, role);
164
+ const previous = fs.existsSync(file) ? store.readJsonFile(file) : null;
165
+ const now = currentSnapshot(where, role, result, options);
166
+ store.writeJsonAtomic(where, file, now);
167
+ if (!previous || !previous.entries) return { baseline: true, changes: [] };
168
+ const changes = [];
169
+ const keys = [...new Set([...Object.keys(previous.entries), ...Object.keys(now.entries)])].sort();
170
+ for (const key of keys) {
171
+ const before = previous.entries[key] ?? "(none)";
172
+ const after = now.entries[key] ?? "(none)";
173
+ if (before !== after) changes.push(`${key}: ${before} -> ${after}`);
174
+ }
175
+ const seen = new Set((previous.unread || []).map((record) => record.id));
176
+ for (const record of now.unread) {
177
+ if (!seen.has(record.id)) changes.push(`unread: ${record.id} from ${record.from}, unanswered since ${record.created}`);
178
+ }
179
+ return { baseline: false, changes };
180
+ }
181
+
182
+ function notifyChanges(where, role, changes) {
183
+ const group = store.directName(NOTIFY_SENDER, role);
184
+ if (!store.groupState(store.readLog(where, group)).exists) {
185
+ store.createGroup(where, NOTIFY_SENDER, group, [role], { direct: true });
186
+ }
187
+ const text = [`Patrol ${store.isoLocal(new Date())}: what changed since the last run:`, ...changes.map((line) => `- changed: ${line}`)].join("\n");
188
+ return store.writeRecord(where, { group, kind: "message", from: NOTIFY_SENDER, refs: [NOTIFY_SENDER], text });
189
+ }
190
+
124
191
  function render(result) {
125
192
  const lines = [];
126
- if (!result.notices.length && !result.held.length) lines.push("keel patrol: nothing new.");
193
+ const changes = result.sinceLast ? result.sinceLast.changes : [];
194
+ if (result.sinceLast && result.sinceLast.baseline) lines.push("keel patrol: baseline recorded.");
195
+ else if (!result.notices.length && !result.held.length && !changes.length) lines.push("keel patrol: nothing new.");
196
+ for (const change of changes) lines.push(`changed: ${change}`);
127
197
  for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
128
198
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
129
199
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
130
200
  for (const warning of result.warnings) lines.push(`warning: ${warning}`);
131
- for (const row of result.roles) {
201
+ // A scheduled run reports roles only through what changed (D1).
202
+ for (const row of result.sinceLast ? [] : result.roles) {
132
203
  lines.push(`role ${row.role}: ${row.presence}${row.idle ? " (idle)" : ""}, last active ${row.lastActive || "unknown"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`);
133
204
  }
134
205
  return lines.join("\n");
135
206
  }
136
207
 
208
+ // --- the host task (#295 D4) ---------------------------------------------------------
209
+ //
210
+ // Keel renders the task and creates nothing: a host's schedule is set through
211
+ // its own tool, which the session's model calls (F1).
212
+
213
+ function suggestCron(every) {
214
+ const match = String(every).match(/^(\d+)([smhd])$/);
215
+ const n = match ? Number(match[1]) : 0;
216
+ const unit = match ? match[2] : "";
217
+ if ((unit === "m" && n === 60) || (unit === "h" && n === 1)) return { cron: "0 * * * *" };
218
+ if (unit === "m" && n > 0 && n < 60 && 60 % n === 0) return { cron: `*/${n} * * * *` };
219
+ if (unit === "h" && n > 1 && 24 % n === 0) return { cron: `0 */${n} * * *` };
220
+ if (unit === "d" && n === 1) return { cron: "0 9 * * *" };
221
+ return { cron: null, why: `every: ${every} has no plain cron form; choose a schedule near it` };
222
+ }
223
+
224
+ function shellPath(file) {
225
+ return /[\s"'$`\\]/.test(file) ? JSON.stringify(file) : file;
226
+ }
227
+
228
+ function hostTask(where) {
229
+ const config = require("./config");
230
+ const declaration = config.readPatrolDeclaration(where.worktree);
231
+ if (!declaration.role) {
232
+ throw new PatrolError(declaration.message || "keel/config.yaml declares no `patrol:` with role and every, so there is no patrol task to render.");
233
+ }
234
+ const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
235
+ .filter(([, role]) => role === declaration.role).map(([worktree]) => worktree).sort();
236
+ if (!bound.length) {
237
+ throw new PatrolError(`No worktree is bound to role ${declaration.role}; bind one with \`keel chat role --set ${declaration.role}\` there first.`);
238
+ }
239
+ const worktree = bound[0];
240
+ const role = declaration.role;
241
+ const at = shellPath(worktree);
242
+ const schedule = suggestCron(declaration.every);
243
+ const prompt = [
244
+ `You run the Keel patrol for chat role ${role} of the repository at ${worktree}. Do exactly the steps below and nothing else.`,
245
+ "",
246
+ `Do not change into that directory: run every command with the paths given, so this session does not act as ${role} (Keel's session hooks follow the working directory). `
247
+ + "Do not edit files, commit, push, close or comment on issues, or message anyone yourself: `keel patrol` sends the coordinator what changed.",
248
+ "",
249
+ `1. Run \`git -C ${at} fetch -q origin\`. If it fails, keep its error and continue.`,
250
+ `2. Run \`keel patrol --repo ${at} --since-last --notify\`.`,
251
+ `3. Exit 0: nothing changed. Exit 2: keel has already told ${role}. In both cases end without output. `
252
+ + "Exit 1: end with one line, `keel patrol failed: <its error output>`, adding the fetch error from step 1 if there was one.",
253
+ ].join("\n");
254
+ return {
255
+ taskId: declaration.hostTask || `keel-patrol-${role}`,
256
+ description: `Keel patrol for role ${role}: tells it what changed since the last run`,
257
+ cronExpression: schedule.cron,
258
+ cronNote: schedule.why || null,
259
+ every: declaration.every,
260
+ model: declaration.model,
261
+ worktree,
262
+ prompt,
263
+ };
264
+ }
265
+
266
+ function renderTask(task) {
267
+ return [
268
+ `Host scheduled task for the patrol of role ${task.prompt.match(/chat role (\S+)/)[1]}. Keel creates nothing: install it with the host's scheduled-task tool.`,
269
+ `task id: ${task.taskId}`,
270
+ `schedule: ${task.cronExpression ? `${task.cronExpression} (from every: ${task.every}; hosts may add jitter)` : task.cronNote}`,
271
+ `model: ${task.model || "no model is declared: choose a small model; Keel names none"}`,
272
+ `description: ${task.description}`,
273
+ "prompt:",
274
+ task.prompt,
275
+ ].join("\n");
276
+ }
277
+
137
278
  function runPatrol(argv) {
138
- const options = { repo: process.cwd(), issues: null, idle: "30m", json: false };
279
+ if (argv[0] === "task") {
280
+ const json = argv.includes("--json");
281
+ const at = argv.indexOf("--repo");
282
+ try {
283
+ const where = store.requireLocation(path.resolve(at >= 0 ? argv[at + 1] || "" : process.cwd()));
284
+ const task = hostTask(where);
285
+ process.stdout.write(`${json ? JSON.stringify(task, null, 2) : renderTask(task)}\n`);
286
+ return EXIT_QUIET;
287
+ } catch (error) {
288
+ if (error instanceof PatrolError || error instanceof store.ChatError) {
289
+ process.stderr.write(`keel patrol task: ${error.message}\n`);
290
+ return EXIT_ERROR;
291
+ }
292
+ throw error;
293
+ }
294
+ }
295
+ const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false };
139
296
  try {
140
297
  for (let index = 0; index < argv.length; index += 1) {
141
298
  const arg = argv[index];
142
299
  if (arg === "--json") options.json = true;
300
+ else if (arg === "--since-last") options.sinceLast = true;
301
+ else if (arg === "--notify") options.notify = true;
143
302
  else if (arg === "--help" || arg === "-h") {
144
303
  process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
145
304
  return EXIT_QUIET;
@@ -149,13 +308,19 @@ function runPatrol(argv) {
149
308
  options[arg.slice(2)] = value;
150
309
  } else throw new PatrolError(`Unknown argument ${arg}. ${USAGE}`);
151
310
  }
311
+ if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends what changed, so it needs --since-last.");
152
312
  if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
153
313
  options.issues = readIssues(options.issues);
154
314
  const where = store.requireLocation(path.resolve(options.repo));
155
315
  const role = store.requireRole(where);
156
316
  const result = patrol(where, role, options);
317
+ if (options.sinceLast) {
318
+ result.sinceLast = sinceLast(where, role, result, options);
319
+ if (options.notify && result.sinceLast.changes.length) result.notified = notifyChanges(where, role, result.sinceLast.changes).id;
320
+ }
157
321
  process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
158
- return result.notices.length || result.held.length ? EXIT_WROTE : EXIT_QUIET;
322
+ const changed = result.sinceLast && result.sinceLast.changes.length;
323
+ return result.notices.length || result.held.length || changed ? EXIT_WROTE : EXIT_QUIET;
159
324
  } catch (error) {
160
325
  if (error instanceof PatrolError || error instanceof store.ChatError) {
161
326
  process.stderr.write(`keel patrol: ${error.message}\n`);
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
 
@@ -25,8 +25,9 @@ const USAGE = [
25
25
  "keel shift ready [text | --file f] store the shift note, close the request (refused while loose)",
26
26
  " [--role r] ...under role r, from a worktree bound to no role (#290)",
27
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)",
28
29
  "keel shift start <role> [text] wake the cleared role to resume (once its note waits)",
29
- "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)",
30
31
  "keel shift status [--json] each role's shift state",
31
32
  "Options: --repo <path>. See docs/shift-change.md.",
32
33
  ].join("\n");
@@ -363,6 +364,10 @@ function readyRole(where, options) {
363
364
 
364
365
  function ready(where, options) {
365
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();
366
371
  const result = check(where, role);
367
372
  if (!result.ready && !options.forceReason) {
368
373
  throw new ShiftError(`${renderCheck(result)}\nResolve these, or give --force-reason "<why they may stay>".`);
@@ -392,12 +397,77 @@ function ready(where, options) {
392
397
  store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
393
398
  }
394
399
  }
395
- 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();
396
462
  }
397
463
 
398
464
  function start(where, role, text) {
399
465
  const from = requireRole(where);
400
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
+ }
401
471
  if (!fs.existsSync(notePath(where, role))) {
402
472
  throw new ShiftError(`No shift note waits for ${role}: it has not run \`keel shift ready\`, or already resumed.`);
403
473
  }
@@ -409,8 +479,19 @@ function start(where, role, text) {
409
479
  return store.post(where, { group, text: body, refs: [REF] });
410
480
  }
411
481
 
412
- function resume(where) {
413
- 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);
414
495
  const note = waitingNote(where, role);
415
496
  if (!note) return { role: role || null, note: null, text: null };
416
497
  const text = fs.readFileSync(note, "utf8");
@@ -427,7 +508,10 @@ function resume(where) {
427
508
  let told = null;
428
509
  if (latest && latest.from !== role) {
429
510
  const group = directGroup(where, role, latest.from);
430
- 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;
431
515
  }
432
516
  return { role, note: history, text, told, waiting: role ? unstarted(where, role) : [] };
433
517
  }
@@ -485,7 +569,11 @@ function describe(row) {
485
569
  if (row.note && row.role.startsWith("worktree ")) {
486
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\``;
487
571
  }
488
- if (row.note) return `${row.role}: note waiting since ${row.note}; \`keel shift start ${row.role}\` wakes it to resume`;
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`;
489
577
  if (row.request && row.request.open) {
490
578
  const elsewhere = row.worktreeNotesSince
491
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}\``
@@ -504,9 +592,23 @@ const CLEAR_HINT = [
504
592
  "- Claude desktop app: call `clear_session(\"self\")` (the owner approves it), or type /clear;",
505
593
  "- Claude Code CLI: /clear;",
506
594
  "- Codex: start a new session in this worktree.",
507
- "The coordinator's `keel shift start` then wakes the new shift; without chat roles, tell the new session to run `keel shift resume`.",
508
595
  ].join("\n");
509
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
+
510
612
  function runShift(argv) {
511
613
  const options = { json: false, repo: process.cwd(), positionals: [], file: null, forceReason: null, role: null };
512
614
  for (let index = 0; index < argv.length; index += 1) {
@@ -516,6 +618,8 @@ function runShift(argv) {
516
618
  else if (arg === "--file") options.file = argv[++index] || "";
517
619
  else if (arg === "--force-reason") options.forceReason = argv[++index] || "";
518
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;
519
623
  else if (arg === "--help" || arg === "-h") {
520
624
  process.stdout.write(`${USAGE}\n`);
521
625
  return 0;
@@ -540,7 +644,15 @@ function runShift(argv) {
540
644
  case "ready": {
541
645
  const result = ready(where, { ...options, text: rest.join(" ") });
542
646
  const whose = result.role || "this worktree (no chat role, so no request to close)";
543
- 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);
544
656
  return 0;
545
657
  }
546
658
  case "start": {
@@ -550,7 +662,7 @@ function runShift(argv) {
550
662
  return 0;
551
663
  }
552
664
  case "resume": {
553
- const result = resume(where);
665
+ const result = resume(where, options.role);
554
666
  if (!result.note) {
555
667
  out(result, `No shift note waits for ${result.role || "this worktree"}.`);
556
668
  return 0;
@@ -559,7 +671,7 @@ function runShift(argv) {
559
671
  const { readPatrolDeclaration, patrolReminder } = require("./config");
560
672
  const patrol = readPatrolDeclaration(where.worktree);
561
673
  const remind = patrol.role && result.role === patrol.role;
562
- if (remind) result.patrol = { role: patrol.role, every: patrol.every };
674
+ if (remind) result.patrol = { role: patrol.role, every: patrol.every, ...(patrol.hostTask ? { hostTask: patrol.hostTask } : {}) };
563
675
  // A new coordinator learns whom its previous shift left unstarted (#289 D2).
564
676
  const waiting = (result.waiting || []).map((w) => w.role);
565
677
  const still = waiting.length ? `\n\nStill waiting for \`keel shift start\`: ${waiting.join(", ")}.` : "";
@@ -594,4 +706,4 @@ function waitingFor(repo) {
594
706
  return { note, since: store.isoLocal(fs.statSync(note).mtime) };
595
707
  }
596
708
 
597
- module.exports = { check, runShift, waitingFor };
709
+ module.exports = { check, describe, runShift, shiftStatus: status, waitingFor };