@christang/keel 5.152.0 → 5.153.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.152.0",
3
+ "version": "5.153.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,4 +1,4 @@
1
- <!-- keel:start version=5.152.0 -->
1
+ <!-- keel:start version=5.153.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.152.0",
3
+ "version": "5.153.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.152.0",
9
+ "version": "5.153.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.152.0",
5
+ "version": "5.153.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.152.0",
3
+ "version": "5.153.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.152.0",
3
+ "version": "5.153.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",
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.152.0"
53
- PROTOCOL_VERSION = "5.152.0"
52
+ PACKAGE_VERSION = "5.153.0"
53
+ PROTOCOL_VERSION = "5.153.0"
54
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -3020,6 +3020,86 @@ def validate_patrol_exit_says_who_acts_scenario() -> int:
3020
3020
  return 0
3021
3021
 
3022
3022
 
3023
+ def validate_patrol_next_scenario() -> int:
3024
+ """Issue #356: a patrol recommends when to run next.
3025
+
3026
+ With `cadence: adaptive` the first matching rule picks the delay — risk,
3027
+ quota, night, busy, idle — and each case has a failing arm: the same
3028
+ fixture without its condition gives another rule. A fixed `every:` keeps
3029
+ today's cadence.
3030
+ """
3031
+ label = "patrol-next:"
3032
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-356-") as raw:
3033
+ base = Path(raw)
3034
+ rtl, verify, env, _ = shift_scratch(base)
3035
+
3036
+ def config(extra: str) -> None:
3037
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n" + extra)
3038
+
3039
+ def patrol(*args: str) -> dict:
3040
+ result = run_keel(rtl, "patrol", "--json", *args, env=env)
3041
+ return json.loads(result.stdout) if result.stdout.strip().startswith("{") else {"raw": result.stdout + result.stderr}
3042
+
3043
+ def expect(name: str, payload: dict, rule: str, seconds: int | None) -> bool:
3044
+ if payload.get("next_rule") != rule:
3045
+ report(f"{label} {name}: next_rule {payload.get('next_rule')!r}, not {rule!r}: {payload!r}")
3046
+ return False
3047
+ if seconds is not None and payload.get("next_after_s") != seconds:
3048
+ report(f"{label} {name}: next_after_s {payload.get('next_after_s')!r}, not {seconds}")
3049
+ return False
3050
+ return True
3051
+
3052
+ config("")
3053
+ if not expect("fixed", patrol(), "fixed", 3600):
3054
+ return 1
3055
+ config(" cadence: adaptive\n")
3056
+ if not expect("idle", patrol(), "idle", 3 * 3600):
3057
+ return 1
3058
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify, env=env,
3059
+ text=True, capture_output=True, check=False,
3060
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": "v1", "source": "startup"}))
3061
+ if not expect("busy", patrol(), "busy", 3600):
3062
+ return 1
3063
+ patrol("--quota", "92")
3064
+ if not expect("quota", patrol("--quota", "92"), "quota", 4 * 3600):
3065
+ return 1
3066
+ # The risk is a clean checkout turning dirty, so the config is committed first.
3067
+ subprocess.run(["git", "add", "-A"], cwd=rtl, check=True, capture_output=True)
3068
+ subprocess.run(["git", "commit", "-q", "-m", "cadence"], cwd=rtl, check=True, capture_output=True)
3069
+ patrol("--since-last")
3070
+ (rtl / "stray.txt").write_text("x\n")
3071
+ if not expect("risk", patrol("--since-last"), "risk", 30 * 60):
3072
+ return 1
3073
+ (rtl / "stray.txt").unlink()
3074
+ patrol("--since-last")
3075
+ now = datetime.now()
3076
+ start = (now - timedelta(minutes=30)).strftime("%H:%M")
3077
+ end_at = now + timedelta(minutes=90)
3078
+ config(f" cadence: adaptive\n idle: 2h\n quiet: {start}-{end_at.strftime('%H:%M')}\n")
3079
+ night = patrol()
3080
+ if not expect("night", night, "night", None):
3081
+ return 1
3082
+ if not 80 * 60 <= night.get("next_after_s", 0) <= 91 * 60:
3083
+ report(f"{label} night: next_after_s {night.get('next_after_s')} does not end at the window's end.")
3084
+ return 1
3085
+ config(" cadence: adaptive\n busy: 45m\n min: 50m\n")
3086
+ if not expect("busy clamped to min", patrol(), "busy", 50 * 60):
3087
+ return 1
3088
+ text = run_keel(rtl, "patrol", env=env).stdout
3089
+ if not re.search(r"^next: 50m \(busy\)$", text, re.M):
3090
+ report(f"{label} the text output has no `next: 50m (busy)` line: {text!r}")
3091
+ return 1
3092
+ log = (mailbox_common_dir(rtl) / "keel-chat" / "patrol" / "log" / "rtl.log").read_text(encoding="utf-8").splitlines()
3093
+ if not log[-1].endswith("next=50m (busy)"):
3094
+ report(f"{label} the run log does not record the next run: {log[-1]!r}")
3095
+ return 1
3096
+ if "patrol-next" not in {name for name, _ in SCENARIOS}:
3097
+ report(f"{label} scenario is not registered.")
3098
+ return 1
3099
+ report("patrol-next scenario passed.")
3100
+ return 0
3101
+
3102
+
3023
3103
  def validate_patrol_nudge_scenario() -> int:
