@christang/keel 5.114.0 → 5.116.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
@@ -770,7 +770,7 @@ Without a known default branch, no issue range is inferred.
770
770
 
771
771
  ## Group chat between sessions
772
772
 
773
- Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. A member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). A session's chat role is its identity: address other sessions by role, never by the host's session title, which Keel cannot see; `keel context` and the session projection name the role bound to the worktree, and remind a worktree with none when others here have one (#245). Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). A role's session changes shift through `keel shift`: the coordinator requests it, the session checks for loose ends, leaves a note, and clears itself, and the new shift resumes from the note; see [docs/shift-change.md](docs/shift-change.md). The 5.83 `keel mail` commands keep working on direct groups.
773
+ Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. A member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). A session's chat role is its identity: address other sessions by role, never by the host's session title, which Keel cannot see; `keel context` and the session projection name the role bound to the worktree, and remind a worktree with none when others here have one (#245). Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Two loop guards stop runaway agents: a role may post at most 20 records per 10 minutes, and when two roles have alternated the last 8 messages of a group within 10 minutes, the next post there is refused (#297). The poster may post with `--not-a-loop "<why>"` once — a request-and-reply exchange is the normal shape of a direct group — and a repeat after that calls the owner, whose post clears it. `limits` in `keel/chat.json` sets `rate`, `window_minutes`, `pingpong`, and `pingpong_minutes`. A time in a message should come from Keel's clock, not an estimate: `keel chat post` and `keel chat dm` take `--stamp`, which prefixes `[MM-DD HH:MM]` (#298). Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). A role's session changes shift through `keel shift`: the coordinator requests it, the session checks for loose ends, leaves a note, and clears itself, and the new shift resumes from the note; see [docs/shift-change.md](docs/shift-change.md). The 5.83 `keel mail` commands keep working on direct groups.
774
774
 
775
775
  ## Coordinator patrol
776
776
 
@@ -790,6 +790,15 @@ fetches nothing, schedules nothing, calls no model, and writes nothing when noth
790
790
  0 then, 2 when it sent something, and 1 on an error, so a cheap scheduler — cron, `/loop`, CI — can
791
791
  wake the model only on 2. `keel chat waits` lists what is still awaited.
792
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
+
793
802
  With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
794
803
  maps a label to a role, and each role gets one direct message per update of an issue carrying its
795
804
  label — so a handoff labelled `role:verify` reaches `verify` without a second message.
@@ -809,6 +818,15 @@ patrol:
809
818
  every: 30m
810
819
  ```
811
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
+
812
830
  ## Commands
813
831
 
814
832
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.114.0 -->
1
+ <!-- keel:start version=5.116.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.114.0",
3
+ "version": "5.116.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.114.0",
9
+ "version": "5.116.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.114.0",
5
+ "version": "5.116.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.114.0",
3
+ "version": "5.116.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.114.0",
3
+ "version": "5.116.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.114.0"
51
- PROTOCOL_VERSION = "5.114.0"
50
+ PACKAGE_VERSION = "5.116.0"
51
+ PROTOCOL_VERSION = "5.116.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
@@ -2583,6 +2583,45 @@ def chat_logs_snapshot(repo: Path) -> dict:
2583
2583
  return {str(p): p.read_bytes() for p in groups.rglob("*") if p.is_file()}
2584
2584
 
2585
2585
 
2586
+ def validate_chat_stamp_help_scenario() -> int:
2587
+ """Issue #298: `--stamp` writes Keel's time; `keel chat --help` is not an error."""
2588
+ label = "chat-stamp-help:"
2589
+ with tempfile.TemporaryDirectory(prefix="keel-chat-stamp-") as raw:
2590
+ base = Path(raw)
2591
+ rtl, _verify, env = chat_scratch_group(base)
2592
+
2593
+ def stamped(group: str, *args: str) -> str | None:
2594
+ posted = run_keel(rtl, "chat", *args, env=env)
2595
+ if posted.returncode != 0:
2596
+ return f"{' '.join(args)} failed: {posted.stderr.strip()}"
2597
+ record = sorted(chat_log(rtl, group).glob("*.md"))[-1].read_text(encoding="utf-8")
2598
+ created = re.search(r"^created: \d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})", record, re.M)
2599
+ if not created:
2600
+ return f"the record has no created time:\n{record}"
2601
+ month, day, hour, minute = created.groups()
2602
+ want = f"[{month}-{day} {hour}:{minute}] "
2603
+ body = record.split("\n---\n", 1)[1].strip()
2604
+ if not body.startswith(want):
2605
+ return f"{' '.join(args)} stored {body!r}, not text starting with {want!r}"
2606
+ return None
2607
+
2608
+ for group, args in (("soc", ("post", "soc", "--stamp", "R008 done")), ("dm-rtl--verify", ("dm", "verify", "--stamp", "x"))):
2609
+ problem = stamped(group, *args)
2610
+ if problem:
2611
+ report(f"{label} {problem}")
2612
+ return 1
2613
+ for flag in ("--help", "-h"):
2614
+ helped = run_keel(rtl, "chat", flag, env=env)
2615
+ if helped.returncode != 0:
2616
+ report(f"{label} keel chat {flag} exited {helped.returncode}: {helped.stderr.strip()}")
2617
+ return 1
2618
+ if "Usage:" not in helped.stdout:
2619
+ report(f"{label} keel chat {flag} printed no usage: {helped.stdout!r}")
2620
+ return 1
2621
+ report("chat-stamp-help scenario passed.")
2622
+ return 0
2623
+
2624
+
2586
2625
  def validate_patrol_rearm_scenario() -> int:
2587
2626
  """Issue #260: the patrolling role is reminded to re-arm its schedule.
2588
2627
 
@@ -2649,6 +2688,151 @@ def validate_patrol_rearm_scenario() -> int:
2649
2688
  return 0
2650
2689
 
2651
2690
 
2691
+ def validate_patrol_host_task_scenario() -> int:
2692
+ """Issue #295: `patrol:` names the host task; `keel patrol task` renders it.
2693
+
2694
+ The rendered task carries the id, a cron from `every:`, the declared model
2695
+ or none, and a prompt running the change-based patrol by path; it writes
2696
+ nothing. A declared host task changes the reminder.
2697
+ """
2698
+ label = "patrol-host-task:"
2699
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-host-") as raw:
2700
+ base = Path(raw)
2701
+ repo = mailbox_repository(base / "repo")
2702
+ write_text(repo / "openspec/specs/.keep", "")
2703
+ declaration = "patrol:\n role: rtl\n every: 30m\n host_task: soc-patrol\n"
2704
+ write_authorize_config(repo, declaration)
2705
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
2706
+ subprocess.run(["git", "commit", "-q", "-m", "patrol"], cwd=repo, check=True, capture_output=True)
2707
+ rtl = chat_worktree(repo, base / "rtl")
2708
+ env = chat_environment()
2709
+
2710
+ unbound = run_keel(rtl, "patrol", "task", env=env)
2711
+ if unbound.returncode == 0:
2712
+ report(f"{label} keel patrol task was accepted with no worktree bound to rtl.")
2713
+ return 1
2714
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
2715
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
2716
+ task = run_keel(rtl, "patrol", "task", env=env)
2717
+ if task.returncode != 0:
2718
+ report(f"{label} keel patrol task failed: {task.stdout} {task.stderr}")
2719
+ return 1
2720
+ for needle in ("soc-patrol", "*/30 * * * *", "no model is declared",
2721
+ f"keel patrol --repo {rtl.resolve()} --since-last --notify"):
2722
+ if needle not in task.stdout:
2723
+ report(f"{label} the rendered task does not carry {needle!r}: {task.stdout!r}")
2724
+ return 1
2725
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
2726
+ if before != after:
2727
+ report(f"{label} keel patrol task changed the worktree: {after!r}")
2728
+ return 1
2729
+ write_authorize_config(rtl, declaration + " model: small-model\n")
2730
+ modelled = run_keel(rtl, "patrol", "task", env=env)
2731
+ if "small-model" not in modelled.stdout:
2732
+ report(f"{label} the declared model is not rendered: {modelled.stdout!r}")
2733
+ return 1
2734
+ if "no model is declared" in modelled.stdout:
2735
+ report(f"{label} a declared model is still reported as undeclared: {modelled.stdout!r}")
2736
+ return 1
2737
+
2738
+ context = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
2739
+ if (context.get("patrol") or {}).get("hostTask") != "soc-patrol":
2740
+ report(f"{label} keel context carries patrol {context.get('patrol')!r}.")
2741
+ return 1
2742
+ session = run_session_start_hook(
2743
+ rtl, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(rtl)},
2744
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
2745
+ )
2746
+ note = session_start_context(session) or ""
2747
+ if "soc-patrol" not in note or "still enabled" not in note:
2748
+ report(f"{label} the session-start note does not name the host task: {note!r}")
2749
+ return 1
2750
+ if "re-create it with the host" in note:
2751
+ report(f"{label} the note still asks to re-create a session schedule: {note!r}")
2752
+ return 1
2753
+
2754
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 30m\n host_task: Bad_Id\n")
2755
+ broken = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
2756
+ if not any("host_task" in w and "Bad_Id" in w for w in broken.get("warnings", [])):
2757
+ report(f"{label} a malformed host_task is not reported by name: {broken.get('warnings')!r}")
2758
+ return 1
2759
+ report("patrol-host-task scenario passed.")
2760
+ return 0
2761
+
2762
+
2763
+ def validate_patrol_since_last_scenario() -> int:
2764
+ """Issue #295: a scheduled patrol reports only what changed, once.
2765
+
2766
+ `--since-last` records a baseline, then reports changed entries and exits
2767
+ 2; `--notify` sends them to the coordinator as one message from
2768
+ `keel-patrol`; an unchanged run is quiet. `--notify` alone is refused.
2769
+ """
2770
+ label = "patrol-since-last:"
2771
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-since-") as raw:
2772
+ base = Path(raw)
2773
+ rtl, verify, env, _ = shift_scratch(base)
2774
+
2775
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
2776
+ return run_keel(rtl, "patrol", *args, env=env)
2777
+
2778
+ def notices() -> list[str]:
2779
+ return chat_records_with(rtl, "dm-keel-patrol--rtl", "changed")
2780
+
2781
+ alone = patrol("--notify")
2782
+ if alone.returncode != 1:
2783
+ report(f"{label} --notify without --since-last exited {alone.returncode}.")
2784
+ return 1
2785
+ first = patrol("--since-last", "--notify")
2786
+ if first.returncode != 0:
2787
+ report(f"{label} the first run exited {first.returncode}: {first.stdout!r} {first.stderr!r}")
2788
+ return 1
2789
+ if "baseline recorded" not in first.stdout:
2790
+ report(f"{label} the first run did not record a baseline: {first.stdout!r}")
2791
+ return 1
2792
+ if notices():
2793
+ report(f"{label} the baseline run sent a notice.")
2794
+ return 1
2795
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
2796
+ if readied.returncode != 0:
2797
+ report(f"{label} verify's ready failed: {readied.stderr}")
2798
+ return 1
2799
+ for args in (["commit", "-q", "--allow-empty", "-m", "landed"], ["push", "-q", "origin", "HEAD"]):
2800
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
2801
+ second = patrol("--since-last", "--notify")
2802
+ if second.returncode != 2:
2803
+ report(f"{label} the run after a change exited {second.returncode}: {second.stdout!r} {second.stderr!r}")
2804
+ return 1
2805
+ changed = [line for line in second.stdout.splitlines() if line.startswith("changed:")]
2806
+ if not any("shift" in line and "verify" in line for line in changed):
2807
+ report(f"{label} the shift status change is not reported: {second.stdout!r}")
2808
+ return 1
2809
+ if not any("remote" in line for line in changed):
2810
+ report(f"{label} the remote tip change is not reported: {second.stdout!r}")
2811
+ return 1
2812
+ if len(notices()) != 1:
2813
+ report(f"{label} expected one keel-patrol notice after the change, found {len(notices())}.")
2814
+ return 1
2815
+ if "from: keel-patrol" not in notices()[0]:
2816
+ report(f"{label} the notice is not from keel-patrol: {notices()[0]!r}")
2817
+ return 1
2818
+ woken = run_keel(rtl, "chat", "notice", "--check", env=env)
2819
+ if woken.returncode != 0:
2820
+ report(f"{label} the notice does not wake rtl (notice --check exit {woken.returncode}).")
2821
+ return 1
2822
+ third = patrol("--since-last", "--notify")
2823
+ if third.returncode != 0:
2824
+ report(f"{label} an unchanged run exited {third.returncode}: {third.stdout!r}")
2825
+ return 1
2826
+ if "changed:" in third.stdout:
2827
+ report(f"{label} an unchanged run reported a change: {third.stdout!r}")
2828
+ return 1
2829
+ if len(notices()) != 1:
2830
+ report(f"{label} an unchanged run sent another notice.")
2831
+ return 1
2832
+ report("patrol-since-last scenario passed.")
2833
+ return 0
2834
+
2835
+
2652
2836
  def validate_coordinator_patrol_scenario() -> int:
2653
2837
  """Issue #260: declared waits, and a patrol that notifies once.
2654
2838
 
@@ -3361,27 +3545,64 @@ def validate_chat_loop_guards_scenario() -> int:
3361
3545
  extra = {"KEEL_CHAT_ROLE": role} if role else {}
3362
3546
  return run_keel(cwd, "chat", *args, env={**env, **extra})
3363
3547
 
3364
- for index in range(8):
3365
- cwd = rtl if index % 2 == 0 else verify
3366
- turn = chat(cwd, "post", "soc", f"round {index}")
3367
- if turn.returncode != 0:
3368
- report(f"{label} alternating post {index} was refused before the threshold: {turn.stderr.strip()}")
3369
- return 1
3548
+ # Enough rate for the ping-pong rounds below; the rate limit is checked with lint.
3549
+ for tree in (rtl, verify):
3550
+ write_text(tree / "keel" / "chat.json", json.dumps({"limits": {"rate": 100}}) + "\n")
3551
+
3552
+ def alternate(group: str, start: int, poster=None) -> str | None:
3553
+ post = poster or (lambda cwd, text: chat(cwd, "post", group, text))
3554
+ for index in range(start, start + 8):
3555
+ cwd = rtl if index % 2 == 0 else verify
3556
+ turn = post(cwd, f"round {index}")
3557
+ if turn.returncode != 0:
3558
+ return f"alternating post {index} in {group} was refused before the threshold: {turn.stderr.strip()}"
3559
+ return None
3560
+
3561
+ def systems(group: str) -> list[str]:
3562
+ return [p.read_text(encoding="utf-8") for p in chat_log(rtl, group).glob("*.md") if "kind: system" in p.read_text(encoding="utf-8")]
3563
+
3564
+ problem = alternate("soc", 0)
3565
+ if problem:
3566
+ report(f"{label} {problem}")
3567
+ return 1
3370
3568
  ninth = chat(rtl, "post", "soc", "round 8")
3371
3569
  if ninth.returncode == 0:
3372
- report(f"{label} a ninth alternating post was accepted.")
3570
+ report(f"{label} a ninth quick alternating post was accepted.")
3373
3571
  return 1
3374
3572
  if "loop guard" not in ninth.stderr:
3375
3573
  report(f"{label} the ping-pong refusal does not name the loop guard: {ninth.stderr.strip()}")
3376
3574
  return 1
3377
- chat(verify, "post", "soc", "round 8 again")
3378
- records = [p.read_text(encoding="utf-8") for p in chat_log(rtl, "soc").glob("*.md")]
3379
- system = [r for r in records if "kind: system" in r]
3380
- if len(system) != 1:
3381
- report(f"{label} expected one system record after two refused posts, found {len(system)}.")
3575
+ if "--not-a-loop" not in ninth.stderr:
3576
+ report(f"{label} the first refusal does not name --not-a-loop: {ninth.stderr.strip()}")
3577
+ return 1
3578
+ if systems("soc"):
3579
+ report(f"{label} the first trip already called the owner.")
3580
+ return 1
3581
+ overridden = chat(rtl, "post", "soc", "--not-a-loop", "new assignment", "R009 next")
3582
+ if overridden.returncode != 0:
3583
+ report(f"{label} a --not-a-loop post was refused: {overridden.stderr.strip()}")
3584
+ return 1
3585
+ if not chat_records_with(rtl, "soc", "not_a_loop: new assignment"):
3586
+ report(f"{label} the override's reason is not recorded on the post.")
3587
+ return 1
3588
+ problem = alternate("soc", 9)
3589
+ if problem:
3590
+ report(f"{label} after the override, {problem}")
3591
+ return 1
3592
+ again = chat(rtl, "post", "soc", "round 17")
3593
+ if again.returncode == 0:
3594
+ report(f"{label} a quick alternating post after the override run was accepted.")
3595
+ return 1
3596
+ chat(verify, "post", "soc", "round 17 again")
3597
+ if len(systems("soc")) != 1:
3598
+ report(f"{label} expected one system record after the repeat trip, found {len(systems('soc'))}.")
3382
3599
  return 1
3383
- if " - owner" not in system[0]:
3384
- report(f"{label} the system record does not mention owner:\n{system[0]}")
3600
+ if " - owner" not in systems("soc")[0]:
3601
+ report(f"{label} the system record does not mention owner:\n{systems('soc')[0]}")
3602
+ return 1
3603
+ refused_override = chat(rtl, "post", "soc", "--not-a-loop", "really", "x")
3604
+ if refused_override.returncode == 0:
3605
+ report(f"{label} an override was accepted after the owner was called.")
3385
3606
  return 1
3386
3607
  owner = chat(rtl, "post", "soc", "Stop and summarize, please.", role="owner")
3387
3608
  if owner.returncode != 0:
@@ -3392,6 +3613,36 @@ def validate_chat_loop_guards_scenario() -> int:
3392
3613
  report(f"{label} rtl could not post after the owner did: {resumed.stderr.strip()}")
3393
3614
  return 1
3394
3615
 
3616
+ direct = lambda cwd, text: chat(cwd, "dm", "verify" if cwd == rtl else "rtl", text)
3617
+ for step in (lambda: alternate("dm-rtl--verify", 0, direct),
3618
+ lambda: None if chat(rtl, "dm", "verify", "--not-a-loop", "work", "x").returncode == 0 else "the direct override was refused",
3619
+ lambda: alternate("dm-rtl--verify", 1, direct)):
3620
+ problem = step()
3621
+ if problem:
3622
+ report(f"{label} in the direct group, {problem}")
3623
+ return 1
3624
+ escalated = chat(verify, "dm", "rtl", "one more")
3625
+ if escalated.returncode == 0:
3626
+ report(f"{label} the repeat trip in the direct group was accepted.")
3627
+ return 1
3628
+ if "another member" in escalated.stderr:
3629
+ report(f"{label} the direct group's refusal names another member: {escalated.stderr.strip()}")
3630
+ return 1
3631
+
3632
+ run_keel(rtl, "chat", "group", "create", "slow", "--member", "verify", env=env)
3633
+ problem = alternate("slow", 0)
3634
+ if problem:
3635
+ report(f"{label} {problem}")
3636
+ return 1
3637
+ hours_ago = (datetime.now().astimezone() - timedelta(hours=3)).isoformat(timespec="seconds")
3638
+ for record in chat_log(rtl, "slow").glob("*.md"):
3639
+ text = record.read_text(encoding="utf-8")
3640
+ record.write_text(re.sub(r"^created: .*$", f"created: {hours_ago}", text, count=1, flags=re.M), encoding="utf-8")
3641
+ slow = chat(rtl, "post", "slow", "a new piece of work, hours later")
3642
+ if slow.returncode != 0:
3643
+ report(f"{label} a post after a slow exchange was refused: {slow.stderr.strip()}")
3644
+ return 1
3645
+
3395
3646
  write_text(lint / "keel" / "chat.json", json.dumps({"limits": {"rate": 3, "window_minutes": 10}}) + "\n")
3396
3647
  for index in range(3):
3397
3648
  within = chat(lint, "post", "soc", f"lint note {index}")
@@ -38996,6 +39247,10 @@ SCENARIOS: tuple = (
38996
39247
  "chat-loop-guards",
38997
39248
  validate_chat_loop_guards_scenario,
38998
39249
  ),
39250
+ (
39251
+ "chat-stamp-help",
39252
+ validate_chat_stamp_help_scenario,
39253
+ ),
38999
39254
  (
39000
39255
  "chat-human-view",
39001
39256
  validate_chat_human_view_scenario,
@@ -39327,6 +39582,8 @@ SCENARIOS: tuple = (
39327
39582
  ("chat-supersedes", validate_chat_supersedes_scenario),
39328
39583
  ("chat-ack", validate_chat_ack_scenario),
39329
39584
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39585
+ ("patrol-since-last", validate_patrol_since_last_scenario),
39586
+ ("patrol-host-task", validate_patrol_host_task_scenario),
39330
39587
  ("patrol-rearm", validate_patrol_rearm_scenario),
39331
39588
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
39332
39589
  ("chat-listen-only", validate_chat_listen_only_scenario),
@@ -20,13 +20,13 @@ const USAGE = [
20
20
  "keel chat group add|remove <group> <role> [--listen] (--listen: receives the group, may ack and close its todos, does not post)",
21
21
  "keel chat group archive <group>",
22
22
  "keel chat group list [--all] [--json] (also: keel chat list)",
23
- "keel chat post <group> <text...> [--reply-to <id>] [--supersedes <id>] [--ack] [--json] (also: keel chat <group> <text...>)",
23
+ "keel chat post <group> <text...> [--reply-to <id>] [--supersedes <id>] [--ack] [--stamp] [--not-a-loop <why>] [--json] (also: keel chat <group> <text...>)",
24
24
  "keel chat ack <id> acknowledge a record that asks (a reply also counts)",
25
25
  "keel chat acks [--mine] [--json] records still waiting on an acknowledgement",
26
26
  "keel chat summary --since <90s|15m|2h|3d|date> [--group <group>] [--json] (what changed, per group and sender; reads without marking read)",
27
27
  "keel chat wait <group> --commit <sha> [--remote <name>] [note...] (or --issue <n> --closed: what this role waits for; keel patrol tells it when it holds)",
28
28
  "keel chat waits [--json] waits not yet met",
29
- "keel chat dm <role> <text...> [--json]",
29
+ "keel chat dm <role> <text...> [--stamp] [--not-a-loop <why>] [--json]",
30
30
  "keel chat <group> [--since <90s|15m|2h|3d|date>] [--follow] [--peek] [--json] (view; advances your read position unless --peek)",
31
31
  "keel chat unread [--json]",
32
32
  "keel chat read [<group>] [--json]",
@@ -59,6 +59,7 @@ const VALUED = {
59
59
  "--alias": "alias",
60
60
  "--reply-to": "replyTo",
61
61
  "--supersedes": "supersedes",
62
+ "--not-a-loop": "notALoop",
62
63
  "--repo": "repo",
63
64
  "--assignee": "assignee",
64
65
  "--issue": "issue",
@@ -73,10 +74,10 @@ const VALUED = {
73
74
  "--compact-at": "compactAt",
74
75
  };
75
76
  const REPEATED = { "--member": "members" };
76
- const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen", "--closed": "closed" };
77
+ const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen", "--closed": "closed", "--stamp": "stamp", "--help": "help", "-h": "help" };
77
78
 
78
79
  function parseChatArgs(argv) {
79
- const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false, closed: false };
80
+ const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false, closed: false, stamp: false, help: false };
80
81
  for (const key of Object.values(VALUED)) options[key] = null;
81
82
  for (let index = 0; index < argv.length; index += 1) {
82
83
  const arg = argv[index];
@@ -114,6 +115,13 @@ function parseChatArgs(argv) {
114
115
  return options;
115
116
  }
116
117
 
118
+ // `--stamp` (#298 D3): the time comes from Keel's clock, never the author's estimate.
119
+ function stamped(text, options) {
120
+ if (!options.stamp || !String(text || "").trim()) return text;
121
+ const now = store.isoLocal(new Date());
122
+ return `[${now.slice(5, 10)} ${now.slice(11, 16)}] ${text}`;
123
+ }
124
+
117
125
  function out(text) {
118
126
  process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
119
127
  }
@@ -296,7 +304,7 @@ function dispatch(where, options) {
296
304
  case "post": {
297
305
  const [group, ...words] = rest;
298
306
  if (!group) throw new ChatError("keel chat post needs a group.");
299
- postResult(where, store.post(where, { group, text: textFrom(words), replyTo: options.replyTo, supersedes: options.supersedes, ack: options.ack }), options.json);
307
+ postResult(where, store.post(where, { group, text: stamped(textFrom(words), options), replyTo: options.replyTo, supersedes: options.supersedes, ack: options.ack, notALoop: options.notALoop }), options.json);
300
308
  return 0;
301
309
  }
302
310
  case "ack": {
@@ -345,7 +353,7 @@ function dispatch(where, options) {
345
353
  case "dm": {
346
354
  const [target, ...words] = rest;
347
355
  if (!target) throw new ChatError("keel chat dm needs a role.");
348
- postResult(where, store.directPost(where, target, textFrom(words)), options.json);
356
+ postResult(where, store.directPost(where, target, stamped(textFrom(words), options), { notALoop: options.notALoop }), options.json);
349
357
  return 0;
350
358
  }
351
359
  case "unread": {
@@ -602,7 +610,7 @@ function runChat(argv) {
602
610
  try {
603
611
  const options = parseChatArgs(argv);
604
612
  const cwd = path.resolve(options.repo || process.cwd());
605
- if (!options.positionals.length || options.positionals[0] === "help") {
613
+ if (!options.positionals.length || options.positionals[0] === "help" || options.help) {
606
614
  out(`Usage:\n ${USAGE.join("\n ")}`);
607
615
  return 0;
608
616
  }
@@ -8,15 +8,20 @@
8
8
  // records per `limits.window_minutes` across the project
9
9
  // (default 20 per 10).
10
10
  // ping-pong when the last `limits.pingpong` messages of a group (default 8)
11
- // alternate between the same two roles other than `owner`, the
12
- // next post there by either is refused, and Keel calls the owner
13
- // with one `system` record. Any other member's post clears it.
11
+ // since its latest override alternate between the same two
12
+ // roles other than `owner`, and the first of them is within
13
+ // `limits.pingpong_minutes` (default 10), the next post there by
14
+ // either is refused (#297 D1). A first refusal only names
15
+ // `--not-a-loop "<why>"`, which lets the poster through once;
16
+ // a repeat after an override calls the owner with one `system`
17
+ // record (D2). The owner's post clears it, or in a group of more
18
+ // than two, any other member's.
14
19
  //
15
20
  // Both refuse by name, so an agent reading its error knows what stopped it.
16
21
 
17
22
  const { loadChatConfig } = require("./config");
18
23
 
19
- const DEFAULTS = { rate: 20, window_minutes: 10, pingpong: 8 };
24
+ const DEFAULTS = { rate: 20, window_minutes: 10, pingpong: 8, pingpong_minutes: 10 };
20
25
  const SYSTEM_SENDER = "keel";
21
26
 
22
27
  function positiveInteger(value, fallback) {
@@ -30,13 +35,19 @@ function limitsFor(where) {
30
35
  rate: positiveInteger(limits.rate, DEFAULTS.rate),
31
36
  window_minutes: positiveInteger(limits.window_minutes, DEFAULTS.window_minutes),
32
37
  pingpong: positiveInteger(limits.pingpong, DEFAULTS.pingpong),
38
+ pingpong_minutes: positiveInteger(limits.pingpong_minutes, DEFAULTS.pingpong_minutes),
33
39
  };
34
40
  }
35
41
 
36
- // The two roles a group's recent messages alternate between, or null.
37
- function pingPongPair(records, length) {
38
- const messages = records.filter((record) => record.kind === "message").slice(-length);
42
+ // The two roles a group's recent messages alternate between, or null: only
43
+ // messages after the latest override count, and only a run whose first
44
+ // message is within `minutes` of now (#297 D1).
45
+ function pingPongPair(records, length, minutes) {
46
+ const override = records.map((record) => Boolean(record.not_a_loop)).lastIndexOf(true);
47
+ const messages = records.slice(override + 1).filter((record) => record.kind === "message").slice(-length);
39
48
  if (messages.length < length) return null;
49
+ const first = Date.parse(messages[0].created || "");
50
+ if (Number.isNaN(first) || Date.now() - first > minutes * 60 * 1000) return null;
40
51
  const pair = [messages[0].from, messages[1].from];
41
52
  if (pair[0] === pair[1] || pair.includes("owner")) return null;
42
53
  for (let index = 0; index < messages.length; index += 1) {
@@ -57,12 +68,34 @@ function postedSince(store, where, role, since) {
57
68
  return count;
58
69
  }
59
70
 
60
- // Throws the store's error when `role` may not post to `group` now.
61
- function checkPost(store, where, role, group, records) {
62
- if (role === "owner") return;
71
+ // Escalated once the group's latest override or call to the owner has not
72
+ // been followed by an owner message (#297 D2).
73
+ function escalated(records) {
74
+ for (let index = records.length - 1; index >= 0; index -= 1) {
75
+ const record = records[index];
76
+ if (record.from === "owner" && record.kind === "message") return false;
77
+ if (record.not_a_loop || (record.kind === "system" && record.from === SYSTEM_SENDER)) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ // Throws the store's error when `role` may not post to `group` now. Returns
83
+ // whether `notALoop` let the post through, so the caller records the reason.
84
+ function checkPost(store, where, role, group, records, notALoop = null) {
85
+ if (role === "owner") return { overridden: false };
63
86
  const limits = limitsFor(where);
64
- const pair = pingPongPair(records, limits.pingpong);
65
- if (pair && pair.includes(role)) {
87
+ const pair = pingPongPair(records, limits.pingpong, limits.pingpong_minutes);
88
+ let overridden = false;
89
+ if (pair && pair.includes(role) && !escalated(records)) {
90
+ if (!notALoop) {
91
+ throw new store.ChatError(
92
+ `The loop guard stopped this post: ${pair[0]} and ${pair[1]} have alternated the last ${limits.pingpong} `
93
+ + `messages in ${group} within ${limits.pingpong_minutes} minutes. If this is ordinary request and reply, `
94
+ + "post again with `--not-a-loop \"<why>\"`; if it trips again, the owner is called."
95
+ );
96
+ }
97
+ overridden = true;
98
+ } else if (pair && pair.includes(role)) {
66
99
  const last = records[records.length - 1];
67
100
  if (!(last && last.kind === "system" && last.from === SYSTEM_SENDER)) {
68
101
  store.writeRecord(where, {
@@ -74,9 +107,10 @@ function checkPost(store, where, role, group, records) {
74
107
  + "the loop guard holds their next posts here until someone else posts.",
75
108
  });
76
109
  }
110
+ const clears = store.isDirect(group) ? "a post by the owner clears it" : "a post by the owner or another member clears it";
77
111
  throw new store.ChatError(
78
112
  `The loop guard stopped this post: ${pair[0]} and ${pair[1]} have alternated the last ${limits.pingpong} `
79
- + `messages in ${group}. The owner has been called; any other member's post clears it.`
113
+ + `messages in ${group} again after an override. The owner has been called; ${clears}, and --not-a-loop no longer applies.`
80
114
  );
81
115
  }
82
116
  const since = Date.now() - limits.window_minutes * 60 * 1000;
@@ -87,6 +121,7 @@ function checkPost(store, where, role, group, records) {
87
121
  + `minutes, the limit set by limits.rate in keel/chat.json (default ${DEFAULTS.rate}).`
88
122
  );
89
123
  }
