@christang/keel 5.190.0 → 5.192.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.
@@ -0,0 +1,31 @@
1
+ // Markdown parsing and SVG raster fallback, using local dependencies only.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { pathToFileURL } from 'node:url';
6
+ const root = process.env.MD2WORD_NODE_MODULES;
7
+ const req = root ? createRequire(path.join(root, '__md2word.cjs')) : createRequire(import.meta.url);
8
+ const input = JSON.parse(await new Promise((resolve) => {
9
+ let data = ''; process.stdin.setEncoding('utf8');
10
+ process.stdin.on('data', chunk => data += chunk);
11
+ process.stdin.on('end', () => resolve(data));
12
+ }));
13
+ try {
14
+ if (input.action === 'parse') {
15
+ const { marked } = await import(pathToFileURL(req.resolve('marked')).href);
16
+ process.stdout.write(JSON.stringify(marked.lexer(input.markdown, { gfm: true })));
17
+ } else if (input.action === 'svg') {
18
+ const sharp = req('sharp');
19
+ if (/<(?:\w+:)?foreignObject\b/i.test(input.svg)) {
20
+ throw new Error('SVG contains foreignObject HTML labels; convert these labels to SVG text or paths first.');
21
+ }
22
+ const output = await sharp(Buffer.from(input.svg), { density: 192, limitInputPixels: 64000000 })
23
+ .resize({ width: 2000, height: 2200, fit: 'inside', withoutEnlargement: false })
24
+ .png().toBuffer();
25
+ await fs.writeFile(input.output, output);
26
+ const metadata = await sharp(output).metadata();
27
+ process.stdout.write(JSON.stringify({ width: metadata.width, height: metadata.height }));
28
+ } else throw new Error('Unknown action');
29
+ } catch (error) {
30
+ console.error(error.message); process.exitCode = 1;
31
+ }
@@ -222,6 +222,8 @@ MUTATING_KEEL_COMMANDS = (
222
222
  "--clear",
223
223
  "--update",
224
224
  "--with-git-hooks",
225
+ # Installs into, and writes from, the Keel-managed environment (#405).
226
+ "docx",
225
227
  )
226
228
 
227
229
 
@@ -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.190.0"
38
+ PACKAGE_VERSION = "5.192.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.190.0"
41
+ PROTOCOL_VERSION = "5.192.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
 
@@ -463,6 +464,8 @@ SCENARIOS: tuple = (
463
464
  ("patrol-host-task", shift.validate_patrol_host_task_scenario),
464
465
  ("patrol-rearm", shift.validate_patrol_rearm_scenario),
465
466
  ("patrol-issue-routing", shift.validate_patrol_issue_routing_scenario),
467
+ ("patrol-issue-label-sets", shift.validate_patrol_issue_label_sets_scenario),
468
+ ("patrol-issue-label-set-unreadable", shift.validate_patrol_issue_label_set_unreadable_scenario),
466
469
  ("chat-listen-only", chat.validate_chat_listen_only_scenario),
467
470
  ("chat-summary", chat.validate_chat_summary_scenario),
468
471
  ("worktree-overview", shift.validate_worktree_overview_scenario),
@@ -639,4 +642,8 @@ SCENARIOS: tuple = (
639
642
  "a-count-is-derived-from-what-it-counts",
640
643
  docs.validate_a_count_is_derived_from_what_it_counts_scenario,
641
644
  ),
645
+ ("docx-skill-ships", export.validate_docx_skill_ships_scenario),
646
+ ("docx-setup-asks-first", export.validate_docx_setup_asks_first_scenario),
647
+ ("docx-convert-refuses-first", export.validate_docx_convert_refuses_first_scenario),
648
+ ("docx-converts-markdown-with-svg", export.validate_docx_converts_markdown_with_svg_scenario),
642
649
  )
@@ -1070,6 +1070,78 @@ def validate_patrol_issue_routing_scenario() -> int:
1070
1070
  return 0
1071
1071
 
1072
1072
 
