@christang/keel 5.117.0 → 5.119.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
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.117.0 -->
1
+ <!-- keel:start version=5.119.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.117.0",
3
+ "version": "5.119.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.117.0",
9
+ "version": "5.119.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.117.0",
5
+ "version": "5.119.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.117.0",
3
+ "version": "5.119.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.117.0",
3
+ "version": "5.119.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.117.0"
51
- PROTOCOL_VERSION = "5.117.0"
50
+ PACKAGE_VERSION = "5.119.0"
51
+ PROTOCOL_VERSION = "5.119.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
@@ -5898,6 +5898,74 @@ 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
+
5901
5969
  def validate_host_run_session_scenario() -> int:
5902
5970
  """Issue #300: a scheduled run started in a role's worktree is not that role.
5903
5971
 
@@ -5969,6 +6037,121 @@ def validate_host_run_session_scenario() -> int:
5969
6037
  return 0
5970
6038
 
5971
6039
 
6040
+ def validate_shift_history_scenario() -> int:
6041
+ """Issue #304: a cleared shift's conversation stays findable.
6042
+
6043
+ The hooks record each transcript a role's session runs in; a scheduled
6044
+ run's is undone; `keel shift history` lists and greps them; `ready` and
6045
+ the clear hint name the history and Remote Control.
6046
+ """
6047
+ label = "shift-history:"
6048
+ with tempfile.TemporaryDirectory(prefix="keel-shift-history-") as raw:
6049
+ base = Path(raw)
6050
+ rtl, verify, env, _ = shift_scratch(base)
6051
+ transcripts = base / "transcripts"
6052
+ transcripts.mkdir()
6053
+
6054
+ def transcript(name: str, said: str) -> Path:
6055
+ path = transcripts / f"{name}.jsonl"
6056
+ path.write_text("\n".join(json.dumps(record) for record in (
6057
+ {"type": "user", "timestamp": "2026-10-12T01:00:00.000Z", "message": {"role": "user", "content": "carry on with R008"}},
6058
+ {"type": "assistant", "timestamp": "2026-10-12T01:00:05.000Z",
6059
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
6060
+ )) + "\n", encoding="utf-8")
6061
+ return path
6062
+
6063
+ a = transcript("a", "The timing fix for the clock gate lands in R008 after the review.")
6064
+ b = transcript("b", "Resumed from the note.")
6065
+ c = transcript("c", "patrol run")
6066
+
6067
+ def hook(event: str, payload: dict) -> None:
6068
+ subprocess.run(
6069
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
6070
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
6071
+ input=json.dumps({"cwd": str(verify), **payload}),
6072
+ )
6073
+
6074
+ def history(*args: str) -> subprocess.CompletedProcess[str]:
6075
+ return run_keel(verify, "shift", "history", *args, env=env)
6076
+
6077
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "s1", "transcript_path": str(a)})
6078
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "go", "transcript_path": str(a)})
6079
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
6080
+ if "keel shift history verify" not in readied.stdout:
6081
+ report(f"{label} ready does not name keel shift history verify: {readied.stdout!r} {readied.stderr!r}")
6082
+ return 1
6083
+ if "Remote Control" not in readied.stdout:
6084
+ report(f"{label} the clear hint does not name Remote Control: {readied.stdout!r}")
6085
+ return 1
6086
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "clear", "session_id": "s1", "transcript_path": str(b)})
6087
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "resume", "transcript_path": str(b)})
6088
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1", "transcript_path": str(c)})
6089
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1",
6090
+ "prompt": '<scheduled-task name="patrol">run', "transcript_path": str(c)})
6091
+
6092
+ listed = history("verify")
6093
+ if listed.returncode != 0:
6094
+ report(f"{label} keel shift history failed: {listed.stderr}")
6095
+ return 1
6096
+ lines = [line for line in listed.stdout.splitlines() if ".jsonl" in line]
6097
+ if len(lines) != 2:
6098
+ report(f"{label} expected two transcript segments, got: {listed.stdout!r}")
6099
+ return 1
6100
+ if str(b) not in lines[0] or "now" not in lines[0]:
6101
+ report(f"{label} the newest segment is not B, still current: {lines[0]!r}")
6102
+ return 1
6103
+ if str(a) not in lines[1] or "now" in lines[1]:
6104
+ report(f"{label} the older segment is not A, ended: {lines[1]!r}")
6105
+ return 1
6106
+ if str(c) in listed.stdout:
6107
+ report(f"{label} the scheduled run's transcript is listed: {listed.stdout!r}")
6108
+ return 1
6109
+ found = history("verify", "--grep", "clock gate")
6110
+ if found.returncode != 0:
6111
+ report(f"{label} --grep for a phrase in A exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
6112
+ return 1
6113
+ if "clock gate" not in found.stdout or str(a) not in found.stdout:
6114
+ report(f"{label} --grep does not print the phrase under A: {found.stdout!r}")
6115
+ return 1
6116
+ missing = history("verify", "--grep", "nothing like this")
6117
+ if missing.returncode != 1:
6118
+ report(f"{label} --grep for an absent phrase exited {missing.returncode}.")
6119
+ return 1
6120
+ as_json = json.loads(history("verify", "--json").stdout)
6121
+ if [seg.get("transcript") for seg in as_json.get("segments", [])] != [str(b), str(a)]:
6122
+ report(f"{label} --json segments are {as_json.get('segments')!r}.")
6123
+ return 1
6124
+
6125
+ # Earlier history, kept by Claude before Keel recorded anything (D6).
6126
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
6127
+ bound = next(path for path, role in roles.items() if role == "verify")
6128
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
6129
+ project.mkdir(parents=True)
6130
+ (project / "d.jsonl").write_text("\n".join(json.dumps(record) for record in (
6131
+ {"type": "user", "timestamp": "2026-10-04T13:19:18.000Z", "cwd": bound, "message": {"role": "user", "content": "start the shift"}},
6132
+ {"type": "assistant", "timestamp": "2026-10-04T13:27:58.000Z", "cwd": bound,
6133
+ "message": {"role": "assistant", "content": [{"type": "text", "text": "The DMC arbiter plan was agreed on the first day."}]}},
6134
+ )) + "\n", encoding="utf-8")
6135
+ (project / "e.jsonl").write_text(json.dumps(
6136
+ {"type": "user", "timestamp": "2026-10-12T11:57:15.000Z", "cwd": bound, "message": {"role": "user", "content": '<scheduled-task name="patrol">run'}}
6137
+ ) + "\n", encoding="utf-8")
6138
+ found_env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
6139
+ earlier = run_keel(verify, "shift", "history", "verify", env=found_env)
6140
+ d_line = next((line for line in earlier.stdout.splitlines() if "d.jsonl" in line), "")
6141
+ if "(found)" not in d_line:
6142
+ report(f"{label} the earlier transcript D is not listed as found: {earlier.stdout!r} {earlier.stderr!r}")
6143
+ return 1
6144
+ if "e.jsonl" in earlier.stdout:
6145
+ report(f"{label} the scheduled run E is listed: {earlier.stdout!r}")
6146
+ return 1
6147
+ arbiter = run_keel(verify, "shift", "history", "verify", "--grep", "arbiter plan", env=found_env)
6148
+ if "arbiter plan" not in arbiter.stdout:
6149
+ report(f"{label} --grep does not search the earlier transcript D: {arbiter.stdout!r}")
6150
+ return 1
6151
+ report("shift-history scenario passed.")
6152
+ return 0
6153
+
6154
+
5972
6155
  def validate_shift_coordinator_last_scenario() -> int:
5973
6156
  """Issue #289: the coordinator starts the others before its own shift ends.
