@christang/keel 5.120.0 → 5.121.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
@@ -799,6 +799,14 @@ writes that snapshot on every run, and exits 2 only when something changed. Add
799
799
  changes go to the coordinator as one direct message from `keel-patrol`, which wakes its session, so
800
800
  the scheduled run needs no model judgment and no session id.
801
801
 
802
+ `keel patrol --nudge` goes further and nudges each idle role itself, with one direct message from
803
+ `keel-patrol` that wakes its session (#307): when records addressed to it have waited longer than
804
+ `--idle` (at most every two hours); when the host reports with `--context <role>=<percent>` that its
805
+ context is at or above `--shift-at` (default 50) and nothing waits, telling it to change its own shift
806
+ with `keel shift ready --wake` (at most every six hours); and when a note it filed with `ready --wake`
807
+ was never resumed. A note filed without `--wake` — a coordinator parking a role — is left alone, and
808
+ Keel's own messages never count as waiting.
809
+
802
810
  With `--issues`, patrol also routes issue updates (#242): `issue_roles:` in `keel/config.yaml`
803
811
  maps a label to a role, and each role gets one direct message per update of an issue carrying its
804
812
  label — so a handoff labelled `role:verify` reaches `verify` without a second message.
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.120.0 -->
1
+ <!-- keel:start version=5.121.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.121.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.121.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.121.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.121.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.121.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.121.0"
51
+ PROTOCOL_VERSION = "5.121.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
@@ -2833,6 +2833,92 @@ def validate_patrol_since_last_scenario() -> int:
2833
2833
  return 0
2834
2834
 
2835
2835
 
2836
+ def validate_patrol_nudge_scenario() -> int:
2837
+ """Issue #307 part 1: the patrol nudges idle roles directly, rate-limited.
2838
+
2839
+ Unread addressed records, a host-reported context share, and a
2840
+ self-initiated shift note each nudge once; a parked note and the
2841
+ patrol's own messages never do.
2842
+ """
2843
+ label = "patrol-nudge:"
2844
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-nudge-") as raw:
2845
+ base = Path(raw)
2846
+ rtl, verify, env, _ = shift_scratch(base)
2847
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "1"}
2848
+ lint = chat_worktree(rtl, base / "lint")
2849
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=lint, check=True, capture_output=True)
2850
+ run_keel(lint, "chat", "role", "--set", "lint", env=env)
2851
+ run_keel(rtl, "chat", "post", "soc", "@verify please rerun R007", env=env)
2852
+ time.sleep(1.2)
2853
+
2854
+ def nudge(*args: str) -> subprocess.CompletedProcess[str]:
2855
+ return run_keel(rtl, "patrol", "--nudge", "--idle", "1s", *args, env=env)
2856
+
2857
+ def nudged(result: subprocess.CompletedProcess[str]) -> list[str]:
2858
+ return [line for line in result.stdout.splitlines() if line.startswith("nudged ")]
2859
+
2860
+ seen: list[str] = []
2861
+ first = nudge("--context", "lint=40")
2862
+ seen += nudged(first)
2863
+ if "nudged verify: unread" not in nudged(first):
2864
+ report(f"{label} verify was not nudged for unread: {first.stdout!r} {first.stderr!r}")
2865
+ return 1
2866
+ if any(line.startswith("nudged lint") for line in nudged(first)):
2867
+ report(f"{label} lint was nudged below the shift threshold: {nudged(first)!r}")
2868
+ return 1
2869
+ if first.returncode != 2:
2870
+ report(f"{label} a run that nudged exited {first.returncode}.")
2871
+ return 1
2872
+ if not chat_records_with(rtl, "dm-keel-patrol--verify", "keel chat unread"):
2873
+ report(f"{label} no keel-patrol record reached verify.")
2874
+ return 1
2875
+ if run_keel(verify, "chat", "notice", "--check", env=env).returncode != 0:
2876
+ report(f"{label} the nudge does not wake verify.")
2877
+ return 1
2878
+ second = nudge("--context", "lint=62")
2879
+ seen += nudged(second)
2880
+ if nudged(second) != ["nudged lint: shift"]:
2881
+ report(f"{label} the second run should nudge only lint's shift: {second.stdout!r}")
2882
+ return 1
2883
+ shift_text = "\n".join(chat_records_with(rtl, "dm-keel-patrol--lint", "context is at 62%"))
2884
+ if "keel shift ready --wake" not in shift_text:
2885
+ report(f"{label} the shift nudge does not name keel shift ready --wake: {shift_text!r}")
2886
+ return 1
2887
+ if "Remote Control" not in shift_text:
2888
+ report(f"{label} the shift nudge does not name Remote Control: {shift_text!r}")
2889
+ return 1
2890
+ time.sleep(1.2)
2891
+ third = nudge("--context", "lint=62")
2892
+ seen += nudged(third)
2893
+ if nudged(third):
2894
+ report(f"{label} a run within the rate limits nudged: {nudged(third)!r}")
2895
+ return 1
2896
+ if third.returncode != 0:
2897
+ report(f"{label} a run that nudged nobody exited {third.returncode}.")
2898
+ return 1
2899
+ armed = run_keel(lint, "shift", "ready", "--wake", "lint note", env=env)
2900
+ if armed.returncode != 0:
2901
+ report(f"{label} lint's ready --wake failed: {armed.stderr}")
2902
+ return 1
2903
+ if run_keel(verify, "shift", "ready", "--force-reason", "parked by the coordinator", "verify parked", env=env).returncode != 0:
2904
+ report(f"{label} verify's ready failed.")
2905
+ return 1
2906
+ time.sleep(1.2)
2907
+ fourth = nudge()
2908
+ seen += nudged(fourth)
2909
+ if "nudged lint: resume" not in nudged(fourth):
2910
+ report(f"{label} lint's self-initiated note was not nudged to resume: {fourth.stdout!r}")
2911
+ return 1
2912
+ if "nudged verify: resume" in nudged(fourth):
2913
+ report(f"{label} verify's parked note was nudged to resume.")
2914
+ return 1
2915
+ if "nudged lint: unread" in seen:
2916
+ report(f"{label} lint was nudged over the patrol's own message.")
2917
+ return 1
2918
+ report("patrol-nudge scenario passed.")
2919
+ return 0
2920
+
2921
+
2836
2922
  def validate_coordinator_patrol_scenario() -> int:
