@christang/keel 5.198.0 → 5.200.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.198.0",
3
+ "version": "5.200.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.198.0 -->
1
+ <!-- keel:start version=5.200.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.198.0",
3
+ "version": "5.200.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.198.0",
9
+ "version": "5.200.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.198.0",
5
+ "version": "5.200.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.198.0",
3
+ "version": "5.200.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.198.0",
3
+ "version": "5.200.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",
@@ -64,6 +64,9 @@ class FakeSlack:
64
64
  # (token, channel) pairs `chat.postMessage` answers with
65
65
  # `not_in_channel`, for a bot nobody invited.
66
66
  self.not_in_channel: set[tuple[str, str]] = set()
67
+ # Methods answered with a chosen error body until cleared, such as a
68
+ # `missing_scope` with its `needed` field.
69
+ self.failing: dict[str, dict] = {}
67
70
  # Which app token each Socket Mode connection was opened with.
68
71
  self.socket_apps: dict[socket.socket, str] = {}
69
72
  self.pending_apps: dict[str, str] = {}
@@ -93,6 +96,14 @@ class FakeSlack:
93
96
  with self.lock:
94
97
  self.rate_limit_next.append((method, retry_after))
95
98
 
99
+ def fail(self, method: str, body: dict | None) -> None:
100
+ """Answer every call of `method` with `body` (HTTP 200), or normally again when `body` is None."""
101
+ with self.lock:
102
+ if body is None:
103
+ self.failing.pop(method, None)
104
+ else:
105
+ self.failing[method] = body
106
+
96
107
  def calls_to(self, method: str) -> list[dict]:
97
108
  with self.lock:
98
109
  return [call for call in self.calls if call["method"] == method and not call.get("rate_limited")]
@@ -168,6 +179,8 @@ class FakeSlack:
168
179
  self.calls.append({"method": method, "params": params, "rate_limited": True, "at": time.time()})
169
180
  return 429, {"Retry-After": str(retry_after)}, {"ok": False, "error": "ratelimited"}
170
181
  self.calls.append({"method": method, "params": params, "at": time.time()})
182
+ if method in self.failing:
183
+ return 200, {}, dict(self.failing[method])
171
184
  token = str(params.get("_auth", "")).removeprefix("Bearer ")
172
185
  identity = self.identities.get(token, {"user_id": "UBOT", "bot_id": "BBOT"})
173
186
  if method == "auth.test":
@@ -2989,6 +2989,76 @@ def validate_chat_bridge_lifecycle_scenario() -> int:
2989
2989
  return 0
2990
2990
 
2991
2991
 
