@christang/keel 5.122.0 → 5.124.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
@@ -801,6 +801,10 @@ coordinator gets one direct message from `keel-patrol`, which wakes its session,
801
801
  `--disk-free-gb` dropping below `--disk-min-gb` (default 20), and a role that left two nudges in a row
802
802
  unanswered. Shift-status changes and new commits are printed, not sent. Every run appends one line to
803
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.
804
808
 
805
809
  `keel patrol --nudge` goes further and nudges each idle role itself, with one direct message from
806
810
  `keel-patrol` that wakes its session (#307): when records addressed to it have waited longer than
@@ -843,7 +847,7 @@ session, so it neither marks the role offline nor fires a `keel shift ready --wa
843
847
 
844
848
  ## The owner's language
845
849
 
846
- An agent reads mostly English — tool output, issues, specs, Keel's own output — and drifts into it when it answers you. Declare the language you want to be addressed in, and the rule is restated where replies are written: in `keel context`, the session-start note, and the chat hook on every prompt, in every worktree (#305). The agent may still work in any language; identifiers, commands, paths, and quoted output stay as they are.
850
+ An agent reads mostly English — tool output, issues, specs, Keel's own output — and drifts into it when it answers you. Declare the language you want to be addressed in, and the rule is restated where replies are written: in `keel context`, the session-start note, and the chat hook on every prompt, in every worktree (#305) — and, on Claude, after every 15 tool calls or 10 minutes of them, since a status update written mid-turn follows no prompt (#311). The agent may still work in any language; identifiers, commands, paths, and quoted output stay as they are.
847
851
 
848
852
  ```yaml
849
853
  owner_language: zh
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.122.0 -->
1
+ <!-- keel:start version=5.124.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.122.0",
3
+ "version": "5.124.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.122.0",
9
+ "version": "5.124.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.122.0",
5
+ "version": "5.124.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.122.0",
3
+ "version": "5.124.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.122.0",
3
+ "version": "5.124.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",
@@ -28,7 +28,7 @@ try {
28
28
  // Copied on its own: no hand-off.
29
29
  }
30
30
 
31
- const EVENTS = new Set(["session-start", "user-prompt-submit", "file-changed", "session-end"]);
31
+ const EVENTS = new Set(["session-start", "user-prompt-submit", "post-tool-use", "file-changed", "session-end"]);
32
32
  const TIMEOUT_MS = Number(process.env.KEEL_HOOK_TIMEOUT_MS || 8000) || 8000;
33
33
 
34
34
  function readStdin() {
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.122.0"
51
- PROTOCOL_VERSION = "5.122.0"
50
+ PACKAGE_VERSION = "5.124.0"
51
+ PROTOCOL_VERSION = "5.124.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
@@ -2973,6 +2973,53 @@ def validate_patrol_escalate_scenario() -> int:
2973
2973
  return 0
2974
2974
 
2975
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
+
2976
3023
  def validate_coordinator_patrol_scenario() -> int:
2977
3024
  """Issue #260: declared waits, and a patrol that notifies once.
2978
3025
 
@@ -6358,6 +6405,62 @@ def validate_owner_language_scenario() -> int:
6358
6405
  return 0
6359
6406
 
6360
6407
 
6408
+ def validate_owner_language_after_tools_scenario() -> int:
6409
+ """Issue #311: the owner's language is restated after runs of tool calls."""
6410
+ label = "owner-language-after-tools:"
6411
+ manifest = json.loads((ROOT / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))
6412
+ post = json.dumps(manifest.get("hooks", {}).get("PostToolUse", []))
6413
+ if "mail-hook.js" not in post or "post-tool-use" not in post:
6414
+ report(f"{label} .claude-plugin/plugin.json does not register PostToolUse on mail-hook.js post-tool-use: {post}")
6415
+ return 1
6416
+ with tempfile.TemporaryDirectory(prefix="keel-language-tools-") as raw:
6417
+ base = Path(raw)
6418
+ rtl, _verify, env = chat_scratch_group(base)
6419
+ env = {**env, "KEEL_CLI": f'node "{ROOT / "bin" / "keel.js"}"'}
6420
+ write_authorize_config(rtl, "owner_language: zh\n")
6421
+
6422
+ def hook(event: str, payload: dict) -> str:
6423
+ result = subprocess.run(
6424
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"), event],
6425
+ cwd=rtl, env=env, text=True, capture_output=True, check=False,
6426
+ input=json.dumps({"cwd": str(rtl), **payload}),
6427
+ )
6428
+ if not result.stdout.strip():
6429
+ return ""
6430
+ return json.loads(result.stdout).get("hookSpecificOutput", {}).get("additionalContext", "")
6431
+
6432
+ def tool(session: str) -> str:
6433
+ return hook("post-tool-use", {"hook_event_name": "PostToolUse", "session_id": session, "tool_name": "Bash"})
6434
+
6435
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "t1", "prompt": "go on"})
6436
+ outputs = [tool("t1") for _ in range(16)]
6437
+ early = [n + 1 for n, text in enumerate(outputs[:14]) if text]
6438
+ if early:
6439
+ report(f"{label} PostToolUse calls {early} restated the rule before the 15th.")
6440
+ return 1
6441
+ if "中文" not in outputs[14]:
6442
+ report(f"{label} the 15th PostToolUse did not restate the rule: {outputs[14]!r}")
6443
+ return 1
6444
+ if outputs[15]:
6445
+ report(f"{label} the 16th PostToolUse restated the rule again: {outputs[15]!r}")
6446
+ return 1
6447
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "t1", "prompt": "next"})
6448
+ if tool("t1"):
6449
+ report(f"{label} the first tool call after a prompt restated the rule.")
6450
+ return 1
6451
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1"})
6452
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1", "prompt": '<scheduled-task name="patrol">run'})
6453
+ if any(tool("run1") for _ in range(16)):
6454
+ report(f"{label} a host-run session was reminded.")
6455
+ return 1
6456
+ write_authorize_config(rtl, "")
6457
+ if any(tool("t2") for _ in range(16)):
6458
+ report(f"{label} a repository without owner_language was reminded.")
6459
+ return 1
6460
+ report("owner-language-after-tools scenario passed.")
6461
+ return 0
6462
+
6463
+
6361
6464
  def validate_shift_coordinator_last_scenario() -> int:
