@christang/keel 5.108.0 → 5.109.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
@@ -758,6 +758,33 @@ Without a known default branch, no issue range is inferred.
758
758
 
759
759
  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.
760
760
 
761
+ ## Coordinator patrol
762
+
763
+ A coordinating session that goes quiet stalls everyone waiting on it (#260). A role records what it
764
+ is waiting for, and a patrol the host runs on a schedule tells it when that holds:
765
+
766
+ ```bash
767
+ keel chat wait soc --commit eb340a7 rerun R007 when the fix lands # or: --issue 42 --closed
768
+ git fetch && gh issue list --json number,title,state,labels,updatedAt > /tmp/issues.json
769
+ keel patrol --issues /tmp/issues.json # as the coordinator's role
770
+ ```
771
+
772
+ `keel patrol` marks each wait whose condition now holds — a commit on the remote, an issue closed —
773
+ as met and sends the waiting role one direct message, which wakes it. It lists every role's
774
+ presence, last activity, and open todos, marking those idle beyond `--idle` (default `30m`). It
775
+ fetches nothing, schedules nothing, calls no model, and writes nothing when nothing is new; it exits
776
+ 0 then, 2 when it sent something, and 1 on an error, so a cheap scheduler — cron, `/loop`, CI — can
777
+ wake the model only on 2. `keel chat waits` lists what is still awaited.
778
+
779
+ With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
780
+ maps a label to a role, and each role gets one direct message per update of an issue carrying its
781
+ label — so a handoff labelled `role:verify` reaches `verify` without a second message.
782
+
783
+ ```yaml
784
+ issue_roles:
785
+ role:verify: verify
786
+ ```
787
+
761
788
  ## Commands
762
789
 
763
790
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.108.0 -->
1
+ <!-- keel:start version=5.109.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.
package/bin/keel.js CHANGED
@@ -2871,6 +2871,9 @@ function main() {
2871
2871
  if (process.argv[2] === "lock") {
2872
2872
  return require("../src/core/lock").runLock(process.argv.slice(3));
2873
2873
  }
2874
+ if (process.argv[2] === "patrol") {
2875
+ return require("../src/core/patrol").runPatrol(process.argv.slice(3));
2876
+ }
2874
2877
  if (process.argv[2] === "worktrees") {
2875
2878
  return require("../src/core/worktrees").runWorktrees(process.argv.slice(3));
2876
2879
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.108.0",
3
+ "version": "5.109.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.108.0",
9
+ "version": "5.109.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.108.0",
5
+ "version": "5.109.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.108.0",
3
+ "version": "5.109.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.108.0",
3
+ "version": "5.109.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.108.0"
51
- PROTOCOL_VERSION = "5.108.0"
50
+ PACKAGE_VERSION = "5.109.0"
51
+ PROTOCOL_VERSION = "5.109.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
@@ -2578,6 +2578,160 @@ def validate_chat_listen_only_scenario() -> int:
2578
2578
  return 0
2579
2579
 
2580
2580
 
2581
+ def chat_logs_snapshot(repo: Path) -> dict:
2582
+ groups = mailbox_common_dir(repo) / "keel-chat" / "groups"
2583
+ return {str(p): p.read_bytes() for p in groups.rglob("*") if p.is_file()}
2584
+
2585
+
2586
+ def validate_coordinator_patrol_scenario() -> int:
2587
+ """Issue #260: declared waits, and a patrol that notifies once.
2588
+
2589
+ `keel chat wait` records what a role waits for; `keel patrol` marks a held
2590
+ condition met and direct-messages the waiter, writes nothing when nothing
2591
+ holds, and exits 0 (quiet), 2 (wrote), or 1 (error).
2592
+ """
2593
+ label = "coordinator-patrol:"
2594
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-") as raw:
2595
+ base = Path(raw)
2596
+ rtl, verify, env = chat_scratch_group(base)
2597
+ origin = base / "origin.git"
2598
+ subprocess.run(["git", "init", "-q", "--bare", str(origin)], check=True, capture_output=True)
2599
+ for args in (["remote", "add", "origin", str(origin)], ["push", "-q", "origin", "main"],
2600
+ ["switch", "-q", "-c", "feature"], ["commit", "-q", "--allow-empty", "-m", "fix"]):
2601
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
2602
+ sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=rtl, check=True, capture_output=True, text=True).stdout.strip()
2603
+
2604
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2605
+ return run_keel(cwd, "chat", *args, env=env)
2606
+
2607
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
2608
+ return run_keel(rtl, "patrol", *args, env=env)
2609
+
2610
+ waited = chat(verify, "wait", "soc", "--commit", sha, "rerun R007 when the fix lands")
2611
+ if waited.returncode != 0:
2612
+ report(f"{label} keel chat wait failed: {waited.stdout} {waited.stderr}")
2613
+ return 1
2614
+ waits = chat_json(chat(rtl, "waits", "--json")).get("waits", [])
2615
+ if [(w.get("from"), w.get("condition")) for w in waits] != [("verify", f"commit {sha} on origin")]:
2616
+ report(f"{label} waits lists {waits!r}.")
2617
+ return 1
2618
+ if chat_json(chat(rtl, "unread", "--json")).get("unread"):
2619
+ report(f"{label} a wait left rtl something unread.")
2620
+ return 1
2621
+ for what, result in (
2622
+ ("no condition", chat(verify, "wait", "soc")),
2623
+ ("both conditions", chat(verify, "wait", "soc", "--commit", sha, "--issue", "42", "--closed")),
2624
+ ):
2625
+ if result.returncode == 0:
2626
+ report(f"{label} a wait with {what} was accepted.")
2627
+ return 1
2628
+ if "--commit" not in result.stderr or "--issue" not in result.stderr:
2629
+ report(f"{label} a wait with {what} was refused without naming both forms: {result.stderr}")
2630
+ return 1
2631
+
2632
+ before = chat_logs_snapshot(rtl)
2633
+ quiet = patrol()
2634
+ if quiet.returncode != 0:
2635
+ report(f"{label} patrol before the push exited {quiet.returncode}: {quiet.stdout} {quiet.stderr}")
2636
+ return 1
2637
+ if chat_logs_snapshot(rtl) != before:
2638
+ report(f"{label} a quiet patrol wrote to the chat.")
2639
+ return 1
2640
+ if "verify" not in quiet.stdout:
2641
+ report(f"{label} the digest does not list verify: {quiet.stdout!r}")
2642
+ return 1
2643
+
2644
+ subprocess.run(["git", "push", "-q", "origin", "feature"], cwd=rtl, check=True, capture_output=True)
2645
+ landed = patrol()
2646
+ if landed.returncode != 2:
2647
+ report(f"{label} patrol after the push exited {landed.returncode}, not 2: {landed.stdout} {landed.stderr}")
2648
+ return 1
2649
+ if chat_json(chat(rtl, "waits", "--json")).get("waits"):
2650
+ report(f"{label} the met wait is still listed.")
2651
+ return 1
2652
+ texts = [r.get("text", "") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
2653
+ if not any(sha[:7] in text for text in texts):
2654
+ report(f"{label} verify has no unread message naming the commit: {texts!r}")
2655
+ return 1
2656
+ before = chat_logs_snapshot(rtl)
2657
+ again = patrol()
2658
+ if again.returncode != 0:
2659
+ report(f"{label} a second patrol exited {again.returncode}, not 0.")
2660
+ return 1
2661
+ if chat_logs_snapshot(rtl) != before:
2662
+ report(f"{label} a second patrol wrote again.")
2663
+ return 1
2664
+
2665
+ chat(verify, "wait", "soc", "--issue", "42", "--closed")
2666
+ unchecked = patrol()
2667
+ if unchecked.returncode != 0:
2668
+ report(f"{label} patrol without --issues exited {unchecked.returncode}, not 0.")
2669
+ return 1
2670
+ if "unchecked" not in unchecked.stdout:
2671
+ report(f"{label} patrol without --issues does not report the issue wait unchecked: {unchecked.stdout!r}")
2672
+ return 1
2673
+ issues = base / "issues.json"
2674
+ issues.write_text(json.dumps([{"number": 42, "title": "clock fix", "state": "CLOSED", "labels": [], "updatedAt": "2026-10-11T00:00:00Z"}]), encoding="utf-8")
2675
+ closed = patrol("--issues", str(issues))
2676
+ if closed.returncode != 2:
2677
+ report(f"{label} patrol with issue 42 closed exited {closed.returncode}, not 2: {closed.stdout} {closed.stderr}")
2678
+ return 1
2679
+ report("coordinator-patrol scenario passed.")
2680
+ return 0
2681
+
2682
+
2683
+ def validate_patrol_issue_routing_scenario() -> int:
2684
+ """Issue #242: `issue_roles:` routes each labelled issue update once.
2685
+
2686
+ The label's role gets one direct message per `updatedAt`, deduped against
2687
+ the chat; an unreadable line is reported and routes nothing.
2688
+ """
2689
+ label = "patrol-issue-routing:"
2690
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-issues-") as raw:
2691
+ base = Path(raw)
2692
+ rtl, verify, env = chat_scratch_group(base)
2693
+ write_authorize_config(rtl, "issue_roles:\n role:verify: verify\n this line has no role\n")
2694
+ issues = base / "issues.json"
2695
+
2696
+ def patrol(updated: str) -> subprocess.CompletedProcess[str]:
2697
+ issues.write_text(json.dumps([{
2698
+ "number": 157, "title": "rerun on new commit", "state": "OPEN",
2699
+ "labels": [{"name": "role:verify"}], "updatedAt": updated,
2700
+ }]), encoding="utf-8")
2701
+ return run_keel(rtl, "patrol", "--issues", str(issues), env=env)
2702
+
2703
+ def notices() -> list:
2704
+ return [r.get("text", "") for r in chat_json(run_keel(verify, "chat", "unread", "--json", env=env)).get("unread", []) if "#157" in r.get("text", "")]
2705
+
2706
+ first = patrol("2026-10-11T01:00:00Z")
2707
+ if first.returncode != 2:
2708
+ report(f"{label} the first patrol exited {first.returncode}, not 2: {first.stdout} {first.stderr}")
2709
+ return 1
2710
+ if len(notices()) != 1:
2711
+ report(f"{label} verify has {len(notices())} notices about #157, not 1.")
2712
+ return 1
2713
+ if "this line has no role" not in first.stdout:
2714
+ report(f"{label} the unreadable issue_roles line is not reported: {first.stdout!r}")
2715
+ return 1
2716
+ before = chat_logs_snapshot(rtl)
2717
+ same = patrol("2026-10-11T01:00:00Z")
2718
+ if same.returncode != 0:
2719
+ report(f"{label} the same update exited {same.returncode}, not 0.")
2720
+ return 1
2721
+ if chat_logs_snapshot(rtl) != before:
2722
+ report(f"{label} the same update was sent again.")
2723
+ return 1
2724
+ later = patrol("2026-10-11T02:00:00Z")
2725
+ if later.returncode != 2:
2726
+ report(f"{label} a later update exited {later.returncode}, not 2.")
2727
+ return 1
2728
+ if len(notices()) != 2:
2729
+ report(f"{label} a later update left {len(notices())} notices, not 2.")
2730
+ return 1
2731
+ report("patrol-issue-routing scenario passed.")
2732
+ return 0
2733
+
2734
+
2581
2735
  def validate_chat_ack_scenario() -> int:
2582
2736
  """Issue #253: a record asks for an acknowledgement and the sender sees who gave it.
2583
2737
 
@@ -38643,6 +38797,8 @@ SCENARIOS: tuple = (
38643
38797
  ("resource-lock", validate_resource_lock_scenario),
38644
38798
  ("chat-supersedes", validate_chat_supersedes_scenario),
38645
38799
  ("chat-ack", validate_chat_ack_scenario),
38800
+ ("coordinator-patrol", validate_coordinator_patrol_scenario),
38801
+ ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
38646
38802
  ("chat-listen-only", validate_chat_listen_only_scenario),
38647
38803
  ("chat-summary", validate_chat_summary_scenario),
38648
38804
  ("worktree-overview", validate_worktree_overview_scenario),
@@ -24,6 +24,8 @@ const USAGE = [
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
+ "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
+ "keel chat waits [--json] waits not yet met",
27
29
  "keel chat dm <role> <text...> [--json]",
28
30
  "keel chat <group> [--since <90s|15m|2h|3d|date>] [--follow] [--peek] [--json] (view; advances your read position unless --peek)",
29
31
  "keel chat unread [--json]",
@@ -62,6 +64,8 @@ const VALUED = {
62
64
  "--issue": "issue",
63
65
  "--group": "group",
64
66
  "--since": "since",
67
+ "--commit": "commit",
68
+ "--remote": "remote",
65
69
  "--worktree": "worktree",
66
70
  "--thread": "thread",
67
71
  "--host": "host",
@@ -69,10 +73,10 @@ const VALUED = {
69
73
  "--compact-at": "compactAt",
70
74
  };
71
75
  const REPEATED = { "--member": "members" };
72
- const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen" };
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" };
73
77
 
74
78
  function parseChatArgs(argv) {
75
- const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false };
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 };
76
80
  for (const key of Object.values(VALUED)) options[key] = null;
77
81
  for (let index = 0; index < argv.length; index += 1) {
78
82
  const arg = argv[index];
@@ -322,6 +326,22 @@ function dispatch(where, options) {
322
326
  else out(summaryLines(digest, sinceText).join("\n"));
323
327
  return 0;
324
328
  }
329
+ case "wait": {
330
+ const [group, ...words] = rest;
331
+ if (!group) throw new ChatError("keel chat wait needs a group.");
332
+ const record = store.wait(where, {
333
+ group, commit: options.commit, remote: options.remote, issue: options.issue,
334
+ closed: options.closed, text: words.join(" "),
335
+ });
336
+ out(options.json ? JSON.stringify({ id: record.id, condition: record.condition }) : `Waiting: ${record.condition} (${record.id}).`);
337
+ return 0;
338
+ }
339
+ case "waits": {
340
+ const waits = store.openWaits(where);
341
+ if (options.json) out(JSON.stringify({ waits: waits.map((w) => ({ id: w.id, group: w.group, from: w.from, condition: w.condition, text: w.text, created: w.created })) }));
342
+ else out(waits.length ? waits.map((w) => `${w.group} ${w.id} ${w.from} waits for ${w.condition}${w.text ? `: ${w.text}` : ""}`).join("\n") : "keel chat: nobody is waiting.");
343
+ return 0;
344
+ }
325
345
  case "dm": {
326
346
  const [target, ...words] = rest;
327
347
  if (!target) throw new ChatError("keel chat dm needs a role.");
@@ -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", "refs", "origin", "slack_channel", "slack_ts",
44
+ "assignee", "issue", "target", "access", "condition", "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.
@@ -807,6 +807,57 @@ function directPost(where, target, text, extra = {}) {
807
807
  return post(where, { group, text, replyTo: extra.replyTo || null, refs: extra.refs || [] });
808
808
  }
809
809
 
810
+ // --- waits (#260) ---------------------------------------------------------------
811
+
812
+ const WAIT_FORMS = "`--commit <sha> [--remote <name>]` or `--issue <n> --closed`";
813
+
814
+ // What a role is waiting for, as a record every session can read. A wait is
815
+ // not readable (D1): it wakes nobody and is unread for nobody.
816
+ function wait(where, options) {
817
+ const from = requireRole(where);
818
+ const group = options.group;
819
+ checkName(group, "Group");
820
+ const byCommit = options.commit !== null && options.commit !== undefined;
821
+ const byIssue = options.issue !== null && options.issue !== undefined;
822
+ if (byCommit === byIssue) {
823
+ throw new ChatError(`keel chat wait needs exactly one condition: ${WAIT_FORMS}.`);
824
+ }
825
+ let condition;
826
+ if (byCommit) {
827
+ if (!/^[0-9a-f]{7,40}$/i.test(String(options.commit))) {
828
+ throw new ChatError(`--commit ${JSON.stringify(options.commit)} is not a commit id; use ${WAIT_FORMS}.`);
829
+ }
830
+ const remote = options.remote || "origin";
831
+ checkName(remote.toLowerCase(), "Remote");
832
+ condition = `commit ${String(options.commit).toLowerCase()} on ${remote}`;
833
+ } else {
834
+ if (!options.closed) throw new ChatError(`keel chat wait --issue needs --closed; use ${WAIT_FORMS}.`);
835
+ condition = `issue ${normalizeIssue(options.issue)} closed`;
836
+ }
837
+ const { state } = loadGroup(where, group);
838
+ requireOpenMembership(group, state, from);
839
+ return writeRecord(where, { group, kind: "wait", from, condition, text: String(options.text || "").replace(/\s+$/, "") });
840
+ }
841
+
842
+ // Waits no `met` record targets, in the open groups `role` can read (or all).
843
+ function openWaits(where, role = null) {
844
+ const waits = [];
845
+ for (const group of listGroupNames(where)) {
846
+ const records = readLog(where, group);
847
+ const state = groupState(records);
848
+ if (!state.exists || state.archived || (role && !canAct(state, role))) continue;
849
+ const met = new Set(records.filter((r) => r.kind === "met").map((r) => r.target));
850
+ for (const record of records) {
851
+ if (record.kind === "wait" && !met.has(record.id)) waits.push(record);
852
+ }
853
+ }
854
+ return waits;
855
+ }
856
+
857
+ function markMet(where, waitRecord, by) {
858
+ return writeRecord(where, { group: waitRecord.group, kind: "met", from: by, target: waitRecord.id });
859
+ }
860
+
810
861
  // --- cursors and receipts -----------------------------------------------------
811
862
 
812
863
  // What changed since a time, per group and sender (#255): built from the
@@ -931,6 +982,10 @@ function readGroups(where, role, group) {
931
982
  }
932
983
 
933
984
  module.exports = {
985
+ wait,
986
+ openWaits,
987
+ markMet,
988
+ canAct,
934
989
  ack,
935
990
  summary,
936
991
  ackStatus,
@@ -124,6 +124,7 @@ const CONFIG_DECLARATIONS = [
124
124
  "merge",
125
125
  "external_agents",
126
126
  "read_only_roles",
127
+ "issue_roles",
127
128
  ];
128
129
 
129
130
  const CONFIG_RELATIVE_PATH = path.join("keel", "config.yaml");
@@ -827,7 +828,31 @@ function readReadOnlyRoles(repo) {
827
828
  return { roles, unreadable, message };
828
829
  }
829
830
 
831
+ // `issue_roles:` — which chat role an issue label routes to (#242), one
832
+ // `<label>: <role>` per line, read by `keel patrol`. A label may itself hold a
833
+ // colon (`role:verify`), so the role is what follows the last `: `. A line
834
+ // that is not that shape is reported and routes nothing.
835
+ function readIssueRoles(repo) {
836
+ const block = configBlockLines(repo, "issue_roles");
837
+ const routes = new Map();
838
+ const unreadable = [];
839
+ if (block === null) return { routes, unreadable };
840
+ if (block.inline !== null) unreadable.push(block.inline);
841
+ for (const line of block.lines) {
842
+ const text = line.replace(/\s+#.*$/, "").trim();
843
+ if (!text) continue;
844
+ const match = text.match(/^(.+?):\s+([a-z0-9][a-z0-9-]{0,31})$/);
845
+ if (!match) {
846
+ unreadable.push(text);
847
+ continue;
848
+ }
849
+ routes.set(match[1].replace(/^["']|["']$/g, ""), match[2]);
850
+ }
851
+ return { routes, unreadable };
852
+ }
853
+
830
854
  module.exports = {
855
+ readIssueRoles,
831
856
  readReadOnlyRoles,
832
857
  readExternalAgents,
833
858
  CONFIG_RELATIVE_PATH,
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+
3
+ // `keel patrol` (#260, #242): run by the coordinator's role on a host schedule.
4
+ // It marks each declared wait whose condition now holds as met and tells the
5
+ // waiting role, routes labelled issue updates to the roles `issue_roles:`
6
+ // names, and lists every role's presence. Keel fetches nothing and schedules
7
+ // nothing (F4): the caller fetches, passes `gh` output, and runs it.
8
+ const fs = require("fs");
9
+ const path = require("path");
10
+ const { spawnSync } = require("child_process");
11
+ const store = require("./chat/store");
12
+ const notice = require("./chat/notice");
13
+ const { parseSince } = require("./chat/view");
14
+
15
+ const USAGE = "keel patrol [--issues <file>] [--idle <90s|15m|2h|3d>] [--json] [--repo <path>]";
16
+ const EXIT_QUIET = 0;
17
+ const EXIT_ERROR = 1;
18
+ const EXIT_WROTE = 2;
19
+
20
+ class PatrolError extends Error {}
21
+
22
+ function git(cwd, args) {
23
+ const result = spawnSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } });
24
+ return result.status === 0 ? String(result.stdout || "").trim() : null;
25
+ }
26
+
27
+ // `gh issue list --json number,title,state,labels,updatedAt`, refused by name
28
+ // when it is not that shape.
29
+ function readIssues(file) {
30
+ if (!file) return null;
31
+ let parsed;
32
+ try {
33
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
34
+ } catch (error) {
35
+ throw new PatrolError(`--issues ${file} is not readable JSON: ${error.message}`);
36
+ }
37
+ if (!Array.isArray(parsed) || parsed.some((issue) => !issue || !Number.isInteger(issue.number))) {
38
+ throw new PatrolError(`--issues ${file} must be the JSON array \`gh issue list --json number,title,state,labels,updatedAt\` prints.`);
39
+ }
40
+ return parsed;
41
+ }
42
+
43
+ // D3: a commit condition holds when a `refs/remotes/<remote>/` ref contains it.
44
+ function conditionHolds(where, condition, issues) {
45
+ const commit = condition.match(/^commit ([0-9a-f]+) on (\S+)$/);
46
+ if (commit) {
47
+ if (git(where.worktree, ["cat-file", "-e", `${commit[1]}^{commit}`]) === null) return { holds: false };
48
+ const refs = git(where.worktree, ["for-each-ref", "--contains", commit[1], "--format=%(refname)", `refs/remotes/${commit[2]}/`]);
49
+ return { holds: Boolean(refs) };
50
+ }
51
+ const issue = condition.match(/^issue #(\d+) closed$/);
52
+ if (issue) {
53
+ if (!issues) return { unchecked: true };
54
+ const found = issues.find((entry) => entry.number === Number(issue[1]));
55
+ return { holds: Boolean(found && String(found.state).toUpperCase() === "CLOSED") };
56
+ }
57
+ return { unchecked: true };
58
+ }
59
+
60
+ function patrol(where, role, options) {
61
+ const result = { role, notices: [], held: [], unchecked: [], roles: [], warnings: [] };
62
+ for (const waitRecord of store.openWaits(where, role)) {
63
+ const check = conditionHolds(where, waitRecord.condition, options.issues);
64
+ if (check.unchecked) {
65
+ result.unchecked.push({ id: waitRecord.id, from: waitRecord.from, condition: waitRecord.condition });
66
+ continue;
67
+ }
68
+ if (!check.holds) continue;
69
+ store.markMet(where, waitRecord, role);
70
+ result.held.push({ id: waitRecord.id, from: waitRecord.from, condition: waitRecord.condition });
71
+ if (waitRecord.from !== role) {
72
+ const text = `Condition met: ${waitRecord.condition} (wait ${waitRecord.id}${waitRecord.text ? `: ${waitRecord.text}` : ""}).`;
73
+ const posted = store.directPost(where, waitRecord.from, text, { refs: [`wait:${waitRecord.id}`] });
74
+ result.notices.push({ to: waitRecord.from, id: posted.id, text });
75
+ }
76
+ }
77
+ const routed = routeIssues(where, role, options);
78
+ result.notices.push(...routed.notices);
79
+ result.warnings.push(...routed.warnings);
80
+ // D6: presence is reported, never acted on.
81
+ const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))].sort();
82
+ const threshold = parseSince(options.idle);
83
+ for (const name of roles) {
84
+ const presence = notice.presenceOf(where, name);
85
+ const last = Date.parse(presence.last_active || "");
86
+ result.roles.push({
87
+ role: name,
88
+ presence: presence.state,
89
+ lastActive: presence.last_active,
90
+ idle: Number.isNaN(last) || last < threshold,
91
+ openTodos: store.openTodos(where, { assignee: name }).length,
92
+ });
93
+ }
94
+ return result;
95
+ }
96
+
97
+ // D5 (#242): each role a label of an issue maps to gets one direct message
98
+ // per `updatedAt`, deduped by its ref against the direct group's records.
99
+ function routeIssues(where, role, options) {
100
+ const { routes, unreadable } = require("./config").readIssueRoles(where.worktree);
101
+ const warnings = unreadable.map(
102
+ (line) => `keel/config.yaml issue_roles line \`${line}\` is not \`<label>: <role>\`; it routes nothing.`
103
+ );
104
+ const notices = [];
105
+ if (!options.issues || !routes.size) return { notices, warnings };
106
+ for (const issue of options.issues) {
107
+ const labels = (issue.labels || []).map((entry) => (typeof entry === "string" ? entry : entry && entry.name)).filter(Boolean);
108
+ const targets = [...new Set(labels.map((name) => routes.get(name)).filter(Boolean))];
109
+ for (const target of targets) {
110
+ if (target === role) continue;
111
+ const ref = `issue:#${issue.number}@${issue.updatedAt || "unknown"}`;
112
+ const group = store.directName(role, target);
113
+ if (store.readLog(where, group).some((record) => (record.refs || []).includes(ref))) continue;
114
+ const when = issue.updatedAt ? ` at ${issue.updatedAt}` : "";
115
+ const title = issue.title ? `: ${issue.title}` : "";
116
+ const text = `Issue #${issue.number} changed${when}${title} (its label routes it to ${target}).`;
117
+ const posted = store.directPost(where, target, text, { refs: [ref] });
118
+ notices.push({ to: target, id: posted.id, text });
119
+ }
120
+ }
121
+ return { notices, warnings };
122
+ }
123
+
124
+ function render(result) {
125
+ const lines = [];
126
+ if (!result.notices.length && !result.held.length) lines.push("keel patrol: nothing new.");
127
+ for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
128
+ for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
129
+ for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
130
+ for (const warning of result.warnings) lines.push(`warning: ${warning}`);
131
+ for (const row of result.roles) {
132
+ lines.push(`role ${row.role}: ${row.presence}${row.idle ? " (idle)" : ""}, last active ${row.lastActive || "unknown"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`);
133
+ }
134
+ return lines.join("\n");
135
+ }
136
+
137
+ function runPatrol(argv) {
138
+ const options = { repo: process.cwd(), issues: null, idle: "30m", json: false };
139
+ try {
140
+ for (let index = 0; index < argv.length; index += 1) {
141
+ const arg = argv[index];
142
+ if (arg === "--json") options.json = true;
143
+ else if (arg === "--help" || arg === "-h") {
144
+ process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
145
+ return EXIT_QUIET;
146
+ } else if (["--repo", "--issues", "--idle"].includes(arg)) {
147
+ const value = argv[++index];
148
+ if (!value || value.startsWith("--")) throw new PatrolError(`${arg} needs a value.`);
149
+ options[arg.slice(2)] = value;
150
+ } else throw new PatrolError(`Unknown argument ${arg}. ${USAGE}`);
151
+ }
152
+ if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
153
+ options.issues = readIssues(options.issues);
154
+ const where = store.requireLocation(path.resolve(options.repo));
155
+ const role = store.requireRole(where);
156
+ const result = patrol(where, role, options);
157
+ 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;
159
+ } catch (error) {
160
+ if (error instanceof PatrolError || error instanceof store.ChatError) {
161
+ process.stderr.write(`keel patrol: ${error.message}\n`);
162
+ return EXIT_ERROR;
163
+ }
164
+ throw error;
165
+ }
166
+ }
167
+
168
+ module.exports = { PatrolError, runPatrol, patrol };