2837
2923
  """Issue #260: declared waits, and a patrol that notifies once.
2838
2924
 
@@ -39907,6 +39993,7 @@ SCENARIOS: tuple = (
39907
39993
  ("chat-ack", validate_chat_ack_scenario),
39908
39994
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39909
39995
  ("patrol-since-last", validate_patrol_since_last_scenario),
39996
+ ("patrol-nudge", validate_patrol_nudge_scenario),
39910
39997
  ("patrol-host-task", validate_patrol_host_task_scenario),
39911
39998
  ("patrol-rearm", validate_patrol_rearm_scenario),
39912
39999
  ("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;
@@ -182,6 +182,88 @@ function sinceLast(where, role, result, options) {
182
182
  return { baseline: false, changes };
183
183
  }
184
184
 
185
+ // --- nudges (#307 part 1) -----------------------------------------------------------
186
+ //
187
+ // The patrol nudges an idle role itself, with one direct message from
188
+ // `keel-patrol` that wakes its session (D1-D5). Keel's own records never count
189
+ // as waiting, so a nudge cannot cause the next one.
190
+
191
+ const KEEL_SENDERS = new Set([NOTIFY_SENDER, "keel-shift", "keel"]);
192
+ const UNREAD_EVERY_MS = 2 * 60 * 60 * 1000;
193
+ const SHIFT_EVERY_MS = 6 * 60 * 60 * 1000;
194
+ const SELF_INITIATED = "Self-initiated: this shift armed `keel shift ready --wake`.";
195
+
196
+ function parseContexts(values) {
197
+ const contexts = new Map();
198
+ for (const value of values) {
199
+ const match = String(value).match(/^([a-z0-9][a-z0-9-]{0,31})=(\d{1,3}(?:\.\d+)?)%?$/);
200
+ if (!match) throw new PatrolError(`--context ${value} is not <role>=<percent>.`);
201
+ contexts.set(match[1], Number(match[2]));
202
+ }
203
+ return contexts;
204
+ }
205
+
206
+ function sendNudge(where, role, kind, text) {
207
+ const group = store.directName(NOTIFY_SENDER, role);
208
+ if (!store.groupState(store.readLog(where, group)).exists) {
209
+ store.createGroup(where, NOTIFY_SENDER, group, [role], { direct: true });
210
+ }
211
+ store.writeRecord(where, { group, kind: "message", from: NOTIFY_SENDER, refs: ["keel-patrol-nudge"], text });
212
+ return { role, kind, text };
213
+ }
214
+
215
+ function nudgeRoles(where, patroller, options) {
216
+ const stateFile = path.join(where.root, "patrol", "nudges.json");
217
+ const state = store.readJsonFile(stateFile);
218
+ const now = Date.now();
219
+ const idleBefore = parseSince(options.idle);
220
+ const sent = [];
221
+ const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))]
222
+ .filter((role) => role !== patroller).sort();
223
+ for (const role of roles) {
224
+ const last = Date.parse(notice.presenceOf(where, role).last_active || "");
225
+ if (!Number.isNaN(last) && last >= idleBefore) continue;
226
+ const mine = state[role] || {};
227
+ const waiting = store.unread(where, role)
228
+ .filter((record) => store.wakes(record, role) && !KEEL_SENDERS.has(record.from))
229
+ .sort((a, b) => (a.id < b.id ? -1 : 1));
230
+ const note = path.join(where.root, "shift", `${role}.md`);
231
+ const noteText = fs.existsSync(note) ? fs.readFileSync(note, "utf8") : null;
232
+ if (waiting.length) {
233
+ const oldest = Date.parse(waiting[0].created || "");
234
+ const recent = Date.parse(mine.unread || "");
235
+ if (!Number.isNaN(oldest) && oldest < idleBefore && (Number.isNaN(recent) || now - recent >= UNREAD_EVERY_MS)) {
236
+ sent.push(sendNudge(where, role, "unread",
237
+ `${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));
239
+ }
240
+ } else if (!noteText && options.contexts.has(role) && options.contexts.get(role) >= options.shiftAt) {
241
+ const recent = Date.parse(mine.shift || "");
242
+ if (Number.isNaN(recent) || now - recent >= SHIFT_EVERY_MS) {
243
+ sent.push(sendNudge(where, role, "shift",
244
+ `${role}: your context is at ${options.contexts.get(role)}%. Change your own shift: \`keel shift check\`, `
245
+ + "then `keel shift ready --wake \"<note>\"`, then clear this session. A session serving Remote Control "
246
+ + "cannot be cleared: turn it off, clear, then turn it back on."));
247
+ mine.shift = store.isoLocal(new Date(now));
248
+ }
249
+ }
250
+ if (noteText && noteText.includes(SELF_INITIATED)) {
251
+ const written = fs.statSync(note).mtime;
252
+ const woken = store.readLog(where, store.directName("keel-shift", role))
253
+ .some((record) => record.from === "keel-shift" && Date.parse(record.created || "") >= written.getTime() - 1000);
254
+ const stamp = store.isoLocal(written);
255
+ if (written.getTime() < idleBefore && !woken && mine.resume !== stamp) {
256
+ sent.push(sendNudge(where, role, "resume",
257
+ `${role}: your previous shift left a note at ${stamp}; run \`keel context\`, then \`keel shift resume\`.`));
258
+ mine.resume = stamp;
259
+ }
260
+ }
261
+ state[role] = mine;
262
+ }
263
+ if (sent.length) store.writeJsonAtomic(where, stateFile, state);
264
+ return sent;
265
+ }
266
+
185
267
  function notifyChanges(where, role, changes) {
186
268
  const group = store.directName(NOTIFY_SENDER, role);
187
269
  if (!store.groupState(store.readLog(where, group)).exists) {
@@ -197,6 +279,7 @@ function render(result) {
197
279
  if (result.sinceLast && result.sinceLast.baseline) lines.push("keel patrol: baseline recorded.");
198
280
  else if (!result.notices.length && !result.held.length && !changes.length) lines.push("keel patrol: nothing new.");
199
281
  for (const change of changes) lines.push(`changed: ${change}`);
282
+ for (const sent of result.nudges || []) lines.push(`nudged ${sent.role}: ${sent.kind}`);
200
283
  for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
201
284
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
202
285
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
@@ -298,13 +381,16 @@ function runPatrol(argv) {
298
381
  throw error;
299
382
  }
300
383
  }
301
- const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false };
384
+ const options = { repo: process.cwd(), issues: null, idle: "30m", json: false, sinceLast: false, notify: false, nudge: false, context: [], shiftAt: 50 };
302
385
  try {
303
386
  for (let index = 0; index < argv.length; index += 1) {
304
387
  const arg = argv[index];
305
388
  if (arg === "--json") options.json = true;
306
389
  else if (arg === "--since-last") options.sinceLast = true;
307
390
  else if (arg === "--notify") options.notify = true;
391
+ else if (arg === "--nudge") options.nudge = true;
392
+ else if (arg === "--context") options.context.push(argv[++index] || "");
393
+ else if (arg === "--shift-at") options.shiftAt = Number(argv[++index]);
308
394
  else if (arg === "--help" || arg === "-h") {
309
395
  process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
310
396
  return EXIT_QUIET;
@@ -315,18 +401,21 @@ function runPatrol(argv) {
315
401
  } else throw new PatrolError(`Unknown argument ${arg}. ${USAGE}`);
316
402
  }
317
403
  if (options.notify && !options.sinceLast) throw new PatrolError("--notify sends what changed, so it needs --since-last.");
404
+ if (!(options.shiftAt > 0 && options.shiftAt <= 100)) throw new PatrolError("--shift-at needs a percentage from 1 to 100.");
405
+ options.contexts = parseContexts(options.context);
318
406
  if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
319
407
  options.issues = readIssues(options.issues);
320
408
  const where = store.requireLocation(path.resolve(options.repo));
321
409
  const role = store.requireRole(where);
322
410
  const result = patrol(where, role, options);
411
+ if (options.nudge) result.nudges = nudgeRoles(where, role, options);
323
412
  if (options.sinceLast) {
324
413
  result.sinceLast = sinceLast(where, role, result, options);
325
414
  if (options.notify && result.sinceLast.changes.length) result.notified = notifyChanges(where, role, result.sinceLast.changes).id;
326
415
  }
327
416
  process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
328
417
  const changed = result.sinceLast && result.sinceLast.changes.length;
329
- return result.notices.length || result.held.length || changed ? EXIT_WROTE : EXIT_QUIET;
418
+ return result.notices.length || result.held.length || changed || (result.nudges || []).length ? EXIT_WROTE : EXIT_QUIET;
330
419
  } catch (error) {
331
420
  if (error instanceof PatrolError || error instanceof store.ChatError) {
332
421
  process.stderr.write(`keel patrol: ${error.message}\n`);
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");