2992
+ def validate_chat_bridge_logs_once_scenario() -> int:
2993
+ """Issue #460: a failure that never changes is logged once, and a missing scope is named.
2994
+
2995
+ On 2026-10-25 the bridge log held 2944 copies of one project's
2996
+ `this repository has no remote` (one per archive sync) and 278 of
2997
+ `catch-up failed: … missing_scope` (one per reconnect), and none named
2998
+ the scope Slack said was missing. A running bridge now logs each repeating
2999
+ failure once, a recovery once, and names Slack's `needed` scopes.
3000
+ """
3001
+ label = "chat-bridge-logs-once:"
3002
+ if chat_bridge_node_missing("chat-bridge-logs-once"):
3003
+ return 3
3004
+ FakeSlack = fake_slack_class()
3005
+ with tempfile.TemporaryDirectory(prefix="keel-chat-460-") as raw, FakeSlack() as slack:
3006
+ base = Path(raw)
3007
+ rtl, _, env = chat_scratch_group(base)
3008
+ chat_slack_config(rtl, {"soc": "CSOC"})
3009
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_ARCHIVE_EVERY_MS": "300"}
3010
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
3011
+ slack.fail("conversations.history", {"ok": False, "error": "missing_scope", "needed": "channels:history", "provided": "chat:write"})
3012
+
3013
+ def history_calls() -> int:
3014
+ return len(slack.calls_to("conversations.history"))
3015
+
3016
+ bridge = start_chat_bridge(rtl, benv)
3017
+ stderr = ""
3018
+ try:
3019
+ if not slack.wait_for(lambda: slack.sockets and history_calls() >= 1, 10):
3020
+ report(f"{label} the bridge never connected and caught up: {stop_chat_bridge(bridge).strip()}")
3021
+ return 1
3022
+ # Each reconnect is a new `hello` and so a new catch-up, which fails the same way.
3023
+ for _ in range(3):
3024
+ calls = history_calls()
3025
+ slack.drop_connections()
3026
+ if not slack.wait_for(lambda: history_calls() > calls, 15):
3027
+ report(f"{label} the bridge did not catch up again after a reconnect: {stop_chat_bridge(bridge).strip()}")
3028
+ return 1
3029
+ slack.fail("conversations.history", None)
3030
+ calls = history_calls()
3031
+ slack.drop_connections()
3032
+ # The reconnect backoff doubles while sessions stay short: 2, 4, 8, then 16 s.
3033
+ if not slack.wait_for(lambda: history_calls() > calls and slack.sockets, 30):
3034
+ report(f"{label} the bridge did not catch up after the scope was granted: {stop_chat_bridge(bridge).strip()}")
3035
+ return 1
3036
+ time.sleep(2)
3037
+ finally:
3038
+ stderr = stop_chat_bridge(bridge)
3039
+ lines = stderr.splitlines()
3040
+ refusals = [line for line in lines if "this repository has no remote" in line]
3041
+ if len(refusals) != 1:
3042
+ report(f"{label} the archive refusal was logged {len(refusals)} times over syncs every 300 ms, not once: {stderr!r}")
3043
+ return 1
3044
+ failed = [line for line in lines if "catch-up failed" in line]
3045
+ if len(failed) != 1:
3046
+ report(f"{label} the same catch-up failure was logged {len(failed)} times over four connects, not once: {stderr!r}")
3047
+ return 1
3048
+ if "missing_scope: needs channels:history" not in failed[0]:
3049
+ report(f"{label} the catch-up failure does not name the missing scope: {failed[0]!r}")
3050
+ return 1
3051
+ recovered = [line for line in lines if "catch-up works again" in line]
3052
+ if len(recovered) != 1:
3053
+ report(f"{label} the catch-up's recovery was logged {len(recovered)} times, not once: {stderr!r}")
3054
+ return 1
3055
+ if "chat-bridge-logs-once" not in {name for name, _ in registry.SCENARIOS}:
3056
+ report(f"{label} scenario is not registered.")
3057
+ return 1
3058
+ report("chat-bridge-logs-once scenario passed.")
3059
+ return 0
3060
+
3061
+
2992
3062
  def validate_chat_bridge_start_race_scenario() -> int:
