@christang/keel 5.116.0 → 5.118.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
@@ -770,7 +770,7 @@ Without a known default branch, no issue range is inferred.
770
770
 
771
771
  ## Group chat between sessions
772
772
 
773
- Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. A member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). A session's chat role is its identity: address other sessions by role, never by the host's session title, which Keel cannot see; `keel context` and the session projection name the role bound to the worktree, and remind a worktree with none when others here have one (#245). Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Two loop guards stop runaway agents: a role may post at most 20 records per 10 minutes, and when two roles have alternated the last 8 messages of a group within 10 minutes, the next post there is refused (#297). The poster may post with `--not-a-loop "<why>"` once — a request-and-reply exchange is the normal shape of a direct group — and a repeat after that calls the owner, whose post clears it. `limits` in `keel/chat.json` sets `rate`, `window_minutes`, `pingpong`, and `pingpong_minutes`. A time in a message should come from Keel's clock, not an estimate: `keel chat post` and `keel chat dm` take `--stamp`, which prefixes `[MM-DD HH:MM]` (#298). Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). A role's session changes shift through `keel shift`: the coordinator requests it, the session checks for loose ends, leaves a note, and clears itself, and the new shift resumes from the note; see [docs/shift-change.md](docs/shift-change.md). The 5.83 `keel mail` commands keep working on direct groups.
773
+ Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. A record can supersede its author's earlier one (`--supersedes <id>`), and the earlier one then leaves everyone's unread; unread lists newest first. A record posted with `--ack` asks the roles it addresses to acknowledge it, by `keel chat ack <id>` or a reply, and `keel chat show <id>` and `keel chat acks` list who has acknowledged, who only read it, and who has not read it. `keel chat summary --since <time>` digests what changed in the groups you can read — per sender, the message count, todos opened with whether they are still open, todos closed, superseded records folded into their successors, and acknowledgements still waiting — without a model and without marking anything read. Each member has its own unread state, and history is kept. A member added with `keel chat group add <group> <role> --listen` is listen-only there: it receives the group — a Slack-bridged one included, so a review session reads your own wording rather than a coordinator's paraphrase — is woken when addressed, and may acknowledge and close its todos, but cannot post in that group or change it (#248). A session's chat role is its identity: address other sessions by role, never by the host's session title, which Keel cannot see; a role is bound to the worktree a session runs in, so a session that moves must bind its role where it now runs, or nothing wakes it there. `keel patrol` and `keel --doctor` report a binding to a removed worktree and a role with something waiting and no session active for two hours, a session starting unbound is told which roles those are, and `keel chat role --prune` drops bindings to removed worktrees (#301); `keel context` and the session projection name the role bound to the worktree, and remind a worktree with none when others here have one (#245). Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Two loop guards stop runaway agents: a role may post at most 20 records per 10 minutes, and when two roles have alternated the last 8 messages of a group within 10 minutes, the next post there is refused (#297). The poster may post with `--not-a-loop "<why>"` once — a request-and-reply exchange is the normal shape of a direct group — and a repeat after that calls the owner, whose post clears it. `limits` in `keel/chat.json` sets `rate`, `window_minutes`, `pingpong`, and `pingpong_minutes`. A time in a message should come from Keel's clock, not an estimate: `keel chat post` and `keel chat dm` take `--stamp`, which prefixes `[MM-DD HH:MM]` (#298). Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). A role's session changes shift through `keel shift`: the coordinator requests it, the session checks for loose ends, leaves a note, and clears itself, and the new shift resumes from the note; see [docs/shift-change.md](docs/shift-change.md). The 5.83 `keel mail` commands keep working on direct groups.
774
774
 
775
775
  ## Coordinator patrol
776
776
 
@@ -825,7 +825,10 @@ prints the task — id, a cron from `every:`, the model, and a self-contained pr
825
825
  `keel patrol --since-last --notify` against the coordinator's worktree by path. Keel creates
826
826
  nothing; the session's model installs it with the host's own scheduled-task tool, since a host keeps
827
827
  the schedule itself. With `host_task:` declared, the reminder asks only to confirm the task is still
828
- enabled.
828
+ enabled. Create the task from a session whose folder is bound to no role: a host task starts its runs
829
+ in the folder it was created from. A run that starts in a role's worktree anyway is recognized by its
830
+ first prompt (`<scheduled-task …`), and Keel then restores that role's presence and ignores the
831
+ session, so it neither marks the role offline nor fires a `keel shift ready --wake` (#300).
829
832
 
830
833
  ## Commands
831
834
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.116.0 -->
1
+ <!-- keel:start version=5.118.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.
package/bin/keel.js CHANGED
@@ -2176,10 +2176,30 @@ function runDoctor(options) {
2176
2176
  printMergeSurface(repo);
2177
2177
  printFastPrePushSurface(repo);
2178
2178
  printSourceRepoCliResolution(repo);
2179
+ printChatRoleDrift(repo);
2179
2180
 
2180
2181
  return authorizationOk ? checkStatus : 1;
2181
2182
  }
2182
2183
 
2184
+ // Chat role bindings that drifted from where sessions run (#301 D3). Nothing
2185
+ // is printed without a chat store that binds roles.
2186
+ function printChatRoleDrift(repo) {
2187
+ let where = null;
2188
+ try {
2189
+ where = require("../src/core/chat/store").locate(repo);
2190
+ } catch {
2191
+ where = null;
2192
+ }
2193
+ if (!where || !fs.existsSync(path.join(where.root, "roles.json"))) return;
2194
+ const drift = require("../src/core/chat/drift");
2195
+ const lines = drift.driftLines(drift.roleDrift(where));
2196
+ if (!lines.length) {
2197
+ printDoctorLine("chat roles", "ok", "every binding points at a worktree, and no role with something waiting has gone unattended");
2198
+ return;
2199
+ }
2200
+ for (const line of lines) printDoctorLine("chat roles", "drift", line.text);
2201
+ }
2202
+
2183
2203
  // Only meaningful in Keel's own repository: a bare `keel` resolves to the
2184
2204
  // installed package, so gate commands verify the released CLI rather than the
2185
2205
  // working tree. The failure mode is a silently stale result, not an error, so
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.116.0",
3
+ "version": "5.118.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.116.0",
9
+ "version": "5.118.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.116.0",
5
+ "version": "5.118.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.116.0",
3
+ "version": "5.118.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.116.0",
3
+ "version": "5.118.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",
@@ -677,6 +677,12 @@ function main() {
677
677
  // The role other sessions address this one by (#245).
678
678
  if (context.role) {
679
679
  lines.push(`- chat role: ${context.role} (other sessions address this one by it).`);
680
+ } else if (context.roleReminder && Array.isArray(context.unattendedRoles) && context.unattendedRoles.length) {
681
+ // Roles nobody is active for where they are bound (#301 D5).
682
+ lines.push(
683
+ "- chat role: none bound here while other worktrees have one; roles with nobody active where they are "
684
+ + `bound: ${context.unattendedRoles.join(", ")}. If this session is one of them, run \`keel chat role --set <role>\` here.`
685
+ );
680
686
  } else if (context.roleReminder) {
681
687
  lines.push(
682
688
  "- chat role: none bound here while other worktrees have one; bind one "
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.116.0"
51
- PROTOCOL_VERSION = "5.116.0"
50
+ PACKAGE_VERSION = "5.118.0"
51
+ PROTOCOL_VERSION = "5.118.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
@@ -5845,7 +5845,7 @@ def validate_shift_self_wake_scenario() -> int:
5845
5845
  with tempfile.TemporaryDirectory(prefix="keel-shift-wake-") as raw:
5846
5846
  base = Path(raw)
5847
5847
  rtl, verify, env, _ = shift_scratch(base)
5848
- env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
5848
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_SETTLE_MS": "500", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
5849
5849
  loose = chat_worktree(rtl, base / "loose")
5850
5850
  subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=loose, check=True, capture_output=True)
5851
5851
 
@@ -5898,6 +5898,145 @@ def validate_shift_self_wake_scenario() -> int:
5898
5898
  return 0
5899
5899
 
5900
5900
 
5901
+ def validate_role_drift_scenario() -> int:
5902
+ """Issue #301: bindings that drift from where sessions run are reported.
5903
+
5904
+ A binding to a removed worktree and a role with a waiting note and no
5905
+ session are named by `keel patrol`, `keel --doctor`, and an unbound
5906
+ session's projection; `keel chat role --prune` removes only the former.
5907
+ """
5908
+ label = "role-drift:"
5909
+ with tempfile.TemporaryDirectory(prefix="keel-role-drift-") as raw:
5910
+ base = Path(raw)
5911
+ rtl, verify, env, _ = shift_scratch(base)
5912
+ ghost = chat_worktree(rtl, base / "ghost")
5913
+ run_keel(ghost, "chat", "role", "--set", "ghost", env=env)
5914
+ subprocess.run(["git", "worktree", "remove", "--force", str(ghost)], cwd=rtl, check=True, capture_output=True)
5915
+ loose = chat_worktree(rtl, base / "loose")
5916
+ write_text(loose / "openspec/specs/.keep", "")
5917
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
5918
+ if readied.returncode != 0:
5919
+ report(f"{label} verify's ready failed: {readied.stderr}")
5920
+ return 1
5921
+
5922
+ patrolled = run_keel(rtl, "patrol", env=env)
5923
+ drift = [line for line in patrolled.stdout.splitlines() if line.startswith("drift:")]
5924
+ if not any("ghost" in line and "/ghost" in line for line in drift):
5925
+ report(f"{label} keel patrol does not report ghost's removed worktree: {patrolled.stdout!r} {patrolled.stderr!r}")
5926
+ return 1
5927
+ if not any("verify" in line and "shift note" in line for line in drift):
5928
+ report(f"{label} keel patrol does not report verify as unattended: {patrolled.stdout!r}")
5929
+ return 1
5930
+ doctor = run_keel(rtl, "--doctor", env=env).stdout
5931
+ doctor_drift = [line for line in doctor.splitlines() if line.startswith("chat roles: drift")]
5932
+ if not any("ghost" in line for line in doctor_drift):
5933
+ report(f"{label} keel --doctor does not report ghost: {doctor_drift!r}")
5934
+ return 1
5935
+ if not any("verify" in line for line in doctor_drift):
5936
+ report(f"{label} keel --doctor does not report verify: {doctor_drift!r}")
5937
+ return 1
5938
+ context = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
5939
+ if "verify" not in (context.get("unattendedRoles") or []):
5940
+ report(f"{label} an unbound worktree's context does not name verify: {context.get('unattendedRoles')!r}")
5941
+ return 1
5942
+ session = run_session_start_hook(
5943
+ loose, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(loose)},
5944
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
5945
+ )
5946
+ note = session_start_context(session) or ""
5947
+ if "verify" not in note:
5948
+ report(f"{label} the unbound session's note does not name verify: {note!r}")
5949
+ return 1
5950
+ pruned = run_keel(rtl, "chat", "role", "--prune", env=env)
5951
+ if "Pruned ghost" not in pruned.stdout:
5952
+ report(f"{label} keel chat role --prune did not prune ghost: {pruned.stdout!r} {pruned.stderr!r}")
5953
+ return 1
5954
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
5955
+ if "ghost" in roles.values():
5956
+ report(f"{label} roles.json still binds ghost: {roles!r}")
5957
+ return 1
5958
+ if sorted(set(roles.values())) != ["rtl", "verify"]:
5959
+ report(f"{label} prune changed other bindings: {roles!r}")
5960
+ return 1
5961
+ again = run_keel(rtl, "chat", "role", "--prune", env=env)
5962
+ if "No binding" not in again.stdout:
5963
+ report(f"{label} a second prune did not say there was nothing to prune: {again.stdout!r}")
5964
+ return 1
5965
+ report("role-drift scenario passed.")
5966
+ return 0
5967
+
5968
+
5969
+ def validate_host_run_session_scenario() -> int:
5970
+ """Issue #300: a scheduled run started in a role's worktree is not that role.
5971
+
5972
+ Its first prompt, starting `<scheduled-task`, restores the presence its
5973
+ SessionStart replaced; its hooks then write and inject nothing, its end
5974
+ changes nothing, and it never fires `ready --wake`. An ordinary clear
5975
+ still wakes the role once, after the wake settles.
5976
+ """
5977
+ label = "host-run-session:"
5978
+ with tempfile.TemporaryDirectory(prefix="keel-host-run-") as raw:
5979
+ base = Path(raw)
5980
+ rtl, verify, env, _ = shift_scratch(base)
5981
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_SETTLE_MS": "1500", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "30000"}
5982
+ presence = mailbox_common_dir(rtl) / "keel-chat" / "presence" / "verify.json"
5983
+
5984
+ def hook(event: str, payload: dict) -> subprocess.CompletedProcess[str]:
5985
+ return subprocess.run(
5986
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
5987
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
5988
+ input=json.dumps({"cwd": str(verify), **payload}),
5989
+ )
5990
+
5991
+ def wakes() -> list[str]:
5992
+ return chat_records_with(rtl, "dm-keel-shift--verify", "keel shift resume")
5993
+
5994
+ def current() -> str:
5995
+ return presence.read_text(encoding="utf-8") if presence.exists() else ""
5996
+
5997
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "s1"})
5998
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "hello"})
5999
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note", env=env)
6000
+ if armed.returncode != 0:
6001
+ report(f"{label} ready --wake failed: {armed.stderr}")
6002
+ return 1
6003
+ run_keel(rtl, "chat", "post", "soc", "@verify something to read", env=env)
6004
+ before = current()
6005
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1"})
6006
+ prompted = hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1",
6007
+ "prompt": '<scheduled-task name="patrol">\nrun the patrol'})
6008
+ if current() != before:
6009
+ report(f"{label} the host run's presence was not restored:\nbefore {before}\nafter {current()}")
6010
+ return 1
6011
+ if prompted.stdout.strip():
6012
+ report(f"{label} the host run's prompt hook injected output: {prompted.stdout!r}")
6013
+ return 1
6014
+ time.sleep(3)
6015
+ if wakes():
6016
+ report(f"{label} the host run's start fired the wake.")
6017
+ return 1
6018
+ hook("session-end", {"hook_event_name": "SessionEnd", "session_id": "run1"})
6019
+ if current() != before:
6020
+ report(f"{label} the host run's end changed presence:\nbefore {before}\nafter {current()}")
6021
+ return 1
6022
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "clear", "session_id": "s2"})
6023
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s2", "prompt": "carry on"})
6024
+ deadline = time.time() + 6
6025
+ while time.time() < deadline and not wakes():
6026
+ time.sleep(0.1)
6027
+ if len(wakes()) != 1:
6028
+ report(f"{label} expected one wake after the clear start, found {len(wakes())}.")
6029
+ return 1
6030
+ task_config = "patrol:\n role: verify\n every: 30m\n"
6031
+ write_text(verify / "keel" / "config.yaml", task_config)
6032
+ task = run_keel(verify, "patrol", "task", env=env)
6033
+ if "bound to no role" not in task.stdout:
6034
+ report(f"{label} keel patrol task does not say to create the task from a folder bound to no role: {task.stdout!r} {task.stderr!r}")
6035
+ return 1
6036
+ report("host-run-session scenario passed.")
6037
+ return 0
6038
+
6039
+
5901
6040
  def validate_shift_coordinator_last_scenario() -> int:
