sdtk-spec-kit 0.4.11 → 0.4.14

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 (143) hide show
  1. package/README.md +353 -353
  2. package/assets/atlas/build_atlas.py +880 -880
  3. package/assets/atlas/doc_atlas_viewer_template.html +3796 -3796
  4. package/assets/atlas/vendor/mermaid.min.js +2029 -2029
  5. package/assets/keys/spec-entitlement-public.pem +9 -9
  6. package/assets/manifest/toolkit-bundle.manifest.json +496 -496
  7. package/assets/manifest/toolkit-bundle.sha256.txt +97 -97
  8. package/assets/toolkit/toolkit/AGENTS.md +157 -241
  9. package/assets/toolkit/toolkit/README.md +51 -51
  10. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +206 -206
  11. package/assets/toolkit/toolkit/install.ps1 +362 -362
  12. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +95 -91
  13. package/assets/toolkit/toolkit/runtimes/codex/CODEX_TEMPLATE.md +70 -69
  14. package/assets/toolkit/toolkit/scripts/agents/run-claude-task.ps1 +332 -332
  15. package/assets/toolkit/toolkit/scripts/agents/run-codex-task.ps1 +618 -618
  16. package/assets/toolkit/toolkit/scripts/agents/validate-mailbox-formal-artifact.py +87 -87
  17. package/assets/toolkit/toolkit/scripts/generate-code-handoff.ps1 +317 -317
  18. package/assets/toolkit/toolkit/scripts/init-feature.ps1 +262 -262
  19. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +180 -180
  20. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +209 -209
  21. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +139 -139
  22. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +143 -143
  23. package/assets/toolkit/toolkit/sdtk-spec.config.json +28 -28
  24. package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +50 -50
  25. package/assets/toolkit/toolkit/session/SDTK_ACTIVE_BOOTSTRAP.md +46 -46
  26. package/assets/toolkit/toolkit/session/SDTK_AGENT_WORKING_RULES.md +48 -48
  27. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/SKILL.md +111 -111
  28. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/scripts/generate_api_design_detail.py +732 -732
  29. package/assets/toolkit/toolkit/skills/sdtk-api-doc/SKILL.md +79 -79
  30. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +85 -85
  31. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +46 -46
  32. package/assets/toolkit/toolkit/skills/sdtk-design-layout/SKILL.md +91 -91
  33. package/assets/toolkit/toolkit/skills/sdtk-design-layout/scripts/render_design_layout_images.py +246 -246
  34. package/assets/toolkit/toolkit/skills/sdtk-dev/SKILL.md +133 -133
  35. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/code-quality-reviewer.md +34 -34
  36. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/implementer.md +60 -60
  37. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/spec-reviewer.md +41 -41
  38. package/assets/toolkit/toolkit/skills/sdtk-dev-backend/SKILL.md +80 -80
  39. package/assets/toolkit/toolkit/skills/sdtk-dev-frontend/SKILL.md +80 -80
  40. package/assets/toolkit/toolkit/skills/sdtk-mailbox-dispatch/SKILL.md +73 -73
  41. package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +176 -108
  42. package/assets/toolkit/toolkit/skills/sdtk-pm/SKILL.md +74 -74
  43. package/assets/toolkit/toolkit/skills/sdtk-qa/SKILL.md +75 -75
  44. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/SKILL.md +108 -107
  45. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/excel-image-export.md +51 -51
  46. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/figma-mcp.md +54 -54
  47. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/numbering-rules.md +28 -28
  48. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/renumber_flow_action_spec_global.py +136 -136
  49. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/validate_flow_action_spec_numbering.py +414 -414
  50. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/SKILL.md +110 -110
  51. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/scripts/validate_test_case_spec.py +97 -97
  52. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +330 -330
  53. package/assets/toolkit/toolkit/skills-claude/api-design-spec/SKILL.md +116 -116
  54. package/assets/toolkit/toolkit/skills-claude/api-doc/SKILL.md +87 -87
  55. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +59 -59
  56. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +67 -67
  57. package/assets/toolkit/toolkit/skills-claude/design-layout/SKILL.md +91 -91
  58. package/assets/toolkit/toolkit/skills-claude/dev/SKILL.md +59 -59
  59. package/assets/toolkit/toolkit/skills-claude/dev-backend/SKILL.md +73 -73
  60. package/assets/toolkit/toolkit/skills-claude/dev-frontend/SKILL.md +73 -73
  61. package/assets/toolkit/toolkit/skills-claude/mailbox-dispatch/SKILL.md +73 -73
  62. package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +88 -42
  63. package/assets/toolkit/toolkit/skills-claude/pm/SKILL.md +88 -88
  64. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +58 -58
  65. package/assets/toolkit/toolkit/skills-claude/screen-design-spec/SKILL.md +113 -112
  66. package/assets/toolkit/toolkit/skills-claude/test-case-spec/SKILL.md +115 -115
  67. package/assets/toolkit/toolkit/templates/QUALITY_CHECKLIST.md +124 -124
  68. package/assets/toolkit/toolkit/templates/README.md +68 -68
  69. package/assets/toolkit/toolkit/templates/SHARED_PLANNING.md +81 -81
  70. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_CREATION_RULES.md +21 -21
  71. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_DETAIL_TEMPLATE.md +67 -67
  72. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_FLOWCHART_CREATION_RULES.md +468 -468
  73. package/assets/toolkit/toolkit/templates/docs/api/API_ENDPOINTS_TEMPLATE.md +229 -229
  74. package/assets/toolkit/toolkit/templates/docs/api/FEATURE_API_TEMPLATE.yaml +20 -20
  75. package/assets/toolkit/toolkit/templates/docs/api/FLOWCHART_CREATION_RULES.md +20 -20
  76. package/assets/toolkit/toolkit/templates/docs/api/YAML_CREATION_RULES.md +128 -128
  77. package/assets/toolkit/toolkit/templates/docs/api/feature_api_flow_list_TEMPLATE.txt +12 -12
  78. package/assets/toolkit/toolkit/templates/docs/architecture/ARCH_DESIGN_TEMPLATE.md +109 -109
  79. package/assets/toolkit/toolkit/templates/docs/database/DATABASE_SPEC_TEMPLATE.md +175 -175
  80. package/assets/toolkit/toolkit/templates/docs/design/DESIGN_LAYOUT_TEMPLATE.md +60 -60
  81. package/assets/toolkit/toolkit/templates/docs/dev/FEATURE_IMPL_PLAN_TEMPLATE.md +117 -117
  82. package/assets/toolkit/toolkit/templates/docs/dev/OPS_HANDOFF_CREATION_RULES.md +369 -369
  83. package/assets/toolkit/toolkit/templates/docs/discovery/REQUIREMENT_TEMPLATE.md +155 -155
  84. package/assets/toolkit/toolkit/templates/docs/product/BACKLOG_TEMPLATE.md +50 -50
  85. package/assets/toolkit/toolkit/templates/docs/product/CONDENSED_UPSTREAM_INPUT_TEMPLATE.md +276 -276
  86. package/assets/toolkit/toolkit/templates/docs/product/PRD_TEMPLATE.md +66 -66
  87. package/assets/toolkit/toolkit/templates/docs/product/PROJECT_INITIATION_TEMPLATE.md +98 -98
  88. package/assets/toolkit/toolkit/templates/docs/qa/CONTROLLER_ACCEPTANCE_TEMPLATE.md +90 -90
  89. package/assets/toolkit/toolkit/templates/docs/qa/QA_RELEASE_REPORT_TEMPLATE.md +162 -162
  90. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_CREATION_RULES.md +129 -129
  91. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_TEMPLATE.md +104 -104
  92. package/assets/toolkit/toolkit/templates/docs/specs/BA_SPEC_TEMPLATE.md +139 -139
  93. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_CREATION_RULES.md +220 -220
  94. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_TEMPLATE.md +197 -197
  95. package/assets/toolkit/toolkit/templates/handoffs/ARCH_TO_DEV.md +31 -31
  96. package/assets/toolkit/toolkit/templates/handoffs/BA_TO_ARCH.md +28 -28
  97. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE1_SPEC_REVIEW.md +26 -26
  98. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE2_CODE_QUALITY_REVIEW.md +20 -20
  99. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_QA.md +33 -33
  100. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_SDTK_CODE.md +60 -60
  101. package/assets/toolkit/toolkit/templates/handoffs/PM_TO_BA.md +30 -30
  102. package/assets/toolkit/toolkit/templates/handoffs/QA_RELEASE_DECISION.md +26 -26
  103. package/assets/toolkit/toolkit/templates/mailbox/AGENT_REPORT_TEMPLATE.md +63 -63
  104. package/assets/toolkit/toolkit/templates/mailbox/AGENT_TASK_TEMPLATE.md +76 -76
  105. package/bin/sdtk.js +15 -15
  106. package/package.json +48 -48
  107. package/src/commands/activate.js +94 -94
  108. package/src/commands/atlas.js +339 -339
  109. package/src/commands/auth.js +85 -85
  110. package/src/commands/entitlement.js +170 -170
  111. package/src/commands/generate.js +191 -170
  112. package/src/commands/help.js +248 -246
  113. package/src/commands/init.js +117 -117
  114. package/src/commands/project.js +51 -51
  115. package/src/commands/runtime.js +239 -239
  116. package/src/commands/update.js +11 -11
  117. package/src/index.js +68 -68
  118. package/src/lib/activation-state.js +68 -68
  119. package/src/lib/args.js +116 -116
  120. package/src/lib/atlas-config.js +200 -200
  121. package/src/lib/atlas-runner.js +435 -435
  122. package/src/lib/browser-open.js +39 -39
  123. package/src/lib/capabilities.js +89 -89
  124. package/src/lib/entitlements.js +245 -245
  125. package/src/lib/errors.js +41 -41
  126. package/src/lib/github-access.js +143 -143
  127. package/src/lib/legacy-auth-migration.js +56 -56
  128. package/src/lib/license-activation.js +386 -386
  129. package/src/lib/powershell.js +85 -85
  130. package/src/lib/premium-loader.js +124 -124
  131. package/src/lib/premium-packs.js +333 -333
  132. package/src/lib/premium-sync.js +235 -235
  133. package/src/lib/project-audit.js +332 -332
  134. package/src/lib/project-config.js +108 -108
  135. package/src/lib/project-ingest.js +450 -450
  136. package/src/lib/project-refresh.js +666 -666
  137. package/src/lib/project-target-guard.js +79 -79
  138. package/src/lib/requirement-analysis.js +14 -4
  139. package/src/lib/scope.js +83 -83
  140. package/src/lib/state.js +74 -74
  141. package/src/lib/suite-state.js +70 -70
  142. package/src/lib/toolkit-payload.js +99 -99
  143. package/src/lib/update.js +333 -333
