@christang/keel 5.119.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.
@@ -830,6 +838,14 @@ in the folder it was created from. A run that starts in a role's worktree anyway
830
838
  first prompt (`<scheduled-task …`), and Keel then restores that role's presence and ignores the
831
839
  session, so it neither marks the role offline nor fires a `keel shift ready --wake` (#300).
832
840
 
841
+ ## The owner's language
842
+
843
+ 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.
844
+
845
+ ```yaml
846
+ owner_language: zh
847
+ ```
848
+
833
849
  ## Commands
834
850
 
835
851
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.119.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.119.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.119.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.119.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.119.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.119.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",
@@ -11,7 +11,7 @@
11
11
  // exit 2 from FileChanged is the wake signal.
12
12
  //
13
13
  // Nothing here advances a read position, and a worktree with no chat role gets
14
- // no output. A failure to run the CLI exits 0 silently: a missing notice costs
14
+ // no output except, on UserPromptSubmit, the declared owner language (#305). A failure to run the CLI exits 0 silently: a missing notice costs
15
15
  // a late read, while a spurious exit 2 would wake the session for nothing.
16
16
 
17
17
  const fs = require("fs");
@@ -674,6 +674,10 @@ function main() {
674
674
  + "if this session has none, and wake the model only on exit 2."
675
675
  );
676
676
  }
677
+ // The language every message to the owner is in (#305 D3).
678
+ if (context.ownerLanguage && context.ownerLanguageRule) {
679
+ lines.push(`- ${context.ownerLanguageRule}`);
680
+ }
677
681
  // The role other sessions address this one by (#245).
678
682
  if (context.role) {
679
683
  lines.push(`- chat role: ${context.role} (other sessions address this one by it).`);
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.119.0"
51
- PROTOCOL_VERSION = "5.119.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
 
@@ -6152,6 +6238,72 @@ def validate_shift_history_scenario() -> int:
6152
6238
  return 0
6153
6239
 
6154
6240
 
6241
+ def validate_owner_language_scenario() -> int:
6242
+ """Issue #305: a declared owner language is restated where replies are written."""
6243
+ label = "owner-language:"
6244
+ protocol = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
6245
+ if "declares `owner_language:`" not in protocol:
6246
+ report(f"{label} AGENTS.md does not make a declared owner_language binding.")
6247
+ return 1
6248
+ with tempfile.TemporaryDirectory(prefix="keel-owner-language-") as raw:
6249
+ base = Path(raw)
6250
+ rtl, verify, env = chat_scratch_group(base)
6251
+ loose = chat_worktree(rtl, base / "loose")
6252
+ for tree in (rtl, loose):
6253
+ write_text(tree / "openspec/specs/.keep", "")
6254
+ write_authorize_config(tree, "owner_language: zh\n")
6255
+
6256
+ def prompt(cwd: Path) -> str:
6257
+ result = subprocess.run(
6258
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "user-prompt-submit"],
6259
+ cwd=cwd, env=env, text=True, capture_output=True, check=False,
6260
+ input=json.dumps({"cwd": str(cwd), "hook_event_name": "UserPromptSubmit", "session_id": "p1", "prompt": "go on"}),
6261
+ )
6262
+ if not result.stdout.strip():
6263
+ return ""
6264
+ return json.loads(result.stdout).get("hookSpecificOutput", {}).get("additionalContext", "")
6265
+
6266
+ unbound = prompt(loose)
6267
+ if "中文" not in unbound:
6268
+ report(f"{label} the prompt hook in an unbound worktree does not restate the language: {unbound!r}")
6269
+ return 1
6270
+ if "structured-choice" not in unbound:
6271
+ report(f"{label} the restated rule does not cover structured-choice options: {unbound!r}")
6272
+ return 1
6273
+ context = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
6274
+ if context.get("ownerLanguage") != "zh":
6275
+ report(f"{label} keel context carries ownerLanguage {context.get('ownerLanguage')!r}.")
6276
+ return 1
6277
+ session = run_session_start_hook(
6278
+ loose, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(loose)},
6279
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
6280
+ )
6281
+ if "中文" not in (session_start_context(session) or ""):
6282
+ report(f"{label} the session-start note does not state the language: {session_start_context(session)!r}")
6283
+ return 1
6284
+ run_keel(verify, "chat", "post", "soc", "@rtl please look", env=env)
6285
+ bound = prompt(rtl)
6286
+ if "中文" not in bound:
6287
+ report(f"{label} a bound role's prompt hook lost the language line: {bound!r}")
6288
+ return 1
6289
+ if "please look" not in bound:
6290
+ report(f"{label} a bound role's prompt hook lost the chat notice: {bound!r}")
6291
+ return 1
6292
+ write_authorize_config(loose, "owner_language: Chinese!\n")
6293
+ broken = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
6294
+ if not any("owner_language" in w for w in broken.get("warnings", [])):
6295
+ report(f"{label} a malformed owner_language is not reported: {broken.get('warnings')!r}")
6296
+ return 1
6297
+ if "ownerLanguage" in broken:
6298
+ report(f"{label} a malformed owner_language is still carried: {broken.get('ownerLanguage')!r}")
6299
+ return 1
6300
+ if "Owner language" in prompt(loose):
6301
+ report(f"{label} a malformed owner_language still adds a language line.")
6302
+ return 1
6303
+ report("owner-language scenario passed.")
6304
+ return 0
6305
+
6306
+
6155
6307
  def validate_shift_coordinator_last_scenario() -> int:
