@christang/keel 5.189.0 → 5.191.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.
@@ -351,6 +351,43 @@ def validate_chat_hook_follows_session_worktree_scenario() -> int:
351
351
  if "sess-v" in chat_session_list(rtl, "rtl"):
352
352
  report(f"{label} rtl's session list took the resumed session: {chat_session_list(rtl, 'rtl')!r}")
353
353
  return 1
354
+
355
+ # #441, measured on Claude Code 2.1.304 (2026-10-21): on resume the host
356
+ # reports the launch directory for `transcript_path` too, naming a file that
357
+ # does not exist; the session keeps writing its transcript in the project
358
+ # directory of the worktree it runs in.
359
+ with tempfile.TemporaryDirectory(prefix="keel-chat-441-") as raw:
360
+ base = Path(raw)
361
+ rtl, verify, env = chat_scratch_group(base)
362
+ config = base / "claude-config"
363
+ env = {**env, "CLAUDE_CONFIG_DIR": str(config)}
364
+ chat_session_start(rtl, env, "sess-r", os.getpid())
365
+ real = config / "projects" / host_project_name(verify) / "sess-w.jsonl"
366
+ write_text(real, json.dumps({"type": "user", "message": {"role": "user", "content": "carry on"}}) + "\n")
367
+ reported = config / "projects" / host_project_name(rtl) / "sess-w.jsonl"
368
+ started = chat_session_start(rtl, env, "sess-w", os.getpid(), source="resume", transcript=reported)
369
+ try:
370
+ watched = json.loads(started.stdout)["hookSpecificOutput"]["watchPaths"]
371
+ except (ValueError, KeyError, TypeError):
372
+ report(f"{label} the measured resume payload printed no watch paths: {started.stdout!r} {started.stderr!r}")
373
+ return 1
374
+ if not any(path.endswith("/signal/verify") for path in watched):
375
+ report(f"{label} a resumed -w session whose reported transcript does not exist watches {watched!r}, not verify's signal.")
376
+ return 1
377
+ if any(path.endswith("/signal/rtl") for path in watched):
378
+ report(f"{label} a resumed -w session whose reported transcript does not exist also watches rtl's signal: {watched!r}")
379
+ return 1
380
+ if chat_session_record(rtl, "sess-w").get("role") != "verify":
381
+ report(f"{label} the measured resume was recorded as {chat_session_record(rtl, 'sess-w').get('role')!r}, not verify.")
382
+ return 1
383
+ if chat_presence(rtl, "rtl").get("cli_session") != "sess-r":
384
+ report(f"{label} rtl's presence took the measured resume: {chat_presence(rtl, 'rtl')!r}")
385
+ return 1
386
+ segments_file = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "segments" / "verify.json"
387
+ segments = json.loads(segments_file.read_text(encoding="utf-8")).get("segments", []) if segments_file.is_file() else []
388
+ if not segments or os.path.realpath(segments[-1].get("transcript") or "") != os.path.realpath(real):
389
+ report(f"{label} the resumed session's segment names {segments!r}, not the transcript that exists ({real}).")
390
+ return 1
354
391
  if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
355
392
  report(f"{label} the scenario registry does not include it.")
356
393
  return 1
