zcode-expert-system 3.2.1 → 3.2.2

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,632 +1,707 @@
1
- #!/usr/bin/env python3
2
- """OpenSpec 引擎 —— 内置 CLI(前三个子命令:new-change / status / instructions)。
3
-
4
- 仅使用 Python 3 标准库(json/os/re/sys/argparse/datetime/pathlib),无第三方依赖。
5
- .openspec.yaml 手写/手读简单键值对,不依赖第三方 YAML 库。
6
- LF 行尾,pathlib 跨平台路径。
7
- """
8
-
9
- import argparse
10
- import json
11
- import os
12
- import re
13
- import shutil
14
- import sys
15
- from datetime import date, datetime
16
- from pathlib import Path
17
-
18
- # 四件产物及其在 change 目录下的相对路径(按 OpenSpec/S2 规格)
19
- PRODUCTS = {
20
- "proposal": "proposal.md",
21
- "design": "design.md",
22
- "tasks": "tasks.md",
23
- "specs": "specs",
24
- }
25
-
26
-
27
- def change_dir(root: Path, name: str) -> Path:
28
- # 库模式抛 ValueError(调用方自行处置);6 个 CLI 入口捕获后转
29
- # 「error: ... + return 1」,进程退出码语义不变——勿在库函数里
30
- # sys.exit,那会以 SystemExit 炸宿主进程。
31
- if name == "archive":
32
- raise ValueError("'archive' is a reserved container name, not a change")
33
- return root / "openspec" / "changes" / name
34
-
35
-
36
- def write_metadata(cdir: Path, name: str) -> None:
37
- """手写 .openspec.yaml,简单键值对,LF 行尾。"""
38
- lines = [
39
- "schema: spec-driven",
40
- f"name: {name}",
41
- f"created: {date.today().isoformat()}",
42
- "status: pending",
43
- ]
44
- (cdir / ".openspec.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")
45
-
46
-
47
- def write_status(cdir: Path, status: dict) -> None:
48
- """手写 .status.json,简单 JSON,LF 行尾。"""
49
- (cdir / ".status.json").write_text(
50
- json.dumps(status, ensure_ascii=False, indent=2),
51
- encoding="utf-8",
52
- )
53
-
54
-
55
- def cmd_new_change(args) -> int:
56
- root = Path(args.root).resolve()
57
- try:
58
- cdir = change_dir(root, args.name)
59
- except ValueError as exc:
60
- print(f"error: {exc}", file=sys.stderr)
61
- return 1
62
- if cdir.exists():
63
- print(f"error: change already exists: {cdir}", file=sys.stderr)
64
- return 1
65
- cdir.mkdir(parents=True, exist_ok=True)
66
- (cdir / "specs").mkdir(exist_ok=True)
67
- write_metadata(cdir, args.name)
68
- write_status(cdir, {
69
- "tasksCompleted": False,
70
- "specsConsistent": False,
71
- "testsPassed": False,
72
- "reviewPassed": False,
73
- "noBlockers": True,
74
- "gitStatusOk": True,
75
- "docsUpdated": True,
76
- "parked": False,
77
- })
78
- print(f"change created: {cdir}")
79
- return 0
80
-
81
-
82
- def product_state(cdir: Path, product: str) -> str:
83
- """状态只判文件是否存在(OpenSpec:status 只判文件存在,别被 done 误导)。"""
84
- rel = PRODUCTS[product]
85
- target = cdir / rel
86
- if product == "specs":
87
- # 空的 specs/ 子目录不算产物就绪;只有包含具体 spec 时才为 done
88
- return "done" if (target.is_dir() and any(target.iterdir())) else "pending"
89
- return "done" if target.is_file() else "pending"
90
-
91
-
92
- def cmd_status(args) -> int:
93
- root = Path(args.root).resolve()
94
- try:
95
- cdir = change_dir(root, args.change)
96
- except ValueError as exc:
97
- print(f"error: {exc}", file=sys.stderr)
98
- return 1
99
- if not cdir.exists():
100
- print(f"error: change not found: {cdir}", file=sys.stderr)
101
- return 1
102
- products = {name: product_state(cdir, name) for name in PRODUCTS}
103
- result = {
104
- "change": args.change,
105
- "status": "pending",
106
- "products": products,
107
- "applyRequires": [],
108
- "requires": [],
109
- "artifactPaths": {},
110
- }
111
- # 从 .openspec.yaml 读取 requires 元数据(如果存在)
112
- meta_path = cdir / ".openspec.yaml"
113
- if meta_path.is_file():
114
- try:
115
- meta_text = meta_path.read_text(encoding="utf-8")
116
- meta = {}
117
- for line in meta_text.splitlines():
118
- line = line.strip()
119
- if ":" in line:
120
- k, v = line.split(":", 1)
121
- meta[k.strip()] = v.strip()
122
- requires_raw = meta.get("requires", "")
123
- if requires_raw:
124
- result["requires"] = [r.strip() for r in requires_raw.split(",") if r.strip()]
125
- apply_requires_raw = meta.get("applyRequires", "")
126
- if apply_requires_raw:
127
- result["applyRequires"] = [r.strip() for r in apply_requires_raw.split(",") if r.strip()]
128
- except OSError:
129
- pass
130
- # artifactPaths:从当前 change 的 artifacts 目录构造(如果存在)
131
- artifacts_dir = cdir / "artifacts"
132
- if artifacts_dir.is_dir():
133
- artifact_paths = {}
134
- for entry in sorted(artifacts_dir.iterdir()):
135
- if entry.is_file():
136
- artifact_paths[entry.name] = str(entry.resolve())
137
- result["artifactPaths"] = artifact_paths
138
- print(json.dumps(result, ensure_ascii=False, indent=2))
139
- return 0
140
-
141
-
142
- def cmd_instructions(args) -> int:
143
- root = Path(args.root).resolve()
144
- try:
145
- cdir = change_dir(root, args.change)
146
- except ValueError as exc:
147
- print(f"error: {exc}", file=sys.stderr)
148
- return 1
149
- if not cdir.exists():
150
- print(f"error: change not found: {cdir}", file=sys.stderr)
151
- return 1
152
- # apply 不是四件产物,而是实施模式入口(AGENTS.md:「instructions apply 取
153
- # contextFiles/动态指令与 progress」)。返回实施上下文来源,不校验产物存在。
154
- if args.id == "apply":
155
- tasks_path = cdir / "tasks.md"
156
- specs_dir = cdir / "specs"
157
- result = {
158
- "template": "apply",
159
- "resolvedOutputPath": str(tasks_path),
160
- "required": False,
161
- "exists": tasks_path.is_file(),
162
- "contextFiles": [str(tasks_path)] if tasks_path.is_file() else [],
163
- "specsDir": str(specs_dir),
164
- "note": "实施模式:按 tasks.md 逐任务最小改动并立即勾选;无计划文档、"
165
- "不建 progress.md、账本即 tasks.md 勾选",
166
- }
167
- print(json.dumps(result, ensure_ascii=False, indent=2))
168
- return 0
169
- if args.id not in PRODUCTS:
170
- print(f"error: unknown product id: {args.id}", file=sys.stderr)
171
- return 1
172
- rel = PRODUCTS[args.id]
173
- target = cdir / rel
174
- exists = target.is_dir() if args.id == "specs" else target.is_file()
175
- result = {
176
- "template": args.id,
177
- "resolvedOutputPath": str(target),
178
- "required": True,
179
- "exists": exists,
180
- }
181
- print(json.dumps(result, ensure_ascii=False, indent=2))
182
- return 0
183
-
184
-
185
- def _split_sections(text: str):
186
- """按 ## 标题切分 Markdown,返回 [(header 或 None, [lines], ...)]。
187
- 仅做行级/段落级判断,不依赖第三方 Markdown 库。"""
188
- sections = []
189
- cur_header = None
190
- cur_lines = []
191
- for line in text.split("\n"):
192
- if line.startswith("## "):
193
- sections.append((cur_header, cur_lines))
194
- cur_header = line[2:].strip()
195
- cur_lines = []
196
- else:
197
- cur_lines.append(line)
198
- sections.append((cur_header, cur_lines))
199
- return sections
200
-
201
-
202
- def _section_lines(sections, header):
203
- for h, lines in sections:
204
- if h == header:
205
- return list(lines)
206
- return []
207
-
208
-
209
- def _has_purpose(sections) -> bool:
210
- lines = _section_lines(sections, "Purpose")
211
- return any(l.strip() for l in lines)
212
-
213
-
214
- def cmd_validate_change(args) -> int:
215
- """validate --change <name>:检查四件产物是否完整,输出 JSON,rc=0 无论 valid 与否。"""
216
- root = Path(args.root).resolve()
217
- try:
218
- cdir = change_dir(root, args.change)
219
- except ValueError as exc:
220
- print(f"error: {exc}", file=sys.stderr)
221
- return 1
222
- if not cdir.exists():
223
- print(f"error: change not found: {cdir}", file=sys.stderr)
224
- return 1
225
- missing = []
226
- for fname in ("proposal.md", "design.md", "tasks.md"):
227
- if not (cdir / fname).is_file():
228
- missing.append(fname)
229
- specs_dir = cdir / "specs"
230
- spec_found = False
231
- if specs_dir.is_dir():
232
- for entry in specs_dir.iterdir():
233
- if entry.is_dir() and (entry / "spec.md").is_file():
234
- spec_found = True
235
- break
236
- if not spec_found:
237
- missing.append("specs/spec.md")
238
- valid = len(missing) == 0
239
- print(json.dumps({"change": args.change, "valid": valid, "missing": missing},
240
- ensure_ascii=False, indent=2))
241
- return 0
242
-
243
-
244
- def _find_change_spec(cdir: Path):
245
- """在 change 目录下找 specs 产物:返回 (capability, spec_path)。找不到返回 (None, None)。"""
246
- specs_dir = cdir / "specs"
247
- if not specs_dir.is_dir():
248
- return None, None
249
- for entry in sorted(specs_dir.iterdir()):
250
- if entry.is_dir() and (entry / "spec.md").is_file():
251
- return entry.name, entry / "spec.md"
252
- return None, None
253
-
254
-
255
- def _merge_delta_into_main(main_text: str, delta_text: str) -> str:
256
- """把 delta spec 合并进主 spec(行级/段落级规则)。
257
-
258
- 规则:
259
- - 主 spec 的 ## Purpose 权威不动(不被 delta 覆盖)。
260
- - ## Requirements:保留主 spec 既有场景,追加 delta 未提及的新场景(去重)。
261
- - ## ADDED / ## MODIFIED / ## REMOVED / ## RENAMED:按段落原文合并记录。
262
- - 其他未知段落:新增则追加,已存在则并入。
263
- """
264
- main_secs = _split_sections(main_text or "")
265
- delta_secs = _split_sections(delta_text)
266
-
267
- main_by_header = {}
268
- main_order = []
269
- leading = []
270
- for h, lines in main_secs:
271
- if h is None:
272
- leading = list(lines)
273
- continue
274
- if h not in main_by_header:
275
- main_by_header[h] = []
276
- main_order.append(h)
277
- main_by_header[h].extend(lines)
278
-
279
- result = {h: list(lines) for h, lines in main_by_header.items()}
280
- result_order = list(main_order)
281
-
282
- def _ensure(header):
283
- if header not in result:
284
- result[header] = []
285
- result_order.append(header)
286
- return result[header]
287
-
288
- for h, lines in delta_secs:
289
- if h is None:
290
- continue
291
- if h == "Purpose":
292
- # 主 spec Purpose 权威不动
293
- continue
294
- if h == "Requirements":
295
- dst = _ensure("Requirements")
296
- for line in lines:
297
- s = line.strip()
298
- if s and s not in dst:
299
- dst.append(s)
300
- elif h.startswith("ADDED"):
301
- dst = _ensure(h)
302
- dst.extend(lines)
303
- elif h.startswith("MODIFIED"):
304
- dst = _ensure(h)
305
- dst.extend(lines)
306
- elif h.startswith("REMOVED"):
307
- # P2-1(老板批准 2026-11-18):REMOVED 整块移除(stage-S8:29/125)。
308
- # delta 中 REMOVED 段落列出的条目从主 spec 的 Requirements 中移除;
309
- # REMOVED 段本身不写入主 spec(归档复验要求「REMOVED 消失」)。
310
- # 旧实现 dst.extend(lines) 把 REMOVED 连同条目一起追加——语义相反。
311
- dst = result.get("Requirements")
312
- if dst is not None:
313
- removed = {line.strip() for line in lines if line.strip()}
314
- dst[:] = [ln for ln in dst if ln.strip() not in removed]
315
- elif h.startswith("RENAMED"):
316
- dst = _ensure(h)
317
- dst.extend(lines)
318
- else:
319
- if h not in result:
320
- result[h] = list(lines)
321
- result_order.append(h)
322
- else:
323
- result[h].extend(lines)
324
-
325
- out = []
326
- if leading:
327
- out.extend(leading)
328
- for h in result_order:
329
- out.append(f"## {h}")
330
- out.extend(result[h])
331
- return "\n".join(out).rstrip("\n") + "\n"
332
-
333
-
334
- def cmd_sync_specs_change(args) -> int:
335
- """sync-specs --change <name>:delta 合并进主 spec,输出 JSON,rc=0。
336
-
337
- P0-2 安全契约:--dry-run 只计算不写入;正常执行时对主 spec 做
338
- .bak-<ts> 备份后再覆盖,保证合并出错可回滚。
339
- """
340
- root = Path(args.root).resolve()
341
- try:
342
- cdir = change_dir(root, args.change)
343
- except ValueError as exc:
344
- print(f"error: {exc}", file=sys.stderr)
345
- return 1
346
- if not cdir.exists():
347
- print(f"error: change not found: {cdir}", file=sys.stderr)
348
- return 1
349
- capability, delta_path = _find_change_spec(cdir)
350
- if capability is None or delta_path is None:
351
- print(f"error: specs product not found in change: {cdir}", file=sys.stderr)
352
- return 1
353
- main_dir = root / "openspec" / "specs" / capability
354
- main_dir.mkdir(parents=True, exist_ok=True)
355
- main_path = main_dir / "spec.md"
356
- main_text = main_path.read_text(encoding="utf-8") if main_path.is_file() else ""
357
- delta_text = delta_path.read_text(encoding="utf-8")
358
- merged = _merge_delta_into_main(main_text, delta_text)
359
-
360
- if args.dry_run:
361
- print(json.dumps({
362
- "change": args.change,
363
- "capability": capability,
364
- "dry_run": True,
365
- "target": str(main_path),
366
- }, ensure_ascii=False, indent=2))
367
- return 0
368
-
369
- # 备份主 spec(.bak-<ts>,同一目录下),覆盖写入前保留回滚点
370
- backup_path = None
371
- if main_path.is_file():
372
- ts = datetime.now().strftime("%Y%m%d-%H%M%S%f")
373
- backup_path = main_path.with_name(f"{main_path.name}.bak-{ts}")
374
- backup_path.write_text(main_text, encoding="utf-8")
375
- main_path.write_text(merged, encoding="utf-8")
376
- print(json.dumps({
377
- "change": args.change,
378
- "capability": capability,
379
- "merged": True,
380
- "target": str(main_path),
381
- "backup": str(backup_path) if backup_path else None,
382
- }, ensure_ascii=False, indent=2))
383
- return 0
384
-
385
-
386
- def _status_flag(status: dict, *keys) -> bool:
387
- for k in keys:
388
- if k in status and status[k]:
389
- return True
390
- return False
391
-
392
-
393
- def cmd_archive_change(args) -> int:
394
- """archive-change <name>:七条件逐条检查后归档到 archive/YYYY-MM-DD-<change>。
395
-
396
- P0-3 安全契约:--dry-run 只校验不移动;正常归档前对变更目录做
397
- .bak-<ts> 备份,移动成功后清理备份(成功才清,失败保留供回滚)。
398
- """
399
- root = Path(args.root).resolve()
400
- try:
401
- cdir = change_dir(root, args.name)
402
- except ValueError as exc:
403
- print(f"error: {exc}", file=sys.stderr)
404
- return 1
405
- if not cdir.exists():
406
- print(f"error: change not found: {cdir}", file=sys.stderr)
407
- return 1
408
- status_path = cdir / ".status.json"
409
- if not status_path.is_file():
410
- print(f"error: .status.json not found, archive blocked: {cdir}", file=sys.stderr)
411
- return 1
412
- try:
413
- status = json.loads(status_path.read_text(encoding="utf-8"))
414
- except (json.JSONDecodeError, OSError) as exc:
415
- print(f"error: .status.json invalid: {exc}", file=sys.stderr)
416
- return 1
417
-
418
- # W8:存在 PARKED 任务,默认禁止归档
419
- if _status_flag(status, "parked", "PARKED"):
420
- print(f"error: PARKED tasks present, archive prohibited (W8): {cdir}", file=sys.stderr)
421
- return 1
422
-
423
- required = [
424
- ("tasksCompleted", "tasks_completed", "所有必须完成的任务已完成"),
425
- ("specsConsistent", "specs_consistent", "规格与实现一致"),
426
- ("testsPassed", "tests_passed", "测试验证通过"),
427
- ("reviewPassed", "review_passed", "代码审查通过"),
428
- ("noBlockers", "no_blockers", "无未解决阻断问题"),
429
- ("gitStatusOk", "git_status_ok", "Git 状态符合要求"),
430
- ("docsUpdated", "docs_updated", "必要文档已更新"),
431
- ]
432
- failed = [label for camel, snake, label in required
433
- if not _status_flag(status, camel, snake)]
434
- if failed:
435
- print(f"error: archive conditions not met: {', '.join(failed)}", file=sys.stderr)
436
- return 1
437
-
438
- # 变更目录只允许标准产物(含引擎元数据与 artifacts);插件运行时残留
439
- # (如 .mimosa)混入时拒绝归档——备份在归档成功后即删,无清理兜底
440
- allowed = {"proposal.md", "design.md", "tasks.md", "specs",
441
- ".openspec.yaml", ".status.json", "artifacts"}
442
- extras = sorted(e.name for e in cdir.iterdir() if e.name not in allowed)
443
- if extras:
444
- print(f"error: non-standard entries in change dir, archive blocked: "
445
- f"{', '.join(extras)}: {cdir}", file=sys.stderr)
446
- return 1
447
-
448
- archive_root = root / "openspec" / "changes" / "archive"
449
- archive_root.mkdir(parents=True, exist_ok=True)
450
- target = archive_root / f"{date.today().isoformat()}-{args.name}"
451
- if target.exists():
452
- print(f"error: archive target already exists: {target}", file=sys.stderr)
453
- return 1
454
-
455
- if args.dry_run:
456
- print(json.dumps({
457
- "change": args.name,
458
- "dry_run": True,
459
- "target": str(target),
460
- }, ensure_ascii=False, indent=2))
461
- return 0
462
-
463
- # 备份变更目录(.bak-<ts>),作为移动操作的回滚点
464
- ts = datetime.now().strftime("%Y%m%d-%H%M%S%f")
465
- backup_dir = cdir.with_name(f"{cdir.name}.bak-{ts}")
466
- shutil.copytree(str(cdir), str(backup_dir))
467
-
468
- # 归档前把元数据 status 更新为 archived(备份在前,替换失误可从 .bak 回滚)
469
- meta_path = cdir / ".openspec.yaml"
470
- if meta_path.is_file():
471
- text = meta_path.read_text(encoding="utf-8")
472
- updated = re.sub(r"^status:.*$", "status: archived",
473
- text, count=1, flags=re.MULTILINE)
474
- if updated != text:
475
- meta_path.write_text(updated, encoding="utf-8")
476
-
477
- try:
478
- shutil.move(str(cdir), str(target))
479
- except OSError as exc:
480
- # 移动失败:保留备份,便于回滚(不静默失败)
481
- print(f"error: archive move failed: {exc}", file=sys.stderr)
482
- return 1
483
-
484
- # 移动成功:清理备份(成功才清)
485
- shutil.rmtree(str(backup_dir))
486
-
487
- print(json.dumps({
488
- "change": args.name,
489
- "archived": True,
490
- "target": str(target),
491
- }, ensure_ascii=False, indent=2))
492
- return 0
493
-
494
-
495
- def cmd_validate_specs(args) -> int:
496
- """validate-specs:验证 openspec/specs/ 下所有 spec.md(Purpose 非空、退役不留空 Requirements)。"""
497
- root = Path(args.root).resolve()
498
- specs_root = root / "openspec" / "specs"
499
- issues = []
500
- if specs_root.is_dir():
501
- for cap_dir in sorted(specs_root.iterdir()):
502
- if not cap_dir.is_dir():
503
- continue
504
- spec_path = cap_dir / "spec.md"
505
- if not spec_path.is_file():
506
- continue
507
- capability = cap_dir.name
508
- text = spec_path.read_text(encoding="utf-8")
509
- sections = _split_sections(text)
510
- if not _has_purpose(sections):
511
- issues.append(f"{capability}: 缺少非空的 ## Purpose")
512
- # 能力退役:文中出现 退役/retired 时,## Requirements 不得为空
513
- is_retired = ("退役" in text) or ("retired" in text.lower())
514
- if is_retired:
515
- req_lines = _section_lines(sections, "Requirements")
516
- if not any(l.strip() for l in req_lines):
517
- issues.append(f"{capability}: 已退役但 ## Requirements 为空")
518
- valid = len(issues) == 0
519
- print(json.dumps({"valid": valid, "issues": issues}, ensure_ascii=False, indent=2))
520
- return 0
521
-
522
-
523
- def cmd_list_changes(args) -> int:
524
- """list --root <根>:列出所有 change 目录及其状态,输出 JSON,rc=0。
525
-
526
- 输出:
527
- {
528
- "changes": [
529
- {"name": "add-user-auth", "path": "...", "status": "pending", "products": {...}},
530
- ...
531
- ],
532
- "root": "<根目录绝对路径>"
533
- }
534
- """
535
- # --root 缺省(None)时 fallback 到 cwd,与父 --root 语义一致。
536
- # 旧实现直接 Path(None).resolve() 崩溃(list 必崩)。
537
- root = Path(getattr(args, "root", os.getcwd()) or os.getcwd()).resolve()
538
- changes_dir = root / "openspec" / "changes"
539
- changes = []
540
- if changes_dir.is_dir():
541
- for entry in sorted(changes_dir.iterdir()):
542
- if not entry.is_dir():
543
- continue
544
- # P1-2:archive/ 是归档容器而非 pending 变更,跳过(对齐官方 openspec 口径)
545
- if entry.name == 'archive':
546
- continue
547
- cdir = entry
548
- # 读取元数据,兼容无 .openspec.yaml 的旧 change
549
- meta_path = cdir / ".openspec.yaml"
550
- name = entry.name
551
- status = "pending"
552
- if meta_path.is_file():
553
- try:
554
- for line in meta_path.read_text(encoding="utf-8").splitlines():
555
- line = line.strip()
556
- if line.startswith("status:"):
557
- status = line.split(":", 1)[1].strip()
558
- break
559
- except OSError:
560
- pass
561
- # products 状态
562
- products = {name_: product_state(cdir, name_) for name_ in PRODUCTS}
563
- changes.append({
564
- "name": name,
565
- "path": str(cdir),
566
- "status": status,
567
- "products": products,
568
- })
569
- print(json.dumps({
570
- "changes": changes,
571
- "root": str(root),
572
- "openspec": changes_dir.is_dir(),
573
- }, ensure_ascii=False, indent=2))
574
- return 0
575
-
576
-
577
- def build_parser() -> argparse.ArgumentParser:
578
- parser = argparse.ArgumentParser(prog="openspec_engine.py")
579
- parser.add_argument("--root", default=os.getcwd(), help="仓库根目录(默认 cwd)")
580
- sub = parser.add_subparsers(dest="command", required=True)
581
-
582
- p_new = sub.add_parser("new-change", help="创建 change 目录 + 元数据文件")
583
- p_new.add_argument("name", help="change 名(kebab-case)")
584
- p_new.set_defaults(func=cmd_new_change)
585
-
586
- p_status = sub.add_parser("status", help="读取变更状态")
587
- p_status.add_argument("--change", required=True, help="change 名")
588
- p_status.set_defaults(func=cmd_status)
589
-
590
- p_instr = sub.add_parser("instructions", help="读取产物模板 + resolvedOutputPath")
591
- p_instr.add_argument("id", help="产物 id(proposal/design/tasks/specs)")
592
- p_instr.add_argument("--change", required=True, help="change 名")
593
- p_instr.set_defaults(func=cmd_instructions)
594
-
595
- p_validate = sub.add_parser("validate", help="验证 change 四件产物完整")
596
- p_validate.add_argument("--change", required=True, help="change 名")
597
- p_validate.set_defaults(func=cmd_validate_change)
598
-
599
- p_sync = sub.add_parser("sync-specs", help="delta 合并进主 spec")
600
- p_sync.add_argument("--change", required=True, help="change 名")
601
- p_sync.add_argument("--dry-run", action="store_true",
602
- help="只计算合并结果,不写主 spec、不产生备份")
603
- p_sync.set_defaults(func=cmd_sync_specs_change)
604
-
605
- p_archive = sub.add_parser("archive-change", help="归档 change")
606
- p_archive.add_argument("name", help="change 名")
607
- p_archive.add_argument("--dry-run", action="store_true",
608
- help="只校验七条件、目录标准性与目标路径,不移动、不备份")
609
- p_archive.set_defaults(func=cmd_archive_change)
610
-
611
- p_validatespecs = sub.add_parser("validate-specs", help="验证主 spec")
612
- p_validatespecs.set_defaults(func=cmd_validate_specs)
613
-
614
- p_list = sub.add_parser("list", help="列出所有 change 及其状态")
615
- # P3-6:default=argparse.SUPPRESS,子命令未传 --root 时不覆盖顶层已设值
616
- # (旧 default=None 会把顶层 --root 静默覆盖为 None,回落 cwd)。
617
- # 显式传 `list --root X` 时仍生效;两者都不传时由 cmd_list_changes 用 getattr 兜底 cwd。
618
- p_list.add_argument("--root", default=argparse.SUPPRESS,
619
- help="仓库根目录(优先于顶层 --root;缺省用顶层 --root 或 cwd)")
620
- p_list.set_defaults(func=cmd_list_changes)
621
-
622
- return parser
623
-
624
-
625
- def main(argv=None) -> int:
626
- parser = build_parser()
627
- args = parser.parse_args(argv)
628
- return args.func(args)
629
-
630
-
631
- if __name__ == "__main__":
632
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ """OpenSpec 引擎 —— 内置 CLI(前三个子命令:new-change / status / instructions)。
3
+
4
+ 仅使用 Python 3 标准库(json/os/re/sys/argparse/datetime/pathlib),无第三方依赖。
5
+ .openspec.yaml 手写/手读简单键值对,不依赖第三方 YAML 库。
6
+ LF 行尾,pathlib 跨平台路径。
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ from datetime import date, datetime
16
+ from pathlib import Path
17
+
18
+ # 四件产物及其在 change 目录下的相对路径(按 OpenSpec/S2 规格)
19
+ PRODUCTS = {
20
+ "proposal": "proposal.md",
21
+ "design": "design.md",
22
+ "tasks": "tasks.md",
23
+ "specs": "specs",
24
+ }
25
+
26
+ # I-05:归档前校验 tasks.md 实际勾选。口径与 workflow_check.count_checkboxes
27
+ # 一致——空框 [] 算未完成,仅 x/X 算完成([ x ] 带空格同样算 x)。
28
+ _TASK_LINE_PATTERN = re.compile(r"^\s*(?:[-*+]|\d{1,9}[.)])\s*\[([^\]]*)\]\s*(.*)$")
29
+
30
+
31
+ def count_task_checkboxes(text):
32
+ """统计 tasks.md 勾选:返回 (done, todo)。
33
+
34
+ 空框 [] 算 todo(未完成);x/X(含 [ x ] 带空格)算 done。
35
+ 与 workflow_check.count_checkboxes 的 done/todo 口径一致,但 I-05
36
+ 只需二分判定,不单独拆 other(异形标记 [~] 等按未完成处理,更保守)。
37
+ """
38
+ done = todo = 0
39
+ for line in (text or "").splitlines():
40
+ m = _TASK_LINE_PATTERN.match(line)
41
+ if not m:
42
+ continue
43
+ mark = (m.group(1) or "").strip().lower()
44
+ if mark == "x":
45
+ done += 1
46
+ else:
47
+ todo += 1
48
+ return done, todo
49
+
50
+
51
+ def change_dir(root: Path, name: str) -> Path:
52
+ # 库模式抛 ValueError(调用方自行处置);6 个 CLI 入口捕获后转
53
+ # 「error: ... + return 1」,进程退出码语义不变——勿在库函数里
54
+ # sys.exit,那会以 SystemExit 炸宿主进程。
55
+ if name == "archive":
56
+ raise ValueError("'archive' is a reserved container name, not a change")
57
+ return root / "openspec" / "changes" / name
58
+
59
+
60
+ def write_metadata(cdir: Path, name: str) -> None:
61
+ """手写 .openspec.yaml,简单键值对,LF 行尾。"""
62
+ lines = [
63
+ "schema: spec-driven",
64
+ f"name: {name}",
65
+ f"created: {date.today().isoformat()}",
66
+ "status: pending",
67
+ ]
68
+ (cdir / ".openspec.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")
69
+
70
+
71
+ def write_status(cdir: Path, status: dict) -> None:
72
+ """手写 .status.json,简单 JSON,LF 行尾。"""
73
+ (cdir / ".status.json").write_text(
74
+ json.dumps(status, ensure_ascii=False, indent=2),
75
+ encoding="utf-8",
76
+ )
77
+
78
+
79
+ def cmd_new_change(args) -> int:
80
+ root = Path(args.root).resolve()
81
+ try:
82
+ cdir = change_dir(root, args.name)
83
+ except ValueError as exc:
84
+ print(f"error: {exc}", file=sys.stderr)
85
+ return 1
86
+ if cdir.exists():
87
+ print(f"error: change already exists: {cdir}", file=sys.stderr)
88
+ return 1
89
+ cdir.mkdir(parents=True, exist_ok=True)
90
+ (cdir / "specs").mkdir(exist_ok=True)
91
+ write_metadata(cdir, args.name)
92
+ write_status(cdir, {
93
+ "tasksCompleted": False,
94
+ "specsConsistent": False,
95
+ "testsPassed": False,
96
+ "reviewPassed": False,
97
+ "noBlockers": True,
98
+ "gitStatusOk": True,
99
+ "docsUpdated": True,
100
+ "parked": False,
101
+ })
102
+ print(f"change created: {cdir}")
103
+ return 0
104
+
105
+
106
+ def product_state(cdir: Path, product: str) -> str:
107
+ """状态只判文件是否存在(OpenSpec:status 只判文件存在,别被 done 误导)。"""
108
+ rel = PRODUCTS[product]
109
+ target = cdir / rel
110
+ if product == "specs":
111
+ # 空的 specs/ 子目录不算产物就绪;只有包含具体 spec 时才为 done
112
+ return "done" if (target.is_dir() and any(target.iterdir())) else "pending"
113
+ return "done" if target.is_file() else "pending"
114
+
115
+
116
+ def cmd_status(args) -> int:
117
+ root = Path(args.root).resolve()
118
+ try:
119
+ cdir = change_dir(root, args.change)
120
+ except ValueError as exc:
121
+ print(f"error: {exc}", file=sys.stderr)
122
+ return 1
123
+ if not cdir.exists():
124
+ print(f"error: change not found: {cdir}", file=sys.stderr)
125
+ return 1
126
+ products = {name: product_state(cdir, name) for name in PRODUCTS}
127
+ result = {
128
+ "change": args.change,
129
+ "status": "pending",
130
+ "products": products,
131
+ "applyRequires": [],
132
+ "requires": [],
133
+ "artifactPaths": {},
134
+ }
135
+ # 从 .openspec.yaml 读取 requires 元数据(如果存在)
136
+ meta_path = cdir / ".openspec.yaml"
137
+ if meta_path.is_file():
138
+ try:
139
+ meta_text = meta_path.read_text(encoding="utf-8")
140
+ meta = {}
141
+ for line in meta_text.splitlines():
142
+ line = line.strip()
143
+ if ":" in line:
144
+ k, v = line.split(":", 1)
145
+ meta[k.strip()] = v.strip()
146
+ requires_raw = meta.get("requires", "")
147
+ if requires_raw:
148
+ result["requires"] = [r.strip() for r in requires_raw.split(",") if r.strip()]
149
+ apply_requires_raw = meta.get("applyRequires", "")
150
+ if apply_requires_raw:
151
+ result["applyRequires"] = [r.strip() for r in apply_requires_raw.split(",") if r.strip()]
152
+ except OSError:
153
+ pass
154
+ # artifactPaths:从当前 change 的 artifacts 目录构造(如果存在)
155
+ artifacts_dir = cdir / "artifacts"
156
+ if artifacts_dir.is_dir():
157
+ artifact_paths = {}
158
+ for entry in sorted(artifacts_dir.iterdir()):
159
+ if entry.is_file():
160
+ artifact_paths[entry.name] = str(entry.resolve())
161
+ result["artifactPaths"] = artifact_paths
162
+ # M2 修复:补齐 S8 delta 唯一来源 artifactPaths.specs.existingOutputPaths。
163
+ # 文档(config/workflow.json:336、commands/wf/archive.md:24、stage-S8)声明主控
164
+ # 只认此嵌套字段,但旧实现只产扁平 artifacts 映射,导致 S8 同步机制静默失效。
165
+ # 现从 change 的 specs/*/spec.md 收集 existingOutputPaths,与文档对齐。
166
+ specs_dir = cdir / "specs"
167
+ existing_output_paths = []
168
+ if specs_dir.is_dir():
169
+ for spec_file in sorted(specs_dir.glob("*/spec.md")):
170
+ existing_output_paths.append(str(spec_file.resolve()))
171
+ result["artifactPaths"].setdefault("specs", {})["existingOutputPaths"] = existing_output_paths
172
+ print(json.dumps(result, ensure_ascii=False, indent=2))
173
+ return 0
174
+
175
+
176
+ def cmd_instructions(args) -> int:
177
+ root = Path(args.root).resolve()
178
+ try:
179
+ cdir = change_dir(root, args.change)
180
+ except ValueError as exc:
181
+ print(f"error: {exc}", file=sys.stderr)
182
+ return 1
183
+ if not cdir.exists():
184
+ print(f"error: change not found: {cdir}", file=sys.stderr)
185
+ return 1
186
+ # apply 不是四件产物,而是实施模式入口(AGENTS.md:「instructions apply 取
187
+ # contextFiles/动态指令与 progress」)。返回实施上下文来源,不校验产物存在。
188
+ if args.id == "apply":
189
+ tasks_path = cdir / "tasks.md"
190
+ specs_dir = cdir / "specs"
191
+ result = {
192
+ "template": "apply",
193
+ "resolvedOutputPath": str(tasks_path),
194
+ "required": False,
195
+ "exists": tasks_path.is_file(),
196
+ "contextFiles": [str(tasks_path)] if tasks_path.is_file() else [],
197
+ "specsDir": str(specs_dir),
198
+ "note": "实施模式:按 tasks.md 逐任务最小改动并立即勾选;无计划文档、"
199
+ "不建 progress.md、账本即 tasks.md 勾选",
200
+ }
201
+ print(json.dumps(result, ensure_ascii=False, indent=2))
202
+ return 0
203
+ if args.id not in PRODUCTS:
204
+ print(f"error: unknown product id: {args.id}", file=sys.stderr)
205
+ return 1
206
+ rel = PRODUCTS[args.id]
207
+ target = cdir / rel
208
+ exists = target.is_dir() if args.id == "specs" else target.is_file()
209
+ result = {
210
+ "template": args.id,
211
+ "resolvedOutputPath": str(target),
212
+ "required": True,
213
+ "exists": exists,
214
+ }
215
+ print(json.dumps(result, ensure_ascii=False, indent=2))
216
+ return 0
217
+
218
+
219
+ def _split_sections(text: str):
220
+ """按 ## 标题切分 Markdown,返回 [(header 或 None, [lines], ...)]。
221
+ 仅做行级/段落级判断,不依赖第三方 Markdown 库。"""
222
+ sections = []
223
+ cur_header = None
224
+ cur_lines = []
225
+ for line in text.split("\n"):
226
+ if line.startswith("## "):
227
+ sections.append((cur_header, cur_lines))
228
+ cur_header = line[2:].strip()
229
+ cur_lines = []
230
+ else:
231
+ cur_lines.append(line)
232
+ sections.append((cur_header, cur_lines))
233
+ return sections
234
+
235
+
236
+ def _section_lines(sections, header):
237
+ for h, lines in sections:
238
+ if h == header:
239
+ return list(lines)
240
+ return []
241
+
242
+
243
+ def _has_purpose(sections) -> bool:
244
+ lines = _section_lines(sections, "Purpose")
245
+ return any(l.strip() for l in lines)
246
+
247
+
248
+ def cmd_validate_change(args) -> int:
249
+ """validate --change <name>:检查四件产物是否完整,输出 JSON,rc=0 无论 valid 与否。"""
250
+ root = Path(args.root).resolve()
251
+ try:
252
+ cdir = change_dir(root, args.change)
253
+ except ValueError as exc:
254
+ print(f"error: {exc}", file=sys.stderr)
255
+ return 1
256
+ if not cdir.exists():
257
+ print(f"error: change not found: {cdir}", file=sys.stderr)
258
+ return 1
259
+ missing = []
260
+ for fname in ("proposal.md", "design.md", "tasks.md"):
261
+ if not (cdir / fname).is_file():
262
+ missing.append(fname)
263
+ specs_dir = cdir / "specs"
264
+ spec_found = False
265
+ if specs_dir.is_dir():
266
+ for entry in specs_dir.iterdir():
267
+ if entry.is_dir() and (entry / "spec.md").is_file():
268
+ spec_found = True
269
+ break
270
+ if not spec_found:
271
+ missing.append("specs/spec.md")
272
+ valid = len(missing) == 0
273
+ print(json.dumps({"change": args.change, "valid": valid, "missing": missing},
274
+ ensure_ascii=False, indent=2))
275
+ return 0
276
+
277
+
278
+ def _find_change_spec(cdir: Path):
279
+ """在 change 目录下找 specs 产物:返回 (capability, spec_path)。找不到返回 (None, None)。"""
280
+ specs_dir = cdir / "specs"
281
+ if not specs_dir.is_dir():
282
+ return None, None
283
+ for entry in sorted(specs_dir.iterdir()):
284
+ if entry.is_dir() and (entry / "spec.md").is_file():
285
+ return entry.name, entry / "spec.md"
286
+ return None, None
287
+
288
+
289
+ def _merge_delta_into_main(main_text: str, delta_text: str) -> str:
290
+ """把 delta spec 合并进主 spec(行级/段落级规则)。
291
+
292
+ 规则:
293
+ - 主 spec 的 ## Purpose 权威不动(不被 delta 覆盖)。
294
+ - ## Requirements:保留主 spec 既有场景,追加 delta 未提及的新场景(去重)。
295
+ - ## ADDED / ## MODIFIED / ## REMOVED / ## RENAMED:按段落原文合并记录。
296
+ - 其他未知段落:新增则追加,已存在则并入。
297
+ """
298
+ main_secs = _split_sections(main_text or "")
299
+ delta_secs = _split_sections(delta_text)
300
+
301
+ main_by_header = {}
302
+ main_order = []
303
+ leading = []
304
+ for h, lines in main_secs:
305
+ if h is None:
306
+ leading = list(lines)
307
+ continue
308
+ if h not in main_by_header:
309
+ main_by_header[h] = []
310
+ main_order.append(h)
311
+ main_by_header[h].extend(lines)
312
+
313
+ result = {h: list(lines) for h, lines in main_by_header.items()}
314
+ result_order = list(main_order)
315
+
316
+ def _ensure(header):
317
+ if header not in result:
318
+ result[header] = []
319
+ result_order.append(header)
320
+ return result[header]
321
+
322
+ for h, lines in delta_secs:
323
+ if h is None:
324
+ continue
325
+ if h == "Purpose":
326
+ # 主 spec Purpose 权威不动
327
+ continue
328
+ if h == "Requirements":
329
+ dst = _ensure("Requirements")
330
+ for line in lines:
331
+ s = line.strip()
332
+ if s and s not in dst:
333
+ dst.append(s)
334
+ elif h.startswith("ADDED"):
335
+ dst = _ensure(h)
336
+ dst.extend(lines)
337
+ elif h.startswith("MODIFIED"):
338
+ dst = _ensure(h)
339
+ dst.extend(lines)
340
+ elif h.startswith("REMOVED"):
341
+ # P2-1(老板批准 2026-11-18):REMOVED 整块移除(stage-S8:29/125)。
342
+ # delta 中 REMOVED 段落列出的条目从主 spec 的 Requirements 中移除;
343
+ # REMOVED 段本身不写入主 spec(归档复验要求「REMOVED 消失」)。
344
+ # 旧实现 dst.extend(lines) 把 REMOVED 连同条目一起追加——语义相反。
345
+ dst = result.get("Requirements")
346
+ if dst is not None:
347
+ removed = {line.strip() for line in lines if line.strip()}
348
+ dst[:] = [ln for ln in dst if ln.strip() not in removed]
349
+ elif h.startswith("RENAMED"):
350
+ dst = _ensure(h)
351
+ dst.extend(lines)
352
+ else:
353
+ if h not in result:
354
+ result[h] = list(lines)
355
+ result_order.append(h)
356
+ else:
357
+ result[h].extend(lines)
358
+
359
+ out = []
360
+ if leading:
361
+ out.extend(leading)
362
+ for h in result_order:
363
+ out.append(f"## {h}")
364
+ out.extend(result[h])
365
+ return "\n".join(out).rstrip("\n") + "\n"
366
+
367
+
368
+ def cmd_sync_specs_change(args) -> int:
369
+ """sync-specs --change <name>:delta 合并进主 spec,输出 JSON,rc=0。
370
+
371
+ P0-2 安全契约:--dry-run 只计算不写入;正常执行时对主 spec 做
372
+ .bak-<ts> 备份后再覆盖,保证合并出错可回滚。
373
+ """
374
+ root = Path(args.root).resolve()
375
+ try:
376
+ cdir = change_dir(root, args.change)
377
+ except ValueError as exc:
378
+ print(f"error: {exc}", file=sys.stderr)
379
+ return 1
380
+ if not cdir.exists():
381
+ print(f"error: change not found: {cdir}", file=sys.stderr)
382
+ return 1
383
+ capability, delta_path = _find_change_spec(cdir)
384
+ if capability is None or delta_path is None:
385
+ print(f"error: specs product not found in change: {cdir}", file=sys.stderr)
386
+ return 1
387
+ main_dir = root / "openspec" / "specs" / capability
388
+ main_dir.mkdir(parents=True, exist_ok=True)
389
+ main_path = main_dir / "spec.md"
390
+ main_text = main_path.read_text(encoding="utf-8") if main_path.is_file() else ""
391
+ delta_text = delta_path.read_text(encoding="utf-8")
392
+ merged = _merge_delta_into_main(main_text, delta_text)
393
+
394
+ if args.dry_run:
395
+ print(json.dumps({
396
+ "change": args.change,
397
+ "capability": capability,
398
+ "dry_run": True,
399
+ "target": str(main_path),
400
+ }, ensure_ascii=False, indent=2))
401
+ return 0
402
+
403
+ # 备份主 spec(.bak-<ts>,同一目录下),覆盖写入前保留回滚点
404
+ backup_path = None
405
+ if main_path.is_file():
406
+ ts = datetime.now().strftime("%Y%m%d-%H%M%S%f")
407
+ backup_path = main_path.with_name(f"{main_path.name}.bak-{ts}")
408
+ backup_path.write_text(main_text, encoding="utf-8")
409
+ main_path.write_text(merged, encoding="utf-8")
410
+ print(json.dumps({
411
+ "change": args.change,
412
+ "capability": capability,
413
+ "merged": True,
414
+ "target": str(main_path),
415
+ "backup": str(backup_path) if backup_path else None,
416
+ }, ensure_ascii=False, indent=2))
417
+ return 0
418
+
419
+
420
+ def _status_flag(status: dict, *keys) -> bool:
421
+ for k in keys:
422
+ if k in status and status[k]:
423
+ return True
424
+ return False
425
+
426
+
427
+ def cmd_archive_change(args) -> int:
428
+ """archive-change <name>:七条件逐条检查后归档到 archive/YYYY-MM-DD-<change>。
429
+
430
+ P0-3 安全契约:--dry-run 只校验不移动;正常归档前对变更目录做
431
+ .bak-<ts> 备份,移动成功后清理备份(成功才清,失败保留供回滚)。
432
+ """
433
+ root = Path(args.root).resolve()
434
+ try:
435
+ cdir = change_dir(root, args.name)
436
+ except ValueError as exc:
437
+ print(f"error: {exc}", file=sys.stderr)
438
+ return 1
439
+ if not cdir.exists():
440
+ print(f"error: change not found: {cdir}", file=sys.stderr)
441
+ return 1
442
+ status_path = cdir / ".status.json"
443
+ if not status_path.is_file():
444
+ print(f"error: .status.json not found, archive blocked: {cdir}", file=sys.stderr)
445
+ return 1
446
+ try:
447
+ status = json.loads(status_path.read_text(encoding="utf-8"))
448
+ except (json.JSONDecodeError, OSError) as exc:
449
+ print(f"error: .status.json invalid: {exc}", file=sys.stderr)
450
+ return 1
451
+
452
+ # W8:存在 PARKED 任务,默认禁止归档
453
+ if _status_flag(status, "parked", "PARKED"):
454
+ print(f"error: PARKED tasks present, archive prohibited (W8): {cdir}", file=sys.stderr)
455
+ return 1
456
+
457
+ required = [
458
+ ("tasksCompleted", "tasks_completed", "所有必须完成的任务已完成"),
459
+ ("specsConsistent", "specs_consistent", "规格与实现一致"),
460
+ ("testsPassed", "tests_passed", "测试验证通过"),
461
+ ("reviewPassed", "review_passed", "代码审查通过"),
462
+ ("noBlockers", "no_blockers", "无未解决阻断问题"),
463
+ ("gitStatusOk", "git_status_ok", "Git 状态符合要求"),
464
+ ("docsUpdated", "docs_updated", "必要文档已更新"),
465
+ ]
466
+ failed = [label for camel, snake, label in required
467
+ if not _status_flag(status, camel, snake)]
468
+ if failed:
469
+ print(f"error: archive conditions not met: {', '.join(failed)}", file=sys.stderr)
470
+ return 1
471
+
472
+ # I-05:七标志全 true 只是手工维护的元数据,必须与 tasks.md 实际勾选
473
+ # 状态核对。tasks.md 存在时,有未勾选任务则拒绝归档;不存在时
474
+ # 无账本可查,沿用 status 标志(保持既有口径)。
475
+ tasks_path = cdir / "tasks.md"
476
+ if tasks_path.is_file():
477
+ try:
478
+ tasks_text = tasks_path.read_text(encoding="utf-8")
479
+ except OSError as exc:
480
+ print(f"error: tasks.md read failed: {exc}", file=sys.stderr)
481
+ return 1
482
+ done, todo = count_task_checkboxes(tasks_text)
483
+ if todo > 0:
484
+ print(
485
+ f"error: archive blocked: tasks.md has {todo} unchecked "
486
+ f"task(s) ({done} done)",
487
+ file=sys.stderr)
488
+ return 1
489
+
490
+ # 变更目录只允许标准产物(含引擎元数据与 artifacts);插件运行时残留
491
+ # (如 .mimosa)混入时拒绝归档——备份在归档成功后即删,无清理兜底
492
+ allowed = {"proposal.md", "design.md", "tasks.md", "specs",
493
+ ".openspec.yaml", ".status.json", "artifacts"}
494
+ extras = sorted(e.name for e in cdir.iterdir() if e.name not in allowed)
495
+ if extras:
496
+ print(f"error: non-standard entries in change dir, archive blocked: "
497
+ f"{', '.join(extras)}: {cdir}", file=sys.stderr)
498
+ return 1
499
+
500
+ archive_root = root / "openspec" / "changes" / "archive"
501
+ archive_root.mkdir(parents=True, exist_ok=True)
502
+ target = archive_root / f"{date.today().isoformat()}-{args.name}"
503
+ if target.exists():
504
+ print(f"error: archive target already exists: {target}", file=sys.stderr)
505
+ return 1
506
+
507
+ if args.dry_run:
508
+ print(json.dumps({
509
+ "change": args.name,
510
+ "dry_run": True,
511
+ "target": str(target),
512
+ }, ensure_ascii=False, indent=2))
513
+ return 0
514
+
515
+ # 备份变更目录(.bak-<ts>),作为移动操作的回滚点
516
+ ts = datetime.now().strftime("%Y%m%d-%H%M%S%f")
517
+ backup_dir = cdir.with_name(f"{cdir.name}.bak-{ts}")
518
+ shutil.copytree(str(cdir), str(backup_dir))
519
+
520
+ # 归档前把元数据 status 更新为 archived(备份在前,替换失误可从 .bak 回滚)
521
+ meta_path = cdir / ".openspec.yaml"
522
+ if meta_path.is_file():
523
+ text = meta_path.read_text(encoding="utf-8")
524
+ updated = re.sub(r"^status:.*$", "status: archived",
525
+ text, count=1, flags=re.MULTILINE)
526
+ if updated != text:
527
+ meta_path.write_text(updated, encoding="utf-8")
528
+
529
+ try:
530
+ shutil.move(str(cdir), str(target))
531
+ except OSError as exc:
532
+ # 移动失败:保留备份,便于回滚(不静默失败)
533
+ print(f"error: archive move failed: {exc}", file=sys.stderr)
534
+ return 1
535
+
536
+ # 移动成功:清理备份(成功才清)
537
+ shutil.rmtree(str(backup_dir))
538
+
539
+ print(json.dumps({
540
+ "change": args.name,
541
+ "archived": True,
542
+ "target": str(target),
543
+ }, ensure_ascii=False, indent=2))
544
+ return 0
545
+
546
+
547
+ def cmd_validate_specs(args) -> int:
548
+ """validate-specs:验证 openspec/specs/ 下所有 spec.md(Purpose 非空、退役不留空 Requirements)。"""
549
+ root = Path(args.root).resolve()
550
+ specs_root = root / "openspec" / "specs"
551
+ issues = []
552
+ if specs_root.is_dir():
553
+ for cap_dir in sorted(specs_root.iterdir()):
554
+ if not cap_dir.is_dir():
555
+ continue
556
+ spec_path = cap_dir / "spec.md"
557
+ if not spec_path.is_file():
558
+ continue
559
+ capability = cap_dir.name
560
+ text = spec_path.read_text(encoding="utf-8")
561
+ sections = _split_sections(text)
562
+ if not _has_purpose(sections):
563
+ issues.append(f"{capability}: 缺少非空的 ## Purpose")
564
+ # 能力退役:文中出现 退役/retired 时,## Requirements 不得为空
565
+ is_retired = ("退役" in text) or ("retired" in text.lower())
566
+ if is_retired:
567
+ req_lines = _section_lines(sections, "Requirements")
568
+ if not any(l.strip() for l in req_lines):
569
+ issues.append(f"{capability}: 已退役但 ## Requirements 为空")
570
+ valid = len(issues) == 0
571
+ print(json.dumps({"valid": valid, "issues": issues}, ensure_ascii=False, indent=2))
572
+ return 0
573
+
574
+
575
+ def cmd_list_changes(args) -> int:
576
+ """list --root <根>:列出所有 change 目录及其状态,输出 JSON,rc=0。
577
+
578
+ 输出:
579
+ {
580
+ "changes": [
581
+ {"name": "add-user-auth", "path": "...", "status": "pending", "products": {...}},
582
+ ...
583
+ ],
584
+ "root": "<根目录绝对路径>"
585
+ }
586
+ """
587
+ # --root 缺省(None)时 fallback 到 cwd,与父 --root 语义一致。
588
+ # 旧实现直接 Path(None).resolve() 崩溃(list 必崩)。
589
+ root = Path(getattr(args, "root", os.getcwd()) or os.getcwd()).resolve()
590
+ changes_dir = root / "openspec" / "changes"
591
+ changes = []
592
+ if changes_dir.is_dir():
593
+ for entry in sorted(changes_dir.iterdir()):
594
+ if not entry.is_dir():
595
+ continue
596
+ # P1-2:archive/ 是归档容器而非 pending 变更,跳过(对齐官方 openspec 口径)
597
+ if entry.name == 'archive':
598
+ continue
599
+ cdir = entry
600
+ # 读取元数据,兼容无 .openspec.yaml 的旧 change
601
+ meta_path = cdir / ".openspec.yaml"
602
+ name = entry.name
603
+ status = "pending"
604
+ if meta_path.is_file():
605
+ try:
606
+ for line in meta_path.read_text(encoding="utf-8").splitlines():
607
+ line = line.strip()
608
+ if line.startswith("status:"):
609
+ status = line.split(":", 1)[1].strip()
610
+ break
611
+ except OSError:
612
+ pass
613
+ # products 状态
614
+ products = {name_: product_state(cdir, name_) for name_ in PRODUCTS}
615
+ changes.append({
616
+ "name": name,
617
+ "path": str(cdir),
618
+ "status": status,
619
+ "products": products,
620
+ })
621
+ print(json.dumps({
622
+ "changes": changes,
623
+ "root": str(root),
624
+ "openspec": changes_dir.is_dir(),
625
+ }, ensure_ascii=False, indent=2))
626
+ return 0
627
+
628
+
629
+ def build_parser() -> argparse.ArgumentParser:
630
+ parser = argparse.ArgumentParser(prog="openspec_engine.py")
631
+ parser.add_argument("--root", default=os.getcwd(), help="仓库根目录(默认 cwd)")
632
+ sub = parser.add_subparsers(dest="command", required=True)
633
+
634
+ p_new = sub.add_parser("new-change", help="创建 change 目录 + 元数据文件")
635
+ p_new.add_argument("name", help="change 名(kebab-case)")
636
+ p_new.set_defaults(func=cmd_new_change)
637
+
638
+ p_status = sub.add_parser("status", help="读取变更状态")
639
+ p_status.add_argument("--change", required=True, help="change 名")
640
+ p_status.set_defaults(func=cmd_status)
641
+
642
+ p_instr = sub.add_parser("instructions", help="读取产物模板 + resolvedOutputPath")
643
+ p_instr.add_argument("id", help="产物 id(proposal/design/tasks/specs)")
644
+ p_instr.add_argument("--change", required=True, help="change 名")
645
+ p_instr.set_defaults(func=cmd_instructions)
646
+
647
+ p_validate = sub.add_parser("validate", help="验证 change 四件产物完整")
648
+ p_validate.add_argument("--change", required=True, help="change 名")
649
+ p_validate.set_defaults(func=cmd_validate_change)
650
+
651
+ p_sync = sub.add_parser("sync-specs", help="delta 合并进主 spec")
652
+ p_sync.add_argument("--change", required=True, help="change 名")
653
+ p_sync.add_argument("--dry-run", action="store_true",
654
+ help="只计算合并结果,不写主 spec、不产生备份")
655
+ p_sync.set_defaults(func=cmd_sync_specs_change)
656
+
657
+ p_archive = sub.add_parser("archive-change", help="归档 change")
658
+ p_archive.add_argument("name", help="change 名")
659
+ p_archive.add_argument("--dry-run", action="store_true",
660
+ help="只校验七条件、目录标准性与目标路径,不移动、不备份")
661
+ p_archive.set_defaults(func=cmd_archive_change)
662
+
663
+ p_validatespecs = sub.add_parser("validate-specs", help="验证主 spec")
664
+ p_validatespecs.set_defaults(func=cmd_validate_specs)
665
+
666
+ p_list = sub.add_parser("list", help="列出所有 change 及其状态")
667
+ # P3-6:default=argparse.SUPPRESS,子命令未传 --root 时不覆盖顶层已设值
668
+ # (旧 default=None 会把顶层 --root 静默覆盖为 None,回落 cwd)。
669
+ # 显式传 `list --root X` 时仍生效;两者都不传时由 cmd_list_changes 用 getattr 兜底 cwd。
670
+ p_list.add_argument("--root", default=argparse.SUPPRESS,
671
+ help="仓库根目录(优先于顶层 --root;缺省用顶层 --root 或 cwd)")
672
+ p_list.set_defaults(func=cmd_list_changes)
673
+
674
+ return parser
675
+
676
+
677
+ def main(argv=None) -> int:
678
+ parser = build_parser()
679
+ args = parser.parse_args(argv)
680
+ return args.func(args)
681
+
682
+
683
+ def _force_utf8_stdout():
684
+ """让 stdout/stderr 用 UTF-8 输出,避免非 UTF-8 控制台抛 UnicodeEncodeError。
685
+
686
+ 中文 Windows 默认代码页 CP936 可编码 GB2312 汉字,但无法编码 emoji
687
+ (⚙️ U+2699)与 ⇒(U+21D2) 等符号。本脚本 :569 等处 print(json.dumps
688
+ (..., ensure_ascii=False)) 会把含 emoji 的路径/内容原样透出,CP936
689
+ 终端下抛 UnicodeEncodeError,rc=1、stdout 全空。
690
+
691
+ 与 zcode_expert_system.py / zcode_dev_workflow.py / skill_entry.py
692
+ / scripts/workflow_check.py 的同名函数保持一致(R10 补齐最后一个入口)。
693
+ """
694
+ for stream_name in ("stdout", "stderr"):
695
+ stream = getattr(sys, stream_name, None)
696
+ reconfigure = getattr(stream, "reconfigure", None)
697
+ if reconfigure is None:
698
+ continue
699
+ try:
700
+ reconfigure(encoding="utf-8", errors="replace")
701
+ except (AttributeError, ValueError, OSError):
702
+ pass
703
+
704
+
705
+ if __name__ == "__main__":
706
+ _force_utf8_stdout()
707
+ sys.exit(main())