@christang/keel 5.192.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.192.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
@@ -928,6 +928,24 @@ patrol:
928
928
  every: 30m
929
929
  ```
930
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
+
931
949
  Better, run the patrol outside the coordinator's session altogether, as a host scheduled task on a
932
950
  small model, which survives the coordinator clearing itself (#295). Add `host_task: <id>` (and, if
933
951
  you like, `model: <id>`, which Keel passes through and never chooses) and run `keel patrol task`: it
package/README.zh-CN.md CHANGED
@@ -773,6 +773,22 @@ patrol:
773
773
  every: 30m
774
774
  ```
775
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
+
776
792
  更好的做法是把巡查完全放到协调者的会话之外,作为一个运行在小模型上的宿主计划任务,这样它能熬过协调者清空自己
777
793
  (#295)。加上 `host_task: <id>`(愿意的话再加 `model: <id>`,Keel 只是原样传递,从不替你选择),然后运行
778
794
  `keel patrol task`:它打印出这个任务——id、由 `every:` 生成的 cron、模型,以及一份按路径针对协调者 worktree 运行
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.192.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.192.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.192.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.192.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.192.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.192.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.192.0"
38
+ PACKAGE_VERSION = "5.193.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.192.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,6 +463,9 @@ 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),
467
471
  ("patrol-issue-label-sets", shift.validate_patrol_issue_label_sets_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
 
@@ -952,24 +952,28 @@ function readIssueRoles(repo) {
952
952
  return { routes, unreadable };
953
953
  }
954
954
 
955
- // `patrol:` — which role runs `keel patrol`, and how often (#260). Keel only
956
- // 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
957
957
  // declaration missing a value, or with a malformed one, reminds nobody.
958
958
  // `host_task:` names the host scheduled task that runs it and `model:` the
959
959
  // model that task declares (#295 D3); Keel passes a model through and never
960
960
  // chooses one, and a malformed one of these is ignored by name.
961
- function readPatrolDeclaration(repo) {
962
- const block = configMap(repo, "patrol");
963
- 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) {
964
967
  const problems = [];
965
968
  if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(block.role || "")) problems.push(`role \`${block.role || ""}\` is not a chat role name`);
966
969
  if (!/^\d+[smhd]$/.test(block.every || "")) problems.push(`every \`${block.every || ""}\` is not a duration such as 30m`);
967
- if (problems.length) {
968
- return {
969
- declared: true, role: null, every: null, hostTask: null, model: null,
970
- message: `keel/config.yaml patrol: ${problems.join("; ")}, so no session is reminded to run \`keel patrol\`.`,
971
- };
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>`);
972
975
  }
976
+ if (problems.length) return { problems };
973
977
  const ignored = [];
974
978
  let hostTask = null;
975
979
  let model = null;
@@ -1002,8 +1006,68 @@ function readPatrolDeclaration(repo) {
1002
1006
  if (block.runner === "tick") runner = "tick";
1003
1007
  else ignored.push(`runner \`${block.runner}\` is not tick`);
1004
1008
  }
1005
- const message = ignored.length ? `keel/config.yaml patrol: ${ignored.join("; ")}, so it is ignored.` : null;
1006
- 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 };
1007
1071
  }
1008
1072
 
1009
1073
  // `shift: permission_mode:` for the session a CLI hand-off starts (#357 D5).
@@ -1048,6 +1112,7 @@ module.exports = {
1048
1112
  readOwnerLanguage,
1049
1113
  ownerLanguageRule,
1050
1114
  readPatrolDeclaration,
1115
+ readPatrolDeclarations,
1051
1116
  readShiftDeclaration,
1052
1117
  durationSeconds,
1053
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);
@@ -114,6 +141,9 @@ function routeIssues(where, role, options) {
114
141
  );
115
142
  const notices = [];