6156
6308
  """Issue #289: the coordinator starts the others before its own shift ends.
6157
6309
 
@@ -39831,6 +39983,7 @@ SCENARIOS: tuple = (
39831
39983
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39832
39984
  ("shift-self", validate_shift_self_scenario),
39833
39985
  ("shift-self-wake", validate_shift_self_wake_scenario),
39986
+ ("owner-language", validate_owner_language_scenario),
39834
39987
  ("shift-history", validate_shift_history_scenario),
39835
39988
  ("role-drift", validate_role_drift_scenario),
39836
39989
  ("host-run-session", validate_host_run_session_scenario),
@@ -39840,6 +39993,7 @@ SCENARIOS: tuple = (
39840
39993
  ("chat-ack", validate_chat_ack_scenario),
39841
39994
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
39842
39995
  ("patrol-since-last", validate_patrol_since_last_scenario),
39996
+ ("patrol-nudge", validate_patrol_nudge_scenario),
39843
39997
  ("patrol-host-task", validate_patrol_host_task_scenario),
39844
39998
  ("patrol-rearm", validate_patrol_rearm_scenario),
39845
39999
  ("patrol-issue-routing", validate_patrol_issue_routing_scenario),
@@ -256,11 +256,26 @@ function hook(event, input, { mail = false } = {}) {
256
256
  // A session's watch list is fixed at SessionStart, so a worktree with no role
257
257
  // yet still watches its own signal, which a role bound later will touch
258
258
  // (chat-wake-late-binding D1). Nothing else is said until there is a role.
259
+ // The owner's language is restated on every prompt, role or not (#305 D4).
260
+ let languageLine = null;
261
+ if (where && event === "user-prompt-submit") {
262
+ try {
263
+ const { readOwnerLanguage, ownerLanguageRule } = require("../config");
264
+ const language = readOwnerLanguage(where.worktree);
265
+ if (language.tag) languageLine = ownerLanguageRule(language.tag);
266
+ } catch {
267
+ languageLine = null;
268
+ }
269
+ }
270
+ const promptOutput = (text) => ({
271
+ code: 0,
272
+ stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } })}\n`,
273
+ });
259
274
  if (where && !role && event === "session-start") {
260
275
  const watched = ensureWorktreeSignal(where);
261
276
  return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
262
277
  }
263
- if (!where || !role) return { code: 0 };
278
+ if (!where || !role) return languageLine ? promptOutput(languageLine) : { code: 0 };
264
279
  const file = sessionFile(where, payload);
265
280
  const session = file && fs.existsSync(file) ? store.readJsonFile(file) : null;
266
281
  if (event === "session-end" && file) fs.rmSync(file, { force: true });
@@ -287,11 +302,8 @@ function hook(event, input, { mail = false } = {}) {
287
302
  return { code: 0, stdout: `${JSON.stringify(output)}\n` };
288
303
  }
289
304
  if (event === "user-prompt-submit") {
290
- if (!text) return { code: 0 };
291
- return {
292
- code: 0,
293
- stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } })}\n`,
294
- };
305
+ const context = [languageLine, text].filter(Boolean).join("\n");
306
+ return context ? promptOutput(context) : { code: 0 };
295
307
  }
296
308
  // file-changed
297
309
  const waking = store.unread(where, role).some((record) => store.wakes(record, role));
@@ -130,6 +130,7 @@ const CONFIG_DECLARATIONS = [
130
130
  "read_only_roles",
131
131
  "issue_roles",
132
132
  "patrol",
133
+ "owner_language",
133
134
  ];
134
135
 
135
136
  const CONFIG_RELATIVE_PATH = path.join("keel", "config.yaml");
@@ -684,6 +685,35 @@ function readMergeDeclaration(repo) {
684
685
  };
685
686
  }
686
687
 
688
+ // `owner_language:` — the language every message to the owner is written in
689
+ // (#305 D1, D2). The agent may work in any language; what it says to the owner
690
+ // is in this one, and the rule is restated where replies are written.
691
+ const LANGUAGE_NAMES = [
692
+ ["zh", "Chinese (中文)", "对负责人说话一律用中文。"],
693
+ ["en", "English", ""],
694
+ ["ja", "Japanese (日本語)", ""],
695
+ ["ko", "Korean (한국어)", ""],
696
+ ];
697
+
698
+ function readOwnerLanguage(repo) {
699
+ const declared = configScalar(repo, "owner_language");
700
+ if (!declared) return { tag: null, message: null };
701
+ if (/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(declared)) return { tag: declared, message: null };
702
+ return {
703
+ tag: null,
704
+ message: `keel/config.yaml owner_language \`${declared}\` is not a language tag such as zh or en; it is ignored.`,
705
+ };
706
+ }
707
+
708
+ function ownerLanguageRule(tag) {
709
+ const known = LANGUAGE_NAMES.find(([prefix]) => tag === prefix || tag.startsWith(`${prefix}-`));
710
+ const name = known ? known[1] : tag;
711
+ const native = known && known[2] ? ` ${known[2]}` : "";
712
+ return `Owner language: ${tag} — write every message to the owner in ${name}: replies, summaries, reports, `
713
+ + "and the question and options of a structured-choice prompt. Work in any language; identifiers, commands, "
714
+ + `paths, and quoted output stay as they are.${native}`;
715
+ }
716
+
687
717
  function configScalar(repo, key) {
688
718
  const configPath = path.join(repo, "keel", "config.yaml");
689
719
  if (!fs.existsSync(configPath)) return null;
@@ -916,6 +946,8 @@ function patrolReminder(patrol) {
916
946
  }
917
947
 
918
948
  module.exports = {
949
+ readOwnerLanguage,
950
+ ownerLanguageRule,
919
951
  readPatrolDeclaration,
920
952
  patrolReminder,
921
953
  readIssueRoles,
@@ -19,6 +19,8 @@ const {
19
19
  readMergeDeclaration,
20
20
  readReadOnlyRoles,
21
21
  readPatrolDeclaration,
22
+ readOwnerLanguage,
23
+ ownerLanguageRule,
22
24
  } = require("./config");
23
25
  const { isKeelSourceRepo } = require("./capabilities");
24
26
 
@@ -857,6 +859,13 @@ function resolveContext(repo, options) {
857
859
  } catch {
858
860
  context.role = null;
859
861
  }
862
+ // The language every message to the owner is in (#305 D3).
863
+ const language = readOwnerLanguage(repo);
864
+ if (language.message) context.warnings.push(language.message);
865
+ if (language.tag) {
866
+ context.ownerLanguage = language.tag;
867
+ context.ownerLanguageRule = ownerLanguageRule(language.tag);
868
+ }
860
869
  // The patrolling role is reminded to re-arm its schedule (#260).
861
870
  const patrol = readPatrolDeclaration(repo);
862
871
  if (patrol.message) context.warnings.push(patrol.message);
@@ -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");