6362
6465
  """Issue #289: the coordinator starts the others before its own shift ends.
6363
6466
 
@@ -21060,6 +21163,7 @@ def validate_native_plugin_manifests_scenario() -> int:
21060
21163
  {"hooks": [mail_hook("session-start")]},
21061
21164
  ]
21062
21165
  expected_hooks["UserPromptSubmit"] = [{"hooks": [mail_hook("user-prompt-submit")]}]
21166
+ expected_hooks["PostToolUse"] = [{"hooks": [mail_hook("post-tool-use")]}]
21063
21167
  expected_hooks["FileChanged"] = [
21064
21168
  {"hooks": [mail_hook("file-changed", asyncRewake=True)]}
21065
21169
  ]
@@ -40038,6 +40142,7 @@ SCENARIOS: tuple = (
40038
40142
  ("shift-self", validate_shift_self_scenario),
40039
40143
  ("shift-self-wake", validate_shift_self_wake_scenario),
40040
40144
  ("owner-language", validate_owner_language_scenario),
40145
+ ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
40041
40146
  ("shift-history", validate_shift_history_scenario),
40042
40147
  ("role-drift", validate_role_drift_scenario),
40043
40148
  ("host-run-session", validate_host_run_session_scenario),
@@ -40049,6 +40154,7 @@ SCENARIOS: tuple = (
40049
40154
  ("patrol-since-last", validate_patrol_since_last_scenario),
40050
40155
  ("patrol-nudge", validate_patrol_nudge_scenario),
40051
40156
  ("patrol-escalate", validate_patrol_escalate_scenario),
40157
+ ("patrol-quota", validate_patrol_quota_scenario),
40052
40158
  ("patrol-host-task", validate_patrol_host_task_scenario),
40053
40159
  ("patrol-rearm", validate_patrol_rearm_scenario),
40054
40160
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
@@ -161,6 +161,7 @@ const OWNER_RULE = "Slack notifies the owner only for messages that write `@owne
161
161
  const HOST_EVENTS = {
162
162
  "session-start": "SessionStart",
163
163
  "user-prompt-submit": "UserPromptSubmit",
164
+ "post-tool-use": "PostToolUse",
164
165
  "file-changed": "FileChanged",
165
166
  "session-end": "SessionEnd",
166
167
  };
@@ -237,6 +238,55 @@ function decideSession(where, file, session, prompt) {
237
238
  return hostRun;
238
239
  }
239
240
 
241
+ // --- the owner's language after tool calls (#311) ---------------------------------------
242
+
243
+ function languageFile(where, payload) {
244
+ const file = sessionFile(where, payload);
245
+ return file ? file.replace(/\.json$/, ".language.json") : null;
246
+ }
247
+
248
+ function resetLanguageCount(where, payload) {
249
+ const file = languageFile(where, payload);
250
+ if (!file) return;
251
+ try {
252
+ store.writeJsonAtomic(where, file, { count: 0, at: Date.now() });
253
+ } catch {
254
+ // A convenience: never fail the hook.
255
+ }
256
+ }
257
+
258
+ // Once 15 tool calls or 10 minutes have passed since the rule was last stated
259
+ // in this session, it is stated again (D2); a host run gets nothing (D4).
260
+ function languageAfterTools(where, payload) {
261
+ const file = languageFile(where, payload);
262
+ if (!file) return { code: 0 };
263
+ try {
264
+ const session = sessionFile(where, payload);
265
+ if (fs.existsSync(session) && store.readJsonFile(session).host_run) return { code: 0 };
266
+ const { readOwnerLanguage, ownerLanguageRule } = require("../config");
267
+ const language = readOwnerLanguage(where.worktree);
268
+ if (!language.tag) return { code: 0 };
269
+ const everyTools = Number(process.env.KEEL_LANGUAGE_EVERY_TOOLS) > 0 ? Number(process.env.KEEL_LANGUAGE_EVERY_TOOLS) : 15;
270
+ const everyMs = Number(process.env.KEEL_LANGUAGE_EVERY_MS) > 0 ? Number(process.env.KEEL_LANGUAGE_EVERY_MS) : 10 * 60 * 1000;
271
+ const now = Date.now();
272
+ const record = fs.existsSync(file) ? store.readJsonFile(file) : null;
273
+ if (!record || typeof record.count !== "number") {
274
+ store.writeJsonAtomic(where, file, { count: 1, at: now });
275
+ return { code: 0 };
276
+ }
277
+ const count = record.count + 1;
278
+ if (count >= everyTools || now - Number(record.at || 0) >= everyMs) {
279
+ store.writeJsonAtomic(where, file, { count: 0, at: now });
280
+ const output = { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: ownerLanguageRule(language.tag) } };
281
+ return { code: 0, stdout: `${JSON.stringify(output)}\n` };
282
+ }
283
+ store.writeJsonAtomic(where, file, { count, at: record.at });
284
+ } catch {
285
+ // Never fail a tool call over a reminder.
286
+ }
287
+ return { code: 0 };
288
+ }
289
+
240
290
  function hook(event, input, { mail = false } = {}) {
241
291
  if (!(event in HOST_EVENTS)) return { code: 0 };
242
292
  let payload = {};
@@ -256,6 +306,8 @@ function hook(event, input, { mail = false } = {}) {
256
306
  // A session's watch list is fixed at SessionStart, so a worktree with no role
257
307
  // yet still watches its own signal, which a role bound later will touch
258
308
  // (chat-wake-late-binding D1). Nothing else is said until there is a role.
309
+ // After a run of tool calls the owner's language is restated too (#311).
310
+ if (event === "post-tool-use") return where ? languageAfterTools(where, payload) : { code: 0 };
259
311
  // The owner's language is restated on every prompt, role or not (#305 D4).
260
312
  let languageLine = null;
261
313
  if (where && event === "user-prompt-submit") {
@@ -266,6 +318,8 @@ function hook(event, input, { mail = false } = {}) {
266
318
  } catch {
267
319
  languageLine = null;
268
320
  }
321
+ // A prompt that states the rule starts the tool count over (#311 D3).
322
+ if (languageLine) resetLanguageCount(where, payload);
269
323
  }
270
324
  const promptOutput = (text) => ({
271
325
  code: 0,
@@ -287,6 +287,22 @@ function nudgeRoles(where, patroller, options) {
287
287
  return { sent, escalations };
288
288
  }
289
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)}%`;
304
+ }
305
+
290
306
  function notifyRisks(where, role, risks) {
291
307
  const group = store.directName(NOTIFY_SENDER, role);
292
308
  if (!store.groupState(store.readLog(where, group)).exists) {
@@ -304,6 +320,7 @@ function render(result) {
304
320
  for (const change of changes) lines.push(`changed: ${change}`);
305
321
  for (const sent of result.nudges || []) lines.push(`nudged ${sent.role}: ${sent.kind}`);
306
322
  for (const risk of result.risks || []) lines.push(`risk: ${risk}`);
323
+ if (result.paused) lines.push(result.paused);
307
324
  for (const held of result.held) lines.push(`met: ${held.from} waited for ${held.condition} (${held.id})`);
308
325
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
309
326
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
@@ -405,7 +422,7 @@ function runPatrol(argv) {
405
422
  throw error;
406
423
  }
407
424
  }
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 };
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 };
409
426
  try {
410
427
  for (let index = 0; index < argv.length; index += 1) {
411
428
  const arg = argv[index];
@@ -417,6 +434,9 @@ function runPatrol(argv) {
417
434
  else if (arg === "--shift-at") options.shiftAt = Number(argv[++index]);
418
435
  else if (arg === "--disk-free-gb") options.diskFreeGb = Number(argv[++index]);
419
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]);
420
440
  else if (arg === "--help" || arg === "-h") {
421
441
  process.stdout.write(`${USAGE}\nExit 0: wrote nothing. 2: sent a notice or marked a wait met. 1: error.\n`);
422
442
  return EXIT_QUIET;
@@ -431,13 +451,22 @@ function runPatrol(argv) {
431
451
  options.contexts = parseContexts(options.context);
432
452
  if (options.diskFreeGb !== null && !(options.diskFreeGb >= 0)) throw new PatrolError("--disk-free-gb needs a number of gigabytes.");
433
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.");
434
458
  if (parseSince(options.idle) === null) throw new PatrolError(`--idle ${JSON.stringify(options.idle)} is not a duration; use 90s, 15m, 2h, or 3d.`);
435
459
  options.issues = readIssues(options.issues);
436
460
  const where = store.requireLocation(path.resolve(options.repo));
437
461
  const role = store.requireRole(where);
438
462
  const result = patrol(where, role, options);
439
463
  result.risks = [];
440
- if (options.nudge) {
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) {
441
470
  const nudged = nudgeRoles(where, role, options);
442
471
  result.nudges = nudged.sent;
443
472
  result.risks.push(...nudged.escalations);