@christang/keel 5.180.0 → 5.182.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.180.0",
3
+ "version": "5.182.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
@@ -39,7 +39,7 @@ Keel leans on native capabilities rather than reinventing them. The spec workflo
39
39
  OpenSpec. The execution skills, the SessionStart continuity hook, and the write-guard hook
40
40
  ship as an ordinary Claude Code / Codex plugin. Besides running OpenSpec's own init,
41
41
  `keel --init` writes a small host surface into your repo: an `AGENTS.md` bootstrap block, the
42
- OpenSpec schema, the `/opsx:*` command overlay, and on Claude the plugin's auto-update entry in
42
+ OpenSpec schema, the overlay on OpenSpec's workflow skills, and on Claude the plugin's auto-update entry in
43
43
  `.claude/settings.json`.
44
44
 
45
45
  ## Requirements
@@ -180,13 +180,14 @@ A subagent is the model's choice and is treated as the main agent is: the gates,
180
180
  no brief, activation, or second agent's rerun before one acts, and does not nudge the
181
181
  model toward or away from using one (#414).
182
182
 
183
- Do the spec work through OpenSpec's commands (`/opsx:propose`, `/opsx:apply`, `/opsx:sync`,
184
- `/opsx:archive`). Keel's gates run at the task boundaries. The whole loop:
183
+ Do the spec work through OpenSpec's workflow skills (`openspec-propose`, `openspec-apply-change`,
184
+ `openspec-sync-specs`, `openspec-archive-change`); Keel generates them as skills only, with no OpenSpec
185
+ slash commands (#406). Keel's gates run at the task boundaries. The whole loop:
185
186
 
186
187
  ```
187
- keel --init → keel context → /opsx:apply (tasks in order)
188
+ keel --init → keel context → openspec-apply-change (tasks in order)
188
189
  → task-start (+ write guard) → implement & verify
189
- → task-complete → /opsx:sync · /opsx:archive
190
+ → task-complete → openspec-sync-specs · openspec-archive-change
190
191
  ```
191
192
 
192
193
  On the Claude target, the session-start hook also shows that state to **you**, not only to the
@@ -521,7 +522,7 @@ command at the right moment. Three things make that happen.
521
522
  session with `keel context`, route the work Full or Lite, pass the gates at task boundaries,
522
523
  and stay inside the task's declared write scope. That is how the agent knows *when* to run
523
524
  what.
524
- - **The skills.** The `keel-*` execution skills and the `/opsx:*` command overlays walk the
525
+ - **The skills.** The `keel-*` execution skills and the overlays on OpenSpec's workflow skills walk the
525
526
  agent through align → apply → review → complete, invoking the gates at each step. A new or
526
527
  materially expanded skill is researched from an authoritative source with its provenance and
527
528
  license recorded, its description is tested with realistic should-trigger and should-not-trigger
package/README.zh-CN.md CHANGED
@@ -31,7 +31,7 @@ Keel 加的东西:
31
31
  Keel 尽量借力原生能力,而不是重造。spec 工作流就是原生 OpenSpec;执行技能、SessionStart 连续性
32
32
  hook 和写入守卫 hook 都以一个普通的 Claude Code / Codex 插件分发。除了运行 OpenSpec 自己的 init,
33
33
  `keel --init` 还往你的 repo 里写一小块宿主面:`AGENTS.md` bootstrap 块、OpenSpec schema、
34
- `/opsx:*` 命令 overlay,以及在 Claude 上写入 `.claude/settings.json` 的插件自动更新条目。
34
+ OpenSpec 工作流 skill 上的 overlay,以及在 Claude 上写入 `.claude/settings.json` 的插件自动更新条目。
35
35
 
36
36
  ## 环境要求
37
37
 
@@ -154,13 +154,13 @@ overlay 状态,所以 Claude 一侧正常不会掩盖 Codex overlay 的缺失
154
154
  和证据规则适用于执行该步骤的任何一方。Keel 在 subagent 动手前不要求 brief、额外激活或另一个
155
155
  agent 复跑,也不引导模型去用或不用它(#414)。
156
156
 
157
- spec 相关的活走 OpenSpec 的命令(`/opsx:propose`、`/opsx:apply`、`/opsx:sync`、`/opsx:archive`),
158
- Keel 的门禁在任务边界处运行。整个回路:
157
+ spec 相关的活走 OpenSpec 的工作流 skill(`openspec-propose`、`openspec-apply-change`、`openspec-sync-specs`、
158
+ `openspec-archive-change`);Keel 只生成 skill,不生成 OpenSpec 斜杠命令(#406)。Keel 的门禁在任务边界处运行。整个回路:
159
159
 
160
160
  ```
161
- keel --init → keel context → /opsx:apply(按顺序做 task)
161
+ keel --init → keel context → openspec-apply-change(按顺序做 task)
162
162
  → task-start(+ 写入守卫) → 实现并验证
163
- → task-complete → /opsx:sync · /opsx:archive
163
+ → task-complete → openspec-sync-specs · openspec-archive-change
164
164
  ```
165
165
 
166
166
  在 Claude target 上,session-start hook 还会把这个状态展示给**你**,而不只是给 agent——在你输入任何内容
@@ -422,7 +422,7 @@ executor_tier: high
422
422
  - **协议**:`keel --init` 会往你 repo 的 `AGENTS.md` 写一段 bootstrap 块(在 Claude 上由
423
423
  `CLAUDE.md` 引入)。它写明 agent 要遵守的规则:每次会话先跑 `keel context`、把工作路由到 Full 或 Lite、
424
424
  在任务边界处过门禁、只在任务声明的写入范围内改文件。这就是 agent 知道**何时**运行什么的来源。
425
- - **技能**:`keel-*` 执行技能和 `/opsx:*` 命令 overlay 带着 agent 走「对齐 → apply → review →
425
+ - **技能**:`keel-*` 执行技能和 OpenSpec 工作流 skill 上的 overlay 带着 agent 走「对齐 → apply → review →
426
426
  完成」,每一步调用门禁。新增或实质扩展的技能,要从 authoritative source 研究并记录出处与许可证,
427
427
  用真实的 should-trigger 与 should-not-trigger 用例检验其 description,并至少通过一个 real task。
428
428
  `src/skills/<name>/SKILL.md` 是唯一可移植权威,target metadata 只是附加,发现与激活由 target-native 运行时负责。
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.180.0 -->
1
+ <!-- keel:start version=5.182.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.
@@ -137,7 +137,7 @@ artifacts:
137
137
  final assertions, immediate task-stop conditions, and
138
138
  evidence. The task must agree with design.md's Coupled Iteration Contract.
139
139
 
140
- `/opsx:apply` works through the unchecked tasks of this file in order. Any
140
+ `openspec-apply-change` works through the unchecked tasks of this file in order. Any
141
141
  repository file may be read needed for the selected task; Read lists required
142
142
  starting context, not a read allowlist. The Slice Start Gate requires each
143
143
  selected current slice or contiguous slice group to name source
@@ -183,7 +183,7 @@ apply:
183
183
  - tasks
184
184
  tracks: tasks.md
185
185
  instruction: |
186
- Use `/opsx:apply` as the implementation entry for Keel-managed work.
186
+ Use the `openspec-apply-change` skill as the implementation entry for Keel-managed work.
187
187
 
188
188
  Apply workflow:
189
189
  1. Read the current change's proposal.md, specs, design.md when present, and tasks.md.
@@ -200,5 +200,5 @@ apply:
200
200
  12. Modify only files listed under Touch. If modifying any other file is required, stop and report an Out-of-scope Need with file or area, why needed, consequence if unchanged, minimal proposed change, and evidence.
201
201
  13. Do not commit or push unless the selected task, a human instruction, or a standing authorization in `keel/config.yaml` allows it.
202
202
  14. After each iteration, compare Changed Files and command evidence with the selected task contract before checking tasks complete.
203
- 15. Run `keel-review-checklist` only at completion gates: after a complete task group, before `/opsx:sync openspec/changes/<change>/tasks.md` or `/opsx:archive openspec/changes/<change>/tasks.md`, before meaningful handoff, or when implementation reports risks, follow-ups, or out-of-scope need. No hook gates completion; running the gates is the agent's own step.
203
+ 15. Run `keel-review-checklist` only at completion gates: after a complete task group, before `openspec-sync-specs` or `openspec-archive-change` for `openspec/changes/<change>/tasks.md`, before meaningful handoff, or when implementation reports risks, follow-ups, or out-of-scope need. No hook gates completion; running the gates is the agent's own step.
204
204
  16. Before archive or handoff, unresolved follow-ups must be owned by current OpenSpec tasks, a new OpenSpec change, archive evidence, or an explicit discard reason.
package/bin/keel.js CHANGED
@@ -66,7 +66,7 @@ const OPENSPEC_SKILLS = [
66
66
  // `sync` is here because `AGENTS.md` gates it exactly as it gates archive —
67
67
  // `keel gate change-close --action sync|archive` plus `keel-review-checklist`.
68
68
  // Archive's surface said so and sync's said nothing, so an agent invoking
69
- // `/opsx:sync` read generic upstream instructions with no mention of the gate
69
+ // the sync workflow read generic upstream instructions with no mention of the gate
70
70
  // that decides whether the sync may complete. `explore` is deliberately absent:
71
71
  // it reads and reports, reaches no gate, and changes no state, so an overlay
72
72
  // there would read as governance where there is none.
@@ -666,6 +666,7 @@ function runCommand(command, args, options = {}) {
666
666
 
667
667
  const result = spawnSync(command, args, {
668
668
  cwd: options.cwd || process.cwd(),
669
+ env: options.env || process.env,
669
670
  stdio: options.stdio || "inherit",
670
671
  encoding: options.encoding || "utf8",
671
672
  shell: process.platform === "win32",
@@ -1532,6 +1533,46 @@ function openspecToolsForTarget(target) {
1532
1533
  return target;
1533
1534
  }
1534
1535
 
1536
+ // Where OpenSpec reads its one global configuration (OpenSpec 1.14
1537
+ // `getGlobalConfigDir`): XDG_CONFIG_HOME on every platform when set, else
1538
+ // %APPDATA% on Windows and ~/.config elsewhere.
1539
+ function openspecGlobalConfigFile() {
1540
+ const base = process.env.XDG_CONFIG_HOME
1541
+ || (process.platform === "win32"
1542
+ ? process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming")
1543
+ : path.join(os.homedir(), ".config"));
1544
+ return path.join(base, "openspec", "config.json");
1545
+ }
1546
+
1547
+ // OpenSpec reads `delivery` only from that global file, and its default,
1548
+ // `both`, put every workflow on Claude twice: a skill and an `/opsx:` command
1549
+ // (#406). The OpenSpec runs that generate surfaces get the user's own
1550
+ // configuration with `delivery` replaced by `skills`, through a temporary
1551
+ // XDG_CONFIG_HOME; the user's file is read and never written. Every other
1552
+ // field, the workflow selection among them, still applies.
1553
+ function withSkillsDelivery(run) {
1554
+ let config = {};
1555
+ try {
1556
+ const parsed = JSON.parse(fs.readFileSync(openspecGlobalConfigFile(), "utf8"));
1557
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) config = parsed;
1558
+ } catch {
1559
+ // Absent or unreadable reads as OpenSpec's defaults, as OpenSpec does.
1560
+ }
1561
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "keel-openspec-config-"));
1562
+ try {
1563
+ fs.mkdirSync(path.join(home, "openspec"));
1564
+ fs.writeFileSync(
1565
+ path.join(home, "openspec", "config.json"),
1566
+ `${JSON.stringify({ ...config, delivery: "skills" }, null, 2)}\n`
1567
+ );
1568
+ return run({ ...process.env, XDG_CONFIG_HOME: home });
1569
+ } finally {
1570
+ fs.rmSync(home, { recursive: true, force: true });
1571
+ }
1572
+ }
1573
+
1574
+ const OPENSPEC_GENERATING_COMMANDS = new Set(["init", "update"]);
1575
+
1535
1576
  function runOpenSpec(args, repo, options) {
1536
1577
  const command = options.dryRun ? "openspec" : findOpenSpecCommand();
1537
1578
  if (!command) {
@@ -1540,10 +1581,8 @@ function runOpenSpec(args, repo, options) {
1540
1581
  );
1541
1582
  return 1;
1542
1583
  }
1543
- return runCommand(command, args, {
1544
- cwd: repo,
1545
- dryRun: options.dryRun,
1546
- });
1584
+ if (options.dryRun) return runCommand(command, args, { cwd: repo, dryRun: true });
1585
+ return withSkillsDelivery((env) => runCommand(command, args, { cwd: repo, env }));
1547
1586
  }
1548
1587
 
1549
1588
  function runProjectInit(options) {
@@ -1746,7 +1785,8 @@ function commandSurfaceForTarget(target, repo) {
1746
1785
  paths: OPENSPEC_COMMAND_IDS.map((id) =>
1747
1786
  path.join(repo, location, `${id}.md`)
1748
1787
  ),
1749
- remediation: "run keel --init --target claude or openspec update --force",
1788
+ remediation: "run keel --init --target claude to remove them",
1789
+ retired: true,
1750
1790
  };
1751
1791
  }
1752
1792
  if (target === "codex" && codexOpenSpecLayout(repo) === "agents") {
@@ -1776,7 +1816,8 @@ function commandSurfaceForTarget(target, repo) {
1776
1816
  paths: OPENSPEC_COMMAND_IDS.map((id) =>
1777
1817
  path.join(repo, location, `opsx-${id}.md`)
1778
1818
  ),
1779
- remediation: "run keel --init --target opencode or openspec update --force",
1819
+ remediation: "run keel --init --target opencode to remove them",
1820
+ retired: true,
1780
1821
  };
1781
1822
  }
1782
1823
 
@@ -1804,16 +1845,19 @@ function openspecOverlaySurfacesForTarget(target, repo) {
1804
1845
  archive: "openspec-archive-change",
1805
1846
  sync: "openspec-sync-specs",
1806
1847
  }[action];
1848
+ // Claude and OpenCode command files are no longer generated (#406); one a
1849
+ // repository still holds from a `both` delivery keeps its overlay until
1850
+ // the next `keel --init` removes it.
1851
+ const command = commandPathForAction(target, repo, action);
1852
+ const keepsCommand = command !== null
1853
+ && (target === "codex" || fs.existsSync(command));
1807
1854
  return [
1808
1855
  {
1809
1856
  action,
1810
1857
  path: path.join(repo, skillRoot, skillName, "SKILL.md"),
1811
1858
  },
1812
- {
1813
- action,
1814
- path: commandPathForAction(target, repo, action),
1815
- },
1816
- ].filter((surface) => surface.path !== null);
1859
+ ...(keepsCommand ? [{ action, path: command }] : []),
1860
+ ];
1817
1861
  });
1818
1862
  }
