@christang/keel 5.114.0 → 5.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -790,6 +790,15 @@ fetches nothing, schedules nothing, calls no model, and writes nothing when noth
790
790
  0 then, 2 when it sent something, and 1 on an error, so a cheap scheduler — cron, `/loop`, CI — can
791
791
  wake the model only on 2. `keel chat waits` lists what is still awaited.
792
792
 
793
+ A patrol on an hourly schedule should report change, not state, or it wakes the coordinator every
794
+ hour for a note deliberately left parked (#295). `keel patrol --since-last` keeps a snapshot per role
795
+ — shift status, the remote default branch tip, the main checkout's uncommitted paths, each role's
796
+ idleness and open todos, and the coordinator's addressed records unread beyond `--idle` — and prints
797
+ only `changed:` lines for what differs from the previous run; the first run records a baseline. It
798
+ writes that snapshot on every run, and exits 2 only when something changed. Add `--notify` and the
799
+ changes go to the coordinator as one direct message from `keel-patrol`, which wakes its session, so
800
+ the scheduled run needs no model judgment and no session id.
801
+
793
802
  With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
794
803
  maps a label to a role, and each role gets one direct message per update of an issue carrying its
795
804
  label — so a handoff labelled `role:verify` reaches `verify` without a second message.
@@ -809,6 +818,15 @@ patrol:
809
818
  every: 30m
810
819
  ```
811
820
 
821
+ Better, run the patrol outside the coordinator's session altogether, as a host scheduled task on a
822
+ small model, which survives the coordinator clearing itself (#295). Add `host_task: <id>` (and, if
823
+ you like, `model: <id>`, which Keel passes through and never chooses) and run `keel patrol task`: it
824
+ prints the task — id, a cron from `every:`, the model, and a self-contained prompt that runs
825
+ `keel patrol --since-last --notify` against the coordinator's worktree by path. Keel creates
826
+ nothing; the session's model installs it with the host's own scheduled-task tool, since a host keeps
827
+ the schedule itself. With `host_task:` declared, the reminder asks only to confirm the task is still
828
+ enabled.
829
+
812
830
  ## Commands
813
831
 
814
832
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.114.0 -->
1
+ <!-- keel:start version=5.115.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.114.0",
3
+ "version": "5.115.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.114.0",
9
+ "version": "5.115.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.114.0",
5
+ "version": "5.115.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.114.0",
3
+ "version": "5.115.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.114.0",
3
+ "version": "5.115.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -661,7 +661,13 @@ function main() {
661
661
  );
662
662
  }
663
663
  // The patrolling role re-arms its schedule after a shift change (#260).
664
- if (context.patrol && context.patrol.role) {
664
+ if (context.patrol && context.patrol.role && context.patrol.hostTask) {
665
+ // A host scheduled task outlives the session (#295 D3).
666
+ lines.push(
667
+ `- patrol: role ${context.patrol.role} runs \`keel patrol\` every ${context.patrol.every} through host scheduled task `
668
+ + `${context.patrol.hostTask}, which outlives this session; confirm it is still enabled rather than creating a schedule in this session.`
669
+ );
670
+ } else if (context.patrol && context.patrol.role) {
665
671
  lines.push(
666
672
  `- patrol: role ${context.patrol.role} runs \`keel patrol\` every ${context.patrol.every}; `
667
673
  + "a session's schedule ends with the session, so re-create it with the host "
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.114.0"
51
- PROTOCOL_VERSION = "5.114.0"
50
+ PACKAGE_VERSION = "5.115.0"
51
+ PROTOCOL_VERSION = "5.115.0"
52
52
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
53
53
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
54
54
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -2649,6 +2649,151 @@ def validate_patrol_rearm_scenario() -> int:
2649
2649
  return 0
2650
2650
 
2651
2651
 
2652
+ def validate_patrol_host_task_scenario() -> int:
2653
+ """Issue #295: `patrol:` names the host task; `keel patrol task` renders it.
2654
+
2655
+ The rendered task carries the id, a cron from `every:`, the declared model
2656
+ or none, and a prompt running the change-based patrol by path; it writes
2657
+ nothing. A declared host task changes the reminder.
2658
+ """
2659
+ label = "patrol-host-task:"
2660
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-host-") as raw:
2661
+ base = Path(raw)
2662
+ repo = mailbox_repository(base / "repo")
2663
+ write_text(repo / "openspec/specs/.keep", "")
2664
+ declaration = "patrol:\n role: rtl\n every: 30m\n host_task: soc-patrol\n"
2665
+ write_authorize_config(repo, declaration)
2666
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
2667
+ subprocess.run(["git", "commit", "-q", "-m", "patrol"], cwd=repo, check=True, capture_output=True)
2668
+ rtl = chat_worktree(repo, base / "rtl")
2669
+ env = chat_environment()
2670
+
2671
+ unbound = run_keel(rtl, "patrol", "task", env=env)
2672
+ if unbound.returncode == 0:
2673
+ report(f"{label} keel patrol task was accepted with no worktree bound to rtl.")
2674
+ return 1
2675
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
2676
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
2677
+ task = run_keel(rtl, "patrol", "task", env=env)
2678
+ if task.returncode != 0:
2679
+ report(f"{label} keel patrol task failed: {task.stdout} {task.stderr}")
2680
+ return 1
2681
+ for needle in ("soc-patrol", "*/30 * * * *", "no model is declared",
2682
+ f"keel patrol --repo {rtl.resolve()} --since-last --notify"):
2683
+ if needle not in task.stdout:
2684
+ report(f"{label} the rendered task does not carry {needle!r}: {task.stdout!r}")
2685
+ return 1
2686
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
2687
+ if before != after:
2688
+ report(f"{label} keel patrol task changed the worktree: {after!r}")
2689
+ return 1
2690
+ write_authorize_config(rtl, declaration + " model: small-model\n")
2691
+ modelled = run_keel(rtl, "patrol", "task", env=env)
2692
+ if "small-model" not in modelled.stdout:
2693
+ report(f"{label} the declared model is not rendered: {modelled.stdout!r}")
2694
+ return 1
2695
+ if "no model is declared" in modelled.stdout:
2696
+ report(f"{label} a declared model is still reported as undeclared: {modelled.stdout!r}")
2697
+ return 1
2698
+
2699
+ context = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
2700
+ if (context.get("patrol") or {}).get("hostTask") != "soc-patrol":
2701
+ report(f"{label} keel context carries patrol {context.get('patrol')!r}.")
2702
+ return 1
2703
+ session = run_session_start_hook(
2704
+ rtl, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(rtl)},
2705
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
2706
+ )
2707
+ note = session_start_context(session) or ""
2708
+ if "soc-patrol" not in note or "still enabled" not in note:
2709
+ report(f"{label} the session-start note does not name the host task: {note!r}")
2710
+ return 1
2711
+ if "re-create it with the host" in note:
2712
+ report(f"{label} the note still asks to re-create a session schedule: {note!r}")
2713
+ return 1
2714
+
2715
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 30m\n host_task: Bad_Id\n")
2716
+ broken = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
2717
+ if not any("host_task" in w and "Bad_Id" in w for w in broken.get("warnings", [])):
2718
+ report(f"{label} a malformed host_task is not reported by name: {broken.get('warnings')!r}")
2719
+ return 1
2720
+ report("patrol-host-task scenario passed.")
2721
+ return 0
2722
+
2723
+
2724
+ def validate_patrol_since_last_scenario() -> int:
2725
+ """Issue #295: a scheduled patrol reports only what changed, once.
2726
+
2727
+ `--since-last` records a baseline, then reports changed entries and exits
2728
+ 2; `--notify` sends them to the coordinator as one message from
2729
+ `keel-patrol`; an unchanged run is quiet. `--notify` alone is refused.
2730
+ """
2731
+ label = "patrol-since-last:"
2732
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-since-") as raw:
2733
+ base = Path(raw)
2734
+ rtl, verify, env, _ = shift_scratch(base)
2735
+
2736
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
2737
+ return run_keel(rtl, "patrol", *args, env=env)
2738
+
2739
+ def notices() -> list[str]:
2740
+ return chat_records_with(rtl, "dm-keel-patrol--rtl", "changed")
2741
+
2742
+ alone = patrol("--notify")
2743
+ if alone.returncode != 1:
2744
+ report(f"{label} --notify without --since-last exited {alone.returncode}.")
2745
+ return 1
2746
+ first = patrol("--since-last", "--notify")
2747
+ if first.returncode != 0:
2748
+ report(f"{label} the first run exited {first.returncode}: {first.stdout!r} {first.stderr!r}")
2749
+ return 1
2750
+ if "baseline recorded" not in first.stdout:
2751
+ report(f"{label} the first run did not record a baseline: {first.stdout!r}")
2752
+ return 1
2753
+ if notices():
2754
+ report(f"{label} the baseline run sent a notice.")
2755
+ return 1
2756
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
2757
+ if readied.returncode != 0:
2758
+ report(f"{label} verify's ready failed: {readied.stderr}")
2759
+ return 1
2760
+ for args in (["commit", "-q", "--allow-empty", "-m", "landed"], ["push", "-q", "origin", "HEAD"]):
2761
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
2762
+ second = patrol("--since-last", "--notify")
2763
+ if second.returncode != 2:
2764
+ report(f"{label} the run after a change exited {second.returncode}: {second.stdout!r} {second.stderr!r}")
2765
+ return 1
2766
+ changed = [line for line in second.stdout.splitlines() if line.startswith("changed:")]
2767
+ if not any("shift" in line and "verify" in line for line in changed):
2768
+ report(f"{label} the shift status change is not reported: {second.stdout!r}")
2769
+ return 1
2770
+ if not any("remote" in line for line in changed):
2771
+ report(f"{label} the remote tip change is not reported: {second.stdout!r}")
2772
+ return 1
2773
+ if len(notices()) != 1:
2774
+ report(f"{label} expected one keel-patrol notice after the change, found {len(notices())}.")
2775
+ return 1
2776
+ if "from: keel-patrol" not in notices()[0]:
2777
+ report(f"{label} the notice is not from keel-patrol: {notices()[0]!r}")
2778
+ return 1
2779
+ woken = run_keel(rtl, "chat", "notice", "--check", env=env)
2780
+ if woken.returncode != 0:
2781
+ report(f"{label} the notice does not wake rtl (notice --check exit {woken.returncode}).")
2782
+ return 1
2783
+ third = patrol("--since-last", "--notify")
2784
+ if third.returncode != 0:
2785
+ report(f"{label} an unchanged run exited {third.returncode}: {third.stdout!r}")
2786
+ return 1
2787
+ if "changed:" in third.stdout:
2788
+ report(f"{label} an unchanged run reported a change: {third.stdout!r}")
2789
+ return 1
2790
+ if len(notices()) != 1:
2791
+ report(f"{label} an unchanged run sent another notice.")
2792
+ return 1
2793
+ report("patrol-since-last scenario passed.")
2794
+ return 0
2795
+
2796
+
2652
2797
  def validate_coordinator_patrol_scenario() -> int:
2653
2798
  """Issue #260: declared waits, and a patrol that notifies once.
2654
2799
 
@@ -39327,6 +39472,8 @@ SCENARIOS: tuple = (
39327
39472
  ("chat-supersedes", validate_chat_supersedes_scenario),
39328
39473
  ("chat-ack", validate_chat_ack_scenario),
39329
39474
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39475
+ ("patrol-since-last", validate_patrol_since_last_scenario),
39476
+ ("patrol-host-task", validate_patrol_host_task_scenario),
39330
39477
  ("patrol-rearm", validate_patrol_rearm_scenario),
39331
39478
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
39332
39479
  ("chat-listen-only", validate_chat_listen_only_scenario),
@@ -876,22 +876,41 @@ function readIssueRoles(repo) {
876
876
  // `patrol:` — which role runs `keel patrol`, and how often (#260). Keel only
877
877
  // reminds that role to re-create its host schedule; it schedules nothing. A
878
878
  // declaration missing a value, or with a malformed one, reminds nobody.
879
+ // `host_task:` names the host scheduled task that runs it and `model:` the
880
+ // model that task declares (#295 D3); Keel passes a model through and never
881
+ // chooses one, and a malformed one of these is ignored by name.
879
882
  function readPatrolDeclaration(repo) {
880
883
  const block = configMap(repo, "patrol");
881
- if (!Object.keys(block).length) return { declared: false, role: null, every: null, message: null };
884
+ if (!Object.keys(block).length) return { declared: false, role: null, every: null, hostTask: null, model: null, message: null };
882
885
  const problems = [];
883
886
  if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(block.role || "")) problems.push(`role \`${block.role || ""}\` is not a chat role name`);
884
887
  if (!/^\d+[smhd]$/.test(block.every || "")) problems.push(`every \`${block.every || ""}\` is not a duration such as 30m`);
885
888
  if (problems.length) {
886
889
  return {
887
- declared: true, role: null, every: null,
890
+ declared: true, role: null, every: null, hostTask: null, model: null,
888
891
  message: `keel/config.yaml patrol: ${problems.join("; ")}, so no session is reminded to run \`keel patrol\`.`,
889
892
  };
890
893
  }
891
- return { declared: true, role: block.role, every: block.every, message: null };
894
+ const ignored = [];
895
+ let hostTask = null;
896
+ let model = null;
897
+ if (block.host_task !== undefined) {
898
+ if (/^[a-z0-9][a-z0-9-]{0,63}$/.test(block.host_task)) hostTask = block.host_task;
899
+ else ignored.push(`host_task \`${block.host_task}\` is not a task id such as soc-patrol`);
900
+ }
901
+ if (block.model !== undefined) {
902
+ if (/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(block.model)) model = block.model;
903
+ else ignored.push(`model \`${block.model}\` is not a model id`);
904
+ }
905
+ const message = ignored.length ? `keel/config.yaml patrol: ${ignored.join("; ")}, so it is ignored.` : null;
906
+ return { declared: true, role: block.role, every: block.every, hostTask, model, message };
892
907
  }
893
908
 
894
909
  function patrolReminder(patrol) {
910
+ if (patrol.hostTask) {
911
+ return `Patrol: role ${patrol.role} runs \`keel patrol\` every ${patrol.every} through host scheduled task `
912
+ + `${patrol.hostTask}, which outlives this session; confirm it is still enabled rather than creating a schedule in this session.`;
913
+ }
895
914
  return `Patrol: role ${patrol.role} runs \`keel patrol\` every ${patrol.every}; a session's schedule ends with `
896
915
  + "the session, so re-create it with the host if this session has none, and wake the model only on exit 2.";
897
916
  }
@@ -851,7 +851,10 @@ function resolveContext(repo, options) {
851
851
  // The patrolling role is reminded to re-arm its schedule (#260).
852
852
  const patrol = readPatrolDeclaration(repo);
853
853
  if (patrol.message) context.warnings.push(patrol.message);
854
- if (patrol.role && context.role === patrol.role) context.patrol = { role: patrol.role, every: patrol.every };
854
+ if (patrol.role && context.role === patrol.role) {
855
+ context.patrol = { role: patrol.role, every: patrol.every };
856
+ if (patrol.hostTask) context.patrol.hostTask = patrol.hostTask;
857
+ }
855
858
  context.warnings.push(...gitWarnings(repo));
856
859
  // A broken `authorize:` declaration is otherwise reported only by
857
860
  // `keel --doctor`, an explicitly-invoked diagnostic — surfaced here too so a
@@ -12,7 +12,8 @@ const store = require("./chat/store");
12
12
  const notice = require("./chat/notice");
13
13
  const { parseSince } = require("./chat/view");
14
14
 
15
- const USAGE = "keel patrol [--issues <file>] [--idle <90s|15m|2h|3d>] [--json] [--repo <path>]";
15
+ const USAGE = "keel patrol [--issues <file>] [--idle <90s|15m|2h|3d>] [--since-last [--notify]] [--json] [--repo <path>]\n keel patrol task [--json] [--repo <path>] print the host scheduled task for `patrol:`";
16
+ const NOTIFY_SENDER = "keel-patrol";
16
17
  const EXIT_QUIET = 0;
17
18
  const EXIT_ERROR = 1;
18
19
  const EXIT_WROTE = 2;
@@ -121,25 +122,183 @@ function routeIssues(where, role, options) {
121
122
  return { notices, warnings };
122
123
  }
123
124
 
125
+ // --- what changed since the last run (#295 D1, D2) ------------------------------------
126
+
127
+ function snapshotFile(where, role) {
128
+ return path.join(where.root, "patrol", `${role}.json`);
129
+ }
130
+
131
+ function primaryWorktree(where) {
132
+ const list = git(where.worktree, ["worktree", "list", "--porcelain"]);
133
+ const first = list && list.split("\n").find((line) => line.startsWith("worktree "));
134
+ return first ? first.slice("worktree ".length) : null;
135
+ }
136
+
137
+ // The entries a scheduled run compares, keyed so a change names its subject.
138
+ function currentSnapshot(where, role, result, options) {
139
+ const shift = require("./shift");
140
+ const entries = {};
141
+ for (const row of shift.shiftStatus(where)) entries[`shift ${row.role}`] = shift.describe(row);
142
+ const base = require("./worktrees").defaultBranch(where.worktree);
143
+ if (base) {
144
+ const ref = `refs/remotes/origin/${base.replace(/^origin\//, "")}`;
145
+ entries[`remote ${ref.replace(/^refs\/remotes\//, "")}`] = git(where.worktree, ["rev-parse", "--verify", "--quiet", ref]) || "none";
146
+ }
147
+ const primary = primaryWorktree(where);
148
+ if (primary) {
149
+ const status = git(primary, ["status", "--porcelain"]);
150
+ if (status !== null) entries[`checkout ${primary}`] = `${status ? status.split("\n").length : 0} uncommitted paths`;
151
+ }
152
+ for (const row of result.roles) {
153
+ entries[`role ${row.role}`] = `${row.idle ? "idle" : "active"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`;
154
+ }
155
+ const threshold = parseSince(options.idle);
156
+ const unread = store.unread(where, role)
157
+ .filter((record) => store.wakes(record, role) && Date.parse(record.created || "") < threshold)
158
+ .map((record) => ({ id: record.id, from: record.from, created: record.created }));
159
+ return { entries, unread };
160
+ }
161
+
162
+ function sinceLast(where, role, result, options) {
163
+ const file = snapshotFile(where, role);
164
+ const previous = fs.existsSync(file) ? store.readJsonFile(file) : null;
165
+ const now = currentSnapshot(where, role, result, options);
166
+ store.writeJsonAtomic(where, file, now);
167
+ if (!previous || !previous.entries) return { baseline: true, changes: [] };
168
+ const changes = [];
169
+ const keys = [...new Set([...Object.keys(previous.entries), ...Object.keys(now.entries)])].sort();
170
+ for (const key of keys) {
171
+ const before = previous.entries[key] ?? "(none)";
172
+ const after = now.entries[key] ?? "(none)";
173
+ if (before !== after) changes.push(`${key}: ${before} -> ${after}`);
174
+ }
175
+ const seen = new Set((previous.unread || []).map((record) => record.id));
176
+ for (const record of now.unread) {
177
+ if (!seen.has(record.id)) changes.push(`unread: ${record.id} from ${record.from}, unanswered since ${record.created}`);
178
+ }
179
+ return { baseline: false, changes };
180
+ }
181
+
182
+ function notifyChanges(where, role, changes) {
183
+ const group = store.directName(NOTIFY_SENDER, role);
184
+ if (!store.groupState(store.readLog(where, group)).exists) {
185
+ store.createGroup(where, NOTIFY_SENDER, group, [role], { direct: true });
186
+ }
187
+ const text = [`Patrol ${store.isoLocal(new Date())}: what changed since the last run:`, ...changes.map((line) => `- changed: ${line}`)].join("\n");
188
+ return store.writeRecord(where, { group, kind: "message", from: NOTIFY_SENDER, refs: [NOTIFY_SENDER], text });
189
+ }
190
+
124
191
  function render(result) {
125
192
  const lines = [];
126
- if (!result.notices.length && !result.held.length) lines.push("keel patrol: nothing new.");
193
+ const changes = result.sinceLast ? result.sinceLast.changes : [];
194
+ if (result.sinceLast && result.sinceLast.baseline) lines.push("keel patrol: baseline recorded.");
195
+ else if (!result.notices.length && !result.held.length && !changes.length) lines.push("keel patrol: nothing new.");
196
+ for (const change of changes) lines.push(`changed: ${change}`);
127
197
  for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
128
198
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
129
199
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
130
200
  for (const warning of result.warnings) lines.push(`warning: ${warning}`);
131
- for (const row of result.roles) {
201
+ // A scheduled run reports roles only through what changed (D1).
202
+ for (const row of result.sinceLast ? [] : result.roles) {
132
203
  lines.push(`role ${row.role}: ${row.presence}${row.idle ? " (idle)" : ""}, last active ${row.lastActive || "unknown"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`);
133
204
  }
134
205
  return lines.join("\n");
135
206
  }
136
207
 
208
+ // --- the host task (#295 D4) ---------------------------------------------------------
209
+ //
210
+ // Keel renders the task and creates nothing: a host's schedule is set through
211
+ // its own tool, which the session's model calls (F1).
212
+
213
+ function suggestCron(every) {
214
+ const match = String(every).match(/^(\d+)([smhd])$/);
215
+ const n = match ? Number(match[1]) : 0;
216
+ const unit = match ? match[2] : "";
217
+ if ((unit === "m" && n === 60) || (unit === "h" && n === 1)) return { cron: "0 * * * *" };
218
+ if (unit === "m" && n > 0 && n < 60 && 60 % n === 0) return { cron: `*/${n} * * * *` };
219
+ if (unit === "h" && n > 1 && 24 % n === 0) return { cron: `0 */${n} * * *` };
220
+ if (unit === "d" && n === 1) return { cron: "0 9 * * *" };
221
+ return { cron: null, why: `every: ${every} has no plain cron form; choose a schedule near it` };
222
+ }
223
+
224
+ function shellPath(file) {
225
+ return /[\s"'$`\\]/.test(file) ? JSON.stringify(file) : file;
226
+ }
227
+
228
+ function hostTask(where) {
229
+ const config = require("./config");
230
+ const declaration = config.readPatrolDeclaration(where.worktree);
231
+ if (!declaration.role) {
232
+ throw new PatrolError(declaration.message || "keel/config.yaml declares no `patrol:` with role and every, so there is no patrol task to render.");
233
+ }
234
+ const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
235
+ .filter(([, role]) => role === declaration.role).map(([worktree]) => worktree).sort();
236
+ if (!bound.length) {
237
+ throw new PatrolError(`No worktree is bound to role ${declaration.role}; bind one with \`keel chat role --set ${declaration.role}\` there first.`);
238
+ }
239
+ const worktree = bound[0];
240
+ const role = declaration.role;
241
+ const at = shellPath(worktree);
242
+ const schedule = suggestCron(declaration.every);
243
+ const prompt = [
244
+ `You run the Keel patrol for chat role ${role} of the repository at ${worktree}. Do exactly the steps below and nothing else.`,
245
+ "",
246
+ `Do not change into that directory: run every command with the paths given, so this session does not act as ${role} (Keel's session hooks follow the working directory). `
247
+ + "Do not edit files, commit, push, close or comment on issues, or message anyone yourself: `keel patrol` sends the coordinator what changed.",
248
+ "",
249
+ `1. Run \`git -C ${at} fetch -q origin\`. If it fails, keep its error and continue.`,
250
+ `2. Run \`keel patrol --repo ${at} --since-last --notify\`.`,
251
+ `3. Exit 0: nothing changed. Exit 2: keel has already told ${role}. In both cases end without output. `
252
+ + "Exit 1: end with one line, `keel patrol failed: <its error output>`, adding the fetch error from step 1 if there was one.",
253
+ ].join("\n");
254
+ return {
255
+ taskId: declaration.hostTask || `keel-patrol-${role}`,
256
+ description: `Keel patrol for role ${role}: tells it what changed since the last run`,
257
+ cronExpression: schedule.cron,
258
+ cronNote: schedule.why || null,
259
+ every: declaration.every,
260
+ model: declaration.model,
261
+ worktree,
262
+ prompt,
263
+ };
264
+ }
265
+
266
+ function renderTask(task) {
267
+ return [
268
+ `Host scheduled task for the patrol of role ${task.prompt.match(/chat role (\S+)/)[1]}. Keel creates nothing: install it with the host's scheduled-task tool.`,
269
+ `task id: ${task.taskId}`,
270
+ `schedule: ${task.cronExpression ? `${task.cronExpression} (from every: ${task.every}; hosts may add jitter)` : task.cronNote}`,
271
+ `model: ${task.model || "no model is declared: choose a small model; Keel names none"}`,
272
+ `description: ${task.description}`,
273
+ "prompt:",
274
+ task.prompt,
275
+ ].join("\n");
276
+ }
277
+
137
278
  function runPatrol(argv) {
138
- const options = { repo: process.cwd(), issues: null, idle: "30m", json: false };
279
+ if (argv[0] === "task") {
280
+ const json = argv.includes("--json");
281
+ const at = argv.indexOf("--repo");
282
+ try {
283
+ const where = store.requireLocation(path.resolve(at >= 0 ? argv[at + 1] || "" : process.cwd()));
284
+ const task = hostTask(where);
285
+ process.stdout.write(`${json ? JSON.stringify(task, null, 2) : renderTask(task)}\n`);
286
+ return EXIT_QUIET;
287
+ } catch (error) {
288
+ if (error instanceof PatrolError || error instanceof store.ChatError) {
289
+ process.stderr.write(`keel patrol task: ${error.message}\n`);
290
+ return EXIT_ERROR;
291
+ }
292
+ throw error;
293
+ }
294
+ }
295
+ const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false };
139
296
  try {
140
297
  for (let index = 0; index < argv.length; index += 1) {
141
298
  const arg = argv[index];
142
299
  if (arg === "--json") options.json = true;
300
+ else if (arg === "--since-last") options.sinceLast = true;
301
+ else if (arg === "--notify") options.notify = true;
143
302
  else if (arg === "--help" || arg === "-h") {
144
303
  process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
145
304
  return EXIT_QUIET;
@@ -149,13 +308,19 @@ function runPatrol(argv) {
149
308
  options[arg.slice(2)] = value;
150
309
  } else throw new PatrolError(`Unknown argument ${arg}. ${USAGE}`);
151
310
  }
311
+ if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends what changed, so it needs --since-last.");
152
312
  if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
153
313
  options.issues = readIssues(options.issues);
154
314
  const where = store.requireLocation(path.resolve(options.repo));
155
315
  const role = store.requireRole(where);
156
316
  const result = patrol(where, role, options);
317
+ if (options.sinceLast) {
318
+ result.sinceLast = sinceLast(where, role, result, options);
319
+ if (options.notify && result.sinceLast.changes.length) result.notified = notifyChanges(where, role, result.sinceLast.changes).id;
320
+ }
157
321
  process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
158
- return result.notices.length || result.held.length ? EXIT_WROTE : EXIT_QUIET;
322
+ const changed = result.sinceLast && result.sinceLast.changes.length;
323
+ return result.notices.length || result.held.length || changed ? EXIT_WROTE : EXIT_QUIET;
159
324
  } catch (error) {
160
325
  if (error instanceof PatrolError || error instanceof store.ChatError) {
161
326
  process.stderr.write(`keel patrol: ${error.message}\n`);
package/src/core/shift.js CHANGED
@@ -671,7 +671,7 @@ function runShift(argv) {
671
671
  const { readPatrolDeclaration, patrolReminder } = require("./config");
672
672
  const patrol = readPatrolDeclaration(where.worktree);
673
673
  const remind = patrol.role && result.role === patrol.role;
674
- if (remind) result.patrol = { role: patrol.role, every: patrol.every };
674
+ if (remind) result.patrol = { role: patrol.role, every: patrol.every, ...(patrol.hostTask ? { hostTask: patrol.hostTask } : {}) };
675
675
  // A new coordinator learns whom its previous shift left unstarted (#289 D2).
676
676
  const waiting = (result.waiting || []).map((w) => w.role);
677
677
  const still = waiting.length ? `\n\nStill waiting for \`keel shift start\`: ${waiting.join(", ")}.` : "";
@@ -706,4 +706,4 @@ function waitingFor(repo) {
706
706
  return { note, since: store.isoLocal(fs.statSync(note).mtime) };
707
707
  }
708
708
 
709
- module.exports = { check, runShift, waitingFor };
709
+ module.exports = { check, describe, runShift, shiftStatus: status, waitingFor };