1073
+ def issue_label_scratch(base: Path, config: str) -> tuple[Path, dict, dict[str, Path]]:
1074
+ """`rtl` patrols; `design-iecc`, `design-rmw`, and `flow` each have a worktree."""
1075
+ rtl, _verify, env = chat_scratch_group(base)
1076
+ worktrees = {}
1077
+ for role in ("design-iecc", "design-rmw", "flow"):
1078
+ worktrees[role] = chat_worktree(rtl, base / role)
1079
+ run_keel(worktrees[role], "chat", "role", "--set", role, env=env)
1080
+ write_authorize_config(rtl, config)
1081
+ return rtl, env, worktrees
1082
+
1083
+
1084
+ def issue_notices(worktree: Path, env: dict, number: int) -> int:
1085
+ unread = chat_json(run_keel(worktree, "chat", "unread", "--json", env=env)).get("unread", [])
1086
+ return sum(1 for record in unread if f"#{number} " in record.get("text", "") or f"#{number}:" in record.get("text", ""))
1087
+
1088
+
1089
+ def validate_patrol_issue_label_sets_scenario() -> int:
1090
+ """Issue #433: a route keyed on a set of labels refines a single-label one.
1091
+
1092
+ An issue carrying `design` and `dmc_rmw` reaches the `design + dmc_rmw`
1093
+ role and not the `design` role; a route that is not nested still sends.
1094
+ """
1095
+ label = "patrol-issue-label-sets:"
1096
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-label-sets-") as raw:
1097
+ base = Path(raw)
1098
+ rtl, env, worktrees = issue_label_scratch(
1099
+ base, "issue_roles:\n design: design-iecc\n design + dmc_rmw: design-rmw\n flow: flow\n")
1100
+ issues = base / "issues.json"
1101
+ issues.write_text(json.dumps([
1102
+ {"number": 160, "title": "rmw ecc path", "state": "OPEN",
1103
+ "labels": [{"name": "design"}, {"name": "dmc_rmw"}, {"name": "flow"}], "updatedAt": "2026-10-21T01:00:00Z"},
1104
+ {"number": 161, "title": "iecc ecc path", "state": "OPEN",
1105
+ "labels": [{"name": "design"}], "updatedAt": "2026-10-21T01:00:00Z"},
1106
+ ]), encoding="utf-8")
1107
+ run = run_keel(rtl, "patrol", "--issues", str(issues), env=env)
1108
+ if run.returncode != 3:
1109
+ report(f"{label} patrol exited {run.returncode}, not 3: {run.stdout} {run.stderr}")
1110
+ return 1
1111
+ expected = (("design-rmw", 160, 1), ("flow", 160, 1), ("design-iecc", 160, 0),
1112
+ ("design-iecc", 161, 1), ("design-rmw", 161, 0))
1113
+ for role, number, want in expected:
1114
+ got = issue_notices(worktrees[role], env, number)
1115
+ if got != want:
1116
+ report(f"{label} {role} has {got} notices about #{number}, not {want}.")
1117
+ return 1
1118
+ report("patrol-issue-label-sets scenario passed.")
1119
+ return 0
1120
+
1121
+
1122
+ def validate_patrol_issue_label_set_unreadable_scenario() -> int:
1123
+ """Issue #433: a set with an empty or repeated label is reported and routes nothing."""
1124
+ label = "patrol-issue-label-set-unreadable:"
1125
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-label-set-bad-") as raw:
1126
+ base = Path(raw)
1127
+ rtl, env, worktrees = issue_label_scratch(
1128
+ base, "issue_roles:\n design + : design-rmw\n design + design: design-rmw\n")
1129
+ issues = base / "issues.json"
1130
+ issues.write_text(json.dumps([{"number": 162, "title": "ecc", "state": "OPEN",
1131
+ "labels": [{"name": "design"}], "updatedAt": "2026-10-21T01:00:00Z"}]), encoding="utf-8")
1132
+ run = run_keel(rtl, "patrol", "--issues", str(issues), env=env)
1133
+ for line in ("design + : design-rmw", "design + design: design-rmw"):
1134
+ if f"`{line}`" not in run.stdout:
1135
+ report(f"{label} the unreadable line `{line}` is not reported: {run.stdout!r}")
1136
+ return 1
1137
+ got = issue_notices(worktrees["design-rmw"], env, 162)
1138
+ if got:
1139
+ report(f"{label} design-rmw has {got} notices about #162 from unreadable lines.")
1140
+ return 1
1141
+ report("patrol-issue-label-set-unreadable scenario passed.")
1142
+ return 0
1143
+
1144
+
1073
1145
  def validate_worktree_overview_scenario() -> int:
1074
1146
  """Read every worktree through the CLI without fetching or changing chat."""
1075
1147
  label = "worktree-overview:"
@@ -918,11 +918,15 @@ function readReadOnlyRoles(repo) {
918
918
 
919
919
  // `issue_roles:` — which chat role an issue label routes to (#242), one
920
920
  // `<label>: <role>` per line, read by `keel patrol`. A label may itself hold a
921
- // colon (`role:verify`), so the role is what follows the last `: `. A line
922
- // that is not that shape is reported and routes nothing.
921
+ // colon (`role:verify`), so the role is what follows the last `: `. A key may
922
+ // name a set of labels joined by ` + ` (#433), which matches an issue carrying
923
+ // all of them; a quoted key is one label and is not split. A line that is not
924
+ // that shape, or a set with an empty or repeated label, is reported and routes
925
+ // nothing. Routes come back in declaration order, a repeated set replacing the
926
+ // earlier line.
923
927
  function readIssueRoles(repo) {
924
928
  const block = configBlockLines(repo, "issue_roles");
925
- const routes = new Map();
929
+ const routes = [];
926
930
  const unreadable = [];
927
931
  if (block === null) return { routes, unreadable };
928
932
  if (block.inline !== null) unreadable.push(block.inline);
@@ -934,7 +938,16 @@ function readIssueRoles(repo) {
934
938
  unreadable.push(text);
935
939
  continue;
936
940
  }
937
- routes.set(match[1].replace(/^["']|["']$/g, ""), match[2]);
941
+ const quoted = /^(["']).*\1$/.test(match[1]);
942
+ const labels = quoted ? [match[1].slice(1, -1)] : match[1].split(/\s+\+(?:\s+|$)/).map((label) => label.trim());
943
+ if (labels.some((label) => !label) || new Set(labels).size !== labels.length) {
944
+ unreadable.push(text);
945
+ continue;
946
+ }
947
+ const key = [...labels].sort().join("\n");
948
+ const earlier = routes.findIndex((route) => [...route.labels].sort().join("\n") === key);
949
+ if (earlier !== -1) routes.splice(earlier, 1);
950
+ routes.push({ labels, role: match[2] });
938
951
  }
939
952
  return { routes, unreadable };
940
953
  }