@topmindspace/tms-skills 2.0.0 → 2.0.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.
Files changed (99) hide show
  1. package/CHANGELOG.md +139 -123
  2. package/README.md +126 -103
  3. package/bin/tms-skills.js +160 -160
  4. package/package.json +48 -48
  5. package/top-ppt-html/README.md +254 -253
  6. package/top-ppt-html/SKILL.md +111 -111
  7. package/top-ppt-html/assets/examples/2026-09-09-architecture-graphite-dark.html +3873 -3926
  8. package/top-ppt-html/assets/examples/2026-09-09-architecture-graphite-dark.model.json +167 -167
  9. package/top-ppt-html/assets/examples/2026-09-09-architecture-spectrum.html +3873 -3926
  10. package/top-ppt-html/assets/examples/2026-09-09-architecture-spectrum.model.json +167 -167
  11. package/top-ppt-html/assets/examples/2026-09-09-presentation-apple-mono.html +4272 -4325
  12. package/top-ppt-html/assets/examples/2026-09-09-presentation-apple-mono.model.json +320 -320
  13. package/top-ppt-html/assets/examples/2026-09-09-presentation-brand-red.html +4272 -4325
  14. package/top-ppt-html/assets/examples/2026-09-09-presentation-brand-red.model.json +320 -320
  15. package/top-ppt-html/assets/examples/2026-09-09-presentation-business-blue.html +4272 -4325
  16. package/top-ppt-html/assets/examples/2026-09-09-presentation-business-blue.model.json +320 -320
  17. package/top-ppt-html/assets/examples/2026-09-09-research-deep-teal.html +5474 -5527
  18. package/top-ppt-html/assets/examples/2026-09-09-research-deep-teal.model.json +913 -913
  19. package/top-ppt-html/assets/examples/2026-09-09-research-indigo-violet.html +5474 -5527
  20. package/top-ppt-html/assets/examples/2026-09-09-research-indigo-violet.model.json +913 -913
  21. package/top-ppt-html/assets/examples/2026-09-09-research-mckinsey.html +5474 -5527
  22. package/top-ppt-html/assets/examples/2026-09-09-research-mckinsey.model.json +913 -913
  23. package/top-ppt-html/assets/examples/2026-09-09-research-warm-sand.html +5474 -5527
  24. package/top-ppt-html/assets/examples/2026-09-09-research-warm-sand.model.json +913 -913
  25. package/top-ppt-html/assets/pptx-export.js +1944 -1944
  26. package/top-ppt-html/assets/style-gallery.html +559 -589
  27. package/top-ppt-html/assets/templates/architecture.html +3675 -3728
  28. package/top-ppt-html/assets/templates/engine.css +787 -840
  29. package/top-ppt-html/assets/templates/presentation.html +3685 -3738
  30. package/top-ppt-html/assets/templates/research.html +3964 -4017
  31. package/top-ppt-html/assets/templates/ui.js +520 -520
  32. package/top-ppt-html/assets/theme-overview-architecture.png +0 -0
  33. package/top-ppt-html/assets/theme-overview-presentation.png +0 -0
  34. package/top-ppt-html/assets/theme-overview-research.png +0 -0
  35. package/top-ppt-html/assets/theme-overview.png +0 -0
  36. package/top-ppt-html/evals/prompts.csv +15 -15
  37. package/top-ppt-html/evals/rubric.schema.json +25 -25
  38. package/top-ppt-html/evals/run_evals.py +220 -220
  39. package/top-ppt-html/evals/trace.example.json +16 -16
  40. package/top-ppt-html/package-lock.json +175 -0
  41. package/top-ppt-html/package.json +30 -35
  42. package/top-ppt-html/references/charts-basic.md +624 -624
  43. package/top-ppt-html/references/charts-discipline.md +108 -108
  44. package/top-ppt-html/references/charts-extended.md +482 -482
  45. package/top-ppt-html/references/charts.md +28 -28
  46. package/top-ppt-html/references/components-atoms.md +624 -624
  47. package/top-ppt-html/references/components.md +30 -30
  48. package/top-ppt-html/references/content-rules.md +490 -490
  49. package/top-ppt-html/references/design-system-engine.md +235 -235
  50. package/top-ppt-html/references/design-system.md +471 -478
  51. package/top-ppt-html/references/failure-modes.md +214 -214
  52. package/top-ppt-html/references/high-fidelity.md +127 -127
  53. package/top-ppt-html/references/icons.md +397 -397
  54. package/top-ppt-html/references/industry-benchmark.md +105 -105
  55. package/top-ppt-html/references/infographics-stats.md +308 -308
  56. package/top-ppt-html/references/infographics-structure.md +226 -226
  57. package/top-ppt-html/references/infographics.md +43 -43
  58. package/top-ppt-html/references/layout-grammar.md +315 -315
  59. package/top-ppt-html/references/layouts-architecture.md +108 -108
  60. package/top-ppt-html/references/layouts-combo.md +600 -600
  61. package/top-ppt-html/references/layouts-research.md +160 -160
  62. package/top-ppt-html/references/modes.md +254 -254
  63. package/top-ppt-html/references/outline-design.md +275 -275
  64. package/top-ppt-html/references/playbook.md +266 -266
  65. package/top-ppt-html/references/pptx-export.md +209 -209
  66. package/top-ppt-html/references/reform-plan.md +252 -252
  67. package/top-ppt-html/references/styles.md +336 -370
  68. package/top-ppt-html/references/tech-design.md +138 -138
  69. package/top-ppt-html/scripts/audit_css.py +109 -109
  70. package/top-ppt-html/scripts/audit_docs.py +176 -176
  71. package/top-ppt-html/scripts/audit_skill.py +220 -220
  72. package/top-ppt-html/scripts/audit_styles.py +293 -351
  73. package/top-ppt-html/scripts/build_examples.py +2276 -2276
  74. package/top-ppt-html/scripts/build_pptx.js +2380 -2380
  75. package/top-ppt-html/scripts/capture_theme_overview.js +78 -78
  76. package/top-ppt-html/scripts/checks_html.py +127 -127
  77. package/top-ppt-html/scripts/cross_verify.py +294 -294
  78. package/top-ppt-html/scripts/env_probe.py +158 -158
  79. package/top-ppt-html/scripts/extract_model.py +210 -210
  80. package/top-ppt-html/scripts/extract_snippet.py +374 -374
  81. package/top-ppt-html/scripts/gen_channel_a.js +214 -214
  82. package/top-ppt-html/scripts/layout-constants.json +3309 -3377
  83. package/top-ppt-html/scripts/layout_slots.json +830 -830
  84. package/top-ppt-html/scripts/lib_layout_regions.js +412 -412
  85. package/top-ppt-html/scripts/measure_height.py +178 -178
  86. package/top-ppt-html/scripts/model-schema.json +547 -547
  87. package/top-ppt-html/scripts/negative_tests.py +307 -307
  88. package/top-ppt-html/scripts/package_skill.py +291 -291
  89. package/top-ppt-html/scripts/prepare_images.py +341 -341
  90. package/top-ppt-html/scripts/probe_image_export.py +188 -188
  91. package/top-ppt-html/scripts/quality_gate.py +301 -301
  92. package/top-ppt-html/scripts/regression.py +307 -308
  93. package/top-ppt-html/scripts/render_compare.py +275 -275
  94. package/top-ppt-html/scripts/render_from_model.py +698 -698
  95. package/top-ppt-html/scripts/scaffold_report.py +1054 -1054
  96. package/top-ppt-html/scripts/section-file-map.json +104 -104
  97. package/top-ppt-html/scripts/sync_runtime.py +662 -662
  98. package/top-ppt-html/scripts/validate_pptx.py +1510 -1510
  99. package/top-ppt-html/scripts/validate_report.py +1456 -1456