2993
3063
  """Issue #226: start, stop, install, and status follow launchd's state.
2994
3064
 
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.198.0"
38
+ PACKAGE_VERSION = "5.200.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.198.0"
41
+ PROTOCOL_VERSION = "5.200.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -101,6 +101,10 @@ SCENARIOS: tuple = (
101
101
  "chat-bridge-start-race",
102
102
  chat.validate_chat_bridge_start_race_scenario,
103
103
  ),
104
+ (
105
+ "chat-bridge-logs-once",
106
+ chat.validate_chat_bridge_logs_once_scenario,
107
+ ),
104
108
  (
105
109
  "chat-owner-mention",
106
110
  chat.validate_chat_owner_mention_scenario,
@@ -416,6 +420,7 @@ SCENARIOS: tuple = (
416
420
  ("shift-self-wake", shift.validate_shift_self_wake_scenario),
417
421
  ("shift-cli-self-shift", shift.validate_shift_cli_self_shift_scenario),
418
422
  ("shift-cli-keeps-old-sessions", shift.validate_shift_cli_keeps_old_sessions_scenario),
423
+ ("shift-resume-removes-old-sessions", shift.validate_shift_resume_removes_old_sessions_scenario),
419
424
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
420
425
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
421
426
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
@@ -3742,9 +3742,20 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
3742
3742
  # #418 (owner, 2026-10-21): no declaration keeps none, so the shift just handed over leaves the
3743
3743
  # session list too; a value that is not a whole number is named and none are kept.
3744
3744
  for keep in (None, "many"):
3745
- olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"])]
3745
+ # #462: after a rename a session's working directory names no bound worktree; Keel's copy of its
3746
+ # transcript under verify still makes it verify's, and one kept under no role stays.
3747
+ moved, stray = old_row(7, str(base / "renamed-away" / "verify")), old_row(8, str(base / "renamed-away" / "other"))
3748
+ (kept_dir / f"{moved['sessionId']}.jsonl.gz").write_bytes(gzip.compress(b'{"type": "user"}\n'))
3749
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"]), moved, stray]
3746
3750
  setup(keep, olds)
3747
3751
  ids = sorted(r["argv"][1] for r in removed())
3752
+ if "07070707" not in ids:
3753
+ report(f"{label} a session of verify's from a missing worktree stayed: {ids!r}")
3754
+ return 1
3755
+ if "08080808" in ids:
3756
+ report(f"{label} a session from a missing worktree kept under no role was removed: {ids!r}")
3757
+ return 1
3758
+ ids = [i for i in ids if i != "07070707"]
3748
3759
  if ids != sorted(["01010101", "02020202", "04040404", OLD[:8]]):
3749
3760
  report(f"{label} the default keeps the wrong number of old sessions (keep_old_sessions {keep!r}): removed {ids!r}")
3750
3761
  return 1
@@ -3764,6 +3775,139 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
3764
3775
  return 0
3765
3776
 
3766
3777
 
3778
+ def validate_shift_resume_removes_old_sessions_scenario() -> int:
3779
+ """Issue #462 (owner, 2026-10-25): a takeover Keel did not carry out left the old shift listed.
3780
+
3781
+ After the workspace rename the owner opened a session by hand and it ran
3782
+ `keel shift resume`; only a delivered hand-over removed old sessions, and it
3783
+ matched them by a working directory the rename had moved. `resume` of a
3784
+ note a CLI session wrote, in a Claude Code session, now removes them as a
3785
+ hand-over does, and a session whose transcript Keel keeps under the role is
3786
+ the role's wherever it ran. It asks the host only when it may remove
3787
+ something.
3788
+ """
3789
+ label = "shift-resume-removes-old-sessions:"
3790
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
3791
+ NEW = "c0ffee00-1111-2222-3333-444444444444"
3792
+ MOVED = "07070707-0000-0000-0000-000000000007"
3793
+ with tempfile.TemporaryDirectory(prefix="keel-shift-462-") as raw:
3794
+ base = Path(raw)
3795
+ rtl, verify, env, _ = shift_scratch(base)
3796
+ calls, agents = base / "claude-calls.jsonl", base / "agents.json"
3797
+ config_dir = base / "claude-config"
3798
+ shift_root = mailbox_common_dir(rtl) / "keel-chat" / "shift"
3799
+ kept_dir = shift_root / "transcripts" / "verify"
3800
+ fake = base / "fake-claude"
3801
+ # The row shapes of shift-cli-keeps-old-sessions: a stopped row has no `status`; `rm` drops the row and
3802
+ # logs whether Keel's copy was there when it ran.
3803
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
3804
+ f"agents, kept = {str(agents)!r}, {str(kept_dir)!r}\n"
3805
+ "argv = sys.argv[1:]\n"
3806
+ "rows = json.loads(open(agents).read())\n"
3807
+ "record = {'argv': argv}\n"
3808
+ "if argv[:1] == ['rm']:\n"
3809
+ " gone = [row for row in rows if row['id'] == argv[1]]\n"
3810
+ " record['kept'] = bool(gone) and os.path.exists(os.path.join(kept, gone[0]['sessionId'] + '.jsonl.gz'))\n"
3811
+ " rows = [row for row in rows if row['id'] != argv[1]]\n"
3812
+ f"open({str(calls)!r}, 'a').write(json.dumps(record) + '\\n')\n"
3813
+ "if argv[:2] == ['agents', '--json']:\n print(json.dumps(rows)); sys.exit(0)\n"
3814
+ "open(agents, 'w').write(json.dumps(rows)); print('ok'); sys.exit(0)\n")
3815
+ fake.chmod(0o755)
3816
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir)}
3817
+ exited = subprocess.Popen(["true"])
3818
+ exited.wait()
3819
+ old_cli = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(exited.pid)}
3820
+ new_cli = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": NEW, "CLAUDE_PID": str(os.getpid())}
3821
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
3822
+ bound = {role: path for path, role in roles.items()}
3823
+ moved_cwd = str(base / "renamed-away" / "verify")
3824
+
3825
+ def transcript(cwd: str, session: str) -> None:
3826
+ project = config_dir / "projects" / re.sub(r"[^A-Za-z0-9]", "-", cwd)
3827
+ project.mkdir(parents=True, exist_ok=True)
3828
+ (project / f"{session}.jsonl").write_text(json.dumps(
3829
+ {"type": "user", "timestamp": "2026-10-21T01:00:00.000Z", "cwd": cwd, "message": {"role": "user", "content": "carry on"}}) + "\n",
3830
+ encoding="utf-8")
3831
+
3832
+ def row(session: str, cwd: str, n: int, **extra: object) -> dict:
3833
+ return {"kind": "background", "name": "verify", "sessionId": session, "id": session[:8], "state": "stopped",
3834
+ "cwd": cwd, "startedAt": 1792400000000 + n * 1000, **extra}
3835
+
3836
+ def readied(text: str) -> None:
3837
+ calls.write_text("")
3838
+ done = run_keel(verify, "shift", "ready", text, env=old_cli)
3839
+ if done.returncode != 0:
3840
+ raise RuntimeError(f"ready failed: {done.stdout} {done.stderr}")
3841
+
3842
+ def host_calls() -> list[list[str]]:
3843
+ return [json.loads(line)["argv"] for line in calls.read_text().splitlines()]
3844
+
3845
+ # The old shift and a pre-rename one Keel kept under verify are verify's; rtl's stopped session is not,
3846
+ # and the session running resume is live.
3847
+ transcript(bound["verify"], OLD)
3848
+ transcript(bound["rtl"], "05050505-0000-0000-0000-000000000005")
3849
+ kept_dir.mkdir(parents=True, exist_ok=True)
3850
+ (kept_dir / f"{MOVED}.jsonl.gz").write_bytes(gzip.compress(b'{"type": "user"}\n'))
3851
+ agents.write_text(json.dumps([
3852
+ row(MOVED, moved_cwd, 1), row("05050505-0000-0000-0000-000000000005", bound["rtl"], 5),
3853
+ row(OLD, bound["verify"], 8),
3854
+ row(NEW, bound["verify"], 9, status="busy", state="working", pid=os.getpid()),
3855
+ ]))
3856
+ readied("next: rerun R021")
3857
+ resumed = run_keel(verify, "shift", "resume", env=new_cli)
3858
+ if resumed.returncode != 0:
3859
+ report(f"{label} resume exited {resumed.returncode}: {resumed.stderr!r}")
3860
+ return 1
3861
+ if "next: rerun R021" not in resumed.stdout:
3862
+ report(f"{label} resume did not print the note: {resumed.stdout!r}")
3863
+ return 1
3864
+ gone = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
3865
+ if not gone:
3866
+ report(f"{label} resume removed no old session: {calls.read_text()!r}")
3867
+ return 1
3868
+ ids = sorted(r["argv"][1] for r in gone)
3869
+ if ids != sorted([OLD[:8], MOVED[:8]]):
3870
+ report(f"{label} resume removed {ids!r}, not the shift handed over and verify's session from a missing worktree.")
3871
+ return 1
3872
+ if not all(r["kept"] for r in gone):
3873
+ report(f"{label} a session was removed before Keel's store held its transcript: {gone!r}")
3874
+ return 1
3875
+ left = {r["id"] for r in json.loads(agents.read_text())}
3876
+ if left != {"05050505", NEW[:8]}:
3877
+ report(f"{label} rtl's session and the current one should stay, and the listed ones are {sorted(left)!r}")
3878
+ return 1
3879
+ for needle in (OLD[:8], MOVED[:8], "keel shift history verify --show"):
3880
+ if needle not in resumed.stdout:
3881
+ report(f"{label} resume does not name {needle!r}: {resumed.stdout!r}")
3882
+ return 1
3883
+
3884
+ # Outside a Claude Code host, and in the session Keel's own delivered hand-over started, there is nothing to
3885
+ # ask the host: the first runs no `claude`, and the hand-over already removed them.
3886
+ readied("next: rerun R022")
3887
+ plain = run_keel(verify, "shift", "resume", env=env)
3888
+ if "next: rerun R022" not in plain.stdout:
3889
+ report(f"{label} resume outside a Claude Code host did not print the note: {plain.stdout!r}")
3890
+ return 1
3891
+ if host_calls():
3892
+ report(f"{label} resume outside a Claude Code host called claude: {host_calls()!r}")
3893
+ return 1
3894
+ readied("next: rerun R023")
3895
+ write_text(shift_root / "queue" / "verify.json", json.dumps(
3896
+ {"role": "verify", "session": OLD, "worktree": bound["verify"], "state": "delivered", "new_session": NEW[:8]}))
3897
+ handed = run_keel(verify, "shift", "resume", env=new_cli)
3898
+ if "next: rerun R023" not in handed.stdout:
3899
+ report(f"{label} resume after a delivered hand-over did not print the note: {handed.stdout!r}")
3900
+ return 1
3901
+ if host_calls():
3902
+ report(f"{label} resume after a delivered hand-over called claude: {host_calls()!r}")
3903
+ return 1
3904
+ if "shift-resume-removes-old-sessions" not in {name for name, _ in registry.SCENARIOS}:
3905
+ report(f"{label} scenario is not registered.")
3906
+ return 1
3907
+ report("shift-resume-removes-old-sessions scenario passed.")
3908
+ return 0
3909
+
3910
+
3767
3911
  def validate_shift_history_show_scenario() -> int:
3768
3912
  """Issue #397 (owner, 2026-10-20): a shift no longer in `claude agents` can be read in full.
