@christang/keel 5.191.0 → 5.193.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.191.0",
3
+ "version": "5.193.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",
package/README.md CHANGED
@@ -906,11 +906,16 @@ Keel's own messages never count as waiting.
906
906
 
907
907
  With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
908
908
  maps a label to a role, and each role gets one direct message per update of an issue carrying its
909
- label — so a handoff labelled `role:verify` reaches `verify` without a second message.
909
+ label — so a handoff labelled `role:verify` reaches `verify` without a second message. A key may
910
+ name a set of labels joined by ` + ` (#433), which matches an issue carrying all of them, so teams of
911
+ the same shape can share capability labels. When one matching route's labels are a subset of
912
+ another's, only the larger set's role is sent the update; a quoted key stays one label.
910
913
 
911
914
  ```yaml
912
915
  issue_roles:
913
916
  role:verify: verify
917
+ design: design-iecc
918
+ design + dmc_rmw: design-rmw
914
919
  ```
915
920
 
916
921
  A host schedule made inside a session ends with that session, so a shift change or restart drops
@@ -923,6 +928,24 @@ patrol:
923
928
  every: 30m
924
929
  ```
925
930
 
931
+ A repository with one coordinator per team lists several (#434), each item carrying the same keys
932
+ plus `scope: group:<name>`. A scoped coordinator nudges, routes issues to, and reports on only the
933
+ members of that chat group; an unscoped one covers the roles in no scope, and a role in two groups
934
+ is covered by both and nudged at most once per window. The remote tip, the shared checkout, drift,
935
+ disk, and quota are reported by the unscoped coordinator, or by the first listed when all are
936
+ scoped. Each role gets its own reminder, `keel patrol task` renders the calling worktree's role's
937
+ task (or `--role <role>`'s), and `keel tick` runs each one when it is due:
938
+
939
+ ```yaml
940
+ patrol:
941
+ - role: pm-iecc
942
+ every: 60m
943
+ scope: group:iecc
944
+ - role: pm-rmw
945
+ every: 60m
946
+ scope: group:rmw
947
+ ```
948
+
926
949
  Better, run the patrol outside the coordinator's session altogether, as a host scheduled task on a
927
950
  small model, which survives the coordinator clearing itself (#295). Add `host_task: <id>` (and, if
928
951
  you like, `model: <id>`, which Keel passes through and never chooses) and run `keel patrol task`: it
package/README.zh-CN.md CHANGED
@@ -752,11 +752,15 @@ keel patrol --issues /tmp/issues.json # 以协调者的角色运行
752
752
 
753
753
  带上 `--issues` 时,巡查还会分派 issue 更新(#242):`keel/config.yaml` 里的 `issue_roles:` 把一个标签映射到
754
754
  一个角色,每个角色会为带着它标签的 issue 的每次更新收到一条私信——这样一个标为 `role:verify` 的交接无需第二条
755
- 消息就能到达 `verify`。
755
+ 消息就能到达 `verify`。一个键也可以是用 ` + ` 连起来的一组标签(#433),只匹配同时带着这些标签的 issue,这样
756
+ 结构相同的几个团队就能共用能力标签。当一条匹配路由的标签是另一条的子集时,只有标签更多的那条的角色收到更新;
757
+ 加了引号的键仍是单个标签。
756
758
 
757
759
  ```yaml
758
760
  issue_roles:
759
761
  role:verify: verify
762
+ design: design-iecc
763
+ design + dmc_rmw: design-rmw
760
764
  ```
761
765
 
762
766
  在会话内创建的宿主计划任务会随该会话结束,所以换班或重启就会丢掉它。声明由哪个角色巡查、多久一次,那个角色的
@@ -769,6 +773,22 @@ patrol:
769
773
  every: 30m
770
774
  ```
771
775
 
776
+ 一个团队一个协调者的仓库可以列出多个(#434),每一项带同样的键,再加上 `scope: group:<name>`。带范围的协调者
777
+ 只催促该聊天群的成员、只把 issue 分派给他们、也只报告他们的情况;不带范围的协调者负责不在任何范围里的角色,
778
+ 同时在两个群里的角色两边都管,但同一窗口内只会被催一次。远端分支头、共享 checkout、绑定漂移、磁盘和配额由不带
779
+ 范围的协调者报告,全部都带范围时由列在第一个的报告。每个角色收到自己的提醒,`keel patrol task` 渲染调用所在
780
+ worktree 的角色的任务(或 `--role <role>` 指定的),`keel tick` 在各自到期时分别运行:
781
+
782
+ ```yaml
783
+ patrol:
784
+ - role: pm-iecc
785
+ every: 60m
786
+ scope: group:iecc
787
+ - role: pm-rmw
788
+ every: 60m
789
+ scope: group:rmw
790
+ ```
791
+
772
792
  更好的做法是把巡查完全放到协调者的会话之外,作为一个运行在小模型上的宿主计划任务,这样它能熬过协调者清空自己
773
793
  (#295)。加上 `host_task: <id>`(愿意的话再加 `model: <id>`,Keel 只是原样传递,从不替你选择),然后运行
774
794
  `keel patrol task`:它打印出这个任务——id、由 `every:` 生成的 cron、模型,以及一份按路径针对协调者 worktree 运行
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.191.0 -->
1
+ <!-- keel:start version=5.193.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.191.0",
3
+ "version": "5.193.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.191.0",
9
+ "version": "5.193.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.191.0",
5
+ "version": "5.193.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.191.0",
3
+ "version": "5.193.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.191.0",
3
+ "version": "5.193.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",
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.191.0"
38
+ PACKAGE_VERSION = "5.193.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.191.0"
41
+ PROTOCOL_VERSION = "5.193.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -455,6 +455,7 @@ SCENARIOS: tuple = (
455
455
  ("patrol-since-last", shift.validate_patrol_since_last_scenario),
456
456
  ("patrol-next", shift.validate_patrol_next_scenario),
457
457
  ("tick-runs-due-patrol", shift.validate_tick_runs_due_patrol_scenario),
458
+ ("tick-runs-each-patrol", shift.validate_tick_runs_each_patrol_scenario),
458
459
  ("launchd-stable-node", shift.validate_launchd_stable_node_scenario),
459
460
  ("shift-slash-command", shift.validate_shift_slash_command_scenario),
460
461
  ("patrol-exit-says-who-acts", shift.validate_patrol_exit_says_who_acts_scenario),
@@ -462,8 +463,13 @@ SCENARIOS: tuple = (
462
463
  ("patrol-escalate", shift.validate_patrol_escalate_scenario),
463
464
  ("patrol-quota", shift.validate_patrol_quota_scenario),
464
465
  ("patrol-host-task", shift.validate_patrol_host_task_scenario),
466
+ ("patrol-scopes-declared", shift.validate_patrol_scopes_declared_scenario),
467
+ ("patrol-scopes-cover", shift.validate_patrol_scopes_cover_scenario),
468
+ ("patrol-scopes-repository-wide", shift.validate_patrol_scopes_repository_wide_scenario),
465
469
  ("patrol-rearm", shift.validate_patrol_rearm_scenario),
466
470
  ("patrol-issue-routing", shift.validate_patrol_issue_routing_scenario),
471
+ ("patrol-issue-label-sets", shift.validate_patrol_issue_label_sets_scenario),
472
+ ("patrol-issue-label-set-unreadable", shift.validate_patrol_issue_label_set_unreadable_scenario),
467
473
  ("chat-listen-only", chat.validate_chat_listen_only_scenario),
468
474
  ("chat-summary", chat.validate_chat_summary_scenario),
469
475
  ("worktree-overview", shift.validate_worktree_overview_scenario),
@@ -178,6 +178,176 @@ def validate_patrol_rearm_scenario() -> int:
178
178
  return 0
179
179
 
180
180
 
181
+ PATROL_SCOPES = (
182
+ "patrol:\n"
183
+ " - role: pm-a\n every: 30m\n scope: group:team-a\n"
184
+ " - role: pm-b\n every: 45m\n host_task: team-b-patrol\n scope: group:team-b\n"
185
+ )
186
+
187
+
188
+ def patrol_scopes_scratch(base: Path, config: str) -> tuple[Path, dict, dict[str, Path]]:
189
+ """Two team coordinators, their teams, a role in both teams, and one in neither (#434).
190
+
191
+ `team-a` holds pm-a, dev-a, and flow; `team-b` holds pm-b, dev-b, and
192
+ flow; lead and chief are in no team, as kaiwu-ip's shared roles are.
193
+ """
194
+ repo = mailbox_repository(base / "repo")
195
+ write_text(repo / "openspec/specs/.keep", "")
196
+ write_authorize_config(repo, config)
197
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
198
+ subprocess.run(["git", "commit", "-q", "-m", "patrol scopes"], cwd=repo, check=True, capture_output=True)
199
+ env = chat_environment()
200
+ worktrees = {}
201
+ for role in ("pm-a", "pm-b", "dev-a", "dev-b", "flow", "lead", "chief"):
202
+ worktrees[role] = chat_worktree(repo, base / role)
203
+ run_keel(worktrees[role], "chat", "role", "--set", role, env=env)
204
+ run_keel(worktrees["pm-a"], "chat", "group", "create", "team-a", "--member", "dev-a", "--member", "flow", env=env)
205
+ run_keel(worktrees["pm-b"], "chat", "group", "create", "team-b", "--member", "dev-b", "--member", "flow", env=env)
206
+ return repo, env, worktrees
207
+
208
+
209
+ def validate_patrol_scopes_declared_scenario() -> int:
210
+ """Issue #434: each role a `patrol:` list declares gets its own reminder and host task.
211
+
212
+ A broken item is reported while the others apply; `keel patrol task`
213
+ renders the calling worktree's declaration, or `--role`'s, and refuses
214
+ to guess between two.
215
+ """
216
+ label = "patrol-scopes-declared:"
217
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-scopes-") as raw:
218
+ base = Path(raw)
219
+ _repo, env, wt = patrol_scopes_scratch(base, PATROL_SCOPES + " - role: pm-c\n every: soon\n")
220
+
221
+ def context(role: str) -> dict:
222
+ return json.loads(run_keel(wt[role], "context", "--json", env=env).stdout)
223
+
224
+ a = context("pm-a")
225
+ if a.get("patrol") != {"role": "pm-a", "every": "30m"}:
226
+ report(f"{label} pm-a's context carries patrol {a.get('patrol')!r}.")
227
+ return 1
228
+ b = context("pm-b")
229
+ if b.get("patrol") != {"role": "pm-b", "every": "45m", "hostTask": "team-b-patrol"}:
230
+ report(f"{label} pm-b's context carries patrol {b.get('patrol')!r}.")
231
+ return 1
232
+ dev = context("dev-a")
233
+ if "patrol" in dev:
234
+ report(f"{label} dev-a's context carries patrol {dev.get('patrol')!r}.")
235
+ return 1
236
+ if not any("pm-c" in w and "soon" in w for w in dev.get("warnings", [])):
237
+ report(f"{label} the broken pm-c item is not reported: {dev.get('warnings')!r}")
238
+ return 1
239
+ ready = run_keel(wt["pm-b"], "shift", "ready", "next: keep patrolling team-b", env=env)
240
+ if ready.returncode != 0:
241
+ report(f"{label} keel shift ready failed in pm-b: {ready.stdout} {ready.stderr}")
242
+ return 1
243
+ resumed = run_keel(wt["pm-b"], "shift", "resume", env=env)
244
+ tail = resumed.stdout.strip().splitlines()[-1] if resumed.stdout.strip() else ""
245
+ if "team-b-patrol" not in tail:
246
+ report(f"{label} pm-b's resume does not end with its own reminder: {resumed.stdout!r}")
247
+ return 1
248
+ own = run_keel(wt["pm-b"], "patrol", "task", env=env)
249
+ if own.returncode != 0:
250
+ report(f"{label} keel patrol task in pm-b's worktree exited {own.returncode}: {own.stderr!r}")
251
+ return 1
252
+ if "task id: team-b-patrol" not in own.stdout:
253
+ report(f"{label} keel patrol task in pm-b's worktree did not render team-b-patrol: {own.stdout!r}")
254
+ return 1
255
+ guessed = run_keel(wt["dev-a"], "patrol", "task", env=env)
256
+ if guessed.returncode == 0:
257
+ report(f"{label} keel patrol task in dev-a's worktree guessed a declaration: {guessed.stdout!r}")
258
+ return 1
259
+ missing = [name for name in ("pm-a", "pm-b", "--role") if name not in guessed.stderr]
260
+ if missing:
261
+ report(f"{label} keel patrol task's refusal in dev-a's worktree does not name {missing!r}: {guessed.stderr!r}")
262
+ return 1
263
+ chosen = run_keel(wt["dev-a"], "patrol", "task", "--role", "pm-a", env=env)
264
+ for needle in ("task id: keel-patrol-pm-a", "*/30 * * * *", f"keel patrol --repo {wt['pm-a'].resolve()} --since-last --notify"):
265
+ if needle not in chosen.stdout:
266
+ report(f"{label} keel patrol task --role pm-a does not carry {needle!r}: {chosen.stdout!r} {chosen.stderr!r}")
267
+ return 1
268
+ report("patrol-scopes-declared scenario passed.")
269
+ return 0
270
+
271
+
272
+ PATROL_CHIEF = " - role: chief\n every: 60m\n"
273
+ PATROL_ISSUE_ROLES = "issue_roles:\n flow: flow\n dev: dev-b\n"
274
+
275
+
276
+ def validate_patrol_scopes_cover_scenario() -> int:
277
+ """Issue #434 D3, D5: each coordinator nudges and routes only the roles it covers.
278
+
279
+ A scoped declaration covers its group, the unscoped one the roles in no
280
+ group; flow, in both teams, is nudged once and sent one message per
281
+ issue update.
282
+ """
283
+ label = "patrol-scopes-cover:"
284
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-cover-") as raw:
285
+ base = Path(raw)
286
+ _repo, env, wt = patrol_scopes_scratch(base, PATROL_SCOPES + PATROL_CHIEF + PATROL_ISSUE_ROLES)
287
+ for role in ("dev-a", "dev-b", "flow", "lead"):
288
+ run_keel(wt["chief"], "chat", "dm", role, f"{role}: please report status", env=env)
289
+ time.sleep(1.2)
290
+ expected = (("pm-a", ["dev-a", "flow"]), ("pm-b", ["dev-b"]), ("chief", ["lead"]))
291
+ for coordinator, want in expected:
292
+ run = run_keel(wt[coordinator], "patrol", "--nudge", "--idle", "1s", env=env)
293
+ got = sorted(line.split()[1].rstrip(":") for line in run.stdout.splitlines() if line.startswith("nudged "))
294
+ if got != want:
295
+ report(f"{label} {coordinator} nudged {got}, not {want}: {run.stdout!r} {run.stderr!r}")
296
+ return 1
297
+ issues = base / "issues.json"
298
+ issues.write_text(json.dumps([{"number": 170, "title": "shared flow step", "state": "OPEN",
299
+ "labels": [{"name": "flow"}, {"name": "dev"}], "updatedAt": "2026-10-21T01:00:00Z"}]),
300
+ encoding="utf-8")
301
+ for coordinator, want in (("pm-a", {"flow": 1, "dev-b": 0}), ("pm-b", {"flow": 1, "dev-b": 1})):
302
+ run_keel(wt[coordinator], "patrol", "--issues", str(issues), env=env)
303
+ for role, count in want.items():
304
+ got = issue_notices(wt[role], env, 170)
305
+ if got != count:
306
+ report(f"{label} after {coordinator}'s patrol {role} has {got} messages about #170, not {count}.")
307
+ return 1
308
+ report("patrol-scopes-cover scenario passed.")
309
+ return 0
310
+
311
+
312
+ def validate_patrol_scopes_repository_wide_scenario() -> int:
313
+ """Issue #434 D4: a repository-wide risk reaches one coordinator.
314
+
315
+ The unscoped declaration owns the shared checkout; with every declaration
316
+ scoped, the first declared does.
317
+ """
318
+ label = "patrol-scopes-repository-wide:"
319
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-wide-") as raw:
320
+ base = Path(raw)
321
+ repo, env, wt = patrol_scopes_scratch(base, PATROL_SCOPES + PATROL_CHIEF)
322
+
323
+ def told(role: str) -> int:
324
+ group = "dm-" + "--".join(sorted(("keel-patrol", role)))
325
+ return len(chat_records_with(repo, group, "shared checkout"))
326
+
327
+ def round_trip(roles: tuple[str, ...]) -> None:
328
+ for role in roles:
329
+ run_keel(wt[role], "patrol", "--since-last", "--notify", env=env)
330
+ write_text(repo / "scratch.txt", "left behind\n")
331
+ for role in roles:
332
+ run_keel(wt[role], "patrol", "--since-last", "--notify", env=env)
333
+
334
+ round_trip(("pm-a", "pm-b", "chief"))
335
+ got = {role: told(role) for role in ("pm-a", "pm-b", "chief")}
336
+ if got != {"pm-a": 0, "pm-b": 0, "chief": 1}:
337
+ report(f"{label} with chief unscoped the checkout risk reached {got}, not chief alone.")
338
+ return 1
339
+ (repo / "scratch.txt").unlink()
340
+ for role in ("pm-a", "pm-b", "chief"):
341
+ write_authorize_config(wt[role], PATROL_SCOPES)
342
+ round_trip(("pm-a", "pm-b"))
343
+ got = {role: told(role) for role in ("pm-a", "pm-b")}
344
+ if got != {"pm-a": 1, "pm-b": 0}:
345
+ report(f"{label} with every declaration scoped the checkout risk reached {got}, not pm-a alone.")
346
+ return 1
347
+ report("patrol-scopes-repository-wide scenario passed.")
348
+ return 0
349
+
350
+
181
351
  def validate_patrol_host_task_scenario() -> int:
182
352
  """Issue #295: `patrol:` names the host task; `keel patrol task` renders it.
183
353
 
@@ -699,6 +869,52 @@ def validate_tick_runs_due_patrol_scenario() -> int:
699
869
  return 0
700
870
 
701
871
 
872
+ def validate_tick_runs_each_patrol_scenario() -> int:
873
+ """Issue #434 D7: `keel tick` runs each declared patrol when it is due.
874
+
875
+ Each role keeps its own `next_at`; moving one into the past runs that
876
+ role's patrol alone.
877
+ """
878
+ label = "tick-runs-each-patrol:"
879
+ with tempfile.TemporaryDirectory(prefix="keel-tick-each-") as raw:
880
+ base = Path(raw)
881
+ config = ("patrol:\n"
882
+ " - role: pm-a\n every: 30m\n runner: tick\n scope: group:team-a\n"
883
+ " - role: pm-b\n every: 45m\n runner: tick\n scope: group:team-b\n")
884
+ repo, env, wt = patrol_scopes_scratch(base, config)
885
+ store_root = mailbox_common_dir(repo) / "keel-chat"
886
+ state = store_root / "tick" / "state.json"
887
+
888
+ def runs(role: str) -> int:
889
+ log = store_root / "patrol" / "log" / f"{role}.log"
890
+ return len(log.read_text(encoding="utf-8").splitlines()) if log.exists() else 0
891
+
892
+ def tick() -> subprocess.CompletedProcess[str]:
893
+ return run_keel(wt["dev-a"], "tick", "--repo", str(repo), env=env)
894
+
895
+ first = tick()
896
+ if (runs("pm-a"), runs("pm-b")) != (1, 1):
897
+ report(f"{label} the first tick ran pm-a {runs('pm-a')} and pm-b {runs('pm-b')} times, not once each: {first.stdout!r} {first.stderr!r}")
898
+ return 1
899
+ second = tick()
900
+ if (runs("pm-a"), runs("pm-b")) != (1, 1):
901
+ report(f"{label} a tick before either next_at ran a patrol: pm-a {runs('pm-a')}, pm-b {runs('pm-b')}.")
902
+ return 1
903
+ for role in ("pm-a", "pm-b"):
904
+ if not any(role in line and "not due" in line for line in second.stdout.splitlines()):
905
+ report(f"{label} the skipped tick does not say {role}'s patrol is not due: {second.stdout!r}")
906
+ return 1
907
+ saved = json.loads(state.read_text(encoding="utf-8"))
908
+ saved["patrols"]["pm-b"]["next_at"] = "2000-01-01T00:00:00+00:00"
909
+ state.write_text(json.dumps(saved), encoding="utf-8")
910
+ third = tick()
911
+ if (runs("pm-a"), runs("pm-b")) != (1, 2):
912
+ report(f"{label} with only pm-b due the tick ran pm-a {runs('pm-a')} and pm-b {runs('pm-b')} times in all: {third.stdout!r}")
913
+ return 1
914
+ report("tick-runs-each-patrol scenario passed.")
915
+ return 0
916
+
917
+
702
918
  def validate_patrol_nudge_scenario() -> int:
703
919
  """Issues #307 part 1 and #313: the patrol nudges idle roles directly.
704
920
 
@@ -1070,6 +1286,78 @@ def validate_patrol_issue_routing_scenario() -> int:
1070
1286
  return 0
1071
1287
 
1072
1288
 
1289
+ def issue_label_scratch(base: Path, config: str) -> tuple[Path, dict, dict[str, Path]]:
1290
+ """`rtl` patrols; `design-iecc`, `design-rmw`, and `flow` each have a worktree."""
1291
+ rtl, _verify, env = chat_scratch_group(base)
1292
+ worktrees = {}
1293
+ for role in ("design-iecc", "design-rmw", "flow"):
1294
+ worktrees[role] = chat_worktree(rtl, base / role)
1295
+ run_keel(worktrees[role], "chat", "role", "--set", role, env=env)
1296
+ write_authorize_config(rtl, config)
1297
+ return rtl, env, worktrees
1298
+
1299
+
1300
+ def issue_notices(worktree: Path, env: dict, number: int) -> int:
1301
+ unread = chat_json(run_keel(worktree, "chat", "unread", "--json", env=env)).get("unread", [])
1302
+ return sum(1 for record in unread if f"#{number} " in record.get("text", "") or f"#{number}:" in record.get("text", ""))
1303
+
1304
+
1305
+ def validate_patrol_issue_label_sets_scenario() -> int:
1306
+ """Issue #433: a route keyed on a set of labels refines a single-label one.
1307
+
1308
+ An issue carrying `design` and `dmc_rmw` reaches the `design + dmc_rmw`
1309
+ role and not the `design` role; a route that is not nested still sends.
1310
+ """
1311
+ label = "patrol-issue-label-sets:"
1312
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-label-sets-") as raw:
1313
+ base = Path(raw)
1314
+ rtl, env, worktrees = issue_label_scratch(
1315
+ base, "issue_roles:\n design: design-iecc\n design + dmc_rmw: design-rmw\n flow: flow\n")
1316
+ issues = base / "issues.json"
1317
+ issues.write_text(json.dumps([
1318
+ {"number": 160, "title": "rmw ecc path", "state": "OPEN",
1319
+ "labels": [{"name": "design"}, {"name": "dmc_rmw"}, {"name": "flow"}], "updatedAt": "2026-10-21T01:00:00Z"},
1320
+ {"number": 161, "title": "iecc ecc path", "state": "OPEN",
1321
+ "labels": [{"name": "design"}], "updatedAt": "2026-10-21T01:00:00Z"},
1322
+ ]), encoding="utf-8")
1323
+ run = run_keel(rtl, "patrol", "--issues", str(issues), env=env)
1324
+ if run.returncode != 3:
1325
+ report(f"{label} patrol exited {run.returncode}, not 3: {run.stdout} {run.stderr}")
1326
+ return 1
1327
+ expected = (("design-rmw", 160, 1), ("flow", 160, 1), ("design-iecc", 160, 0),
1328
+ ("design-iecc", 161, 1), ("design-rmw", 161, 0))
1329
+ for role, number, want in expected:
1330
+ got = issue_notices(worktrees[role], env, number)
1331
+ if got != want:
1332
+ report(f"{label} {role} has {got} notices about #{number}, not {want}.")
1333
+ return 1
1334
+ report("patrol-issue-label-sets scenario passed.")
1335
+ return 0
1336
+
1337
+
1338
+ def validate_patrol_issue_label_set_unreadable_scenario() -> int:
1339
+ """Issue #433: a set with an empty or repeated label is reported and routes nothing."""
1340
+ label = "patrol-issue-label-set-unreadable:"
1341
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-label-set-bad-") as raw:
1342
+ base = Path(raw)
1343
+ rtl, env, worktrees = issue_label_scratch(
1344
+ base, "issue_roles:\n design + : design-rmw\n design + design: design-rmw\n")
1345
+ issues = base / "issues.json"
1346
+ issues.write_text(json.dumps([{"number": 162, "title": "ecc", "state": "OPEN",
1347
+ "labels": [{"name": "design"}], "updatedAt": "2026-10-21T01:00:00Z"}]), encoding="utf-8")
1348
+ run = run_keel(rtl, "patrol", "--issues", str(issues), env=env)
1349
+ for line in ("design + : design-rmw", "design + design: design-rmw"):
1350
+ if f"`{line}`" not in run.stdout:
1351
+ report(f"{label} the unreadable line `{line}` is not reported: {run.stdout!r}")
1352
+ return 1
1353
+ got = issue_notices(worktrees["design-rmw"], env, 162)
1354
+ if got:
1355
+ report(f"{label} design-rmw has {got} notices about #162 from unreadable lines.")
1356
+ return 1
1357
+ report("patrol-issue-label-set-unreadable scenario passed.")
1358
+ return 0
1359
+
1360
+
1073
1361
  def validate_worktree_overview_scenario() -> int:
1074
1362
  """Read every worktree through the CLI without fetching or changing chat."""
1075
1363
  label = "worktree-overview:"
@@ -918,11 +918,15 @@ function readReadOnlyRoles(repo) {
918
918
 
919
919
  // `issue_roles:` — which chat role an issue label routes to (#242), one
920
920
  // `<label>: <role>` per line, read by `keel patrol`. A label may itself hold a
921
- // colon (`role:verify`), so the role is what follows the last `: `. A line
922
- // that is not that shape is reported and routes nothing.
921
+ // colon (`role:verify`), so the role is what follows the last `: `. A key may
922
+ // name a set of labels joined by ` + ` (#433), which matches an issue carrying
923
+ // all of them; a quoted key is one label and is not split. A line that is not
924
+ // that shape, or a set with an empty or repeated label, is reported and routes
925
+ // nothing. Routes come back in declaration order, a repeated set replacing the
926
+ // earlier line.
923
927
  function readIssueRoles(repo) {
924
928
  const block = configBlockLines(repo, "issue_roles");
925
- const routes = new Map();
929
+ const routes = [];
926
930
  const unreadable = [];
927
931
  if (block === null) return { routes, unreadable };
928
932
  if (block.inline !== null) unreadable.push(block.inline);
@@ -934,29 +938,42 @@ function readIssueRoles(repo) {
934
938
  unreadable.push(text);
935
939
  continue;
936
940
  }
937
- routes.set(match[1].replace(/^["']|["']$/g, ""), match[2]);
941
+ const quoted = /^(["']).*\1$/.test(match[1]);
942
+ const labels = quoted ? [match[1].slice(1, -1)] : match[1].split(/\s+\+(?:\s+|$)/).map((label) => label.trim());
943
+ if (labels.some((label) => !label) || new Set(labels).size !== labels.length) {
944
+ unreadable.push(text);
945
+ continue;
946
+ }
947
+ const key = [...labels].sort().join("\n");
948
+ const earlier = routes.findIndex((route) => [...route.labels].sort().join("\n") === key);
949
+ if (earlier !== -1) routes.splice(earlier, 1);
950
+ routes.push({ labels, role: match[2] });
938
951
  }
939
952
  return { routes, unreadable };
940
953
  }
941
954
 
942
- // `patrol:` — which role runs `keel patrol`, and how often (#260). Keel only
943
- // reminds that role to re-create its host schedule; it schedules nothing. A
955
+ // `patrol:` — which roles run `keel patrol`, and how often (#260). Keel only
956
+ // reminds each role to re-create its host schedule; it schedules nothing. A
944
957
  // declaration missing a value, or with a malformed one, reminds nobody.
945
958
  // `host_task:` names the host scheduled task that runs it and `model:` the
946
959
  // model that task declares (#295 D3); Keel passes a model through and never
947
960
  // chooses one, and a malformed one of these is ignored by name.
948
- function readPatrolDeclaration(repo) {
949
- const block = configMap(repo, "patrol");
950
- if (!Object.keys(block).length) return { declared: false, role: null, every: null, hostTask: null, model: null, message: null };
961
+ //
962
+ // The block is one mapping, or a list of them for one coordinator per team
963
+ // (#434 D1), each item opened by `- role:` and optionally scoped with
964
+ // `scope: group:<name>` (D2). A list item that does not read, or that repeats
965
+ // a role, is reported and patrols nothing while the other items apply.
966
+ function patrolItem(block) {
951
967
  const problems = [];
952
968
  if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(block.role || "")) problems.push(`role \`${block.role || ""}\` is not a chat role name`);
953
969
  if (!/^\d+[smhd]$/.test(block.every || "")) problems.push(`every \`${block.every || ""}\` is not a duration such as 30m`);
954
- if (problems.length) {
955
- return {
956
- declared: true, role: null, every: null, hostTask: null, model: null,
957
- message: `keel/config.yaml patrol: ${problems.join("; ")}, so no session is reminded to run \`keel patrol\`.`,
958
- };
970
+ let scope = null;
971
+ if (block.scope !== undefined) {
972
+ const group = String(block.scope).match(/^group:([A-Za-z0-9][\w.-]{0,63})$/);
973
+ if (group) scope = group[1];
974
+ else problems.push(`scope \`${block.scope}\` is not group:<name>`);
959
975
  }
976
+ if (problems.length) return { problems };
960
977
  const ignored = [];
961
978
  let hostTask = null;
962
979
  let model = null;
@@ -989,8 +1006,68 @@ function readPatrolDeclaration(repo) {
989
1006
  if (block.runner === "tick") runner = "tick";
990
1007
  else ignored.push(`runner \`${block.runner}\` is not tick`);
991
1008
  }
992
- const message = ignored.length ? `keel/config.yaml patrol: ${ignored.join("; ")}, so it is ignored.` : null;
993
- return { declared: true, role: block.role, every: block.every, hostTask, model, message, cadence, runner };
1009
+ return { declaration: { declared: true, role: block.role, every: block.every, hostTask, model, cadence, runner, scope }, ignored };
1010
+ }
1011
+
1012
+ function readPatrolDeclarations(repo) {
1013
+ const block = configBlockLines(repo, "patrol");
1014
+ const empty = { declared: false, declarations: [], messages: [] };
1015
+ if (block === null) return empty;
1016
+ const declarations = [];
1017
+ const messages = [];
1018
+ if (!block.lines.some((line) => /^\s*-\s/.test(line))) {
1019
+ const map = configMap(repo, "patrol");
1020
+ if (!Object.keys(map).length) return empty;
1021
+ const item = patrolItem(map);
1022
+ if (item.problems) {
1023
+ messages.push(`keel/config.yaml patrol: ${item.problems.join("; ")}, so no session is reminded to run \`keel patrol\`.`);
1024
+ } else {
1025
+ declarations.push(item.declaration);
1026
+ if (item.ignored.length) messages.push(`keel/config.yaml patrol: ${item.ignored.join("; ")}, so it is ignored.`);
1027
+ }
1028
+ return { declared: true, declarations, messages };
1029
+ }
1030
+ const items = [];
1031
+ const stray = [];
1032
+ for (const line of block.lines) {
1033
+ const text = line.replace(/\s+#.*$/, "");
1034
+ if (!text.trim()) continue;
1035
+ const opened = text.match(/^\s*-\s+(\w+)\s*:\s*(\S+)\s*$/);
1036
+ const entry = text.match(/^\s+(\w+)\s*:\s*(\S+)\s*$/);
1037
+ if (opened) items.push({ [opened[1]]: opened[2] });
1038
+ else if (entry && items.length) items[items.length - 1][entry[1]] = entry[2];
1039
+ else stray.push(text.trim());
1040
+ }
1041
+ if (stray.length) messages.push(`keel/config.yaml patrol: ${stray.map((line) => `\`${line}\``).join(", ")} is not part of a \`- role:\` item, so it is ignored.`);
1042
+ items.forEach((map, index) => {
1043
+ const name = `keel/config.yaml patrol item ${index + 1}${map.role ? ` (\`${map.role}\`)` : ""}`;
1044
+ const item = patrolItem(map);
1045
+ if (item.problems) {
1046
+ messages.push(`${name}: ${item.problems.join("; ")}, so it patrols nothing.`);
1047
+ return;
1048
+ }
1049
+ if (declarations.some((declaration) => declaration.role === item.declaration.role)) {
1050
+ messages.push(`${name}: role ${item.declaration.role} is declared already, so this item patrols nothing.`);
1051
+ return;
1052
+ }
1053
+ declarations.push(item.declaration);
1054
+ if (item.ignored.length) messages.push(`${name}: ${item.ignored.join("; ")}, so it is ignored.`);
1055
+ });
1056
+ return { declared: true, declarations, messages };
1057
+ }
1058
+
1059
+ // One role's declaration, `{ role }` naming whose; without it the first, which
1060
+ // is the single mapping's. `message` carries every problem in the block, so a
1061
+ // caller that reports it reports the whole declaration.
1062
+ function readPatrolDeclaration(repo, options = {}) {
1063
+ const all = readPatrolDeclarations(repo);
1064
+ const message = all.messages.length ? all.messages.join(" ") : null;
1065
+ if (!all.declared) return { declared: false, role: null, every: null, hostTask: null, model: null, scope: null, message: null };
1066
+ const found = "role" in options
1067
+ ? all.declarations.find((declaration) => declaration.role === options.role)
1068
+ : all.declarations[0];
1069
+ if (!found) return { declared: true, role: null, every: null, hostTask: null, model: null, scope: null, message };
1070
+ return { ...found, message };
994
1071
  }
995
1072
 
996
1073
  // `shift: permission_mode:` for the session a CLI hand-off starts (#357 D5).
@@ -1035,6 +1112,7 @@ module.exports = {
1035
1112
  readOwnerLanguage,
1036
1113
  ownerLanguageRule,
1037
1114
  readPatrolDeclaration,
1115
+ readPatrolDeclarations,
1038
1116
  readShiftDeclaration,
1039
1117
  durationSeconds,
1040
1118
  patrolReminder,
@@ -877,10 +877,11 @@ function resolveContext(repo, options) {
877
877
  const twins = chatWhere ? require("./chat/notice").twinWarning(chatWhere, context.role) : null;
878
878
  if (twins) context.warnings.push(twins);
879
879
  }
880
- // The patrolling role is reminded to re-arm its schedule (#260).
881
- const patrol = readPatrolDeclaration(repo);
880
+ // The patrolling role is reminded to re-arm its schedule (#260), each
881
+ // declared role of its own declaration (#434 D6).
882
+ const patrol = readPatrolDeclaration(repo, { role: context.role || null });
882
883
  if (patrol.message) context.warnings.push(patrol.message);
883
- if (patrol.role && context.role === patrol.role) {
884
+ if (patrol.role) {
884
885
  context.patrol = { role: patrol.role, every: patrol.every };
885
886
  if (patrol.hostTask) context.patrol.hostTask = patrol.hostTask;
886
887
  if (patrol.runner) context.patrol.runner = patrol.runner;
@@ -12,7 +12,7 @@ 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>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>]\n keel patrol task [--json] [--repo <path>] print the host scheduled task for `patrol:`";
15
+ const USAGE = "keel patrol [--issues <file>] [--idle <90s|15m|2h|3d>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>]\n keel patrol task [--role <role>] [--json] [--repo <path>] print the host scheduled task for `patrol:`";
16
16
  const NOTIFY_SENDER = "keel-patrol";
17
17
  // 2 asks the coordinator to act — a risk, or a wait of its own now met — and
18
18
  // 3 says patrol recorded or delivered something only other roles need: a
@@ -63,8 +63,34 @@ function conditionHolds(where, condition, issues) {
63
63
  return { unchecked: true };
64
64
  }
65
65
 
66
+ // What a patrolling role covers (#434 D3, D4, D9, D10): a scoped declaration
67
+ // its group's members, the unscoped one the roles in no declared scope, and a
68
+ // role `patrol:` does not declare every role. The repository-wide items belong
69
+ // to the unscoped declaration, or to the first declared when all are scoped.
70
+ function coverageOf(where, role) {
71
+ const { declarations } = require("./config").readPatrolDeclarations(where.worktree);
72
+ const own = declarations.find((declaration) => declaration.role === role);
73
+ if (!own) return { covers: (name) => name !== role, repositoryWide: true, warnings: [] };
74
+ const membersOf = (group) => store.groupState(store.readLog(where, group)).members;
75
+ const warnings = [];
76
+ let inside;
77
+ if (own.scope) {
78
+ const members = membersOf(own.scope);
79
+ if (!members.size) warnings.push(`patrol scope group:${own.scope} has no members, so ${role} covers no role.`);
80
+ inside = (name) => members.has(name);
81
+ } else {
82
+ const scoped = new Set(declarations.filter((declaration) => declaration.scope).flatMap((declaration) => [...membersOf(declaration.scope)]));
83
+ inside = (name) => !scoped.has(name);
84
+ }
85
+ const owner = declarations.find((declaration) => !declaration.scope) || declarations[0];
86
+ return { covers: (name) => name !== role && inside(name), repositoryWide: owner.role === role, warnings };
87
+ }
88
+
66
89
  function patrol(where, role, options) {
67
90
  const result = { role, notices: [], held: [], unchecked: [], roles: [], warnings: [] };
91
+ if (!options.coverage) options = { ...options, coverage: coverageOf(where, role) };
92
+ const { coverage } = options;
93
+ result.warnings.push(...coverage.warnings);
68
94
  for (const waitRecord of store.openWaits(where, role)) {
69
95
  const check = conditionHolds(where, waitRecord.condition, options.issues);
70
96
  if (check.unchecked) {
@@ -83,10 +109,11 @@ function patrol(where, role, options) {
83
109
  const routed = routeIssues(where, role, options);
84
110
  result.notices.push(...routed.notices);
85
111
  result.warnings.push(...routed.warnings);
86
- // D6: presence is reported, never acted on.
87
- const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))].sort();
112
+ // D6: presence is reported, never acted on, for the patroller and the roles it covers.
113
+ const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))]
114
+ .filter((name) => name === role || coverage.covers(name)).sort();
88
115
  // Bindings that drifted from where sessions run (#301 D2): reported, never acted on.
89
- result.drift = require("./chat/drift").driftLines(require("./chat/drift").roleDrift(where));
116
+ result.drift = coverage.repositoryWide ? require("./chat/drift").driftLines(require("./chat/drift").roleDrift(where)) : [];
90
117
  const threshold = parseSince(options.idle);
91
118
  for (const name of roles) {
92
119
  const presence = notice.presenceOf(where, name);
@@ -103,23 +130,33 @@ function patrol(where, role, options) {
103
130
  return result;
104
131
  }
105
132
 
106
- // D5 (#242): each role a label of an issue maps to gets one direct message
107
- // per `updatedAt`, deduped by its ref against the direct group's records.
133
+ // D5 (#242): each role a matching route names gets one direct message per
134
+ // `updatedAt`, deduped by its ref against the direct group's records. A route
135
+ // whose labels are a strict subset of another matching route's is refined by
136
+ // it and sends nothing (#433).
108
137
  function routeIssues(where, role, options) {
109
138
  const { routes, unreadable } = require("./config").readIssueRoles(where.worktree);
110
139
  const warnings = unreadable.map(
111
- (line) => `keel/config.yaml issue_roles line \`${line}\` is not \`<label>: <role>\`; it routes nothing.`
140
+ (line) => `keel/config.yaml issue_roles line \`${line}\` is not \`<label>: <role>\` or \`<label> + <label>: <role>\`; it routes nothing.`
112
141
  );
113
142
  const notices = [];
114
- if (!options.issues || !routes.size) return { notices, warnings };
143
+ if (!options.issues || !routes.length) return { notices, warnings };
144
+ // A role covered by two coordinators hears of an update once (#434 D5).
145
+ const patrollers = [...new Set([role, ...require("./config").readPatrolDeclarations(where.worktree).declarations.map((d) => d.role)])];
146
+ const covers = options.coverage ? options.coverage.covers : () => true;
115
147
  for (const issue of options.issues) {
116
- const labels = (issue.labels || []).map((entry) => (typeof entry === "string" ? entry : entry && entry.name)).filter(Boolean);
117
- const targets = [...new Set(labels.map((name) => routes.get(name)).filter(Boolean))];
148
+ const labels = new Set((issue.labels || []).map((entry) => (typeof entry === "string" ? entry : entry && entry.name)).filter(Boolean));
149
+ const matching = routes.filter((route) => route.labels.every((name) => labels.has(name)));
150
+ const refined = (route) => matching.some(
151
+ (other) => other.labels.length > route.labels.length && route.labels.every((name) => other.labels.includes(name))
152
+ );
153
+ const targets = [...new Set(matching.filter((route) => !refined(route)).map((route) => route.role))];
118
154
  for (const target of targets) {
119
- if (target === role) continue;
155
+ if (target === role || !covers(target)) continue;
120
156
  const ref = `issue:#${issue.number}@${issue.updatedAt || "unknown"}`;
121
- const group = store.directName(role, target);
122
- if (store.readLog(where, group).some((record) => (record.refs || []).includes(ref))) continue;
157
+ const sent = patrollers.filter((patroller) => patroller !== target)
158
+ .some((patroller) => store.readLog(where, store.directName(patroller, target)).some((record) => (record.refs || []).includes(ref)));
159
+ if (sent) continue;
123
160
  const when = issue.updatedAt ? ` at ${issue.updatedAt}` : "";
124
161
  const title = issue.title ? `: ${issue.title}` : "";
125
162
  const text = `Issue #${issue.number} changed${when}${title} (its label routes it to ${target}).`;
@@ -146,20 +183,23 @@ function primaryWorktree(where) {
146
183
  function currentSnapshot(where, role, result, options) {
147
184
  const shift = require("./shift");
148
185
  const entries = {};
149
- for (const row of shift.shiftStatus(where)) entries[`shift ${row.role}`] = shift.describe(row);
150
- const base = require("./worktrees").defaultBranch(where.worktree);
186
+ const coverage = options.coverage || { covers: () => true, repositoryWide: true };
187
+ for (const row of shift.shiftStatus(where)) {
188
+ if (row.role === role || coverage.covers(row.role)) entries[`shift ${row.role}`] = shift.describe(row);
189
+ }
190
+ const base = coverage.repositoryWide ? require("./worktrees").defaultBranch(where.worktree) : null;
151
191
  if (base) {
152
192
  const ref = `refs/remotes/origin/${base.replace(/^origin\//, "")}`;
153
193
  entries[`remote ${ref.replace(/^refs\/remotes\//, "")}`] = git(where.worktree, ["rev-parse", "--verify", "--quiet", ref]) || "none";
154
194
  }
155
- const primary = primaryWorktree(where);
195
+ const primary = coverage.repositoryWide ? primaryWorktree(where) : null;
156
196
  if (primary) {
157
197
  const status = git(primary, ["status", "--porcelain"]);
158
198
  if (status !== null) entries[`checkout ${primary}`] = `${status ? status.split("\n").length : 0} uncommitted paths`;
159
199
  }
160
200
  for (const line of result.drift) entries[line.key] = line.text;
161
201
  // Free disk as the host measured it (#307 part 3 D1).
162
- if (options.diskFreeGb !== null) entries.disk = options.diskFreeGb < options.diskMinGb ? "low" : "ok";
202
+ if (options.diskFreeGb !== null && coverage.repositoryWide) entries.disk = options.diskFreeGb < options.diskMinGb ? "low" : "ok";
163
203
  for (const row of result.roles) {
164
204
  entries[`role ${row.role}`] = `${row.parked ? "parked" : row.idle ? "idle" : "active"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`;
165
205
  }
@@ -246,8 +286,9 @@ function nudgeRoles(where, patroller, options) {
246
286
  const idleBefore = parseSince(options.idle);
247
287
  const sent = [];
248
288
  const escalations = [];
289
+ const covers = options.coverage ? options.coverage.covers : (role) => role !== patroller;
249
290
  const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))]
250
- .filter((role) => role !== patroller).sort();
291
+ .filter((role) => role !== patroller && covers(role)).sort();
251
292
  const closures = closedTodos(where);
252
293
  for (const role of roles) {
253
294
  // A role parked on purpose is left alone, its state kept (#316 D4).
@@ -388,12 +429,28 @@ function shellPath(file) {
388
429
  return /[\s"'$`\\]/.test(file) ? JSON.stringify(file) : file;
389
430
  }
390
431
 
391
- function hostTask(where) {
392
- const config = require("./config");
393
- const declaration = config.readPatrolDeclaration(where.worktree);
394
- if (!declaration.role) {
395
- throw new PatrolError(declaration.message || "keel/config.yaml declares no `patrol:` with role and every, so there is no patrol task to render.");
432
+ // Whose task (#434 D6): `--role`'s, else the calling worktree's role's, else
433
+ // the only declaration; between several it refuses rather than guess.
434
+ function chooseDeclaration(where, requested) {
435
+ const all = require("./config").readPatrolDeclarations(where.worktree);
436
+ const { declarations } = all;
437
+ if (!declarations.length) {
438
+ throw new PatrolError(all.messages.join(" ") || "keel/config.yaml declares no `patrol:` with role and every, so there is no patrol task to render.");
439
+ }
440
+ if (requested) {
441
+ const named = declarations.find((declaration) => declaration.role === requested);
442
+ if (!named) throw new PatrolError(`keel/config.yaml patrol: declares no role ${requested}; it declares ${declarations.map((d) => d.role).join(", ")}.`);
443
+ return named;
396
444
  }
445
+ const own = declarations.find((declaration) => declaration.role === store.currentRole(where));
446
+ if (own) return own;
447
+ if (declarations.length === 1) return declarations[0];
448
+ throw new PatrolError(`keel/config.yaml patrol: declares ${declarations.map((d) => d.role).join(", ")}, and this worktree's role is none of them; `
449
+ + "name one with `--role <role>`.");
450
+ }
451
+
452
+ function hostTask(where, requested = null) {
453
+ const declaration = chooseDeclaration(where, requested);
397
454
  const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
398
455
  .filter(([, role]) => role === declaration.role).map(([worktree]) => worktree).sort();
399
456
  if (!bound.length) {
@@ -444,9 +501,11 @@ function runPatrol(argv) {
444
501
  if (argv[0] === "task") {
445
502
  const json = argv.includes("--json");
446
503
  const at = argv.indexOf("--repo");
504
+ const roleAt = argv.indexOf("--role");
447
505
  try {
506
+ if (roleAt >= 0 && !argv[roleAt + 1]) throw new PatrolError("--role needs a role name.");
448
507
  const where = store.requireLocation(path.resolve(at >= 0 ? argv[at + 1] || "" : process.cwd()));
449
- const task = hostTask(where);
508
+ const task = hostTask(where, roleAt >= 0 ? argv[roleAt + 1] : null);
450
509
  process.stdout.write(`${json ? JSON.stringify(task, null, 2) : renderTask(task)}\n`);
451
510
  return EXIT_QUIET;
452
511
  } catch (error) {
@@ -493,12 +552,13 @@ function runPatrol(argv) {
493
552
  options.issues = readIssues(options.issues);
494
553
  const where = store.requireLocation(path.resolve(options.repo));
495
554
  const role = store.requireRole(where);
555
+ options.coverage = coverageOf(where, role);
496
556
  const result = patrol(where, role, options);
497
557
  result.risks = [];
498
- const quota = quotaRisk(where, options);
558
+ const quota = options.coverage.repositoryWide ? quotaRisk(where, options) : null;
499
559
  if (quota) result.risks.push(quota);
500
- // A CLI hand-off that failed or hangs (#357 D4).
501
- result.risks.push(...require("./shift").handOffRisks(where));
560
+ // A CLI hand-off that failed or hangs (#357 D4), of the roles this patrol covers.
561
+ result.risks.push(...require("./shift").handOffRisks(where, Date.now(), (name) => name === role || options.coverage.covers(name)));
502
562
  // Near the limit nudges stop, since each wakes a large session (D3).
503
563
  const quiet = options.quota !== null && options.quota >= options.quotaQuietAt;
504
564
  if (options.nudge && quiet) result.paused = `nudges paused: quota at ${options.quota}%`;
@@ -538,7 +598,7 @@ function runPatrol(argv) {
538
598
  // is the caller's; this only recommends.
539
599
  function recommendNext(where, role, result, options, now = new Date()) {
540
600
  const { readPatrolDeclaration, durationSeconds } = require("./config");
541
- const declaration = readPatrolDeclaration(where.worktree);
601
+ const declaration = readPatrolDeclaration(where.worktree, { role });
542
602
  const cadence = declaration.cadence;
543
603
  if (!cadence || !cadence.adaptive) {
544
604
  const every = durationSeconds(declaration.every) || 3600;
package/src/core/shift.js CHANGED
@@ -845,8 +845,9 @@ function retryNote(entry) {
845
845
  }
846
846
 
847
847
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
848
- function handOffRisks(where, now = Date.now()) {
849
- return handOffs(where).filter((entry) => entry.state === "failed"
848
+ // `covers` limits them to the roles a scoped patrol coordinates (#434 D5).
849
+ function handOffRisks(where, now = Date.now(), covers = () => true) {
850
+ return handOffs(where).filter((entry) => covers(entry.role)).filter((entry) => entry.state === "failed"
850
851
  || (entry.state === "pending" && now - Date.parse(entry.requested_at) > 15 * 60 * 1000))
851
852
  .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}; ${retryNote(entry)}` : ` since ${entry.requested_at}`}`
852
853
  + `${entry.waiting_on ? ` (${entry.waiting_on})` : ""}; see \`keel shift status\``);
@@ -1489,8 +1490,8 @@ function runShift(argv) {
1489
1490
  }
1490
1491
  // A new shift of the patrolling role re-creates its schedule (#260).
1491
1492
  const { readPatrolDeclaration, patrolReminder } = require("./config");
1492
- const patrol = readPatrolDeclaration(where.worktree);
1493
- const remind = patrol.role && result.role === patrol.role;
1493
+ const patrol = readPatrolDeclaration(where.worktree, { role: result.role || null });
1494
+ const remind = Boolean(patrol.role);
1494
1495
  if (remind) result.patrol = { role: patrol.role, every: patrol.every, ...(patrol.hostTask ? { hostTask: patrol.hostTask } : {}), ...(patrol.runner ? { runner: patrol.runner } : {}) };
1495
1496
  // A new coordinator learns whom its previous shift left unstarted (#289 D2).
1496
1497
  const waiting = (result.waiting || []).map((w) => w.role);
package/src/core/tick.js CHANGED
@@ -27,19 +27,27 @@ function readState(where) {
27
27
  return state && typeof state === "object" ? state : {};
28
28
  }
29
29
 
30
- // The patrol runs in the worktree bound to its role, whichever worktree called.
31
- function patrolWorktree(where) {
32
- const { readPatrolDeclaration } = require("./config");
33
- const declaration = readPatrolDeclaration(where.worktree);
34
- if (!declaration.role) {
35
- return { declaration, worktree: null, why: declaration.message || "keel/config.yaml declares no `patrol:` with role and every." };
36
- }
37
- const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
38
- .filter(([, role]) => role === declaration.role).map(([worktree]) => worktree).sort();
39
- if (!bound.length) {
40
- return { declaration, worktree: null, why: `No worktree is bound to role ${declaration.role}; bind one with \`keel chat role --set ${declaration.role}\` there first.` };
30
+ // Each declared patrol runs in the worktree bound to its role, whichever
31
+ // worktree called (#434 D7); a list's first role is the one a bare
32
+ // `patrolWorktree` answers for.
33
+ function patrolWorktrees(where) {
34
+ const all = require("./config").readPatrolDeclarations(where.worktree);
35
+ if (!all.declarations.length) {
36
+ return [{ declaration: null, worktree: null, why: all.messages.join(" ") || "keel/config.yaml declares no `patrol:` with role and every." }];
41
37
  }
42
- return { declaration, worktree: bound[0], why: null };
38
+ const roles = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")));
39
+ return all.declarations.map((declaration) => {
40
+ const bound = roles.filter(([, role]) => role === declaration.role).map(([worktree]) => worktree).sort();
41
+ if (!bound.length) {
42
+ return { declaration, worktree: null, why: `No worktree is bound to role ${declaration.role}; bind one with \`keel chat role --set ${declaration.role}\` there first.` };
43
+ }
44
+ return { declaration, worktree: bound[0], why: null };
45
+ });
46
+ }
47
+
48
+ function patrolWorktree(where) {
49
+ const all = patrolWorktrees(where);
50
+ return all.find((found) => found.worktree) || all[0];
43
51
  }
44
52
 
45
53
  // Roles whose CLI session ended while a record addressed to them waits are
@@ -76,50 +84,55 @@ function tick(where, now = new Date()) {
76
84
  if (result.woken.length) {
77
85
  store.writeJsonAtomic(where, stateFile(where), { ...readState(where), woken: wakeState.woken, wake_attempts: wakeState.wake_attempts });
78
86
  }
79
- const found = patrolWorktree(where);
80
- if (!found.worktree) {
81
- result.patrol = { ran: false, why: found.why };
82
- return result;
83
- }
87
+ // A single mapping keeps its due time at `patrol`; a list keeps each role's
88
+ // under `patrols`, the first falling back to `patrol` when it was a mapping.
89
+ const all = patrolWorktrees(where);
90
+ const listed = all.length > 1;
84
91
  const state = readState(where);
85
- const due = state.patrol && state.patrol.next_at ? Date.parse(state.patrol.next_at) : NaN;
86
- if (!Number.isNaN(due) && due > now.getTime()) {
87
- result.patrol = { ran: false, why: `patrol not due until ${state.patrol.next_at}`, next_at: state.patrol.next_at };
88
- return result;
89
- }
90
- // The host task this replaces fetched first (F1); a failed fetch is reported
91
- // and the patrol still runs on the refs it has.
92
- const fetched = spawnSync("git", ["-C", found.worktree, "fetch", "-q", "origin"], { encoding: "utf8" });
93
- const fetchError = fetched.status === 0 ? null : String(fetched.stderr || fetched.error || "fetch failed").trim();
94
- const ran = spawnSync(process.execPath, [KEEL, "patrol", "--repo", found.worktree, "--since-last", "--notify", "--json"], {
95
- cwd: found.worktree, encoding: "utf8",
92
+ result.patrols = all.map((found) => {
93
+ if (!found.worktree) return { role: found.declaration ? found.declaration.role : null, ran: false, why: found.why };
94
+ const role = found.declaration.role;
95
+ const own = listed ? ((state.patrols || {})[role] || (role === all[0].declaration.role ? state.patrol : null)) : state.patrol;
96
+ const due = own && own.next_at ? Date.parse(own.next_at) : NaN;
97
+ if (!Number.isNaN(due) && due > now.getTime()) {
98
+ return { role, ran: false, why: `${listed ? `${role}'s ` : ""}patrol not due until ${own.next_at}`, next_at: own.next_at };
99
+ }
100
+ // The host task this replaces fetched first (F1); a failed fetch is reported
101
+ // and the patrol still runs on the refs it has.
102
+ const fetched = spawnSync("git", ["-C", found.worktree, "fetch", "-q", "origin"], { encoding: "utf8" });
103
+ const fetchError = fetched.status === 0 ? null : String(fetched.stderr || fetched.error || "fetch failed").trim();
104
+ const ran = spawnSync(process.execPath, [KEEL, "patrol", "--repo", found.worktree, "--since-last", "--notify", "--json"], {
105
+ cwd: found.worktree, encoding: "utf8",
106
+ });
107
+ let payload = {};
108
+ try {
109
+ payload = JSON.parse(ran.stdout);
110
+ } catch {
111
+ payload = {};
112
+ }
113
+ const next = payload.next_at || null;
114
+ const record = { next_at: next, last_run: store.isoLocal(now), last_exit: ran.status };
115
+ if (listed) state.patrols = { ...(state.patrols || {}), [role]: record };
116
+ else state.patrol = record;
117
+ store.writeJsonAtomic(where, stateFile(where), state);
118
+ return {
119
+ role, listed, ran: true, exit: ran.status, next_at: next, rule: payload.next_rule || null,
120
+ fetchError, error: ran.status === 1 ? String(ran.stderr || "").trim() : null,
121
+ };
96
122
  });
97
- let payload = {};
98
- try {
99
- payload = JSON.parse(ran.stdout);
100
- } catch {
101
- payload = {};
102
- }
103
- const next = payload.next_at || null;
104
- state.patrol = { next_at: next, last_run: store.isoLocal(now), last_exit: ran.status };
105
- store.writeJsonAtomic(where, stateFile(where), state);
106
- result.patrol = {
107
- ran: true, exit: ran.status, next_at: next, rule: payload.next_rule || null,
108
- fetchError, error: ran.status === 1 ? String(ran.stderr || "").trim() : null,
109
- };
123
+ result.patrol = result.patrols[0];
110
124
  return result;
111
125
  }
112
126
 
113
127
  function render(result) {
114
128
  const woke = (result.woken || []).map((w) => `keel tick: ${w.ok ? "resumed" : "could not resume"} ${w.role}'s CLI session ${w.session} for ${w.record}`);
115
129
  const handed = (result.handedOver || []).map((h) => `keel tick: ${h.role}'s hand-off ${h.state}${h.new_session ? ` as session ${h.new_session}` : ""}${h.error ? `: ${h.error}` : ""}`);
116
- return [...handed, ...woke, renderPatrol(result)].join("\n");
130
+ return [...handed, ...woke, ...(result.patrols || [result.patrol]).map(renderPatrol)].join("\n");
117
131
  }
118
132
 
119
- function renderPatrol(result) {
120
- const p = result.patrol;
133
+ function renderPatrol(p) {
121
134
  if (!p.ran) return `keel tick: ${p.why}`;
122
- const lines = [`keel tick: ran the patrol (exit ${p.exit})${p.next_at ? `; next ${p.next_at} (${p.rule})` : ""}`];
135
+ const lines = [`keel tick: ran ${p.listed ? `${p.role}'s` : "the"} patrol (exit ${p.exit})${p.next_at ? `; next ${p.next_at} (${p.rule})` : ""}`];
123
136
  if (p.fetchError) lines.push(`fetch failed: ${p.fetchError}`);
124
137
  if (p.error) lines.push(`patrol failed: ${p.error}`);
125
138
  return lines.join("\n");