@@ -1,374 +1,374 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """TopPPT HTML · L2 节级片段抽取器(减少整读 components.md / charts.md 的上下文成本)
4
-
5
- 用法:
6
- python scripts/extract_snippet.py --list
7
- python scripts/extract_snippet.py --chart waterfall
8
- python scripts/extract_snippet.py --page-type exhibit
9
- python scripts/extract_snippet.py --file components.md --section 46
10
- python scripts/extract_snippet.py --task research-evidence
11
- python scripts/extract_snippet.py --task pptx-export
12
-
13
- 设计:
14
- 智能体按「任务 → 只读相关节」取代码,而不是整文件读入 70KB+ 规范。
15
- 节边界用标题行识别;--task 走内置路由表(与 playbook.md §十 同源)。
16
- """
17
- from __future__ import annotations
18
-
19
- import argparse
20
- import json
21
- import re
22
- import sys
23
- from pathlib import Path
24
-
25
- try:
26
- sys.stdout.reconfigure(encoding='utf-8', errors='replace')
27
- except Exception:
28
- pass
29
-
30
- ROOT = Path(__file__).resolve().parent.parent
31
- REF = ROOT / 'references'
32
- LC = json.loads((ROOT / 'scripts' / 'layout-constants.json').read_text(encoding='utf-8'))
33
- # §编号 → 物理文件(components/charts 拆分后逻辑路由;单源 scripts/section-file-map.json)
34
- _SECTION_MAP_PATH = ROOT / 'scripts' / 'section-file-map.json'
35
- try:
36
- SECTION_FILE_MAP = json.loads(_SECTION_MAP_PATH.read_text(encoding='utf-8'))
37
- except (OSError, json.JSONDecodeError):
38
- SECTION_FILE_MAP = {}
39
-
40
- # 任务 → 建议只读的文件与节(与 references/playbook.md §十 保持一致)
41
- # 节号三种形态均可寻址:阿拉伯(46 / 46b / 8-1)、中文(三 / 一-b)、标题关键词(精导 / 速查)
42
- TASK_ROUTES = {
43
- 'research-evidence': {
44
- 'desc': 'research 证据页 / Exhibit / 密表',
45
- 'reads': [
46
- ('components.md', ['36d', '46', '46c']),
47
- ('playbook.md', ['三', '四']),
48
- ],
49
- },
50
- 'presentation-combo': {
51
- 'desc': '演示组合版式与卡片',
52
- 'reads': [
53
- ('components.md', ['39', '40', '41', '42', '46', '46b', '46c']),
54
- ('playbook.md', ['三', '四']),
55
- ],
56
- },
57
- 'architecture-diagram': {
58
- 'desc': '架构/泳道/分层',
59
- 'reads': [
60
- ('components.md', ['37', '38', '38b']),
61
- ('infographics.md', ['78', '79', '80']),
62
- ('playbook.md', ['三', '七']),
63
- ],
64
- },
65
- 'chart-pick': {
66
- 'desc': '选图与取图表代码',
67
- 'reads': [
68
- ('playbook.md', ['五']),
69
- ('charts.md', ['16']),
70
- ],
71
- },
72
- 'content-rules': {
73
- 'desc': '密度/字数/去AI味/细节保全',
74
- 'reads': [
75
- ('content-rules.md', ['四', '一']),
76
- ('playbook.md', ['六']),
77
- ],
78
- },
79
- 'layout-grammar': {
80
- 'desc': '布局骨架 P1–P12 / 元素排版 / 组合与留白',
81
- 'reads': [
82
- ('layout-grammar.md', ['〇', '二', '三', '四']),
83
- ('playbook.md', ['〇']),
84
- ],
85
- },
86
- 'model-render': {
87
- 'desc': '模型驱动生成 / 单写路径',
88
- 'reads': [
89
- ('pptx-export.md', ['内容模型']),
90
- ('content-rules.md', ['二-b']),
91
- ],
92
- },
93
- 'pptx-export': {
94
- 'desc': 'PPTX 精导与页型字段',
95
- 'reads': [
96
- ('pptx-export.md', ['精导', '内容模型']),
97
- ('playbook.md', ['九']),
98
- ],
99
- },
100
- 'high-fidelity': {
101
- 'desc': '深度高保真/锚点/manifest',
102
- 'reads': [
103
- ('high-fidelity.md', ['三', '四']),
104
- ],
105
- },
106
- 'image-layout': {
107
- 'desc': '素材图片六版式与配图占位',
108
- 'reads': [
109
- ('components.md', ['11c']),
110
- ('playbook.md', ['三']),
111
- ],
112
- },
113
- 'style-theme': {
114
- 'desc': '配色/亮暗/风格选型',
115
- 'reads': [
116
- ('styles.md', ['快速选型', '新增']),
117
- ('design-system.md', ['1a', '1b', '9']),
118
- ],
119
- },
120
- 'icons': {
121
- 'desc': '图标语义速查与使用准则',
122
- 'reads': [
123
- ('icons.md', ['速查', '使用准则']),
124
- ],
125
- },
126
- }
127
-
128
- # 节号:阿拉伯(8 / 8b / 8-1)或中文(一 / 一-b / 一-续 / 十),须带 .、. 分隔或后随空白;
129
- # 无节号的二级标题也入节表(num='',用标题关键词寻址——modes/icons/styles 等中文标题文件)
130
- _SEC_NUM = r'(?:\d+(?:[a-z]|-\d+)?|[一二三四五六七八九十]{1,3}(?:-[a-z0-9续]+)?)'
131
- HEADING_RE = re.compile(
132
- r'^(#{2,4})[ \t]+(?:§)?(%s)[.、.]?[ \t]*(.*)$' % _SEC_NUM, re.M)
133
- HEADING_UNNUM_RE = re.compile(r'^(##)[ \t]+(.+)$', re.M)
134
- # 任意级别标题行(extract_chart 定位代码节边界用——### 代码节不能再被 ## 回退错层)
135
- _HEADING_ANY = re.compile(r'\n#{2,4}[ \t]')
136
- _CODE_FENCE = re.compile(r'```[\s\S]*?```')
137
-
138
- _TEXT_CACHE: dict[str, str] = {}
139
-
140
-
141
- def _read(path: Path) -> str:
142
- """带缓存的读取(extract_section/_sections/extract_chart 共用,防同文件重复 IO)。"""
143
- key = str(path)
144
- if key not in _TEXT_CACHE:
145
- _TEXT_CACHE[key] = path.read_text(encoding='utf-8')
146
- return _TEXT_CACHE[key]
147
-
148
-
149
- def _fence_spans(text: str) -> list[tuple[int, int]]:
150
- """代码围栏 ``` 区间(供 extract_chart 优先在代码内定位 data-chart)。"""
151
- return [(m.start(), m.end()) for m in _CODE_FENCE.finditer(text)]
152
-
153
-
154
- def _sections(path: Path) -> list[tuple[str, str, int, int]]:
155
- """返回 [(编号, 标题, start, end), ...]
156
-
157
- 编号节(## ~ ####)与无编号二级标题共同构成节边界;
158
- 无编号节 num='',仅供 extract_section 的标题关键词兜底命中。
159
- """
160
- text = _read(path)
161
- marks: list[tuple[str, str, int]] = []
162
- num_starts: set[int] = set()
163
- for m in HEADING_RE.finditer(text):
164
- marks.append((m.group(2), m.group(3).strip(), m.start()))
165
- num_starts.add(m.start())
166
- for m in HEADING_UNNUM_RE.finditer(text):
167
- if m.start() not in num_starts: # 已被编号正则命中则跳过
168
- marks.append(('', m.group(2).strip(), m.start()))
169
- marks.sort(key=lambda t: t[2])
170
- out = []
171
- for i, (num, title, start) in enumerate(marks):
172
- end = marks[i + 1][2] if i + 1 < len(marks) else len(text)
173
- out.append((num, title, start, end))
174
- return out
175
-
176
-
177
- def resolve_physical(filename: str, section: str | None = None) -> str:
178
- """逻辑文件名 → 物理文件名(components/charts 拆分后路由)。"""
179
- if not section:
180
- return filename
181
- mapping = SECTION_FILE_MAP.get(filename) or {}
182
- return mapping.get(str(section), filename)
183
-
184
-
185
- def extract_section(filename: str, section: str, max_chars: int = 12000) -> str:
186
- physical = resolve_physical(filename, section)
187
- path = REF / physical
188
- if not path.exists():
189
- path = REF / filename
190
- if not path.exists():
191
- return f'错误:{path} 不存在'
192
- secs = _sections(path)
193
- # ① 精确节号优先;② 无精确命中才允许前缀(并提示,防敲错节号静默取错码);③ 标题关键词兜底
194
- hits = [s for s in secs if s[0] == section]
195
- note = ''
196
- if not hits:
197
- prefix = [s for s in secs if s[0].startswith(section)]
198
- if prefix:
199
- hits = prefix[:1]
200
- note = (f'\n/* 提示:§{section} 无精确节号,已按前缀命中 §{hits[0][0]} '
201
- f'({hits[0][1][:24]});若非本意请用精确节号 */')
202
- if not hits:
203
- hits = [s for s in secs if section in s[1]]
204
- if not hits:
205
- seen: list[str] = []
206
- for s in secs:
207
- label = s[0] or (s[1][:10] + '…' if len(s[1]) > 10 else s[1])
208
- if label not in seen:
209
- seen.append(label)
210
- sample = '、'.join(seen[:12])
211
- return f'错误:{filename} 未找到 §{section}。可用节号/标题样例: {sample}'
212
- num, title, start, end = hits[0]
213
- body = _read(path)[start:end].rstrip()
214
- if len(body) > max_chars:
215
- body = body[:max_chars] + f'\n…(截断,全文见 references/{physical})'
216
- return f'/* references/{physical} §{num} {title} */\n\n{body}{note}'
217
-
218
-
219
- def verify_routes() -> list[str]:
220
- """遍历 TASK_ROUTES,返回不可解析/空路由问题清单(audit_docs ⑥ 与 regression ⑦-b 共用同一实现)。"""
221
- bad: list[str] = []
222
- for task, r in TASK_ROUTES.items():
223
- for fn, secs in r['reads']:
224
- if not secs:
225
- bad.append(f'{task}:{fn} 空路由')
226
- continue
227
- for sec in secs:
228
- if extract_section(fn, sec, max_chars=200).startswith('错误'):
229
- bad.append(f'{task}:{fn} §{sec}')
230
- return bad
231
-
232
-
233
- def extract_chart(chart_type: str, max_chars: int = 14000) -> str:
234
- chart_type = (chart_type or '').strip().lower()
235
- reg = ((LC.get('charts') or {}).get('registry') or {}).get(chart_type)
236
- if not reg:
237
- known = sorted((LC.get('charts') or {}).get('registry') or {})
238
- return f'错误:未登记图表 {chart_type!r}。可用: {", ".join(known)}'
239
- info_types = set(((LC.get('charts') or {}).get('scaffold') or {}).get('infoTypes') or {})
240
- key = f'data-chart="{chart_type}"'
241
- candidates = (
242
- [REF / 'infographics-stats.md', REF / 'infographics-structure.md', REF / 'infographics.md']
243
- if chart_type in info_types
244
- else [REF / 'charts-basic.md', REF / 'charts-extended.md',
245
- REF / 'charts-discipline.md', REF / 'charts.md']
246
- )
247
- path = next((p for p in candidates if p.exists() and key in _read(p)), None)
248
- if path is None:
249
- names = ', '.join(p.name for p in candidates if p.exists())
250
- return f'错误:未找到 {key}(检索: {names})'
251
- text = _read(path)
252
- # 优先取**代码围栏内**的 data-chart 出现位置——概述散文里的首个出现不是代码节
253
- fences = _fence_spans(text)
254
- idx = -1
255
- pos = text.find(key)
256
- while pos >= 0:
257
- if any(a <= pos < b for a, b in fences):
258
- idx = pos
259
- break
260
- pos = text.find(key, pos + 1)
261
- if idx < 0:
262
- idx = text.find(key) # 无围栏命中时退回首现
263
- # 回退到该代码块前最近的标题(任意级别——### 代码节不能被 ## 回退错层)
264
- prev_head = None
265
- for m in _HEADING_ANY.finditer(text, 0, idx + 1):
266
- prev_head = m
267
- head = prev_head.start() if prev_head else max(0, idx - 200)
268
- # 前进到下一个任意级别标题或文件尾
269
- nxt = _HEADING_ANY.search(text, idx)
270
- end = nxt.start() if nxt else len(text)
271
- body = text[head:end].rstrip()
272
- if len(body) > max_chars:
273
- body = body[:max_chars] + f'\n…(截断,全文见 {path.name})'
274
- meta = (f'/* chart={chart_type} · pptx={reg.get("pptx")} · '
275
- f'dataTable={reg.get("dataTable")} · 来源 references/{path.name} */')
276
- return f'{meta}\n\n{body}'
277
-
278
-
279
- def extract_page_type(page_type: str, max_chars: int = 10000) -> str:
280
- ms = json.loads((ROOT / 'scripts' / 'model-schema.json').read_text(encoding='utf-8'))
281
- pages = ms.get('pages') or ms.get('pageTypes') or ms
282
- # schema 结构:可能是 {pages: {type: {...}}} 或顶层
283
- entry = None
284
- if isinstance(pages, dict) and page_type in pages:
285
- entry = pages[page_type]
286
- elif isinstance(ms.get('sections'), dict) and page_type in ms['sections']:
287
- entry = ms['sections'][page_type]
288
- # 兜底:递归找 type
289
- if entry is None:
290
- def find(obj):
291
- if isinstance(obj, dict):
292
- if obj.get('type') == page_type or page_type in obj and isinstance(obj[page_type], dict):
293
- return obj.get(page_type, obj)
294
- for v in obj.values():
295
- r = find(v)
296
- if r is not None:
297
- return r
298
- return None
299
- entry = find(ms)
300
- if entry is None:
301
- return f'错误:model-schema.json 未找到页型 {page_type!r}'
302
- # 选型表提示
303
- hint = extract_section('components.md', '46', max_chars=4000)
304
- schema_txt = json.dumps({page_type: entry}, ensure_ascii=False, indent=2)
305
- return (f'/* pageType={page_type} · schema 字段(scripts/model-schema.json) */\n'
306
- f'{schema_txt}\n\n'
307
- f'/* 选型表摘要(components.md §46,完整表见原文) */\n'
308
- f'{hint}')
309
-
310
-
311
- def main() -> int:
312
- ap = argparse.ArgumentParser(description='L2 节级片段抽取')
313
- ap.add_argument('--list', action='store_true', help='列出任务路由与已登记图表')
314
- ap.add_argument('--task', help='任务路由名(research-evidence / chart-pick / …)')
315
- ap.add_argument('--chart', help='图表类型,从 charts.md / infographics.md 抽代码节')
316
- ap.add_argument('--page-type', dest='page_type', help='页型名,输出 schema 字段 + 选型提示')
317
- ap.add_argument('--file', help='references 下文件名,如 components.md')
318
- ap.add_argument('--section', help='节编号,如 46 / 11c / 36d')
319
- ap.add_argument('--max-chars', type=int, default=12000)
320
- args = ap.parse_args()
321
-
322
- if args.list:
323
- print('任务路由:')
324
- for name, r in TASK_ROUTES.items():
325
- print(f' {name:22} {r["desc"]}')
326
- for fn, secs in r['reads']:
327
- sec = ('§' + ' §'.join(secs)) if secs else '(全文按需)'
328
- print(f' · references/{fn} {sec}')
329
- print('\n已登记图表:')
330
- reg = (LC.get('charts') or {}).get('registry') or {}
331
- for t, meta in sorted(reg.items()):
332
- if t.startswith('$') or not isinstance(meta, dict):
333
- continue
334
- print(f' {t:14} pptx={meta.get("pptx")} dataTable={meta.get("dataTable")}')
335
- print('\n用法示例:')
336
- print(' python scripts/extract_snippet.py --task research-evidence')
337
- print(' python scripts/extract_snippet.py --chart waterfall')
338
- print(' python scripts/extract_snippet.py --page-type exhibit')
339
- print(' python scripts/extract_snippet.py --file components.md --section 46c')
340
- return 0
341
-
342
- if args.task:
343
- r = TASK_ROUTES.get(args.task)
344
- if not r:
345
- print(f'错误:未知任务 {args.task!r}。用 --list 查看。')
346
- return 2
347
- print(f'# 任务:{args.task} — {r["desc"]}\n')
348
- print('## 建议只读(读完即停,不预读下一份)\n')
349
- for fn, secs in r['reads']:
350
- sec = ('§' + '、'.join(secs)) if secs else '全文按需'
351
- print(f'- references/{fn} — {sec}')
352
- print('\n## 片段\n')
353
- for fn, secs in r['reads']:
354
- for sec in secs[:2]: # 每文件最多抽 2 节,防上下文爆
355
- print(extract_section(fn, sec, args.max_chars))
356
- print('\n---\n')
357
- return 0
358
-
359
- if args.chart:
360
- print(extract_chart(args.chart, args.max_chars))
361
- return 0
362
- if args.page_type:
363
- print(extract_page_type(args.page_type, args.max_chars))
364
- return 0
365
- if args.file and args.section:
366
- print(extract_section(args.file, args.section, args.max_chars))
367
- return 0
368
-
369
- ap.print_help()
370
- return 2
371
-
372
-
373
- if __name__ == '__main__':
374
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """TopPPT HTML · L2 节级片段抽取器(减少整读 components.md / charts.md 的上下文成本)
4
+
5
+ 用法:
6
+ python scripts/extract_snippet.py --list
7
+ python scripts/extract_snippet.py --chart waterfall
8
+ python scripts/extract_snippet.py --page-type exhibit
9
+ python scripts/extract_snippet.py --file components.md --section 46
10
+ python scripts/extract_snippet.py --task research-evidence
11
+ python scripts/extract_snippet.py --task pptx-export
12
+
13
+ 设计:
14
+ 智能体按「任务 → 只读相关节」取代码,而不是整文件读入 70KB+ 规范。
15
+ 节边界用标题行识别;--task 走内置路由表(与 playbook.md §十 同源)。
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import re
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ try:
26
+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')
27
+ except Exception:
28
+ pass
29
+
30
+ ROOT = Path(__file__).resolve().parent.parent
31
+ REF = ROOT / 'references'
32
+ LC = json.loads((ROOT / 'scripts' / 'layout-constants.json').read_text(encoding='utf-8'))
33
+ # §编号 → 物理文件(components/charts 拆分后逻辑路由;单源 scripts/section-file-map.json)
34
+ _SECTION_MAP_PATH = ROOT / 'scripts' / 'section-file-map.json'
35
+ try:
36
+ SECTION_FILE_MAP = json.loads(_SECTION_MAP_PATH.read_text(encoding='utf-8'))
37
+ except (OSError, json.JSONDecodeError):
38
+ SECTION_FILE_MAP = {}
39
+
40
+ # 任务 → 建议只读的文件与节(与 references/playbook.md §十 保持一致)
41
+ # 节号三种形态均可寻址:阿拉伯(46 / 46b / 8-1)、中文(三 / 一-b)、标题关键词(精导 / 速查)
42
+ TASK_ROUTES = {
43
+ 'research-evidence': {
44
+ 'desc': 'research 证据页 / Exhibit / 密表',
45
+ 'reads': [
46
+ ('components.md', ['36d', '46', '46c']),
47
+ ('playbook.md', ['三', '四']),
48
+ ],
49
+ },
50
+ 'presentation-combo': {
51
+ 'desc': '演示组合版式与卡片',
52
+ 'reads': [
53
+ ('components.md', ['39', '40', '41', '42', '46', '46b', '46c']),
54
+ ('playbook.md', ['三', '四']),
55
+ ],
56
+ },
57
+ 'architecture-diagram': {
58
+ 'desc': '架构/泳道/分层',
59
+ 'reads': [
60
+ ('components.md', ['37', '38', '38b']),
61
+ ('infographics.md', ['78', '79', '80']),
62
+ ('playbook.md', ['三', '七']),
63
+ ],
64
+ },
65
+ 'chart-pick': {
66
+ 'desc': '选图与取图表代码',
67
+ 'reads': [
68
+ ('playbook.md', ['五']),
69
+ ('charts.md', ['16']),
70
+ ],
71
+ },
72
+ 'content-rules': {
73
+ 'desc': '密度/字数/去AI味/细节保全',
74
+ 'reads': [
75
+ ('content-rules.md', ['四', '一']),
76
+ ('playbook.md', ['六']),
77
+ ],
78
+ },
79
+ 'layout-grammar': {
80
+ 'desc': '布局骨架 P1–P12 / 元素排版 / 组合与留白',
81
+ 'reads': [
82
+ ('layout-grammar.md', ['〇', '二', '三', '四']),
83
+ ('playbook.md', ['〇']),
84
+ ],
85
+ },
86
+ 'model-render': {
87
+ 'desc': '模型驱动生成 / 单写路径',
88
+ 'reads': [
89
+ ('pptx-export.md', ['内容模型']),
90
+ ('content-rules.md', ['二-b']),
91
+ ],
92
+ },
93
+ 'pptx-export': {
94
+ 'desc': 'PPTX 精导与页型字段',
95
+ 'reads': [
96
+ ('pptx-export.md', ['精导', '内容模型']),
97
+ ('playbook.md', ['九']),
98
+ ],
99
+ },
100
+ 'high-fidelity': {
101
+ 'desc': '深度高保真/锚点/manifest',
102
+ 'reads': [
103
+ ('high-fidelity.md', ['三', '四']),
104
+ ],
105
+ },
106
+ 'image-layout': {
107
+ 'desc': '素材图片六版式与配图占位',
108
+ 'reads': [
109
+ ('components.md', ['11c']),
110
+ ('playbook.md', ['三']),
111
+ ],
112
+ },
113
+ 'style-theme': {
114
+ 'desc': '配色/亮暗/风格选型',
115
+ 'reads': [
116
+ ('styles.md', ['快速选型', '新增']),
117
+ ('design-system.md', ['1a', '1b', '9']),
118
+ ],
119
+ },
120
+ 'icons': {
121
+ 'desc': '图标语义速查与使用准则',
122
+ 'reads': [
123
+ ('icons.md', ['速查', '使用准则']),
124
+ ],
125
+ },
126
+ }
127
+
128
+ # 节号:阿拉伯(8 / 8b / 8-1)或中文(一 / 一-b / 一-续 / 十),须带 .、. 分隔或后随空白;
129
+ # 无节号的二级标题也入节表(num='',用标题关键词寻址——modes/icons/styles 等中文标题文件)
130
+ _SEC_NUM = r'(?:\d+(?:[a-z]|-\d+)?|[一二三四五六七八九十]{1,3}(?:-[a-z0-9续]+)?)'
131
+ HEADING_RE = re.compile(
132
+ r'^(#{2,4})[ \t]+(?:§)?(%s)[.、.]?[ \t]*(.*)$' % _SEC_NUM, re.M)
133
+ HEADING_UNNUM_RE = re.compile(r'^(##)[ \t]+(.+)$', re.M)
134
+ # 任意级别标题行(extract_chart 定位代码节边界用——### 代码节不能再被 ## 回退错层)
135
+ _HEADING_ANY = re.compile(r'\n#{2,4}[ \t]')
136
+ _CODE_FENCE = re.compile(r'```[\s\S]*?```')
137
+
138
+ _TEXT_CACHE: dict[str, str] = {}
139
+
140
+
141
+ def _read(path: Path) -> str:
142
+ """带缓存的读取(extract_section/_sections/extract_chart 共用,防同文件重复 IO)。"""
143
+ key = str(path)
144
+ if key not in _TEXT_CACHE:
145
+ _TEXT_CACHE[key] = path.read_text(encoding='utf-8')
146
+ return _TEXT_CACHE[key]
147
+
148
+
149
+ def _fence_spans(text: str) -> list[tuple[int, int]]:
150
+ """代码围栏 ``` 区间(供 extract_chart 优先在代码内定位 data-chart)。"""
151
+ return [(m.start(), m.end()) for m in _CODE_FENCE.finditer(text)]
152
+
153
+
154
+ def _sections(path: Path) -> list[tuple[str, str, int, int]]:
155
+ """返回 [(编号, 标题, start, end), ...]
156
+
157
+ 编号节(## ~ ####)与无编号二级标题共同构成节边界;
158
+ 无编号节 num='',仅供 extract_section 的标题关键词兜底命中。
159
+ """
160
+ text = _read(path)
161
+ marks: list[tuple[str, str, int]] = []
162
+ num_starts: set[int] = set()
163
+ for m in HEADING_RE.finditer(text):
164
+ marks.append((m.group(2), m.group(3).strip(), m.start()))
165
+ num_starts.add(m.start())
166
+ for m in HEADING_UNNUM_RE.finditer(text):
167
+ if m.start() not in num_starts: # 已被编号正则命中则跳过
168
+ marks.append(('', m.group(2).strip(), m.start()))
169
+ marks.sort(key=lambda t: t[2])
170
+ out = []
171
+ for i, (num, title, start) in enumerate(marks):
172
+ end = marks[i + 1][2] if i + 1 < len(marks) else len(text)
173
+ out.append((num, title, start, end))
174
+ return out
175
+
176
+
177
+ def resolve_physical(filename: str, section: str | None = None) -> str:
178
+ """逻辑文件名 → 物理文件名(components/charts 拆分后路由)。"""
179
+ if not section:
180
+ return filename
181
+ mapping = SECTION_FILE_MAP.get(filename) or {}
182
+ return mapping.get(str(section), filename)
183
+
184
+
185
+ def extract_section(filename: str, section: str, max_chars: int = 12000) -> str:
186
+ physical = resolve_physical(filename, section)
187
+ path = REF / physical
188
+ if not path.exists():
189
+ path = REF / filename
190
+ if not path.exists():
191
+ return f'错误:{path} 不存在'
192
+ secs = _sections(path)
193
+ # ① 精确节号优先;② 无精确命中才允许前缀(并提示,防敲错节号静默取错码);③ 标题关键词兜底
194
+ hits = [s for s in secs if s[0] == section]
195
+ note = ''
196
+ if not hits:
197
+ prefix = [s for s in secs if s[0].startswith(section)]
198
+ if prefix:
199
+ hits = prefix[:1]
200
+ note = (f'\n/* 提示:§{section} 无精确节号,已按前缀命中 §{hits[0][0]} '
201
+ f'({hits[0][1][:24]});若非本意请用精确节号 */')
202
+ if not hits:
203
+ hits = [s for s in secs if section in s[1]]
204
+ if not hits:
205
+ seen: list[str] = []
206
+ for s in secs:
207
+ label = s[0] or (s[1][:10] + '…' if len(s[1]) > 10 else s[1])
208
+ if label not in seen:
209
+ seen.append(label)
210
+ sample = '、'.join(seen[:12])
211
+ return f'错误:{filename} 未找到 §{section}。可用节号/标题样例: {sample}'
212
+ num, title, start, end = hits[0]
213
+ body = _read(path)[start:end].rstrip()
214
+ if len(body) > max_chars:
215
+ body = body[:max_chars] + f'\n…(截断,全文见 references/{physical})'
216
+ return f'/* references/{physical} §{num} {title} */\n\n{body}{note}'
217
+
218
+
219
+ def verify_routes() -> list[str]:
220
+ """遍历 TASK_ROUTES,返回不可解析/空路由问题清单(audit_docs ⑥ 与 regression ⑦-b 共用同一实现)。"""
221
+ bad: list[str] = []
222
+ for task, r in TASK_ROUTES.items():
223
+ for fn, secs in r['reads']:
224
+ if not secs:
225
+ bad.append(f'{task}:{fn} 空路由')
226
+ continue
227
+ for sec in secs:
228
+ if extract_section(fn, sec, max_chars=200).startswith('错误'):
229
+ bad.append(f'{task}:{fn} §{sec}')
230
+ return bad
231
+
232
+
233
+ def extract_chart(chart_type: str, max_chars: int = 14000) -> str:
234
+ chart_type = (chart_type or '').strip().lower()
235
+ reg = ((LC.get('charts') or {}).get('registry') or {}).get(chart_type)
236
+ if not reg:
237
+ known = sorted((LC.get('charts') or {}).get('registry') or {})
238
+ return f'错误:未登记图表 {chart_type!r}。可用: {", ".join(known)}'
239
+ info_types = set(((LC.get('charts') or {}).get('scaffold') or {}).get('infoTypes') or {})
240
+ key = f'data-chart="{chart_type}"'
241
+ candidates = (
242
+ [REF / 'infographics-stats.md', REF / 'infographics-structure.md', REF / 'infographics.md']
243
+ if chart_type in info_types
244
+ else [REF / 'charts-basic.md', REF / 'charts-extended.md',
245
+ REF / 'charts-discipline.md', REF / 'charts.md']
246
+ )
247
+ path = next((p for p in candidates if p.exists() and key in _read(p)), None)
248
+ if path is None:
249
+ names = ', '.join(p.name for p in candidates if p.exists())
250
+ return f'错误:未找到 {key}(检索: {names})'
251
+ text = _read(path)
252
+ # 优先取**代码围栏内**的 data-chart 出现位置——概述散文里的首个出现不是代码节
253
+ fences = _fence_spans(text)
254
+ idx = -1
255
+ pos = text.find(key)
256
+ while pos >= 0:
257
+ if any(a <= pos < b for a, b in fences):
258
+ idx = pos
259
+ break
260
+ pos = text.find(key, pos + 1)
261
+ if idx < 0:
262
+ idx = text.find(key) # 无围栏命中时退回首现
263
+ # 回退到该代码块前最近的标题(任意级别——### 代码节不能被 ## 回退错层)
264
+ prev_head = None
265
+ for m in _HEADING_ANY.finditer(text, 0, idx + 1):
266
+ prev_head = m
267
+ head = prev_head.start() if prev_head else max(0, idx - 200)
268
+ # 前进到下一个任意级别标题或文件尾
269
+ nxt = _HEADING_ANY.search(text, idx)
270
+ end = nxt.start() if nxt else len(text)
271
+ body = text[head:end].rstrip()
272
+ if len(body) > max_chars:
273
+ body = body[:max_chars] + f'\n…(截断,全文见 {path.name})'
274
+ meta = (f'/* chart={chart_type} · pptx={reg.get("pptx")} · '
275
+ f'dataTable={reg.get("dataTable")} · 来源 references/{path.name} */')
276
+ return f'{meta}\n\n{body}'
277
+
278
+
279
+ def extract_page_type(page_type: str, max_chars: int = 10000) -> str:
280
+ ms = json.loads((ROOT / 'scripts' / 'model-schema.json').read_text(encoding='utf-8'))
281
+ pages = ms.get('pages') or ms.get('pageTypes') or ms
282
+ # schema 结构:可能是 {pages: {type: {...}}} 或顶层
283
+ entry = None
284
+ if isinstance(pages, dict) and page_type in pages:
285
+ entry = pages[page_type]
286
+ elif isinstance(ms.get('sections'), dict) and page_type in ms['sections']:
287
+ entry = ms['sections'][page_type]
288
+ # 兜底:递归找 type
289
+ if entry is None:
290
+ def find(obj):
291
+ if isinstance(obj, dict):
292
+ if obj.get('type') == page_type or page_type in obj and isinstance(obj[page_type], dict):
293
+ return obj.get(page_type, obj)
294
+ for v in obj.values():
295
+ r = find(v)
296
+ if r is not None:
297
+ return r
298
+ return None
299
+ entry = find(ms)
300
+ if entry is None:
301
+ return f'错误:model-schema.json 未找到页型 {page_type!r}'
302
+ # 选型表提示
303
+ hint = extract_section('components.md', '46', max_chars=4000)
304
+ schema_txt = json.dumps({page_type: entry}, ensure_ascii=False, indent=2)
305
+ return (f'/* pageType={page_type} · schema 字段(scripts/model-schema.json) */\n'
306
+ f'{schema_txt}\n\n'
307
+ f'/* 选型表摘要(components.md §46,完整表见原文) */\n'
308
+ f'{hint}')
309
+
310
+
311
+ def main() -> int:
312
+ ap = argparse.ArgumentParser(description='L2 节级片段抽取')
313
+ ap.add_argument('--list', action='store_true', help='列出任务路由与已登记图表')
314
+ ap.add_argument('--task', help='任务路由名(research-evidence / chart-pick / …)')
315
+ ap.add_argument('--chart', help='图表类型,从 charts.md / infographics.md 抽代码节')
316
+ ap.add_argument('--page-type', dest='page_type', help='页型名,输出 schema 字段 + 选型提示')
317
+ ap.add_argument('--file', help='references 下文件名,如 components.md')
318
+ ap.add_argument('--section', help='节编号,如 46 / 11c / 36d')
319
+ ap.add_argument('--max-chars', type=int, default=12000)
320
+ args = ap.parse_args()
321
+
322
+ if args.list:
323
+ print('任务路由:')
324
+ for name, r in TASK_ROUTES.items():
325
+ print(f' {name:22} {r["desc"]}')
326
+ for fn, secs in r['reads']:
327
+ sec = ('§' + ' §'.join(secs)) if secs else '(全文按需)'
328
+ print(f' · references/{fn} {sec}')
329
+ print('\n已登记图表:')
330
+ reg = (LC.get('charts') or {}).get('registry') or {}
331
+ for t, meta in sorted(reg.items()):
332
+ if t.startswith('$') or not isinstance(meta, dict):
333
+ continue
334
+ print(f' {t:14} pptx={meta.get("pptx")} dataTable={meta.get("dataTable")}')
335
+ print('\n用法示例:')
336
+ print(' python scripts/extract_snippet.py --task research-evidence')
337
+ print(' python scripts/extract_snippet.py --chart waterfall')
338
+ print(' python scripts/extract_snippet.py --page-type exhibit')
339
+ print(' python scripts/extract_snippet.py --file components.md --section 46c')
340
+ return 0
341
+
342
+ if args.task:
343
+ r = TASK_ROUTES.get(args.task)
344
+ if not r:
345
+ print(f'错误:未知任务 {args.task!r}。用 --list 查看。')
346
+ return 2
347
+ print(f'# 任务:{args.task} — {r["desc"]}\n')
348
+ print('## 建议只读(读完即停,不预读下一份)\n')
349
+ for fn, secs in r['reads']:
350
+ sec = ('§' + '、'.join(secs)) if secs else '全文按需'
351
+ print(f'- references/{fn} — {sec}')
352
+ print('\n## 片段\n')
353
+ for fn, secs in r['reads']:
354
+ for sec in secs[:2]: # 每文件最多抽 2 节,防上下文爆
355
+ print(extract_section(fn, sec, args.max_chars))
356
+ print('\n---\n')
357
+ return 0
358
+
359
+ if args.chart:
360
+ print(extract_chart(args.chart, args.max_chars))
361
+ return 0
362
+ if args.page_type:
363
+ print(extract_page_type(args.page_type, args.max_chars))
364
+ return 0
365
+ if args.file and args.section:
366
+ print(extract_section(args.file, args.section, args.max_chars))
367
+ return 0
368
+
369
+ ap.print_help()
370
+ return 2
371
+
372
+
373
+ if __name__ == '__main__':
374
+ sys.exit(main())