3024
3104
  """Issues #307 part 1 and #313: the patrol nudges idle roles directly.
3025
3105
 
@@ -42045,6 +42125,7 @@ SCENARIOS: tuple = (
42045
42125
  ("chat-ack", validate_chat_ack_scenario),
42046
42126
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
42047
42127
  ("patrol-since-last", validate_patrol_since_last_scenario),
42128
+ ("patrol-next", validate_patrol_next_scenario),
42048
42129
  ("patrol-exit-says-who-acts", validate_patrol_exit_says_who_acts_scenario),
42049
42130
  ("patrol-nudge", validate_patrol_nudge_scenario),
42050
42131
  ("patrol-escalate", validate_patrol_escalate_scenario),
@@ -940,8 +940,28 @@ function readPatrolDeclaration(repo) {
940
940
  if (/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(block.model)) model = block.model;
941
941
  else ignored.push(`model \`${block.model}\` is not a model id`);
942
942
  }
943
+ // `cadence: adaptive` turns on the next-run rules (#356); each override is a
944
+ // flat key under `patrol:`, and one that does not read is ignored by name.
945
+ const cadence = { adaptive: block.cadence === "adaptive", risk: 1800, quota: 14400, busy: 3600, idle: 10800, quiet: null, min: null, max: null };
946
+ if (block.cadence !== undefined && block.cadence !== "adaptive") ignored.push(`cadence \`${block.cadence}\` is not adaptive`);
947
+ for (const key of ["risk", "quota", "busy", "idle", "min", "max"]) {
948
+ if (block[key] === undefined) continue;
949
+ const seconds = durationSeconds(block[key]);
950
+ if (seconds === null) ignored.push(`${key} \`${block[key]}\` is not a duration such as 30m`);
951
+ else cadence[key] = seconds;
952
+ }
953
+ if (block.quiet !== undefined) {
954
+ const window = String(block.quiet).match(/^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/);
955
+ if (window) cadence.quiet = { start: Number(window[1]) * 60 + Number(window[2]), end: Number(window[3]) * 60 + Number(window[4]) };
956
+ else ignored.push(`quiet \`${block.quiet}\` is not a window such as 23:00-08:30`);
957
+ }
943
958
  const message = ignored.length ? `keel/config.yaml patrol: ${ignored.join("; ")}, so it is ignored.` : null;
944
- return { declared: true, role: block.role, every: block.every, hostTask, model, message };
959
+ return { declared: true, role: block.role, every: block.every, hostTask, model, message, cadence };
960
+ }
961
+
962
+ function durationSeconds(value) {
963
+ const match = String(value || "").match(/^(\d+)([smhd])$/);
964
+ return match ? Number(match[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[match[2]] : null;
945
965
  }
946
966
 
947
967
  function patrolReminder(patrol) {
@@ -957,6 +977,7 @@ module.exports = {
957
977
  readOwnerLanguage,
958
978
  ownerLanguageRule,
959
979
  readPatrolDeclaration,
980
+ durationSeconds,
960
981
  patrolReminder,
961
982
  readIssueRoles,
962
983
  readReadOnlyRoles,
@@ -507,7 +507,11 @@ function runPatrol(argv) {
507
507
  // Only risks reach the coordinator (#307 part 3 D3).
508
508
  if (options.notify && result.risks.length) result.notified = notifyRisks(where, role, result.risks).id;
509
509
  }
510
- process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : render(result)}\n`);
510
+ const next = recommendNext(where, role, result, options);
511
+ result.next_after_s = next.seconds;
512
+ result.next_rule = next.rule;
513
+ result.next_at = store.isoLocal(new Date(Date.now() + next.seconds * 1000));
514
+ process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : `${render(result)}\nnext: ${formatDuration(next.seconds)} (${next.rule})`}\n`);
511
515
  const changed = result.sinceLast && result.sinceLast.changes.length;
512
516
  const own = result.held.some((held) => held.from === role);
513
517
  const recorded = result.notices.length || result.held.length || changed || (result.nudges || []).length;
@@ -523,6 +527,56 @@ function runPatrol(argv) {
523
527
  }
524
528
  }
525
529
 
530
+ // When to run next (#356): `every:` as a fixed cadence, or with
531
+ // `cadence: adaptive` the first matching rule. The runner that re-arms on it
532
+ // is the caller's; this only recommends.
533
+ function recommendNext(where, role, result, options, now = new Date()) {
534
+ const { readPatrolDeclaration, durationSeconds } = require("./config");
535
+ const declaration = readPatrolDeclaration(where.worktree);
536
+ const cadence = declaration.cadence;
537
+ if (!cadence || !cadence.adaptive) {
538
+ const every = durationSeconds(declaration.every) || 3600;
539
+ return { seconds: every, rule: "fixed" };
540
+ }
541
+ const active = new Set(result.roles.filter((r) => !r.idle).map((r) => r.role));
542
+ const assigned = [
543
+ ...store.openTodos(where, {}).map((todo) => todo.assignee),
544
+ ...store.openWaits(where, role).map((waitRecord) => waitRecord.from),
545
+ ];
546
+ let pick;
547
+ if (result.risks.length) pick = { seconds: cadence.risk, rule: "risk" };
548
+ else if (options.quota !== null && options.quota >= 90) pick = { seconds: cadence.quota, rule: "quota" };
549
+ else if (cadence.quiet && inWindow(cadence.quiet, now)) {
550
+ return { seconds: untilWindowEnd(cadence.quiet, now), rule: "night" };
551
+ } else if ([...active].some((name) => name !== role) || assigned.some((name) => active.has(name))) pick = { seconds: cadence.busy, rule: "busy" };
552
+ else pick = { seconds: cadence.idle, rule: "idle" };
553
+ if (cadence.min !== null) pick.seconds = Math.max(pick.seconds, cadence.min);
554
+ if (cadence.max !== null) pick.seconds = Math.min(pick.seconds, cadence.max);
555
+ return pick;
556
+ }
557
+
558
+ function minuteOfDay(now) {
559
+ return now.getHours() * 60 + now.getMinutes();
560
+ }
561
+
562
+ function inWindow(window, now) {
563
+ const minute = minuteOfDay(now);
564
+ return window.start <= window.end
565
+ ? minute >= window.start && minute < window.end
566
+ : minute >= window.start || minute < window.end;
567
+ }
568
+
569
+ function untilWindowEnd(window, now) {
570
+ const minutes = (window.end - minuteOfDay(now) + 1440) % 1440 || 1440;
571
+ return minutes * 60 - now.getSeconds();
572
+ }
573
+
574
+ function formatDuration(seconds) {
575
+ if (seconds % 3600 === 0) return `${seconds / 3600}h`;
576
+ if (seconds % 60 === 0) return `${seconds / 60}m`;
577
+ return `${Math.round(seconds / 60)}m`;
578
+ }
579
+
526
580
  // One line per run, so a silent run can be audited (#307 part 3 D4).
527
581
  function appendRunLog(where, role, code, result) {
528
582
  try {
@@ -530,7 +584,8 @@ function appendRunLog(where, role, code, result) {
530
584
  fs.mkdirSync(path.dirname(file), { recursive: true });
531
585
  const changes = result.sinceLast ? result.sinceLast.changes.length : 0;
532
586
  fs.appendFileSync(file, `${store.isoLocal(new Date())} exit=${code} changes=${changes} nudges=${(result.nudges || []).length} `
533
- + `risks=${result.risks.length} notified=${result.notified ? "yes" : "no"}\n`);
587
+ + `risks=${result.risks.length} notified=${result.notified ? "yes" : "no"}`
588
+ + `${result.next_rule ? ` next=${formatDuration(result.next_after_s)} (${result.next_rule})` : ""}\n`);
534
589
  } catch {
535
590
  // The log is for audit; failing to write it never fails the patrol.
536
591
  }