dsh-harness-kit 0.0.0-stage → 0.1.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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -2
  3. package/README.zh-CN.md +278 -0
  4. package/client.js +1272 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/DETAIL.en.md +97 -0
  7. package/docs/DETAIL.md +73 -0
  8. package/docs/assets/ui-new-task.png +0 -0
  9. package/docs/assets/ui-onboarding.png +0 -0
  10. package/docs/assets/ui-war-room.png +0 -0
  11. package/icon.svg +7 -0
  12. package/index.js +49 -0
  13. package/kernel/advance.js +96 -0
  14. package/kernel/bindings.js +24 -0
  15. package/kernel/commands.js +927 -0
  16. package/kernel/env.js +64 -0
  17. package/kernel/exec.js +41 -0
  18. package/kernel/flows.js +89 -0
  19. package/kernel/guards.js +79 -0
  20. package/kernel/miniyaml.js +133 -0
  21. package/kernel/models.js +104 -0
  22. package/kernel/panel.js +1103 -0
  23. package/kernel/paths.js +53 -0
  24. package/kernel/roles.js +67 -0
  25. package/kernel/setup.js +644 -0
  26. package/kernel/state.js +59 -0
  27. package/kernel/steer.js +27 -0
  28. package/kernel/sync.js +140 -0
  29. package/kernel/te.js +122 -0
  30. package/kernel/worktree.js +868 -0
  31. package/locale/en.json +14 -0
  32. package/locale/zh.json +14 -0
  33. package/package.json +63 -4
  34. package/packs/ai-coding/agents/business-analyst.md +90 -0
  35. package/packs/ai-coding/agents/code-reviewer.md +156 -0
  36. package/packs/ai-coding/agents/developer.md +147 -0
  37. package/packs/ai-coding/agents/project-manager.md +190 -0
  38. package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
  39. package/packs/ai-coding/agents/solution-architect.md +122 -0
  40. package/packs/ai-coding/agents/test-engineer.md +230 -0
  41. package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
  42. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
  43. package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
  44. package/packs/ai-coding/assets/scripts/harness.py +38 -0
  45. package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
  46. package/packs/ai-coding/assets/scripts/lib.py +1011 -0
  47. package/packs/ai-coding/assets/scripts/run_field.py +295 -0
  48. package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
  49. package/packs/ai-coding/assets/scripts/update_board.py +524 -0
  50. package/packs/ai-coding/assets/scripts/verify.py +184 -0
  51. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
  52. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
  53. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
  54. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
  55. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
  56. package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
  57. package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
  58. package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
  59. package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
  60. package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
  61. package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
  62. package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
  63. package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
  64. package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
  65. package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
  66. package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
  67. package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
  68. package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
  69. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
  70. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
  71. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
  72. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
  73. package/packs/ai-coding/flows/_router.yml +14 -0
  74. package/packs/ai-coding/flows/bugfix.yml +37 -0
  75. package/packs/ai-coding/flows/fix.yml +44 -0
  76. package/packs/ai-coding/flows/init.yml +83 -0
  77. package/packs/ai-coding/flows/new.yml +29 -0
  78. package/packs/ai-coding/flows/quick.yml +40 -0
  79. package/packs/ai-coding/flows/refactor.yml +50 -0
  80. package/packs/ai-coding/flows/standard.yml +49 -0
  81. package/packs/ai-coding/rules/code-standards.md +30 -0
  82. package/packs/ai-coding/rules/core.md +83 -0
  83. package/packs/ai-coding/templates/bugfix.md +29 -0
  84. package/packs/ai-coding/templates/memory-entry.md +46 -0
  85. package/packs/ai-coding/templates/proposal.md +47 -0
  86. package/packs/ai-coding/templates/spec-template.md +34 -0
  87. package/screenshots.json +5 -0
