@christang/keel 5.223.0 → 5.225.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.223.0",
3
+ "version": "5.225.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
@@ -2,11 +2,11 @@
2
2
 
3
3
  **English** | [中文](README.zh-CN.md)
4
4
 
5
- > OpenSpec execution discipline for AI coding agents — Claude Code, Codex, and OpenCode.
5
+ > OpenSpec execution discipline for AI coding agents — Claude Code, Codex, OpenCode, and DSH.
6
6
 
7
7
  ![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)
8
8
  ![Node](https://img.shields.io/badge/node-%3E%3D20.19.0-brightgreen.svg)
9
- ![Targets](https://img.shields.io/badge/targets-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20OpenCode-blue.svg)
9
+ ![Targets](https://img.shields.io/badge/targets-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20OpenCode%20%C2%B7%20DSH-blue.svg)
10
10
 
11
11
  ## What Keel is for
12
12
 
@@ -159,9 +159,11 @@ In your project's root, set it up once:
159
159
 
160
160
  ```bash
161
161
  keel --init # default target: claude
162
- keel --init --target codex # or: opencode
162
+ keel --init --target codex # or: opencode, dsh
163
163
  ```
164
164
 
165
+ `--target dsh` (DSH, DeepSeek Harness) writes, checks and removes exactly the files `--target codex` does: DSH reads the repository `AGENTS.md` and `.agents/skills`, so there is no separate DSH copy, and uninstalling one removes them for the other. DSH's factory profiles carry no session-start hook, so every capability is `manual` and the `AGENTS.md` bootstrap ("run `keel context` first") is the entry; `keel --doctor --target dsh` reports whether a `dsh` is on PATH and says so.
166
+
165
167
  `keel --init` runs OpenSpec init/update and writes Keel's host surface. Then, every time you
166
168
  start or resume work:
167
169
 
package/README.zh-CN.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  [English](README.md) | **中文**
4
4
 
5
- > 面向 AI 编码 agent 的 OpenSpec 执行纪律 —— Claude Code、Codex、OpenCode 通用。
5
+ > 面向 AI 编码 agent 的 OpenSpec 执行纪律 —— Claude Code、Codex、OpenCode、DSH 通用。
6
6
 
7
7
  ![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)
8
8
  ![Node](https://img.shields.io/badge/node-%3E%3D20.19.0-brightgreen.svg)
9
- ![Targets](https://img.shields.io/badge/targets-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20OpenCode-blue.svg)
9
+ ![Targets](https://img.shields.io/badge/targets-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20OpenCode%20%C2%B7%20DSH-blue.svg)
10
10
 
11
11
  ## Keel 是做什么的
12
12
 
@@ -136,9 +136,11 @@ rm -rf "$tmp_dir"
136
136
 
137
137
  ```bash
138
138
  keel --init # 默认 target:claude
139
- keel --init --target codex # 或 opencode
139
+ keel --init --target codex # 或 opencode、dsh
140
140
  ```
141
141
 
142
+ `--target dsh`(DSH,DeepSeek Harness)写入、检查、移除的文件与 `--target codex` 完全相同:DSH 读仓库的 `AGENTS.md` 和 `.agents/skills`,所以没有单独的 DSH 副本,卸载其中一个会让另一个也失去这些文件。DSH 的出厂 profile 没有 session-start hook,所以六项能力都是 `manual`,入口是 `AGENTS.md` 的 bootstrap(「先运行 `keel context`」);`keel --doctor --target dsh` 会报告 PATH 上有没有 `dsh`。
143
+
142
144
  `keel --init` 会跑 OpenSpec 初始化/更新,并写入 Keel 的宿主面。之后每次开始或恢复工作:
143
145
 
144
146
  ```bash
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.223.0 -->
1
+ <!-- keel:start version=5.225.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.
package/bin/keel.js CHANGED
@@ -48,7 +48,9 @@ const PACKAGE_ROOT = path.resolve(__dirname, "..");
48
48
  const PACKAGE_JSON = require(path.join(PACKAGE_ROOT, "package.json"));
49
49
  const INSTALL_SCRIPT = path.join(PACKAGE_ROOT, "scripts", "install_to_repo.py");
50
50
  const DEFAULT_UPDATE_SOURCE = "@christang/keel";
51
- const VALID_TARGETS = new Set(["claude", "codex", "opencode", "both"]);
51
+ // `dsh` is a host, not a surface of its own: DSH reads the files the Codex target
52
+ // writes, so parseArgs turns it into target `codex` and remembers the host (#504).
53
+ const VALID_TARGETS = new Set(["claude", "codex", "opencode", "dsh", "both"]);
52
54
  const KEEL_SKILLS = [
53
55
  "align-expectations",
54
56
  "debug-failure",
@@ -86,8 +88,8 @@ const HELP = `keel ${PACKAGE_JSON.version}
86
88
 
87
89
  Usage:
88
90
  keel context [repo] [--change name] [--task id] [--json] [--clear-handoff]
89
- keel capabilities [repo] [--target claude|codex|opencode] [--json]
90
- keel project --target claude|codex|opencode --event startup|resume|compaction|worktree [--expected-owner owner] [--change name] [--task id] [--json]
91
+ keel capabilities [repo] [--target claude|codex|opencode|dsh] [--json]
92
+ keel project --target claude|codex|opencode|dsh --event startup|resume|compaction|worktree [--expected-owner owner] [--change name] [--task id] [--json]
91
93
  keel gate task-start|task-complete [repo] [--change name] [--task id] [--base git-ref] [--no-guard] [--record] [--keep-evidence M1,M3] [--json]
92
94
  keel gate change-close [repo] [--change name] --action sync|archive [--base git-ref] [--json]
93
95
  keel guard start|status|clear [repo] [--change name] [--task id] [--force] [--json]
@@ -105,19 +107,19 @@ Usage:
105
107
  keel patrol [--issues <file>] [--idle <dur>] [--since-last [--notify]] [--nudge] [--json] [--repo <path>] (the coordinator's patrol; keel patrol task prints its schedule)
106
108
  keel tick [--repo <path>] [--json] (one model-free step for a host scheduler; keel tick task prints the job)
107
109
  keel openspec [args...]
108
- keel --init [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update]
109
- keel --install [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update] [--with-git-hooks]
110
- keel --clear [repo] [--target claude|codex|opencode] [--dry-run]
111
- keel --uninstall [repo] [--target claude|codex|opencode] [--dry-run]
110
+ keel --init [repo] [--target claude|codex|opencode|dsh] [--dry-run] [--force-template-update]
111
+ keel --install [repo] [--target claude|codex|opencode|dsh] [--dry-run] [--force-template-update] [--with-git-hooks]
112
+ keel --clear [repo] [--target claude|codex|opencode|dsh] [--dry-run]
113
+ keel --uninstall [repo] [--target claude|codex|opencode|dsh] [--dry-run]
112
114
  keel --update [--dry-run] [--source npm-package-or-git-spec] [--adopt]
113
- keel --check [repo] [--target claude|codex|opencode]
114
- keel --doctor [repo] [--target claude|codex|opencode]
115
+ keel --check [repo] [--target claude|codex|opencode|dsh]
116
+ keel --doctor [repo] [--target claude|codex|opencode|dsh]
115
117
  keel --version
116
118
  keel --help
117
119
 
118
120
  Defaults:
119
121
  repo defaults to the current working directory.
120
- target defaults to claude.
122
+ target defaults to claude. dsh is DSH (DeepSeek Harness), which reads the files the codex target writes.
121
123
  --update refreshes the global keel CLI and the Claude and Codex plugins it
122
124
  finds installed, not project protocol files.
123
125
  update source defaults to ${DEFAULT_UPDATE_SOURCE}.
@@ -369,7 +371,7 @@ function parseArgs(argv) {
369
371
  if (arg === "--target") {
370
372
  index += 1;
371
373
  if (index >= argv.length) {
372
- fail("--target requires claude, codex, or opencode");
374
+ fail("--target requires claude, codex, opencode, or dsh");
373
375
  }
374
376
  parsed.target = argv[index];
375
377
  continue;
@@ -461,6 +463,10 @@ function parseArgs(argv) {
461
463
  if (!VALID_TARGETS.has(parsed.target)) {
462
464
  fail(`invalid target: ${parsed.target}`);
463
465
  }
466
+ parsed.host = parsed.target;
467
+ if (parsed.target === "dsh") {
468
+ parsed.target = "codex";
469
+ }
464
470
  if (
465
471
  !["context", "gate", "capabilities", "project", "guard", "triage"].includes(
466
472
  parsed.action
@@ -2203,7 +2209,35 @@ function printAdditionalOverlayHealth(repo, selectedTarget) {
2203
2209
  }
2204
2210
  }
2205
2211
 
2206
- function printTargetSurface(repo, target) {
2212
+ // DSH reads the files the Codex target writes, so its surface is checked by the
2213
+ // Codex code above; these lines add what is DSH's own to say (#504). A missing
2214
+ // `dsh` is reported, not failed: a repository can be prepared on another machine.
2215
+ function printDshSurface() {
2216
+ const probe = spawnSync("dsh", ["--version"], { encoding: "utf8", timeout: 5000 });
2217
+ const version = probe.error || probe.status !== 0
2218
+ ? null
2219
+ : String(probe.stdout || "").trim().split("\n")[0];
2220
+ if (version) {
2221
+ printDoctorLine("DSH CLI", "ok", version);
2222
+ } else if (probe.error && probe.error.code !== "ENOENT") {
2223
+ printDoctorLine("DSH CLI", "unreadable", `dsh --version did not answer (${probe.error.code || "error"})`);
2224
+ } else {
2225
+ printDoctorLine("DSH CLI", "not found", "no dsh on PATH; the repository surface does not need it");
2226
+ }
2227
+ printDoctorLine(
2228
+ "DSH hooks",
2229
+ "manual",
2230
+ "DSH's factory profiles carry no session-start, resume or compaction hook "
2231
+ + "(probed with DSH 0.2.2-rc.1); the AGENTS.md bootstrap is the entry"
2232
+ );
2233
+ printDoctorLine(
2234
+ "DSH surface",
2235
+ "ok",
2236
+ "shared with Codex: AGENTS.md and .agents/skills, which DSH reads"
2237
+ );
2238
+ }
2239
+
2240
+ function printTargetSurface(repo, target, host = target) {
2207
2241
  process.stdout.write("\nTarget surface:\n");
2208
2242
 
2209
2243
  const agentsPath = path.join(repo, "AGENTS.md");
@@ -2364,7 +2398,7 @@ function printTargetSurface(repo, target) {
2364
2398
  );
2365
2399
 
2366
2400
  process.stdout.write("\n");
2367
- process.stdout.write(renderCapabilities(probeCapabilities(repo, target)));
2401
+ process.stdout.write(renderCapabilities(probeCapabilities(repo, host)));
2368
2402
  }
2369
2403
 
2370
2404
  function runDoctor(options) {
@@ -2488,7 +2522,8 @@ function runDoctor(options) {
2488
2522
  );
2489
2523
  }
2490
2524
 
2491
- printTargetSurface(repo, options.target);
2525
+ printTargetSurface(repo, options.target, options.host || options.target);
2526
+ if (options.host === "dsh") printDshSurface();
2492
2527
  printAdditionalOverlayHealth(repo, options.target);
2493
2528
  printLensSurface(repo, options.target);
2494
2529
  const authorizationOk = printStandingAuthorizationSurface(repo);
@@ -3200,7 +3235,7 @@ function runAction(options) {
3200
3235
  fail("capabilities does not accept install or update options");
3201
3236
  }
3202
3237
  const repo = path.resolve(options.repo || process.cwd());
3203
- const result = probeCapabilities(repo, options.target);
3238
+ const result = probeCapabilities(repo, options.host || options.target);
3204
3239
  process.stdout.write(
3205
3240
  options.json
3206
3241
  ? `${JSON.stringify(result, null, 2)}\n`
@@ -3219,7 +3254,7 @@ function runAction(options) {
3219
3254
  const repo = path.resolve(options.repo || process.cwd());
3220
3255
  let result;
3221
3256
  try {
3222
- result = projectRuntime(repo, options);
3257
+ result = projectRuntime(repo, { ...options, target: options.host || options.target });
3223
3258
  } catch (error) {
3224
3259
  process.stderr.write(`keel: projection input error: ${error.message}\n`);
3225
3260
  return 1;
@@ -3253,6 +3288,13 @@ function runAction(options) {
3253
3288
  }
3254
3289
 
3255
3290
  if (options.action === "clear" || options.action === "uninstall") {
3291
+ if (options.host === "dsh") {
3292
+ process.stdout.write(
3293
+ "keel: DSH's files are shared with Codex (AGENTS.md and .agents/skills); "
3294
+ + "removing them removes them for Codex too, and Keel cannot tell from "
3295
+ + "the files which host the repository was set up for\n"
3296
+ );
3297
+ }
3256
3298
  const uninstallStatus = runPython(
3257
3299
  INSTALL_SCRIPT,
3258
3300
  installerArgs(options, ["--uninstall"])
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.223.0",
3
+ "version": "5.225.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.223.0",
9
+ "version": "5.225.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.223.0",
5
+ "version": "5.225.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.223.0",
3
+ "version": "5.225.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.223.0",
3
+ "version": "5.225.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",
@@ -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.223.0"
38
+ PACKAGE_VERSION = "5.225.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.223.0"
41
+ PROTOCOL_VERSION = "5.225.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -0,0 +1,254 @@
1
+ """Keel validation: dsh (#504). DSH is a target that shares Codex's repository surface."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import shutil
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ from validation.common import report, run_keel
11
+
12
+
13
+ def dsh_env(home: Path) -> dict[str, str]:
14
+ """An environment with no DSH on it and a Codex home of its own, so the real machine is not read."""
15
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("CLAUDE", "KEEL_"))}
16
+ env["CODEX_HOME"] = str(home / "codex-home")
17
+ env["HOME"] = str(home)
18
+ return env
19
+
20
+
21
+ def validate_dsh_capabilities_scenario() -> int:
22
+ with tempfile.TemporaryDirectory(prefix="keel-dsh-cap-") as raw:
23
+ base = Path(raw).resolve()
24
+ repo = base / "repo"
25
+ repo.mkdir()
26
+ env = dsh_env(base)
27
+ result = run_keel(repo, "capabilities", "--target", "dsh", "--json", env=env)
28
+ if result.returncode != 0:
29
+ report(f"dsh-capabilities: exit {result.returncode}: {(result.stderr or result.stdout).strip()}")
30
+ return 1
31
+ payload = json.loads(result.stdout)
32
+ if payload.get("target") != "dsh":
33
+ report(f"dsh-capabilities: target is {payload.get('target')!r}, not 'dsh'")
34
+ return 1
35
+ capabilities = payload.get("capabilities", {})
36
+ if len(capabilities) != 6:
37
+ report(f"dsh-capabilities: expected six capabilities, got {sorted(capabilities)}")
38
+ return 1
39
+ not_manual = [name for name, c in capabilities.items() if c.get("level") != "manual"]
40
+ if not_manual:
41
+ report(f"dsh-capabilities: not manual: {not_manual}")
42
+ return 1
43
+ for name, capability in capabilities.items():
44
+ evidence = capability.get("evidence", "")
45
+ if "no session-start, resume or compaction hook" not in evidence or "AGENTS.md bootstrap" not in evidence:
46
+ report(f"dsh-capabilities: {name} evidence does not state the probe: {evidence!r}")
47
+ return 1
48
+ plain = run_keel(repo, "capabilities", "--target", "dsh", env=env)
49
+ if "Target capabilities (dsh):" not in plain.stdout:
50
+ report(f"dsh-capabilities: plain rendering lacks its heading: {plain.stdout[:200]!r}")
51
+ return 1
52
+ bad = run_keel(repo, "capabilities", "--target", "nope", env=env)
53
+ if bad.returncode == 0:
54
+ report("dsh-capabilities: an unknown target exited 0")
55
+ return 1
56
+ if "invalid target: nope" not in bad.stderr:
57
+ report(f"dsh-capabilities: an unknown target was refused without naming it: {bad.stderr!r}")
58
+ return 1
59
+ report("dsh-capabilities scenario passed.")
60
+ return 0
61
+
62
+
63
+ def validate_dsh_project_scenario() -> int:
64
+ with tempfile.TemporaryDirectory(prefix="keel-dsh-proj-") as raw:
65
+ base = Path(raw).resolve()
66
+ repo = base / "repo"
67
+ repo.mkdir()
68
+ env = dsh_env(base)
69
+ init = run_keel(repo, "--init", "--target", "codex", env=env)
70
+ if init.returncode != 0:
71
+ report(f"dsh-project: init failed: {(init.stderr or init.stdout).strip()}")
72
+ return 1
73
+ results = {}
74
+ for target in ("dsh", "codex"):
75
+ out = run_keel(repo, "project", "--target", target, "--event", "startup", "--json", env=env)
76
+ if out.returncode != 0:
77
+ report(f"dsh-project: {target} exit {out.returncode}: {(out.stderr or out.stdout).strip()}")
78
+ return 1
79
+ results[target] = json.loads(out.stdout)
80
+ if set(results["dsh"]) != set(results["codex"]):
81
+ report(f"dsh-project: keys differ: {sorted(results['dsh'])} vs {sorted(results['codex'])}")
82
+ return 1
83
+ if results["dsh"].get("target") != "dsh":
84
+ report(f"dsh-project: target is {results['dsh'].get('target')!r}, not 'dsh'")
85
+ return 1
86
+ report("dsh-project scenario passed.")
87
+ return 0
88
+
89
+
90
+ def restricted_path(base: Path, *, dsh_version: str | None) -> dict[str, str]:
91
+ """An environment whose PATH holds node, git and python3, and a `dsh` only when a version is given."""
92
+ bin_dir = base / "bin"
93
+ bin_dir.mkdir(exist_ok=True)
94
+ for tool in ("node", "git", "python3", "python3.11"):
95
+ found = shutil.which(tool)
96
+ if found and not (bin_dir / tool).exists():
97
+ (bin_dir / tool).symlink_to(found)
98
+ if dsh_version is not None:
99
+ script = bin_dir / "dsh"
100
+ script.write_text(f'#!/bin/sh\necho "{dsh_version}"\n', encoding="utf-8")
101
+ script.chmod(0o755)
102
+ env = dsh_env(base)
103
+ env["PATH"] = str(bin_dir)
104
+ return env
105
+
106
+
107
+ def validate_dsh_init_doctor_scenario() -> int:
108
+ with tempfile.TemporaryDirectory(prefix="keel-dsh-init-") as raw:
109
+ base = Path(raw).resolve()
110
+ repo = base / "repo"
111
+ repo.mkdir()
112
+ env = dsh_env(base)
113
+ init = run_keel(repo, "--init", "--target", "dsh", env=env)
114
+ if init.returncode != 0:
115
+ report(f"dsh-init-doctor: init exit {init.returncode}: {(init.stderr or init.stdout).strip()}")
116
+ return 1
117
+ agents = repo / "AGENTS.md"
118
+ if not agents.exists():
119
+ report("dsh-init-doctor: init wrote no AGENTS.md")
120
+ return 1
121
+ if "keel:start" not in agents.read_text(encoding="utf-8"):
122
+ report("dsh-init-doctor: AGENTS.md carries no Keel bootstrap block")
123
+ return 1
124
+ if not (repo / ".agents/skills/openspec-apply-change/SKILL.md").exists():
125
+ report("dsh-init-doctor: init left no OpenSpec skill under .agents/skills")
126
+ return 1
127
+ for forbidden in (".dsh", ".claude"):
128
+ if (repo / forbidden).exists():
129
+ report(f"dsh-init-doctor: init created {forbidden}")
130
+ return 1
131
+ check = run_keel(repo, "--check", "--target", "dsh", env=env)
132
+ if check.returncode != 0:
133
+ report(f"dsh-init-doctor: check exit {check.returncode}: {(check.stderr or check.stdout).strip()}")
134
+ return 1
135
+ doctor = run_keel(repo, "--doctor", "--target", "dsh", env=env)
136
+ if doctor.returncode != 0:
137
+ report(f"dsh-init-doctor: doctor exit {doctor.returncode}: {(doctor.stderr or doctor.stdout).strip()}")
138
+ return 1
139
+ for expected in ("bootstrap: ok", "Target capabilities (dsh):", "DSH hooks: manual", "DSH surface: ok"):
140
+ if expected not in doctor.stdout:
141
+ report(f"dsh-init-doctor: doctor output lacks {expected!r}")
142
+ return 1
143
+ report("dsh-init-doctor scenario passed.")
144
+ return 0
145
+
146
+
147
+ def validate_dsh_binary_scenario() -> int:
148
+ with tempfile.TemporaryDirectory(prefix="keel-dsh-bin-") as raw:
149
+ base = Path(raw).resolve()
150
+ repo = base / "repo"
151
+ repo.mkdir()
152
+ (base / "absent").mkdir()
153
+ absent = restricted_path(base / "absent", dsh_version=None)
154
+ init = run_keel(repo, "--init", "--target", "dsh", env=absent)
155
+ if init.returncode != 0:
156
+ report(f"dsh-binary: init exit {init.returncode}: {(init.stderr or init.stdout).strip()}")
157
+ return 1
158
+ missing = run_keel(repo, "--doctor", "--target", "dsh", env=absent)
159
+ if missing.returncode != 0:
160
+ report(f"dsh-binary: doctor without dsh exit {missing.returncode}: {(missing.stderr or missing.stdout).strip()}")
161
+ return 1
162
+ if "DSH CLI: not found" not in missing.stdout:
163
+ report("dsh-binary: doctor without dsh did not say `DSH CLI: not found`")
164
+ return 1
165
+ (base / "present").mkdir()
166
+ present = restricted_path(base / "present", dsh_version="9.9.9")
167
+ found = run_keel(repo, "--doctor", "--target", "dsh", env=present)
168
+ if found.returncode != 0:
169
+ report(f"dsh-binary: doctor with dsh exit {found.returncode}: {(found.stderr or found.stdout).strip()}")
170
+ return 1
171
+ line = next((l for l in found.stdout.splitlines() if l.startswith("DSH CLI:")), "")
172
+ if "ok" not in line:
173
+ report(f"dsh-binary: doctor with dsh did not report ok: {line!r}")
174
+ return 1
175
+ if "9.9.9" not in line:
176
+ report(f"dsh-binary: doctor with dsh did not carry the version: {line!r}")
177
+ return 1
178
+ report("dsh-binary scenario passed.")
179
+ return 0
180
+
181
+
182
+ def validate_dsh_uninstall_shared_scenario() -> int:
183
+ with tempfile.TemporaryDirectory(prefix="keel-dsh-un-") as raw:
184
+ base = Path(raw).resolve()
185
+ repo = base / "repo"
186
+ repo.mkdir()
187
+ env = dsh_env(base)
188
+ for target in ("claude", "dsh"):
189
+ init = run_keel(repo, "--init", "--target", target, env=env)
190
+ if init.returncode != 0:
191
+ report(f"dsh-uninstall-shared: init {target} exit {init.returncode}: {(init.stderr or init.stdout).strip()}")
192
+ return 1
193
+ dsh_plan = run_keel(repo, "--uninstall", "--target", "dsh", "--dry-run", env=env)
194
+ codex_plan = run_keel(repo, "--uninstall", "--target", "codex", "--dry-run", env=env)
195
+ if dsh_plan.returncode != 0 or codex_plan.returncode != 0:
196
+ report(f"dsh-uninstall-shared: dry-run exits {dsh_plan.returncode}/{codex_plan.returncode}")
197
+ return 1
198
+ if "shared with Codex" not in dsh_plan.stdout + dsh_plan.stderr:
199
+ report("dsh-uninstall-shared: the DSH plan does not say the files are shared with Codex")
200
+ return 1
201
+ kept = [l for l in dsh_plan.stdout.splitlines() if "shared with Codex" not in l]
202
+ if kept != codex_plan.stdout.splitlines():
203
+ report("dsh-uninstall-shared: the DSH plan lists removals the Codex plan does not (or the reverse)")
204
+ return 1
205
+ real = run_keel(repo, "--uninstall", "--target", "dsh", env=env)
206
+ if real.returncode != 0:
207
+ report(f"dsh-uninstall-shared: uninstall exit {real.returncode}: {(real.stderr or real.stdout).strip()}")
208
+ return 1
209
+ marker = "keel:openspec-surface-overlay"
210
+ shared = (repo / ".agents/skills/openspec-apply-change/SKILL.md").read_text(encoding="utf-8")
211
+ if marker in shared:
212
+ report("dsh-uninstall-shared: the Keel overlay is still in .agents/skills after the uninstall")
213
+ return 1
214
+ claude = (repo / ".claude/skills/openspec-apply-change/SKILL.md").read_text(encoding="utf-8")
215
+ if marker not in claude:
216
+ report("dsh-uninstall-shared: the Claude overlay was removed with DSH's")
217
+ return 1
218
+ report("dsh-uninstall-shared scenario passed.")
219
+ return 0
220
+
221
+
222
+ def validate_dsh_docs_scenario() -> int:
223
+ from validation.common import ROOT
224
+
225
+ with tempfile.TemporaryDirectory(prefix="keel-dsh-docs-") as raw:
226
+ base = Path(raw).resolve()
227
+ env = dsh_env(base)
228
+ helped = run_keel(base, "--help", env=env)
229
+ target_lines = [l for l in helped.stdout.splitlines() if "--target claude|codex|opencode" in l or "--target claude|codex|opencode|dsh" in l]
230
+ if not target_lines:
231
+ report("dsh-docs: --help lists no target line at all")
232
+ return 1
233
+ without = [l.strip() for l in target_lines if "dsh" not in l]
234
+ if without:
235
+ report(f"dsh-docs: --help target lines without dsh: {without}")
236
+ return 1
237
+ bare = run_keel(base, "--init", "--target", env=env)
238
+ if bare.returncode == 0:
239
+ report("dsh-docs: `--init --target` with no value exited 0")
240
+ return 1
241
+ if "dsh" not in bare.stderr:
242
+ report(f"dsh-docs: the missing-value message does not name dsh: {bare.stderr!r}")
243
+ return 1
244
+ for name in ("README.md", "README.zh-CN.md"):
245
+ text = (ROOT / name).read_text(encoding="utf-8")
246
+ if "--target dsh" not in text:
247
+ report(f"dsh-docs: {name} never mentions `--target dsh`")
248
+ return 1
249
+ head = "\n".join(text.splitlines()[:12])
250
+ if "DSH" not in head:
251
+ report(f"dsh-docs: {name} tagline and badge do not name DSH")
252
+ return 1
253
+ report("dsh-docs scenario passed.")
254
+ return 0
@@ -8,6 +8,7 @@ from validation import shift
8
8
  from validation import docs
9
9
  from validation import selfcheck
10
10
  from validation import export
11
+ from validation import dsh
11
12
  from validation import feedback
12
13
 
13
14
 
@@ -429,6 +430,9 @@ SCENARIOS: tuple = (
429
430
  ("shift-resume-removes-old-sessions", shift.validate_shift_resume_removes_old_sessions_scenario),
430
431
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
431
432
  ("shift-cli-keeps-worktree-in-use", shift.validate_shift_cli_keeps_worktree_in_use_scenario),
433
+ ("shift-replaced-refuses", shift.validate_shift_replaced_refuses_scenario),
434
+ ("shift-unreplaced-not-refused", shift.validate_shift_unreplaced_not_refused_scenario),
435
+ ("shift-replaced-told", shift.validate_shift_replaced_told_scenario),
432
436
  ("shift-cli-names-failed-removal", shift.validate_shift_cli_names_failed_removal_scenario),
433
437
  ("shift-ready-says-session-stays", shift.validate_shift_ready_says_session_stays_scenario),
434
438
  ("shift-ready-promises-removal-when-removable", shift.validate_shift_ready_promises_removal_when_removable_scenario),
@@ -542,6 +546,12 @@ SCENARIOS: tuple = (
542
546
  ("feedback-create", feedback.validate_feedback_create_scenario),
543
547
  ("feedback-gh-missing", feedback.validate_feedback_gh_missing_scenario),
544
548
  ("feedback-command-surface", feedback.validate_feedback_command_surface_scenario),
549
+ ("dsh-capabilities", dsh.validate_dsh_capabilities_scenario),
550
+ ("dsh-project", dsh.validate_dsh_project_scenario),
551
+ ("dsh-init-doctor", dsh.validate_dsh_init_doctor_scenario),
552
+ ("dsh-binary", dsh.validate_dsh_binary_scenario),
553
+ ("dsh-uninstall-shared", dsh.validate_dsh_uninstall_shared_scenario),
554
+ ("dsh-docs", dsh.validate_dsh_docs_scenario),
545
555
  ("push-protected-guard", guard.validate_push_protected_guard_scenario),
546
556
  ("authorize-role-scoped", guard.validate_authorize_role_scoped_scenario),
547
557
  ("touch-guard-record-layer", guard.validate_touch_guard_record_layer_scenario),
@@ -4001,12 +4001,14 @@ def validate_shift_cli_removes_after_exit_scenario() -> int:
4001
4001
 
4002
4002
 
4003
4003
  def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None, ready_out: list | None = None,
4004
- config_text: str | None = None, **fake_env: str):
4004
+ config_text: str | None = None, probe=None, **fake_env: str):
4005
4005
  """A delivered hand-over of `5b14fbae` from verify's worktree under the contract fake (#492).
4006
4006
 
4007
4007
  Returns the `rm` calls the fake logged and `keel shift status` from rtl.
4008
4008
  The row's `cwd` and the host's recorded `worktreePath` are the inputs.
4009
4009
  `ready_out`, when given, receives what `shift ready --wake` printed as text and then as `--json` (#506).
4010
+ `probe`, when given, is called as `probe(verify, env, OLD)` once the hand-over is delivered and the old
4011
+ session is still listed, to run commands as the replaced session (#506).
4010
4012
  """
4011
4013
  OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
4012
4014
  rtl, verify, env, _ = shift_scratch(base)
@@ -4039,6 +4041,8 @@ def handover_old_session(base: Path, row_cwd: Path, worktree_path: Path | None,
4039
4041
  as_json = run_keel(verify, "shift", "ready", "--wake", "--json", "next: rerun R032", env=cli_env)
4040
4042
  ready_out.extend([readied.stdout, as_json.stdout])
4041
4043
  run_keel(verify, "tick", "--repo", str(rtl), env=env)
4044
+ if probe is not None:
4045
+ probe(verify, env, OLD)
4042
4046
  removals = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
4043
4047
  return removals, run_keel(rtl, "shift", "status", env=env).stdout, verify
4044
4048
  finally:
@@ -4789,6 +4793,9 @@ def validate_shift_cli_self_shift_scenario() -> int:
4789
4793
  # The tick and the waiter start one session: a fresh lock holds the tick off.
4790
4794
  calls.write_text("")
4791
4795
  agents_row("idle", "done")
4796
+ # In life the next hand-over comes from the new session; this fixture reuses one id, so the
4797
+ # delivered record that names it as replaced is cleared first (#506).
4798
+ (queue / "verify.json").unlink(missing_ok=True)
4792
4799
  run_keel(verify, "shift", "ready", "--wake", "next: rerun R014", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
4793
4800
  lock = queue / "verify.lock"
4794
4801
  write_text(lock, "held")
@@ -4810,6 +4817,7 @@ def validate_shift_cli_self_shift_scenario() -> int:
4810
4817
  calls.write_text("")
4811
4818
  agents_row("idle", "done")
4812
4819
  write_text(fail, "x")
4820
+ (queue / "verify.json").unlink(missing_ok=True)
4813
4821
  run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
4814
4822
  tick()
4815
4823
  text = status_text()
@@ -4905,6 +4913,8 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
4905
4913
  live = {"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8], "status": "idle", "state": "working",
4906
4914
  "cwd": bound["verify"], "startedAt": 1792490000000}
4907
4915
  agents.write_text(json.dumps([*olds, live]))
4916
+ # One id plays every old shift here; the delivered record of the last one would refuse the next (#506).
4917
+ (mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue" / "verify.json").unlink(missing_ok=True)
4908
4918
  readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R020", env=cli_env)
4909
4919
  if readied.returncode != 0:
4910
4920
  raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
@@ -6652,3 +6662,127 @@ def validate_branches_pointed_out_scenario() -> int:
6652
6662
  return 1
6653
6663
  report(f"{label.rstrip(':')} scenario passed.")
6654
6664
  return 0
6665
+
6666
+
6667
+ def replaced_session_probe(results: dict):
6668
+ """A `probe` for `handover_old_session` that runs the gates as the replaced session (#506)."""
6669
+ def probe(verify: Path, env: dict, old: str) -> None:
6670
+ queue = mailbox_common_dir(verify) / "keel-chat" / "shift" / "queue" / "verify.json"
6671
+ results["entry"] = json.loads(queue.read_text())
6672
+ results["queue_before"] = queue.read_bytes()
6673
+ as_old = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": old}
6674
+ as_other = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "0f0f0f0f-aaaa-bbbb-cccc-111122223333"}
6675
+ as_none = {k: v for k, v in env.items() if k != "CLAUDE_CODE_SESSION_ID"}
6676
+ results["start_old"] = run_keel(verify, "gate", "task-start", env=as_old)
6677
+ results["ready_old"] = run_keel(verify, "shift", "ready", "--wake", "again", env=as_old)
6678
+ results["complete_old"] = run_keel(verify, "gate", "task-complete", env=as_old)
6679
+ results["start_other"] = run_keel(verify, "gate", "task-start", env=as_other)
6680
+ results["start_none"] = run_keel(verify, "gate", "task-start", env=as_none)
6681
+ results["guard_exists"] = (verify / "keel" / "guard.json").exists()
6682
+ results["queue_after"] = queue.read_bytes()
6683
+ return probe
6684
+
6685
+
6686
+ def validate_shift_replaced_refuses_scenario() -> int:
6687
+ """Issue #506: a session a hand-over replaced cannot start a task or hand over again."""
6688
+ label = "shift-replaced-refuses:"
6689
+ results: dict = {}
6690
+ with tempfile.TemporaryDirectory(prefix="keel-shift-506b-") as raw:
6691
+ try:
6692
+ handover_old_session(Path(raw), Path("rtl"), Path("verify"), probe=replaced_session_probe(results))
6693
+ except RuntimeError as error:
6694
+ report(f"{label} {error}")
6695
+ return 1
6696
+ entry = results.get("entry", {})
6697
+ if entry.get("state") != "delivered" or not entry.get("new_session"):
6698
+ report(f"{label} the fixture did not deliver a hand-over: {entry!r}")
6699
+ return 1
6700
+ start = results["start_old"].stdout
6701
+ for needle in ("Status: fail", "Problem:", "handed over", "verify", entry["new_session"]):
6702
+ if needle not in start:
6703
+ report(f"{label} task-start as the replaced session lacks {needle!r}: {start!r}")
6704
+ return 1
6705
+ ready = results["ready_old"]
6706
+ if ready.returncode == 0:
6707
+ report(f"{label} shift ready as the replaced session exited 0: {ready.stdout!r}")
6708
+ return 1
6709
+ for needle in ("verify", entry["new_session"]):
6710
+ if needle not in ready.stderr + ready.stdout:
6711
+ report(f"{label} shift ready does not name {needle!r}: {ready.stderr!r}")
6712
+ return 1
6713
+ if results["guard_exists"]:
6714
+ report(f"{label} task-start wrote a guard manifest for the replaced session.")
6715
+ return 1
6716
+ if results["queue_after"] != results["queue_before"]:
6717
+ report(f"{label} the hand-over entry changed after the refused commands.")
6718
+ return 1
6719
+ report("shift-replaced-refuses scenario passed.")
6720
+ return 0
6721
+
6722
+
6723
+ def validate_shift_unreplaced_not_refused_scenario() -> int:
6724
+ """Issue #506: another session, no session, and task-complete are not refused for it."""
6725
+ label = "shift-unreplaced-not-refused:"
6726
+ results: dict = {}
6727
+ with tempfile.TemporaryDirectory(prefix="keel-shift-506c-") as raw:
6728
+ try:
6729
+ handover_old_session(Path(raw), Path("rtl"), Path("verify"), probe=replaced_session_probe(results))
6730
+ except RuntimeError as error:
6731
+ report(f"{label} {error}")
6732
+ return 1
6733
+ new_session = results["entry"]["new_session"]
6734
+ for what in ("start_other", "start_none", "complete_old"):
6735
+ shown = results[what].stdout + results[what].stderr
6736
+ if "handed over" in shown:
6737
+ report(f"{label} {what} carries the replaced-session wording: {shown!r}")
6738
+ return 1
6739
+ if new_session in shown:
6740
+ report(f"{label} {what} names the new session: {shown!r}")
6741
+ return 1
6742
+ report("shift-unreplaced-not-refused scenario passed.")
6743
+ return 0
6744
+
6745
+
6746
+ def validate_shift_replaced_told_scenario() -> int:
6747
+ """Issue #506: the replaced session is told first, when it starts and when it is prompted."""
6748
+ label = "shift-replaced-told:"
6749
+ seen: dict = {}
6750
+
6751
+ def probe(verify: Path, env: dict, old: str) -> None:
6752
+ queue = mailbox_common_dir(verify) / "keel-chat" / "shift" / "queue" / "verify.json"
6753
+ seen["new_session"] = json.loads(queue.read_text())["new_session"]
6754
+ for event, extra in (("session-start", {"source": "resume"}), ("user-prompt-submit", {"prompt": "are you still there"})):
6755
+ for who, session_id in (("old", old), ("other", "0f0f0f0f-aaaa-bbbb-cccc-111122223333")):
6756
+ payload = {"session_id": session_id, "cwd": str(verify), "hook_event_name": event, **extra}
6757
+ ran = subprocess.run(
6758
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
6759
+ cwd=verify, env=env, input=json.dumps(payload), text=True, capture_output=True, check=False,
6760
+ )
6761
+ try:
6762
+ context = json.loads(ran.stdout or "{}").get("hookSpecificOutput", {}).get("additionalContext", "")
6763
+ except ValueError:
6764
+ context = ran.stdout
6765
+ seen[(event, who)] = (ran.returncode, context)
6766
+
6767
+ with tempfile.TemporaryDirectory(prefix="keel-shift-506d-") as raw:
6768
+ try:
6769
+ handover_old_session(Path(raw), Path("rtl"), Path("verify"), probe=probe)
6770
+ except RuntimeError as error:
6771
+ report(f"{label} {error}")
6772
+ return 1
6773
+ for event in ("session-start", "user-prompt-submit"):
6774
+ code, context = seen[(event, "old")]
6775
+ if code != 0:
6776
+ report(f"{label} the {event} hook exited {code} for the old session.")
6777
+ return 1
6778
+ first = context.splitlines()[0] if context else ""
6779
+ for needle in ("handed over", "verify", seen["new_session"], "Tell the user"):
6780
+ if needle not in first:
6781
+ report(f"{label} the {event} context for the old session does not start with {needle!r}: {context!r}")
6782
+ return 1
6783
+ _, other = seen[(event, "other")]
6784
+ if "handed over" in other:
6785
+ report(f"{label} the {event} context for another session carries the notice: {other!r}")
6786
+ return 1
6787
+ report("shift-replaced-told scenario passed.")
6788
+ return 0
@@ -20,7 +20,7 @@ const CAPABILITY_COMMANDS = {
20
20
  "keel project --target <target> --event worktree --expected-owner <owner> --json",
21
21
  };
22
22
 
23
- const SUPPORTED_TARGETS = new Set(["claude", "codex", "opencode"]);
23
+ const SUPPORTED_TARGETS = new Set(["claude", "codex", "opencode", "dsh"]);
24
24
 
25
25
  function codexHome() {
26
26
  const configured = (process.env.CODEX_HOME || "").trim();
@@ -49,6 +49,9 @@ const PLUGIN_RUNTIME_OBSERVATION =
49
49
  + "native runtime evidence and remain advisory or manual until probed";
50
50
 
51
51
  function pluginObservation(repo, target) {
52
+ if (target === "dsh") {
53
+ return "DSH takes no Keel plugin; it reads the repository's AGENTS.md and .agents/skills";
54
+ }
52
55
  if (target === "opencode") {
53
56
  return "OpenCode has no v4 native plugin surface; manual CLI compatibility only";
54
57
  }
@@ -97,6 +100,13 @@ function targetObservation(repo, target) {
97
100
  } else {
98
101
  observations.push("Claude hook activation evidence is incomplete");
99
102
  }
103
+ } else if (target === "dsh") {
104
+ observations.push(
105
+ "DSH reads AGENTS.md and .agents/skills, and its factory profiles carry "
106
+ + "no session-start, resume or compaction hook (probed with DSH "
107
+ + "0.2.2-rc.1, 2026-11-08), so the AGENTS.md bootstrap is the entry; "
108
+ + "installation, trust and behavior are not verifiable from Keel"
109
+ );
100
110
  } else if (target === "codex") {
101
111
  const hooks = path.join(codexHome(), "hooks.json");
102
112
  observations.push(
@@ -725,6 +725,18 @@ function hook(event, input, { mail = false } = {}) {
725
725
  return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
726
726
  }
727
727
  if (!where || !role) return languageLine ? promptOutput(languageLine) : { code: 0 };
728
+ // A session a hand-over replaced is told first, whatever else is announced
729
+ // (#506 D3). The record is all that is read; a failure says nothing.
730
+ let replacedLine = null;
731
+ if (event === "session-start" || event === "user-prompt-submit") {
732
+ try {
733
+ const shift = require("../shift");
734
+ const info = shift.replacedBy(where, payload.session_id || process.env.CLAUDE_CODE_SESSION_ID);
735
+ replacedLine = info ? shift.replacedNotice(info) : null;
736
+ } catch {
737
+ replacedLine = null;
738
+ }
739
+ }
728
740
  const file = sessionFile(where, payload);
729
741
  const session = file && fs.existsSync(file) ? store.readJsonFile(file) : null;
730
742
  if (event === "session-end" && file) fs.rmSync(file, { force: true });
@@ -746,12 +758,12 @@ function hook(event, input, { mail = false } = {}) {
746
758
  const output = {
747
759
  hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role), ensureWorktreeSignal(where)] },
748
760
  };
749
- const context = [bridgeLine(where), text].filter(Boolean).join("\n");
761
+ const context = [replacedLine, bridgeLine(where), text].filter(Boolean).join("\n");
750
762
  if (context) output.hookSpecificOutput.additionalContext = context;
751
763
  return { code: 0, stdout: `${JSON.stringify(output)}\n` };
752
764
  }
753
765
  if (event === "user-prompt-submit") {
754
- const context = [languageLine, text].filter(Boolean).join("\n");
766
+ const context = [replacedLine, languageLine, text].filter(Boolean).join("\n");
755
767
  return context ? promptOutput(context) : { code: 0 };
756
768
  }
757
769
  // file-changed
package/src/core/gates.js CHANGED
@@ -2377,7 +2377,14 @@ function runGate(repo, stage, options) {
2377
2377
  if (!GATE_STAGES.has(stage)) {
2378
2378
  throw new GateInputError(`unsupported gate stage: ${stage}`);
2379
2379
  }
2380
- if (stage === "task-start") return taskStart(repo, options);
2380
+ if (stage === "task-start") {
2381
+ // A session a hand-over replaced begins no new work (#506 D4).
2382
+ const replaced = require("./shift").replacedNoticeHere(repo);
2383
+ if (replaced) {
2384
+ return gateResult("task-start", "fail", options.change || "(none)", [], [problem("session-replaced", replaced)]);
2385
+ }
2386
+ return taskStart(repo, options);
2387
+ }
2381
2388
  if (stage === "task-complete") return taskComplete(repo, options);
2382
2389
  return changeClose(repo, options);
2383
2390
  }
@@ -81,7 +81,7 @@ function projectRuntime(repo, options) {
81
81
  if (!EVENTS.has(event)) {
82
82
  throw new Error(`unsupported projection event: ${event || "<missing>"}`);
83
83
  }
84
- if (!["claude", "codex", "opencode"].includes(options.target)) {
84
+ if (!["claude", "codex", "opencode", "dsh"].includes(options.target)) {
85
85
  throw new Error(`unsupported target: ${options.target}`);
86
86
  }
87
87
 
package/src/core/shift.js CHANGED
@@ -458,6 +458,8 @@ function awaitClear(pid, timeoutMs) {
458
458
  }
459
459
 
460
460
  function ready(where, options) {
461
+ const replaced = replacedNoticeHere(where.worktree);
462
+ if (replaced) throw new ShiftError(replaced);
461
463
  const role = readyRole(where, options);
462
464
  if (options.wake && !role) {
463
465
  throw new ShiftError("--wake wakes a chat role, and this worktree has none: bind one with `keel chat role --set <name>`, or name it with --role.");
@@ -536,6 +538,34 @@ function handOffs(where) {
536
538
  .map((name) => store.readJsonFile(path.join(shiftDir(where), "queue", name))).filter((entry) => entry && entry.role);
537
539
  }
538
540
 
541
+ // The hand-over that replaced this session, or null (#506 D1). A session is
542
+ // replaced when the role's latest hand-over is `delivered`, names it as the old
543
+ // session and names a new one. Only the record is read: no process, no host.
544
+ function replacedBy(where, sessionId) {
545
+ if (!sessionId) return null;
546
+ const entry = handOffs(where).find((item) => item.state === "delivered" && item.new_session
547
+ && item.session === sessionId && !String(sessionId).startsWith(item.new_session));
548
+ return entry ? { role: entry.role, newSession: entry.new_session, deliveredAt: entry.delivered_at || null } : null;
549
+ }
550
+
551
+ // One sentence for every surface that tells or refuses a replaced session (D2).
552
+ function replacedNotice(info) {
553
+ return `This session was handed over for role ${info.role}${info.deliveredAt ? ` at ${info.deliveredAt}` : ""} to session ${info.newSession}: `
554
+ + "it no longer owns the role and shares its worktree with the new shift. Tell the user before doing anything here; "
555
+ + "`keel gate task-start` and `keel shift ready` refuse this session, and to use it again the user must end the new shift first.";
556
+ }
557
+
558
+ // The notice for the session running this command, or null.
559
+ function replacedNoticeHere(repo, sessionId = process.env.CLAUDE_CODE_SESSION_ID) {
560
+ try {
561
+ const where = store.locate(repo);
562
+ const info = where ? replacedBy(where, sessionId) : null;
563
+ return info ? replacedNotice(info) : null;
564
+ } catch {
565
+ return null;
566
+ }
567
+ }
568
+
539
569
  const SHIFT_START_TEXT = (role) => `${role}: your new shift starts now. Run keel context, then keel shift resume.`;
540
570
 
541
571
  // The old session has finished when it is gone, stopped (no status), or idle.
@@ -1761,4 +1791,5 @@ function waitingFor(repo) {
1761
1791
  }
1762
1792
 
1763
1793
  module.exports = {
1764
- desktopProcess, foundTranscripts, handOver, handOffRisks, check, describe, runShift, shiftStatus: status, waitingFor };
1794
+ desktopProcess, foundTranscripts, handOver, handOffRisks, check, describe, runShift, shiftStatus: status, waitingFor,
1795
+ replacedBy, replacedNotice, replacedNoticeHere };