@christang/keel 5.193.0 → 5.195.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.193.0",
3
+ "version": "5.195.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.193.0 -->
1
+ <!-- keel:start version=5.195.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.193.0",
3
+ "version": "5.195.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.193.0",
9
+ "version": "5.195.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.193.0",
5
+ "version": "5.195.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.193.0",
3
+ "version": "5.195.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.193.0",
3
+ "version": "5.195.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",
@@ -227,6 +227,18 @@ function installedTarget(cwd) {
227
227
  return "codex";
228
228
  }
229
229
 
230
+ // Keel's own source repository, by the test `isKeelSourceRepo` makes
231
+ // (src/core/capabilities.js), inlined because these scripts load nothing from
232
+ // src/core. There the managed block is the checked-out branch's own version.
233
+ function keelSourceRepo(cwd) {
234
+ try {
235
+ if (JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")).name !== "@christang/keel") return false;
236
+ } catch {
237
+ return false;
238
+ }
239
+ return fs.existsSync(path.join(cwd, "plugins", "keel"));
240
+ }
241
+
230
242
  // Three versions are comparable in any repository: the plugin executing this
231
243
  // hook, the CLI it just invoked, and the protocol version the repository
232
244
  // stamped into its managed block. Keel reports the disagreement and stops
@@ -288,7 +300,12 @@ function versionReport(cwd, cli, pathCli = null) {
288
300
  const parts = [];
289
301
  if (pending) parts.push(`The host has already installed plugin ${pending}, so nothing needs updating.`);
290
302
  else if (runtimeBehind || !protocolBehind) parts.push(`Updating is ${plugin.remedy}, which Keel names and does not run.`);
291
- if (protocolBehind) {
303
+ if (protocolBehind && keelSourceRepo(cwd)) {
304
+ // #446 D2: a refresh is not the remedy here, and `keel context` prints no
305
+ // Protocol: line in this repository.
306
+ parts.push("This is Keel's source repository, whose protocol block is the checked-out branch's own version: "
307
+ + "an older one means the branch is behind its default branch, so start from that branch rather than refreshing.");
308
+ } else if (protocolBehind) {
292
309
  parts.push(`The repository's protocol block is behind: refresh it with \`keel --install --target ${installedTarget(cwd)}\`, `
293
310
  + "the command `keel context` names on its Protocol: line.");
294
311
  }
@@ -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.193.0"
38
+ PACKAGE_VERSION = "5.195.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.193.0"
41
+ PROTOCOL_VERSION = "5.195.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -1638,6 +1638,48 @@ def plant_spawn_recorder(path: Path) -> str:
1638
1638
  return f"--require {path}"
1639
1639
 
1640
1640
 
1641
+ def validate_session_start_source_repo_protocol_scenario() -> int:
1642
+ """Issue #446 D2: in Keel's source repository a lagging protocol is a lagging branch.
1643
+
1644
+ There the managed block is the checked-out branch's own version, and
1645
+ `keel context` prints no Protocol: line, so naming the refresh sends the
1646
+ maintainer to the wrong command. Elsewhere the refresh is still named.
1647
+ """
1648
+ label = "session-start-source-repo-protocol:"
1649
+ event = {"hook_event_name": "SessionStart", "source": "startup"}
1650
+ with tempfile.TemporaryDirectory(prefix="keel-446-hook-") as raw:
1651
+ tmp = Path(raw)
1652
+ plugin = plant_session_start_plugin(tmp / "plugin", "5.9.0")
1653
+ cli = fake_keel_cli(tmp / "cli.js", "5.9.0")
1654
+ lagging = "<!-- keel:start version=5.2.0 -->\n## Session Start\n<!-- keel:end -->\n"
1655
+ source = tmp / "keel-source"
1656
+ write_text(source / "openspec/changes/demo/tasks.md", task_contract_fixture())
1657
+ write_text(source / "CLAUDE.md", lagging)
1658
+ write_text(source / "package.json", json.dumps({"name": "@christang/keel", "version": "5.2.0"}) + "\n")
1659
+ write_text(source / "plugins/keel/.keep", "")
1660
+ text = session_start_context(run_session_start_hook(source, event, keel_cli=cli, plugin_root=plugin)) or ""
1661
+ if VERSION_DRIFT_STATEMENT not in text:
1662
+ report(f"{label} the source repository's lagging protocol is not reported at all: {text!r}")
1663
+ return 1
1664
+ for forbidden in ("keel --install", "Protocol: line"):
1665
+ if forbidden in text:
1666
+ report(f"{label} the source repository's report still names {forbidden!r}: {text!r}")
1667
+ return 1
1668
+ if "checked-out branch" not in text:
1669
+ report(f"{label} the source repository's report does not say the block is the checked-out branch's: {text!r}")
1670
+ return 1
1671
+ other = tmp / "user-repo"
1672
+ write_text(other / "openspec/changes/demo/tasks.md", task_contract_fixture())
1673
+ write_text(other / "CLAUDE.md", lagging)
1674
+ write_text(other / "package.json", json.dumps({"name": "user-app"}) + "\n")
1675
+ elsewhere = session_start_context(run_session_start_hook(other, event, keel_cli=cli, plugin_root=plugin)) or ""
1676
+ if "keel --install --target claude" not in elsewhere:
1677
+ report(f"{label} a user repository's lagging protocol no longer names the refresh: {elsewhere!r}")
1678
+ return 1
1679
+ report("session-start-source-repo-protocol scenario passed.")
1680
+ return 0
1681
+
1682
+
1641
1683
  def validate_runtime_version_drift_scenario() -> int:
1642
1684
  codex_event = {"hook_event_name": "SessionStart", "source": "startup"}
1643
1685
 
@@ -386,6 +386,7 @@ SCENARIOS: tuple = (
386
386
  ("native-plugin-manifests", hosts.validate_native_plugin_manifests_scenario),
387
387
  ("native-plugin-session-start", hosts.validate_native_plugin_session_start_scenario),
388
388
  ("runtime-version-drift", hosts.validate_runtime_version_drift_scenario),
389
+ ("session-start-source-repo-protocol", hosts.validate_session_start_source_repo_protocol_scenario),
389
390
  ("plugin-runs-its-own-cli", hosts.validate_plugin_runs_its_own_cli_scenario),
390
391
  ("drift-names-a-pending-reload", hosts.validate_drift_names_a_pending_reload_scenario),
391
392
  ("hook-hands-off-to-installed-update", hosts.validate_hook_hands_off_to_installed_update_scenario),
@@ -425,6 +426,8 @@ SCENARIOS: tuple = (
425
426
  ("shift-history", shift.validate_shift_history_scenario),
426
427
  ("shift-history-show", shift.validate_shift_history_show_scenario),
427
428
  ("shift-resume-checks-commits", shift.validate_shift_resume_checks_commits_scenario),
429
+ ("shift-resume-skips-session-ids", shift.validate_shift_resume_skips_session_ids_scenario),
430
+ ("shift-resume-names-merged-branch", shift.validate_shift_resume_names_merged_branch_scenario),
428
431
  ("shift-keeps-transcripts", shift.validate_shift_keeps_transcripts_scenario),
429
432
  ("shift-keeps-found-transcripts", shift.validate_shift_keeps_found_transcripts_scenario),
430
433
  ("role-drift", shift.validate_role_drift_scenario),
@@ -1526,6 +1526,108 @@ def validate_worktree_overview_scenario() -> int:
1526
1526
  return 0
1527
1527
 
1528
1528
 
1529
+ def validate_shift_resume_skips_session_ids_scenario() -> int:
1530
+ """Issue #445: a shift note's session ids are not read as commits.
1531
+
1532
+ The `CLI session:` header Keel writes, and a recorded session id quoted
1533
+ in prose, are not listed; a landed commit and an unknown hex token still
1534
+ are. An empty session slot leaves no blank line in the header.
1535
+ """
1536
+ label = "shift-resume-skips-session-ids:"
1537
+ with tempfile.TemporaryDirectory(prefix="keel-shift-445-") as raw:
1538
+ base = Path(raw)
1539
+ rtl, verify, env, _ = shift_scratch(base)
1540
+ own = "b5a55cf2-5e84-4193-902b-22012e35eb8e"
1541
+ other = "a166c34f-93e5-441e-b277-fe1e0bda647d"
1542
+ chat_session_start(rtl, env, other, os.getpid())
1543
+
1544
+ def git(*args: str) -> str:
1545
+ return subprocess.run(["git", *args], cwd=rtl, text=True, capture_output=True, check=True).stdout.strip()
1546
+
1547
+ git("commit", "-q", "--allow-empty", "-m", "landed")
1548
+ git("push", "-q", "origin", "HEAD")
1549
+ landed = git("rev-parse", "HEAD")
1550
+ default = git("rev-parse", "--abbrev-ref", "HEAD")
1551
+ note = f"{landed[:8]} landed. deadbee1 was the old base. Session {other[:8]} ran the probe."
1552
+ cli = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": own, "CLAUDE_PID": str(os.getpid())}
1553
+ readied = run_keel(verify, "shift", "ready", note, env=cli)
1554
+ if readied.returncode != 0:
1555
+ report(f"{label} ready failed: {readied.stdout} {readied.stderr}")
1556
+ return 1
1557
+ resumed = run_keel(verify, "shift", "resume", env=env)
1558
+ listed = [line for line in resumed.stdout.splitlines() if line.startswith("- ")]
1559
+
1560
+ def line_for(token: str) -> str:
1561
+ return next((line for line in listed if line.startswith(f"- {token}")), "")
1562
+
1563
+ if f"already in origin/{default}" not in line_for(landed[:8]):
1564
+ report(f"{label} the landed commit is not marked already in origin/{default}: {listed!r}")
1565
+ return 1
1566
+ if "not found" not in line_for("deadbee1"):
1567
+ report(f"{label} an unknown hex token is no longer reported not found: {listed!r}")
1568
+ return 1
1569
+ for name, session in (("the header's CLI session", own), ("a recorded session", other)):
1570
+ if line_for(session[:8]):
1571
+ report(f"{label} {name} id {session[:8]} is listed as a commit: {line_for(session[:8])!r}")
1572
+ return 1
1573
+ if f"CLI session: {own}." not in resumed.stdout:
1574
+ report(f"{label} the note header lost its CLI session line: {resumed.stdout!r}")
1575
+ return 1
1576
+ if "\n\n\n" in resumed.stdout.split(note)[0]:
1577
+ report(f"{label} the note header holds blank lines for empty slots: {resumed.stdout.split(note)[0]!r}")
1578
+ return 1
1579
+ report("shift-resume-skips-session-ids scenario passed.")
1580
+ return 0
1581
+
1582
+
1583
+ def validate_shift_resume_names_merged_branch_scenario() -> int:
1584
+ """Issue #446: resume says when the worktree is on a branch already merged.
1585
+
1586
+ A new shift starts on the branch the last one left, which `land` has
1587
+ usually merged; resume names it and says to start from the default
1588
+ branch. A branch with commits of its own gets no such line.
1589
+ """
1590
+ label = "shift-resume-names-merged-branch:"
1591
+ with tempfile.TemporaryDirectory(prefix="keel-shift-446-") as raw:
1592
+ base = Path(raw)
1593
+ rtl, verify, env, _ = shift_scratch(base)
1594
+ default = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=rtl, text=True,
1595
+ capture_output=True, check=True).stdout.strip()
1596
+
1597
+ def git(*args: str) -> str:
1598
+ return subprocess.run(["git", *args], cwd=verify, text=True, capture_output=True, check=True).stdout.strip()
1599
+
1600
+ git("fetch", "-q", "origin")
1601
+ git("switch", "-q", "-c", "feat", f"origin/{default}")
1602
+ git("commit", "-q", "--allow-empty", "-m", "feat work")
1603
+ git("push", "-q", "origin", f"feat:{default}")
1604
+ after = git("commit-tree", git("rev-parse", "HEAD^{tree}"), "-p", "HEAD", "-m", "next shift's work")
1605
+ git("push", "-q", "origin", f"{after}:refs/heads/{default}")
1606
+ git("fetch", "-q", "origin")
1607
+
1608
+ def resumed(note: str) -> str:
1609
+ ready = run_keel(verify, "shift", "ready", note, env=env)
1610
+ if ready.returncode != 0:
1611
+ return f"ready failed: {ready.stdout} {ready.stderr}"
1612
+ return run_keel(verify, "shift", "resume", env=env).stdout
1613
+
1614
+ merged = resumed("next: pick the next issue")
1615
+ notice = next((line for line in merged.splitlines() if f"already in origin/{default}" in line and "feat" in line), "")
1616
+ if not notice:
1617
+ report(f"{label} resume on merged branch feat does not say so: {merged!r}")
1618
+ return 1
1619
+ if "1 commit behind" not in notice:
1620
+ report(f"{label} the merged-branch line does not say 1 commit behind: {notice!r}")
1621
+ return 1
1622
+ git("commit", "-q", "--allow-empty", "-m", "unpushed work")
1623
+ own = resumed("next: push feat")
1624
+ if any("feat" in line and f"already in origin/{default}" in line for line in own.splitlines()):
1625
+ report(f"{label} a branch with an unpushed commit is reported as merged: {own!r}")
1626
+ return 1
1627
+ report("shift-resume-names-merged-branch scenario passed.")
1628
+ return 0
1629
+
1630
+
1529
1631
  def validate_shift_resume_checks_commits_scenario() -> int:
1530
1632
  """Issue #347: a shift note's commit ids go stale before the next shift reads it.
1531
1633
 
package/src/core/shift.js CHANGED
@@ -451,6 +451,7 @@ function ready(where, options) {
451
451
  const desktop = desktopSession();
452
452
  const pid = desktop ? desktopProcess() : null;
453
453
  const cli = desktop ? null : cliSession();
454
+ // An empty slot is dropped rather than left as a blank line (#445 D3).
454
455
  const head = [
455
456
  `# Shift note: ${role || path.basename(where.worktree)}`,
456
457
  "",
@@ -463,8 +464,7 @@ function ready(where, options) {
463
464
  options.wake ? "Self-initiated: this shift armed `keel shift ready --wake`." : "",
464
465
  !role ? `Started by hand: ${options.forceReason}.` : "",
465
466
  options.forceReason && result.items.length ? `\nLeft as is (${options.forceReason}):\n${result.items.map((item) => `- ${item.kind}: ${item.detail}`).join("\n")}` : "",
466
- "",
467
- ].join("\n");
467
+ ].filter((line, index) => index < 2 || line !== "").concat("").join("\n");
468
468
  const note = ownNotePath(where, role);
469
469
  writeFileAtomic(note, `${head}\n${text}\n`);
470
470
  // Requests are chat records; without a role there is none to close (D2).
@@ -964,7 +964,8 @@ function resumeRole(where, named) {
964
964
  // `ready` and `resume` (#347). Each is marked against the remote-tracking refs
965
965
  // as they are: Keel fetches nothing, and says when they were last fetched.
966
966
  const NOTE_PAIR = /([A-Za-z0-9][\w./-]*)\s*@\s*([0-9a-f]{7,40})\b/g;
967
- const NOTE_SHA = /(?<![\w@/-])([0-9a-f]{7,40})\b/g;
967
+ // The first segment of a UUID — a session id — is not a commit (#445 D1).
968
+ const NOTE_SHA = /(?<![\w@/-])([0-9a-f]{7,40})\b(?!-[0-9a-f]{4}-)/g;
968
969
  const looksLikeSha = (token) => /[a-f]/.test(token) && /\d/.test(token);
969
970
 
970
971
  function remoteDefault(cwd) {
@@ -976,7 +977,23 @@ function remoteDefault(cwd) {
976
977
  return null;
977
978
  }
978
979
 
979
- function noteCommits(cwd, text) {
980
+ // Session ids Keel records or keeps a transcript of (#445 D2).
981
+ function knownSessionIds(where) {
982
+ const ids = new Set();
983
+ const names = (dir) => {
984
+ try {
985
+ return fs.readdirSync(dir);
986
+ } catch {
987
+ return [];
988
+ }
989
+ };
990
+ for (const file of names(path.join(where.root, "sessions"))) ids.add(file.split(".")[0]);
991
+ const kept = path.join(where.root, "shift", "transcripts");
992
+ for (const role of names(kept)) for (const file of names(path.join(kept, role))) ids.add(file.split(".")[0]);
993
+ return [...ids].filter((id) => /^[0-9a-f]{8}-/.test(id));
994
+ }
995
+
996
+ function noteCommits(cwd, text, sessions = []) {
980
997
  const seen = new Set();
981
998
  const named = [];
982
999
  // After `@` the pair already says it is a commit, so an all-digit sha counts
@@ -988,7 +1005,9 @@ function noteCommits(cwd, text) {
988
1005
  for (const match of String(text).matchAll(NOTE_SHA)) {
989
1006
  if (seen.has(match.index)) continue;
990
1007
  // A bare token needs a letter and a digit, or, when it is all digits, to
991
- // resolve to a commit, so a date does not count.
1008
+ // resolve to a commit, so a date does not count; one that begins a session
1009
+ // id Keel records is that session (#445 D2).
1010
+ if (sessions.some((id) => id.startsWith(match[1]))) continue;
992
1011
  const allDigits = /^\d+$/.test(match[1]);
993
1012
  if (allDigits ? !git(cwd, ["rev-parse", "--verify", "--quiet", `${match[1]}^{commit}`]).ok : !looksLikeSha(match[1])) continue;
994
1013
  named.push({ index: match.index, branch: null, sha: match[1], token: match[1] });
@@ -1014,6 +1033,21 @@ function noteCommits(cwd, text) {
1014
1033
  return commits;
1015
1034
  }
1016
1035
 
1036
+ // A new shift starts on the branch the last one left, which `land` has
1037
+ // usually merged (#446 D1): named when HEAD is behind the remote default branch
1038
+ // and contained in it. Nothing is fetched.
1039
+ function mergedBranch(cwd) {
1040
+ const base = remoteDefault(cwd);
1041
+ if (!base) return null;
1042
+ const head = git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"]);
1043
+ const tip = git(cwd, ["rev-parse", "--verify", "--quiet", `refs/remotes/${base}`]);
1044
+ if (!head.ok || !tip.ok || head.out === tip.out) return null;
1045
+ if (!git(cwd, ["merge-base", "--is-ancestor", head.out, tip.out]).ok) return null;
1046
+ const branch = git(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1047
+ const behind = Number(git(cwd, ["rev-list", "--count", `${head.out}..${tip.out}`]).out) || 0;
1048
+ return { branch: branch.ok ? branch.out : null, base, behind };
1049
+ }
1050
+
1017
1051
  function lastFetch(cwd) {
1018
1052
  const file = git(cwd, ["rev-parse", "--git-path", "FETCH_HEAD"]);
1019
1053
  if (!file.ok) return null;
@@ -1033,7 +1067,7 @@ function resume(where, named = null) {
1033
1067
  const history = path.join(shiftDir(where), "history", `${role || path.basename(note, ".md")}-${stamp}.md`);
1034
1068
  fs.mkdirSync(path.dirname(history), { recursive: true });
1035
1069
  fs.renameSync(note, history);
1036
- if (!role) return { role: null, note: history, text, told: null, commits: noteCommits(where.worktree, text), fetched: lastFetch(where.worktree) };
1070
+ if (!role) return { role: null, note: history, text, told: null, commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree) };
1037
1071
  // The cold-start message has done its work once the note is read.
1038
1072
  for (const record of store.unread(where, role)) {
1039
1073
  if (isShift(record)) store.advanceCursor(where, role, record.group, record.id);
@@ -1047,7 +1081,7 @@ function resume(where, named = null) {
1047
1081
  ? store.post(where, { group, text, refs: [REF] })
1048
1082
  : store.writeRecord(where, { group, kind: "message", from: role, refs: [REF], text })).id;
1049
1083
  }
1050
- return { role, note: history, text, told, waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text), fetched: lastFetch(where.worktree) };
1084
+ 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) };
1051
1085
  }
1052
1086
 
1053
1087
  function status(where) {
@@ -1512,7 +1546,12 @@ function runShift(argv) {
1512
1546
  ? `\n\nCommits the note names, against the remote-tracking refs (not fetched; last fetch ${result.fetched || "never"}):\n`
1513
1547
  + result.commits.map((c) => `- ${c.token}: ${c.marks.join("; ")}`).join("\n")
1514
1548
  : "";
1515
- out(result, `${result.text.replace(/\s+$/, "")}${commits}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1549
+ const merged = result.merged_branch;
1550
+ const stale = merged
1551
+ ? `\n\nThis worktree is on ${merged.branch ? `\`${merged.branch}\`` : "a detached HEAD"}, already in ${merged.base} and `
1552
+ + `${merged.behind} commit${merged.behind === 1 ? "" : "s"} behind it: start new work from ${merged.base}.`
1553
+ : "";
1554
+ out(result, `${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1516
1555
  return 0;
1517
1556
  }
1518
1557
  case "history": {