124
+ return { overridden };
90
125
  }
91
126
 
92
127
  module.exports = {
@@ -41,7 +41,7 @@ const READABLE_KINDS = new Set(["message", "todo", "system"]);
41
41
  const LIST_FIELDS = new Set(["mentions", "refs"]);
42
42
  const FIELD_ORDER = [
43
43
  "id", "group", "kind", "from", "created", "mentions", "reply_to", "supersedes", "ack",
44
- "assignee", "issue", "target", "access", "condition", "refs", "origin", "slack_channel", "slack_ts",
44
+ "assignee", "issue", "target", "access", "condition", "not_a_loop", "refs", "origin", "slack_channel", "slack_ts",
45
45
  ];
46
46
 
47
47
  // A group may not take a name `keel chat <group>` would read as a subcommand.
@@ -568,7 +568,7 @@ function post(where, options) {
568
568
  requireSpeaker(group, state, from);
569
569
  const mentions = resolveMentions(where, group, state, text);
570
570
  // Loaded here rather than at the top: the guards read the store's own API.
571
- require("./guards").checkPost(module.exports, where, from, group, records);
571
+ const guard = require("./guards").checkPost(module.exports, where, from, group, records, options.notALoop || null);
572
572
  if (options.replyTo) {
573
573
  const parent = findRecord(where, options.replyTo);
574
574
  if (!parent || parent.group !== group) {
@@ -597,6 +597,7 @@ function post(where, options) {
597
597
  assignee: options.assignee || null,
598
598
  issue: options.issue || null,
599
599
  refs: options.refs || [],
600
+ not_a_loop: guard.overridden ? String(options.notALoop) : null,
600
601
  text: text.replace(/\s+$/, ""),
601
602
  });
602
603
  // A reply that opens with `done` or ✅ closes the todo it answers (D6).
@@ -804,7 +805,7 @@ function directPost(where, target, text, extra = {}) {
804
805
  if (!groupState(readLog(where, group)).exists) {
805
806
  createGroup(where, from, group, [target], { direct: true });
806
807
  }
807
- return post(where, { group, text, replyTo: extra.replyTo || null, refs: extra.refs || [] });
808
+ return post(where, { group, text, replyTo: extra.replyTo || null, refs: extra.refs || [], notALoop: extra.notALoop || null });
808
809
  }
809
810
 
810
811
  // --- waits (#260) ---------------------------------------------------------------
@@ -1014,6 +1015,7 @@ module.exports = {
1014
1015
  directPost,
1015
1016
  findRecord,
1016
1017
  groupState,
1018
+ isDirect,
1017
1019
  isoLocal,
1018
1020
  listGroups,
1019
1021
  listGroupNames,
@@ -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
@@ -671,7 +671,7 @@ function runShift(argv) {
671
671
  const { readPatrolDeclaration, patrolReminder } = require("./config");
672
672
  const patrol = readPatrolDeclaration(where.worktree);
673
673
  const remind = patrol.role && result.role === patrol.role;
674
- 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 } : {}) };
675
675
  // A new coordinator learns whom its previous shift left unstarted (#289 D2).
676
676
  const waiting = (result.waiting || []).map((w) => w.role);
677
677
  const still = waiting.length ? `\n\nStill waiting for \`keel shift start\`: ${waiting.join(", ")}.` : "";
@@ -706,4 +706,4 @@ function waitingFor(repo) {
706
706
  return { note, since: store.isoLocal(fs.statSync(note).mtime) };
707
707
  }
708
708
 
709
- module.exports = { check, runShift, waitingFor };
709
+ module.exports = { check, describe, runShift, shiftStatus: status, waitingFor };