@christang/keel 5.120.0 → 5.122.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
@@ -796,8 +796,19 @@ hour for a note deliberately left parked (#295). `keel patrol --since-last` keep
796
796
  idleness and open todos, and the coordinator's addressed records unread beyond `--idle` — and prints
797
797
  only `changed:` lines for what differs from the previous run; the first run records a baseline. It
798
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.
799
+ coordinator gets one direct message from `keel-patrol`, which wakes its session, carrying only risks
800
+ (#307): the shared checkout gaining uncommitted paths after a clean run, free disk the host reports with
801
+ `--disk-free-gb` dropping below `--disk-min-gb` (default 20), and a role that left two nudges in a row
802
+ unanswered. Shift-status changes and new commits are printed, not sent. Every run appends one line to
803
+ `patrol/log/<role>.log` in the chat store, so a silent run can still be audited.
804
+
805
+ `keel patrol --nudge` goes further and nudges each idle role itself, with one direct message from
806
+ `keel-patrol` that wakes its session (#307): when records addressed to it have waited longer than
807
+ `--idle` (at most every two hours); when the host reports with `--context <role>=<percent>` that its
808
+ context is at or above `--shift-at` (default 50) and nothing waits, telling it to change its own shift
809
+ with `keel shift ready --wake` (at most every six hours); and when a note it filed with `ready --wake`
810
+ was never resumed. A note filed without `--wake` — a coordinator parking a role — is left alone, and
811
+ Keel's own messages never count as waiting.
801
812
 
802
813
  With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
803
814
  maps a label to a role, and each role gets one direct message per update of an issue carrying its
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.120.0 -->
1
+ <!-- keel:start version=5.122.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.120.0",
3
+ "version": "5.122.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.120.0",
9
+ "version": "5.122.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.120.0",
5
+ "version": "5.122.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.120.0",
3
+ "version": "5.122.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.120.0",
3
+ "version": "5.122.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.120.0"
51
- PROTOCOL_VERSION = "5.120.0"
50
+ PACKAGE_VERSION = "5.122.0"
51
+ PROTOCOL_VERSION = "5.122.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
@@ -2809,15 +2809,9 @@ def validate_patrol_since_last_scenario() -> int:
2809
2809
  if not any("remote" in line for line in changed):
2810
2810
  report(f"{label} the remote tip change is not reported: {second.stdout!r}")
2811
2811
  return 1
2812
- if len(notices()) != 1:
2813
- report(f"{label} expected one keel-patrol notice after the change, found {len(notices())}.")
2814
- return 1
2815
- if "from: keel-patrol" not in notices()[0]:
2816
- report(f"{label} the notice is not from keel-patrol: {notices()[0]!r}")
2817
- return 1
2818
- woken = run_keel(rtl, "chat", "notice", "--check", env=env)
2819
- if woken.returncode != 0:
2820
- report(f"{label} the notice does not wake rtl (notice --check exit {woken.returncode}).")
2812
+ # Shift-status and remote changes are not risks (#307 part 3): printed, not sent.
2813
+ if notices():
2814
+ report(f"{label} a run with no risk sent the coordinator a notice: {notices()!r}")
2821
2815
  return 1
2822
2816
  third = patrol("--since-last", "--notify")
2823
2817
  if third.returncode != 0:
@@ -2826,13 +2820,159 @@ def validate_patrol_since_last_scenario() -> int:
2826
2820
  if "changed:" in third.stdout:
2827
2821
  report(f"{label} an unchanged run reported a change: {third.stdout!r}")
2828
2822
  return 1
2829
- if len(notices()) != 1:
2830
- report(f"{label} an unchanged run sent another notice.")
2823
+ if notices():
2824
+ report(f"{label} an unchanged run sent a notice.")
2831
2825
  return 1
2832
2826
  report("patrol-since-last scenario passed.")
2833
2827
  return 0
2834
2828
 
2835
2829
 
2830
+ def validate_patrol_nudge_scenario() -> int:
2831
+ """Issue #307 part 1: the patrol nudges idle roles directly, rate-limited.
2832
+
2833
+ Unread addressed records, a host-reported context share, and a
2834
+ self-initiated shift note each nudge once; a parked note and the
2835
+ patrol's own messages never do.
2836
+ """
2837
+ label = "patrol-nudge:"
2838
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-nudge-") as raw:
2839
+ base = Path(raw)
2840
+ rtl, verify, env, _ = shift_scratch(base)
2841
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "1"}
2842
+ lint = chat_worktree(rtl, base / "lint")
2843
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=lint, check=True, capture_output=True)
2844
+ run_keel(lint, "chat", "role", "--set", "lint", env=env)
2845
+ run_keel(rtl, "chat", "post", "soc", "@verify please rerun R007", env=env)
2846
+ time.sleep(1.2)
2847
+
2848
+ def nudge(*args: str) -> subprocess.CompletedProcess[str]:
2849
+ return run_keel(rtl, "patrol", "--nudge", "--idle", "1s", *args, env=env)
2850
+
2851
+ def nudged(result: subprocess.CompletedProcess[str]) -> list[str]:
2852
+ return [line for line in result.stdout.splitlines() if line.startswith("nudged ")]
2853
+
2854
+ seen: list[str] = []
2855
+ first = nudge("--context", "lint=40")
2856
+ seen += nudged(first)
2857
+ if "nudged verify: unread" not in nudged(first):
2858
+ report(f"{label} verify was not nudged for unread: {first.stdout!r} {first.stderr!r}")
2859
+ return 1
2860
+ if any(line.startswith("nudged lint") for line in nudged(first)):
2861
+ report(f"{label} lint was nudged below the shift threshold: {nudged(first)!r}")
2862
+ return 1
2863
+ if first.returncode != 2:
2864
+ report(f"{label} a run that nudged exited {first.returncode}.")
2865
+ return 1
2866
+ if not chat_records_with(rtl, "dm-keel-patrol--verify", "keel chat unread"):
2867
+ report(f"{label} no keel-patrol record reached verify.")
2868
+ return 1
2869
+ if run_keel(verify, "chat", "notice", "--check", env=env).returncode != 0:
2870
+ report(f"{label} the nudge does not wake verify.")
2871
+ return 1
2872
+ second = nudge("--context", "lint=62")
2873
+ seen += nudged(second)
2874
+ if nudged(second) != ["nudged lint: shift"]:
2875
+ report(f"{label} the second run should nudge only lint's shift: {second.stdout!r}")
2876
+ return 1
2877
+ shift_text = "\n".join(chat_records_with(rtl, "dm-keel-patrol--lint", "context is at 62%"))
2878
+ if "keel shift ready --wake" not in shift_text:
2879
+ report(f"{label} the shift nudge does not name keel shift ready --wake: {shift_text!r}")
2880
+ return 1
2881
+ if "Remote Control" not in shift_text:
2882
+ report(f"{label} the shift nudge does not name Remote Control: {shift_text!r}")
2883
+ return 1
2884
+ time.sleep(1.2)
2885
+ third = nudge("--context", "lint=62")
2886
+ seen += nudged(third)
2887
+ if nudged(third):
2888
+ report(f"{label} a run within the rate limits nudged: {nudged(third)!r}")
2889
+ return 1
2890
+ if third.returncode != 0:
2891
+ report(f"{label} a run that nudged nobody exited {third.returncode}.")
2892
+ return 1
2893
+ armed = run_keel(lint, "shift", "ready", "--wake", "lint note", env=env)
2894
+ if armed.returncode != 0:
2895
+ report(f"{label} lint's ready --wake failed: {armed.stderr}")
2896
+ return 1
2897
+ if run_keel(verify, "shift", "ready", "--force-reason", "parked by the coordinator", "verify parked", env=env).returncode != 0:
2898
+ report(f"{label} verify's ready failed.")
2899
+ return 1
2900
+ time.sleep(1.2)
2901
+ fourth = nudge()
2902
+ seen += nudged(fourth)
2903
+ if "nudged lint: resume" not in nudged(fourth):
2904
+ report(f"{label} lint's self-initiated note was not nudged to resume: {fourth.stdout!r}")
2905
+ return 1
2906
+ if "nudged verify: resume" in nudged(fourth):
2907
+ report(f"{label} verify's parked note was nudged to resume.")
2908
+ return 1
2909
+ if "nudged lint: unread" in seen:
2910
+ report(f"{label} lint was nudged over the patrol's own message.")
2911
+ return 1
2912
+ report("patrol-nudge scenario passed.")
2913
+ return 0
2914
+
2915
+
2916
+ def validate_patrol_escalate_scenario() -> int:
2917
+ """Issue #307 part 3: only risks reach the coordinator; every run is logged."""
2918
+ label = "patrol-escalate:"
2919
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-escalate-") as raw:
2920
+ base = Path(raw)
2921
+ rtl, verify, env, _ = shift_scratch(base)
2922
+ env = {**env, "KEEL_PATROL_UNREAD_EVERY_MS": "1"}
2923
+ runs = 0
2924
+
2925
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
2926
+ nonlocal runs
2927
+ runs += 1
2928
+ return run_keel(rtl, "patrol", "--since-last", "--notify", "--idle", "1s", *args, env=env)
2929
+
2930
+ def sent(needle: str) -> int:
2931
+ return len(chat_records_with(rtl, "dm-keel-patrol--rtl", needle))
2932
+
2933
+ patrol()
2934
+ write_text(rtl / "dirty.txt", "left behind\n")
2935
+ dirty = patrol()
2936
+ if sent("uncommitted") != 1:
2937
+ report(f"{label} the dirty checkout was not sent once: {dirty.stdout!r} {dirty.stderr!r}")
2938
+ return 1
2939
+ if not any(line.startswith("risk:") for line in dirty.stdout.splitlines()):
2940
+ report(f"{label} the risk is not printed: {dirty.stdout!r}")
2941
+ return 1
2942
+ patrol("--disk-free-gb", "12")
2943
+ if sent("free disk is 12 GB") != 1:
2944
+ report(f"{label} low disk was not sent once.")
2945
+ return 1
2946
+ patrol("--disk-free-gb", "12")
2947
+ if sent("free disk") != 1:
2948
+ report(f"{label} low disk was sent again without changing.")
2949
+ return 1
2950
+ if sent("uncommitted") != 1:
2951
+ report(f"{label} the still-dirty checkout was sent again.")
2952
+ return 1
2953
+ run_keel(rtl, "chat", "post", "soc", "@verify rerun R007 please", env=env)
2954
+ time.sleep(1.2)
2955
+ patrol("--nudge")
2956
+ time.sleep(0.2)
2957
+ second = patrol("--nudge")
2958
+ if sent("2 nudges") != 1:
2959
+ report(f"{label} two unanswered nudges were not escalated once: {second.stdout!r}")
2960
+ return 1
2961
+ if "verify" not in "\n".join(chat_records_with(rtl, "dm-keel-patrol--rtl", "2 nudges")):
2962
+ report(f"{label} the escalation does not name verify.")
2963
+ return 1
2964
+ log = mailbox_common_dir(rtl) / "keel-chat" / "patrol" / "log" / "rtl.log"
2965
+ lines = log.read_text(encoding="utf-8").splitlines() if log.exists() else []
2966
+ if len(lines) != runs:
2967
+ report(f"{label} the run log holds {len(lines)} lines for {runs} runs.")
2968
+ return 1
2969
+ if not all("exit=" in line and "risks=" in line for line in lines):
2970
+ report(f"{label} a run log line lacks exit= or risks=: {lines!r}")
2971
+ return 1
2972
+ report("patrol-escalate scenario passed.")
2973
+ return 0
2974
+
2975
+
2836
2976
  def validate_coordinator_patrol_scenario() -> int:
2837
2977
  """Issue #260: declared waits, and a patrol that notifies once.
2838
2978
 
@@ -39907,6 +40047,8 @@ SCENARIOS: tuple = (
39907
40047
  ("chat-ack", validate_chat_ack_scenario),
39908
40048
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39909
40049
  ("patrol-since-last", validate_patrol_since_last_scenario),
40050
+ ("patrol-nudge", validate_patrol_nudge_scenario),
40051
+ ("patrol-escalate", validate_patrol_escalate_scenario),
39910
40052
  ("patrol-host-task", validate_patrol_host_task_scenario),
39911
40053
  ("patrol-rearm", validate_patrol_rearm_scenario),
39912
40054
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
@@ -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]] [--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 [--context <role>=<pct>]... [--shift-at <pct>]] [--json] [--repo <path>]\n keel patrol task [--json] [--repo <path>] print the host scheduled task for `patrol:`";
16
16
  const NOTIFY_SENDER = "keel-patrol";
17
17
  const EXIT_QUIET = 0;
18
18
  const EXIT_ERROR = 1;
@@ -152,6 +152,8 @@ function currentSnapshot(where, role, result, options) {
152
152
  if (status !== null) entries[`checkout ${primary}`] = `${status ? status.split("\n").length : 0} uncommitted paths`;
153
153
  }
154
154
  for (const line of result.drift) entries[line.key] = line.text;
155
+ // Free disk as the host measured it (#307 part 3 D1).
156
+ if (options.diskFreeGb !== null) entries.disk = options.diskFreeGb < options.diskMinGb ? "low" : "ok";
155
157
  for (const row of result.roles) {
156
158
  entries[`role ${row.role}`] = `${row.idle ? "idle" : "active"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`;
157
159
  }
@@ -167,7 +169,7 @@ function sinceLast(where, role, result, options) {
167
169
  const previous = fs.existsSync(file) ? store.readJsonFile(file) : null;
168
170
  const now = currentSnapshot(where, role, result, options);
169
171
  store.writeJsonAtomic(where, file, now);
170
- if (!previous || !previous.entries) return { baseline: true, changes: [] };
172
+ if (!previous || !previous.entries) return { baseline: true, changes: [], risks: [] };
171
173
  const changes = [];
172
174
  const keys = [...new Set([...Object.keys(previous.entries), ...Object.keys(now.entries)])].sort();
173
175
  for (const key of keys) {
@@ -179,15 +181,118 @@ function sinceLast(where, role, result, options) {
179
181
  for (const record of now.unread) {
180
182
  if (!seen.has(record.id)) changes.push(`unread: ${record.id} from ${record.from}, unanswered since ${record.created}`);
181
183
  }
182
- return { baseline: false, changes };
184
+ // What the coordinator must hear (#307 part 3 D1): a clean checkout turned
185
+ // dirty, and free disk turned low; the rest of the changes are only printed.
186
+ const risks = [];
187
+ for (const key of Object.keys(now.entries).filter((entry) => entry.startsWith("checkout "))) {
188
+ const count = Number.parseInt(now.entries[key], 10);
189
+ if (previous.entries[key] === "0 uncommitted paths" && count > 0) {
190
+ risks.push(`the shared checkout ${key.slice("checkout ".length)} has ${count} uncommitted paths`);
191
+ }
192
+ }
193
+ if (now.entries.disk === "low" && previous.entries.disk !== "low") {
194
+ risks.push(`free disk is ${options.diskFreeGb} GB, below ${options.diskMinGb} GB`);
195
+ }
196
+ return { baseline: false, changes, risks };
183
197
  }
184
198
 
185
- function notifyChanges(where, role, changes) {
199
+ // --- nudges (#307 part 1) -----------------------------------------------------------
200
+ //
201
+ // The patrol nudges an idle role itself, with one direct message from
202
+ // `keel-patrol` that wakes its session (D1-D5). Keel's own records never count
203
+ // as waiting, so a nudge cannot cause the next one.
204
+
205
+ const KEEL_SENDERS = new Set([NOTIFY_SENDER, "keel-shift", "keel"]);
206
+ const UNREAD_EVERY_MS = Number(process.env.KEEL_PATROL_UNREAD_EVERY_MS) > 0 ? Number(process.env.KEEL_PATROL_UNREAD_EVERY_MS) : 2 * 60 * 60 * 1000;
207
+ const SHIFT_EVERY_MS = 6 * 60 * 60 * 1000;
208
+ const SELF_INITIATED = "Self-initiated: this shift armed `keel shift ready --wake`.";
209
+
210
+ function parseContexts(values) {
211
+ const contexts = new Map();
212
+ for (const value of values) {
213
+ const match = String(value).match(/^([a-z0-9][a-z0-9-]{0,31})=(\d{1,3}(?:\.\d+)?)%?$/);
214
+ if (!match) throw new PatrolError(`--context ${value} is not <role>=<percent>.`);
215
+ contexts.set(match[1], Number(match[2]));
216
+ }
217
+ return contexts;
218
+ }
219
+
220
+ function sendNudge(where, role, kind, text) {
186
221
  const group = store.directName(NOTIFY_SENDER, role);
187
222
  if (!store.groupState(store.readLog(where, group)).exists) {
188
223
  store.createGroup(where, NOTIFY_SENDER, group, [role], { direct: true });
189
224
  }
190
- const text = [`Patrol ${store.isoLocal(new Date())}: what changed since the last run:`, ...changes.map((line) => `- changed: ${line}`)].join("\n");
225
+ store.writeRecord(where, { group, kind: "message", from: NOTIFY_SENDER, refs: ["keel-patrol-nudge"], text });
226
+ return { role, kind, text };
227
+ }
228
+
229
+ function nudgeRoles(where, patroller, options) {
230
+ const stateFile = path.join(where.root, "patrol", "nudges.json");
231
+ const state = store.readJsonFile(stateFile);
232
+ const now = Date.now();
233
+ const idleBefore = parseSince(options.idle);
234
+ const sent = [];
235
+ const escalations = [];
236
+ const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))]
237
+ .filter((role) => role !== patroller).sort();
238
+ for (const role of roles) {
239
+ const last = Date.parse(notice.presenceOf(where, role).last_active || "");
240
+ if (!Number.isNaN(last) && last >= idleBefore) continue;
241
+ const mine = state[role] || {};
242
+ const waiting = store.unread(where, role)
243
+ .filter((record) => store.wakes(record, role) && !KEEL_SENDERS.has(record.from))
244
+ .sort((a, b) => (a.id < b.id ? -1 : 1));
245
+ const note = path.join(where.root, "shift", `${role}.md`);
246
+ const noteText = fs.existsSync(note) ? fs.readFileSync(note, "utf8") : null;
247
+ if (waiting.length) {
248
+ const oldest = Date.parse(waiting[0].created || "");
249
+ const recent = Date.parse(mine.unread || "");
250
+ if (!Number.isNaN(oldest) && oldest < idleBefore && (Number.isNaN(recent) || now - recent >= UNREAD_EVERY_MS)) {
251
+ sent.push(sendNudge(where, role, "unread",
252
+ `${role}: ${waiting.length} record(s) addressed to you have waited since ${waiting[0].created}; read them with \`keel chat unread\`.`));
253
+ // A nudge over work older than the last one is a nudge left unanswered (D2).
254
+ mine.unanswered = !Number.isNaN(recent) && oldest < recent ? (mine.unanswered || 0) + 1 : 1;
255
+ if (mine.unanswered === 2) {
256
+ escalations.push(`${role} has not answered 2 nudges; ${waiting.length} record(s) addressed to it have waited since ${waiting[0].created}`);
257
+ }
258
+ mine.unread = new Date(now).toISOString();
259
+ }
260
+ } else {
261
+ mine.unanswered = 0;
262
+ }
263
+ if (!waiting.length && !noteText && options.contexts.has(role) && options.contexts.get(role) >= options.shiftAt) {
264
+ const recent = Date.parse(mine.shift || "");
265
+ if (Number.isNaN(recent) || now - recent >= SHIFT_EVERY_MS) {
266
+ sent.push(sendNudge(where, role, "shift",
267
+ `${role}: your context is at ${options.contexts.get(role)}%. Change your own shift: \`keel shift check\`, `
268
+ + "then `keel shift ready --wake \"<note>\"`, then clear this session. A session serving Remote Control "
269
+ + "cannot be cleared: turn it off, clear, then turn it back on."));
270
+ mine.shift = store.isoLocal(new Date(now));
271
+ }
272
+ }
273
+ if (noteText && noteText.includes(SELF_INITIATED)) {
274
+ const written = fs.statSync(note).mtime;
275
+ const woken = store.readLog(where, store.directName("keel-shift", role))
276
+ .some((record) => record.from === "keel-shift" && Date.parse(record.created || "") >= written.getTime() - 1000);
277
+ const stamp = store.isoLocal(written);
278
+ if (written.getTime() < idleBefore && !woken && mine.resume !== stamp) {
279
+ sent.push(sendNudge(where, role, "resume",
280
+ `${role}: your previous shift left a note at ${stamp}; run \`keel context\`, then \`keel shift resume\`.`));
281
+ mine.resume = stamp;
282
+ }
283
+ }
284
+ state[role] = mine;
285
+ }
286
+ store.writeJsonAtomic(where, stateFile, state);
287
+ return { sent, escalations };
288
+ }
289
+
290
+ function notifyRisks(where, role, risks) {
291
+ const group = store.directName(NOTIFY_SENDER, role);
292
+ if (!store.groupState(store.readLog(where, group)).exists) {
293
+ store.createGroup(where, NOTIFY_SENDER, group, [role], { direct: true });
294
+ }
295
+ const text = [`Patrol ${store.isoLocal(new Date())}: risks for the coordinator:`, ...risks.map((line) => `- risk: ${line}`)].join("\n");
191
296
  return store.writeRecord(where, { group, kind: "message", from: NOTIFY_SENDER, refs: [NOTIFY_SENDER], text });
192
297
  }
193
298
 
@@ -197,6 +302,8 @@ function render(result) {
197
302
  if (result.sinceLast && result.sinceLast.baseline) lines.push("keel patrol: baseline recorded.");
198
303
  else if (!result.notices.length && !result.held.length && !changes.length) lines.push("keel patrol: nothing new.");
199
304
  for (const change of changes) lines.push(`changed: ${change}`);
305
+ for (const sent of result.nudges || []) lines.push(`nudged ${sent.role}: ${sent.kind}`);
306
+ for (const risk of result.risks || []) lines.push(`risk: ${risk}`);
200
307
  for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
201
308
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
202
309
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
@@ -298,13 +405,18 @@ function runPatrol(argv) {
298
405
  throw error;
299
406
  }
300
407
  }
301
- const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false };
408
+ const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false, nudge: false, context: [], shiftAt: 50, diskFreeGb: null, diskMinGb: 20 };
302
409
  try {
303
410
  for (let index = 0; index < argv.length; index += 1) {
304
411
  const arg = argv[index];
305
412
  if (arg === "--json") options.json = true;
306
413
  else if (arg === "--since-last") options.sinceLast = true;
307
414
  else if (arg === "--notify") options.notify = true;
415
+ else if (arg === "--nudge") options.nudge = true;
416
+ else if (arg === "--context") options.context.push(argv[++index] || "");
417
+ else if (arg === "--shift-at") options.shiftAt = Number(argv[++index]);
418
+ else if (arg === "--disk-free-gb") options.diskFreeGb = Number(argv[++index]);
419
+ else if (arg === "--disk-min-gb") options.diskMinGb = Number(argv[++index]);
308
420
  else if (arg === "--help" || arg === "-h") {
309
421
  process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
310
422
  return EXIT_QUIET;
@@ -314,19 +426,33 @@ function runPatrol(argv) {
314
426
  options[arg.slice(2)] = value;
315
427
  } else throw new PatrolError(`Unknown argument ${arg}. ${USAGE}`);
316
428
  }
317
- if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends what changed, so it needs --since-last.");
429
+ if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends the risks found since the last run, so it needs --since-last.");
430
+ if (!(options.shiftAt > 0 && options.shiftAt <= 100)) throw new PatrolError("--shift-at needs a percentage from 1 to 100.");
431
+ options.contexts = parseContexts(options.context);
432
+ if (options.diskFreeGb !== null && !(options.diskFreeGb >= 0)) throw new PatrolError("--disk-free-gb needs a number of gigabytes.");
433
+ if (!(options.diskMinGb > 0)) throw new PatrolError("--disk-min-gb needs a positive number of gigabytes.");
318
434
  if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
319
435
  options.issues = readIssues(options.issues);
320
436
  const where = store.requireLocation(path.resolve(options.repo));
321
437
  const role = store.requireRole(where);
322
438
  const result = patrol(where, role, options);
439
+ result.risks = [];
440
+ if (options.nudge) {
441
+ const nudged = nudgeRoles(where, role, options);
442
+ result.nudges = nudged.sent;
443
+ result.risks.push(...nudged.escalations);
444
+ }
323
445
  if (options.sinceLast) {
324
446
  result.sinceLast = sinceLast(where, role, result, options);
325
- if (options.notify && result.sinceLast.changes.length) result.notified = notifyChanges(where, role, result.sinceLast.changes).id;
447
+ result.risks.unshift(...result.sinceLast.risks);
448
+ // Only risks reach the coordinator (#307 part 3 D3).
449
+ if (options.notify && result.risks.length) result.notified = notifyRisks(where, role, result.risks).id;
326
450
  }
327
451
  process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
328
452
  const changed = result.sinceLast && result.sinceLast.changes.length;
329
- return result.notices.length || result.held.length || changed ? EXIT_WROTE : EXIT_QUIET;
453
+ const code = result.notices.length || result.held.length || changed || (result.nudges || []).length || result.risks.length ? EXIT_WROTE : EXIT_QUIET;
454
+ appendRunLog(where, role, code, result);
455
+ return code;
330
456
  } catch (error) {
331
457
  if (error instanceof PatrolError || error instanceof store.ChatError) {
332
458
  process.stderr.write(`keel patrol: ${error.message}\n`);
@@ -336,4 +462,17 @@ function runPatrol(argv) {
336
462
  }
337
463
  }
338
464
 
465
+ // One line per run, so a silent run can be audited (#307 part 3 D4).
466
+ function appendRunLog(where, role, code, result) {
467
+ try {
468
+ const file = path.join(where.root, "patrol", "log", `${role}.log`);
469
+ fs.mkdirSync(path.dirname(file), { recursive: true });
470
+ const changes = result.sinceLast ? result.sinceLast.changes.length : 0;
471
+ fs.appendFileSync(file, `${store.isoLocal(new Date())} exit=${code} changes=${changes} nudges=${(result.nudges || []).length} `
472
+ + `risks=${result.risks.length} notified=${result.notified ? "yes" : "no"}\n`);
473
+ } catch {
474
+ // The log is for audit; failing to write it never fails the patrol.
475
+ }
476
+ }
477
+
339
478
  module.exports = { PatrolError, runPatrol, patrol };
package/src/core/shift.js CHANGED
@@ -218,6 +218,9 @@ function check(where, role) {
218
218
  }
219
219
  for (const record of store.unread(where, role)) {
220
220
  if (isShift(record) || !store.wakes(record, role)) continue;
221
+ // Keel's own nudges and wakes are instructions, not work left over (#307):
222
+ // a role told to change its shift is not held back by being told.
223
+ if (record.from === "keel-patrol" || record.from === "keel-shift") continue;
221
224
  if (record.kind === "todo" && record.assignee === role) continue;
222
225
  items.push({ kind: "unread", detail: `${record.id} in ${record.group} from ${record.from}: ${firstLine(record.text)}` });
223
226
  }
@@ -380,6 +383,8 @@ function ready(where, options) {
380
383
  `# Shift note: ${role || path.basename(where.worktree)}`,
381
384
  "",
382
385
  `Written ${stamp} in ${result.worktree}.`,
386
+ // A shift the role started itself; the patrol may nudge it to resume (#307 D4).
387
+ options.wake ? "Self-initiated: this shift armed `keel shift ready --wake`." : "",
383
388
  options.forceReason ? `\nLeft as is (${options.forceReason}):\n${result.items.map((item) => `- ${item.kind}: ${item.detail}`).join("\n")}` : "",
384
389
  "",
385
390
  ].join("\n");