@@ -0,0 +1,524 @@
1
+ #!/usr/bin/env python3
2
+ """update_board.py — 看板(.harness/tasks/board.md)唯一写入门禁。
3
+
4
+ 纪律:PM/Worker **禁止直接编辑 board.md**,一律经本脚本更新(内核 updateBoard 只机械
5
+ 更新「状态/上次活动」两列,且本脚本提供的校验它不做)。漂移教训见 DESIGN.md:
6
+ 自由手写导致单元格混入 `|` 破列(15/16 列)、续接提示膨胀到 11 万字符。
7
+
8
+ 列格式契约(7 列,顺序固定):
9
+ 任务名 目录名同源,禁止含 `|`/空格
10
+ 状态 枚举:PENDING | IN_PROGRESS | CR_REVIEW_PENDING | AWAITING_ARCHIVE | DONE
11
+ Profile standard | quick | fix | refactor | 待裁决… | —
12
+ (看板用短名 fix,对应 proposal 里的 bugfix;内核四档 standard/quick/bugfix/refactor)
13
+ Profile standard | quick | bugfix | fix | fix-full | fix-light | refactor | 待裁决… | —
14
+ (fix 三态:bugfix=全流程(有 proposal.md);fix-full/fix-light=直通(质量门起步),
15
+ full 走 CR→TE,light 跳过 CR/TE;fix=直通裁决未定的过渡态,质量门裁决后必须
16
+ 改写为 fix-full 或 fix-light)
17
+ Apply进度 — | 已归档 | R<n>:<阶段链>(v4:链必须**完整等于**该 profile 的固定流程,
18
+ 不许省略阶段;跳过用 — 标记表达)
19
+ 固定流程模板(每阶段必须有标记):
20
+ standard/quick/bugfix:propose 审批1 Dev CR TE 审批2 验证
21
+ refactor: 影响面 propose 审批1 Dev CR TE 审批2 验证
22
+ fix/fix-full/fix-light(直通):质量门 Dev CR TE 验证
23
+ 每阶段后缀:✅完成 ▶当前(至多一个) …待做 ⛔阻塞(即当前卡点) —跳过
24
+ 顺序约束:▶/⛔ 之前不许有 …(前序阶段须先标 ✅ 或 —)
25
+ ✅ 须连续在链首;— 仅 fix-light 的 CR/TE 允许;
26
+ 例:R2:propose✅ 审批1✅ Dev▶ CR… TE… 审批2… 验证…
27
+ R1:质量门✅ Dev✅ CR— TE— 验证▶(fix-light)
28
+ 分支 分支名(可带 `(子工程)` 标注,逗号分隔多个)或 —
29
+ 上次活动 YYYY-MM-DD HH:mm(本脚本自动写当前时间,勿手填)
30
+ 续接提示 ≤300 字符一句话:「卡在X,下一步Y」;依赖前缀 [等 <任务>];禁 `|`/换行
31
+
32
+ 用法:
33
+ update_board.py <task> [--status S] [--profile P] [--apply A] [--branch B] [--hint H]
34
+ update_board.py --check 校验整个看板(doctor 用),违规非零退出
35
+ update_board.py --repair [--write] 规范化存量行(默认 dry-run 打印 diff)
36
+ """
37
+ import argparse
38
+ import re
39
+ import sys
40
+ import time
41
+ from pathlib import Path
42
+
43
+ STATUSES = ["PENDING", "IN_PROGRESS", "CR_REVIEW_PENDING", "AWAITING_ARCHIVE", "DONE"]
44
+ # 每 profile 的固定流程模板(v4.1,2026-11-12):已定档任务的 Apply 链必须完整等于模板
45
+ # (不许省略阶段,跳过用 — 标记)。profile 自描述三态:bugfix=全流程(同 standard 模板);
46
+ # fix-full/fix-light=直通模板 FIX_DIRECT(light 的 CR/TE 标 —);fix=直通裁决未定过渡态。
47
+ PROFILE_STAGES = {
48
+ "standard": ["propose", "审批1", "Dev", "CR", "TE", "审批2", "验证"],
49
+ "quick": ["propose", "审批1", "Dev", "CR", "TE", "审批2", "验证"],
50
+ "bugfix": ["propose", "审批1", "Dev", "CR", "TE", "审批2", "验证"],
51
+ "refactor": ["影响面", "propose", "审批1", "Dev", "CR", "TE", "审批2", "验证"],
52
+ }
53
+ FIX_DIRECT = ["质量门", "Dev", "CR", "TE", "验证"] # fix 直通模板;仅 fix-light 允许 CR/TE 标 —
54
+ # 未定档(—/待裁决…)时的并集顺序
55
+ STAGE_ORDER = ["影响面", "propose", "审批1", "质量门", "Dev", "CR", "TE", "审批2", "验证"]
56
+ STAGES = STAGE_ORDER # 兼容旧引用
57
+ MARKS = ["✅", "▶", "…", "⛔", "—"] # ✅完成 ▶当前(至多一个) …待做 ⛔阻塞(即当前卡点) —不适用/跳过
58
+ APPLY_RE = re.compile(
59
+ r"^(—|已归档|R\d+[::](" + "|".join(STAGE_ORDER) + r")[" + "".join(MARKS) + r"]"
60
+ r"( (" + "|".join(STAGE_ORDER) + r")[" + "".join(MARKS) + r"])*)$"
61
+ )
62
+ PROFILE_RE = re.compile(r"^(standard|quick|bugfix|fix|fix-full|fix-light|refactor|—|待裁决.*)$")
63
+
64
+
65
+ def profile_template(profile: str, root: Path = None, task: str = None):
66
+ """该 profile 的固定看板链模板(完整序列,不许省略;跳过用 — 标记表达)。
67
+
68
+ profile 自描述:bugfix 同 standard 模板;fix/fix-full/fix-light 均直通模板
69
+ (fix 为裁决未定过渡态)。未定档(—/待裁决)→ None(调用方走宽松子序列校验)。
70
+ root/task 参数保留仅为签名兼容。
71
+ """
72
+ if profile in ("standard", "quick", "bugfix"):
73
+ return PROFILE_STAGES["standard"]
74
+ if profile == "refactor":
75
+ return PROFILE_STAGES["refactor"]
76
+ if profile in ("fix", "fix-full", "fix-light"):
77
+ return FIX_DIRECT
78
+ return None
79
+
80
+
81
+ def infer_fix_profile(root: Path, task: str) -> str:
82
+ """遗留 fix 看板值三态消解(repair 用):有 proposal.md → bugfix;
83
+ bugfix.md 质量门裁决含 --full → fix-full、含 轻量 → fix-light;否则保持 fix(待裁决)。"""
84
+ base = Path(root) / ".harness" / "deliverables"
85
+ for d in (base / task, base / "_archive" / task):
86
+ if (d / "proposal.md").is_file():
87
+ return "bugfix"
88
+ for d in (base / task, base / "_archive" / task):
89
+ bf = d / "bugfix.md"
90
+ if bf.is_file():
91
+ text = bf.read_text(encoding="utf-8", errors="replace")
92
+ for m in re.finditer(r"裁决[^\n]*", text):
93
+ seg = m.group(0)
94
+ if "--full" in seg:
95
+ return "fix-full"
96
+ if "轻量" in seg:
97
+ return "fix-light"
98
+ return "fix"
99
+
100
+
101
+ def parse_chain(apply: str):
102
+ """解析 Apply进度 → (round, [(stage, mark), ...]);非链式返回 None。"""
103
+ m = re.match(r"^R(\d+)[::](.+)$", apply)
104
+ if not m:
105
+ return None
106
+ tokens = m.group(2).split()
107
+ chain = []
108
+ for tok in tokens:
109
+ if len(tok) < 2 or tok[-1] not in MARKS:
110
+ return None
111
+ chain.append((tok[:-1], tok[-1]))
112
+ return int(m.group(1)), chain
113
+
114
+
115
+ def chain_problems(chain, profile: str, root: Path = None, task: str = None):
116
+ """链语义校验 v4:已定档 profile 的链必须**完整等于固定流程模板**(省略阶段即违规,
117
+ 跳过用 — 标记);— 仅 fix 直通模板的 CR/TE 允许(轻量裁决)。
118
+ 通用约束:✅ 单调在链首、▶/⛔ 至多一个、▶/⛔ 之前不许有 …(前序须先 ✅ 或 —)。
119
+ 未定档(—/待裁决)保持子序列宽松校验。"""
120
+ template = profile_template(profile, root, task)
121
+ seen_current, seen_gap, seen_todo = False, False, False
122
+ for stage, mark in chain:
123
+ if mark in ("▶", "⛔"):
124
+ if seen_current:
125
+ return ["▶/⛔ 当前标记至多一个"]
126
+ if seen_todo:
127
+ return ["▶/⛔ 不能出现在 … 待做阶段之后(前序阶段须先标 ✅ 或 —)"]
128
+ seen_current = True
129
+ if mark == "…":
130
+ seen_todo = True
131
+ if mark in ("…", "▶", "⛔"):
132
+ seen_gap = True
133
+ elif mark == "✅" and seen_gap:
134
+ return ["✅ 只能出现在未开始阶段之前(已完成阶段应连续在链首,— 跳过不限位置)"]
135
+ if template is None:
136
+ # 未定档/无法消解:宽松子序列校验(阶段属于并集、顺序递增不重复)
137
+ order = {s: i for i, s in enumerate(STAGE_ORDER)}
138
+ idxs = []
139
+ for stage, _ in chain:
140
+ if stage not in order:
141
+ return [f"阶段 {stage!r} 非法(可选 {'/'.join(STAGE_ORDER)})"]
142
+ idxs.append(order[stage])
143
+ if idxs != sorted(idxs) or len(set(idxs)) != len(idxs):
144
+ return ["阶段顺序不符合流程先后(" + "→".join(STAGE_ORDER) + ")"]
145
+ return []
146
+ stages = [s for s, _ in chain]
147
+ if stages != template:
148
+ return [
149
+ f"链必须完整覆盖 {profile} 固定流程({' → '.join(template)});"
150
+ f"当前为 {' → '.join(stages) or '(空)'},缺省阶段不许省略,跳过请标 —"
151
+ ]
152
+ skippable = {"CR", "TE"} if profile == "fix-light" else set()
153
+ for stage, mark in chain:
154
+ if mark == "—" and stage not in skippable:
155
+ return [f"{stage} 不允许标 —(仅 fix-light 轻量裁决可跳过 CR/TE)"]
156
+ return []
157
+ HINT_MAX = 300
158
+
159
+ TEMPLATE = """# 任务看板
160
+
161
+ > **状态机**:PENDING → IN_PROGRESS → CR_REVIEW_PENDING → IN_PROGRESS → AWAITING_ARCHIVE → DONE →(重开轮次)→ PENDING
162
+ > **Apply 子步骤**:按 profile 的完整流程记录于「Apply进度」列(▶=当前阶段;格式契约见脚本 docstring)
163
+ > **续接机制**:任何人读看板 + deliverables 即可接手继续
164
+
165
+ | 任务名 | 状态 | Profile | Apply进度 | 分支 | 上次活动 | 续接提示 |
166
+ |--------|------|---------|-----------|------|---------|----------|
167
+
168
+ > **写入纪律**:禁止直接编辑本文件,一律 `python3 .harness/scripts/update_board.py <任务> [--status …] [--apply …] [--branch …] [--hint …]`(格式契约见脚本 docstring;续接提示 ≤300 字符一句话「卡在X,下一步Y」,依赖前缀 [等 任务名])。
169
+ """
170
+
171
+
172
+ def board_path(root: Path) -> Path:
173
+ return root / ".harness" / "tasks" / "board.md"
174
+
175
+
176
+ def now_stamp() -> str:
177
+ return time.strftime("%Y-%m-%d %H:%M")
178
+
179
+
180
+ def sanitize_cell(text: str) -> str:
181
+ """单元格消毒:去 `**`、`|`→`/`、换行→空格、折叠空白。"""
182
+ t = (text or "").replace("**", "").replace("|", "/")
183
+ t = re.sub(r"\s+", " ", t).strip()
184
+ return t
185
+
186
+
187
+ def parse_row(line: str):
188
+ """解析数据行为 7 格:超列时溢出并入「续接提示」(管道符只可能从自由文本混入)。"""
189
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
190
+ if len(cells) > 7:
191
+ cells = cells[:6] + [" / ".join(cells[6:])]
192
+ while len(cells) < 7:
193
+ cells.append("—")
194
+ return cells
195
+
196
+
197
+ def render_row(cells) -> str:
198
+ return "| " + " | ".join(cells) + " |"
199
+
200
+
201
+ def read_rows(text: str):
202
+ """返回 (lines, rows):rows 为 (行号, cells) 列表,跳过表头/分隔线。"""
203
+ lines = text.splitlines()
204
+ rows = []
205
+ for i, line in enumerate(lines):
206
+ if not line.startswith("|"):
207
+ continue
208
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
209
+ head = cells[0] if cells else ""
210
+ if head == "任务名" or (head and not head.strip("-: ")):
211
+ continue
212
+ rows.append((i, parse_row(line)))
213
+ return lines, rows
214
+
215
+
216
+ def validate(cells, root: Path = None):
217
+ """校验一行 7 格,返回违规信息列表(空 = 合规)。root 用于 fix 模板二义消解。"""
218
+ problems = []
219
+ name, status, profile, apply, branch, date, hint = cells
220
+ if "|" in name or not name or " " in name:
221
+ problems.append(f"任务名非法:{name!r}")
222
+ if status not in STATUSES:
223
+ problems.append(f"状态非枚举:{status!r}(可选 {'/'.join(STATUSES)})")
224
+ if not PROFILE_RE.match(profile):
225
+ problems.append(f"Profile 非法:{profile!r}(可选 standard/quick/bugfix/fix/fix-full/fix-light/refactor/待裁决…/—)")
226
+ if not APPLY_RE.match(apply):
227
+ problems.append(f"Apply进度 不合语法:{apply!r}(应为 —|已归档|R<n>:阶段链,阶段 {'/'.join(STAGE_ORDER)} + 标记 {'/'.join(MARKS)})")
228
+ else:
229
+ parsed = parse_chain(apply)
230
+ if parsed:
231
+ _, chain = parsed
232
+ problems.extend(chain_problems(chain, profile, root, name))
233
+ if not re.match(r"^\d{4}-\d{2}-\d{2}( \d{2}:\d{2})?$", date):
234
+ problems.append(f"上次活动格式非法:{date!r}(YYYY-MM-DD 或 YYYY-MM-DD HH:mm)")
235
+ if len(hint) > HINT_MAX:
236
+ problems.append(f"续接提示超长:{len(hint)} 字符(上限 {HINT_MAX})")
237
+ return problems
238
+
239
+
240
+ def normalize_chain(root: Path, task: str, profile: str, status: str, apply: str):
241
+ """把 Apply 链规范化为该 profile 固定流程模板(repair 用),返回 (round, [(stage, mark)]) 或 None。
242
+
243
+ 标记推导:旧链已有的阶段沿用标记;缺失阶段按位置补齐——在最早有进展(✅/▶/⛔)阶段
244
+ 之前 → ✅(已过),之后 → …(未做);AWAITING_ARCHIVE 视为全程完成,缺失一律 ✅。
245
+ 非法 —(非 fix-light 的 CR/TE)按同规则重推导。apply=—(未开始)→ 全 … 链 R1。
246
+ """
247
+ template = profile_template(profile, root, task)
248
+ if template is None or status == "DONE" or apply == "已归档":
249
+ return None
250
+ parsed = parse_chain(apply)
251
+ if apply != "—" and not parsed:
252
+ return None # 非法格式不猜,留给人工
253
+ old = dict(parsed[1]) if parsed else {}
254
+ rn = parsed[0] if parsed else 1
255
+ tpos = {s: i for i, s in enumerate(template)}
256
+ first_prog = None
257
+ for s, mk in (parsed[1] if parsed else []):
258
+ if s in tpos and mk in ("✅", "▶", "⛔") and (first_prog is None or tpos[s] < first_prog):
259
+ first_prog = tpos[s]
260
+ out = []
261
+ for idx, stage in enumerate(template):
262
+ mk = old.get(stage)
263
+ skip_ok = profile == "fix-light" and stage in ("CR", "TE")
264
+ if mk is None or (mk == "—" and not skip_ok):
265
+ if status == "AWAITING_ARCHIVE":
266
+ mk = "✅"
267
+ else:
268
+ mk = "✅" if (first_prog is not None and idx < first_prog) else "…"
269
+ out.append((stage, mk))
270
+ return rn, out
271
+
272
+
273
+ def cmd_update(root: Path, args) -> int:
274
+ task = args.task
275
+ if not task or "|" in task or " " in task:
276
+ print(f"❌ 任务名非法:{task!r}")
277
+ return 2
278
+ board = board_path(root)
279
+ if not board.is_file():
280
+ board.parent.mkdir(parents=True, exist_ok=True)
281
+ board.write_text(TEMPLATE, encoding="utf-8")
282
+ lines, rows = read_rows(board.read_text(encoding="utf-8"))
283
+
284
+ updates = {}
285
+ if args.status is not None:
286
+ if args.status not in STATUSES:
287
+ print(f"❌ --status 非枚举:{args.status!r}(可选 {'/'.join(STATUSES)})")
288
+ return 2
289
+ updates[1] = args.status
290
+ if args.profile is not None:
291
+ if not PROFILE_RE.match(args.profile):
292
+ print(f"❌ --profile 非法:{args.profile!r}")
293
+ return 2
294
+ updates[2] = args.profile
295
+ if args.apply is not None:
296
+ # 半角冒号归一为全角(契约展示形)
297
+ m = re.match(r"^(R\d+):", args.apply)
298
+ normalized = ("R" + args.apply[1:].replace(":", ":", 1)) if m else args.apply
299
+ if not APPLY_RE.match(normalized):
300
+ print(f"❌ --apply 不合语法:{args.apply!r}")
301
+ print(f" 应为 —|已归档|R<n>:阶段链(阶段 {'/'.join(STAGE_ORDER)},标记 {'/'.join(MARKS)})")
302
+ print(" 例:R2:propose✅ 审批1✅ Dev▶ CR… ;fix 直通:R1:质量门✅ Dev✅ CR— TE— 验证▶")
303
+ return 2
304
+ # 语义校验需结合行内 profile:先取现值(待写入时再用行值复核)
305
+ updates[3] = normalized
306
+ if args.branch is not None:
307
+ updates[4] = sanitize_cell(args.branch) or "—"
308
+ if args.hint is not None:
309
+ h = sanitize_cell(args.hint) or "—"
310
+ if len(h) > HINT_MAX:
311
+ print(f"⚠️ 续接提示 {len(h)} 字符,超限截断至 {HINT_MAX}:详情请放 deliverables,看板只写「卡在X,下一步Y」")
312
+ h = h[:HINT_MAX]
313
+ updates[6] = h
314
+
315
+ # 时间戳:默认现在;--at 回填(仅日期补 00:00,契约分钟级精度)
316
+ stamp = now_stamp()
317
+ if args.at is not None:
318
+ a = args.at.strip()
319
+ if re.match(r"^\d{4}-\d{2}-\d{2}$", a):
320
+ a += " 00:00"
321
+ if not re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$", a):
322
+ print(f"❌ --at 非法:{args.at!r}(应为 YYYY-MM-DD[ HH:mm])")
323
+ return 2
324
+ stamp = a
325
+
326
+ hit = None
327
+ dup = 0
328
+ for i, cells in rows:
329
+ if cells[0] == task:
330
+ if hit is None:
331
+ hit = (i, cells)
332
+ else:
333
+ dup += 1
334
+ if dup:
335
+ print(f"❌ 任务 {task!r} 在看板中有 {dup + 1} 行(契约:一任务一行)。")
336
+ print(" 先运行 --repair --write 合并重复行,再重试")
337
+ return 2
338
+ if hit:
339
+ i, cells = hit
340
+ for idx, val in updates.items():
341
+ cells[idx] = val
342
+ else:
343
+ cells = [task, "—", "—", "—", "—", stamp, "—"]
344
+ for idx, val in updates.items():
345
+ cells[idx] = val
346
+ # Apply 链语义复核(结合行内 profile 与 fix 二义消解;新行/老行都校验)
347
+ parsed = parse_chain(cells[3])
348
+ if parsed:
349
+ probs = chain_problems(parsed[1], cells[2], root, task)
350
+ if probs:
351
+ print(f"❌ Apply 链语义违规:{probs[0]}")
352
+ return 2
353
+ if hit:
354
+ cells[5] = stamp
355
+ lines[i] = render_row(cells)
356
+ else:
357
+ # 新行插到表格末尾(最后一个表格行之后),不能盲 append——
358
+ # 文件尾部有「写入纪律」引用块,追加会把行落到表格外。
359
+ new_row = render_row(cells)
360
+ last_row = max((i for i, ln in enumerate(lines) if ln.startswith("|")), default=-1)
361
+ if last_row >= 0:
362
+ lines.insert(last_row + 1, new_row)
363
+ else:
364
+ lines.append(new_row)
365
+ board.write_text("\n".join(lines) + "\n", encoding="utf-8")
366
+ print(f"✅ 看板已更新:{task}({', '.join(f'列{idx}' for idx in sorted(updates)) or '仅活动时间'})")
367
+ return 0
368
+
369
+
370
+ def cmd_check(root: Path) -> int:
371
+ board = board_path(root)
372
+ if not board.is_file():
373
+ print("ℹ️ 无 board.md,跳过")
374
+ return 0
375
+ _, rows = read_rows(board.read_text(encoding="utf-8"))
376
+ bad = 0
377
+ seen = {}
378
+ for i, cells in rows:
379
+ if cells[0] in seen:
380
+ print(f"❌ 行{i + 1} [{cells[0]}] 任务名重复(首见于行{seen[cells[0]] + 1},契约:一任务一行)")
381
+ bad += 1
382
+ else:
383
+ seen[cells[0]] = i
384
+ problems = validate(cells, root)
385
+ for p in problems:
386
+ print(f"❌ 行{i + 1} [{cells[0]}] {p}")
387
+ bad += 1
388
+ if bad:
389
+ print(f"看板体检 FAIL:{bad} 处违规。修复:python3 .harness/scripts/update_board.py --repair --write")
390
+ return 1
391
+ print(f"✅ 看板体检 PASS({len(rows)} 行全合规)")
392
+ return 0
393
+
394
+
395
+ def cmd_repair(root: Path, write: bool) -> int:
396
+ """规范化存量行:破列合并、状态提纯、Profile 映射、超长截断、DONE→已归档。"""
397
+ board = board_path(root)
398
+ if not board.is_file():
399
+ print("ℹ️ 无 board.md,跳过")
400
+ return 0
401
+ lines, rows = read_rows(board.read_text(encoding="utf-8"))
402
+ changed = 0
403
+ # 表头/分隔线规范化(曾有 Agent 用空格把单元格撑到 3.8 万字符)
404
+ CANON = {
405
+ "header": "| 任务名 | 状态 | Profile | Apply进度 | 分支 | 上次活动 | 续接提示 |",
406
+ "sep": "|--------|------|---------|-----------|------|---------|----------|",
407
+ }
408
+ for i, line in enumerate(lines):
409
+ if not line.startswith("|"):
410
+ continue
411
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
412
+ head = cells[0] if cells else ""
413
+ canon = CANON["header"] if head == "任务名" else (CANON["sep"] if head and not head.strip("-: ") else None)
414
+ if canon and line != canon:
415
+ print(f"── 行{i + 1} 表头/分隔线规范化({len(line)} → {len(canon)} 字符)")
416
+ if write:
417
+ lines[i] = canon
418
+ changed += 1
419
+ # 重复任务行合并:契约一任务一行。DONE 是终态快照 → 优先保留最后一个非 DONE 行;全 DONE 则保留最后一行
420
+ by_name = {}
421
+ for i, cells in rows:
422
+ by_name.setdefault(cells[0], []).append(i)
423
+ drop = set()
424
+ row_map = dict(rows)
425
+ for name, idxs in by_name.items():
426
+ if len(idxs) < 2:
427
+ continue
428
+ keep = next((i for i in reversed(idxs) if row_map[i][1] != "DONE"), idxs[-1])
429
+ for i in idxs:
430
+ if i != keep:
431
+ drop.add(i)
432
+ print(f"── 行{i + 1} [{name}] 重复行删除(保留行{keep + 1})")
433
+ changed += 1
434
+ if drop:
435
+ rows = [(i, c) for i, c in rows if i not in drop]
436
+ for i, cells in rows:
437
+ before = list(cells)
438
+ # 状态提纯:提取前缀枚举,括注信息并入续接提示(若提示为占位符)
439
+ m = re.match(r"^(PENDING|IN_PROGRESS|CR_REVIEW_PENDING|AWAITING_ARCHIVE|DONE)\s*[((]?(.*?)[))]?$", cells[1])
440
+ if m:
441
+ cells[1] = m.group(1)
442
+ extra = sanitize_cell(m.group(2))
443
+ if extra and cells[6] in ("—", ""):
444
+ cells[6] = extra
445
+ # Profile 归一:大小写归一,非法值→—;遗留 fix 短名三态消解(proposal.md/质量门裁决)
446
+ low = cells[2].lower()
447
+ if low in ("standard", "quick", "bugfix", "fix", "fix-full", "fix-light", "refactor"):
448
+ cells[2] = low
449
+ elif not PROFILE_RE.match(cells[2]):
450
+ cells[2] = "—"
451
+ if cells[2] == "fix":
452
+ cells[2] = infer_fix_profile(root, cells[0])
453
+ # DONE 行 Apply进度规范形
454
+ if cells[1] == "DONE" and not APPLY_RE.match(cells[3]):
455
+ cells[3] = "已归档"
456
+ # 链规范化 v4:已定档 profile 的链必须完整等于固定流程模板(缺省补齐、非法 — 重推导)
457
+ norm = normalize_chain(root, cells[0], cells[2], cells[1], cells[3])
458
+ if norm:
459
+ rn, nchain = norm
460
+ new_apply = f"R{rn}:" + " ".join(s + mk for s, mk in nchain)
461
+ if new_apply != cells[3]:
462
+ cells[3] = new_apply
463
+ # ▶ 当前标记推导:实施中任务且链上无 ▶/⛔ 时,首个待做(…)阶段即当前
464
+ if cells[1] in ("IN_PROGRESS", "CR_REVIEW_PENDING"):
465
+ parsed = parse_chain(cells[3])
466
+ if parsed and not any(mk in ("▶", "⛔") for _, mk in parsed[1]):
467
+ rn, marked, new_chain = parsed[0], False, []
468
+ for s, mk in parsed[1]:
469
+ if not marked and mk == "…":
470
+ mk, marked = "▶", True
471
+ new_chain.append((s, mk))
472
+ if marked:
473
+ cells[3] = f"R{rn}:" + " ".join(s + mk for s, mk in new_chain)
474
+ # 自由文本列消毒 + 截断
475
+ for idx in (3, 4, 6):
476
+ cells[idx] = sanitize_cell(cells[idx]) or "—"
477
+ if len(cells[6]) > HINT_MAX:
478
+ cells[6] = cells[6][:HINT_MAX]
479
+ if not re.match(r"^\d{4}-\d{2}-\d{2}( \d{2}:\d{2})?$", cells[5]):
480
+ cells[5] = cells[5][:16] if re.match(r"^\d{4}-\d{2}-\d{2}", cells[5]) else "—"
481
+ if cells != before:
482
+ changed += 1
483
+ print(f"── 行{i + 1} [{cells[0]}]")
484
+ for idx, (a, b) in enumerate(zip(before, cells)):
485
+ if a != b:
486
+ show_a = a[:60] + ("…" if len(a) > 60 else "")
487
+ print(f" 列{idx}: {show_a} → {b}")
488
+ # 内容合规但行文本带冗余填充(空格撑宽)时也重渲染
489
+ if write and lines[i] != render_row(cells):
490
+ lines[i] = render_row(cells)
491
+ print(f"{'已修复' if write else 'dry-run:将修复'} {changed}/{len(rows)} 行" + ("" if write else "(加 --write 落盘)"))
492
+ if write and changed:
493
+ if drop:
494
+ lines = [line for i, line in enumerate(lines) if i not in drop]
495
+ board.write_text("\n".join(lines) + "\n", encoding="utf-8")
496
+ return 0
497
+
498
+
499
+ def main() -> int:
500
+ ap = argparse.ArgumentParser(description="看板唯一写入门禁(格式契约见模块 docstring)")
501
+ ap.add_argument("task", nargs="?", help="任务名")
502
+ ap.add_argument("--status")
503
+ ap.add_argument("--profile")
504
+ ap.add_argument("--apply")
505
+ ap.add_argument("--branch")
506
+ ap.add_argument("--hint")
507
+ ap.add_argument("--at", help="覆盖上次活动时间戳(YYYY-MM-DD[ HH:mm],仅日期补 00:00);默认当前时间")
508
+ ap.add_argument("--check", action="store_true", help="校验整个看板")
509
+ ap.add_argument("--repair", action="store_true", help="规范化存量行(默认 dry-run)")
510
+ ap.add_argument("--write", action="store_true", help="配合 --repair 落盘")
511
+ args = ap.parse_args()
512
+ root = Path.cwd()
513
+
514
+ if args.check:
515
+ return cmd_check(root)
516
+ if args.repair:
517
+ return cmd_repair(root, args.write)
518
+ if not args.task:
519
+ ap.error("缺少任务名(或用 --check / --repair)")
520
+ return cmd_update(root, args)
521
+
522
+
523
+ if __name__ == "__main__":
524
+ sys.exit(main())