@christang/keel 5.184.0 → 5.186.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.184.0",
3
+ "version": "5.186.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",
package/README.md CHANGED
@@ -1028,7 +1028,8 @@ distribution copies under `plugins/keel/skills/` must stay byte-identical (enfor
1028
1028
  validation).
1029
1029
 
1030
1030
  ```bash
1031
- npm test # one validate_plugin.py --all run: baseline + all scenarios in parallel (--jobs N sets concurrency)
1031
+ npm test # one validate_plugin.py --all run: baseline + all scenarios in parallel (--jobs N sets concurrency), ending with an evidence: line
1032
+ node scripts/run_python.js scripts/validate_plugin.py --evidence # which scenarios are deterministic and which run against a stand-in host; --markdown for release notes
1032
1033
  node scripts/run_python.js scripts/validate_plugin.py --scenario <name> # one scenario
1033
1034
  node scripts/run_python.js scripts/validate_plugin.py --group <module> # one module's scenarios, e.g. --group chat
1034
1035
  node scripts/bump_version.js <patch|minor|major> # bump every version pin at once
package/README.zh-CN.md CHANGED
@@ -868,7 +868,8 @@ target,后续每次 `--install` / `--check` / `--doctor` / `--uninstall` 都
868
868
  (由校验强制)。
869
869
 
870
870
  ```bash
871
- npm test # 一次 validate_plugin.py --all:baseline + 全部场景并行(--jobs N 控制并发)
871
+ npm test # 一次 validate_plugin.py --all:baseline + 全部场景并行(--jobs N 控制并发),最后一行是 evidence: 证据分类
872
+ node scripts/run_python.js scripts/validate_plugin.py --evidence # 哪些场景是确定性的、哪些对着替身宿主跑;--markdown 给发布说明用
872
873
  node scripts/run_python.js scripts/validate_plugin.py --scenario <name> # 单个场景
873
874
  node scripts/run_python.js scripts/validate_plugin.py --group <module> # 一个模块的场景,例如 --group chat
874
875
  node scripts/bump_version.js <patch|minor|major> # 一次改齐所有版本 pin
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.184.0 -->
1
+ <!-- keel:start version=5.186.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.184.0",
3
+ "version": "5.186.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.184.0",
9
+ "version": "5.186.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.184.0",
5
+ "version": "5.186.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.184.0",
3
+ "version": "5.186.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.184.0",
3
+ "version": "5.186.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",
@@ -48,6 +48,7 @@ from validation.baseline import (
48
48
  validate_templates,
49
49
  )
50
50
  from validation.registry import SCENARIOS
51
+ from validation import evidence
51
52
 
52
53
 
53
54
  def run_baseline() -> int:
@@ -104,6 +105,7 @@ def run_all(jobs: int) -> int:
104
105
  if skipped:
105
106
  summary += f", {len(skipped)} skipped: {', '.join(skipped)}"
106
107
  report(f"{summary}.")
108
+ report(evidence.evidence_line(evidence.classify(SCENARIOS), {name for name, _ in SCENARIOS} - set(skipped)))
107
109
  return 0
108
110
 
109
111
 
@@ -138,6 +140,7 @@ def run_group(group: str, jobs: int) -> int:
138
140
  if skipped:
139
141
  summary += f", {len(skipped)} skipped: {', '.join(skipped)}"
140
142
  report(f"{summary}.")
143
+ report(evidence.evidence_line(evidence.classify(SCENARIOS), set(names) - set(skipped)))
141
144
  return 0
142
145
 
143
146
 
@@ -170,6 +173,15 @@ def main() -> int:
170
173
  return 2
171
174
  return run_group(sys.argv[2], jobs)
172
175
 
176
+ if sys.argv[1:2] == ["--evidence"]:
177
+ rest = sys.argv[2:]
178
+ if rest not in ([], ["--markdown"]):
179
+ report(f"usage: validate_plugin.py --evidence [--markdown], got: {' '.join(rest)}")
180
+ return 2
181
+ classes = evidence.classify(SCENARIOS)
182
+ print(evidence.render_markdown(classes) if rest else evidence.render(classes))
183
+ return 0
184
+
173
185
  return run_baseline()
174
186
 
175
187
 