5974
6157
 
@@ -39648,6 +39831,8 @@ SCENARIOS: tuple = (
39648
39831
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39649
39832
  ("shift-self", validate_shift_self_scenario),
39650
39833
  ("shift-self-wake", validate_shift_self_wake_scenario),
39834
+ ("shift-history", validate_shift_history_scenario),
39835
+ ("role-drift", validate_role_drift_scenario),
39651
39836
  ("host-run-session", validate_host_run_session_scenario),
39652
39837
  ("shift-without-role", validate_shift_without_role_scenario),
39653
39838
  ("resource-lock", validate_resource_lock_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 };
@@ -185,11 +185,34 @@ function sessionFile(where, payload) {
185
185
  return /^[A-Za-z0-9._-]{1,128}$/.test(id) ? path.join(where.root, "sessions", `${id}.json`) : null;
186
186
  }
187
187
 
188
+ // Each transcript a role's session runs in, with when it started and when the
189
+ // next replaced it (#304 D1): a clear keeps the session but starts a new file.
190
+ function segmentsFile(where, role) {
191
+ return path.join(where.root, "shift", "segments", `${role}.json`);
192
+ }
193
+
194
+ function recordSegment(where, role, transcript) {
195
+ if (typeof transcript !== "string" || !path.isAbsolute(transcript)) return;
196
+ try {
197
+ const file = segmentsFile(where, role);
198
+ const segments = Array.isArray(store.readJsonFile(file).segments) ? store.readJsonFile(file).segments : [];
199
+ const last = segments[segments.length - 1];
200
+ if (last && last.transcript === transcript) return;
201
+ const now = store.isoLocal(new Date());
202
+ if (last && !last.ended) last.ended = now;
203
+ segments.push({ transcript, started: now, ended: null });
204
+ store.writeJsonAtomic(where, file, { segments });
205
+ } catch {
206
+ // A convenience, like presence: never fail the hook.
207
+ }
208
+ }
209
+
188
210
  function rememberSession(where, role, file) {
189
211
  if (!file) return;
190
212
  const previous = fs.existsSync(presenceFile(where, role)) ? store.readJsonFile(presenceFile(where, role)) : null;
213
+ const segments = fs.existsSync(segmentsFile(where, role)) ? store.readJsonFile(segmentsFile(where, role)) : null;
191
214
  try {
192
- store.writeJsonAtomic(where, file, { role, previous, decided: false, host_run: false });
215
+ store.writeJsonAtomic(where, file, { role, previous, segments, decided: false, host_run: false });
193
216
  } catch {
194
217
  // Like presence, a convenience: never fail the hook.
195
218
  }
@@ -204,6 +227,9 @@ function decideSession(where, file, session, prompt) {
204
227
  const target = presenceFile(where, session.role);
205
228
  if (session.previous) store.writeJsonAtomic(where, target, session.previous);
206
229
  else fs.rmSync(target, { force: true });
230
+ // The run's transcript is not the role's (#304 D2).
231
+ if (session.segments) store.writeJsonAtomic(where, segmentsFile(where, session.role), session.segments);
232
+ else fs.rmSync(segmentsFile(where, session.role), { force: true });
207
233
  }
208
234
  } catch {
209
235
  // Presence stays as the SessionStart left it.
@@ -249,6 +275,7 @@ function hook(event, input, { mail = false } = {}) {
249
275
  if (event === "session-start") rememberSession(where, role, file);
250
276
  const started = event === "session-start" ? { source: typeof payload.source === "string" ? payload.source : null } : null;
251
277
  touchPresence(where, role, "online", mail ? null : "claude-code", started);
278
+ if (event === "session-start" || event === "user-prompt-submit") recordSegment(where, role, payload.transcript_path);
252
279
  const chatText = noticeText(where, role);
253
280
  const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
254
281
  if (event === "session-start") {
@@ -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"}`);
package/src/core/shift.js CHANGED
@@ -29,6 +29,7 @@ const USAGE = [
29
29
  "keel shift start <role> [text] wake the cleared role to resume (once its note waits)",
30
30
  "keel shift resume [--role r] [--json] print and consume this role's note (--role: from an unbound worktree)",
31
31
  "keel shift status [--json] each role's shift state",
32
+ "keel shift history [role] [--grep t] a role's past transcripts and notes; --grep searches them (#304)",
32
33
  "Options: --repo <path>. See docs/shift-change.md.",
33
34
  ].join("\n");
34
35
 
@@ -566,6 +567,115 @@ function status(where) {
566
567
  return [...roles.values()].sort((a, b) => (a.role < b.role ? -1 : 1));
567
568
  }
568
569
 
570
+ // --- history (#304 D3, D4) -------------------------------------------------------
571
+
572
+ function transcriptText(record) {
573
+ const content = record && record.message ? record.message.content : null;
574
+ if (typeof content === "string") return content;
575
+ if (Array.isArray(content)) return content.filter((part) => part && part.type === "text").map((part) => part.text).join("\n");
576
+ return "";
577
+ }
578
+
579
+ function grepTranscript(file, needle, limit = 3) {
580
+ const hits = [];
581
+ const lower = needle.toLowerCase();
582
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
583
+ if (!line.trim()) continue;
584
+ let record;
585
+ try {
586
+ record = JSON.parse(line);
587
+ } catch {
588
+ continue;
589
+ }
590
+ if (record.type !== "user" && record.type !== "assistant") continue;
591
+ const text = transcriptText(record);
592
+ const at = text.toLowerCase().indexOf(lower);
593
+ if (at < 0) continue;
594
+ const from = Math.max(0, at - 60);
595
+ const snippet = text.slice(from, at + needle.length + 60).replace(/\s+/g, " ");
596
+ const hit = { timestamp: record.timestamp || null, speaker: record.type, snippet: `${from ? "…" : ""}${snippet}…` };
597
+ // A transcript can hold the same message twice; report it once.
598
+ if (hits.some((seen) => seen.timestamp === hit.timestamp && seen.snippet === hit.snippet)) continue;
599
+ hits.push(hit);
600
+ if (hits.length >= limit) break;
601
+ }
602
+ return hits;
603
+ }
604
+
605
+ // Transcripts Claude already keeps for a worktree (#304 D6, F5): its project
606
+ // directory is the cwd with every non-alphanumeric character turned into `-`.
607
+ function claudeTranscripts(worktree) {
608
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
609
+ const found = [];
610
+ for (const cwd of new Set([worktree, realpath(worktree)])) {
611
+ const dir = path.join(config, "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"));
612
+ for (const name of safeList(dir)) {
613
+ if (!name.endsWith(".jsonl")) continue;
614
+ const file = path.join(dir, name);
615
+ let first = null;
616
+ let last = null;
617
+ let opening = null;
618
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
619
+ if (!line.trim()) continue;
620
+ let record;
621
+ try {
622
+ record = JSON.parse(line);
623
+ } catch {
624
+ continue;
625
+ }
626
+ if (record.timestamp) {
627
+ first = first || record.timestamp;
628
+ last = record.timestamp;
629
+ }
630
+ if (opening === null && record.type === "user") opening = transcriptText(record);
631
+ }
632
+ // A host scheduled run is not the role's conversation (#300).
633
+ if (opening && opening.trimStart().startsWith("<scheduled-task")) continue;
634
+ if (!first) continue;
635
+ found.push({ transcript: file, started: store.isoLocal(new Date(first)), ended: store.isoLocal(new Date(last)), found: true });
636
+ }
637
+ }
638
+ return found;
639
+ }
640
+
641
+ function history(where, named, grep) {
642
+ const role = named || store.currentRole(where);
643
+ if (!role) throw new ShiftError("keel shift history needs a role: name it, or run it in a worktree bound to one.");
644
+ store.checkName(role, "Role");
645
+ const file = path.join(shiftDir(where), "segments", `${role}.json`);
646
+ const stored = fs.existsSync(file) ? store.readJsonFile(file).segments : [];
647
+ const recorded = Array.isArray(stored) ? stored : [];
648
+ const known = new Set(recorded.map((segment) => segment.transcript));
649
+ const bound = Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
650
+ .filter(([, name]) => name === role).map(([worktree]) => worktree);
651
+ const earlier = bound.flatMap(claudeTranscripts).filter((segment) => !known.has(segment.transcript));
652
+ const seen = new Set();
653
+ // Newest first; the sort is stable, so segments recorded in the same second keep their order.
654
+ const segments = [...recorded.slice().reverse(), ...earlier]
655
+ .filter((segment) => !seen.has(segment.transcript) && seen.add(segment.transcript))
656
+ .sort((a, b) => Date.parse(b.started) - Date.parse(a.started))
657
+ .map((segment) => ({ ...segment, exists: fs.existsSync(segment.transcript) }));
658
+ const notes = safeList(path.join(shiftDir(where), "history"))
659
+ .filter((name) => name.startsWith(`${role}-`) && name.endsWith(".md"))
660
+ .sort().reverse().map((name) => path.join(shiftDir(where), "history", name));
661
+ if (grep) {
662
+ for (const segment of segments) segment.matches = segment.exists ? grepTranscript(segment.transcript, grep) : [];
663
+ }
664
+ return { role, segments, notes };
665
+ }
666
+
667
+ function renderHistory(result, grep) {
668
+ const lines = [];
669
+ for (const segment of result.segments) {
670
+ if (grep && !segment.matches.length) continue;
671
+ lines.push(`${segment.started} → ${segment.ended || "now"} ${segment.transcript}${segment.found ? " (found)" : ""}${segment.exists ? "" : " (missing)"}`);
672
+ for (const hit of segment.matches || []) lines.push(` ${hit.timestamp || "?"} ${hit.speaker}: ${hit.snippet}`);
673
+ }
674
+ if (!grep) for (const note of result.notes) lines.push(`note ${note}`);
675
+ if (!lines.length) return grep ? `No transcript of ${result.role} mentions ${JSON.stringify(grep)}.` : `No shift history recorded for ${result.role}.`;
676
+ return lines.join("\n");
677
+ }
678
+
569
679
  function safeList(dir) {
570
680
  try {
571
681
  return fs.readdirSync(dir);
@@ -597,6 +707,7 @@ function describe(row) {
597
707
 
598
708
  const CLEAR_HINT = [
599
709
  "Session state a clear destroys — scheduled jobs, Remote Control — is not in Keel; if the note does not say how to re-create it, add that first.",
710
+ "A session serving Remote Control cannot be cleared: turn Remote Control off, clear, then turn it back on.",
600
711
  "Now clear this session:",
601
712
  "- Claude desktop app: call `clear_session(\"self\")` (the owner approves it), or type /clear;",
602
713
  "- Claude Code CLI: /clear;",
@@ -615,7 +726,10 @@ function clearHint(result) {
615
726
  last = `No request named ${result.role}, so nobody is set to start the new session: type into it, `
616
727
  + "or run `keel shift ready --wake` again with this note, which wakes it once it starts.";
617
728
  }
618
- return `${CLEAR_HINT}\n${last}`;
729
+ const history = result.role
730
+ ? `\nThis shift's conversation stays in its transcript; \`keel shift history ${result.role}\` finds it after the clear.`
731
+ : "";
732
+ return `${CLEAR_HINT}\n${last}${history}`;
619
733
  }
620
734
 
621
735
  function runShift(argv) {
@@ -629,6 +743,7 @@ function runShift(argv) {
629
743
  else if (arg === "--role") options.role = argv[++index] || "";
630
744
  else if (arg === "--since") options.since = Number(argv[++index]);
631
745
  else if (arg === "--wake") options.wake = true;
746
+ else if (arg === "--grep") options.grep = argv[++index] || "";
632
747
  else if (arg === "--help" || arg === "-h") {
633
748
  process.stdout.write(`${USAGE}\n`);
634
749
  return 0;
@@ -687,6 +802,11 @@ function runShift(argv) {
687
802
  out(result, `${result.text.replace(/\s+$/, "")}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}`);
688
803
  return 0;
689
804
  }
805
+ case "history": {
806
+ const result = history(where, rest[0] || null, options.grep);
807
+ out(result, renderHistory(result, options.grep));
808
+ return options.grep && !result.segments.some((segment) => segment.matches.length) ? 1 : 0;
809
+ }
690
810
  case "status": {
691
811
  const rows = status(where);
692
812
  out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");