@christang/keel 5.121.0 → 5.123.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,15 @@ 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
+ The host can also pass the weekly quota's percent used with `--quota <percent>`: each threshold in
805
+ `--quota-alerts` (default `90,95,99`) becomes a risk once per quota period, a drop in the figure starts
806
+ a new period, and at `--quota-quiet-at` (default 90) or above, `--nudge` sends nothing, since every
807
+ nudge wakes a large session.
801
808
 
802
809
  `keel patrol --nudge` goes further and nudges each idle role itself, with one direct message from
803
810
  `keel-patrol` that wakes its session (#307): when records addressed to it have waited longer than
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.121.0 -->
1
+ <!-- keel:start version=5.123.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.121.0",
3
+ "version": "5.123.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.121.0",
9
+ "version": "5.123.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.121.0",
5
+ "version": "5.123.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.121.0",
3
+ "version": "5.123.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.121.0",
3
+ "version": "5.123.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.121.0"
51
- PROTOCOL_VERSION = "5.121.0"
50
+ PACKAGE_VERSION = "5.123.0"
51
+ PROTOCOL_VERSION = "5.123.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,8 +2820,8 @@ 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
@@ -2919,6 +2913,113 @@ def validate_patrol_nudge_scenario() -> int:
2919
2913
  return 0
2920
2914
 
2921
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
+
2976
+ def validate_patrol_quota_scenario() -> int:
2977
+ """Issue #307 part 2: quota thresholds once per period; nudges pause near the limit."""
2978
+ label = "patrol-quota:"
2979
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-quota-") as raw:
2980
+ base = Path(raw)
2981
+ rtl, verify, env, _ = shift_scratch(base)
2982
+ env = {**env, "KEEL_PATROL_UNREAD_EVERY_MS": "1"}
2983
+ run_keel(rtl, "chat", "post", "soc", "@verify rerun R007 please", env=env)
2984
+ time.sleep(1.2)
2985
+
2986
+ def patrol(quota: str) -> subprocess.CompletedProcess[str]:
2987
+ return run_keel(rtl, "patrol", "--since-last", "--notify", "--nudge", "--idle", "1s", "--quota", quota, env=env)
2988
+
2989
+ expected = {"50": None, "91": "past 90%", "93": None, "96": "past 95%", "10": None, "92": "past 90%"}
2990
+ for quota, want in expected.items():
2991
+ result = patrol(quota)
2992
+ lines = [line for line in result.stdout.splitlines() if line.startswith("risk: weekly quota")]
2993
+ if want is None and lines:
2994
+ report(f"{label} quota {quota} reported {lines!r}.")
2995
+ return 1
2996
+ if want is not None and len(lines) != 1:
2997
+ report(f"{label} quota {quota} should report one quota line: {result.stdout!r} {result.stderr!r}")
2998
+ return 1
2999
+ if want is not None and want not in lines[0]:
3000
+ report(f"{label} quota {quota} should report {want!r}: {lines[0]!r}")
3001
+ return 1
3002
+ if quota == "50" and "nudged verify: unread" not in result.stdout:
3003
+ report(f"{label} verify was not nudged at 50%: {result.stdout!r}")
3004
+ return 1
3005
+ if quota == "91" and "nudged verify" in result.stdout:
3006
+ report(f"{label} verify was nudged at 91%: {result.stdout!r}")
3007
+ return 1
3008
+ if quota == "91" and "nudges paused: quota at 91%" not in result.stdout:
3009
+ report(f"{label} the pause is not said at 91%: {result.stdout!r}")
3010
+ return 1
3011
+ sent = chat_records_with(rtl, "dm-keel-patrol--rtl", "weekly quota")
3012
+ if len(sent) != 3:
3013
+ report(f"{label} expected three quota messages to rtl, found {len(sent)}.")
3014
+ return 1
3015
+ refused = run_keel(rtl, "patrol", "--quota", "120", env=env)
3016
+ if refused.returncode != 1:
3017
+ report(f"{label} --quota 120 exited {refused.returncode}.")
3018
+ return 1
3019
+ report("patrol-quota scenario passed.")
3020
+ return 0
3021
+
3022
+
2922
3023
  def validate_coordinator_patrol_scenario() -> int:
2923
3024
  """Issue #260: declared waits, and a patrol that notifies once.
2924
3025
 
@@ -39994,6 +40095,8 @@ SCENARIOS: tuple = (
39994
40095
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39995
40096
  ("patrol-since-last", validate_patrol_since_last_scenario),
39996
40097
  ("patrol-nudge", validate_patrol_nudge_scenario),
40098
+ ("patrol-escalate", validate_patrol_escalate_scenario),
40099
+ ("patrol-quota", validate_patrol_quota_scenario),
39997
40100
  ("patrol-host-task", validate_patrol_host_task_scenario),
39998
40101
  ("patrol-rearm", validate_patrol_rearm_scenario),
39999
40102
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
@@ -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,7 +181,19 @@ 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
199
  // --- nudges (#307 part 1) -----------------------------------------------------------
@@ -189,7 +203,7 @@ function sinceLast(where, role, result, options) {
189
203
  // as waiting, so a nudge cannot cause the next one.
190
204
 
191
205
  const KEEL_SENDERS = new Set([NOTIFY_SENDER, "keel-shift", "keel"]);
192
- const UNREAD_EVERY_MS = 2 * 60 * 60 * 1000;
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;
193
207
  const SHIFT_EVERY_MS = 6 * 60 * 60 * 1000;
194
208
  const SELF_INITIATED = "Self-initiated: this shift armed `keel shift ready --wake`.";
195
209
 
@@ -218,6 +232,7 @@ function nudgeRoles(where, patroller, options) {
218
232
  const now = Date.now();
219
233
  const idleBefore = parseSince(options.idle);
220
234
  const sent = [];
235
+ const escalations = [];
221
236
  const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))]
222
237
  .filter((role) => role !== patroller).sort();
223
238
  for (const role of roles) {
@@ -235,9 +250,17 @@ function nudgeRoles(where, patroller, options) {
235
250
  if (!Number.isNaN(oldest) && oldest < idleBefore && (Number.isNaN(recent) || now - recent >= UNREAD_EVERY_MS)) {
236
251
  sent.push(sendNudge(where, role, "unread",
237
252
  `${role}: ${waiting.length} record(s) addressed to you have waited since ${waiting[0].created}; read them with \`keel chat unread\`.`));
238
- mine.unread = store.isoLocal(new Date(now));
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();
239
259
  }
240
- } else if (!noteText && options.contexts.has(role) && options.contexts.get(role) >= options.shiftAt) {
260
+ } else {
261
+ mine.unanswered = 0;
262
+ }
263
+ if (!waiting.length && !noteText && options.contexts.has(role) && options.contexts.get(role) >= options.shiftAt) {
241
264
  const recent = Date.parse(mine.shift || "");
242
265
  if (Number.isNaN(recent) || now - recent >= SHIFT_EVERY_MS) {
243
266
  sent.push(sendNudge(where, role, "shift",
@@ -260,16 +283,32 @@ function nudgeRoles(where, patroller, options) {
260
283
  }
261
284
  state[role] = mine;
262
285
  }
263
- if (sent.length) store.writeJsonAtomic(where, stateFile, state);
264
- return sent;
286
+ store.writeJsonAtomic(where, stateFile, state);
287
+ return { sent, escalations };
288
+ }
289
+
290
+ // --- quota thresholds (#307 part 2) ---------------------------------------------------
291
+ //
292
+ // The host reports the weekly quota's percent used; each threshold is a risk
293
+ // once per period, and a drop in the figure starts a new period (D2).
294
+ function quotaRisk(where, options) {
295
+ if (options.quota === null) return null;
296
+ const file = path.join(where.root, "patrol", "quota.json");
297
+ const state = store.readJsonFile(file);
298
+ let reported = Array.isArray(state.reported) ? state.reported : [];
299
+ if (typeof state.last === "number" && options.quota < state.last) reported = [];
300
+ const reached = options.quotaAlerts.filter((threshold) => threshold <= options.quota && !reported.includes(threshold));
301
+ store.writeJsonAtomic(where, file, { last: options.quota, reported: [...reported, ...reached].sort((a, b) => a - b) });
302
+ if (!reached.length) return null;
303
+ return `weekly quota is at ${options.quota}%, past ${Math.max(...reached)}%`;
265
304
  }
266
305
 
267
- function notifyChanges(where, role, changes) {
306
+ function notifyRisks(where, role, risks) {
268
307
  const group = store.directName(NOTIFY_SENDER, role);
269
308
  if (!store.groupState(store.readLog(where, group)).exists) {
270
309
  store.createGroup(where, NOTIFY_SENDER, group, [role], { direct: true });
271
310
  }
272
- const text = [`Patrol ${store.isoLocal(new Date())}: what changed since the last run:`, ...changes.map((line) => `- changed: ${line}`)].join("\n");
311
+ const text = [`Patrol ${store.isoLocal(new Date())}: risks for the coordinator:`, ...risks.map((line) => `- risk: ${line}`)].join("\n");
273
312
  return store.writeRecord(where, { group, kind: "message", from: NOTIFY_SENDER, refs: [NOTIFY_SENDER], text });
274
313
  }
275
314
 
@@ -280,6 +319,8 @@ function render(result) {
280
319
  else if (!result.notices.length && !result.held.length && !changes.length) lines.push("keel patrol: nothing new.");
281
320
  for (const change of changes) lines.push(`changed: ${change}`);
282
321
  for (const sent of result.nudges || []) lines.push(`nudged ${sent.role}: ${sent.kind}`);
322
+ for (const risk of result.risks || []) lines.push(`risk: ${risk}`);
323
+ if (result.paused) lines.push(result.paused);
283
324
  for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
284
325
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
285
326
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
@@ -381,7 +422,7 @@ function runPatrol(argv) {
381
422
  throw error;
382
423
  }
383
424
  }
384
- const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false, nudge: false, context: [], shiftAt: 50 };
425
+ const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false, nudge: false, context: [], shiftAt: 50, diskFreeGb: null, diskMinGb: 20, quota: null, quotaAlerts: [90, 95, 99], quotaQuietAt: 90 };
385
426
  try {
386
427
  for (let index = 0; index < argv.length; index += 1) {
387
428
  const arg = argv[index];
@@ -391,6 +432,11 @@ function runPatrol(argv) {
391
432
  else if (arg === "--nudge") options.nudge = true;
392
433
  else if (arg === "--context") options.context.push(argv[++index] || "");
393
434
  else if (arg === "--shift-at") options.shiftAt = Number(argv[++index]);
435
+ else if (arg === "--disk-free-gb") options.diskFreeGb = Number(argv[++index]);
436
+ else if (arg === "--disk-min-gb") options.diskMinGb = Number(argv[++index]);
437
+ else if (arg === "--quota") options.quota = Number(argv[++index]);
438
+ else if (arg === "--quota-alerts") options.quotaAlerts = String(argv[++index] || "").split(",").map(Number);
439
+ else if (arg === "--quota-quiet-at") options.quotaQuietAt = Number(argv[++index]);
394
440
  else if (arg === "--help" || arg === "-h") {
395
441
  process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
396
442
  return EXIT_QUIET;
@@ -400,22 +446,42 @@ function runPatrol(argv) {
400
446
  options[arg.slice(2)] = value;
401
447
  } else throw new PatrolError(`Unknown argument ${arg}. ${USAGE}`);
402
448
  }
403
- if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends what changed, so it needs --since-last.");
449
+ if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends the risks found since the last run, so it needs --since-last.");
404
450
  if (!(options.shiftAt > 0 && options.shiftAt <= 100)) throw new PatrolError("--shift-at needs a percentage from 1 to 100.");
405
451
  options.contexts = parseContexts(options.context);
452
+ if (options.diskFreeGb !== null && !(options.diskFreeGb >= 0)) throw new PatrolError("--disk-free-gb needs a number of gigabytes.");
453
+ if (!(options.diskMinGb > 0)) throw new PatrolError("--disk-min-gb needs a positive number of gigabytes.");
454
+ const percent = (value) => Number.isFinite(value) && value >= 0 && value <= 100;
455
+ if (options.quota !== null && !percent(options.quota)) throw new PatrolError("--quota needs the percent used, from 0 to 100.");
456
+ if (!options.quotaAlerts.length || !options.quotaAlerts.every(percent)) throw new PatrolError("--quota-alerts needs percentages separated by commas, such as 90,95,99.");
457
+ if (!percent(options.quotaQuietAt)) throw new PatrolError("--quota-quiet-at needs a percentage from 0 to 100.");
406
458
  if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
407
459
  options.issues = readIssues(options.issues);
408
460
  const where = store.requireLocation(path.resolve(options.repo));
409
461
  const role = store.requireRole(where);
410
462
  const result = patrol(where, role, options);
411
- if (options.nudge) result.nudges = nudgeRoles(where, role, options);
463
+ result.risks = [];
464
+ const quota = quotaRisk(where, options);
465
+ if (quota) result.risks.push(quota);
466
+ // Near the limit nudges stop, since each wakes a large session (D3).
467
+ const quiet = options.quota !== null && options.quota >= options.quotaQuietAt;
468
+ if (options.nudge && quiet) result.paused = `nudges paused: quota at ${options.quota}%`;
469
+ if (options.nudge && !quiet) {
470
+ const nudged = nudgeRoles(where, role, options);
471
+ result.nudges = nudged.sent;
472
+ result.risks.push(...nudged.escalations);
473
+ }
412
474
  if (options.sinceLast) {
413
475
  result.sinceLast = sinceLast(where, role, result, options);
414
- if (options.notify && result.sinceLast.changes.length) result.notified = notifyChanges(where, role, result.sinceLast.changes).id;
476
+ result.risks.unshift(...result.sinceLast.risks);
477
+ // Only risks reach the coordinator (#307 part 3 D3).
478
+ if (options.notify && result.risks.length) result.notified = notifyRisks(where, role, result.risks).id;
415
479
  }
416
480
  process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
417
481
  const changed = result.sinceLast && result.sinceLast.changes.length;
418
- return result.notices.length || result.held.length || changed || (result.nudges || []).length ? EXIT_WROTE : EXIT_QUIET;
482
+ const code = result.notices.length || result.held.length || changed || (result.nudges || []).length || result.risks.length ? EXIT_WROTE : EXIT_QUIET;
483
+ appendRunLog(where, role, code, result);
484
+ return code;
419
485
  } catch (error) {
420
486
  if (error instanceof PatrolError || error instanceof store.ChatError) {
421
487
  process.stderr.write(`keel patrol: ${error.message}\n`);
@@ -425,4 +491,17 @@ function runPatrol(argv) {
425
491
  }
426
492
  }
427
493
 
494
+ // One line per run, so a silent run can be audited (#307 part 3 D4).
495
+ function appendRunLog(where, role, code, result) {
496
+ try {
497
+ const file = path.join(where.root, "patrol", "log", `${role}.log`);
498
+ fs.mkdirSync(path.dirname(file), { recursive: true });
499
+ const changes = result.sinceLast ? result.sinceLast.changes.length : 0;
500
+ fs.appendFileSync(file, `${store.isoLocal(new Date())} exit=${code} changes=${changes} nudges=${(result.nudges || []).length} `
501
+ + `risks=${result.risks.length} notified=${result.notified ? "yes" : "no"}\n`);
502
+ } catch {
503
+ // The log is for audit; failing to write it never fails the patrol.
504
+ }
505
+ }
506
+
428
507
  module.exports = { PatrolError, runPatrol, patrol };