116
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;
117
147
  for (const issue of options.issues) {
118
148
  const labels = new Set((issue.labels || []).map((entry) => (typeof entry === "string" ? entry : entry && entry.name)).filter(Boolean));
119
149
  const matching = routes.filter((route) => route.labels.every((name) => labels.has(name)));
@@ -122,10 +152,11 @@ function routeIssues(where, role, options) {
122
152
  );
123
153
  const targets = [...new Set(matching.filter((route) => !refined(route)).map((route) => route.role))];
124
154
  for (const target of targets) {
125
- if (target === role) continue;
155
+ if (target === role || !covers(target)) continue;
126
156
  const ref = `issue:#${issue.number}@${issue.updatedAt || "unknown"}`;
127
- const group = store.directName(role, target);
128
- 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;
129
160
  const when = issue.updatedAt ? ` at ${issue.updatedAt}` : "";
130
161
  const title = issue.title ? `: ${issue.title}` : "";
131
162
  const text = `Issue #${issue.number} changed${when}${title} (its label routes it to ${target}).`;
@@ -152,20 +183,23 @@ function primaryWorktree(where) {
152
183
  function currentSnapshot(where, role, result, options) {
153
184
  const shift = require("./shift");
154
185
  const entries = {};
155
- for (const row of shift.shiftStatus(where)) entries[`shift ${row.role}`] = shift.describe(row);
156
- 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;
157
191
  if (base) {
158
192
  const ref = `refs/remotes/origin/${base.replace(/^origin\//, "")}`;
159
193
  entries[`remote ${ref.replace(/^refs\/remotes\//, "")}`] = git(where.worktree, ["rev-parse", "--verify", "--quiet", ref]) || "none";
160
194
  }
161
- const primary = primaryWorktree(where);
195
+ const primary = coverage.repositoryWide ? primaryWorktree(where) : null;
162
196
  if (primary) {
163
197
  const status = git(primary, ["status", "--porcelain"]);
164
198
  if (status !== null) entries[`checkout ${primary}`] = `${status ? status.split("\n").length : 0} uncommitted paths`;
165
199
  }
166
200
  for (const line of result.drift) entries[line.key] = line.text;
167
201
  // Free disk as the host measured it (#307 part 3 D1).
168
- 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";
169
203
  for (const row of result.roles) {
170
204
  entries[`role ${row.role}`] = `${row.parked ? "parked" : row.idle ? "idle" : "active"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`;
171
205
  }
@@ -252,8 +286,9 @@ function nudgeRoles(where, patroller, options) {
252
286
  const idleBefore = parseSince(options.idle);
253
287
  const sent = [];
254
288
  const escalations = [];
289
+ const covers = options.coverage ? options.coverage.covers : (role) => role !== patroller;
255
290
  const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))]
256
- .filter((role) => role !== patroller).sort();
291
+ .filter((role) => role !== patroller && covers(role)).sort();
257
292
  const closures = closedTodos(where);
258
293
  for (const role of roles) {
259
294
  // A role parked on purpose is left alone, its state kept (#316 D4).
@@ -394,12 +429,28 @@ function shellPath(file) {
394
429
  return /[\s"'$`\\]/.test(file) ? JSON.stringify(file) : file;
395
430
  }
396
431
 
397
- function hostTask(where) {
398
- const config = require("./config");
399
- const declaration = config.readPatrolDeclaration(where.worktree);
400
- if (!declaration.role) {
401
- 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;
402
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);
403
454
  const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
404
455
  .filter(([, role]) => role === declaration.role).map(([worktree]) => worktree).sort();
405
456
  if (!bound.length) {
@@ -450,9 +501,11 @@ function runPatrol(argv) {
450
501
  if (argv[0] === "task") {
451
502
  const json = argv.includes("--json");
452
503
  const at = argv.indexOf("--repo");
504
+ const roleAt = argv.indexOf("--role");
453
505
  try {
506
+ if (roleAt >= 0 && !argv[roleAt + 1]) throw new PatrolError("--role needs a role name.");
454
507
  const where = store.requireLocation(path.resolve(at >= 0 ? argv[at + 1] || "" : process.cwd()));
455
- const task = hostTask(where);
508
+ const task = hostTask(where, roleAt >= 0 ? argv[roleAt + 1] : null);
456
509
  process.stdout.write(`${json ? JSON.stringify(task, null, 2) : renderTask(task)}\n`);
457
510
  return EXIT_QUIET;
458
511
  } catch (error) {
@@ -499,12 +552,13 @@ function runPatrol(argv) {
499
552
  options.issues = readIssues(options.issues);
500
553
  const where = store.requireLocation(path.resolve(options.repo));
501
554
  const role = store.requireRole(where);
555
+ options.coverage = coverageOf(where, role);
502
556
  const result = patrol(where, role, options);
503
557
  result.risks = [];
504
- const quota = quotaRisk(where, options);
558
+ const quota = options.coverage.repositoryWide ? quotaRisk(where, options) : null;
505
559
  if (quota) result.risks.push(quota);
506
- // A CLI hand-off that failed or hangs (#357 D4).
507
- 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)));
508
562
  // Near the limit nudges stop, since each wakes a large session (D3).
509
563
  const quiet = options.quota !== null && options.quota >= options.quotaQuietAt;
510
564
  if (options.nudge && quiet) result.paused = `nudges paused: quota at ${options.quota}%`;
@@ -544,7 +598,7 @@ function runPatrol(argv) {
544
598
  // is the caller's; this only recommends.
545
599
  function recommendNext(where, role, result, options, now = new Date()) {
546
600
  const { readPatrolDeclaration, durationSeconds } = require("./config");
547
- const declaration = readPatrolDeclaration(where.worktree);
601
+ const declaration = readPatrolDeclaration(where.worktree, { role });
548
602
  const cadence = declaration.cadence;
549
603
  if (!cadence || !cadence.adaptive) {
550
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");