1819
1863
 
@@ -1902,7 +1946,7 @@ function keelOpenSpecOverlay(action) {
1902
1946
  : [
1903
1947
  "- Archive completion is gated by `keel gate change-close --action archive` plus `keel-review-checklist`; verify task evidence, follow-up ownership, and completion gates before proceeding.",
1904
1948
  "- Before final sync/archive, each related critical expectation must have behavior evidence, a durable follow-up owner, or an explicit discard reason.",
1905
- "- When `/opsx:sync` has already promoted the change's spec delta, run the archive with `--skip-specs` so the promoted delta is not re-applied; archive is not idempotent over an already-synced delta.",
1949
+ "- When the `openspec-sync-specs` skill has already promoted the change's spec delta, run the archive with `--skip-specs` so the promoted delta is not re-applied; archive is not idempotent over an already-synced delta.",
1906
1950
  "- After archiving, run `keel guard clear` to drop the change's guard manifest; the read-only gate never clears it for you.",
1907
1951
  "- A repository that standing-authorizes `archive` in `keel/config.yaml` does not need the per-occurrence archive confirmation; a repository that declares nothing still needs it.",
1908
1952
  "- The completion gate and follow-up ownership checks still run unchanged under a standing authorization; it removes the confirmation, not the proof.",
@@ -2237,7 +2281,17 @@ function printTargetSurface(repo, target) {
2237
2281
  );
2238
2282
 
2239
2283
  const commands = commandSurfaceForTarget(target, repo);
2240
- if (commands.skillsOnly) {
2284
+ if (commands.retired) {
2285
+ const leftover = commands.paths.filter((file) => fs.existsSync(file));
2286
+ printDoctorLine(
2287
+ "OpenSpec commands",
2288
+ leftover.length === 0 ? "ok" : "duplicate",
2289
+ leftover.length === 0
2290
+ ? "none; Keel generates OpenSpec's workflows as skills only (#406)"
2291
+ : `${leftover.length} command file${leftover.length === 1 ? "" : "s"} under ${commands.location} `
2292
+ + `duplicate the skills; ${commands.remediation}`
2293
+ );
2294
+ } else if (commands.skillsOnly) {
2241
2295
  printDoctorLine(
2242
2296
  "OpenSpec commands",
2243
2297
  "ok",
@@ -2876,7 +2930,9 @@ function runAction(options) {
2876
2930
  return 1;
2877
2931
  }
2878
2932
  const archiving = options.openspecArgs[0] === "archive" ? archiveTracking(process.cwd(), options.openspecArgs) : null;
2879
- const status = runCommand(openspec, options.openspecArgs, { stdio: "inherit" });
2933
+ const status = OPENSPEC_GENERATING_COMMANDS.has(options.openspecArgs[0])
2934
+ ? withSkillsDelivery((env) => runCommand(openspec, options.openspecArgs, { stdio: "inherit", env }))
2935
+ : runCommand(openspec, options.openspecArgs, { stdio: "inherit" });
2880
2936
  if (status === 0 && archiving) keepArchivedTracked(process.cwd(), archiving);
2881
2937
  if (status !== 0 || options.openspecArgs[0] !== "update") return status;
2882
2938
  const repo = process.cwd();
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.180.0",
3
+ "version": "5.182.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.180.0",
9
+ "version": "5.182.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.180.0",
5
+ "version": "5.182.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.180.0",
3
+ "version": "5.182.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.180.0",
3
+ "version": "5.182.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",
@@ -7,7 +7,7 @@ description: Align explicit requirements, implicit expectations, non-goals, obse
7
7
 
8
8
  ## Purpose
9
9
 
10
- Turn user intent and repository facts into durable OpenSpec authority before specs and executable tasks harden. Alignment is risk-scaled: clear, complete, low-risk requests pass through a compact quick path; material ambiguity switches to a focused deep path. This skill owns materiality routing, acceptance authority, and write-back ownership; which surface a host offers for asking is the host's, and it does not replace `/opsx:apply`, review, or OpenSpec artifact mechanics.
10
+ Turn user intent and repository facts into durable OpenSpec authority before specs and executable tasks harden. Alignment is risk-scaled: clear, complete, low-risk requests pass through a compact quick path; material ambiguity switches to a focused deep path. This skill owns materiality routing, acceptance authority, and write-back ownership; which surface a host offers for asking is the host's, and it does not replace `openspec-apply-change`, review, or OpenSpec artifact mechanics.
11
11
 
12
12
  ## Routing
13
13
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: keel-debug-failure
3
- description: Debug Keel agent command or validation failures under Keel's selected OpenSpec task contract. Use when `/opsx:apply` or a selected task reports failed commands, failing tests, validation errors, stop decisions, or needs an evidence-bound failure report.
3
+ description: Debug Keel agent command or validation failures under Keel's selected OpenSpec task contract. Use when `openspec-apply-change` or a selected task reports failed commands, failing tests, validation errors, stop decisions, or needs an evidence-bound failure report.
4
4
  ---
5
5
 
6
6
  # keel-debug-failure
@@ -7,7 +7,7 @@ description: Run the current agent's thin semantic consistency review after shar
7
7
 
8
8
  ## Purpose
9
9
 
10
- Use this thin Keel consistency gate only at completion gates: after a complete `/opsx:apply` task group, before `/opsx:sync` or `/opsx:archive`, before meaningful handoff, or when delivery reports risks, findings, follow-ups, or out-of-scope need.
10
+ Use this thin Keel consistency gate only at completion gates: after a complete `openspec-apply-change` task group, before `openspec-sync-specs` or `openspec-archive-change`, before meaningful handoff, or when delivery reports risks, findings, follow-ups, or out-of-scope need.
11
11
 
12
12
  Shared Core commands (`keel gate task-start`, `task-complete`, and `change-close`) validate deterministic structure. They do not judge product intent, behavioral test sufficiency, design quality, or risk completeness. Those judgments remain with the current agent.
13
13
 
@@ -51,8 +51,8 @@ REQUIRED_SCRIPTS = [
51
51
  "scripts/validate_plugin.py",
52
52
  ]
53
53
 
54
- PACKAGE_VERSION = "5.180.0"
55
- PROTOCOL_VERSION = "5.180.0"
54
+ PACKAGE_VERSION = "5.182.0"
55
+ PROTOCOL_VERSION = "5.182.0"
56
56
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
57
57
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
58
58
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -171,9 +171,9 @@ SKILL_DOC_REQUIREMENTS = [
171
171
  "path": "src/skills/keel-review-checklist/SKILL.md",
172
172
  "required": [
173
173
  "completion gates",
174
- "/opsx:apply",
175
- "/opsx:sync",
176
- "/opsx:archive",
174
+ "openspec-apply-change",
175
+ "openspec-sync-specs",
176
+ "openspec-archive-change",
177
177
  "## Context to read",
178
178
  "keel gate task-start",
179
179
  "task-complete",
@@ -753,7 +753,7 @@ def validate_openspec_schema(errors: list[str]) -> None:
753
753
  f"name: {OPENSPEC_SCHEMA_NAME}",
754
754
  "description: Keel OpenSpec workflow",
755
755
  "apply:",
756
- "/opsx:apply",
756
+ "openspec-apply-change",
757
757
  "keel-review-checklist",
758
758
  "Mode",
759
759
  "Covers",
@@ -1227,7 +1227,7 @@ def validate_target_surface_scenario() -> int:
1227
1227
  claude_doctor.returncode != 0
1228
1228
  or "Target surface:" not in claude_doctor.stdout
1229
1229
  or "OpenSpec commands: ok" not in claude_doctor.stdout
1230
- or ".claude/commands/opsx" not in posix_paths(claude_doctor.stdout)
1230
+ or "skills only" not in claude_doctor.stdout
1231
1231
  or "OpenSpec action skills: ok" not in claude_doctor.stdout
1232
1232
  or ".claude/skills" not in posix_paths(claude_doctor.stdout)
1233
1233
  or "bootstrap: ok" not in claude_doctor.stdout
@@ -1294,7 +1294,7 @@ def validate_target_surface_scenario() -> int:
1294
1294
  if (
1295
1295
  opencode_doctor.returncode != 0
1296
1296
  or "OpenSpec commands: ok" not in opencode_doctor.stdout
1297
- or ".opencode/commands" not in posix_paths(opencode_doctor.stdout)
1297
+ or "skills only" not in opencode_doctor.stdout
1298
1298
  or "OpenSpec action skills: ok" not in opencode_doctor.stdout
1299
1299
  or ".opencode/skills" not in posix_paths(opencode_doctor.stdout)
1300
1300
  or "bootstrap: ok" not in opencode_doctor.stdout
@@ -2201,7 +2201,7 @@ def mailbox_common_dir(repo: Path) -> Path:
2201
2201
  CHAT_ROLE_VARIABLES = ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")
2202
2202
  # The desktop app's session markers (#319 D5): a run inside it must not change
2203
2203
  # what shift scenarios see.
2204
- DESKTOP_HOST_VARIABLES = ("CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_HOST_SESSION_ID")
2204
+ DESKTOP_HOST_VARIABLES = ("CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_HOST_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_PID")
2205
2205
 
2206
2206
 
2207
2207
  def chat_environment(**extra: str) -> dict[str, str]:
@@ -2498,6 +2498,195 @@ def validate_chat_mention_skips_code_scenario() -> int:
2498
2498
  return 0
2499
2499
 
2500
2500
 
2501
+ def host_project_name(directory: Path) -> str:
2502
+ """The host's project directory name for a working directory (Claude Code's sanitizing)."""
2503
+ return re.sub(r"[^A-Za-z0-9]", "-", os.path.realpath(directory))
2504
+
2505
+
2506
+ def chat_session_start(cwd: Path, env: dict, session: str, pid: int, source: str = "startup",
2507
+ transcript: Path | None = None) -> subprocess.CompletedProcess:
2508
+ payload = {"cwd": str(cwd), "hook_event_name": "SessionStart", "session_id": session, "source": source}
2509
+ if transcript is not None:
2510
+ payload["transcript_path"] = str(transcript)
2511
+ return subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=cwd, text=True,
2512
+ capture_output=True, check=False, input=json.dumps(payload),
2513
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": session, "CLAUDE_PID": str(pid)})
2514
+
2515
+
2516
+ def chat_presence(rtl: Path, role: str) -> dict:
2517
+ path = mailbox_common_dir(rtl) / "keel-chat" / "presence" / f"{role}.json"
2518
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
2519
+
2520
+
2521
+ def chat_session_list(rtl: Path, role: str) -> dict:
2522
+ path = mailbox_common_dir(rtl) / "keel-chat" / "presence" / f"{role}.sessions.json"
2523
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
2524
+
2525
+
2526
+ def chat_session_record(rtl: Path, session: str) -> dict:
2527
+ path = mailbox_common_dir(rtl) / "keel-chat" / "sessions" / f"{session}.json"
2528
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
2529
+
2530
+
2531
+ def validate_chat_hook_follows_session_worktree_scenario() -> int:
2532
+ """Issue #415 (measured 2026-10-21): a resumed `claude --bg -w` session's
2533
+ SessionStart reports the directory it was launched from as `cwd`.
2534
+
2535
+ keel-maint-2, launched from the main checkout, was recorded as the main
2536
+ checkout's role (codex-issues) and watched its signal, so a message to
2537
+ keel-maint-2 did not wake it. The transcript stays in the host project
2538
+ directory of the worktree the session really runs in; the hook follows it.
2539
+ """
2540
+ label = "chat-hook-follows-session-worktree:"
2541
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415a-") as raw:
2542
+ base = Path(raw)
2543
+ rtl, verify, env = chat_scratch_group(base)
2544
+ chat_session_start(rtl, env, "sess-r", os.getpid())
2545
+ transcript = base / "claude" / "projects" / host_project_name(verify) / "sess-v.jsonl"
2546
+ started = chat_session_start(rtl, env, "sess-v", os.getpid(), source="resume", transcript=transcript)
2547
+ try:
2548
+ watched = json.loads(started.stdout)["hookSpecificOutput"]["watchPaths"]
2549
+ except (ValueError, KeyError, TypeError):
2550
+ report(f"{label} the resumed session's SessionStart printed no watch paths: {started.stdout!r} {started.stderr!r}")
2551
+ return 1
2552
+ if not any(path.endswith("/signal/verify") for path in watched) or any(path.endswith("/signal/rtl") for path in watched):
2553
+ report(f"{label} a session whose transcript is verify's watches {watched!r}, not verify's signal alone.")
2554
+ return 1
2555
+ verify_presence = chat_presence(rtl, "verify")
2556
+ if verify_presence.get("cli_session") != "sess-v" or os.path.realpath(verify_presence.get("cli_worktree") or "") != os.path.realpath(verify):
2557
+ report(f"{label} verify's presence does not record the resumed session in verify's worktree: {verify_presence!r}")
2558
+ return 1
2559
+ if chat_session_record(rtl, "sess-v").get("role") != "verify":
2560
+ report(f"{label} the resumed session's record names {chat_session_record(rtl, 'sess-v').get('role')!r}, not verify.")
2561
+ return 1
2562
+ if chat_presence(rtl, "rtl").get("cli_session") != "sess-r":
2563
+ report(f"{label} rtl's presence took the resumed session: {chat_presence(rtl, 'rtl')!r}")
2564
+ return 1
2565
+ if "sess-v" in chat_session_list(rtl, "rtl"):
2566
+ report(f"{label} rtl's session list took the resumed session: {chat_session_list(rtl, 'rtl')!r}")
2567
+ return 1
2568
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2569
+ report(f"{label} the scenario registry does not include it.")
2570
+ return 1
2571
+ report(f"{label.rstrip(':')} scenario passed.")
2572
+ return 0
2573
+
2574
+
2575
+ def validate_chat_visitor_not_recorded_scenario() -> int:
2576
+ """Issue #415: a session that runs a keel command in another role's worktree
2577
+ is not that role's session, and a caller with no Claude session clears nothing."""
2578
+ label = "chat-visitor-not-recorded:"
2579
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415b-") as raw:
2580
+ base = Path(raw)
2581
+ rtl, verify, env = chat_scratch_group(base)
2582
+ chat_session_start(rtl, env, "sess-r", os.getpid())
2583
+ chat_session_start(verify, env, "sess-v", os.getpid())
2584
+ visitor = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-r", "CLAUDE_PID": str(os.getpid())}
2585
+ run_keel(verify, "chat", "unread", env=visitor)
2586
+ bare = {key: value for key, value in env.items() if not key.startswith("CLAUDE")}
2587
+ run_keel(verify, "chat", "unread", env=bare)
2588
+ # A session binding verify's worktree from elsewhere, on someone's behalf: its
2589
+ # transcript lies under rtl's project directory, so it is not recorded.
2590
+ config = base / "claude"
2591
+ write_text(config / "projects" / host_project_name(rtl) / "sess-r.jsonl", "{}\n")
2592
+ run_keel(verify, "chat", "role", "--set", "verify", env={**visitor, "CLAUDE_CONFIG_DIR": str(config)})
2593
+ presence = chat_presence(rtl, "verify")
2594
+ if presence.get("cli_session") != "sess-v" or os.path.realpath(presence.get("cli_worktree") or "") != os.path.realpath(verify):
2595
+ report(f"{label} a visiting or session-less keel command replaced verify's recorded session: {presence!r}")
2596
+ return 1
2597
+ if set(chat_session_list(rtl, "verify")) != {"sess-v"}:
2598
+ report(f"{label} verify's session list is {sorted(chat_session_list(rtl, 'verify'))!r}, not its own session alone.")
2599
+ return 1
2600
+ own = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-v", "CLAUDE_PID": str(os.getpid())}
2601
+ before = chat_presence(rtl, "verify").get("last_active")
2602
+ time.sleep(1.1)
2603
+ run_keel(verify, "chat", "unread", env=own)
2604
+ if chat_presence(rtl, "verify").get("last_active") == before:
2605
+ report(f"{label} verify's own session running a keel command no longer marks it active.")
2606
+ return 1
2607
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2608
+ report(f"{label} the scenario registry does not include it.")
2609
+ return 1
2610
+ report(f"{label.rstrip(':')} scenario passed.")
2611
+ return 0
2612
+
2613
+
2614
+ def validate_chat_role_set_records_session_scenario() -> int:
2615
+ """Issue #415: `keel chat role --set` in the live session makes it the role's session.
2616
+
2617
+ keel-maint-2 bound its role after starting, and `keel chat wake now
2618
+ keel-maint-2` then found no session to resume.
2619
+ """
2620
+ label = "chat-role-set-records-session:"
2621
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415c-") as raw:
2622
+ base = Path(raw)
2623
+ rtl, _verify, env = chat_scratch_group(base)
2624
+ lane = chat_worktree(rtl, base / "lane")
2625
+ config = base / "claude"
2626
+ transcript = config / "projects" / host_project_name(lane) / "sess-3.jsonl"
2627
+ write_text(transcript, json.dumps({"type": "user", "message": {"role": "user", "content": "hi"}}) + "\n")
2628
+ env = {**env, "CLAUDE_CONFIG_DIR": str(config)}
2629
+ chat_session_start(lane, env, "sess-3", os.getpid(), transcript=transcript)
2630
+ bound = run_keel(lane, "chat", "role", "--set", "verify2",
2631
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-3", "CLAUDE_PID": str(os.getpid())})
2632
+ if bound.returncode != 0:
2633
+ report(f"{label} role --set failed: {bound.stdout!r} {bound.stderr!r}")
2634
+ return 1
2635
+ presence = chat_presence(rtl, "verify2")
2636
+ if presence.get("cli_session") != "sess-3" or os.path.realpath(presence.get("cli_worktree") or "") != os.path.realpath(lane):
2637
+ report(f"{label} binding a role did not record the session that bound it: {presence!r}")
2638
+ return 1
2639
+ if chat_session_record(rtl, "sess-3").get("role") != "verify2":
2640
+ report(f"{label} the binding session's record names {chat_session_record(rtl, 'sess-3').get('role')!r}, not verify2.")
2641
+ return 1
2642
+ segments_file = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "segments" / "verify2.json"
2643
+ segments = json.loads(segments_file.read_text(encoding="utf-8")).get("segments", []) if segments_file.exists() else []
2644
+ if not segments or os.path.realpath(segments[-1].get("transcript", "")) != os.path.realpath(transcript):
2645
+ report(f"{label} verify2's current segment is not the binding session's transcript: {segments!r}")
2646
+ return 1
2647
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2648
+ report(f"{label} the scenario registry does not include it.")
2649
+ return 1
2650
+ report(f"{label.rstrip(':')} scenario passed.")
2651
+ return 0
2652
+
2653
+
2654
+ def validate_chat_wake_skips_removed_session_scenario() -> int:
2655
+ """Issue #415: a role's recorded session that `claude rm` removed is not resumed."""
2656
+ label = "chat-wake-skips-removed-session:"
2657
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415d-") as raw:
2658
+ base = Path(raw)
2659
+ rtl, verify, env, _ = shift_scratch(base)
2660
+ calls = base / "claude-calls.jsonl"
2661
+ fake = base / "fake-claude"
2662
+ write_text(fake, "#!/usr/bin/env python3\nimport json, sys\n"
2663
+ f"open({str(calls)!r}, 'a').write(json.dumps(sys.argv[1:]) + '\\n')\n"
2664
+ "if sys.argv[1:3] == ['agents', '--json']:\n"
2665
+ " print(json.dumps([{'kind': 'background', 'sessionId': 'other-0000', 'id': 'other-00', 'cwd': '/tmp'}]))\n"
2666
+ "else:\n print('backgrounded · fake')\n")
2667
+ fake.chmod(0o755)
2668
+ env = {**env, "KEEL_CLAUDE": str(fake)}
2669
+ dead = subprocess.Popen(["true"])
2670
+ dead.wait()
2671
+ chat_session_start(verify, env, "sess-verify-1", dead.pid)
2672
+ woke = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
2673
+ made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2674
+ if any(call[:1] == ["--bg"] for call in made):
2675
+ report(f"{label} wake now resumed a session claude agents no longer lists: {made!r}")
2676
+ return 1
2677
+ if woke.returncode == 0:
2678
+ report(f"{label} wake now exits 0 for a session it could not resume: {woke.stdout!r}")
2679
+ return 1
2680
+ if "removed" not in (woke.stdout + woke.stderr):
2681
+ report(f"{label} wake now does not say the recorded session was removed: {woke.stdout!r} {woke.stderr!r}")
2682
+ return 1
2683
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2684
+ report(f"{label} the scenario registry does not include it.")
2685
+ return 1
2686
+ report(f"{label.rstrip(':')} scenario passed.")
2687
+ return 0
2688
+
2689
+
2501
2690
  def validate_chat_wake_now_cli_scenario() -> int:
2502
2691
  """Issue #348 on the CLI (owner's CLI waker, 2026-10-19): one step wakes a role.
2503
2692
 
@@ -2528,7 +2717,9 @@ def validate_chat_wake_now_cli_scenario() -> int:
2528
2717
  input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": "sess-verify-1", "source": "startup"}))
2529
2718
 
2530
2719
  def made() -> list[dict]:
2531
- return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2720
+ # The resumes only: since #415 a wake first reads `claude agents --json --all`.
2721
+ calls_made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2722
+ return [call for call in calls_made if call["argv"][:1] == ["--bg"]]
2532
2723
 
2533
2724
  start(dead.pid)
2534
2725
  posted = run_keel(rtl, "chat", "dm", "verify", "rerun R009", env=env)
@@ -10760,16 +10951,21 @@ def openspec_overlay_files(
10760
10951
  target: str,
10761
10952
  codex_home: Path | None = None,
10762
10953
  ) -> dict[str, list[Path]]:
10954
+ # Keel generates skills only (#406); a command file counts only while a
10955
+ # repository still holds one from an earlier `both` delivery.
10956
+ def held(*paths: Path) -> list[Path]:
10957
+ return [paths[0], *[p for p in paths[1:] if p.exists()]]
10958
+
10763
10959
  if target == "claude":
10764
10960
  return {
10765
- "apply": [
10961
+ "apply": held(
10766
10962
  repo / ".claude/skills/openspec-apply-change/SKILL.md",
10767
10963
  repo / ".claude/commands/opsx/apply.md",
10768
- ],
10769
- "archive": [
10964
+ ),
10965
+ "archive": held(
10770
10966
  repo / ".claude/skills/openspec-archive-change/SKILL.md",
10771
10967
  repo / ".claude/commands/opsx/archive.md",
10772
- ],
10968
+ ),
10773
10969
  }
10774
10970
  if target == "codex":
10775
10971
  assert codex_home is not None
@@ -10780,14 +10976,14 @@ def openspec_overlay_files(
10780
10976
  "archive": [repo / ".agents/skills/openspec-archive-change/SKILL.md"],
10781
10977
  }
10782
10978
  return {
10783
- "apply": [
10979
+ "apply": held(
10784
10980
  repo / ".opencode/skills/openspec-apply-change/SKILL.md",
10785
10981
  repo / ".opencode/commands/opsx-apply.md",
10786
- ],
10787
- "archive": [
10982
+ ),
10983
+ "archive": held(
10788
10984
  repo / ".opencode/skills/openspec-archive-change/SKILL.md",
10789
10985
  repo / ".opencode/commands/opsx-archive.md",
10790
- ],
10986
+ ),
10791
10987
  }
10792
10988
 
10793
10989
 
@@ -10890,15 +11086,20 @@ def expected_overlay_surfaces(
10890
11086
  for action, skill in OVERLAY_ACTION_SKILLS.items():
10891
11087
  if action == "propose" and target == "opencode":
10892
11088
  continue
11089
+ # Keel generates skills only (#406); a command file counts only while a
11090
+ # repository still holds one from an earlier `both` delivery.
10893
11091
  if target == "claude":
10894
11092
  surfaces.append(repo / f".claude/skills/{skill}/SKILL.md")
10895
- surfaces.append(repo / f".claude/commands/opsx/{action}.md")
11093
+ command = repo / f".claude/commands/opsx/{action}.md"
10896
11094
  elif target == "codex":
10897
11095
  assert codex_home is not None
10898
11096
  surfaces.append(repo / f".agents/skills/{skill}/SKILL.md")
11097
+ command = None
10899
11098
  else:
10900
11099
  surfaces.append(repo / f".opencode/skills/{skill}/SKILL.md")
10901
- surfaces.append(repo / f".opencode/commands/opsx-{action}.md")
11100
+ command = repo / f".opencode/commands/opsx-{action}.md"
11101
+ if command is not None and command.exists():
11102
+ surfaces.append(command)
10902
11103
  return surfaces
10903
11104
 
10904
11105
 
@@ -11134,8 +11335,8 @@ def validate_sync_surface_overlay_scenario() -> int:
11134
11335
  tmp = Path(raw)
11135
11336
 
11136
11337
  surfaces = {
11338
+ # Skills only since #406: Keel generates no `.claude/commands/opsx/`.
11137
11339
  "claude": [
11138
- ".claude/commands/opsx/sync.md",
11139
11340
  ".claude/skills/openspec-sync-specs/SKILL.md",
11140
11341
  ],
11141
11342
  "codex": [
@@ -11186,8 +11387,8 @@ def validate_sync_surface_overlay_scenario() -> int:
11186
11387
 
11187
11388
  # M4 — explore stays uncovered, deliberately.
11188
11389
  explore = repo / (
11189
- ".claude/commands/opsx/explore.md" if target == "claude"
11190
- else f".{target}/skills/openspec-explore/SKILL.md"
11390
+ ".claude/skills/openspec-explore/SKILL.md" if target == "claude"
11391
+ else ".agents/skills/openspec-explore/SKILL.md"
11191
11392
  )
11192
11393
  if explore.is_file() and marker in explore.read_text(encoding="utf-8"):
11193
11394
  report(
@@ -11340,6 +11541,224 @@ def validate_update_restores_overlays_scenario() -> int:
11340
11541
  return 0
11341
11542
 
11342
11543
 
11544
+ def validate_openspec_skills_only_scenario() -> int:
11545
+ """Issue #406: one copy of each OpenSpec workflow, whatever the global delivery.
11546
+
11547
+ OpenSpec reads `delivery` only from the user's global configuration, which
11548
+ defaults to `both` and put every workflow on Claude twice — a skill and an
11549
+ `/opsx:` command. Keel runs OpenSpec with that configuration's `delivery`
11550
+ replaced by `skills`, and never writes the file itself.
11551
+ """
11552
+ label = "openspec-skills-only:"
11553
+ with tempfile.TemporaryDirectory(prefix="keel-406-") as raw_tmp:
11554
+ tmp = Path(raw_tmp)
11555
+ config = tmp / "xdg/openspec/config.json"
11556
+ write_text(config, json.dumps({
11557
+ "featureFlags": {}, "profile": "custom", "delivery": "both",
11558
+ "workflows": ["propose", "explore", "apply", "sync", "archive"],
11559
+ }, indent=2) + "\n")
11560
+ before = config.read_bytes()
11561
+ env = dict(os.environ)
11562
+ env["XDG_CONFIG_HOME"] = str(tmp / "xdg")
11563
+ stray = ".claude/commands/opsx/apply.md"
11564
+ upstream = "---\nname: OPSX: Apply\n---\n\nImplement tasks.\n"
11565
+
11566
+ def keel(repo: Path, *args: str):
11567
+ result = run_keel(repo, *args, env=env)
11568
+ if result.returncode != 0:
11569
+ report(f"{label} `keel {' '.join(args)}` failed: {(result.stderr or result.stdout).strip()}")
11570
+ return result
11571
+
11572
+ claude = tmp / "claude"
11573
+ claude.mkdir()
11574
+ if keel(claude, "--init", "--target", "claude").returncode != 0:
11575
+ return 1
11576
+ commands = sorted(p.name for p in (claude / ".claude/commands/opsx").glob("*")) \
11577
+ if (claude / ".claude/commands/opsx").is_dir() else []
11578
+ if commands:
11579
+ report(f"{label} with a global `delivery: both`, keel --init left command files: {commands!r}")
11580
+ return 1
11581
+ skills = [claude / f".claude/skills/{skill}/SKILL.md" for skill in ("openspec-propose", "openspec-explore", "openspec-apply-change",
11582
+ "openspec-sync-specs", "openspec-archive-change")]
11583
+ absent = [str(p.relative_to(claude)) for p in skills if not p.is_file()]
11584
+ if absent:
11585
+ report(f"{label} keel --init did not generate the workflow skills: {absent!r}")
11586
+ return 1
11587
+ # OpenSpec's own text only: the Keel overlay's wording is
11588
+ # guidance-names-openspec-skills's to check.
11589
+ naming = [str(p.relative_to(claude)) for p in skills
11590
+ if "/opsx:" in strip_openspec_surface_overlay(p.read_text(encoding="utf-8"))]
11591
+ if naming:
11592
+ report(f"{label} OpenSpec's generated skill text still names `/opsx:` commands: {naming!r}")
11593
+ return 1
11594
+ unmarked = [str(p.relative_to(claude)) for p in expected_overlay_surfaces(claude, "claude")
11595
+ if OPENSPEC_SURFACE_OVERLAY_START not in p.read_text(encoding="utf-8")]
11596
+ if unmarked:
11597
+ report(f"{label} managed skills lack the Keel overlay: {unmarked!r}")
11598
+ return 1
11599
+ if config.read_bytes() != before:
11600
+ report(f"{label} keel --init rewrote the global OpenSpec configuration: {config.read_text()!r}")
11601
+ return 1
11602
+
11603
+ doctor = keel(claude, "--doctor", "--target", "claude")
11604
+ commands_line = next((l for l in doctor.stdout.splitlines() if l.startswith("OpenSpec commands:")), "")
11605
+ overlay_line = next((l for l in doctor.stdout.splitlines() if l.startswith("Keel apply/archive/sync overlay:")), "")
11606
+ if not commands_line.startswith("OpenSpec commands: ok"):
11607
+ report(f"{label} doctor does not read a skills-only repository's commands as ok: {commands_line!r}")
11608
+ return 1
11609
+ if "skills only" not in commands_line:
11610
+ report(f"{label} doctor's commands line does not say the workflows are skills only: {commands_line!r}")
11611
+ return 1
11612
+ if not overlay_line.startswith("Keel apply/archive/sync overlay: ok"):
11613
+ report(f"{label} doctor does not read the skills-only overlay as ok: {overlay_line!r}")
11614
+ return 1
11615
+ if "4/4" not in overlay_line:
11616
+ report(f"{label} doctor's overlay line does not count 4/4 surfaces: {overlay_line!r}")
11617
+ return 1
11618
+
11619
+ write_text(claude / stray, upstream)
11620
+ if keel(claude, "--install", "--target", "claude").returncode != 0:
11621
+ return 1
11622
+ if OPENSPEC_SURFACE_OVERLAY_START not in (claude / stray).read_text(encoding="utf-8"):
11623
+ report(f"{label} keel --install did not overlay a command file the repository still holds.")
11624
+ return 1
11625
+ doctor = keel(claude, "--doctor", "--target", "claude")
11626
+ commands_line = next((l for l in doctor.stdout.splitlines() if l.startswith("OpenSpec commands:")), "")
11627
+ if not commands_line.startswith("OpenSpec commands: duplicate"):
11628
+ report(f"{label} doctor does not read a leftover command file as duplicate: {commands_line!r}")
11629
+ return 1
11630
+ for needle in ("1 ", ".claude/commands/opsx", "keel --init --target claude"):
11631
+ if needle not in posix_paths(commands_line):
11632
+ report(f"{label} the duplicate line does not name {needle!r}: {commands_line!r}")
11633
+ return 1
11634
+ if keel(claude, "--init", "--target", "claude").returncode != 0:
11635
+ return 1
11636
+ if (claude / stray).exists():
11637
+ report(f"{label} keel --init did not remove a command file a `both` delivery left.")
11638
+ return 1
11639
+
11640
+ passthrough = tmp / "passthrough"
11641
+ passthrough.mkdir()
11642
+ if keel(passthrough, "--init", "--target", "claude").returncode != 0:
11643
+ return 1
11644
+ write_text(passthrough / stray, upstream)
11645
+ if keel(passthrough, "openspec", "update", "--force").returncode != 0:
11646
+ return 1
11647
+ if (passthrough / stray).exists():
11648
+ report(f"{label} keel openspec update did not remove a command file a `both` delivery left.")
11649
+ return 1
11650
+
11651
+ opencode = tmp / "opencode"
11652
+ opencode.mkdir()
11653
+ if keel(opencode, "--init", "--target", "opencode").returncode != 0:
11654
+ return 1
11655
+ left = sorted(p.name for p in (opencode / ".opencode/commands").glob("opsx-*.md")) \
11656
+ if (opencode / ".opencode/commands").is_dir() else []
11657
+ if left:
11658
+ report(f"{label} keel --init --target opencode left command files: {left!r}")
11659
+ return 1
11660
+ # Any OpenSpec command — doctor runs some — records OpenSpec's own
11661
+ # telemetry notice in the file it reads; everything else must stand.
11662
+ settled = {k: v for k, v in json.loads(config.read_text()).items() if k != "telemetry"}
11663
+ if settled != json.loads(before):
11664
+ report(f"{label} a later run changed the global OpenSpec configuration: {config.read_text()!r}")
11665
+ return 1
11666
+ # Last: OpenSpec itself may record its telemetry notice in the file it reads.
11667
+ listed = keel(passthrough, "openspec", "config", "list")
11668
+ if "delivery: both" not in listed.stdout:
11669
+ report(f"{label} keel openspec config list no longer reports the user's own delivery: {listed.stdout!r}")
11670
+ return 1
11671
+
11672
+ if "openspec-skills-only" not in {name for name, _ in SCENARIOS}:
11673
+ report(f"{label} scenario is not registered.")
11674
+ return 1
11675
+ report("openspec-skills-only scenario passed.")
11676
+ return 0
11677
+
11678
+
11679
+ def validate_guidance_names_openspec_skills_scenario() -> int:
11680
+ """Issue #406: guidance names no `/opsx:` command, since Keel generates none.
11681
+
11682
+ With the workflows delivered as skills only, a sentence telling the reader
11683
+ to run `/opsx:sync` points at a command that does not exist.
11684
+ """
11685
+ label = "guidance-names-openspec-skills:"
11686
+ shipped = [ROOT / "README.md", ROOT / "README.zh-CN.md",
11687
+ ROOT / "assets/openspec/schemas/keel-spec-driven/schema.yaml",
11688
+ *sorted((ROOT / "src/skills").rglob("SKILL.md")),
11689
+ *sorted((ROOT / "plugins/keel/skills").rglob("SKILL.md"))]
11690
+ naming = [str(p.relative_to(ROOT)) for p in shipped if "/opsx:" in p.read_text(encoding="utf-8")]
11691
+ if naming:
11692
+ report(f"{label} shipped guidance still names `/opsx:` commands: {naming!r}")
11693
+ return 1
11694
+ block = extract_managed_block((ROOT / "AGENTS.md").read_text(encoding="utf-8")) or ""
11695
+ if not block:
11696
+ report(f"{label} AGENTS.md has no managed protocol block to read.")
11697
+ return 1
11698
+ for needle in ("/opsx:", "commands/opsx"):
11699
+ if needle in block:
11700
+ report(f"{label} the AGENTS.md protocol block still names {needle!r}.")
11701
+ return 1
11702
+
11703
+ with tempfile.TemporaryDirectory(prefix="keel-406-guidance-") as raw_tmp:
11704
+ repo = Path(raw_tmp)
11705
+ init = run_keel(repo, "--init", "--target", "claude")
11706
+ if init.returncode != 0:
11707
+ report(f"{label} keel --init --target claude failed: {(init.stderr or init.stdout).strip()}")
11708
+ return 1
11709
+ archive = (repo / ".claude/skills/openspec-archive-change/SKILL.md").read_text(encoding="utf-8")
11710
+ overlay = archive[archive.find(OPENSPEC_SURFACE_OVERLAY_START):archive.find(OPENSPEC_SURFACE_OVERLAY_END)]
11711
+ if not overlay:
11712
+ report(f"{label} the archive skill carries no Keel overlay to read.")
11713
+ return 1
11714
+ if "/opsx:" in overlay:
11715
+ report(f"{label} the archive overlay still names an `/opsx:` command.")
11716
+ return 1
11717
+ if "openspec-sync-specs" not in overlay:
11718
+ report(f"{label} the archive overlay does not name `openspec-sync-specs`.")
11719
+ return 1
11720
+
11721
+ if "guidance-names-openspec-skills" not in {name for name, _ in SCENARIOS}:
11722
+ report(f"{label} scenario is not registered.")
11723
+ return 1
11724
+ report("guidance-names-openspec-skills scenario passed.")
11725
+ return 0
11726
+
11727
+
11728
+ def validate_own_surface_is_skills_only_scenario() -> int:
11729
+ """Issue #406: this repository carries the surface Keel now generates.
11730
+
11731
+ Keel's own checkout held `.claude/commands/opsx/*` beside the skills, from
11732
+ OpenSpec 1.6 under `delivery: both`.
11733
+ """
11734
+ label = "own-surface-is-skills-only:"
11735
+ commands = ROOT / ".claude/commands/opsx"
11736
+ held = sorted(p.name for p in commands.glob("*")) if commands.is_dir() else []
11737
+ if held:
11738
+ report(f"{label} this repository still holds OpenSpec command files: {held!r}")
11739
+ return 1
11740
+ naming = [str(p.relative_to(ROOT)) for p in sorted((ROOT / ".claude/skills").glob("openspec-*/SKILL.md"))
11741
+ if "/opsx:" in p.read_text(encoding="utf-8")]
11742
+ if naming:
11743
+ report(f"{label} this repository's Claude skills still name `/opsx:` commands: {naming!r}")
11744
+ return 1
11745
+ doctor = run_keel(ROOT, "--doctor", "--target", "claude")
11746
+ lines = doctor.stdout.splitlines()
11747
+ commands_line = next((l for l in lines if l.startswith("OpenSpec commands:")), "")
11748
+ overlay_line = next((l for l in lines if l.startswith("Keel apply/archive/sync overlay:")), "")
11749
+ if not commands_line.startswith("OpenSpec commands: ok"):
11750
+ report(f"{label} doctor here does not read the commands line ok: {commands_line!r}")
11751
+ return 1
11752
+ if not overlay_line.startswith("Keel apply/archive/sync overlay: ok"):
11753
+ report(f"{label} doctor here does not read the overlay line ok: {overlay_line!r}")
11754
+ return 1
11755
+ if "own-surface-is-skills-only" not in {name for name, _ in SCENARIOS}:
11756
+ report(f"{label} scenario is not registered.")
11757
+ return 1
11758
+ report("own-surface-is-skills-only scenario passed.")
11759
+ return 0
11760
+
11761
+
11343
11762
  def validate_openspec_surface_overlay_scenario() -> int:
11344
11763
  with tempfile.TemporaryDirectory(prefix="keel-overlay-") as raw_tmp:
11345
11764
  tmp = Path(raw_tmp)
@@ -11508,11 +11927,12 @@ def validate_openspec_surface_overlay_scenario() -> int:
11508
11927
  report(f"openspec-surface-overlay scenario OpenCode overlay failed: {error}")
11509
11928
  return 1
11510
11929
 
11511
- opencode_apply_command = opencode_repo / ".opencode/commands/opsx-apply.md"
11930
+ # The skill, since Keel generates no command file (#406).
11931
+ opencode_apply_skill = opencode_repo / ".opencode/skills/openspec-apply-change/SKILL.md"
11512
11932
  write_text(
11513
- opencode_apply_command,
11933
+ opencode_apply_skill,
11514
11934
  strip_openspec_surface_overlay(
11515
- opencode_apply_command.read_text(encoding="utf-8")
11935
+ opencode_apply_skill.read_text(encoding="utf-8")
11516
11936
  ),
11517
11937
  )
11518
11938
  opencode_missing_doctor = run_keel(
@@ -27182,9 +27602,9 @@ def validate_authoring_alignment_overlay_scenario() -> int:
27182
27602
  report("authoring-alignment-overlay Claude init failed:")
27183
27603
  report((claude_init.stderr or claude_init.stdout).strip())
27184
27604
  return 1
27605
+ # Skills only since #406: Keel generates no `.claude/commands/opsx/`.
27185
27606
  claude_surfaces = (
27186
27607
  claude_repo / ".claude/skills/openspec-propose/SKILL.md",
27187
- claude_repo / ".claude/commands/opsx/propose.md",
27188
27608
  )
27189
27609
  for surface in claude_surfaces:
27190
27610
  content = surface.read_text(encoding="utf-8")
@@ -29470,8 +29890,6 @@ def validate_delegation_overlay_scenario() -> int:
29470
29890
  """
29471
29891
 
29472
29892
  generated = [
29473
- ROOT / ".claude/commands/opsx/apply.md",
29474
- ROOT / ".claude/commands/opsx/archive.md",
29475
29893
  ROOT / ".claude/skills/openspec-apply-change/SKILL.md",
29476
29894
  ROOT / ".claude/skills/openspec-archive-change/SKILL.md",
29477
29895
  ROOT / ".codex/skills/openspec-apply-change/SKILL.md",
@@ -39539,8 +39957,6 @@ def validate_native_capabilities_unrestricted_scenario() -> int:
39539
39957
  ROOT / "assets/openspec/schemas/keel-spec-driven/schema.yaml",
39540
39958
  ROOT / "openspec/schemas/keel-spec-driven/schema.yaml",
39541
39959
  ]
39542
- for action in ("apply", "archive", "sync", "propose"):
39543
- surfaces.append(ROOT / f".claude/commands/opsx/{action}.md")
39544
39960
  for name in ("apply-change", "archive-change", "sync-specs", "propose"):
39545
39961
  surfaces.append(ROOT / f".claude/skills/openspec-{name}/SKILL.md")
39546
39962
  surfaces.append(ROOT / f".codex/skills/openspec-{name}/SKILL.md")
@@ -39558,7 +39974,7 @@ def validate_native_capabilities_unrestricted_scenario() -> int:
39558
39974
  for first_read in (
39559
39975
  ROOT / "AGENTS.md",
39560
39976
  ROOT / "assets/bootstrap/AGENTS.md",
39561
- ROOT / ".claude/commands/opsx/apply.md",
39977
+ ROOT / ".claude/skills/openspec-apply-change/SKILL.md",
39562
39978
  ROOT / ".codex/skills/openspec-apply-change/SKILL.md",
39563
39979
  ):
39564
39980
  text = first_read.read_text(encoding="utf-8")
@@ -39622,8 +40038,6 @@ def validate_surfaces_agree_with_code_scenario() -> int:
39622
40038
  return 1
39623
40039
 
39624
40040
  overlays = []
39625
- for action in ("apply", "archive", "sync"):
39626
- overlays.append(ROOT / f".claude/commands/opsx/{action}.md")
39627
40041
  for name in ("apply-change", "archive-change", "sync-specs"):
39628
40042
  overlays.append(ROOT / f".claude/skills/openspec-{name}/SKILL.md")
39629
40043
  overlays.append(ROOT / f".codex/skills/openspec-{name}/SKILL.md")
@@ -41710,6 +42124,9 @@ SCENARIOS: tuple = (
41710
42124
  ("version-alignment", validate_version_alignment_scenario),
41711
42125
  ("sync-surface-overlay", validate_sync_surface_overlay_scenario),
41712
42126
  ("openspec-surface-overlay", validate_openspec_surface_overlay_scenario),
42127
+ ("openspec-skills-only", validate_openspec_skills_only_scenario),
42128
+ ("guidance-names-openspec-skills", validate_guidance_names_openspec_skills_scenario),
42129
+ ("own-surface-is-skills-only", validate_own_surface_is_skills_only_scenario),
41713
42130
  ("update-restores-overlays", validate_update_restores_overlays_scenario),
41714
42131
  ("uninstall", validate_uninstall_scenario),
41715
42132
  (
@@ -41971,6 +42388,10 @@ SCENARIOS: tuple = (
41971
42388
  ("two-live-sessions-on-one-role", validate_two_live_sessions_on_one_role_scenario),
41972
42389
  ("chat-role-rename", validate_chat_role_rename_scenario),
41973
42390
  ("chat-wake-now-cli", validate_chat_wake_now_cli_scenario),
42391
+ ("chat-hook-follows-session-worktree", validate_chat_hook_follows_session_worktree_scenario),
42392
+ ("chat-visitor-not-recorded", validate_chat_visitor_not_recorded_scenario),
42393
+ ("chat-role-set-records-session", validate_chat_role_set_records_session_scenario),
42394
+ ("chat-wake-skips-removed-session", validate_chat_wake_skips_removed_session_scenario),
41974
42395
  ("chat-ack", validate_chat_ack_scenario),
41975
42396
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
41976
42397
  ("patrol-since-last", validate_patrol_since_last_scenario),
@@ -42249,7 +42670,7 @@ def validate_archive_overlay_hygiene(errors: list[str]) -> None:
42249
42670
  if "--skip-specs" not in cli:
42250
42671
  errors.append(
42251
42672
  "the archive overlay must direct archive to pass --skip-specs "
42252
- "after /opsx:sync has promoted the delta."
42673
+ "after the openspec-sync-specs skill has promoted the delta."
42253
42674
  )
42254
42675
  if "drop the change's guard manifest" not in cli:
42255
42676
  errors.append(
@@ -378,13 +378,15 @@ function dispatch(where, options) {
378
378
  }
379
379
  let role = store.currentRole(where);
380
380
  if (options.set !== null) role = store.setRole(where, options.set);
381
+ // The session that binds a role becomes its session (#415 D3).
382
+ const bound = options.set !== null && role ? notice.recordBinding(where, role) : null;
381
383
  if (options.alias !== null) {
382
384
  if (!role) throw new ChatError("Bind a role before adding an alias: `keel chat role --set <name>`.");
383
385
  store.addAlias(where, role, options.alias);
384
386
  }
385
387
  const aliases = role ? store.readMember(where.root, role).aliases : [];
386
388
  if (options.json) out(JSON.stringify({ role, aliases, worktree: where.worktree, store: where.root }));
387
- else out(role ? `Chat role: ${role}${aliases.length ? ` (aliases: ${aliases.join(", ")})` : ""}` : "This worktree has no chat role. Bind one with `keel chat role --set <name>`.");
389
+ else out(role ? `Chat role: ${role}${aliases.length ? ` (aliases: ${aliases.join(", ")})` : ""}${bound ? `\n${bound}` : ""}` : "This worktree has no chat role. Bind one with `keel chat role --set <name>`.");
388
390
  return 0;
389
391
  }
390
392
  case "group":
@@ -705,6 +707,7 @@ function runWake(cwd, options) {
705
707
  return 0;
706
708
  }
707
709
  const resumed = notice.resumeCli(entry);
710
+ if (resumed.removed) throw new ChatError(`${role}'s recorded CLI ${resumed.output}.`);
708
711
  out(`${resumed.ok ? "Resumed" : "Could not resume"} ${role}'s CLI session ${entry.session} in ${entry.worktree}.${resumed.output ? `\n${resumed.output}` : ""}`);
709
712
  return resumed.ok ? 0 : 1;
710
713
  }
@@ -747,7 +750,7 @@ function runChat(argv) {
747
750
  const where = store.requireLocation(cwd);
748
751
  migrateIfNeeded(where);
749
752
  const role = store.currentRole(where);
750
- if (role) notice.touchPresence(where, role);
753
+ if (role) notice.commandPresence(where, role);
751
754
  // Two live sessions on one role share its name and cursor (#369 D3).
752
755
  if (role && ["post", "dm", "todo", "unread", "read"].includes(options.positionals[0])) {
753
756
  const twins = notice.twinWarning(where, role);
@@ -215,6 +215,25 @@ const CLI_WAKE_PROMPT = "You have unread keel chat records; run keel context, th
215
215
  // and the prompt: any other flag starts a copy with a new session id.
216
216
  function resumeCli(entry) {
217
217
  const claude = process.env.KEEL_CLAUDE || "claude";
218
+ // A session `claude rm` removed is gone for good (#415 D4): when the host's
219
+ // list can be read and lacks it, nothing is resumed. An unreadable list
220
+ // resumes as before, since Keel cannot tell.
221
+ const listed = require("child_process").spawnSync(claude, ["agents", "--json", "--all"], {
222
+ encoding: "utf8", timeout: 30 * 1000,
223
+ });
224
+ try {
225
+ const rows = JSON.parse(listed.stdout);
226
+ if (!listed.error && listed.status === 0 && Array.isArray(rows)
227
+ && !rows.some((row) => row && row.sessionId === entry.session)) {
228
+ return {
229
+ ok: false,
230
+ removed: true,
231
+ output: `session ${entry.session} was removed: \`claude agents\` no longer lists it, so a new session must be started for the role in ${entry.worktree || "its worktree"}`,
232
+ };
233
+ }
234
+ } catch {
235
+ // Not a list: fall through and resume.
236
+ }
218
237
  const result = require("child_process").spawnSync(claude, ["--bg", "--resume", entry.session, CLI_WAKE_PROMPT], {
219
238
  cwd: entry.worktree || undefined, encoding: "utf8",
220
239
  });
@@ -506,6 +525,87 @@ function languageAfterTools(where, payload) {
506
525
  return { code: 0 };
507
526
  }
508
527
 
528
+ function realpathOf(file) {
529
+ try {
530
+ return fs.realpathSync(file);
531
+ } catch {
532
+ return path.resolve(file);
533
+ }
534
+ }
535
+
536
+ // The host's project directory name for a working directory.
537
+ function hostProjectName(directory) {
538
+ return directory.replace(/[^A-Za-z0-9]/g, "-");
539
+ }
540
+
541
+ // Where a hook's session runs (#415 D1). A resumed `claude --bg -w` session's
542
+ // SessionStart names the directory it was launched from as `cwd` (measured
543
+ // 2026-10-21, Claude Code 2.1.304), while its transcript stays in the host
544
+ // project directory of the worktree it runs in. When that names another
545
+ // worktree of this repository, the session is that worktree's.
546
+ function hookLocation(payload) {
547
+ const where = store.locate(payload.cwd || process.cwd());
548
+ const transcript = typeof payload.transcript_path === "string" ? payload.transcript_path : "";
549
+ if (!where || !path.isAbsolute(transcript)) return where;
550
+ const project = path.basename(path.dirname(transcript));
551
+ const named = (dir) => [dir, realpathOf(dir)].some((candidate) => hostProjectName(candidate) === project);
552
+ if (named(where.worktree)) return where;
553
+ const listed = require("child_process").spawnSync("git", ["worktree", "list", "--porcelain"], {
554
+ cwd: where.worktree, encoding: "utf8",
555
+ });
556
+ if (listed.error || listed.status !== 0) return where;
557
+ const match = String(listed.stdout).split("\n").filter((line) => line.startsWith("worktree "))
558
+ .map((line) => line.slice("worktree ".length)).find(named);
559
+ return (match && store.locate(match)) || where;
560
+ }
561
+
562
+ // A keel command touches the presence of the role bound to its worktree (#415
563
+ // D2). Only that role's own session — one whose record names the role — records
564
+ // itself there; a visiting session, or a caller with no Claude session, marks
565
+ // the role active and leaves its recorded session and session list as they are.
566
+ function commandPresence(where, role) {
567
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
568
+ const file = id && /^[A-Za-z0-9._-]{1,128}$/.test(id) ? path.join(where.root, "sessions", `${id}.json`) : null;
569
+ if (file && fs.existsSync(file) && store.readJsonFile(file).role === role) {
570
+ touchPresence(where, role);
571
+ return;
572
+ }
573
+ const previous = store.readJsonFile(presenceFile(where, role));
574
+ if (!Object.keys(previous).length) return;
575
+ try {
576
+ store.writeJsonAtomic(where, presenceFile(where, role), { ...previous, state: "online", last_active: store.isoLocal(new Date()) });
577
+ } catch {
578
+ // Presence is a convenience: failing to record it must not fail a command.
579
+ }
580
+ }
581
+
582
+ // `keel chat role --set` inside a Claude Code session makes that session the
583
+ // role's (#415 D3): its record names the role, presence names it, and its
584
+ // transcript starts the role's current segment. Its hooks keep the watch list
585
+ // they were given at start. Returns a sentence for the user, or null.
586
+ function recordBinding(where, role) {
587
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
588
+ if (!id || !/^[A-Za-z0-9._-]{1,128}$/.test(id)) return null;
589
+ // Only a session running in this worktree: its transcript is in this
590
+ // worktree's host project directory. A session binding the role from
591
+ // another worktree on someone's behalf is not recorded (#415 step 1).
592
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(require("os").homedir(), ".claude");
593
+ const transcript = [where.worktree, realpathOf(where.worktree)]
594
+ .map((dir) => path.join(config, "projects", hostProjectName(dir), `${id}.jsonl`))
595
+ .find((candidate) => fs.existsSync(candidate));
596
+ if (!transcript) return null;
597
+ const file = path.join(where.root, "sessions", `${id}.json`);
598
+ try {
599
+ rememberSession(where, role, file);
600
+ store.writeJsonAtomic(where, file, { ...store.readJsonFile(file), decided: true, host_run: false });
601
+ } catch {
602
+ return null;
603
+ }
604
+ touchPresence(where, role, "online", "claude-code", { source: "role-set" });
605
+ recordSegment(where, role, transcript);
606
+ return `Recorded this session (${id.slice(0, 8)}) as ${role}'s, so \`keel chat wake now ${role}\` resumes it.`;
607
+ }
608
+
509
609
  function hook(event, input, { mail = false } = {}) {
510
610
  if (!(event in HOST_EVENTS)) return { code: 0 };
511
611
  let payload = {};
@@ -517,7 +617,7 @@ function hook(event, input, { mail = false } = {}) {
517
617
  let where = null;
518
618
  let role = null;
519
619
  try {
520
- where = store.locate(payload.cwd || process.cwd());
620
+ where = hookLocation(payload);
521
621
  role = where ? store.currentRole(where) : null;
522
622
  } catch {
523
623
  role = null;
@@ -616,4 +716,6 @@ module.exports = {
616
716
  presenceOf,
617
717
  signalPath,
618
718
  touchPresence,
719
+ commandPresence,
720
+ recordBinding,
619
721
  };