@christang/keel 5.141.0 → 5.143.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.141.0",
3
+ "version": "5.143.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.141.0 -->
1
+ <!-- keel:start version=5.143.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
@@ -1013,13 +1013,34 @@ function hostRun(executable, args) {
1013
1013
  });
1014
1014
  }
1015
1015
 
1016
- function hostJson(executable, args) {
1017
- const result = hostRun(executable, args);
1018
- if (result.error || result.status !== 0) return null;
1016
+ // A read-only `plugin list --json` normally answers in 1–3 s, and once hung
1017
+ // for minutes through a proxy (#354). It gets its own short limit, and a query
1018
+ // that fails is reported as one, never as a host with no Keel.
1019
+ function hostQuery(executable, args) {
1020
+ const limit = Number(process.env.KEEL_UPDATE_QUERY_TIMEOUT_MS) || 30 * 1000;
1021
+ const result = spawnSync(executable, args, {
1022
+ encoding: "utf8",
1023
+ shell: process.platform === "win32",
1024
+ timeout: limit,
1025
+ });
1026
+ if (result.error && result.error.code === "ENOENT") return { absent: true };
1027
+ if (result.error && result.error.code === "ETIMEDOUT") {
1028
+ return { failed: `timed out after ${limit / 1000} s` };
1029
+ }
1030
+ if (result.error) return { failed: result.error.message };
1031
+ // On Windows the call goes through cmd.exe, which reports a missing command
1032
+ // as a nonzero exit rather than ENOENT.
1033
+ if (
1034
+ result.status !== 0 && process.platform === "win32"
1035
+ && /is not recognized as an internal or external command/i.test(result.stderr || "")
1036
+ ) {
1037
+ return { absent: true };
1038
+ }
1039
+ if (result.status !== 0) return { failed: `exited ${result.status}` };
1019
1040
  try {
1020
- return JSON.parse(result.stdout);
1041
+ return { json: JSON.parse(result.stdout) };
1021
1042
  } catch {
1022
- return null;
1043
+ return { failed: "printed no JSON" };
1023
1044
  }
1024
1045
  }
1025
1046
 
@@ -1027,8 +1048,12 @@ function hostJson(executable, args) {
1027
1048
  // host is absent or has none. Both hosts answer `plugin list --json`, in
1028
1049
  // different shapes (2026-10-03: Claude a list of {id, version, installPath},
1029
1050
  // Codex {installed: [{pluginId, version, marketplaceSource, source}]}).
1051
+ // Each returns the Keel entry, null for a host with none, or { failed } when
1052
+ // the query itself failed.
1030
1053
  function claudeKeel(executable) {
1031
- const listed = hostJson(executable, ["plugin", "list", "--json"]);
1054
+ const queried = hostQuery(executable, ["plugin", "list", "--json"]);
1055
+ if (queried.failed) return { failed: `\`claude plugin list --json\` ${queried.failed}` };
1056
+ const listed = queried.json;
1032
1057
  const entry = (Array.isArray(listed) ? listed : [])
1033
1058
  .find((item) => item && typeof item.id === "string" && item.id.startsWith("keel@"));
1034
1059
  if (!entry) return null;
@@ -1042,7 +1067,9 @@ const CODEX_SPARSE_PATHS = [".agents/plugins", "plugins/keel"];
1042
1067
  const CODEX_SPARSE_FLAGS = CODEX_SPARSE_PATHS.map((entry) => `--sparse ${entry}`).join(" ");
1043
1068
 
1044
1069
  function codexKeel(executable) {
1045
- const listed = hostJson(executable, ["plugin", "list", "--json"]);
1070
+ const queried = hostQuery(executable, ["plugin", "list", "--json"]);
1071
+ if (queried.failed) return { failed: `\`codex plugin list --json\` ${queried.failed}` };
1072
+ const listed = queried.json;
1046
1073
  const items = listed && Array.isArray(listed.installed) ? listed.installed : [];
1047
1074
  const entry = items.find((item) => item && item.name === "keel" && item.installed !== false);
1048
1075
  if (!entry) return null;
@@ -1089,7 +1116,8 @@ function versionChange(before, after) {
1089
1116
  function updateClaudePlugin(options) {
1090
1117
  const component = "claude plugin";
1091
1118
  const executable = process.env.KEEL_UPDATE_CLAUDE || "claude";
1092
- const installed = claudeKeel(executable);
1119
+ const queried = claudeKeel(executable);
1120
+ const installed = queried && !queried.failed ? queried : null;
1093
1121
  const id = installed ? installed.id : "keel@keel-marketplace";
1094
1122
  const market = installed ? installed.market : "keel-marketplace";
1095
1123
  const steps = [["plugin", "marketplace", "update", market], ["plugin", "update", id]];
@@ -1097,12 +1125,20 @@ function updateClaudePlugin(options) {
1097
1125
  for (const args of steps) process.stdout.write(`keel: would run claude ${args.join(" ")}\n`);
1098
1126
  return true;
1099
1127
  }
1128
+ if (queried && queried.failed) {
1129
+ updateLine(component, "failed", queried.failed);
1130
+ return false;
1131
+ }
1100
1132
  if (!installed) {
1101
1133
  updateLine(component, "absent", "Claude Code is not installed here or has no Keel plugin");
1102
1134
  return true;
1103
1135
  }
1104
1136
  if (!runHostSteps(component, "claude", executable, steps)) return false;
1105
1137
  const after = claudeKeel(executable);
1138
+ if (after && after.failed) {
1139
+ updateLine(component, "failed", `${after.failed} after the update, so its result is unverified`);
1140
+ return false;
1141
+ }
1106
1142
  updateLine(
1107
1143
  component,
1108
1144
  versionChange(installed.version, after && after.version),
@@ -1114,7 +1150,8 @@ function updateClaudePlugin(options) {
1114
1150
  function updateCodexPlugin(options) {
1115
1151
  const component = "codex plugin";
1116
1152
  const executable = process.env.KEEL_UPDATE_CODEX || "codex";
1117
- const installed = codexKeel(executable);
1153
+ const queried = codexKeel(executable);
1154
+ const installed = queried && !queried.failed ? queried : null;
1118
1155
  const id = installed ? installed.id : "keel@keel-marketplace";
1119
1156
  const market = installed ? installed.market : "keel-marketplace";
1120
1157
  const steps = [["plugin", "marketplace", "upgrade", market], ["plugin", "add", id]];
@@ -1122,6 +1159,10 @@ function updateCodexPlugin(options) {
1122
1159
  for (const args of steps) process.stdout.write(`keel: would run codex ${args.join(" ")}\n`);
1123
1160
  return true;
1124
1161
  }
1162
+ if (queried && queried.failed) {
1163
+ updateLine(component, "failed", queried.failed);
1164
+ return false;
1165
+ }
1125
1166
  if (!installed) {
1126
1167
  updateLine(component, "absent", "Codex is not installed here or has no Keel plugin");
1127
1168
  return true;
@@ -1159,10 +1200,18 @@ function updateCodexPlugin(options) {
1159
1200
  ? readOrNull(path.join(codexHome, "plugins", "cache", market, "keel", installed.version, "hooks", "codex.json"))
1160
1201
  : null;
1161
1202
  const upgraded = codexKeel(executable);
1203
+ if (upgraded && upgraded.failed) {
1204
+ updateLine(component, "failed", `${upgraded.failed} after the marketplace refresh`);
1205
+ return false;
1206
+ }
1162
1207
  const newHooks = upgraded && upgraded.path ? readOrNull(path.join(upgraded.path, "hooks", "codex.json")) : null;
1163
1208
  const hooksChanged = oldHooks && newHooks && !oldHooks.equals(newHooks);
1164
1209
  if (!runHostSteps(component, "codex", executable, [steps[1]])) return false;
1165
1210
  const after = codexKeel(executable);
1211
+ if (after && after.failed) {
1212
+ updateLine(component, "failed", `${after.failed} after the update, so its result is unverified`);
1213
+ return false;
1214
+ }
1166
1215
  updateLine(
1167
1216
  component,
1168
1217
  versionChange(installed.version, after && after.version),
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.141.0",
3
+ "version": "5.143.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.141.0",
9
+ "version": "5.143.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.141.0",
5
+ "version": "5.143.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.141.0",
3
+ "version": "5.143.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.141.0",
3
+ "version": "5.143.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",
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
 
6
6
  import contextlib
7
7
  import json
8
+ import gzip
8
9
  import hashlib
9
10
  import os
10
11
  import re
@@ -48,8 +49,8 @@ REQUIRED_SCRIPTS = [
48
49
  "scripts/validate_plugin.py",
49
50
  ]
50
51
 
51
- PACKAGE_VERSION = "5.141.0"
52
- PROTOCOL_VERSION = "5.141.0"
52
+ PACKAGE_VERSION = "5.143.0"
53
+ PROTOCOL_VERSION = "5.143.0"
53
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
54
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
55
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -6260,6 +6261,118 @@ def validate_host_run_session_scenario() -> int:
6260
6261
  return 0
6261
6262
 
6262
6263
 
6264
+ def validate_shift_keeps_transcripts_scenario() -> int:
6265
+ """Issue #343: a shift's conversation outlives the host's transcript file.
6266
+
6267
+ Claude deletes transcripts after `cleanupPeriodDays` (30 by default), so
6268
+ when a role's session starts a new transcript the hook copies the ended
6269
+ one into Keel's store; `history` and `--grep` read the copy once the
6270
+ host's file is gone, and `--grep` reads a Codex rollout too.
6271
+ """
6272
+ label = "shift-keeps-transcripts:"
6273
+ with tempfile.TemporaryDirectory(prefix="keel-shift-343-") as raw:
6274
+ base = Path(raw)
6275
+ rtl, verify, env, _ = shift_scratch(base)
6276
+ store_root = mailbox_common_dir(rtl) / "keel-chat"
6277
+ kept_dir = store_root / "shift" / "transcripts" / "verify"
6278
+ transcripts = base / "transcripts"
6279
+ transcripts.mkdir()
6280
+
6281
+ def claude_transcript(name: str, said: str) -> Path:
6282
+ path = transcripts / f"{name}.jsonl"
6283
+ path.write_text("\n".join(json.dumps(record) for record in (
6284
+ {"type": "user", "timestamp": "2026-10-12T01:00:00.000Z", "message": {"role": "user", "content": "carry on"}},
6285
+ {"type": "assistant", "timestamp": "2026-10-12T01:00:05.000Z",
6286
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
6287
+ )) + "\n", encoding="utf-8")
6288
+ return path
6289
+
6290
+ def hook(transcript: Path, session: str) -> None:
6291
+ for event, name in (("session-start", "SessionStart"), ("user-prompt-submit", "UserPromptSubmit")):
6292
+ subprocess.run(
6293
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
6294
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
6295
+ input=json.dumps({"cwd": str(verify), "hook_event_name": name, "session_id": session,
6296
+ "prompt": "go", "source": "startup", "transcript_path": str(transcript)}),
6297
+ )
6298
+
6299
+ def history(*args: str) -> subprocess.CompletedProcess[str]:
6300
+ return run_keel(verify, "shift", "history", *args, env=env)
6301
+
6302
+ a = claude_transcript("a", "The arbiter retry budget is four cycles.")
6303
+ b = claude_transcript("b", "Resumed from the note.")
6304
+ hook(a, "s1")
6305
+ hook(b, "s1")
6306
+ kept_a = kept_dir / "a.jsonl.gz"
6307
+ if not kept_a.is_file():
6308
+ report(f"{label} no kept copy of transcript A under {kept_dir}: {sorted(p.name for p in kept_dir.glob('*')) if kept_dir.exists() else 'no directory'}")
6309
+ return 1
6310
+ if gzip.decompress(kept_a.read_bytes()) != a.read_bytes():
6311
+ report(f"{label} the kept copy of A is not A's bytes.")
6312
+ return 1
6313
+ if (kept_dir / "b.jsonl.gz").exists():
6314
+ report(f"{label} the current transcript B was copied while it is still being written.")
6315
+ return 1
6316
+
6317
+ a.unlink()
6318
+ listed = history("verify")
6319
+ line_a = next((l for l in listed.stdout.splitlines() if str(a) in l), "")
6320
+ if "(missing)" in line_a:
6321
+ report(f"{label} A, deleted but kept, is still listed as missing: {line_a!r}")
6322
+ return 1
6323
+ if "(kept)" not in line_a:
6324
+ report(f"{label} A, deleted but kept, is not marked (kept): {line_a!r}")
6325
+ return 1
6326
+ found = history("verify", "--grep", "retry budget")
6327
+ if found.returncode != 0:
6328
+ report(f"{label} --grep for a phrase in the kept copy of A exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
6329
+ return 1
6330
+ if "retry budget" not in found.stdout:
6331
+ report(f"{label} --grep does not print the phrase from the kept copy of A: {found.stdout!r}")
6332
+ return 1
6333
+
6334
+ # A Codex rollout is searched the same way.
6335
+ c = transcripts / "rollout-c.jsonl"
6336
+ c.write_text("\n".join(json.dumps(record) for record in (
6337
+ {"timestamp": "2026-10-18T09:50:18.096Z", "type": "session_meta", "payload": {}},
6338
+ {"timestamp": "2026-10-18T09:50:21.766Z", "type": "response_item",
6339
+ "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Check the FIFO depth for the IECC lane."}]}},
6340
+ {"timestamp": "2026-10-18T09:50:23.621Z", "type": "response_item",
6341
+ "payload": {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "ok"}]}},
6342
+ )) + "\n", encoding="utf-8")
6343
+ hook(c, "s2")
6344
+ found = history("verify", "--grep", "FIFO depth")
6345
+ if found.returncode != 0:
6346
+ report(f"{label} --grep for a phrase in a Codex rollout exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
6347
+ return 1
6348
+ if "FIFO depth" not in found.stdout:
6349
+ report(f"{label} --grep does not print the phrase from a Codex rollout: {found.stdout!r}")
6350
+ return 1
6351
+
6352
+ # A transcript that grew after its copy is copied again.
6353
+ with b.open("a", encoding="utf-8") as handle:
6354
+ handle.write(json.dumps({"type": "assistant", "timestamp": "2026-10-12T02:00:00.000Z",
6355
+ "message": {"role": "assistant", "content": [{"type": "text", "text": "late line"}]}}) + "\n")
6356
+ d = claude_transcript("d", "Next shift.")
6357
+ hook(d, "s3")
6358
+ kept_b = kept_dir / "b.jsonl.gz"
6359
+ if not kept_b.is_file():
6360
+ report(f"{label} B ended and has no kept copy.")
6361
+ return 1
6362
+ if gzip.decompress(kept_b.read_bytes()) != b.read_bytes():
6363
+ report(f"{label} B's kept copy does not match B after it ended.")
6364
+ return 1
6365
+ with b.open("a", encoding="utf-8") as handle:
6366
+ handle.write("{}\n")
6367
+ e = claude_transcript("e", "Another shift.")
6368
+ hook(e, "s4")
6369
+ if gzip.decompress(kept_b.read_bytes()) != b.read_bytes():
6370
+ report(f"{label} B grew after its copy and was not copied again.")
6371
+ return 1
6372
+ report("shift-keeps-transcripts scenario passed.")
6373
+ return 0
6374
+
6375
+
6263
6376
  def validate_shift_history_scenario() -> int:
6264
6377
  """Issue #304: a cleared shift's conversation stays findable.
6265
6378
 
@@ -23638,6 +23751,14 @@ const path = require("path");
23638
23751
  const host = process.env.FAKE_HOST;
23639
23752
  const args = process.argv.slice(2);
23640
23753
  fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify([host, ...args]) + "\n");
23754
+ // FAKE_LIST_SLEEP_<HOST> holds `plugin list --json` for N seconds, and
23755
+ // FAKE_LIST_EXIT_<HOST> makes it exit with that status (#354).
23756
+ if (args.join(" ") === "plugin list --json") {
23757
+ const hold = Number(process.env[`FAKE_LIST_SLEEP_${host.toUpperCase()}`] || "0");
23758
+ if (hold > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, hold * 1000);
23759
+ const code = process.env[`FAKE_LIST_EXIT_${host.toUpperCase()}`];
23760
+ if (code) process.exit(Number(code));
23761
+ }
23641
23762
  const stateFile = process.env.FAKE_STATE;
23642
23763
  const state = fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile, "utf8")) : {};
23643
23764
  const save = () => fs.writeFileSync(stateFile, JSON.stringify(state));
@@ -23834,6 +23955,98 @@ OVERLAY_BLOCK_RE = re.compile(
23834
23955
  )
23835
23956
 
23836
23957
 
23958
+ def validate_update_host_query_timeout_scenario() -> int:
23959
+ """Issue #354: a hung or failed host query is `failed`, never `absent`.
23960
+
23961
+ `plugin list --json` once hung for minutes through a proxy; every host call
23962
+ had five minutes, and a query that failed read as a host with no Keel.
23963
+ """
23964
+ label = "update-host-query-timeout:"
23965
+ with tempfile.TemporaryDirectory(prefix="keel-update-354-", ignore_cleanup_errors=True) as raw:
23966
+ tmp = Path(raw)
23967
+ fake = tmp / "fake.js"
23968
+ write_text(fake, UPDATE_FAKE)
23969
+ launchers = {}
23970
+ for host in ("npm", "claude", "codex"):
23971
+ launcher = tmp / f"fake-{host}"
23972
+ write_text(launcher, f'#!/bin/sh\nFAKE_HOST={host} exec node "{fake}" "$@"\n')
23973
+ launcher.chmod(0o755)
23974
+ launchers[host] = launcher
23975
+ source = tmp / "codex-source"
23976
+ write_text(source / "hooks/codex.json", "{}\n")
23977
+
23978
+ def update(*extra: str, env_extra: dict[str, str]):
23979
+ log = tmp / "log.jsonl"
23980
+ state = tmp / "state.json"
23981
+ for stale in (log, state):
23982
+ if stale.exists():
23983
+ stale.unlink()
23984
+ log.write_text("")
23985
+ env = dict(os.environ)
23986
+ env.update({
23987
+ "KEEL_UPDATE_NPM": str(launchers["npm"]),
23988
+ "KEEL_UPDATE_CLAUDE": str(launchers["claude"]),
23989
+ "KEEL_UPDATE_CODEX": str(launchers["codex"]),
23990
+ "KEEL_UPDATE_QUERY_TIMEOUT_MS": "1500",
23991
+ "CODEX_HOME": str(tmp / "codex-home"),
23992
+ "FAKE_LOG": str(log), "FAKE_STATE": str(state),
23993
+ "FAKE_CODEX_SOURCE": str(source),
23994
+ })
23995
+ env.pop("KEEL_UPDATE_SOURCE", None)
23996
+ env.update(env_extra)
23997
+ started = time.monotonic()
23998
+ result = subprocess.run(["node", str(ROOT / "bin/keel.js"), "--update", *extra], cwd=tmp, env=env,
23999
+ text=True, capture_output=True, check=False, timeout=120)
24000
+ calls = [json.loads(line) for line in log.read_text().splitlines() if line.strip()]
24001
+ return result, calls, time.monotonic() - started
24002
+
24003
+ def line(output: str, component: str) -> str:
24004
+ return next((l for l in output.splitlines() if l.startswith(f"keel update: {component}:")), "")
24005
+
24006
+ result, _, _ = update(env_extra={"FAKE_LIST_EXIT_CLAUDE": "3"})
24007
+ claude = line(result.stdout, "claude plugin")
24008
+ if "absent" in claude:
24009
+ report(f"{label} a claude plugin list --json that exited 3 was reported absent: {claude!r}")
24010
+ return 1
24011
+ if "failed" not in claude or "exited 3" not in claude:
24012
+ report(f"{label} a claude plugin list --json that exited 3 does not read failed with exited 3: {claude!r}")
24013
+ return 1
24014
+
24015
+ result, calls, took = update(env_extra={"FAKE_LIST_SLEEP_CODEX": "10"})
24016
+ codex = line(result.stdout, "codex plugin")
24017
+ if "absent" in codex:
24018
+ report(f"{label} a hung codex plugin list --json was reported absent: {codex!r}")
24019
+ return 1
24020
+ for needle in ("failed", "codex plugin list --json", "timed out after 1.5 s"):
24021
+ if needle not in codex:
24022
+ report(f"{label} the hung-query line does not name {needle!r}: {codex!r}")
24023
+ return 1
24024
+ if any(c[:4] == ["codex", "plugin", "marketplace", "upgrade"] for c in calls):
24025
+ report(f"{label} a Codex update command ran after its query failed: {calls!r}")
24026
+ return 1
24027
+ if "updated" not in line(result.stdout, "claude plugin"):
24028
+ report(f"{label} the Claude line did not still report its update: {result.stdout!r}")
24029
+ return 1
24030
+ if result.returncode == 0:
24031
+ report(f"{label} a failed query left keel --update exiting 0.")
24032
+ return 1
24033
+ if took > 9:
24034
+ report(f"{label} the hung query held keel --update for {took:.1f} s, past its 1.5 s limit.")
24035
+ return 1
24036
+
24037
+ result, _, _ = update(env_extra={"KEEL_UPDATE_CODEX": str(tmp / "no-such-codex")})
24038
+ if "absent" not in line(result.stdout, "codex plugin"):
24039
+ report(f"{label} a missing codex executable no longer reads absent: {result.stdout!r}")
24040
+ return 1
24041
+
24042
+ result, _, _ = update("--dry-run", env_extra={"FAKE_LIST_SLEEP_CODEX": "10"})
24043
+ if result.returncode != 0:
24044
+ report(f"{label} --dry-run with a hung query exited {result.returncode}: {result.stdout!r}")
24045
+ return 1
24046
+ report("update-host-query-timeout scenario passed.")
24047
+ return 0
24048
+
24049
+
23837
24050
  def validate_update_codex_refresh_retry_scenario() -> int:
23838
24051
  """Issue #329: a slow link can cut Codex's whole-repository marketplace clone.
23839
24052
 
@@ -41122,6 +41335,7 @@ SCENARIOS: tuple = (
41122
41335
  ("adopted-update-is-silent-unless-reload", validate_adopted_update_is_silent_unless_reload_scenario),
41123
41336
  ("update-covers-installed-hosts", validate_update_covers_installed_hosts_scenario),
41124
41337
  ("update-codex-refresh-retry", validate_update_codex_refresh_retry_scenario),
41338
+ ("update-host-query-timeout", validate_update_host_query_timeout_scenario),
41125
41339
  ("refresh-covers-every-target", validate_refresh_covers_every_target_scenario),
41126
41340
  ("directory-branch-advances", validate_directory_branch_advances_scenario),
41127
41341
  ("release-notes-name-the-directory-branch", validate_release_notes_name_the_directory_branch_scenario),
@@ -41137,6 +41351,7 @@ SCENARIOS: tuple = (
41137
41351
  ("owner-language", validate_owner_language_scenario),
41138
41352
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
41139
41353
  ("shift-history", validate_shift_history_scenario),
41354
+ ("shift-keeps-transcripts", validate_shift_keeps_transcripts_scenario),
41140
41355
  ("role-drift", validate_role_drift_scenario),
41141
41356
  ("host-run-session", validate_host_run_session_scenario),
41142
41357
  ("shift-without-role", validate_shift_without_role_scenario),
@@ -15,6 +15,7 @@
15
15
 
16
16
  const fs = require("fs");
17
17
  const path = require("path");
18
+ const zlib = require("zlib");
18
19
  const store = require("./store");
19
20
  const { relativeAge } = require("./view");
20
21
 
@@ -257,6 +258,36 @@ function segmentsFile(where, role) {
257
258
  return path.join(where.root, "shift", "segments", `${role}.json`);
258
259
  }
259
260
 
261
+ // Where Keel keeps a copy of a role's ended transcript (#343). It stays on this
262
+ // machine: the chat archive syncs none of `shift/`.
263
+ function keptFile(where, role, transcript) {
264
+ return path.join(where.root, "shift", "transcripts", role, `${path.basename(transcript)}.gz`);
265
+ }
266
+
267
+ // Copies each ended segment's transcript that exists and has no up-to-date
268
+ // copy. The host deletes transcripts after its cleanup period (30 days by
269
+ // default for Claude), so the copy is what keeps a shift's conversation. The
270
+ // current segment is left alone: it is still being written.
271
+ function keepEnded(where, role, segments) {
272
+ for (const segment of segments) {
273
+ if (!segment.ended || !segment.transcript) continue;
274
+ try {
275
+ const source = fs.statSync(segment.transcript);
276
+ const target = keptFile(where, role, segment.transcript);
277
+ const kept = segment.kept_from;
278
+ if (fs.existsSync(target) && kept && kept.size === source.size && kept.mtime === source.mtimeMs) continue;
279
+ fs.mkdirSync(path.dirname(target), { recursive: true });
280
+ const temporary = `${target}.${process.pid}.tmp`;
281
+ fs.writeFileSync(temporary, zlib.gzipSync(fs.readFileSync(segment.transcript)));
282
+ fs.renameSync(temporary, target);
283
+ segment.kept = target;
284
+ segment.kept_from = { size: source.size, mtime: source.mtimeMs };
285
+ } catch {
286
+ // The host's file may already be gone; a copy is a convenience.
287
+ }
288
+ }
289
+ }
290
+
260
291
  function recordSegment(where, role, transcript) {
261
292
  if (typeof transcript !== "string" || !path.isAbsolute(transcript)) return;
262
293
  try {
@@ -267,6 +298,7 @@ function recordSegment(where, role, transcript) {
267
298
  const now = store.isoLocal(new Date());
268
299
  if (last && !last.ended) last.ended = now;
269
300
  segments.push({ transcript, started: now, ended: null });
301
+ keepEnded(where, role, segments);
270
302
  store.writeJsonAtomic(where, file, { segments });
271
303
  } catch {
272
304
  // A convenience, like presence: never fail the hook.
package/src/core/shift.js CHANGED
@@ -13,6 +13,7 @@
13
13
 
14
14
  const fs = require("fs");
15
15
  const os = require("os");
16
+ const zlib = require("zlib");
16
17
  const path = require("path");
17
18
  const { spawn, spawnSync } = require("child_process");
18
19
  const store = require("./chat/store");
@@ -649,6 +650,27 @@ function status(where) {
649
650
 
650
651
  // --- history (#304 D3, D4) -------------------------------------------------------
651
652
 
653
+ // The speaker and text of a conversation record: Claude's `{type, message}`,
654
+ // or a Codex rollout's `{type: "response_item", payload: {type: "message"}}`
655
+ // (#343). Anything else is not conversation.
656
+ function conversationLine(record) {
657
+ if (!record) return null;
658
+ if (record.type === "user" || record.type === "assistant") return { speaker: record.type, text: transcriptText(record) };
659
+ const payload = record.type === "response_item" ? record.payload : null;
660
+ if (payload && payload.type === "message" && (payload.role === "user" || payload.role === "assistant")) {
661
+ const parts = Array.isArray(payload.content) ? payload.content : [];
662
+ const text = parts.filter((part) => part && typeof part.text === "string").map((part) => part.text).join("\n");
663
+ return { speaker: payload.role, text };
664
+ }
665
+ return null;
666
+ }
667
+
668
+ // A transcript's text, from the host's file or Keel's gzip copy of it.
669
+ function readTranscript(file) {
670
+ const bytes = fs.readFileSync(file);
671
+ return (file.endsWith(".gz") ? zlib.gunzipSync(bytes) : bytes).toString("utf8");
672
+ }
673
+
652
674
  function transcriptText(record) {
653
675
  const content = record && record.message ? record.message.content : null;
654
676
  if (typeof content === "string") return content;
@@ -659,7 +681,7 @@ function transcriptText(record) {
659
681
  function grepTranscript(file, needle, limit = 3) {
660
682
  const hits = [];
661
683
  const lower = needle.toLowerCase();
662
- for (const line of fs.readFileSync(file, "utf8").split("\n")) {
684
+ for (const line of readTranscript(file).split("\n")) {
663
685
  if (!line.trim()) continue;
664
686
  let record;
665
687
  try {
@@ -667,13 +689,14 @@ function grepTranscript(file, needle, limit = 3) {
667
689
  } catch {
668
690
  continue;
669
691
  }
670
- if (record.type !== "user" && record.type !== "assistant") continue;
671
- const text = transcriptText(record);
692
+ const said = conversationLine(record);
693
+ if (!said) continue;
694
+ const text = said.text;
672
695
  const at = text.toLowerCase().indexOf(lower);
673
696
  if (at < 0) continue;
674
697
  const from = Math.max(0, at - 60);
675
698
  const snippet = text.slice(from, at + needle.length + 60).replace(/\s+/g, " ");
676
- const hit = { timestamp: record.timestamp || null, speaker: record.type, snippet: `${from ? "…" : ""}${snippet}…` };
699
+ const hit = { timestamp: record.timestamp || null, speaker: said.speaker, snippet: `${from ? "…" : ""}${snippet}…` };
677
700
  // A transcript can hold the same message twice; report it once.
678
701
  if (hits.some((seen) => seen.timestamp === hit.timestamp && seen.snippet === hit.snippet)) continue;
679
702
  hits.push(hit);
@@ -734,12 +757,19 @@ function history(where, named, grep) {
734
757
  const segments = [...recorded.slice().reverse(), ...earlier]
735
758
  .filter((segment) => !seen.has(segment.transcript) && seen.add(segment.transcript))
736
759
  .sort((a, b) => Date.parse(b.started) - Date.parse(a.started))
737
- .map((segment) => ({ ...segment, exists: fs.existsSync(segment.transcript) }));
760
+ .map((segment) => ({
761
+ ...segment,
762
+ exists: fs.existsSync(segment.transcript),
763
+ kept: segment.kept && fs.existsSync(segment.kept) ? segment.kept : null,
764
+ }));
738
765
  const notes = safeList(path.join(shiftDir(where), "history"))
739
766
  .filter((name) => name.startsWith(`${role}-`) && name.endsWith(".md"))
740
767
  .sort().reverse().map((name) => path.join(shiftDir(where), "history", name));
741
768
  if (grep) {
742
- for (const segment of segments) segment.matches = segment.exists ? grepTranscript(segment.transcript, grep) : [];
769
+ for (const segment of segments) {
770
+ const source = segment.exists ? segment.transcript : segment.kept;
771
+ segment.matches = source ? grepTranscript(source, grep) : [];
772
+ }
743
773
  }
744
774
  return { role, segments, notes };
745
775
  }
@@ -748,7 +778,7 @@ function renderHistory(result, grep) {
748
778
  const lines = [];
749
779
  for (const segment of result.segments) {
750
780
  if (grep && !segment.matches.length) continue;
751
- lines.push(`${segment.started} → ${segment.ended || "now"} ${segment.transcript}${segment.found ? " (found)" : ""}${segment.exists ? "" : " (missing)"}`);
781
+ lines.push(`${segment.started} → ${segment.ended || "now"} ${segment.transcript}${segment.found ? " (found)" : ""}${segment.exists ? "" : segment.kept ? " (kept)" : " (missing)"}`);
752
782
  for (const hit of segment.matches || []) lines.push(` ${hit.timestamp || "?"} ${hit.speaker}: ${hit.snippet}`);
753
783
  }
754
784
  if (!grep) for (const note of result.notes) lines.push(`note ${note}`);