@christang/keel 5.108.0 → 5.110.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
@@ -182,7 +182,7 @@ because a permission granted in conversation does not survive a context reset. D
182
182
  `keel/config.yaml` instead:
183
183
 
184
184
  ```yaml
185
- authorize: # accepted names: commit, push, push:<branch glob>, release, archive, continuation, issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch
185
+ authorize: # accepted names: commit, push, push:<branch glob>, release, archive, continuation, issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch, push-protected:<branch glob>[@<role>]
186
186
  - commit
187
187
  - push
188
188
  ```
@@ -223,6 +223,14 @@ push destination — naming `git push origin <branch>` instead. A bare `push` ke
223
223
  and declaring it beside a `push:` glob is refused, because it would silently widen the glob. Codex
224
224
  has no such hook, so there the scope is carried, not enforced.
225
225
 
226
+ `push-protected:<branch glob>`, optionally `@<role>`, names a branch that is neither allowed nor
227
+ refused but asked about (#280): a push to it makes the Claude write guard return `ask`, so Claude
228
+ Code asks you to confirm that one command, and the next push asks again — Keel stores no approval.
229
+ `push-protected:main@iecc-pm` lets only the session bound to `iecc-pm` ask; any other session is
230
+ refused. A permission mode that cannot be relied on to ask, `bypassPermissions` or `dontAsk`, is
231
+ refused too. Declaring it turns the push check on by itself, and a bare `push` beside it is
232
+ refused.
233
+
226
234
  `cleanup:scratch` covers removing temporary worktrees and run output under the session's own
227
235
  scratchpad, after checking that they are merged and that no process is using them. It never covers
228
236
  a branch or another session's files, and like the tracker scopes it is carried, not enforced.
@@ -251,7 +259,7 @@ Three things the declaration is not:
251
259
  anything.
252
260
  - **Not a trigger.** It removes a confirmation, not the step that reaches the action. Nothing
253
261
  schedules itself, and no next task is selected for you.
254
- - **Not open-ended.** The ten names above are the whole vocabulary. An unrecognized entry is
262
+ - **Not open-ended.** The eleven names above are the whole vocabulary. An unrecognized entry is
255
263
  reported with the accepted names and the declaration authorizes nothing until you fix it — a
256
264
  typo never becomes a silent grant.
257
265
 
@@ -758,6 +766,33 @@ Without a known default branch, no issue range is inferred.
758
766
 
759
767
  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
768
 
769
+ ## Coordinator patrol
770
+
771
+ A coordinating session that goes quiet stalls everyone waiting on it (#260). A role records what it
772
+ is waiting for, and a patrol the host runs on a schedule tells it when that holds:
773
+
774
+ ```bash
775
+ keel chat wait soc --commit eb340a7 rerun R007 when the fix lands # or: --issue 42 --closed
776
+ git fetch && gh issue list --json number,title,state,labels,updatedAt > /tmp/issues.json
777
+ keel patrol --issues /tmp/issues.json # as the coordinator's role
778
+ ```
779
+
780
+ `keel patrol` marks each wait whose condition now holds — a commit on the remote, an issue closed —
781
+ as met and sends the waiting role one direct message, which wakes it. It lists every role's
782
+ presence, last activity, and open todos, marking those idle beyond `--idle` (default `30m`). It
783
+ fetches nothing, schedules nothing, calls no model, and writes nothing when nothing is new; it exits
784
+ 0 then, 2 when it sent something, and 1 on an error, so a cheap scheduler — cron, `/loop`, CI — can
785
+ wake the model only on 2. `keel chat waits` lists what is still awaited.
786
+
787
+ With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
788
+ maps a label to a role, and each role gets one direct message per update of an issue carrying its
789
+ label — so a handoff labelled `role:verify` reaches `verify` without a second message.
790
+
791
+ ```yaml
792
+ issue_roles:
793
+ role:verify: verify
794
+ ```
795
+
761
796
  ## Commands
762
797
 
763
798
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.108.0 -->
1
+ <!-- keel:start version=5.110.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
@@ -2254,7 +2254,7 @@ function printStandingAuthorizationSurface(repo) {
2254
2254
  // observes none that an agent runs, so the scope is a declaration carried to
2255
2255
  // the people who read it rather than a boundary anything holds. A reader who
2256
2256
  // took it for a sandbox would be relying on nothing.
2257
- if ([...scopes.entries()].some(([action, scope]) => scope !== null && action !== "push")) {
2257
+ if ([...scopes.entries()].some(([action, scope]) => scope !== null && action !== "push" && action !== "push-protected")) {
2258
2258
  printDoctorLine(
2259
2259
  "scope",
2260
2260
  "carried",
@@ -2266,6 +2266,15 @@ function printStandingAuthorizationSurface(repo) {
2266
2266
  // The one scope something holds (#257): the Claude write guard reads the
2267
2267
  // `push:` globs and refuses a `git push` to any other branch, with or
2268
2268
  // without a task. Codex has no such hook, so there it is a declaration too.
2269
+ if (scopes.get("push-protected")) {
2270
+ printDoctorLine(
2271
+ "protected push",
2272
+ "asked",
2273
+ "the Claude write guard asks the user to confirm each push to these "
2274
+ + "branches, one command at a time; a role after `@` limits who may be "
2275
+ + "asked, and a mode that cannot ask (bypassPermissions, dontAsk) is refused"
2276
+ );
2277
+ }
2269
2278
  if (scopes.get("push")) {
2270
2279
  printDoctorLine(
2271
2280
  "push scope",
@@ -2871,6 +2880,9 @@ function main() {
2871
2880
  if (process.argv[2] === "lock") {
2872
2881
  return require("../src/core/lock").runLock(process.argv.slice(3));
2873
2882
  }
2883
+ if (process.argv[2] === "patrol") {
2884
+ return require("../src/core/patrol").runPatrol(process.argv.slice(3));
2885
+ }
2874
2886
  if (process.argv[2] === "worktrees") {
2875
2887
  return require("../src/core/worktrees").runWorktrees(process.argv.slice(3));
2876
2888
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.108.0",
3
+ "version": "5.110.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.110.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.110.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.110.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.110.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",
@@ -55,6 +55,20 @@ function deny(reason) {
55
55
  );
56
56
  }
57
57
 
58
+ // Hand the decision to the user for this one call (#280): the host asks, and
59
+ // nothing is stored, so the next call is asked again.
60
+ function ask(reason) {
61
+ process.stdout.write(
62
+ `${JSON.stringify({
63
+ hookSpecificOutput: {
64
+ hookEventName: "PreToolUse",
65
+ permissionDecision: "ask",
66
+ permissionDecisionReason: reason,
67
+ },
68
+ })}\n`
69
+ );
70
+ }
71
+
58
72
  function sha256(buffer) {
59
73
  return crypto.createHash("sha256").update(buffer).digest("hex");
60
74
  }
@@ -173,14 +187,16 @@ function gitOut(cwd, args) {
173
187
  return result.status === 0 ? String(result.stdout || "").trim() : null;
174
188
  }
175
189
 
190
+ // `push:` globs and `push-protected:` entries ({ glob, role }) of `authorize:`.
176
191
  function readPushGlobs(top) {
177
192
  let text = "";
178
193
  try {
179
194
  text = fs.readFileSync(path.join(top, "keel", "config.yaml"), "utf8");
180
195
  } catch {
181
- return [];
196
+ return { globs: [], protectedEntries: [] };
182
197
  }
183
198
  const globs = [];
199
+ const protectedEntries = [];
184
200
  let inBlock = false;
185
201
  for (const line of text.split(/\r?\n/)) {
186
202
  if (/^\s*#/.test(line) || line.trim() === "") continue;
@@ -190,12 +206,35 @@ function readPushGlobs(top) {
190
206
  }
191
207
  if (!inBlock) continue;
192
208
  if (!/^\s/.test(line)) break;
193
- const entry = line.replace(/\s+#.*$/, "").match(/^\s+-\s*push:(\S+)\s*$/);
209
+ const bare = line.replace(/\s+#.*$/, "");
210
+ const entry = bare.match(/^\s+-\s*push:(\S+)\s*$/);
194
211
  if (entry) globs.push(entry[1]);
212
+ const guarded = bare.match(/^\s+-\s*push-protected:([^@\s]+)(?:@(\S+))?\s*$/);
213
+ if (guarded) protectedEntries.push({ glob: guarded[1], role: guarded[2] || null });
195
214
  }
196
- return globs;
215
+ return { globs, protectedEntries };
197
216
  }
198
217
 
218
+ // The chat role bound to the worktree at `top` (#245), for a role-limited
219
+ // protected branch (#280 D3). Read directly: this hook never spawns the CLI.
220
+ function sessionRole(top) {
221
+ for (const variable of ["KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE"]) {
222
+ const value = (process.env[variable] || "").trim();
223
+ if (value) return value;
224
+ }
225
+ const common = gitOut(top, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
226
+ if (!common) return null;
227
+ try {
228
+ const roles = JSON.parse(fs.readFileSync(path.join(fs.realpathSync(common), "keel-chat", "roles.json"), "utf8"));
229
+ return roles[fs.realpathSync(top)] || null;
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ // Modes in which the host cannot be relied on to ask (#280 D3, F2).
236
+ const MODES_THAT_CANNOT_ASK = new Set(["bypassPermissions", "dontAsk"]);
237
+
199
238
  // Shell words and the separators between commands. Quotes are honoured, and a
200
239
  // word that the shell would expand (`$`, a backtick) is marked, because its
201
240
  // value is not knowable here.
@@ -426,12 +465,16 @@ function checkPushes(event) {
426
465
  ? event.tool_input.command : "";
427
466
  if (!/\bgit\b/.test(command) || !/\bpush\b/.test(command)) return 0;
428
467
  const cwd = typeof event.cwd === "string" && event.cwd ? event.cwd : process.cwd();
468
+ const asks = [];
429
469
  for (const push of findPushes(command, cwd)) {
430
470
  const top = gitOut(push.dir || cwd, ["rev-parse", "--show-toplevel"]);
431
471
  if (!top) continue;
432
- const globs = readPushGlobs(top);
433
- if (!globs.length) continue;
434
- const declared = globs.map((glob) => `\`push:${glob}\``).join(", ");
472
+ const { globs, protectedEntries } = readPushGlobs(top);
473
+ if (!globs.length && !protectedEntries.length) continue;
474
+ const declared = [
475
+ ...globs.map((glob) => `\`push:${glob}\``),
476
+ ...protectedEntries.map((e) => `\`push-protected:${e.glob}${e.role ? `@${e.role}` : ""}\``),
477
+ ].join(", ");
435
478
  const result = pushTargets(push);
436
479
  if (result.undetermined) {
437
480
  deny(
@@ -441,7 +484,27 @@ function checkPushes(event) {
441
484
  );
442
485
  return 0;
443
486
  }
444
- const outside = result.targets.filter((branch) => !globs.some((glob) => globPattern(glob).test(branch)));
487
+ const unlisted = result.targets.filter((branch) => !globs.some((glob) => globPattern(glob).test(branch)));
488
+ const outside = [];
489
+ for (const branch of unlisted) {
490
+ const entry = protectedEntries.find((e) => globPattern(e.glob).test(branch));
491
+ if (!entry) {
492
+ outside.push(branch);
493
+ continue;
494
+ }
495
+ if (entry.role) {
496
+ const role = sessionRole(top);
497
+ if (role !== entry.role) {
498
+ deny(
499
+ `Keel push guard: \`${branch}\` is protected for role ${entry.role}, and this `
500
+ + `session is ${role ? `role ${role}` : "bound to no chat role"}; only an ${entry.role} `
501
+ + "session may ask to push it."
502
+ );
503
+ return 0;
504
+ }
505
+ }
506
+ asks.push(branch);
507
+ }
445
508
  if (outside.length) {
446
509
  deny(
447
510
  `Keel push guard: this command pushes to ${outside.map((b) => `\`${b}\``).join(", ")}, `
@@ -451,6 +514,22 @@ function checkPushes(event) {
451
514
  return 0;
452
515
  }
453
516
  }
517
+ if (asks.length) {
518
+ const mode = typeof event.permission_mode === "string" ? event.permission_mode : "";
519
+ const branches = asks.map((b) => `\`${b}\``).join(", ");
520
+ if (MODES_THAT_CANNOT_ASK.has(mode)) {
521
+ deny(
522
+ `Keel push guard: ${branches} is protected, so each push needs the user's `
523
+ + `confirmation, and permission mode ${mode} cannot be relied on to ask. `
524
+ + "Switch to a mode that asks, or let the user push it."
525
+ );
526
+ return 0;
527
+ }
528
+ ask(
529
+ `Keel push guard: ${branches} is a protected branch (keel/config.yaml `
530
+ + "push-protected). Confirm only if the user approves this one push; the next push asks again."
531
+ );
532
+ }
454
533
  return 0;
455
534
  }
456
535
 
@@ -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.110.0"
51
+ PROTOCOL_VERSION = "5.110.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
 
@@ -24391,6 +24545,42 @@ def validate_authorize_block_reads_every_line_scenario() -> int:
24391
24545
  return 0
24392
24546
 
24393
24547
 
24548
+ def validate_push_protected_declaration_scenario() -> int:
24549
+ """Issue #280: `push-protected:<glob>[@<role>]` is accepted and reported."""
24550
+ label = "push-protected-declaration:"
24551
+ with tempfile.TemporaryDirectory(prefix="keel-push-protected-") as raw_tmp:
24552
+ root = Path(raw_tmp)
24553
+
24554
+ def fixture(name: str, entries: list[str]) -> Path:
24555
+ repo = root / name
24556
+ repo.mkdir()
24557
+ write_authorize_config(repo, "authorize:\n" + "".join(f" - {e}\n" for e in entries))
24558
+ return repo
24559
+
24560
+ doctor = run_keel(fixture("good", ["push:claude/*", "push-protected:main@iecc-pm"]), "--doctor")
24561
+ line = next((l for l in doctor.stdout.splitlines() if l.strip().startswith("push-protected:")), "")
24562
+ if "authorized" not in line or "main@iecc-pm" not in line:
24563
+ report(f"{label} doctor's push-protected line is {line!r}.")
24564
+ report(doctor.stdout)
24565
+ return 1
24566
+ if "asks the user" not in doctor.stdout:
24567
+ report(f"{label} doctor does not say each protected push is asked: {doctor.stdout}")
24568
+ return 1
24569
+ for name, entries, needle in (
24570
+ ("bad-role", ["push-protected:main@Not"], "push-protected:main@Not"),
24571
+ ("mixed", ["push", "push-protected:main"], "push-protected:main"),
24572
+ ):
24573
+ refused = run_keel(fixture(name, entries), "--doctor")
24574
+ if refused.returncode == 0:
24575
+ report(f"{label} {entries!r} was accepted.")
24576
+ return 1
24577
+ if needle not in refused.stdout + refused.stderr:
24578
+ report(f"{label} {entries!r} was refused without naming {needle!r}: {refused.stdout}")
24579
+ return 1
24580
+ report("push-protected-declaration scenario passed.")
24581
+ return 0
24582
+
24583
+
24394
24584
  def validate_authorize_push_close_cleanup_scenario() -> int:
24395
24585
  """Issue #257: `push:<glob>`, `issue-close:<owner>/<repo>`, `cleanup:scratch`.
24396
24586
 
@@ -27385,7 +27575,7 @@ def validate_continuation_authorization_scenario() -> int:
27385
27575
  ACCEPTED_AUTHORIZE_NAMES = (
27386
27576
  "commit, push, push:<branch glob>, release, archive, continuation, "
27387
27577
  "issue:<owner>/<repo>, protocol-refresh, chat-reply:<group>, "
27388
- "issue-close:<owner>/<repo>, cleanup:scratch"
27578
+ "issue-close:<owner>/<repo>, cleanup:scratch, push-protected:<branch glob>[@<role>]"
27389
27579
  )
27390
27580
 
27391
27581
 
@@ -27439,7 +27629,7 @@ def validate_continuation_docs_scenario() -> int:
27439
27629
  # to spell all of it: a reader copies from the list they are shown.
27440
27630
  for needle in (
27441
27631
  f"accepted names: {ACCEPTED_AUTHORIZE_NAMES}",
27442
- "The ten names above are the whole vocabulary.",
27632
+ "The eleven names above are the whole vocabulary.",
27443
27633
  "`protocol-refresh`, the seventh name",
27444
27634
  ):
27445
27635
  if needle not in readme:
@@ -27447,7 +27637,7 @@ def validate_continuation_docs_scenario() -> int:
27447
27637
  return 1
27448
27638
 
27449
27639
  config_text = (ROOT / "keel/config.yaml").read_text(encoding="utf-8")
27450
- if "commit, push, push:<branch glob>,\n# release, archive, continuation, issue:<owner>/<repo>, protocol-refresh,\n# chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch" not in config_text:
27640
+ if "commit, push, push:<branch glob>,\n# release, archive, continuation, issue:<owner>/<repo>, protocol-refresh,\n# chat-reply:<group>, issue-close:<owner>/<repo>, cleanup:scratch,\n# push-protected:<branch glob>[@<role>]" not in config_text:
27451
27641
  report(
27452
27642
  f"{label}: keel/config.yaml's comment lacks: protocol-refresh in the "
27453
27643
  "seven-name vocabulary."
@@ -29912,6 +30102,83 @@ def validate_push_branch_guard_scenario() -> int:
29912
30102
  return 0
29913
30103
 
29914
30104
 
30105
+ def validate_push_protected_guard_scenario() -> int:
30106
+ """Issue #280: a protected push is asked, never stored, and role-limited.
30107
+
30108
+ The real hook returns `ask` for the bound role in a mode that can ask,
30109
+ denies another role and a mode that cannot ask, and leaves `push:` and
30110
+ unlisted branches as they were.
30111
+ """
30112
+ label = "push-protected-guard:"
30113
+ with tempfile.TemporaryDirectory(prefix="keel-push-protected-guard-") as raw:
30114
+ base = Path(raw)
30115
+ repo = mailbox_repository(base / "repo")
30116
+ pm = chat_worktree(repo, base / "pm")
30117
+ rtl = chat_worktree(repo, base / "rtl")
30118
+ env = chat_environment()
30119
+ run_keel(pm, "chat", "role", "--set", "iecc-pm", env=env)
30120
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
30121
+ hook_env = {k: v for k, v in os.environ.items() if k not in ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")}
30122
+ hook_env["CLAUDE_PLUGIN_ROOT"] = str(ROOT / PLUGIN_ROOT)
30123
+
30124
+ def declare(entries: list[str]) -> None:
30125
+ for cwd in (pm, rtl):
30126
+ write_authorize_config(cwd, "authorize:\n" + "".join(f" - {e}\n" for e in entries))
30127
+
30128
+ def decide(cwd: Path, command: str, mode: str = "default") -> dict:
30129
+ event = {"tool_name": "Bash", "tool_input": {"command": command}, "cwd": str(cwd), "permission_mode": mode}
30130
+ result = subprocess.run(
30131
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/pretooluse-guard.js")],
30132
+ cwd=cwd, env=hook_env, input=json.dumps(event), text=True, capture_output=True, check=False,
30133
+ )
30134
+ return pretooluse_decision(result) or {"permissionDecision": "pass"}
30135
+
30136
+ declare(["push:claude/*", "push-protected:main@iecc-pm"])
30137
+ store_before = chat_logs_snapshot(repo)
30138
+ for attempt in (1, 2):
30139
+ asked = decide(pm, "git push origin HEAD:main")
30140
+ if asked.get("permissionDecision") != "ask":
30141
+ report(f"{label} the coordinator's push to main (attempt {attempt}) was {asked!r}, not ask.")
30142
+ return 1
30143
+ if "main" not in asked.get("permissionDecisionReason", ""):
30144
+ report(f"{label} the ask does not name main: {asked!r}")
30145
+ return 1
30146
+ if chat_logs_snapshot(repo) != store_before:
30147
+ report(f"{label} asking wrote to the chat store.")
30148
+ return 1
30149
+ other = decide(rtl, "git push origin HEAD:main")
30150
+ if other.get("permissionDecision") != "deny":
30151
+ report(f"{label} another role's push to main was {other!r}, not deny.")
30152
+ return 1
30153
+ if "iecc-pm" not in other.get("permissionDecisionReason", ""):
30154
+ report(f"{label} the refusal does not name iecc-pm: {other!r}")
30155
+ return 1
30156
+ for mode in ("bypassPermissions", "dontAsk"):
30157
+ refused = decide(pm, "git push origin HEAD:main", mode)
30158
+ if refused.get("permissionDecision") != "deny":
30159
+ report(f"{label} the protected push in {mode} was {refused!r}, not deny.")
30160
+ return 1
30161
+ if mode not in refused.get("permissionDecisionReason", ""):
30162
+ report(f"{label} the {mode} refusal does not name the mode: {refused!r}")
30163
+ return 1
30164
+ if decide(rtl, "git push origin claude/fix").get("permissionDecision") != "pass":
30165
+ report(f"{label} a declared push: branch was intercepted.")
30166
+ return 1
30167
+ if decide(rtl, "git push origin release").get("permissionDecision") != "deny":
30168
+ report(f"{label} an unlisted branch was not denied.")
30169
+ return 1
30170
+
30171
+ declare(["push-protected:main"])
30172
+ if decide(rtl, "git push origin release").get("permissionDecision") != "deny":
30173
+ report(f"{label} with only push-protected declared, an unlisted branch was not denied.")
30174
+ return 1
30175
+ if decide(rtl, "git push origin HEAD:main").get("permissionDecision") != "ask":
30176
+ report(f"{label} with no role limit, a push to main was not asked.")
30177
+ return 1
30178
+ report("push-protected-guard scenario passed.")
30179
+ return 0
30180
+
30181
+
29915
30182
  def validate_touch_write_guard_scenario() -> int:
29916
30183
  with tempfile.TemporaryDirectory(
29917
30184
  prefix="keel-touch-guard-", ignore_cleanup_errors=True
@@ -38457,6 +38724,7 @@ SCENARIOS: tuple = (
38457
38724
  validate_standing_authorization_declaration_scenario,
38458
38725
  ),
38459
38726
  ("authorize-push-close-cleanup", validate_authorize_push_close_cleanup_scenario),
38727
+ ("push-protected-declaration", validate_push_protected_declaration_scenario),
38460
38728
  ("authorize-block-reads-every-line", validate_authorize_block_reads_every_line_scenario),
38461
38729
  (
38462
38730
  "standing-authorization-sync-confusion",
@@ -38643,6 +38911,8 @@ SCENARIOS: tuple = (
38643
38911
  ("resource-lock", validate_resource_lock_scenario),
38644
38912
  ("chat-supersedes", validate_chat_supersedes_scenario),
38645
38913
  ("chat-ack", validate_chat_ack_scenario),
38914
+ ("coordinator-patrol", validate_coordinator_patrol_scenario),
38915
+ ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
38646
38916
  ("chat-listen-only", validate_chat_listen_only_scenario),
38647
38917
  ("chat-summary", validate_chat_summary_scenario),
38648
38918
  ("worktree-overview", validate_worktree_overview_scenario),
@@ -38663,6 +38933,7 @@ SCENARIOS: tuple = (
38663
38933
  ("native-single-task-matrix", validate_native_single_task_matrix_scenario),
38664
38934
  ("touch-write-guard", validate_touch_write_guard_scenario),
38665
38935
  ("push-branch-guard", validate_push_branch_guard_scenario),
38936
+ ("push-protected-guard", validate_push_protected_guard_scenario),
38666
38937
  ("touch-guard-record-layer", validate_touch_guard_record_layer_scenario),
38667
38938
  ("repo-action-mode", validate_repo_action_mode_scenario),
38668
38939
  ("runner-skip-accounting", validate_runner_skip_accounting_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,
@@ -28,6 +28,9 @@ const STANDING_AUTHORIZATION_ACTIONS = [
28
28
  // scratchpad once merged and unused, never a branch or another session's
29
29
  // files (#257). Its one scope, `scratch`, says which tree it reaches.
30
30
  "cleanup",
31
+ // A branch the Claude write guard asks the user about, one push at a time,
32
+ // instead of refusing (#280); `@<role>` limits who may be asked.
33
+ "push-protected",
31
34
  ];
32
35
 
33
36
  // The actions whose credential reaches further than the checkout the
@@ -37,7 +40,7 @@ const STANDING_AUTHORIZATION_ACTIONS = [
37
40
  // actions are declared with the resource they may reach and refused bare —
38
41
  // accepting the bare form as a convenience would make the narrow form optional
39
42
  // and the wide one the default, which is the decision inverted.
40
- const SCOPED_AUTHORIZATION_ACTIONS = new Set(["issue", "chat-reply", "issue-close", "cleanup"]);
43
+ const SCOPED_AUTHORIZATION_ACTIONS = new Set(["issue", "chat-reply", "issue-close", "cleanup", "push-protected"]);
41
44
 
42
45
  // Actions whose scope narrows them but is not required (#257). A bare `push`
43
46
  // keeps the meaning it always had; `push:<branch glob>` limits it to matching
@@ -60,6 +63,7 @@ const AUTHORIZATION_SCOPES = {
60
63
  // Branch-name characters and `*`; `*` matches within one `/` segment and
61
64
  // `**` across them, as Touch globs do.
62
65
  push: { form: "<branch glob>", pattern: /^[A-Za-z0-9._/*-]+$/ },
66
+ "push-protected": { form: "<branch glob>[@<role>]", pattern: /^[A-Za-z0-9._/*-]+(?:@[a-z0-9][a-z0-9-]{0,31})?$/ },
63
67
  };
64
68
 
65
69
  // How the accepted names are spelled back to an author: the scoped ones carry
@@ -124,6 +128,7 @@ const CONFIG_DECLARATIONS = [
124
128
  "merge",
125
129
  "external_agents",
126
130
  "read_only_roles",
131
+ "issue_roles",
127
132
  ];
128
133
 
129
134
  const CONFIG_RELATIVE_PATH = path.join("keel", "config.yaml");
@@ -294,6 +299,14 @@ function standingAuthorizationUnknownMessage(unknown, problems = []) {
294
299
  );
295
300
  continue;
296
301
  }
302
+ if (problem.action === "push-protected") {
303
+ notes.push(
304
+ `\`${problem.entry}\` is not \`push-protected:<branch glob>\` or `
305
+ + "`push-protected:<branch glob>@<role>` — a glob of letters, digits, `.`, `_`, `-`, `/`, and `*`, "
306
+ + "and a chat role of lowercase letters, digits, and hyphens."
307
+ );
308
+ continue;
309
+ }
297
310
  if (problem.action === "push") {
298
311
  notes.push(
299
312
  `\`${problem.entry}\` does not name a branch glob as \`push:<branch glob>\` — `
@@ -370,15 +383,22 @@ function readStandingAuthorization(repo) {
370
383
  // because the alternative is granting the entries beside a typo while the
371
384
  // author believes they granted the typo too.
372
385
  const pushGlobs = [];
386
+ const protectedPushes = [];
373
387
  for (const entry of declared) {
374
388
  const classified = classifyAuthorizationEntry(entry);
375
389
  if (classified.action === "push" && classified.scope !== null && !pushGlobs.includes(classified.scope)) {
376
390
  pushGlobs.push(classified.scope);
377
391
  }
392
+ if (classified.action === "push-protected" && !protectedPushes.includes(classified.scope)) {
393
+ protectedPushes.push(classified.scope);
394
+ }
378
395
  }
379
- if (pushGlobs.length && declared.includes("push")) {
396
+ if ((pushGlobs.length || protectedPushes.length) && declared.includes("push")) {
380
397
  unknown.push("push");
381
- problems.push({ reason: "mixed-push", entry: "push", action: "push", scoped: pushGlobs.map((glob) => `push:${glob}`) });
398
+ problems.push({
399
+ reason: "mixed-push", entry: "push", action: "push",
400
+ scoped: [...pushGlobs.map((glob) => `push:${glob}`), ...protectedPushes.map((scope) => `push-protected:${scope}`)],
401
+ });
382
402
  }
383
403
  if (unknown.length > 0) {
384
404
  return {
@@ -386,13 +406,15 @@ function readStandingAuthorization(repo) {
386
406
  scopes: new Map(),
387
407
  chatReplyGroups: [],
388
408
  pushGlobs: [],
409
+ protectedPushes: [],
389
410
  unknown,
390
411
  message: standingAuthorizationUnknownMessage(unknown, problems),
391
412
  };
392
413
  }
393
414
  if (chatReplyGroups.length) scopes.set("chat-reply", chatReplyGroups.join(", "));
394
415
  if (pushGlobs.length) scopes.set("push", pushGlobs.join(", "));
395
- return { declared, scopes, chatReplyGroups, pushGlobs, unknown, message: null };
416
+ if (protectedPushes.length) scopes.set("push-protected", protectedPushes.join(", "));
417
+ return { declared, scopes, chatReplyGroups, pushGlobs, protectedPushes, unknown, message: null };
396
418
  }
397
419
 
398
420
  // `full_mode_paths:` — the paths whose change always routes Full, whatever the
@@ -827,7 +849,31 @@ function readReadOnlyRoles(repo) {
827
849
  return { roles, unreadable, message };
828
850
  }
829
851
 
852
+ // `issue_roles:` — which chat role an issue label routes to (#242), one
853
+ // `<label>: <role>` per line, read by `keel patrol`. A label may itself hold a
854
+ // colon (`role:verify`), so the role is what follows the last `: `. A line
855
+ // that is not that shape is reported and routes nothing.
856
+ function readIssueRoles(repo) {
857
+ const block = configBlockLines(repo, "issue_roles");
858
+ const routes = new Map();
859
+ const unreadable = [];
860
+ if (block === null) return { routes, unreadable };
861
+ if (block.inline !== null) unreadable.push(block.inline);
862
+ for (const line of block.lines) {
863
+ const text = line.replace(/\s+#.*$/, "").trim();
864
+ if (!text) continue;
865
+ const match = text.match(/^(.+?):\s+([a-z0-9][a-z0-9-]{0,31})$/);
866
+ if (!match) {
867
+ unreadable.push(text);
868
+ continue;
869
+ }
870
+ routes.set(match[1].replace(/^["']|["']$/g, ""), match[2]);
871
+ }
872
+ return { routes, unreadable };
873
+ }
874
+
830
875
  module.exports = {
876
+ readIssueRoles,
831
877
  readReadOnlyRoles,
832
878
  readExternalAgents,
833
879
  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 };