@@ -1,414 +1,414 @@
1
- from __future__ import annotations
2
-
3
- import argparse
4
- import re
5
- import sys
6
- from dataclasses import dataclass
7
- from pathlib import Path
8
-
9
-
10
- TABLE_ROW_RE = re.compile(r"^\|.*\|\s*$")
11
- TABLE_SEP_RE = re.compile(r"^\|\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|\s*$")
12
- HEADING_RE = re.compile(r"^(#{1,6})\s+(.*\S)\s*$")
13
- SCREEN_SECTION_HEADING_RE = re.compile(r"^###\s+(.*\S)\s*$", re.MULTILINE)
14
- VI_DIACRITIC_RE = re.compile(r"[À-ỹ]")
15
- VI_PHRASE_RE = re.compile(
16
- r"\b("
17
- r"thuc thi|hien thi|cap nhat|bo sung|can xac nhan|trong anh|"
18
- r"duoc tra kem|tao lich|theo user|muc global|thay the cho|bao gom"
19
- r")\b",
20
- re.IGNORECASE,
21
- )
22
- INLINE_HEADING_RE = re.compile(r".+\s#{2,}\s+\S")
23
- IMAGE_LINK_RE = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
24
- PLANTUML_FENCE_START_RE = re.compile(r"^\s*```plantuml\s*$", re.IGNORECASE)
25
- NEW_STYLE_ACTIVITY_LINE_RE = re.compile(
26
- r"^\s*(start|stop|partition\s+\"|if\s*\(|fork(?:\s+again)?\b|end\s+fork\b|note\s+(?:right|left|top|bottom)\b|:[^;\n]+;)",
27
- re.IGNORECASE,
28
- )
29
- LEGACY_ACTIVITY_START_RE = re.compile(r"\(\*\)")
30
- LEGACY_EDGE_LABEL_RE = re.compile(r"-->\s*\[")
31
- MIXED_ACTIVITY_ARROW_RE = re.compile(r":[^;\n]+;\s*-->")
32
-
33
-
34
- @dataclass(frozen=True)
35
- class Occurrence:
36
- number: int
37
- section: str
38
- line_no: int
39
- raw_line: str
40
-
41
-
42
- def _split_table_row(line: str) -> list[str]:
43
- # Keep it simple: markdown tables in our spec are plain and don't escape pipes.
44
- parts = [p.strip() for p in line.strip().strip("|").split("|")]
45
- return parts
46
-
47
-
48
- def _read_text(path: Path) -> str:
49
- # Prefer UTF-8; fallback to cp1252-ish if user saved without UTF-8.
50
- for enc in ("utf-8", "utf-8-sig", "cp1252"):
51
- try:
52
- return path.read_text(encoding=enc)
53
- except UnicodeDecodeError:
54
- continue
55
- return path.read_text(errors="replace")
56
-
57
-
58
- def collect_hygiene_issues(md_text: str, *, en_check: bool) -> dict[str, list[tuple[int, str]]]:
59
- issues: dict[str, list[tuple[int, str]]] = {
60
- "encoding": [],
61
- "vi_diacritic": [],
62
- "vi_phrase": [],
63
- "inline_heading": [],
64
- }
65
- lines = md_text.splitlines()
66
- in_code_block = False
67
-
68
- for idx, line in enumerate(lines, start=1):
69
- stripped = line.strip()
70
- if stripped.startswith("```"):
71
- in_code_block = not in_code_block
72
- continue
73
- if in_code_block:
74
- continue
75
-
76
- if "�" in line or "ↁE" in line:
77
- issues["encoding"].append((idx, line))
78
-
79
- # A common corruption symptom: merged headings inside normal text lines.
80
- if INLINE_HEADING_RE.search(line) and not stripped.startswith("#"):
81
- issues["inline_heading"].append((idx, line))
82
-
83
- if en_check:
84
- lowered = stripped.lower()
85
- if "original text" in lowered:
86
- continue
87
- if VI_DIACRITIC_RE.search(line):
88
- issues["vi_diacritic"].append((idx, line))
89
- elif VI_PHRASE_RE.search(line):
90
- issues["vi_phrase"].append((idx, line))
91
-
92
- return issues
93
-
94
-
95
- def _is_root_relative_docs_href(href: str) -> bool:
96
- normalized = href.strip().replace("\\", "/").lower()
97
- if not normalized:
98
- return False
99
- if re.match(r"^[a-z][a-z0-9+.-]*://", normalized):
100
- return False
101
- if normalized.startswith(("mailto:", "tel:", "data:", "#")):
102
- return False
103
- return normalized.startswith(("docs/", "./docs/", "/docs/"))
104
-
105
-
106
- def collect_screen_image_path_issues(md_text: str) -> list[tuple[int, str]]:
107
- issues: list[tuple[int, str]] = []
108
- lines = md_text.splitlines()
109
- in_code_block = False
110
- expecting_image_line = False
111
-
112
- for idx, line in enumerate(lines, start=1):
113
- stripped = line.strip()
114
- if stripped.startswith("```"):
115
- in_code_block = not in_code_block
116
- expecting_image_line = False
117
- continue
118
- if in_code_block:
119
- continue
120
- if not stripped:
121
- continue
122
-
123
- if stripped.lower().startswith("screen image:"):
124
- expecting_image_line = stripped.lower() == "screen image:"
125
- hrefs = IMAGE_LINK_RE.findall(stripped)
126
- elif expecting_image_line and stripped.startswith("!["):
127
- expecting_image_line = False
128
- hrefs = IMAGE_LINK_RE.findall(stripped)
129
- else:
130
- hrefs = []
131
- if not stripped.startswith("<!--"):
132
- expecting_image_line = False
133
-
134
- for href in hrefs:
135
- if _is_root_relative_docs_href(href):
136
- issues.append((idx, href))
137
-
138
- return issues
139
-
140
-
141
- def collect_plantuml_activity_syntax_issues(md_text: str) -> list[tuple[int, str]]:
142
- issues: list[tuple[int, str]] = []
143
- lines = md_text.splitlines()
144
- in_plantuml_block = False
145
- block_start_line = 0
146
- block_lines: list[str] = []
147
-
148
- def flush_block() -> None:
149
- nonlocal issues, block_lines, block_start_line
150
- if not block_lines:
151
- return
152
- has_new_style = any(NEW_STYLE_ACTIVITY_LINE_RE.search(line) for line in block_lines)
153
- if not has_new_style:
154
- block_lines = []
155
- block_start_line = 0
156
- return
157
-
158
- for offset, line in enumerate(block_lines, start=0):
159
- line_no = block_start_line + offset
160
- if LEGACY_ACTIVITY_START_RE.search(line):
161
- issues.append(
162
- (line_no, "Legacy activity start marker `(*)` is not allowed in new-style activity diagrams.")
163
- )
164
- if MIXED_ACTIVITY_ARROW_RE.search(line):
165
- issues.append(
166
- (line_no, "Do not append legacy `-->` transitions after a new-style `:Activity;` action line.")
167
- )
168
- elif LEGACY_EDGE_LABEL_RE.search(line):
169
- issues.append(
170
- (line_no, "Legacy edge labels like `--> [label]` are not allowed in new-style activity diagrams.")
171
- )
172
-
173
- block_lines = []
174
- block_start_line = 0
175
-
176
- for idx, line in enumerate(lines, start=1):
177
- if not in_plantuml_block and PLANTUML_FENCE_START_RE.match(line):
178
- in_plantuml_block = True
179
- block_start_line = idx + 1
180
- block_lines = []
181
- continue
182
-
183
- if in_plantuml_block and line.strip().startswith("```"):
184
- flush_block()
185
- in_plantuml_block = False
186
- continue
187
-
188
- if in_plantuml_block:
189
- block_lines.append(line)
190
-
191
- if in_plantuml_block:
192
- flush_block()
193
-
194
- return issues
195
-
196
-
197
- def collect_wireframe_mapping_issues(md_text: str) -> list[tuple[int, str]]:
198
- issues: list[tuple[int, str]] = []
199
- sections = list(SCREEN_SECTION_HEADING_RE.finditer(md_text))
200
- for idx, match in enumerate(sections):
201
- start = match.start()
202
- end = sections[idx + 1].start() if idx + 1 < len(sections) else len(md_text)
203
- section_text = md_text[start:end]
204
-
205
- if "Design Source Type: generated-draft" not in section_text:
206
- continue
207
- if "> Screen image not rendered in this environment." in section_text:
208
- continue
209
- if "Screen image:" not in section_text or "![" not in section_text:
210
- continue
211
- if "#### Wireframe Marker Mapping" in section_text:
212
- continue
213
-
214
- line_no = md_text.count("\n", 0, start) + 1
215
- section_name = match.group(1).strip()
216
- issues.append(
217
- (line_no, f"{section_name}: missing `Wireframe Marker Mapping` table for generated-draft screen.")
218
- )
219
-
220
- return issues
221
-
222
-
223
- def parse_action_tables(md_text: str) -> list[Occurrence]:
224
- occurrences: list[Occurrence] = []
225
- current_section = ""
226
- lines = md_text.splitlines()
227
-
228
- i = 0
229
- while i < len(lines):
230
- line = lines[i]
231
-
232
- m = HEADING_RE.match(line)
233
- if m:
234
- current_section = m.group(2).strip()
235
-
236
- # Detect table header
237
- if i + 1 < len(lines) and TABLE_ROW_RE.match(line) and TABLE_ROW_RE.match(lines[i + 1]):
238
- header = _split_table_row(line)
239
- sep = lines[i + 1]
240
-
241
- if not TABLE_SEP_RE.match(sep):
242
- i += 1
243
- continue
244
-
245
- # Only validate action tables: must contain No + Action + Description
246
- lowered = [h.lower() for h in header]
247
- if "no" not in lowered and "no." not in lowered:
248
- i += 1
249
- continue
250
- if "action" not in lowered or "description" not in lowered:
251
- i += 1
252
- continue
253
-
254
- try:
255
- no_index = lowered.index("no")
256
- except ValueError:
257
- no_index = lowered.index("no.")
258
-
259
- # Consume rows until table ends
260
- j = i + 2
261
- while j < len(lines) and TABLE_ROW_RE.match(lines[j]):
262
- row = _split_table_row(lines[j])
263
- if len(row) <= no_index:
264
- j += 1
265
- continue
266
- raw_no = row[no_index]
267
- try:
268
- number = int(raw_no)
269
- except ValueError:
270
- j += 1
271
- continue
272
- occurrences.append(
273
- Occurrence(
274
- number=number,
275
- section=current_section or "(unknown section)",
276
- line_no=j + 1, # 1-based
277
- raw_line=lines[j],
278
- )
279
- )
280
- j += 1
281
-
282
- i = j
283
- continue
284
-
285
- i += 1
286
-
287
- return occurrences
288
-
289
-
290
- def main() -> int:
291
- parser = argparse.ArgumentParser(description="Validate numbering in flow-action spec tables.")
292
- parser.add_argument("--spec", required=True, help="Path to *_FLOW_ACTION_SPEC.md")
293
- parser.add_argument(
294
- "--en-check",
295
- action="store_true",
296
- help="Enable EN artifact hygiene checks (Vietnamese leftovers + encoding corruption).",
297
- )
298
- args = parser.parse_args()
299
-
300
- try:
301
- sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
302
- sys.stderr.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
303
- except Exception:
304
- pass
305
-
306
- spec_path = Path(args.spec)
307
- if not spec_path.exists():
308
- print(f"[ERROR] Not found: {spec_path}", file=sys.stderr)
309
- return 2
310
-
311
- text = _read_text(spec_path)
312
- occ = parse_action_tables(text)
313
-
314
- by_number: dict[int, list[Occurrence]] = {}
315
- for o in occ:
316
- by_number.setdefault(o.number, []).append(o)
317
-
318
- duplicates = {n: os for n, os in by_number.items() if len(os) > 1}
319
-
320
- max_seen = -1
321
- decreases: list[tuple[Occurrence, int]] = []
322
- for o in occ:
323
- if o.number < max_seen:
324
- decreases.append((o, max_seen))
325
- max_seen = max(max_seen, o.number)
326
-
327
- has_issues = bool(duplicates or decreases)
328
- hygiene = collect_hygiene_issues(text, en_check=args.en_check)
329
- image_path_issues = collect_screen_image_path_issues(text)
330
- plantuml_activity_issues = collect_plantuml_activity_syntax_issues(text)
331
- wireframe_mapping_issues = collect_wireframe_mapping_issues(text)
332
- if hygiene["encoding"] or hygiene["inline_heading"]:
333
- has_issues = True
334
- if args.en_check and (hygiene["vi_diacritic"] or hygiene["vi_phrase"]):
335
- has_issues = True
336
- if image_path_issues:
337
- has_issues = True
338
- if plantuml_activity_issues:
339
- has_issues = True
340
- if wireframe_mapping_issues:
341
- has_issues = True
342
-
343
- print(f"Checked: {spec_path}")
344
- print(f"- Total numbered rows: {len(occ)}")
345
- print(f"- Unique numbers: {len(by_number)}")
346
- print(f"- EN hygiene check enabled: {args.en_check}")
347
-
348
- if not occ:
349
- print("[WARN] No action tables detected (| No | Action | Description | ... |).")
350
-
351
- if duplicates:
352
- print("\n[FAIL] Duplicate numbers found:")
353
- for n in sorted(duplicates.keys()):
354
- print(f"- No {n}:")
355
- for o in duplicates[n]:
356
- print(f" - {o.section} (line {o.line_no})")
357
-
358
- if decreases:
359
- print("\n[FAIL] Numbering decreases/resets detected (global numbering policy):")
360
- for o, prev_max in decreases:
361
- print(f"- No {o.number} after max {prev_max}: {o.section} (line {o.line_no})")
362
-
363
- if hygiene["encoding"]:
364
- print("\n[FAIL] Encoding/mojibake markers detected:")
365
- for line_no, line in hygiene["encoding"][:20]:
366
- print(f"- line {line_no}: {line.strip()}")
367
-
368
- if hygiene["inline_heading"]:
369
- print("\n[FAIL] Inline/merged heading patterns detected:")
370
- for line_no, line in hygiene["inline_heading"][:20]:
371
- print(f"- line {line_no}: {line.strip()}")
372
-
373
- if args.en_check and hygiene["vi_diacritic"]:
374
- print("\n[FAIL] Vietnamese diacritic text detected in EN artifact:")
375
- for line_no, line in hygiene["vi_diacritic"][:20]:
376
- print(f"- line {line_no}: {line.strip()}")
377
-
378
- if args.en_check and hygiene["vi_phrase"]:
379
- print("\n[FAIL] Vietnamese phrase patterns detected in EN artifact:")
380
- for line_no, line in hygiene["vi_phrase"][:20]:
381
- print(f"- line {line_no}: {line.strip()}")
382
-
383
- if image_path_issues:
384
- print("\n[FAIL] Screen image markdown paths must be file-relative, not docs-root-relative:")
385
- for line_no, href in image_path_issues[:20]:
386
- print(f"- line {line_no}: {href}")
387
-
388
- if plantuml_activity_issues:
389
- print("\n[FAIL] Mixed or legacy PlantUML activity syntax detected in a new-style screen-flow block:")
390
- for line_no, message in plantuml_activity_issues[:20]:
391
- print(f"- line {line_no}: {message}")
392
-
393
- if wireframe_mapping_issues:
394
- print("\n[FAIL] Missing wireframe-marker mapping tables for generated-draft screens:")
395
- for line_no, message in wireframe_mapping_issues[:20]:
396
- print(f"- line {line_no}: {message}")
397
-
398
- if not has_issues:
399
- print("\n[OK] Numbering and text hygiene checks passed.")
400
- return 0
401
-
402
- print("\nHint: Use global numbering across the full document.")
403
- print("- Do not repeat No values in any action table.")
404
- print("- Do not reset numbering per screen/dialog.")
405
- print("- Use file-relative screen image paths such as assets/<feature>/screens/<screen>.svg.")
406
- print("- Use new-style PlantUML activity syntax only for screen-flow diagrams.")
407
- print("- Add a `Wireframe Marker Mapping` table when a generated-draft screen embeds a wireframe image.")
408
- print("- Keep EN artifacts free of Vietnamese leftovers and encoding corruption.")
409
- print("- Keep headings/sections on separate lines (avoid merged markdown blocks).")
410
- return 1
411
-
412
-
413
- if __name__ == "__main__":
414
- raise SystemExit(main())
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import re
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+
10
+ TABLE_ROW_RE = re.compile(r"^\|.*\|\s*$")
11
+ TABLE_SEP_RE = re.compile(r"^\|\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|\s*$")
12
+ HEADING_RE = re.compile(r"^(#{1,6})\s+(.*\S)\s*$")
13
+ SCREEN_SECTION_HEADING_RE = re.compile(r"^###\s+(.*\S)\s*$", re.MULTILINE)
14
+ VI_DIACRITIC_RE = re.compile(r"[À-ỹ]")
15
+ VI_PHRASE_RE = re.compile(
16
+ r"\b("
17
+ r"thuc thi|hien thi|cap nhat|bo sung|can xac nhan|trong anh|"
18
+ r"duoc tra kem|tao lich|theo user|muc global|thay the cho|bao gom"
19
+ r")\b",
20
+ re.IGNORECASE,
21
+ )
22
+ INLINE_HEADING_RE = re.compile(r".+\s#{2,}\s+\S")
23
+ IMAGE_LINK_RE = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
24
+ PLANTUML_FENCE_START_RE = re.compile(r"^\s*```plantuml\s*$", re.IGNORECASE)
25
+ NEW_STYLE_ACTIVITY_LINE_RE = re.compile(
26
+ r"^\s*(start|stop|partition\s+\"|if\s*\(|fork(?:\s+again)?\b|end\s+fork\b|note\s+(?:right|left|top|bottom)\b|:[^;\n]+;)",
27
+ re.IGNORECASE,
28
+ )
29
+ LEGACY_ACTIVITY_START_RE = re.compile(r"\(\*\)")
30
+ LEGACY_EDGE_LABEL_RE = re.compile(r"-->\s*\[")
31
+ MIXED_ACTIVITY_ARROW_RE = re.compile(r":[^;\n]+;\s*-->")
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Occurrence:
36
+ number: int
37
+ section: str
38
+ line_no: int
39
+ raw_line: str
40
+
41
+
42
+ def _split_table_row(line: str) -> list[str]:
43
+ # Keep it simple: markdown tables in our spec are plain and don't escape pipes.
44
+ parts = [p.strip() for p in line.strip().strip("|").split("|")]
45
+ return parts
46
+
47
+
48
+ def _read_text(path: Path) -> str:
49
+ # Prefer UTF-8; fallback to cp1252-ish if user saved without UTF-8.
50
+ for enc in ("utf-8", "utf-8-sig", "cp1252"):
51
+ try:
52
+ return path.read_text(encoding=enc)
53
+ except UnicodeDecodeError:
54
+ continue
55
+ return path.read_text(errors="replace")
56
+
57
+
58
+ def collect_hygiene_issues(md_text: str, *, en_check: bool) -> dict[str, list[tuple[int, str]]]:
59
+ issues: dict[str, list[tuple[int, str]]] = {
60
+ "encoding": [],
61
+ "vi_diacritic": [],
62
+ "vi_phrase": [],
63
+ "inline_heading": [],
64
+ }
65
+ lines = md_text.splitlines()
66
+ in_code_block = False
67
+
68
+ for idx, line in enumerate(lines, start=1):
69
+ stripped = line.strip()
70
+ if stripped.startswith("```"):
71
+ in_code_block = not in_code_block
72
+ continue
73
+ if in_code_block:
74
+ continue
75
+
76
+ if "�" in line or "ↁE" in line:
77
+ issues["encoding"].append((idx, line))
78
+
79
+ # A common corruption symptom: merged headings inside normal text lines.
80
+ if INLINE_HEADING_RE.search(line) and not stripped.startswith("#"):
81
+ issues["inline_heading"].append((idx, line))
82
+
83
+ if en_check:
84
+ lowered = stripped.lower()
85
+ if "original text" in lowered:
86
+ continue
87
+ if VI_DIACRITIC_RE.search(line):
88
+ issues["vi_diacritic"].append((idx, line))
89
+ elif VI_PHRASE_RE.search(line):
90
+ issues["vi_phrase"].append((idx, line))
91
+
92
+ return issues
93
+
94
+
95
+ def _is_root_relative_docs_href(href: str) -> bool:
96
+ normalized = href.strip().replace("\\", "/").lower()
97
+ if not normalized:
98
+ return False
99
+ if re.match(r"^[a-z][a-z0-9+.-]*://", normalized):
100
+ return False
101
+ if normalized.startswith(("mailto:", "tel:", "data:", "#")):
102
+ return False
103
+ return normalized.startswith(("docs/", "./docs/", "/docs/"))
104
+
105
+
106
+ def collect_screen_image_path_issues(md_text: str) -> list[tuple[int, str]]:
107
+ issues: list[tuple[int, str]] = []
108
+ lines = md_text.splitlines()
109
+ in_code_block = False
110
+ expecting_image_line = False
111
+
112
+ for idx, line in enumerate(lines, start=1):
113
+ stripped = line.strip()
114
+ if stripped.startswith("```"):
115
+ in_code_block = not in_code_block
116
+ expecting_image_line = False
117
+ continue
118
+ if in_code_block:
119
+ continue
120
+ if not stripped:
121
+ continue
122
+
123
+ if stripped.lower().startswith("screen image:"):
124
+ expecting_image_line = stripped.lower() == "screen image:"
125
+ hrefs = IMAGE_LINK_RE.findall(stripped)
126
+ elif expecting_image_line and stripped.startswith("!["):
127
+ expecting_image_line = False
128
+ hrefs = IMAGE_LINK_RE.findall(stripped)
129
+ else:
130
+ hrefs = []
131
+ if not stripped.startswith("<!--"):
132
+ expecting_image_line = False
133
+
134
+ for href in hrefs:
135
+ if _is_root_relative_docs_href(href):
136
+ issues.append((idx, href))
137
+
138
+ return issues
139
+
140
+
141
+ def collect_plantuml_activity_syntax_issues(md_text: str) -> list[tuple[int, str]]:
142
+ issues: list[tuple[int, str]] = []
143
+ lines = md_text.splitlines()
144
+ in_plantuml_block = False
145
+ block_start_line = 0
146
+ block_lines: list[str] = []
147
+
148
+ def flush_block() -> None:
149
+ nonlocal issues, block_lines, block_start_line
150
+ if not block_lines:
151
+ return
152
+ has_new_style = any(NEW_STYLE_ACTIVITY_LINE_RE.search(line) for line in block_lines)
153
+ if not has_new_style:
154
+ block_lines = []
155
+ block_start_line = 0
156
+ return
157
+
158
+ for offset, line in enumerate(block_lines, start=0):
159
+ line_no = block_start_line + offset
160
+ if LEGACY_ACTIVITY_START_RE.search(line):
161
+ issues.append(
162
+ (line_no, "Legacy activity start marker `(*)` is not allowed in new-style activity diagrams.")
163
+ )
164
+ if MIXED_ACTIVITY_ARROW_RE.search(line):
165
+ issues.append(
166
+ (line_no, "Do not append legacy `-->` transitions after a new-style `:Activity;` action line.")
167
+ )
168
+ elif LEGACY_EDGE_LABEL_RE.search(line):
169
+ issues.append(
170
+ (line_no, "Legacy edge labels like `--> [label]` are not allowed in new-style activity diagrams.")
171
+ )
172
+
173
+ block_lines = []
174
+ block_start_line = 0
175
+
176
+ for idx, line in enumerate(lines, start=1):
177
+ if not in_plantuml_block and PLANTUML_FENCE_START_RE.match(line):
178
+ in_plantuml_block = True
179
+ block_start_line = idx + 1
180
+ block_lines = []
181
+ continue
182
+
183
+ if in_plantuml_block and line.strip().startswith("```"):
184
+ flush_block()
185
+ in_plantuml_block = False
186
+ continue
187
+
188
+ if in_plantuml_block:
189
+ block_lines.append(line)
190
+
191
+ if in_plantuml_block:
192
+ flush_block()
193
+
194
+ return issues
195
+
196
+
197
+ def collect_wireframe_mapping_issues(md_text: str) -> list[tuple[int, str]]:
198
+ issues: list[tuple[int, str]] = []
199
+ sections = list(SCREEN_SECTION_HEADING_RE.finditer(md_text))
200
+ for idx, match in enumerate(sections):
201
+ start = match.start()
202
+ end = sections[idx + 1].start() if idx + 1 < len(sections) else len(md_text)
203
+ section_text = md_text[start:end]
204
+
205
+ if "Design Source Type: generated-draft" not in section_text:
206
+ continue
207
+ if "> Screen image not rendered in this environment." in section_text:
208
+ continue
209
+ if "Screen image:" not in section_text or "![" not in section_text:
210
+ continue
211
+ if "#### Wireframe Marker Mapping" in section_text:
212
+ continue
213
+
214
+ line_no = md_text.count("\n", 0, start) + 1
215
+ section_name = match.group(1).strip()
216
+ issues.append(
217
+ (line_no, f"{section_name}: missing `Wireframe Marker Mapping` table for generated-draft screen.")
218
+ )
219
+
220
+ return issues
221
+
222
+
223
+ def parse_action_tables(md_text: str) -> list[Occurrence]:
224
+ occurrences: list[Occurrence] = []
225
+ current_section = ""
226
+ lines = md_text.splitlines()
227
+
228
+ i = 0
229
+ while i < len(lines):
230
+ line = lines[i]
231
+
232
+ m = HEADING_RE.match(line)
233
+ if m:
234
+ current_section = m.group(2).strip()
235
+
236
+ # Detect table header
237
+ if i + 1 < len(lines) and TABLE_ROW_RE.match(line) and TABLE_ROW_RE.match(lines[i + 1]):
238
+ header = _split_table_row(line)
239
+ sep = lines[i + 1]
240
+
241
+ if not TABLE_SEP_RE.match(sep):
242
+ i += 1
243
+ continue
244
+
245
+ # Only validate action tables: must contain No + Action + Description
246
+ lowered = [h.lower() for h in header]
247
+ if "no" not in lowered and "no." not in lowered:
248
+ i += 1
249
+ continue
250
+ if "action" not in lowered or "description" not in lowered:
251
+ i += 1
252
+ continue
253
+
254
+ try:
255
+ no_index = lowered.index("no")
256
+ except ValueError:
257
+ no_index = lowered.index("no.")
258
+
259
+ # Consume rows until table ends
260
+ j = i + 2
261
+ while j < len(lines) and TABLE_ROW_RE.match(lines[j]):
262
+ row = _split_table_row(lines[j])
263
+ if len(row) <= no_index:
264
+ j += 1
265
+ continue
266
+ raw_no = row[no_index]
267
+ try:
268
+ number = int(raw_no)
269
+ except ValueError:
270
+ j += 1
271
+ continue
272
+ occurrences.append(
273
+ Occurrence(
274
+ number=number,
275
+ section=current_section or "(unknown section)",
276
+ line_no=j + 1, # 1-based
277
+ raw_line=lines[j],
278
+ )
279
+ )
280
+ j += 1
281
+
282
+ i = j
283
+ continue
284
+
285
+ i += 1
286
+
287
+ return occurrences
288
+
289
+
290
+ def main() -> int:
291
+ parser = argparse.ArgumentParser(description="Validate numbering in flow-action spec tables.")
292
+ parser.add_argument("--spec", required=True, help="Path to *_FLOW_ACTION_SPEC.md")
293
+ parser.add_argument(
294
+ "--en-check",
295
+ action="store_true",
296
+ help="Enable EN artifact hygiene checks (Vietnamese leftovers + encoding corruption).",
297
+ )
298
+ args = parser.parse_args()
299
+
300
+ try:
301
+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
302
+ sys.stderr.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
303
+ except Exception:
304
+ pass
305
+
306
+ spec_path = Path(args.spec)
307
+ if not spec_path.exists():
308
+ print(f"[ERROR] Not found: {spec_path}", file=sys.stderr)
309
+ return 2
310
+
311
+ text = _read_text(spec_path)
312
+ occ = parse_action_tables(text)
313
+
314
+ by_number: dict[int, list[Occurrence]] = {}
315
+ for o in occ:
316
+ by_number.setdefault(o.number, []).append(o)
317
+
318
+ duplicates = {n: os for n, os in by_number.items() if len(os) > 1}
319
+
320
+ max_seen = -1
321
+ decreases: list[tuple[Occurrence, int]] = []
322
+ for o in occ:
323
+ if o.number < max_seen:
324
+ decreases.append((o, max_seen))
325
+ max_seen = max(max_seen, o.number)
326
+
327
+ has_issues = bool(duplicates or decreases)
328
+ hygiene = collect_hygiene_issues(text, en_check=args.en_check)
329
+ image_path_issues = collect_screen_image_path_issues(text)
330
+ plantuml_activity_issues = collect_plantuml_activity_syntax_issues(text)
331
+ wireframe_mapping_issues = collect_wireframe_mapping_issues(text)
332
+ if hygiene["encoding"] or hygiene["inline_heading"]:
333
+ has_issues = True
334
+ if args.en_check and (hygiene["vi_diacritic"] or hygiene["vi_phrase"]):
335
+ has_issues = True
336
+ if image_path_issues:
337
+ has_issues = True
338
+ if plantuml_activity_issues:
339
+ has_issues = True
340
+ if wireframe_mapping_issues:
341
+ has_issues = True
342
+
343
+ print(f"Checked: {spec_path}")
344
+ print(f"- Total numbered rows: {len(occ)}")
345
+ print(f"- Unique numbers: {len(by_number)}")
346
+ print(f"- EN hygiene check enabled: {args.en_check}")
347
+
348
+ if not occ:
349
+ print("[WARN] No action tables detected (| No | Action | Description | ... |).")
350
+
351
+ if duplicates:
352
+ print("\n[FAIL] Duplicate numbers found:")
353
+ for n in sorted(duplicates.keys()):
354
+ print(f"- No {n}:")
355
+ for o in duplicates[n]:
356
+ print(f" - {o.section} (line {o.line_no})")
357
+
358
+ if decreases:
359
+ print("\n[FAIL] Numbering decreases/resets detected (global numbering policy):")
360
+ for o, prev_max in decreases:
361
+ print(f"- No {o.number} after max {prev_max}: {o.section} (line {o.line_no})")
362
+
363
+ if hygiene["encoding"]:
364
+ print("\n[FAIL] Encoding/mojibake markers detected:")
365
+ for line_no, line in hygiene["encoding"][:20]:
366
+ print(f"- line {line_no}: {line.strip()}")
367
+
368
+ if hygiene["inline_heading"]:
369
+ print("\n[FAIL] Inline/merged heading patterns detected:")
370
+ for line_no, line in hygiene["inline_heading"][:20]:
371
+ print(f"- line {line_no}: {line.strip()}")
372
+
373
+ if args.en_check and hygiene["vi_diacritic"]:
374
+ print("\n[FAIL] Vietnamese diacritic text detected in EN artifact:")
375
+ for line_no, line in hygiene["vi_diacritic"][:20]:
376
+ print(f"- line {line_no}: {line.strip()}")
377
+
378
+ if args.en_check and hygiene["vi_phrase"]:
379
+ print("\n[FAIL] Vietnamese phrase patterns detected in EN artifact:")
380
+ for line_no, line in hygiene["vi_phrase"][:20]:
381
+ print(f"- line {line_no}: {line.strip()}")
382
+
383
+ if image_path_issues:
384
+ print("\n[FAIL] Screen image markdown paths must be file-relative, not docs-root-relative:")
385
+ for line_no, href in image_path_issues[:20]:
386
+ print(f"- line {line_no}: {href}")
387
+
388
+ if plantuml_activity_issues:
389
+ print("\n[FAIL] Mixed or legacy PlantUML activity syntax detected in a new-style screen-flow block:")
390
+ for line_no, message in plantuml_activity_issues[:20]:
391
+ print(f"- line {line_no}: {message}")
392
+
393
+ if wireframe_mapping_issues:
394
+ print("\n[FAIL] Missing wireframe-marker mapping tables for generated-draft screens:")
395
+ for line_no, message in wireframe_mapping_issues[:20]:
396
+ print(f"- line {line_no}: {message}")
397
+
398
+ if not has_issues:
399
+ print("\n[OK] Numbering and text hygiene checks passed.")
400
+ return 0
401
+
402
+ print("\nHint: Use global numbering across the full document.")
403
+ print("- Do not repeat No values in any action table.")
404
+ print("- Do not reset numbering per screen/dialog.")
405
+ print("- Use file-relative screen image paths such as assets/<feature>/screens/<screen>.svg.")
406
+ print("- Use new-style PlantUML activity syntax only for screen-flow diagrams.")
407
+ print("- Add a `Wireframe Marker Mapping` table when a generated-draft screen embeds a wireframe image.")
408
+ print("- Keep EN artifacts free of Vietnamese leftovers and encoding corruption.")
409
+ print("- Keep headings/sections on separate lines (avoid merged markdown blocks).")
410
+ return 1
411
+
412
+
413
+ if __name__ == "__main__":
414
+ raise SystemExit(main())