@@ -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.189.0"
38
+ PACKAGE_VERSION = "5.191.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.189.0"
41
+ PROTOCOL_VERSION = "5.191.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -0,0 +1,449 @@
1
+ """Keel validation: export — Markdown with SVG to Word (#405)."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ from validation.common import (
14
+ ROOT,
15
+ report,
16
+ write_text,
17
+ )
18
+ from validation import registry
19
+
20
+
21
+ DOCX_SKILL = "keel-md-docx"
22
+ DOCX_SCRIPTS = ("md2word.py", "runtime.mjs", "fonts-macos.conf", "requirements.txt", "package.json")
23
+ # The SHA-256 #405 states for the prototype files that ship unchanged.
24
+ DOCX_PROTOTYPE_SUMS = {
25
+ "md2word.py": "73331af530b524eeafe465a9d50bc6434d64abadc2f64e2140826a68b9a1bd1f",
26
+ "runtime.mjs": "7fa52c333d16f92bb2c7eb54ad5c5e25d04ee71c13f2501927fd53492eb381a2",
27
+ }
28
+ DOCX_LICENCES = {
29
+ "python-docx": "MIT",
30
+ "lxml": "BSD-3-Clause",
31
+ "Pillow": "MIT-CMU",
32
+ "marked": "MIT",
33
+ "sharp": "Apache-2.0",
34
+ }
35
+
36
+
37
+ # One stand-in for the interpreter Keel resolves, the environment's own Python,
38
+ # and npm. Each call appends `[role, ...argv]` to FAKE_LOG. `-m venv DIR`
39
+ # creates DIR's interpreter as another launcher of this file in the role
40
+ # `venv`; FAKE_PIP_EXIT and FAKE_NPM_EXIT make those steps fail; FAKE_CONVERT
41
+ # makes the venv Python act as the converter, writing its `-o` target and
42
+ # recording its environment.
43
+ DOCX_FAKE = r"""const fs = require("fs");
44
+ const path = require("path");
45
+ const role = process.env.FAKE_ROLE;
46
+ const args = process.argv.slice(2);
47
+ fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify([role, ...args]) + "\n");
48
+ if (args[0] === "--version") { process.stdout.write("Python 3.12.0\n"); process.exit(0); }
49
+ if (role === "python" && args[0] === "-m" && args[1] === "venv") {
50
+ const bin = path.join(args[2], process.platform === "win32" ? "Scripts" : "bin");
51
+ fs.mkdirSync(bin, { recursive: true });
52
+ const launcher = path.join(bin, "python");
53
+ fs.writeFileSync(launcher, `#!/bin/sh\nFAKE_ROLE=venv exec node "${__filename}" "$@"\n`);
54
+ fs.chmodSync(launcher, 0o755);
55
+ process.exit(0);
56
+ }
57
+ if (role === "venv" && args[0] === "-m" && args[1] === "pip") process.exit(Number(process.env.FAKE_PIP_EXIT || 0));
58
+ if (role === "venv" && process.env.FAKE_CONVERT) {
59
+ const output = args[args.indexOf("-o") + 1];
60
+ fs.writeFileSync(output, "converted\n");
61
+ fs.writeFileSync(process.env.FAKE_CONVERT, JSON.stringify({
62
+ MD2WORD_NODE: process.env.MD2WORD_NODE || null,
63
+ MD2WORD_NODE_MODULES: process.env.MD2WORD_NODE_MODULES || null,
64
+ }));
65
+ process.exit(Number(process.env.FAKE_CONVERT_EXIT || 0));
66
+ }
67
+ if (role === "npm") {
68
+ const code = Number(process.env.FAKE_NPM_EXIT || 0);
69
+ if (code === 0) fs.mkdirSync(path.join(args[args.indexOf("--prefix") + 1], "node_modules"), { recursive: true });
70
+ process.exit(code);
71
+ }
72
+ process.exit(0);
73
+ """
74
+
75
+
76
+ def docx_fakes(tmp: Path) -> dict[str, str]:
77
+ """The environment that points `keel docx` at the stand-ins and a scratch KEEL_HOME."""
78
+ fake = tmp / "docx-fake.js"
79
+ write_text(fake, DOCX_FAKE)
80
+ env = dict(os.environ)
81
+ for role in ("python", "npm"):
82
+ launcher = tmp / f"fake-{role}"
83
+ write_text(launcher, f'#!/bin/sh\nFAKE_ROLE={role} exec node "{fake}" "$@"\n')
84
+ launcher.chmod(0o755)
85
+ env.update({
86
+ "KEEL_HOME": str(tmp / "home"),
87
+ "KEEL_PYTHON": str(tmp / "fake-python"),
88
+ "KEEL_DOCX_NPM": str(tmp / "fake-npm"),
89
+ "FAKE_LOG": str(tmp / "log.jsonl"),
90
+ })
91
+ (tmp / "log.jsonl").write_text("")
92
+ return env
93
+
94
+
95
+ def run_docx(tmp: Path, env: dict[str, str], *args: str) -> subprocess.CompletedProcess[str]:
96
+ return subprocess.run(
97
+ ["node", str(ROOT / "bin/keel.js"), "docx", *args],
98
+ cwd=tmp, env=env, text=True, encoding="utf-8", errors="replace",
99
+ capture_output=True, check=False, timeout=60,
100
+ )
101
+
102
+
103
+ def fake_calls(tmp: Path) -> list[list[str]]:
104
+ lines = (tmp / "log.jsonl").read_text().splitlines()
105
+ return [json.loads(line) for line in lines if line.strip()]
106
+
107
+
108
+ def validate_docx_setup_asks_first_scenario() -> int:
109
+ """Issue #405: nothing is installed until the user has seen the list and said yes."""
110
+ label = "docx-setup-asks-first:"
111
+ with tempfile.TemporaryDirectory(prefix="keel-405-setup-") as raw:
112
+ tmp = Path(raw)
113
+ env = docx_fakes(tmp)
114
+ home = tmp / "home/docx"
115
+
116
+ plan = run_docx(tmp, env, "setup")
117
+ said = plan.stdout + plan.stderr
118
+ if plan.returncode != 0:
119
+ report(f"{label} `keel docx setup` without --yes exited {plan.returncode}: {said!r}")
120
+ return 1
121
+ for needle in (*DOCX_LICENCES, *DOCX_LICENCES.values(), str(home), "--yes"):
122
+ if needle not in said:
123
+ report(f"{label} the setup plan does not name {needle!r}: {said!r}")
124
+ return 1
125
+ if fake_calls(tmp):
126
+ report(f"{label} the setup plan ran an installer or probe: {fake_calls(tmp)!r}")
127
+ return 1
128
+ if home.exists():
129
+ report(f"{label} the setup plan created {home}.")
130
+ return 1
131
+
132
+ installed = run_docx(tmp, env, "setup", "--yes")
133
+ said = installed.stdout + installed.stderr
134
+ if installed.returncode != 0:
135
+ report(f"{label} `keel docx setup --yes` exited {installed.returncode}: {said!r}")
136
+ return 1
137
+ steps = [call for call in fake_calls(tmp) if call[1:2] != ["--version"]]
138
+ requirements = ROOT / "plugins/keel/skills" / DOCX_SKILL / "scripts/requirements.txt"
139
+ expected = [
140
+ ["python", "-m", "venv", str(home / "python")],
141
+ ["venv", "-m", "pip", "install", "-r", str(requirements)],
142
+ ["npm", "install", "--prefix", str(home / "node")],
143
+ ]
144
+ got = [call[:len(want)] for call, want in zip(steps, expected)]
145
+ if got != expected or len(steps) != len(expected):
146
+ report(f"{label} setup --yes did not create the venv, pip-install the requirements, and npm-install into the environment, in order: {steps!r}")
147
+ return 1
148
+ if not (home / "node/package.json").is_file():
149
+ report(f"{label} setup --yes did not place the pinned package.json in {home / 'node'}.")
150
+ return 1
151
+ if not (home / "ready.json").is_file():
152
+ report(f"{label} a successful setup did not mark the environment ready.")
153
+ return 1
154
+
155
+ failing = dict(env, FAKE_NPM_EXIT="1")
156
+ broken = run_docx(tmp, failing, "setup", "--yes")
157
+ said = broken.stdout + broken.stderr
158
+ if broken.returncode != 1:
159
+ report(f"{label} a failed npm step exited {broken.returncode}, not 1: {said!r}")
160
+ return 1
161
+ if "npm" not in said:
162
+ report(f"{label} a failed npm step is not named: {said!r}")
163
+ return 1
164
+ if (home / "ready.json").exists():
165
+ report(f"{label} a failed setup left the environment marked ready.")
166
+ return 1
167
+
168
+ if "docx-setup-asks-first" not in {name for name, _ in registry.SCENARIOS}:
169
+ report(f"{label} the scenario registry does not include it.")
170
+ return 1
171
+ report("docx-setup-asks-first scenario passed.")
172
+ return 0
173
+
174
+
175
+ def validate_docx_convert_refuses_first_scenario() -> int:
176
+ """Issue #405: convert refuses rather than overwrites, and hands a ready environment the converter."""
177
+ label = "docx-convert-refuses-first:"
178
+ with tempfile.TemporaryDirectory(prefix="keel-405-convert-") as raw:
179
+ tmp = Path(raw)
180
+ env = docx_fakes(tmp)
181
+ source = tmp / "in.md"
182
+ target = tmp / "in.docx"
183
+ write_text(source, "# 标题\n\n<svg xmlns=\"http://www.w3.org/2000/svg\"/>\n")
184
+
185
+ before = run_docx(tmp, env, "convert", "in.md")
186
+ said = before.stdout + before.stderr
187
+ if before.returncode == 0:
188
+ report(f"{label} convert before setup exited 0: {said!r}")
189
+ return 1
190
+ if "run `keel docx setup`" not in said:
191
+ report(f"{label} convert before setup does not say to run `keel docx setup`: {said!r}")
192
+ return 1
193
+ if target.exists():
194
+ report(f"{label} convert before setup wrote {target.name}.")
195
+ return 1
196
+
197
+ if run_docx(tmp, env, "setup", "--yes").returncode != 0:
198
+ report(f"{label} the stand-in setup failed, so the ready environment could not be built.")
199
+ return 1
200
+ record = tmp / "converter-env.json"
201
+ env = dict(env, FAKE_CONVERT=str(record))
202
+
203
+ target.write_bytes(b"previous output")
204
+ kept = run_docx(tmp, env, "convert", "in.md")
205
+ said = kept.stdout + kept.stderr
206
+ if kept.returncode == 0:
207
+ report(f"{label} an existing output without --replace exited 0: {said!r}")
208
+ return 1
209
+ if "--replace" not in said:
210
+ report(f"{label} an existing output's refusal does not name --replace: {said!r}")
211
+ return 1
212
+ if target.read_bytes() != b"previous output":
213
+ report(f"{label} an existing output was changed without --replace.")
214
+ return 1
215
+ for case, args in (("a missing input", ("convert", "nope.md")),
216
+ ("an output that is the input", ("convert", "in.md", "-o", "in.md")),
217
+ ("a missing template", ("convert", "in.md", "-o", "x.docx", "--template", "none.docx"))):
218
+ refused = run_docx(tmp, env, *args)
219
+ if refused.returncode == 0:
220
+ report(f"{label} {case} was not refused: {refused.stdout + refused.stderr!r}")
221
+ return 1
222
+ if any(call[0] == "venv" and "md2word.py" in " ".join(call) for call in fake_calls(tmp)):
223
+ report(f"{label} a refused conversion still ran the converter: {fake_calls(tmp)!r}")
224
+ return 1
225
+
226
+ replaced = run_docx(tmp, env, "convert", "in.md", "--replace")
227
+ said = replaced.stdout + replaced.stderr
228
+ if replaced.returncode != 0:
229
+ report(f"{label} convert --replace with a ready environment exited {replaced.returncode}: {said!r}")
230
+ return 1
231
+ converter = str(ROOT / "plugins/keel/skills" / DOCX_SKILL / "scripts/md2word.py")
232
+ runs = [call[1:] for call in fake_calls(tmp) if call[0] == "venv" and converter in call]
233
+ if runs[-1:] != [[converter, str(source.resolve()), "-o", str(target.resolve())]]:
234
+ report(f"{label} the environment's Python did not run the shipped converter on the input and output: {runs!r}")
235
+ return 1
236
+ handed = json.loads(record.read_text())
237
+ if not handed.get("MD2WORD_NODE"):
238
+ report(f"{label} the converter was not given MD2WORD_NODE: {handed!r}")
239
+ return 1
240
+ if handed.get("MD2WORD_NODE_MODULES") != str(tmp / "home/docx/node/node_modules"):
241
+ report(f"{label} the converter was not given the environment's node_modules: {handed!r}")
242
+ return 1
243
+
244
+ write_text(tmp / "t.docx", "template")
245
+ templated = run_docx(tmp, env, "convert", "in.md", "-o", "out.docx", "--template", "t.docx")
246
+ runs = [call[1:] for call in fake_calls(tmp) if call[0] == "venv" and converter in call]
247
+ if templated.returncode != 0:
248
+ report(f"{label} convert --template exited {templated.returncode}: {templated.stdout + templated.stderr!r}")
249
+ return 1
250
+ if runs[-1][-2:] != ["--template", str((tmp / "t.docx").resolve())]:
251
+ report(f"{label} --template did not reach the converter: {runs[-1:]!r}")
252
+ return 1
253
+
254
+ failing = run_docx(tmp, dict(env, FAKE_CONVERT_EXIT="1"), "convert", "in.md", "-o", "fail.docx")
255
+ if failing.returncode != 1:
256
+ report(f"{label} a failing converter's status 1 was not returned: exit={failing.returncode}")
257
+ return 1
258
+
259
+ if "docx-convert-refuses-first" not in {name for name, _ in registry.SCENARIOS}:
260
+ report(f"{label} the scenario registry does not include it.")
261
+ return 1
262
+ report("docx-convert-refuses-first scenario passed.")
263
+ return 0
264
+
265
+
266
+ DOCX_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50"><rect width="100" height="50" fill="blue"/></svg>'
267
+ DOCX_NAMESPACES = {
268
+ "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
269
+ "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",
270
+ "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
271
+ }
272
+
273
+
274
+ def validate_docx_converts_markdown_with_svg_scenario() -> int:
275
+ """Issue #405: the prototype's conversion checks, against a provisioned environment.
276
+
277
+ The third-party packages are an external runtime the suite does not
278
+ install, so this runs only when KEEL_DOCX_TEST_ENV names a KEEL_HOME whose
279
+ `docx/` environment is ready, and otherwise reports itself skipped. It never
280
+ reads the user's own ~/.keel.
281
+ """
282
+ import xml.etree.ElementTree as ElementTree
283
+ from zipfile import ZipFile
284
+
285
+ label = "docx-converts-markdown-with-svg:"
286
+ provided = os.environ.get("KEEL_DOCX_TEST_ENV", "")
287
+ if not provided or not (Path(provided) / "docx/ready.json").is_file():
288
+ report(f"{label} skipped: no ready docx environment; set KEEL_DOCX_TEST_ENV to a KEEL_HOME where `keel docx setup --yes` has run.")
289
+ return 3
290
+ env = dict(os.environ, KEEL_HOME=provided)
291
+ with tempfile.TemporaryDirectory(prefix="keel-405-real-") as raw:
292
+ tmp = Path(raw)
293
+
294
+ def convert(markdown: str, *extra: str) -> subprocess.CompletedProcess[str]:
295
+ write_text(tmp / "input.md", markdown)
296
+ return subprocess.run(
297
+ ["node", str(ROOT / "bin/keel.js"), "docx", "convert", "input.md", "-o", "output.docx", *extra],
298
+ cwd=tmp, env=env, text=True, encoding="utf-8", errors="replace",
299
+ capture_output=True, check=False, timeout=180,
300
+ )
301
+
302
+ write_text(tmp / "images/图.svg", DOCX_SVG)
303
+ made = convert(
304
+ "# 中文标题\n\n" + DOCX_SVG + "\n\n```svg\n" + DOCX_SVG + "\n```\n\n"
305
+ "![中文图片](images/图.svg)\n\n"
306
+ "行内代码 `<svg>not a figure</svg>` 保留为代码。\n\n"
307
+ "```python\ntext = \"<svg>leave as code</svg>\"\n```\n\n"
308
+ "| 项目 | 值 |\n|---|---|\n| 中文 | 123 |\n"
309
+ )
310
+ if made.returncode != 0:
311
+ report(f"{label} the three SVG forms did not convert: {made.stderr!r}")
312
+ return 1
313
+ with ZipFile(tmp / "output.docx") as archive:
314
+ document = ElementTree.fromstring(archive.read("word/document.xml"))
315
+ names = archive.namelist()
316
+ vectors = document.findall(".//asvg:svgBlip", DOCX_NAMESPACES)
317
+ if len(vectors) != 3:
318
+ report(f"{label} {len(vectors)} SVG images were embedded, not 3.")
319
+ return 1
320
+ if len([n for n in names if n.endswith(".svg")]) != 3:
321
+ report(f"{label} the package does not hold three SVG parts: {names!r}")
322
+ return 1
323
+ if not any(n.endswith(".png") for n in names):
324
+ report(f"{label} no PNG fallback was embedded: {names!r}")
325
+ return 1
326
+ text = "".join(document.itertext())
327
+ for needle in ("中文标题", "leave as code", "not a figure"):
328
+ if needle not in text:
329
+ report(f"{label} the document text lacks {needle!r}.")
330
+ return 1
331
+ if len(document.findall(".//w:tbl", DOCX_NAMESPACES)) != 1:
332
+ report(f"{label} the table did not convert.")
333
+ return 1
334
+ for extent in document.findall(".//wp:extent", DOCX_NAMESPACES):
335
+ if int(extent.get("cx")) > 6120635:
336
+ report(f"{label} an image is wider than the page: {extent.attrib!r}")
337
+ return 1
338
+ if int(extent.get("cy")) > 8900000:
339
+ report(f"{label} an image is taller than the page: {extent.attrib!r}")
340
+ return 1
341
+
342
+ (tmp / "output.docx").write_bytes(b"previous output")
343
+ bad = convert("```svg\n<svg><invalid></svg>\n```\n", "--replace")
344
+ if bad.returncode == 0:
345
+ report(f"{label} an invalid SVG converted: {bad.stderr!r}")
346
+ return 1
347
+ if "Conversion failed" not in bad.stderr:
348
+ report(f"{label} an invalid SVG's failure does not say `Conversion failed`: {bad.stderr!r}")
349
+ return 1
350
+ if (tmp / "output.docx").read_bytes() != b"previous output":
351
+ report(f"{label} a failed conversion changed the previous output.")
352
+ return 1
353
+ (tmp / "output.docx").unlink()
354
+ for case, markdown, needle in (
355
+ ("a missing image", "![missing](does-not-exist.svg)\n", "Conversion failed"),
356
+ ("a remote image", "![remote](https://example.com/diagram.svg)\n", "save it locally first"),
357
+ ("a foreignObject label",
358
+ DOCX_SVG.replace("</svg>", '<foreignObject width="20" height="20"><div>label</div></foreignObject></svg>') + "\n",
359
+ "text/path labels"),
360
+ ):
361
+ failed = convert(markdown)
362
+ if failed.returncode == 0:
363
+ report(f"{label} {case} converted: {failed.stderr!r}")
364
+ return 1
365
+ if needle not in failed.stderr:
366
+ report(f"{label} {case}'s failure does not say {needle!r}: {failed.stderr!r}")
367
+ return 1
368
+ if (tmp / "output.docx").exists():
369
+ report(f"{label} {case} left an output.")
370
+ return 1
371
+ marker = DOCX_SVG.replace("<rect", '<defs><marker id="x"/></defs><rect').replace(
372
+ 'fill="blue"', "fill=\"blue\" style=\"marker-end: url(' #x ')\"")
373
+ quoted = convert(marker + "\n")
374
+ if quoted.returncode != 0:
375
+ report(f"{label} a quoted local marker reference did not convert: {quoted.stderr!r}")
376
+ return 1
377
+
378
+ if "docx-converts-markdown-with-svg" not in {name for name, _ in registry.SCENARIOS}:
379
+ report(f"{label} the scenario registry does not include it.")
380
+ return 1
381
+ report("docx-converts-markdown-with-svg scenario passed.")
382
+ return 0
383
+
384
+
385
+ def skill_description(text: str) -> str:
386
+ match = re.search(r"^description:\s*(?:[>|]-?\s*\n((?:[ \t]+.*\n?)+)|(.+))$", text, re.M)
387
+ if not match:
388
+ return ""
389
+ return " ".join((match.group(1) or match.group(2) or "").split())
390
+
391
+
392
+ def validate_docx_skill_ships_scenario() -> int:
393
+ """Issue #405: the plugin carries the export skill and the converter it runs."""
394
+ label = "docx-skill-ships:"
395
+ source = ROOT / "src/skills" / DOCX_SKILL
396
+ shipped = ROOT / "plugins/keel/skills" / DOCX_SKILL
397
+ for relative in ("SKILL.md", *(f"scripts/{name}" for name in DOCX_SCRIPTS)):
398
+ plugin_file = shipped / relative
399
+ if not plugin_file.is_file():
400
+ report(f"{label} the plugin does not ship {DOCX_SKILL}/{relative}.")
401
+ return 1
402
+ source_file = source / relative
403
+ if not source_file.is_file() or source_file.read_bytes() != plugin_file.read_bytes():
404
+ report(f"{label} plugins/keel/skills/{DOCX_SKILL}/{relative} is not byte-identical to src/skills.")
405
+ return 1
406
+ for name, expected in DOCX_PROTOTYPE_SUMS.items():
407
+ actual = hashlib.sha256((shipped / "scripts" / name).read_bytes()).hexdigest()
408
+ if actual != expected:
409
+ report(f"{label} scripts/{name} is not the #405 prototype file: sha256 {actual}, expected {expected}.")
410
+ return 1
411
+
412
+ text = (shipped / "SKILL.md").read_text(encoding="utf-8")
413
+ description = skill_description(text).lower()
414
+ for word in ("markdown", "svg", "word"):
415
+ if word not in description:
416
+ report(f"{label} the description does not name {word!r}, so a request for this export may not load it: {description!r}")
417
+ return 1
418
+ for needle in ("keel docx setup", "--yes", "--replace", "unverified"):
419
+ if needle not in text:
420
+ report(f"{label} SKILL.md does not name {needle!r}.")
421
+ return 1
422
+ for package, licence in DOCX_LICENCES.items():
423
+ if package not in text or licence not in text:
424
+ report(f"{label} SKILL.md does not state {package} and its licence {licence}.")
425
+ return 1
426
+
427
+ evidence_path = ROOT / "keel/archive/skill-evidence" / f"{DOCX_SKILL}-v1.md"
428
+ if not evidence_path.is_file():
429
+ report(f"{label} {evidence_path.relative_to(ROOT)} is missing.")
430
+ return 1
431
+ evidence = evidence_path.read_text(encoding="utf-8")
432
+ positives = re.findall(r"^## Positive case P\d+", evidence, re.M)
433
+ negatives = re.findall(r"^## Negative control N\d+", evidence, re.M)
434
+ if len(positives) < 2:
435
+ report(f"{label} the evidence carries {len(positives)} positive trigger case(s), fewer than 2.")
436
+ return 1
437
+ if len(negatives) < 2:
438
+ report(f"{label} the evidence carries {len(negatives)} negative control(s), fewer than 2.")
439
+ return 1
440
+ for package, licence in DOCX_LICENCES.items():
441
+ if not re.search(rf"^- {re.escape(package)}\b.*{re.escape(licence)}", evidence, re.M):
442
+ report(f"{label} the evidence has no licence line for {package} ({licence}).")
443
+ return 1
444
+
445
+ if "docx-skill-ships" not in {name for name, _ in registry.SCENARIOS}:
446
+ report(f"{label} the scenario registry does not include it.")
447
+ return 1
448
+ report("docx-skill-ships scenario passed.")
449
+ return 0
@@ -789,6 +789,7 @@ PLUGIN_SKILLS = (
789
789
  "keel-align-expectations",
790
790
  "keel-debug-failure",
791
791
  "keel-handoff",
792
+ "keel-md-docx",
792
793
  "keel-review-checklist",
793
794
  "keel-tdd-or-test-first",
794
795
  )