@@ -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.184.0"
38
+ PACKAGE_VERSION = "5.186.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.184.0"
41
+ PROTOCOL_VERSION = "5.186.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -0,0 +1,139 @@
1
+ """Keel validation: what kind of evidence each scenario is (#408).
2
+
3
+ A green summary reads as more than it proves when much of the suite runs Keel
4
+ against a stand-in host — a fake `claude`, the host's environment, a host data
5
+ directory, a hook payload — and none of it against a real one. Every
6
+ registered scenario is classified as deterministic or stand-in host, from
7
+ markers derived from Keel's own sources, through the validation helpers and
8
+ scripts it reaches. The classification is static and over-approximates: a
9
+ scenario that only mentions a marker counts as stand-in host, which claims
10
+ less real evidence, never more.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import re
16
+ from pathlib import Path
17
+
18
+ from validation.common import ROOT
19
+
20
+ # A program or service Keel calls, overridable for a test: `process.env.X ||`
21
+ # a program name, a constant, `npmCommand(…)`, or a platform conditional.
22
+ # Path and identity overrides (`path.join(…)`, `os.hostname()`) are not hosts.
23
+ PROGRAM_OVERRIDE = re.compile(r"process\.env\.(KEEL_[A-Z_]+) \|\| (\"[^\"]+\"|[A-Z][A-Z_]+\b|npmCommand\(|\(process\.platform)")
24
+ HOST_VARIABLE = re.compile(r"\b((?:CLAUDE|CODEX)_[A-Z0-9_]+)\b")
25
+ HOST_PROGRAMS = ("claude", "codex", "npm", "gh", "launchctl", "security")
26
+ SHADOWED_PROGRAM = re.compile(r"/ \"(" + "|".join(HOST_PROGRAMS) + r")\"")
27
+ HOOK_PAYLOAD = "hook_event_name"
28
+ SCRIPT_PATH = re.compile(r"scripts/([a-z_]+\.py)")
29
+ CONTRACT = "docs/host-contract.md"
30
+
31
+
32
+ def keel_sources() -> str:
33
+ files = [*sorted((ROOT / "src").rglob("*.js")), ROOT / "bin" / "keel.js", *sorted((ROOT / "plugins" / "keel" / "scripts").rglob("*.js"))]
34
+ return "\n".join(path.read_text(encoding="utf-8") for path in files)
35
+
36
+
37
+ def markers() -> list[str]:
38
+ text = keel_sources()
39
+ found = {match.group(1) for match in PROGRAM_OVERRIDE.finditer(text)} | set(HOST_VARIABLE.findall(text))
40
+ return sorted(found | {HOOK_PAYLOAD})
41
+
42
+
43
+ def definitions() -> dict[str, tuple[set[str], str]]:
44
+ """Each module-level function or assignment under scripts/validation/: the names it references and its source."""
45
+ found: dict[str, tuple[set[str], str]] = {}
46
+ for module in sorted((ROOT / "scripts" / "validation").glob("*.py")):
47
+ source = module.read_text(encoding="utf-8")
48
+ for node in ast.parse(source).body:
49
+ if isinstance(node, ast.FunctionDef):
50
+ names = [node.name]
51
+ elif isinstance(node, ast.Assign):
52
+ names = [target.id for target in node.targets if isinstance(target, ast.Name)]
53
+ else:
54
+ continue
55
+ refs = {item.id for item in ast.walk(node) if isinstance(item, ast.Name)}
56
+ refs |= {item.attr for item in ast.walk(node) if isinstance(item, ast.Attribute)}
57
+ for name in names:
58
+ found[name] = (refs, ast.get_source_segment(source, node) or "")
59
+ return found
60
+
61
+
62
+ def reached_text(function: str, found: dict[str, tuple[set[str], str]]) -> tuple[str, set[str]]:
63
+ seen: set[str] = set()
64
+ todo = [function]
65
+ while todo:
66
+ name = todo.pop()
67
+ if name in seen or name not in found:
68
+ continue
69
+ seen.add(name)
70
+ todo.extend(ref for ref in found[name][0] if ref in found)
71
+ text = "\n".join(found[name][1] for name in sorted(seen))
72
+ for script in sorted(set(SCRIPT_PATH.findall(text))):
73
+ path = ROOT / "scripts" / script
74
+ if path.is_file() and script != "validate_plugin.py":
75
+ text += "\n" + path.read_text(encoding="utf-8")
76
+ return text, seen
77
+
78
+
79
+ def classify(scenarios) -> dict:
80
+ """{"markers", "stand-in host", "deterministic", "can skip"} for the registered scenarios, in registry order."""
81
+ marks = markers()
82
+ found = definitions()
83
+ standin, deterministic, skippable = [], [], []
84
+ for name, function in scenarios:
85
+ defined = getattr(function, "__name__", None)
86
+ text, seen = reached_text(defined, found) if defined in found else ("", set())
87
+ # A scenario whose code cannot be read cannot be shown deterministic.
88
+ if defined not in found or any(mark in text for mark in marks) or SHADOWED_PROGRAM.search(text):
89
+ standin.append(name)
90
+ else:
91
+ deterministic.append(name)
92
+ if "skip_scenario" in seen:
93
+ skippable.append(name)
94
+ return {"markers": marks, "stand-in host": standin, "deterministic": deterministic, "can skip": skippable}
95
+
96
+
97
+ def evidence_line(classes: dict, ran: set[str]) -> str:
98
+ """The line after a passing run: the classes of the scenarios that ran."""
99
+ deterministic = sum(1 for name in classes["deterministic"] if name in ran)
100
+ standin = sum(1 for name in classes["stand-in host"] if name in ran)
101
+ return (f"evidence: {deterministic} deterministic, {standin} against a stand-in host, "
102
+ f"none on a real host (host measurements: {CONTRACT})")
103
+
104
+
105
+ def measured_rows() -> int:
106
+ """Rows of the host contract whose evidence cell records a real-host measurement."""
107
+ text = (ROOT / CONTRACT).read_text(encoding="utf-8")
108
+ return sum(1 for line in text.splitlines()
109
+ if line.startswith("|") and "measured" in line.rstrip().rstrip("|").rsplit("|", 1)[-1])
110
+
111
+
112
+ def render(classes: dict) -> str:
113
+ return "\n".join([
114
+ f"evidence: {len(classes['deterministic'])} deterministic, {len(classes['stand-in host'])} against a stand-in host, "
115
+ f"none on a real host (host measurements: {CONTRACT})",
116
+ f"stand-in markers: {', '.join(classes['markers'])}",
117
+ f"stand-in host: {', '.join(classes['stand-in host'])}",
118
+ f"deterministic: {', '.join(classes['deterministic'])}",
119
+ f"can skip: {', '.join(classes['can skip'])}",
120
+ ])
121
+
122
+
123
+ def render_markdown(classes: dict) -> str:
124
+ skips = ", ".join(f"`{name}`" for name in classes["can skip"]) or "none"
125
+ return "\n".join([
126
+ "",
127
+ "## Evidence",
128
+ "",
129
+ "What the full gate ran for this release, by kind (`validate_plugin.py --evidence`):",
130
+ "",
131
+ f"- **Deterministic:** {len(classes['deterministic'])} scenarios run Keel's own code against real git, Node and files.",
132
+ f"- **Stand-in host:** {len(classes['stand-in host'])} scenarios run Keel against a stand-in for a host program, "
133
+ "the host's environment, a host data directory or a hook payload. They show what Keel does with the shapes they "
134
+ "model, not that a host still produces them.",
135
+ f"- **Real host:** none. CI has no Claude Code or Codex. `{CONTRACT}` records {measured_rows()} conditions "
136
+ "measured on a real host, each with its version and date.",
137
+ f"- **Can skip:** {skips} skip when the runtime they need is missing; the full gate's log names any that did.",
138
+ "",
139
+ ])
@@ -416,6 +416,8 @@ SCENARIOS: tuple = (
416
416
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
417
417
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
418
418
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
419
+ ("shift-cli-handover-claims-once", shift.validate_shift_cli_handover_claims_once_scenario),
420
+ ("shift-cli-retries-failed-handover", shift.validate_shift_cli_retries_failed_handover_scenario),
419
421
  ("owner-language", chat.validate_owner_language_scenario),
420
422
  ("owner-language-after-tools", chat.validate_owner_language_after_tools_scenario),
421
423
  ("shift-history", shift.validate_shift_history_scenario),
@@ -476,6 +478,7 @@ SCENARIOS: tuple = (
476
478
  ("repo-action-mode", guard.validate_repo_action_mode_scenario),
477
479
  ("runner-skip-accounting", selfcheck.validate_runner_skip_accounting_scenario),
478
480
  ("runner-runs-one-group", selfcheck.validate_runner_runs_one_group_scenario),
481
+ ("release-evidence-classes", selfcheck.validate_release_evidence_classes_scenario),
479
482
  ("self-checks-read-every-module", selfcheck.validate_self_checks_read_every_module_scenario),
480
483
  ("resident-topic-matching", selfcheck.validate_resident_topic_matching_scenario),
481
484
  ("task-start-invalidation", contract.validate_task_start_invalidation_scenario),
@@ -1464,3 +1464,89 @@ def validate_the_routing_rule_reaches_the_decision_scenario() -> int:
1464
1464
  return 1
1465
1465
  report(f"{label} scenario passed.")
1466
1466
  return 0
1467
+
1468
+
1469
+ def validate_release_evidence_classes_scenario() -> int:
1470
+ """Issue #408 (owner, 2026-10-21): the suite and each release say what kind of evidence ran.
1471
+
1472
+ A green summary read as more than it proved: much of the suite runs Keel
1473
+ against a stand-in host — a fake `claude`, the host's environment, a host
1474
+ data directory, a hook payload — and none of it against a real one. Each
1475
+ scenario is classified from markers derived from Keel's own sources,
1476
+ through the helpers and scripts it reaches; a passing run and each
1477
+ release's notes give the counts.
1478
+ """
1479
+ label = "release-evidence-classes:"
1480
+ plain = subprocess.run([sys.executable, str(ROOT / "scripts/validate_plugin.py"), "--evidence"],
1481
+ cwd=ROOT, text=True, capture_output=True)
1482
+ if plain.returncode != 0:
1483
+ report(f"{label} `--evidence` exited {plain.returncode}: {(plain.stderr or plain.stdout).strip()!r}")
1484
+ return 1
1485
+ lines = {line.split(":", 1)[0]: line.split(":", 1)[1].strip() for line in plain.stdout.splitlines() if ":" in line}
1486
+ standin = set(filter(None, (name.strip() for name in lines.get("stand-in host", "").split(","))))
1487
+ deterministic = set(filter(None, (name.strip() for name in lines.get("deterministic", "").split(","))))
1488
+ markers = set(filter(None, (name.strip() for name in lines.get("stand-in markers", "").split(","))))
1489
+ for name in ("KEEL_CLAUDE", "CLAUDE_CODE_SESSION_ID"):
1490
+ if name not in markers:
1491
+ report(f"{label} the markers derived from Keel's sources do not include {name}: {sorted(markers)!r}")
1492
+ return 1
1493
+ for name in ("shift-cli-self-shift", "chat-claude-hooks", "codex-receiving", "update-pack-install"):
1494
+ if name not in standin:
1495
+ report(f"{label} {name} is not counted as run against a stand-in host.")
1496
+ return 1
1497
+ if "version-alignment" not in deterministic:
1498
+ report(f"{label} version-alignment is not counted as deterministic.")
1499
+ return 1
1500
+ registered = {name for name, _ in registry.SCENARIOS}
1501
+ if standin & deterministic:
1502
+ report(f"{label} scenarios are counted in both classes: {sorted(standin & deterministic)!r}")
1503
+ return 1
1504
+ if standin | deterministic != registered:
1505
+ report(f"{label} the two classes do not cover the registry: missing {sorted(registered - standin - deterministic)!r}, "
1506
+ f"unknown {sorted((standin | deterministic) - registered)!r}")
1507
+ return 1
1508
+
1509
+ contract = (ROOT / "docs/host-contract.md").read_text(encoding="utf-8")
1510
+ measured = sum(1 for line in contract.splitlines()
1511
+ if line.startswith("|") and "measured" in line.rstrip().rstrip("|").rsplit("|", 1)[-1])
1512
+ skippable = set(filter(None, (name.strip() for name in lines.get("can skip", "").split(","))))
1513
+ if "output-survives-the-pipe" not in skippable:
1514
+ report(f"{label} `--evidence` does not name output-survives-the-pipe among the scenarios that can skip: {sorted(skippable)!r}")
1515
+ return 1
1516
+ markdown = subprocess.run([sys.executable, str(ROOT / "scripts/validate_plugin.py"), "--evidence", "--markdown"],
1517
+ cwd=ROOT, text=True, capture_output=True)
1518
+ section = markdown.stdout
1519
+ for needle in ("## Evidence", f"{len(deterministic)} scenarios", f"{len(standin)} scenarios",
1520
+ f"{measured} conditions", "docs/host-contract.md", *sorted(skippable)):
1521
+ if needle not in section:
1522
+ report(f"{label} the release notes section does not carry {needle!r}: {section!r}")
1523
+ return 1
1524
+
1525
+ workflow = (ROOT / ".github/workflows/publish.yml").read_text(encoding="utf-8")
1526
+ start = workflow.find("- name: Tag and release the landed version")
1527
+ following = workflow.find("\n - name:", start + 1)
1528
+ step = workflow[start:] if following < 0 else workflow[start:following]
1529
+ if "validate_plugin.py --evidence --markdown >> notes.md" not in step:
1530
+ report(f"{label} the publish release step does not append `validate_plugin.py --evidence --markdown` to notes.md.")
1531
+ return 1
1532
+
1533
+ grouped = subprocess.run([sys.executable, str(ROOT / "scripts/validate_plugin.py"), "--group", "docs"],
1534
+ cwd=ROOT, text=True, capture_output=True)
1535
+ tail = grouped.stdout.strip().splitlines()[-2:]
1536
+ verified = re.search(r"validation --group docs passed: (\d+) scenario", tail[0]) if tail else None
1537
+ counts = re.match(r"evidence: (\d+) deterministic, (\d+) against a stand-in host, none on a real host .*docs/host-contract\.md",
1538
+ tail[-1]) if tail else None
1539
+ if grouped.returncode != 0 or not verified:
1540
+ report(f"{label} `--group docs` did not pass: {grouped.stdout[-400:]!r}")
1541
+ return 1
1542
+ if not counts:
1543
+ report(f"{label} a passing `--group docs` does not end with an evidence line: {tail!r}")
1544
+ return 1
1545
+ if int(counts.group(1)) + int(counts.group(2)) != int(verified.group(1)):
1546
+ report(f"{label} the evidence line's counts do not add up to the {verified.group(1)} verified: {tail[-1]!r}")
1547
+ return 1
1548
+ if label.rstrip(":") not in registered:
1549
+ report(f"{label} the scenario registry does not include it.")
1550
+ return 1
1551
+ report(f"{label.rstrip(':')} scenario passed: {len(deterministic)} deterministic, {len(standin)} stand-in host.")
1552
+ return 0
@@ -2672,6 +2672,198 @@ def validate_tick_retries_failed_wake_scenario() -> int:
2672
2672
  return 0
2673
2673
 
2674
2674
 
2675
+ HANDOVER_RETRY_FAKE = """#!/usr/bin/env python3
2676
+ import json, os, sys, time
2677
+ agents, calls = os.environ['FAKE_AGENTS'], os.environ['FAKE_CALLS']
2678
+ argv = sys.argv[1:]
2679
+ def load():
2680
+ return json.loads(open(agents).read())
2681
+ def save(rows):
2682
+ tmp = agents + '.' + str(os.getpid())
2683
+ open(tmp, 'w').write(json.dumps(rows)); os.replace(tmp, agents)
2684
+ open(calls, 'a').write(json.dumps({'argv': argv}) + '\\n')
2685
+ if argv[:2] == ['agents', '--json']:
2686
+ print(json.dumps([{k: v for k, v in row.items() if not k.startswith('_')} for row in load()])); sys.exit(0)
2687
+ if argv[:1] == ['stop']:
2688
+ rows = load()
2689
+ for row in rows:
2690
+ if row['id'] == argv[1] and 'status' in row:
2691
+ row.pop('status', None); pid = row.pop('pid', None); row['state'] = 'stopped'
2692
+ if pid:
2693
+ try:
2694
+ os.kill(pid, 9)
2695
+ except OSError:
2696
+ pass
2697
+ save(rows); print('stopped ' + argv[1]); sys.exit(0)
2698
+ if argv[:1] == ['--bg'] and '--resume' not in argv:
2699
+ failing = os.environ.get('FAKE_BG_FAILS', '0')
2700
+ count = os.environ['FAKE_CALLS'] + '.starts'
2701
+ made = int(open(count).read()) if os.path.exists(count) else 0
2702
+ open(count, 'w').write(str(made + 1))
2703
+ if failing == 'always' or made < int(failing):
2704
+ print('Workspace not trusted.', file=sys.stderr); sys.exit(1)
2705
+ new = 'newsess%d-0000-0000-0000-000000000000' % (made + 1)
2706
+ rows = load()
2707
+ rows.append({'kind': 'background', 'name': argv[2], 'sessionId': new, 'id': new[:8], 'status': 'busy', 'state': 'working',
2708
+ 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': int(time.time() * 1000)})
2709
+ save(rows)
2710
+ time.sleep(float(os.environ.get('FAKE_BG_SLEEP', '0')))
2711
+ print('backgrounded · ' + new[:8] + ' · ' + argv[2]); sys.exit(0)
2712
+ print('ok')
2713
+ """
2714
+
2715
+
2716
+ def handover_retry_scratch(base: Path, old: str) -> dict:
2717
+ """A verify hand-off queued from an idle CLI session, against HANDOVER_RETRY_FAKE."""
2718
+ rtl, verify, env, _ = shift_scratch(base)
2719
+ agents, calls, fake = base / "agents.json", base / "calls.jsonl", base / "fake-claude"
2720
+ write_text(fake, HANDOVER_RETRY_FAKE)
2721
+ fake.chmod(0o755)
2722
+ process = detached_sleeper()
2723
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify · 10-20 09:00", "sessionId": old, "id": old[:8],
2724
+ "status": "idle", "state": "done", "pid": process, "cwd": str(verify),
2725
+ "startedAt": 1792500000000}]))
2726
+ calls.write_text("")
2727
+ exited = subprocess.Popen(["true"])
2728
+ exited.wait()
2729
+ env = {**env, "KEEL_CLAUDE": str(fake), "FAKE_AGENTS": str(agents), "FAKE_CALLS": str(calls),
2730
+ "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1", "KEEL_SHIFT_EXIT_WAIT_MS": "500"}
2731
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": old, "CLAUDE_PID": str(exited.pid)}
2732
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R040", env=cli_env)
2733
+ if readied.returncode != 0:
2734
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
2735
+ queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue" / "verify.json"
2736
+
2737
+ def starts() -> int:
2738
+ return sum(1 for line in calls.read_text().splitlines()
2739
+ if json.loads(line)["argv"][:1] == ["--bg"] and "--resume" not in json.loads(line)["argv"])
2740
+
2741
+ return {"rtl": rtl, "verify": verify, "env": env, "agents": agents, "calls": calls, "queue": queue,
2742
+ "starts": starts, "process": process,
2743
+ "tick": lambda extra=None: run_keel(verify, "tick", "--repo", str(rtl), env={**env, **(extra or {})}),
2744
+ "keel": ["node", str(ROOT / "bin" / "keel.js")]}
2745
+
2746
+
2747
+ def validate_shift_cli_handover_claims_once_scenario() -> int:
2748
+ """Issue #408, second loop: one pending hand-off starts one session.
2749
+
2750
+ Runners claim the entry as `starting` before any host call (D1). So two
2751
+ ticks and a waiter running at the same moment start one session. A runner
2752
+ killed after `claude --bg` listed the new session is settled by adopting
2753
+ that session, not by starting another (D2, D3).
2754
+ """
2755
+ label = "shift-cli-handover-claims-once:"
2756
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2757
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408c-") as raw:
2758
+ s = handover_retry_scratch(Path(raw), OLD)
2759
+ try:
2760
+ race = {**s["env"], "FAKE_BG_SLEEP": "1", "KEEL_SHIFT_HANDOVER_POLL_MS": "50", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "8000"}
2761
+ runners = [subprocess.Popen([*s["keel"], "tick", "--repo", str(s["rtl"])], cwd=s["verify"], env=race,
2762
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(2)]
2763
+ runners.append(subprocess.Popen([*s["keel"], "shift", "handover-wait", "--role", "verify", "--repo", str(s["verify"])],
2764
+ cwd=s["verify"], env=race, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
2765
+ for runner in runners:
2766
+ runner.wait(timeout=60)
2767
+ entry = json.loads(s["queue"].read_text())
2768
+ if s["starts"]() != 1 or entry["state"] != "delivered":
2769
+ report(f"{label} two ticks and a waiter at once ran `claude --bg` {s['starts']()} times; the entry is {entry['state']}.")
2770
+ return 1
2771
+ finally:
2772
+ with contextlib.suppress(OSError):
2773
+ os.kill(s["process"], signal.SIGKILL)
2774
+
2775
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408d-") as raw:
2776
+ s = handover_retry_scratch(Path(raw), OLD)
2777
+ try:
2778
+ slow = {**s["env"], "FAKE_BG_SLEEP": "30"}
2779
+ runner = subprocess.Popen([*s["keel"], "tick", "--repo", str(s["rtl"])], cwd=s["verify"], env=slow,
2780
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
2781
+ deadline = time.time() + 20
2782
+ while s["starts"]() < 1 and time.time() < deadline:
2783
+ time.sleep(0.1)
2784
+ time.sleep(0.5)
2785
+ os.killpg(runner.pid, signal.SIGKILL)
2786
+ runner.wait()
2787
+ # The next tick comes minutes later, when any lock the dead runner left reads as stale.
2788
+ for lock in s["queue"].parent.glob("*.lock"):
2789
+ os.utime(lock, (time.time() - 600, time.time() - 600))
2790
+ s["tick"]()
2791
+ entry = json.loads(s["queue"].read_text())
2792
+ if s["starts"]() != 1:
2793
+ report(f"{label} a tick after the runner died mid-start ran `claude --bg` again: {s['starts']()} starts; the entry is {entry['state']}.")
2794
+ return 1
2795
+ if entry["state"] != "delivered" or not entry.get("adopted") or entry.get("new_session") != "newsess1":
2796
+ report(f"{label} the entry left by a runner that died mid-start was not delivered with the listed session: {entry!r}")
2797
+ return 1
2798
+ finally:
2799
+ with contextlib.suppress(OSError):
2800
+ os.kill(s["process"], signal.SIGKILL)
2801
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2802
+ report(f"{label} the scenario registry does not include it.")
2803
+ return 1
2804
+ report(f"{label.rstrip(':')} scenario passed.")
2805
+ return 0
2806
+
2807
+
2808
+ def validate_shift_cli_retries_failed_handover_scenario() -> int:
2809
+ """Issue #408, second loop: a failed hand-off is retried within a bound (D4, D5).
2810
+
2811
+ The tick makes up to three start attempts per entry. After the last one,
2812
+ status and the patrol name `keel chat wake now <role>`. The tick does not
2813
+ retry when the old session runs again, or when the entry predates the
2814
+ attempt count.
2815
+ """
2816
+ label = "shift-cli-retries-failed-handover:"
2817
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2818
+ for case in ("always", "third", "resumed", "legacy"):
2819
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408e-") as raw:
2820
+ s = handover_retry_scratch(Path(raw), OLD)
2821
+ try:
2822
+ fails = {"FAKE_BG_FAILS": "2" if case == "third" else "always"}
2823
+ s["tick"](fails)
2824
+ if case == "resumed":
2825
+ rows = json.loads(s["agents"].read_text())
2826
+ rows[0].update({"status": "idle", "state": "done", "pid": s["process"]})
2827
+ s["agents"].write_text(json.dumps(rows))
2828
+ if case == "legacy":
2829
+ entry = json.loads(s["queue"].read_text())
2830
+ entry.pop("attempts", None)
2831
+ s["queue"].write_text(json.dumps(entry))
2832
+ for _ in range(4 if case in ("always", "third") else 2):
2833
+ s["tick"](fails)
2834
+ entry = json.loads(s["queue"].read_text())
2835
+ status = run_keel(s["rtl"], "shift", "status", env=s["env"]).stdout
2836
+ if case == "always":
2837
+ if s["starts"]() != 3:
2838
+ report(f"{label} five ticks ran a failing `claude --bg` {s['starts']()} times, not 3.")
2839
+ return 1
2840
+ patrolled = run_keel(s["rtl"], "patrol", env=s["env"]).stdout
2841
+ if entry["state"] != "failed":
2842
+ report(f"{label} after three failed starts the entry is {entry['state']}, not failed.")
2843
+ return 1
2844
+ if "keel chat wake now verify" not in status:
2845
+ report(f"{label} after three failed starts, shift status does not name `keel chat wake now verify`: {status!r}")
2846
+ return 1
2847
+ if "keel chat wake now verify" not in patrolled:
2848
+ report(f"{label} after three failed starts, the patrol does not name `keel chat wake now verify`: {patrolled!r}")
2849
+ return 1
2850
+ elif case == "third":
2851
+ if s["starts"]() != 3 or entry["state"] != "delivered" or entry.get("new_session") != "newsess3":
2852
+ report(f"{label} a start that fails twice was not delivered on the third attempt: {s['starts']()} starts, {entry!r}")
2853
+ return 1
2854
+ elif s["starts"]() != 1 or entry["state"] != "failed":
2855
+ report(f"{label} a failed hand-off was retried although {'its old session runs again' if case == 'resumed' else 'it records no attempts'}: {s['starts']()} starts, {entry['state']}.")
2856
+ return 1
2857
+ finally:
2858
+ with contextlib.suppress(OSError):
2859
+ os.kill(s["process"], signal.SIGKILL)
2860
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2861
+ report(f"{label} the scenario registry does not include it.")
2862
+ return 1
2863
+ report(f"{label.rstrip(':')} scenario passed.")
2864
+ return 0
2865
+
2866
+
2675
2867
  def validate_shift_cli_self_shift_scenario() -> int:
2676
2868
  """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
2677
2869
 
package/src/core/shift.js CHANGED
@@ -663,20 +663,94 @@ function withHandOverLock(where, role, fn) {
663
663
  }
664
664
  }
665
665
 
666
+ // A failed start is tried again this many times in all (#408 D4).
667
+ const HANDOVER_ATTEMPTS = 3;
668
+
669
+ // A claimed hand-over whose runner is gone, or that has outlived the bounded
670
+ // worst case of its host calls, is settled by another runner (#408 D2).
671
+ function runnerGone(entry, now = Date.now()) {
672
+ return !processRunning(Number(entry.runner_pid)) || !(now - Date.parse(entry.starting_at) <= 10 * 60 * 1000);
673
+ }
674
+
675
+ function actionable(entry) {
676
+ return entry.state === "pending"
677
+ || (entry.state === "starting" && runnerGone(entry))
678
+ || (entry.state === "failed" && Number.isInteger(entry.attempts) && entry.attempts < HANDOVER_ATTEMPTS);
679
+ }
680
+
681
+ // The session a claimed hand-over already started, if the host lists one (#408
682
+ // D3): named for the role, in its worktree, started since the claim.
683
+ function startedFor(entry, sessions) {
684
+ const since = Date.parse(entry.starting_at) - 5000;
685
+ const home = realpath(entry.worktree);
686
+ return sessions.find((row) => row && typeof row.name === "string" && row.name.startsWith(`${entry.role} · `)
687
+ && row.sessionId !== entry.session && Number(row.startedAt) >= since && row.cwd && realpath(row.cwd) === home) || null;
688
+ }
689
+
690
+ function deliver(claude, where, entry, id, name, adopted) {
691
+ const { readShiftDeclaration } = require("./config");
692
+ const declared = readShiftDeclaration(entry.worktree);
693
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
694
+ for (const key of ["error", "failed_at", "runner_pid"]) delete entry[key];
695
+ if (adopted) entry.adopted = true;
696
+ entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
697
+ if (declared.message) entry.notice = declared.message;
698
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
699
+ return entry;
700
+ }
701
+
702
+ // Under the role's lock, decide what one entry needs, and claim it as
703
+ // `starting` before any host call, so the lock is held only for this (#408 D1):
704
+ // a runner acts only on an entry nobody has claimed.
705
+ function claim(where, queued, sessions) {
706
+ return withHandOverLock(where, queued.role, () => {
707
+ const entry = store.readJsonFile(queueFile(where, queued.role));
708
+ if (!entry || !actionable(entry)) return null;
709
+ const row = sessions.find((item) => item && item.sessionId === entry.session);
710
+ if (entry.waiting_on) {
711
+ delete entry.waiting_on;
712
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
713
+ }
714
+ if (entry.state === "starting") {
715
+ const started = startedFor(entry, sessions);
716
+ if (started) return { entry, adopt: started };
717
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: "the hand-over runner stopped before the new session started" });
718
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
719
+ if (entry.attempts >= HANDOVER_ATTEMPTS) return null;
720
+ }
721
+ if (entry.state === "failed") {
722
+ // Someone resumed the old session: it is theirs now (#408 D4).
723
+ if (row && row.status) {
724
+ Object.assign(entry, { attempts: HANDOVER_ATTEMPTS, error: `${entry.error}; not retried: the old session is running again` });
725
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
726
+ return null;
727
+ }
728
+ const started = entry.starting_at && startedFor(entry, sessions);
729
+ if (started) return { entry, adopt: started };
730
+ } else if (!finished(row)) {
731
+ return null;
732
+ }
733
+ Object.assign(entry, { state: "starting", runner_pid: process.pid, starting_at: store.isoLocal(new Date()), attempts: (entry.attempts || 0) + 1 });
734
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
735
+ return { entry, row };
736
+ });
737
+ }
738
+
666
739
  // One step of the waker (#357 D2): a busy or unfinished old session waits; a