5902
6041
  """Issue #289: the coordinator starts the others before its own shift ends.
5903
6042
 
@@ -39577,6 +39716,8 @@ SCENARIOS: tuple = (
39577
39716
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39578
39717
  ("shift-self", validate_shift_self_scenario),
39579
39718
  ("shift-self-wake", validate_shift_self_wake_scenario),
39719
+ ("role-drift", validate_role_drift_scenario),
39720
+ ("host-run-session", validate_host_run_session_scenario),
39580
39721
  ("shift-without-role", validate_shift_without_role_scenario),
39581
39722
  ("resource-lock", validate_resource_lock_scenario),
39582
39723
  ("chat-supersedes", validate_chat_supersedes_scenario),
@@ -15,7 +15,7 @@ const { relativeAge } = require("./view");
15
15
  const { ChatError } = store;
16
16
 
17
17
  const USAGE = [
18
- "keel chat role [--set <name>] [--alias <alias>] [--json]",
18
+ "keel chat role [--set <name>] [--alias <alias>] [--prune] [--json] (--prune: drop bindings to removed worktrees)",
19
19
  "keel chat group create <group> [--member <role>]...",
20
20
  "keel chat group add|remove <group> <role> [--listen] (--listen: receives the group, may ack and close its todos, does not post)",
21
21
  "keel chat group archive <group>",
@@ -74,10 +74,10 @@ const VALUED = {
74
74
  "--compact-at": "compactAt",
75
75
  };
76
76
  const REPEATED = { "--member": "members" };
77
- const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen", "--closed": "closed", "--stamp": "stamp", "--help": "help", "-h": "help" };
77
+ const SWITCHES = { "--json": "json", "--peek": "peek", "--all": "all", "--mine": "mine", "--follow": "follow", "--once": "once", "--mail": "mail", "--check": "check", "--ack": "ack", "--listen": "listen", "--closed": "closed", "--stamp": "stamp", "--help": "help", "-h": "help", "--prune": "prune" };
78
78
 
79
79
  function parseChatArgs(argv) {
80
- const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false, closed: false, stamp: false, help: false };
80
+ const options = { positionals: [], members: [], json: false, peek: false, all: false, mine: false, follow: false, once: false, mail: false, check: false, ack: false, listen: false, closed: false, stamp: false, help: false, prune: false };
81
81
  for (const key of Object.values(VALUED)) options[key] = null;
82
82
  for (let index = 0; index < argv.length; index += 1) {
83
83
  const arg = argv[index];
@@ -286,6 +286,13 @@ function dispatch(where, options) {
286
286
  const [command, ...rest] = options.positionals;
287
287
  switch (command) {
288
288
  case "role": {
289
+ if (options.prune) {
290
+ // Bindings to removed worktrees (#301 D4).
291
+ const pruned = require("./drift").pruneBindings(where);
292
+ if (options.json) out(JSON.stringify({ pruned }));
293
+ else out(pruned.length ? pruned.map((entry) => `Pruned ${entry.role} from ${entry.worktree}.`).join("\n") : "No binding points at a removed worktree.");
294
+ return 0;
295
+ }
289
296
  let role = store.currentRole(where);
290
297
  if (options.set !== null) role = store.setRole(where, options.set);
291
298
  if (options.alias !== null) {
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ // Binding drift (#301). `roles.json` binds roles to worktrees, but sessions
4
+ // move: a role can stay bound to a removed worktree, or to one no session runs
5
+ // in while its session runs elsewhere, and then nothing wakes it. This reports
6
+ // both; `keel chat role --prune` removes the first.
7
+
8
+ const fs = require("fs");
9
+ const path = require("path");
10
+ const { spawnSync } = require("child_process");
11
+ const store = require("./store");
12
+
13
+ const UNATTENDED_MS = 2 * 60 * 60 * 1000;
14
+
15
+ function realpath(file) {
16
+ try {
17
+ return fs.realpathSync(file);
18
+ } catch {
19
+ return path.resolve(file);
20
+ }
21
+ }
22
+
23
+ function liveWorktrees(where) {
24
+ const result = spawnSync("git", ["worktree", "list", "--porcelain"], { cwd: where.worktree, encoding: "utf8" });
25
+ if (result.status !== 0) return null;
26
+ return new Set(String(result.stdout).split("\n").filter((line) => line.startsWith("worktree ")).map((line) => realpath(line.slice(9))));
27
+ }
28
+
29
+ // Bindings whose worktree is neither listed by git nor a directory (D1).
30
+ function removedBindings(where) {
31
+ const live = liveWorktrees(where);
32
+ if (!live) return [];
33
+ return Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
34
+ .filter(([worktree, role]) => role && !live.has(realpath(worktree)) && !fs.existsSync(worktree))
35
+ .map(([worktree, role]) => ({ role, worktree }))
36
+ .sort((a, b) => (a.role < b.role ? -1 : 1));
37
+ }
38
+
39
+ function roleDrift(where, now = Date.now()) {
40
+ const { presenceFile } = require("./notice");
41
+ const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))].sort();
42
+ const unattended = [];
43
+ for (const role of roles) {
44
+ const waiting = [];
45
+ let unread = [];
46
+ try {
47
+ unread = store.unread(where, role).filter((record) => store.wakes(record, role));
48
+ } catch {
49
+ unread = [];
50
+ }
51
+ if (unread.length) waiting.push(`${unread.length} unread addressed record${unread.length === 1 ? "" : "s"}`);
52
+ const note = path.join(where.root, "shift", `${role}.md`);
53
+ if (fs.existsSync(note)) waiting.push(`shift note waiting since ${store.isoLocal(fs.statSync(note).mtime)}`);
54
+ if (!waiting.length) continue;
55
+ const lastActive = store.readJsonFile(presenceFile(where, role)).last_active || null;
56
+ const last = Date.parse(lastActive || "");
57
+ if (!Number.isNaN(last) && now - last <= UNATTENDED_MS) continue;
58
+ unattended.push({ role, waiting, lastActive });
59
+ }
60
+ return { removed: removedBindings(where), unattended };
61
+ }
62
+
63
+ function driftLines(drift) {
64
+ return [
65
+ ...drift.removed.map((entry) => ({
66
+ key: `drift ${entry.role} ${entry.worktree}`,
67
+ text: `${entry.role} is bound to ${entry.worktree}, which no longer exists; \`keel chat role --prune\` drops it`,
68
+ })),
69
+ ...drift.unattended.map((entry) => ({
70
+ key: `drift ${entry.role}`,
71
+ text: `${entry.role} has ${entry.waiting.join(" and ")} and no session active since ${entry.lastActive || "ever"}; `
72
+ + `if its session runs in another worktree, bind ${entry.role} there, since nothing wakes it where it is bound`,
73
+ })),
74
+ ];
75
+ }
76
+
77
+ // Removes the bindings to removed worktrees (D4).
78
+ function pruneBindings(where) {
79
+ const removed = removedBindings(where);
80
+ if (!removed.length) return [];
81
+ const roles = store.readJsonFile(path.join(where.root, "roles.json"));
82
+ for (const entry of removed) delete roles[entry.worktree];
83
+ store.writeRoles(where, roles);
84
+ return removed;
85
+ }
86
+
87
+ module.exports = { driftLines, pruneBindings, roleDrift };
@@ -170,6 +170,47 @@ const HOST_EVENTS = {
170
170
  // wake signal and must mean only "something addressed to you arrived".
171
171
  const MAIL_POINTER = "Direct messages can also be read with the 5.83 `keel mail read`.";
172
172
 
173
+ // --- host-run sessions (#300) ---------------------------------------------------------
174
+ //
175
+ // A host scheduled task starts its runs in the folder it was created from, so a
176
+ // run can start in a role's worktree. Its SessionStart fires before its prompt
177
+ // exists, so the hook keeps the presence it replaces per session id (D1), and
178
+ // the first prompt decides: one starting `<scheduled-task` marks the session a
179
+ // host run and restores that presence (D2); a host run then writes nothing (D3).
180
+
181
+ const HOST_RUN_MARKER = "<scheduled-task";
182
+
183
+ function sessionFile(where, payload) {
184
+ const id = typeof payload.session_id === "string" ? payload.session_id : "";
185
+ return /^[A-Za-z0-9._-]{1,128}$/.test(id) ? path.join(where.root, "sessions", `${id}.json`) : null;
186
+ }
187
+
188
+ function rememberSession(where, role, file) {
189
+ if (!file) return;
190
+ const previous = fs.existsSync(presenceFile(where, role)) ? store.readJsonFile(presenceFile(where, role)) : null;
191
+ try {
192
+ store.writeJsonAtomic(where, file, { role, previous, decided: false, host_run: false });
193
+ } catch {
194
+ // Like presence, a convenience: never fail the hook.
195
+ }
196
+ }
197
+
198
+ // Returns true when this prompt marked the session a host run.
199
+ function decideSession(where, file, session, prompt) {
200
+ const hostRun = String(prompt || "").trimStart().startsWith(HOST_RUN_MARKER);
201
+ try {
202
+ store.writeJsonAtomic(where, file, { ...session, decided: true, host_run: hostRun });
203
+ if (hostRun) {
204
+ const target = presenceFile(where, session.role);
205
+ if (session.previous) store.writeJsonAtomic(where, target, session.previous);
206
+ else fs.rmSync(target, { force: true });
207
+ }
208
+ } catch {
209
+ // Presence stays as the SessionStart left it.
210
+ }
211
+ return hostRun;
212
+ }
213
+
173
214
  function hook(event, input, { mail = false } = {}) {
174
215
  if (!(event in HOST_EVENTS)) return { code: 0 };
175
216
  let payload = {};
@@ -194,10 +235,18 @@ function hook(event, input, { mail = false } = {}) {
194
235
  return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
195
236
  }
196
237
  if (!where || !role) return { code: 0 };
238
+ const file = sessionFile(where, payload);
239
+ const session = file && fs.existsSync(file) ? store.readJsonFile(file) : null;
240
+ if (event === "session-end" && file) fs.rmSync(file, { force: true });
241
+ if (session && session.host_run) return { code: 0 };
242
+ if (event === "user-prompt-submit" && session && session.role === role && !session.decided) {
243
+ if (decideSession(where, file, session, payload.prompt)) return { code: 0 };
244
+ }
197
245
  if (event === "session-end") {
198
246
  touchPresence(where, role, "offline");
199
247
  return { code: 0 };
200
248
  }
249
+ if (event === "session-start") rememberSession(where, role, file);
201
250
  const started = event === "session-start" ? { source: typeof payload.source === "string" ? payload.source : null } : null;
202
251
  touchPresence(where, role, "online", mail ? null : "claude-code", started);
203
252
  const chatText = noticeText(where, role);
@@ -837,12 +837,21 @@ function resolveContext(repo, options) {
837
837
  const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
838
838
  .filter(([worktree, role]) => worktree !== where.worktree && role);
839
839
  if (bound.length) {
840
+ // Roles nobody is active for where they are bound (#301 D5).
841
+ let unattended = [];
842
+ try {
843
+ unattended = require("./chat/drift").roleDrift(where).unattended.map((entry) => entry.role);
844
+ } catch {
845
+ unattended = [];
846
+ }
840
847
  context.warnings.push(
841
848
  "This worktree has no chat role while other worktrees here have one; "
842
849
  + "sessions address each other by role. Bind one with "
843
850
  + "`keel chat role --set <name>`."
851
+ + (unattended.length ? ` Roles with nobody active where they are bound: ${unattended.join(", ")}.` : "")
844
852
  );
845
853
  context.roleReminder = true;
854
+ if (unattended.length) context.unattendedRoles = unattended;
846
855
  }
847
856
  }
848
857
  } catch {
@@ -80,6 +80,8 @@ function patrol(where, role, options) {
80
80
  result.warnings.push(...routed.warnings);
81
81
  // D6: presence is reported, never acted on.
82
82
  const roles = [...new Set(Object.values(store.readJsonFile(path.join(where.root, "roles.json"))).filter(Boolean))].sort();
83
+ // Bindings that drifted from where sessions run (#301 D2): reported, never acted on.
84
+ result.drift = require("./chat/drift").driftLines(require("./chat/drift").roleDrift(where));
83
85
  const threshold = parseSince(options.idle);
84
86
  for (const name of roles) {
85
87
  const presence = notice.presenceOf(where, name);
@@ -149,6 +151,7 @@ function currentSnapshot(where, role, result, options) {
149
151
  const status = git(primary, ["status", "--porcelain"]);
150
152
  if (status !== null) entries[`checkout ${primary}`] = `${status ? status.split("\n").length : 0} uncommitted paths`;
151
153
  }
154
+ for (const line of result.drift) entries[line.key] = line.text;
152
155
  for (const row of result.roles) {
153
156
  entries[`role ${row.role}`] = `${row.idle ? "idle" : "active"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`;
154
157
  }
@@ -198,6 +201,7 @@ function render(result) {
198
201
  for (const sent of result.notices) lines.push(`notified ${sent.to}: ${sent.text}`);
199
202
  for (const wait of result.unchecked) lines.push(`unchecked: ${wait.from} waits for ${wait.condition}; pass --issues to check it`);
200
203
  for (const warning of result.warnings) lines.push(`warning: ${warning}`);
204
+ for (const line of result.sinceLast ? [] : result.drift) lines.push(`drift: ${line.text}`);
201
205
  // A scheduled run reports roles only through what changed (D1).
202
206
  for (const row of result.sinceLast ? [] : result.roles) {
203
207
  lines.push(`role ${row.role}: ${row.presence}${row.idle ? " (idle)" : ""}, last active ${row.lastActive || "unknown"}, ${row.openTodos} open todo${row.openTodos === 1 ? "" : "s"}`);
@@ -243,7 +247,7 @@ function hostTask(where) {
243
247
  const prompt = [
244
248
  `You run the Keel patrol for chat role ${role} of the repository at ${worktree}. Do exactly the steps below and nothing else.`,
245
249
  "",
246
- `Do not change into that directory: run every command with the paths given, so this session does not act as ${role} (Keel's session hooks follow the working directory). `
250
+ "Run every command with the paths given. "
247
251
  + "Do not edit files, commit, push, close or comment on issues, or message anyone yourself: `keel patrol` sends the coordinator what changed.",
248
252
  "",
249
253
  `1. Run \`git -C ${at} fetch -q origin\`. If it fails, keep its error and continue.`,
@@ -269,6 +273,8 @@ function renderTask(task) {
269
273
  `task id: ${task.taskId}`,
270
274
  `schedule: ${task.cronExpression ? `${task.cronExpression} (from every: ${task.every}; hosts may add jitter)` : task.cronNote}`,
271
275
  `model: ${task.model || "no model is declared: choose a small model; Keel names none"}`,
276
+ "Create it from a session whose folder is bound to no role: a host task starts its runs in the folder it was created from, "
277
+ + "and Keel recognizes such a run only once its prompt arrives (#300).",
272
278
  `description: ${task.description}`,
273
279
  "prompt:",
274
280
  task.prompt,
package/src/core/shift.js CHANGED
@@ -427,12 +427,14 @@ function armWake(where, role, since) {
427
427
  return child.pid;
428
428
  }
429
429
 
430
- // The role's current session started after `since`, from a clear or a fresh start.
430
+ // The role's current session start, when it is after `since` from a clear or a
431
+ // fresh start; null otherwise.
431
432
  function startedSince(where, role, since) {
432
433
  const { presenceFile } = require("./chat/notice");
433
434
  const presence = store.readJsonFile(presenceFile(where, role));
434
435
  const started = Date.parse(presence.session_started || "");
435
- return !Number.isNaN(started) && started >= since && WAKE_SOURCES.has(presence.session_source);
436
+ const qualifies = !Number.isNaN(started) && started >= since && WAKE_SOURCES.has(presence.session_source);
437
+ return qualifies ? presence.session_started : null;
436
438
  }
437
439
 
438
440
  function writeWake(where, role) {
@@ -448,11 +450,18 @@ function writeWake(where, role) {
448
450
 
449
451
  function waitForWake(where, role, since) {
450
452
  const poll = envMs("KEEL_SHIFT_WAKE_POLL_MS", 5000);
453
+ const settle = envMs("KEEL_SHIFT_WAKE_SETTLE_MS", 15000);
451
454
  const deadline = Date.now() + envMs("KEEL_SHIFT_WAKE_TIMEOUT_MS", 2 * 60 * 60 * 1000);
455
+ // A qualifying start must stay unchanged for `settle` (#300 D4): a host
456
+ // run's start is reverted once its first prompt shows what it is.
457
+ let pending = null;
452
458
  const tick = () => {
453
459
  // A note resumed by hand needs no wake; give up after the time limit.
454
460
  if (!fs.existsSync(notePath(where, role)) || Date.now() > deadline) return;
455
- if (startedSince(where, role, since)) {
461
+ const started = startedSince(where, role, since);
462
+ if (!started) pending = null;
463
+ else if (!pending || pending.value !== started) pending = { value: started, at: Date.now() };
464
+ else if (Date.now() - pending.at >= settle) {
456
465
  writeWake(where, role);
457
466
  return;
458
467
  }