@christang/keel 5.118.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.
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.118.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.118.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.118.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.118.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.118.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.118.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",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.118.0"
51
- PROTOCOL_VERSION = "5.118.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
@@ -6037,6 +6037,121 @@ def validate_host_run_session_scenario() -> int:
6037
6037
  return 0
6038
6038
 
6039
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
+
6040
6155
  def validate_shift_coordinator_last_scenario() -> int:
6041
6156
  """Issue #289: the coordinator starts the others before its own shift ends.
6042
6157
 
@@ -39716,6 +39831,7 @@ SCENARIOS: tuple = (
39716
39831
  ("shift-coordinator-last", validate_shift_coordinator_last_scenario),
39717
39832
  ("shift-self", validate_shift_self_scenario),
39718
39833
  ("shift-self-wake", validate_shift_self_wake_scenario),
39834
+ ("shift-history", validate_shift_history_scenario),
39719
39835
  ("role-drift", validate_role_drift_scenario),
39720
39836
  ("host-run-session", validate_host_run_session_scenario),
39721
39837
  ("shift-without-role", validate_shift_without_role_scenario),
@@ -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") {
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.");