@@ -7,6 +7,7 @@ from validation import chat
7
7
  from validation import shift
8
8
  from validation import docs
9
9
  from validation import selfcheck
10
+ from validation import export
10
11
 
11
12
 
12
13
 
@@ -639,4 +640,8 @@ SCENARIOS: tuple = (
639
640
  "a-count-is-derived-from-what-it-counts",
640
641
  docs.validate_a_count_is_derived_from_what_it_counts_scenario,
641
642
  ),
643
+ ("docx-skill-ships", export.validate_docx_skill_ships_scenario),
644
+ ("docx-setup-asks-first", export.validate_docx_setup_asks_first_scenario),
645
+ ("docx-convert-refuses-first", export.validate_docx_convert_refuses_first_scenario),
646
+ ("docx-converts-markdown-with-svg", export.validate_docx_converts_markdown_with_svg_scenario),
642
647
  )
@@ -546,9 +546,29 @@ function hostProjectName(directory) {
546
546
  // 2026-10-21, Claude Code 2.1.304), while its transcript stays in the host
547
547
  // project directory of the worktree it runs in. When that names another
548
548
  // worktree of this repository, the session is that worktree's.
549
+ // A resumed `claude --bg -w` session reports the launch directory for
550
+ // `transcript_path` as well as `cwd`, naming a file that does not exist; its
551
+ // transcript stays in the project directory of the worktree it runs in
552
+ // (measured on Claude Code 2.1.304, #441). The file that exists is the truth.
553
+ function existingTranscript(payload) {
554
+ const reported = typeof payload.transcript_path === "string" ? payload.transcript_path : "";
555
+ if (path.isAbsolute(reported) && fs.existsSync(reported)) return reported;
556
+ const id = typeof payload.session_id === "string" ? payload.session_id : "";
557
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(id)) return reported;
558
+ const projects = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(require("os").homedir(), ".claude"), "projects");
559
+ let dirs = [];
560
+ try {
561
+ dirs = fs.readdirSync(projects);
562
+ } catch {
563
+ return reported;
564
+ }
565
+ const found = dirs.map((dir) => path.join(projects, dir, `${id}.jsonl`)).find((file) => fs.existsSync(file));
566
+ return found || reported;
567
+ }
568
+
549
569
  function hookLocation(payload) {
550
570
  const where = store.locate(payload.cwd || process.cwd());
551
- const transcript = typeof payload.transcript_path === "string" ? payload.transcript_path : "";
571
+ const transcript = existingTranscript(payload);
552
572
  if (!where || !path.isAbsolute(transcript)) return where;
553
573
  const project = path.basename(path.dirname(transcript));
554
574
  const named = (dir) => [dir, realpathOf(dir)].some((candidate) => hostProjectName(candidate) === project);
@@ -666,7 +686,7 @@ function hook(event, input, { mail = false } = {}) {
666
686
  if (event === "session-start") rememberSession(where, role, file);
667
687
  const started = event === "session-start" ? { source: typeof payload.source === "string" ? payload.source : null } : null;
668
688
  touchPresence(where, role, "online", mail ? null : "claude-code", started);
669
- if (event === "session-start" || event === "user-prompt-submit") recordSegment(where, role, payload.transcript_path);
689
+ if (event === "session-start" || event === "user-prompt-submit") recordSegment(where, role, existingTranscript(payload));
670
690
  const chatText = noticeText(where, role);
671
691
  const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
672
692
  if (event === "session-start") {