3769
3913
 
@@ -892,6 +892,25 @@ function githubRepo(worktree) {
892
892
  return result.status === 0 && match ? match[1] : null;
893
893
  }
894
894
 
895
+ // A failure that repeats unchanged — an archive refusal at every sync, a
896
+ // catch-up failure at every reconnect — is logged once, again only when its
897
+ // line changes, and once more when it clears (#460 D1).
898
+ function onceLog(log) {
899
+ const last = new Map();
900
+ return {
901
+ failed(key, line) {
902
+ if (last.get(key) === line) return;
903
+ last.set(key, line);
904
+ log(line);
905
+ },
906
+ cleared(key, line) {
907
+ if (!last.has(key)) return;
908
+ last.delete(key);
909
+ log(line);
910
+ },
911
+ };
912
+ }
913
+
895
914
  async function createContext(log, { needApp }) {
896
915
  requireWebSocket();
897
916
  const { bot, app } = lifecycle.tokens();
@@ -899,6 +918,7 @@ async function createContext(log, { needApp }) {
899
918
  if (!bot) throw lifecycle.missingTokens("bot token");
900
919
  const ctx = {
901
920
  log,
921
+ once: onceLog(log),
902
922
  token: bot,
903
923
  appToken: app,
904
924
  projects: prepareProjects(),
@@ -963,7 +983,11 @@ function socketSession(ctx, conn) {
963
983
  if (data.type === "hello") {
964
984
  conn.connected = true;
965
985
  writeStatus(ctx);
966
- ctx.queue = ctx.queue.then(() => conn.onHello()).then(() => writeStatus(ctx)).catch((error) => ctx.log(`catch-up failed: ${error.message}`));
986
+ const key = `catch-up:${conn.role || ""}`;
987
+ const whose = conn.role ? ` for ${conn.role}'s app` : "";
988
+ ctx.queue = ctx.queue.then(() => conn.onHello())
989
+ .then(() => { ctx.once.cleared(key, `catch-up works again${whose}.`); writeStatus(ctx); })
990
+ .catch((error) => ctx.once.failed(key, `catch-up failed${whose}: ${error.message}`));
967
991
  return;
968
992
  }
969
993
  if (data.type === "disconnect") {
@@ -1065,20 +1089,24 @@ async function run(log) {
1065
1089
  return stopped;
1066
1090
  };
1067
1091
  // Every ten minutes while connected, each project with archiving on is
1068
- // synced to its keel-chat branch (D19).
1092
+ // synced to its keel-chat branch (D19). A refusal that never changes, such as
1093
+ // a repository with no remote, is logged once (#460 D1).
1094
+ const archiveEvery = /^\d+$/.test(process.env.KEEL_CHAT_ARCHIVE_EVERY_MS || "") ? Number(process.env.KEEL_CHAT_ARCHIVE_EVERY_MS) : 10 * 60 * 1000;
1069
1095
  const archiveTimer = setInterval(() => {
1070
1096
  if (!ctx.connected || ctx.stopping) return;
1071
1097
  const archive = require("./archive");
1072
1098
  for (const project of ctx.projects) {
1073
1099
  if (!archive.archiveSettings(project.where.worktree).automatic) continue;
1100
+ const key = `archive:${project.where.project}`;
1074
1101
  try {
1075
1102
  const result = archive.sync(project.where);
1076
- if (result.refused) log(`${project.where.project}: ${result.refused}`);
1103
+ if (result.refused) ctx.once.failed(key, `${project.where.project}: ${result.refused}`);
1104
+ else ctx.once.cleared(key, `${project.where.project}: archive sync works again.`);
1077
1105
  } catch (error) {
1078
- log(`${project.where.project}: archive sync failed: ${error.message}`);
1106
+ ctx.once.failed(key, `${project.where.project}: archive sync failed: ${error.message}`);
1079
1107
  }
1080
1108
  }
1081
- }, 10 * 60 * 1000);
1109
+ }, archiveEvery);
1082
1110
  archiveTimer.unref();
1083
1111
  // Each second: honor a pause, notice a Keel upgrade, and send what is new.
1084
1112
  const timer = setInterval(() => {
@@ -16,13 +16,17 @@ const FORM_METHODS = new Set([
16
16
  "conversations.replies",
17
17
  ]);
18
18
 
19
+ // Slack names the scopes a `missing_scope` call needed and those the token
20
+ // has; the message names the needed ones, which is what the fix takes (#460 D2).
19
21
  class SlackError extends Error {
20
- constructor(method, error, { retryAfter = null, status = null } = {}) {
21
- super(`Slack ${method} failed: ${error}${status ? ` (HTTP ${status})` : ""}`);
22
+ constructor(method, error, { retryAfter = null, status = null, needed = null, provided = null } = {}) {
23
+ super(`Slack ${method} failed: ${error}${needed ? `: needs ${needed}` : ""}${status ? ` (HTTP ${status})` : ""}`);
22
24
  this.method = method;
23
25
  this.error = error;
24
26
  this.retryAfter = retryAfter;
25
27
  this.status = status;
28
+ this.needed = needed;
29
+ this.provided = provided;
26
30
  }
27
31
  }
28
32
 
@@ -69,7 +73,9 @@ async function call(method, params, token) {
69
73
  throw new SlackError(method, "response was not JSON", { status: response.status });
70
74
  }
71
75
  if (!parsed || parsed.ok !== true) {
72
- throw new SlackError(method, (parsed && parsed.error) || "unknown_error", { status: response.status });
76
+ throw new SlackError(method, (parsed && parsed.error) || "unknown_error", {
77
+ status: response.status, needed: (parsed && parsed.needed) || null, provided: (parsed && parsed.provided) || null,
78
+ });
73
79
  }
74
80
  return parsed;
75
81
  }
package/src/core/shift.js CHANGED
@@ -612,21 +612,24 @@ function keptCopyOf(where, role, transcript) {
612
612
  }
613
613
  }
614
614
 
615
- // After a delivered hand-over, the newest `keep` stopped background sessions in
616
- // the role's bound worktrees stay listed; each older one is removed with
617
- // `claude rm` once Keel's store holds its transcript (#397 D2). `claude rm`
618
- // leaves the host's transcript (F4). Only a session with a transcript, the
619
- // host's or Keel's copy, is a shift: one never given a prompt has neither, so
620
- // it takes no slot and stays (#401).
615
+ // After a delivered hand-over or a resume, the newest `keep` stopped background
616
+ // sessions of the role stay listed; each older one is removed with `claude rm`
617
+ // once Keel's store holds its transcript (#397 D2). `claude rm` leaves the
618
+ // host's transcript (F4). Only a session with a transcript, the host's or
619
+ // Keel's copy, is a shift: one never given a prompt has neither, so it takes no
620
+ // slot and stays (#401). A session is the role's when it ran in a bound
621
+ // worktree, or when Keel keeps its transcript under the role: a renamed or
622
+ // moved worktree leaves a `cwd` no binding names (#462 D2).
621
623
  function removeOldSessions(claude, where, entry, keep) {
622
624
  const bound = new Set(Object.entries(store.readJsonFile(path.join(where.root, "roles.json")))
623
625
  .filter(([, name]) => name === entry.role).map(([worktree]) => realpath(worktree)));
624
626
  const listed = listAgents(claude);
625
627
  if (!listed) return [];
626
628
  const { keptFile } = require("./chat/notice");
629
+ const roles = (row) => bound.has(realpath(row.cwd)) || fs.existsSync(keptFile(where, entry.role, `${row.sessionId}.jsonl`));
627
630
  const old = listed
628
- .filter((row) => row && row.kind === "background" && !row.status && row.cwd && bound.has(realpath(row.cwd))
629
- && row.sessionId && row.id !== entry.new_session)
631
+ .filter((row) => row && row.kind === "background" && !row.status && row.cwd && row.sessionId && roles(row)
632
+ && row.id !== entry.new_session)
630
633
  .map((row) => ({ row, transcript: hostTranscript(row.cwd, row.sessionId),
631
634
  kept: keptFile(where, entry.role, `${row.sessionId}.jsonl`) }))
632
635
  .filter(({ transcript, kept }) => transcript || fs.existsSync(kept))
@@ -1064,6 +1067,23 @@ function lastFetch(cwd) {
1064
1067
  }
1065
1068
  }
1066
1069
 
1070
+ // A takeover Keel did not carry out — a session opened by hand — removes the
1071
+ // old shift's sessions at resume, as a delivered hand-over does (#462 D1). It
1072
+ // asks the host only from a Claude Code session, for a note a CLI session
1073
+ // wrote, and not in the session a delivered hand-over started, which already
1074
+ // removed them.
1075
+ function removeAtResume(where, role, text) {
1076
+ const old = String(text).match(/^CLI session: (\S+)\.$/m);
1077
+ const current = process.env.CLAUDE_CODE_SESSION_ID || "";
1078
+ if (!old || !process.env.CLAUDE_CODE_ENTRYPOINT) return [];
1079
+ const queued = store.readJsonFile(queueFile(where, role));
1080
+ if (queued && queued.state === "delivered" && queued.new_session && current.startsWith(queued.new_session)) return [];
1081
+ const pid = String(text).match(/^CLI process: (\d+)\.$/m);
1082
+ const entry = { role, session: old[1], pid: pid ? Number(pid[1]) : null, new_session: current.slice(0, 8) || null };
1083
+ const { readShiftDeclaration } = require("./config");
1084
+ return removeOldSessions(process.env.KEEL_CLAUDE || "claude", where, entry, readShiftDeclaration(where.worktree).keepOldSessions);
1085
+ }
1086
+
1067
1087
  function resume(where, named = null) {
1068
1088
  const role = resumeRole(where, named);
1069
1089
  const note = waitingNote(where, role);
@@ -1087,7 +1107,7 @@ function resume(where, named = null) {
1087
1107
  ? store.post(where, { group, text, refs: [REF] })
1088
1108
  : store.writeRecord(where, { group, kind: "message", from: role, refs: [REF], text })).id;
1089
1109
  }
1090
- return { role, note: history, text, told, waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree) };
1110
+ return { role, note: history, text, told, removed: removeAtResume(where, role, text), waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree) };
1091
1111
  }
1092
1112
 
1093
1113
  function status(where) {
@@ -1557,7 +1577,10 @@ function runShift(argv) {
1557
1577
  ? `\n\nThis worktree is on ${merged.branch ? `\`${merged.branch}\`` : "a detached HEAD"}, already in ${merged.base} and `
1558
1578
  + `${merged.behind} commit${merged.behind === 1 ? "" : "s"} behind it: start new work from ${merged.base}.`
1559
1579
  : "";
1560
- out(result, `${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1580
+ const removed = (result.removed || []).length
1581
+ ? `\n\nRemoved old sessions from claude agents: ${result.removed.join(", ")}; \`keel shift history ${result.role} --show <id>\` prints each.`
1582
+ : "";
1583
+ out(result, `${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${removed}${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1561
1584
  return 0;
1562
1585
  }
1563
1586
  case "history": {