667
- // finished or gone one is retired (kept: \`claude attach\` reopens it) and a new
668
- // session starts. `only` limits the step to one role (the waiter's).
740
+ // finished or gone one is retired (stopped) and a new session starts. A claim
741
+ // left by a runner that died is settled, and a failed start is tried again
742
+ // (#408). `only` limits the step to one role (the waiter's).
669
743
  function handOver(where, only = null) {
670
744
  const { readShiftDeclaration } = require("./config");
671
745
  const claude = process.env.KEEL_CLAUDE || "claude";
672
- const pending = handOffs(where).filter((entry) => entry.state === "pending" && (!only || entry.role === only));
673
- if (!pending.length) return [];
746
+ const queuedEntries = handOffs(where).filter((entry) => actionable(entry) && (!only || entry.role === only));
747
+ if (!queuedEntries.length) return [];
674
748
  const queried = queryAgents(claude);
675
749
  const sessions = queried.rows;
676
750
  // A listing that failed says nothing about the old session: wait for the next
677
751
  // step, and say why on the entry, which status and the patrol show (#408 D2).
678
752
  if (!sessions) {
679
- for (const queuedEntry of pending) {
753
+ for (const queuedEntry of queuedEntries) {
680
754
  const entry = store.readJsonFile(queueFile(where, queuedEntry.role));
681
755
  if (entry && entry.state === "pending" && entry.waiting_on !== queried.why) {
682
756
  store.writeJsonAtomic(where, queueFile(where, entry.role), { ...entry, waiting_on: queried.why });
@@ -685,39 +759,33 @@ function handOver(where, only = null) {
685
759
  return [];
686
760
  }
687
761
  const done = [];
688
- for (const queued of pending) {
689
- const ran = withHandOverLock(where, queued.role, () => {
690
- const entry = store.readJsonFile(queueFile(where, queued.role));
691
- if (!entry || entry.state !== "pending") return null;
692
- const row = sessions.find((item) => item && item.sessionId === entry.session);
693
- if (entry.waiting_on) {
694
- delete entry.waiting_on;
695
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
696
- }
697
- if (!finished(row)) return null;
698
- // `stop`, `attach` and `logs` take the 8-character job id, not the full
699
- // session id (`No job matching`, measured 2026-10-19).
700
- if (row) retire(claude, entry, row);
701
- const declared = readShiftDeclaration(entry.worktree);
702
- const mode = declared.permissionMode;
703
- const name = sessionName(entry.role);
704
- const started = spawnSync(claude, ["--bg", "-n", name, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
705
- cwd: entry.worktree, encoding: "utf8", timeout: hostTimeout(),
706
- });
707
- const output = `${started.stdout || ""}`;
708
- if (!started.error && started.status === 0) {
709
- const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
710
- Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
711
- entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
712
- if (declared.message) entry.notice = declared.message;
713
- } else {
714
- const reason = started.error ? hostTrouble(started, "claude --bg") : String(started.stderr || output).trim().split(/\r?\n/).pop();
715
- Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
716
- }
717
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
718
- return entry;
762
+ for (const queued of queuedEntries) {
763
+ const claimed = claim(where, queued, sessions);
764
+ if (!claimed) continue;
765
+ const { entry, row, adopt } = claimed;
766
+ if (adopt) {
767
+ done.push(deliver(claude, where, entry, adopt.id || adopt.sessionId.slice(0, 8), adopt.name, true));
768
+ continue;
769
+ }
770
+ // `stop`, `attach` and `logs` take the 8-character job id, not the full
771
+ // session id (`No job matching`, measured 2026-10-19).
772
+ if (row) retire(claude, entry, row);
773
+ const mode = readShiftDeclaration(entry.worktree).permissionMode;
774
+ const name = sessionName(entry.role);
775
+ const started = spawnSync(claude, ["--bg", "-n", name, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
776
+ cwd: entry.worktree, encoding: "utf8", timeout: hostTimeout(),
719
777
  });
720
- if (ran) done.push(ran);
778
+ const output = `${started.stdout || ""}`;
779
+ if (!started.error && started.status === 0) {
780
+ const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
781
+ done.push(deliver(claude, where, entry, id, name, false));
782
+ } else {
783
+ const reason = started.error ? hostTrouble(started, "claude --bg") : String(started.stderr || output).trim().split(/\r?\n/).pop();
784
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
785
+ delete entry.runner_pid;
786
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
787
+ done.push(entry);
788
+ }
721
789
  }
722
790
  return done;
723
791
  }
@@ -750,7 +818,8 @@ function waitForHandOver(where, role) {
750
818
  function describeHandOff(entry) {
751
819
  const tail = entry.state === "delivered"
752
820
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}`
753
- : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}`
821
+ : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}; ${retryNote(entry)}`
822
+ : entry.state === "starting" ? `starting since ${entry.starting_at} (attempt ${entry.attempts} of ${HANDOVER_ATTEMPTS})`
754
823
  : entry.waiting_on ? `pending: cannot ask the host — ${entry.waiting_on}` : "pending: waits for the session to go idle";
755
824
  // An entry from before #399 recorded whether the old session's rename showed.
756
825
  const renamed = entry.state === "delivered" && "renamed" in entry ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
@@ -763,11 +832,19 @@ function describeHandOff(entry) {
763
832
  return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; ${reopen}${removed}${notice}`;
764
833
  }
765
834
 
835
+ // What follows a failed start: the tick's next attempt, or, once none is left,
836
+ // the existing way to bring the role back (#408 D5).
837
+ function retryNote(entry) {
838
+ return Number.isInteger(entry.attempts) && entry.attempts < HANDOVER_ATTEMPTS
839
+ ? `attempt ${entry.attempts} of ${HANDOVER_ATTEMPTS}, the tick tries again`
840
+ : `resume the old session with \`keel chat wake now ${entry.role}\``;
841
+ }
842
+
766
843
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
767
844
  function handOffRisks(where, now = Date.now()) {
768
845
  return handOffs(where).filter((entry) => entry.state === "failed"
769
846
  || (entry.state === "pending" && now - Date.parse(entry.requested_at) > 15 * 60 * 1000))
770
- .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}` : ` since ${entry.requested_at}`}`
847
+ .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}; ${retryNote(entry)}` : ` since ${entry.requested_at}`}`
771
848
  + `${entry.waiting_on ? ` (${entry.waiting_on})` : ""}; see \`keel shift status\``);
772
849
  }
773
850