@lark-apaas/coding-steering 0.1.39-alpha.20260824204539 → 0.1.39

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 (25) hide show
  1. package/package.json +6 -6
  2. package/steering/design-html/skills/pptx-style-extract/SKILL.md +28 -19
  3. package/steering/design-html/skills/pptx-style-extract/scripts/census.py +8 -2
  4. package/steering/design-html/skills/pptx-style-extract/scripts/draft.py +1181 -190
  5. package/steering/design-html/skills/pptx-style-extract/scripts/extract.py +229 -10
  6. package/steering/design-html/skills/pptx-style-extract/scripts/ooxml.py +18 -1
  7. package/steering/design-html/skills/pptx-style-extract/scripts/package.py +643 -40
  8. package/steering/design-html/skills/pptx-style-extract/scripts/parts.py +19 -3
  9. package/steering/design-html/skills/pptx-style-extract/scripts/render_pages.py +4 -2
  10. package/steering/design-html/skills/pptx-style-extract/scripts/test_asset_judgment_package.py +556 -0
  11. package/steering/design-html/skills/pptx-style-extract/scripts/test_background_composite.py +308 -1
  12. package/steering/design-html/skills/pptx-style-extract/scripts/test_design_consumer_contract.py +14 -0
  13. package/steering/design-html/skills/pptx-style-extract/scripts/test_flow_layout_contract.py +157 -7
  14. package/steering/design-html/skills/pptx-style-extract/scripts/test_layout_css.py +1598 -2
  15. package/steering/design-html/skills/pptx-style-extract/scripts/test_logo_scope.py +479 -0
  16. package/steering/design-html/skills/pptx-style-extract/scripts/test_text_role_contract.py +151 -4
  17. package/steering/design-html/skills/pptx-style-extract/scripts/verify_layout_assets.py +400 -0
  18. package/steering/design-html/skills/pptx-style-extract/scripts/verify_logo_scope.py +12 -0
  19. package/steering/design-html/skills/pptx-style-extract/v2-format-spec.md +1 -1
  20. package/steering/design-html/skills/preflight/scripts/probe.sh +0 -0
  21. package/steering/nestjs-react-fullstack/skills/coding-guide/SKILL.md +11 -0
  22. package/steering/nestjs-react-fullstack/skills/contacts-service/SKILL.md +67 -4
  23. package/steering/nestjs-react-fullstack/skills/nestjs-cache/SKILL.md +0 -1
  24. package/steering/nestjs-react-fullstack/skills/openapi-guide/SKILL.md +75 -0
  25. package/steering/nestjs-react-fullstack/skills_local/coding-guide/SKILL.md +5 -7
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env python3
2
+ """Verify that generated slides honor every asset bound to their PPTX layout."""
3
+ import argparse
4
+ import hashlib
5
+ import os
6
+ import posixpath
7
+ import re
8
+ import sys
9
+ from collections import Counter
10
+ from html.parser import HTMLParser
11
+ from urllib.parse import urlsplit
12
+
13
+ from check_v2 import Pack
14
+
15
+
16
+ URL_RE = re.compile(r'url\(\s*[\'"]?([^\'")\s]+)', re.I)
17
+ VOID_TAGS = {
18
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
19
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
20
+ }
21
+
22
+
23
+ def normalized_path(value):
24
+ path = urlsplit(value).path.replace('\\', '/')
25
+ return posixpath.normpath(path).lstrip('./')
26
+
27
+
28
+ def bound_asset_ids(value, known_asset_ids):
29
+ found = Counter()
30
+ if isinstance(value, dict):
31
+ for key, child in value.items():
32
+ if (key in ('asset', 'background')
33
+ and isinstance(child, str)
34
+ and child in known_asset_ids):
35
+ found[child] += 1
36
+ found.update(bound_asset_ids(child, known_asset_ids))
37
+ elif isinstance(value, list):
38
+ for child in value:
39
+ found.update(bound_asset_ids(child, known_asset_ids))
40
+ return found
41
+
42
+
43
+ def layout_asset_contract(pack):
44
+ known_asset_ids = set(pack.assets)
45
+ owners = {}
46
+ for layout_name, (layout, _) in pack.layouts.items():
47
+ for asset_id, _, _ in layout_asset_instances(
48
+ layout, known_asset_ids, pack.canvas):
49
+ owners.setdefault(asset_id, set()).add(layout_name)
50
+ return owners
51
+
52
+
53
+ def asset_urls(pack, asset_prefix, asset_ids):
54
+ prefix = normalized_path(asset_prefix).rstrip('/')
55
+ urls = {}
56
+ for asset_id in asset_ids:
57
+ entry, _ = pack.assets.get(asset_id, (None, None))
58
+ if not isinstance(entry, dict):
59
+ continue
60
+ path = entry.get('path')
61
+ if not isinstance(path, str) or not path:
62
+ continue
63
+ relative = normalized_path(path)
64
+ if relative.startswith('assets/'):
65
+ relative = relative[len('assets/'):]
66
+ urls.setdefault(posixpath.join(prefix, relative), set()).add(asset_id)
67
+ return urls
68
+
69
+
70
+ def bound_asset_instances(value, known_asset_ids):
71
+ """Return every positioned fixed-asset instance nested in slots or flow."""
72
+ instances = []
73
+ if isinstance(value, dict):
74
+ box = value.get('box')
75
+ asset_id = value.get('asset')
76
+ if (isinstance(box, list) and len(box) == 4
77
+ and isinstance(asset_id, str)
78
+ and asset_id in known_asset_ids):
79
+ instances.append((asset_id, value.get('role') or 'asset', box))
80
+ for key, child in value.items():
81
+ if key not in ('asset', 'background'):
82
+ instances.extend(bound_asset_instances(child, known_asset_ids))
83
+ elif isinstance(value, list):
84
+ for child in value:
85
+ instances.extend(bound_asset_instances(child, known_asset_ids))
86
+ return instances
87
+
88
+
89
+ def layout_asset_instances(layout, known_asset_ids, canvas):
90
+ """Return every fixed image instance declared by one layout."""
91
+ if not isinstance(layout, dict):
92
+ return []
93
+ instances = []
94
+ background = layout.get('background')
95
+ if canvas and isinstance(background, str) and background in known_asset_ids:
96
+ instances.append(
97
+ (background, 'background', [0, 0, canvas[0], canvas[1]]))
98
+ instances.extend(bound_asset_instances(layout, known_asset_ids))
99
+ return instances
100
+
101
+
102
+ def inline_styles(value):
103
+ styles = {}
104
+ for declaration in (value or '').split(';'):
105
+ if ':' not in declaration:
106
+ continue
107
+ name, raw = declaration.split(':', 1)
108
+ styles[name.strip().lower()] = re.sub(
109
+ r'\s*!important\s*$', '', raw.strip().lower())
110
+ return styles
111
+
112
+
113
+ def css_number(value):
114
+ match = re.fullmatch(r'(-?(?:\d+(?:\.\d*)?|\.\d+))(?:px)?', value or '')
115
+ return float(match.group(1)) if match else None
116
+
117
+
118
+ def element_box(reference, canvas):
119
+ styles = reference['styles']
120
+ if reference['slide_root'] and not any(
121
+ name in styles for name in ('left', 'top', 'width', 'height')):
122
+ return [0.0, 0.0, float(canvas[0]), float(canvas[1])]
123
+ values = [
124
+ css_number(styles.get(name))
125
+ for name in ('left', 'top', 'width', 'height')
126
+ ]
127
+ if styles.get('position') != 'absolute' or any(
128
+ value is None for value in values):
129
+ return None
130
+ return values
131
+
132
+
133
+ def boxes_match(actual, expected, tolerance=1.0):
134
+ return actual is not None and all(
135
+ abs(actual_value - expected_value) <= tolerance
136
+ for actual_value, expected_value in zip(actual, expected)
137
+ )
138
+
139
+
140
+ def file_sha256(path):
141
+ digest = hashlib.sha256()
142
+ with open(path, 'rb') as stream:
143
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):
144
+ digest.update(chunk)
145
+ return digest.hexdigest()
146
+
147
+
148
+ def copied_asset_problems(pack, html_path, asset_prefix, asset_ids):
149
+ """Verify copied fixed assets still contain the source PPTX bytes."""
150
+ problems = []
151
+ html_root = os.path.dirname(os.path.abspath(html_path))
152
+ prefix = normalized_path(asset_prefix).rstrip('/')
153
+ for asset_id in sorted(asset_ids):
154
+ entry, _ = pack.assets.get(asset_id, (None, None))
155
+ path = entry.get('path') if isinstance(entry, dict) else None
156
+ if not isinstance(path, str) or not path:
157
+ continue
158
+ relative = normalized_path(path)
159
+ if relative.startswith('assets/'):
160
+ relative = relative[len('assets/'):]
161
+ source_path = os.path.join(pack.root, 'assets', *relative.split('/'))
162
+ copied_relative = posixpath.join(prefix, relative)
163
+ copied_path = os.path.join(html_root, *copied_relative.split('/'))
164
+ if not os.path.isfile(copied_path):
165
+ problems.append(
166
+ '固定素材 %s 未复制到项目: %s' % (asset_id, copied_relative))
167
+ continue
168
+ if not os.path.isfile(source_path):
169
+ problems.append(
170
+ '风格包中的固定素材 %s 不存在: %s' % (asset_id, path))
171
+ continue
172
+ if file_sha256(copied_path) != file_sha256(source_path):
173
+ problems.append(
174
+ '固定素材 %s 已被替换或改写,必须使用 PPTX 原文件' % asset_id)
175
+ return problems
176
+
177
+
178
+ def urls_from_attrs(attrs):
179
+ urls = []
180
+ for key, value in attrs:
181
+ if not value:
182
+ continue
183
+ if key.lower() in ('src', 'href'):
184
+ urls.append(value)
185
+ elif key.lower() == 'srcset':
186
+ urls.extend(item.strip().split(' ', 1)[0] for item in value.split(','))
187
+ elif key.lower() == 'style':
188
+ urls.extend(URL_RE.findall(value))
189
+ return urls
190
+
191
+
192
+ class SlideAssetParser(HTMLParser):
193
+ def __init__(self):
194
+ super().__init__()
195
+ self.slides = []
196
+ self._stack = []
197
+ self._style_depth = 0
198
+ self.outside_urls = []
199
+
200
+ def handle_starttag(self, tag, attrs):
201
+ tag = tag.lower()
202
+ attrs_map = {key.lower(): value for key, value in attrs}
203
+ urls = urls_from_attrs(attrs)
204
+ parent = self._stack[-1] if self._stack else None
205
+ parent_slide = parent['slide'] if parent else None
206
+ slide_root = bool(
207
+ tag == 'section' and parent and parent['tag'] == 'deck-stage')
208
+ slide = ({
209
+ 'layout': attrs_map.get('data-pptx-layout'),
210
+ 'references': [],
211
+ } if slide_root else parent_slide)
212
+ if slide_root:
213
+ self.slides.append(slide)
214
+ styles = inline_styles(attrs_map.get('style'))
215
+ hidden = bool(
216
+ (parent and parent['hidden'])
217
+ or 'hidden' in attrs_map
218
+ or attrs_map.get('aria-hidden', '').lower() == 'true'
219
+ or styles.get('display') == 'none'
220
+ or styles.get('visibility') in ('hidden', 'collapse')
221
+ or styles.get('content-visibility') == 'hidden'
222
+ or css_number(styles.get('width')) == 0
223
+ or css_number(styles.get('height')) == 0
224
+ or (
225
+ css_number(styles.get('opacity')) is not None
226
+ and css_number(styles.get('opacity')) <= 0
227
+ )
228
+ )
229
+ if slide is not None and (urls or attrs_map.get('data-pptx-asset')):
230
+ slide['references'].append({
231
+ 'asset': attrs_map.get('data-pptx-asset'),
232
+ 'hidden': hidden,
233
+ 'slide_root': slide_root,
234
+ 'source': attrs_map.get('src'),
235
+ 'styles': styles,
236
+ 'tag': tag,
237
+ 'urls': urls,
238
+ })
239
+ elif urls:
240
+ self.outside_urls.extend(urls)
241
+ if tag == 'style':
242
+ self._style_depth += 1
243
+ if tag not in VOID_TAGS:
244
+ self._stack.append({
245
+ 'hidden': hidden,
246
+ 'slide': slide,
247
+ 'tag': tag,
248
+ })
249
+
250
+ def handle_startendtag(self, tag, attrs):
251
+ self.handle_starttag(tag, attrs)
252
+ if tag.lower() not in VOID_TAGS:
253
+ self.handle_endtag(tag)
254
+
255
+ def handle_endtag(self, tag):
256
+ tag = tag.lower()
257
+ if tag == 'style' and self._style_depth:
258
+ self._style_depth -= 1
259
+ if tag not in VOID_TAGS and self._stack:
260
+ self._stack.pop()
261
+
262
+ def handle_data(self, data):
263
+ if not self._style_depth:
264
+ return
265
+ self.outside_urls.extend(URL_RE.findall(data))
266
+
267
+
268
+ def validate_layout_assets(pack_dir, html_path, asset_prefix):
269
+ """Return violations of the asset contract declared by each layout."""
270
+ pack = Pack(pack_dir)
271
+ owners = layout_asset_contract(pack)
272
+ known_urls = asset_urls(pack, asset_prefix, owners)
273
+ if not known_urls:
274
+ return []
275
+ asset_urls_by_id = {
276
+ asset_id: url
277
+ for url, asset_ids in known_urls.items()
278
+ for asset_id in asset_ids
279
+ }
280
+
281
+ with open(html_path, encoding='utf-8') as stream:
282
+ text = stream.read()
283
+ parser = SlideAssetParser()
284
+ parser.feed(text)
285
+ parser.close()
286
+
287
+ problems = copied_asset_problems(pack, html_path, asset_prefix, owners)
288
+ for url in parser.outside_urls:
289
+ for asset_id in sorted(known_urls.get(normalized_path(url), ())):
290
+ problems.append(
291
+ '模板资产 %s 出现在 slide section 外,无法核验页型归属' % asset_id)
292
+ for number, slide in enumerate(parser.slides, 1):
293
+ layout = slide['layout']
294
+ if not layout:
295
+ problems.append('第 %d 页缺少 data-pptx-layout,无法核验模板资产归属' % number)
296
+ continue
297
+ if layout not in pack.layouts:
298
+ problems.append('第 %d 页声明了不存在的模板页型: %s' % (number, layout))
299
+ continue
300
+ expected = layout_asset_instances(
301
+ pack.layouts[layout][0], set(pack.assets), pack.canvas)
302
+ actual = []
303
+ for reference in slide['references']:
304
+ referenced_ids = set()
305
+ normalized_urls = [normalized_path(url) for url in reference['urls']]
306
+ for url in normalized_urls:
307
+ referenced_ids.update(known_urls.get(url, ()))
308
+ asset_id = reference['asset']
309
+ if not asset_id:
310
+ for referenced_id in sorted(referenced_ids):
311
+ problems.append(
312
+ '第 %d 页模板资产 %s 缺少 data-pptx-asset 实例标记'
313
+ % (number, referenced_id))
314
+ continue
315
+ if asset_id not in pack.assets:
316
+ problems.append(
317
+ '第 %d 页声明了不存在的模板资产: %s' % (number, asset_id))
318
+ continue
319
+ expected_url = asset_urls_by_id.get(asset_id)
320
+ uses_expected_source = (
321
+ len(normalized_urls) == 1
322
+ and normalized_urls[0] == expected_url
323
+ and (
324
+ reference['tag'] != 'img'
325
+ or (
326
+ reference['source']
327
+ and normalized_path(reference['source']) == expected_url
328
+ )
329
+ )
330
+ )
331
+ if not uses_expected_source:
332
+ problems.append(
333
+ '第 %d 页固定实例 %s 未引用对应的 PPTX 原素材'
334
+ % (number, asset_id))
335
+ if reference['hidden']:
336
+ problems.append(
337
+ '第 %d 页固定实例 %s 不可隐藏' % (number, asset_id))
338
+ actual.append({
339
+ 'asset': asset_id,
340
+ 'box': element_box(reference, pack.canvas),
341
+ })
342
+
343
+ used_asset_counts = Counter(instance['asset'] for instance in actual)
344
+ for asset_id in sorted(used_asset_counts):
345
+ if layout not in owners.get(asset_id, set()):
346
+ allowed = '、'.join(sorted(owners.get(asset_id) or ())) or '(无)'
347
+ problems.append(
348
+ '第 %d 页页型 %s 不得使用 %s;只允许: %s'
349
+ % (number, layout, asset_id, allowed))
350
+ unmatched = list(actual)
351
+ for asset_id, _, expected_box in expected:
352
+ matching_index = next((
353
+ index for index, instance in enumerate(unmatched)
354
+ if instance['asset'] == asset_id
355
+ and boxes_match(instance['box'], expected_box)
356
+ ), None)
357
+ if matching_index is not None:
358
+ unmatched.pop(matching_index)
359
+ continue
360
+ same_asset = next((
361
+ instance for instance in unmatched
362
+ if instance['asset'] == asset_id
363
+ ), None)
364
+ if same_asset:
365
+ problems.append(
366
+ '第 %d 页固定实例 %s 的位置尺寸必须为 %s,当前为 %s'
367
+ % (number, asset_id, expected_box, same_asset['box']))
368
+ unmatched.remove(same_asset)
369
+ else:
370
+ problems.append(
371
+ '第 %d 页页型 %s 缺少固定实例 %s,位置尺寸应为 %s'
372
+ % (number, layout, asset_id, expected_box))
373
+ for instance in unmatched:
374
+ if layout in owners.get(instance['asset'], set()):
375
+ problems.append(
376
+ '第 %d 页页型 %s 额外使用了固定实例 %s'
377
+ % (number, layout, instance['asset']))
378
+ return problems
379
+
380
+
381
+ def main(argv=None):
382
+ parser = argparse.ArgumentParser(
383
+ description='Verify that generated deck HTML honors PPTX layout asset bindings.')
384
+ parser.add_argument('pack_dir')
385
+ parser.add_argument('html_path')
386
+ parser.add_argument('--asset-prefix', required=True)
387
+ args = parser.parse_args(argv)
388
+
389
+ problems = validate_layout_assets(args.pack_dir, args.html_path, args.asset_prefix)
390
+ if not problems:
391
+ print('PPTX_LAYOUT_ASSETS: PASS')
392
+ return 0
393
+ print('PPTX_LAYOUT_ASSETS: FAIL count=%d' % len(problems))
394
+ for problem in problems:
395
+ print('[layoutAssets] %s' % problem)
396
+ return 1
397
+
398
+
399
+ if __name__ == '__main__':
400
+ sys.exit(main())
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env python3
2
+ """Backward-compatible entrypoint for PPTX layout asset verification."""
3
+ import sys
4
+
5
+ from verify_layout_assets import main, validate_layout_assets
6
+
7
+
8
+ validate_logo_scope = validate_layout_assets
9
+
10
+
11
+ if __name__ == '__main__':
12
+ sys.exit(main())
@@ -133,7 +133,7 @@ layouts:
133
133
 
134
134
  - **`background` 三形态**:`<asset-id>` / `{<theme>: <asset-id>}` / `{color: <colors-token>}`(`color` 是保留键,主题名禁止叫 color)。`asset` 两形态:`<asset-id>` / `{<theme>: <asset-id>}`。
135
135
  - **背景安全扩展**:有真实背景图的 archetype 建议写 `text_safe: [x,y,w,h]`、`avoid: [{box: [x,y,w,h], reason: "..."}]`、`pairing_rule: "..."`。这些是消费约束,不参与封闭枚举;用于避免标题、正文、图表、卡片、表格、时间线及其容器外接矩形覆盖背景视觉主体、强光斑或深色透明区;透明容器也不能跨进禁放区。
136
- - **流式页型**:内容长度会变化的内容页可用 `flow.regions` 表达纵向区带。`stack` 表达单列顺序,`grid` 表达并列列组,`free` 中的 item 必须带 `box`,用于 logo、页码、页眉和页脚等固定锚点。并列卡片可在 `grid.items` 中使用一层 `{role: group, css, gap, items}`:group 的 `css` 是卡片容器样式,内部 `items` 按顺序排布;不继续嵌套 group。纵向位置与留白由消费模型结合实际内容决定,不把样张的 `y` 坐标当作流式硬约束。
136
+ - **流式页型**:内容长度会变化的内容页可用 `flow.regions` 表达纵向区带。`stack` 表达单列顺序,`grid` 表达并列列组,`free` 中的 item 必须带 `box`,用于 logo、页码、页眉和页脚等固定锚点。并列卡片可在 `grid.items` 中使用一层 `{role: group, css, gap, items}`:group 的 `css` 是卡片容器样式,内部 `items` 按顺序排布;不继续嵌套 group。区带可带自己的 `margin: [左, 右]`,覆盖 `flow` 整块的 `margin`(居中卡片组和贴左标题横向范围本就不同);不带则继承整块 `margin`。纵向位置与留白由消费模型结合实际内容决定,不把样张的 `y` 坐标当作流式硬约束。
137
137
  - **`decor`(可选)**:这一页无文字的图形骨架——图标托底的圆、卡片、分隔线。每条 `{box, geom, css}`:`box` 定位,`css` 是可直接写进 style 的声明串,`geom` 取源形状的 prst(`ellipse` 另加 `border-radius: 50%`)。圆角以每条 `css` 为准,没有 `border-radius` 就按 `0`;不得因 `geom: roundRect` 自行补圆角,因为 OOXML 的 roundRect 可以有零圆角调节点。层级在背景之上、`slots` 之下;带 `asset` 的槽落在 decor 之上是版式本意,不算重叠。
138
138
  - **slot 样式契约**:`box` 只承载 `[x,y,w,h]` 几何;可渲染属性统一放进 `css`,并可直接写入 HTML `style`。PPTX `bodyPr.insets_px` 转成 `box-sizing: border-box; padding: ...`,字号/字重/颜色/水平与垂直对齐/行高/字距/旋转分别转成标准 CSS。禁止在 slot 中输出 `size` / `weight` / `color` / `align` / `valign` / `insets_px` 等旧字段。
139
139
  - **文本角色判断**:脚本把实例页及其引用版式中的现有文本槽、几何和 CSS 完整写入草案;`text_roles` 只供模型把这些槽判断为 `title | subtitle | header | footer | body`,不控制槽位去留。判断不清时用 `body`,不归纳模板中不存在的标题、页眉或页脚。
@@ -446,6 +446,7 @@ await db.select().from(users).where(eq(users.adminUser, userId));
446
446
  async submitPublic(@Body() dto) { ... }
447
447
  ```
448
448
  8. **OpenAPI 文档同步**:改动 `*.openapi.controller.ts` 或其引用的 interface / service 返回值 / schema 字段时,加载 `openapi-guide` skill,同步更新 `docs/openapi.json`
449
+ 9. **服务端查用户信息(CRITICAL)**:**必须** `import { AuthNPaasService } from '@lark-apaas/fullstack-nestjs-core'` 并用 `listUsersByIds`(`PlatformModule.forRoot()` 已注册 global 的 `AuthNPaasModule`,**不要**加 `providers`、**不要**加直接依赖)。**禁止**复用应用内已有的用户 service、裸调平台接口、从库表 join 人名头像、依赖 `req.userContext.userId`(`/openapi` 下恒为空)、`try/catch` 吞掉 SDK 抛的平台错误、用 `getBatchLarkUserIds` 判断用户是否存在(外部用户无 employeeId)、拿不到的字段用 `''` 占位。搜人 / 搜部门 / 搜群、手机号职位工号上级服务端**拿不到**,走飞书开放平台。动手前加载 `contacts-service` skill 第六节
449
450
 
450
451
  ## 异常处理
451
452
 
@@ -513,6 +514,8 @@ async createArticle(@Req() req: Request, @Body() dto: CreateArticleDto) {
513
514
  | 语音识别、音频转文字、STT | AI语音转文字 |
514
515
  | 插件实例、PluginInstance、Capability | 通用插件调用 |
515
516
 
517
+ > ⚠️ **语义检索 / 相似推荐场景例外**:若需求是对**应用自有数据**做语义检索、向量检索、相似推荐、相关推荐、按内容找相似,**不要**用上表的「AI搜索总结 / AI文本转JSON / AI智能生文」等通用插件替代,必须召回 `/semantic-search`。上表的 AI 搜索/文本插件用于公网搜索、文本生成、结构化抽取,**不具备对自有数据库的向量检索能力**。
518
+
516
519
  ### 关键区分:多维表格 vs 数据库表
517
520
 
518
521
  | 场景 | 判断 | 操作 |
@@ -615,6 +618,14 @@ import { axiosForBackend } from '@lark-apaas/client-toolkit/utils/getAxiosForBac
615
618
 
616
619
  禁止未调用 Skill 直接编写表单/图表/表格代码。
617
620
 
621
+ ### 检索 Skill 召回规则(强制执行)
622
+
623
+ | 场景 | Skill | 说明 |
624
+ |------|-------|------|
625
+ | 语义检索、向量检索、相似推荐、相关推荐、相似内容、按内容找相似、猜你喜欢 | `/semantic-search` | 对应用自有数据库的数据做向量检索 / 相似召回 |
626
+
627
+ 禁止未调用 Skill 直接用「AI搜索总结 / AI文本转JSON / AI智能生文」等通用插件实现对自有数据的语义检索。
628
+
618
629
  ### 组件使用规范
619
630
 
620
631
  - 优先使用 `client/src/components` 下已有组件(Card/Button/Badge 等)
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: contacts-service
3
- description: "Use when 搜人/选人/人员选择器/部门选择器/群组选择、获取或展示用户与部门信息、把用户/部门/群组 ID 传给飞书内置插件或飞书开放平台 API、人员字段入库或导出。统一妙搭 ID 体系(miaoda_user_id / employee_id / open_department_id / open_chat_id;lark_* 内部 ID 禁用)、字段获取分级与权限引导。触发词:搜人, 选人, 人员选择器, 部门选择器, 群组选择, UserSelect, DepartmentSelect, ChatSelect, 获取用户信息, 用户字段, 部门信息, 群组信息, employee_id, open_id, union_id, open_department_id, open_chat_id, miaoda_user_id, lark_id, 飞书用户ID, 飞书部门ID, 外部用户, 工号, 手机号, 直属上级, 人员入库, 人员导出, id_convert, 通讯录, 选负责人, 选审批人, 传插件, 传开放平台, 选中的人传给, 把选中的人"
3
+ description: "Use when 搜人/选人/人员选择器/部门选择器/群组选择、获取或展示用户与部门信息、把用户/部门/群组 ID 传给飞书内置插件或飞书开放平台 API、人员字段入库或导出,以及在产物服务端 / OpenAPI 接口里按 ID 查用户信息。统一妙搭 ID 体系(miaoda_user_id / employee_id / open_department_id / open_chat_id;lark_* 内部 ID 禁用)、字段获取分级与权限引导、服务端可用与不可用的通讯录能力边界。触发词:搜人, 选人, 人员选择器, 部门选择器, 群组选择, UserSelect, DepartmentSelect, ChatSelect, 获取用户信息, 用户字段, 部门信息, 群组信息, employee_id, open_id, union_id, open_department_id, open_chat_id, miaoda_user_id, lark_id, 飞书用户ID, 飞书部门ID, 外部用户, 工号, 手机号, 直属上级, 人员入库, 人员导出, id_convert, 通讯录, 选负责人, 选审批人, 传插件, 传开放平台, 选中的人传给, 把选中的人, 服务端查用户, 后端查用户, OpenAPI 查用户, 批量查用户, 按ID查人, AuthNPaasService, listUsersByIds"
4
4
  steering: true
5
5
  steering-topic: contacts_service
6
6
  match-template-name: nestjs-react-fullstack
@@ -10,7 +10,9 @@ match-template-name: nestjs-react-fullstack
10
10
 
11
11
  > 本 Skill 定义妙搭 Agent 处理**用户 / 部门 / 群组信息**的完整规范:ID 体系、接口返回结构、ID 选择决策、字段获取分级与权限引导。
12
12
  >
13
- > **相关 skill**:当前登录用户("我是谁"、useCurrentUserProfile、req.userContext)见 [`user-identity`](../user-identity/SKILL.md);选择器/展示组件的 props 与用法见 [`client-builtins-user-service`](../client-builtins-user-service/SKILL.md);飞书原生接口(通讯录 API、id_convert)见 [`feishu`](../../../feishu/SKILL.md)。
13
+ > **相关 skill**:当前登录用户("我是谁"、useCurrentUserProfile、req.userContext)见 [`user-identity`](../user-identity/SKILL.md);选择器/展示组件的 props 与用法见 [`client-builtins-user-service`](../client-builtins-user-service/SKILL.md);飞书原生接口(通讯录 API、id_convert)见 [`feishu`](../../../feishu/SKILL.md);对外开放接口的编码规范见 [`openapi-guide`](../openapi-guide/SKILL.md)。
14
+ >
15
+ > **⚠️ 先分流**:一~五节讲的是**浏览器里**的搜人 / 选择器口径。代码跑在**产物服务端**(NestJS service / controller,尤其 `*.openapi.controller.ts`)时,能力边界完全不同——直接看[第六节](#六服务端--openapi-态怎么查通讯录)。
14
16
 
15
17
  ## 命名约定(必读)
16
18
 
@@ -198,7 +200,68 @@ match-template-name: nestjs-react-fullstack
198
200
 
199
201
  ---
200
202
 
201
- ## 六、禁止行为
203
+ ## 六、服务端 / OpenAPI 态怎么查通讯录
204
+
205
+ ### 6.1 为什么服务端不一样
206
+
207
+ 前端靠 cookie,网关校验登录态后注入 `x-larkgw-suda-webuser`;OpenAPI 请求**没有 cookie**,`req.userContext.userId` 恒为空。所以判据很简单:**「返回什么取决于调用者是谁」的能力在 OpenAPI 态一律不可用,「给定 ID 取数据」的可用**。
208
+
209
+ ### 6.2 服务端能做什么
210
+
211
+ > **强制规则**:服务端(尤其 `/openapi`)查用户信息,**唯一允许的实现是 `AuthNPaasService.listUsersByIds`**(禁止项见 6.4.0)。`import` 不到说明 core 版本没跟上,**报告阻塞**,不要加直接依赖绕过、也不要自实现。
212
+
213
+ **按 ID 批量查人** —— 从项目统一入口 `@lark-apaas/fullstack-nestjs-core` 取 `AuthNPaasService`。`PlatformModule.forRoot()` 已注册 global 的 `AuthNPaasModule`,**不需要**在业务 module 加 `providers`,也**不需要**加直接依赖:
214
+
215
+ ```ts
216
+ import { AuthNPaasService } from '@lark-apaas/fullstack-nestjs-core';
217
+
218
+ @Injectable()
219
+ export class TicketService {
220
+ constructor(private readonly authn: AuthNPaasService) {}
221
+
222
+ async attachAssignees(ids: string[]) {
223
+ // 返回与入参等长同序,未命中的位置是 null
224
+ const users = await this.authn.listUsersByIds(ids);
225
+ return users.map((u, i) => ({
226
+ miaoda_user_id: ids[i],
227
+ name: u?.name?.zh_cn ?? u?.name?.en_us ?? '', // name 是 I18nText,不是字符串
228
+ avatar: u?.avatar?.image?.large ?? '', // 头像 URL 在 image.large 上
229
+ }));
230
+ }
231
+ }
232
+ ```
233
+
234
+ - 入参是 **miaoda_user_id**,单次最多 **100** 个;返回 `(MiaodaUserInfo | null)[]`,与入参等长同序,不丢项也不错位
235
+ - 只有 `miaodaUserID` / `name` / `avatar` 三个字段——**没有**邮箱、手机号、工号、部门
236
+ - 平台出错抛 `HttpException`(502),**不会**静默返回空数组——**不要 try/catch 吞掉**,「平台挂了」和「查无此人」必须能区分
237
+ - 服务端拿不到的字段(部门 / 邮箱 / 工号 / 职位)**从响应类型里删掉**,别用 `''` 占位骗调用方;**并告诉用户**这些字段要走飞书开放平台通讯录 API(见 6.3),不是没实现
238
+
239
+ **妙搭 ↔ 飞书 ID 转换** —— 同一个 `AuthNPaasService` 上的 `getBatchLarkUserIds()` / `getBatchMiaodaUserIds()`(双向批量,不依赖调用者身份)。**不要拿它判断用户是否存在**——外部用户本来就没有 employeeId,会被误判成「用户不存在」。判存在性用 `listUsersByIds` 的返回是不是 `null`。
240
+
241
+ ### 6.3 服务端做不到什么,改走哪里
242
+
243
+ | 想做的事 | 服务端 | 替代路径 |
244
+ |---|:---:|---|
245
+ | 按 ID 批量查人 | ✅ | `AuthNPaasService.listUsersByIds` |
246
+ | 妙搭 ↔ 飞书 ID 转换 | ✅ | `AuthNPaasService.getBatchLarkUserIds` / `getBatchMiaodaUserIds` |
247
+ | 搜人 / 搜部门 / 搜群(按关键词) | ❌ | 飞书开放平台通讯录 API(应用身份 + 显式授权的通讯录范围) |
248
+ | 取手机号 / 职位 / 工号 / 直属上级 | ❌ | 同上,字段 ↔ 权限映射见 [`feishu` › contacts.md](../../../feishu/references/contacts.md) |
249
+ | 知道「当前调用者是谁」 | ❌ | OpenAPI 语义上没有当前用户;内部 `/api` 路由才有 `req.userContext.userId` |
250
+ | 按 ID 批量查群 | ❌ | 暂无服务端能力;群信息在前端取,或走开放平台 IM API |
251
+
252
+ **为什么搜索类不给服务端**:结果取决于「谁在搜」,而 OpenAPI 没有登录用户。若平台此时按租户全量返回,外部系统就能通过产物 OpenAPI 把整个企业通讯录搜穿。开放平台那条路的可见范围由租户授权决定,语义上正好匹配。
253
+
254
+ ### 6.4 服务端禁止行为
255
+
256
+ 0. **禁止用 `AuthNPaasService.listUsersByIds` 之外的任何方式在服务端查用户信息** —— 包括:复用应用内已有的用户 / 用户资料 service、自己写 HTTP 裸调平台通讯录接口、从数据库表 join 出人名头像。这条优先级最高,与下面各条冲突时以本条为准
257
+ 1. **禁止在 `*.openapi.controller.ts` 里依赖 `req.userContext.userId`** —— OpenAPI 态恒为空
258
+ 2. **禁止用 `getCurrentUserLarkUserId()`** —— 它读 `userId`,取不到只打日志返回 `null`、**不报错**,静默失效。要飞书 ID 一律用 `getBatchLarkUserIds()`
259
+ 3. **禁止把 `name` 当字符串**渲染或入库 —— 它是 `I18nText`,直接用会得到 `[object Object]`
260
+ 4. **禁止 catch 掉 SDK 抛的平台错误当空结果** —— 「平台挂了」和「查无此人」必须区分开
261
+
262
+ ---
263
+
264
+ ## 七、禁止行为
202
265
  1. **禁用兼容字段**:任何调用不得用 lark_id / lark_department_id / lark_chat_id
203
266
  2. **禁止混用废弃名**:不得用 userID / suda_user_id / larkUserId 等旧名
204
267
  3. **禁止给飞书内置插件传 employee_id**:插件入参必须是 miaoda_user_id
@@ -208,7 +271,7 @@ match-template-name: nestjs-react-fullstack
208
271
 
209
272
  ---
210
273
 
211
- ## 七、错误处理
274
+ ## 八、错误处理
212
275
  | 错误场景 | Agent 行为 |
213
276
  |---|---|
214
277
  | 用户说"获取 user_id" | 追问:妙搭 miaoda_user_id 还是飞书 employee_id? |
@@ -4,7 +4,6 @@ description: Use when planning, adding, debugging, or reviewing NestJS cache log
4
4
  steering: true
5
5
  steering-topic: nestjs_cache
6
6
  match-template-name: nestjs-react-fullstack
7
- control-by-feature-ab: true
8
7
  ---
9
8
 
10
9
  # NestJS Caching 使用指南
@@ -17,6 +17,7 @@ file-match-pattern:
17
17
  |------|----------------------|--------------------------|
18
18
  | 鉴权 | 写操作加 `@NeedLogin()` | **不加** `@NeedLogin()`,鉴权在网关层通过 API Key 完成 |
19
19
  | 用户身份 | `req.userContext.userId` 区分用户 | 统一走系统身份,不依赖 `userId` 做业务区分 |
20
+ | 通讯录 | 前端搜人 / 选择器随便用 | **必须**用 `AuthNPaasService.listUsersByIds`(见下文「用户信息」强制规则),搜索类不可用 |
20
21
  | Controller 文件 | `xxx.controller.ts` | `xxx.openapi.controller.ts`,放在同一 module 下 |
21
22
  | OpenAPI 文档 | 不需要 | **必须**同步维护 `docs/openapi.json`(见下文) |
22
23
 
@@ -59,6 +60,80 @@ findAll(@Req() req: Request) {
59
60
  }
60
61
  ```
61
62
 
63
+ ## 用户信息(通讯录)—— 强制规则
64
+
65
+ **`/openapi` 路由下查询用户信息,唯一允许的实现是 `AuthNPaasService.listUsersByIds`。没有例外。**
66
+
67
+ ```typescript
68
+ // ✅ 唯一允许的写法。注意 import 自 fullstack-nestjs-core(项目统一入口)
69
+ import { AuthNPaasService } from '@lark-apaas/fullstack-nestjs-core';
70
+
71
+ @Controller('openapi/xxx')
72
+ export class XxxOpenApiController {
73
+ constructor(private readonly authn: AuthNPaasService) {}
74
+
75
+ @Get(':id')
76
+ async get(@Param('id') id: string) {
77
+ // 不要 try/catch 吞掉——平台故障必须暴露给调用方,别降级成「查无此人」
78
+ const [user] = await this.authn.listUsersByIds([id]);
79
+ if (!user) throw new NotFoundException(`用户 ${id} 不存在`);
80
+ return {
81
+ miaodaUserId: id,
82
+ name: user.name?.zh_cn ?? user.name?.en_us ?? '', // name 是 I18nText,不是字符串
83
+ avatar: user.avatar?.image?.large ?? '', // 头像 URL 在 image.large 上
84
+ };
85
+ }
86
+ }
87
+ ```
88
+
89
+ **不要做这两件多余的事**(`PlatformModule.forRoot()` 已经注册了 global 的 `AuthNPaasModule`):
90
+
91
+ - ❌ 在业务 module 里写 `providers: [AuthNPaasService]` —— 会另建一个实例
92
+ - ❌ 往 `package.json` 加 `@lark-apaas/nestjs-authnpaas` 直接依赖 —— 走 `fullstack-nestjs-core` 即可
93
+
94
+ ### 禁止(以下任一出现即为错误实现)
95
+
96
+ | ❌ 禁止 | 为什么 |
97
+ |---|---|
98
+ | 复用应用里已有的用户 / 用户资料 service | 那些多半是给浏览器写的,依赖登录态;`/openapi` 下没有登录用户,会静默返回空 |
99
+ | 自己写 HTTP 请求裸调平台通讯录接口 | 鉴权 / 重试 / 日志 / trace 都在 SDK 里,裸调必然漏 |
100
+ | 用 `req.userContext.userId` 做用户查询 | `/openapi` 下**恒为空** |
101
+ | 用 `AuthNPaasService.getCurrentUserLarkUserId()` | 它读 `userId`,取不到只打日志返回 `null`、**不报错**,故障静默 |
102
+ | 从数据库表里 join 出人名 / 头像 | 通讯录不是应用数据,会过期且不 follow 权限 |
103
+ | 按关键词搜人 / 搜部门 / 搜群 | 结果取决于「谁在搜」,`/openapi` 下没有调用者视角,**服务端不提供** |
104
+ | `try/catch` 吞掉 `listUsersByIds` 抛的错、返回空值 | 「平台挂了」和「查无此人」是两回事,吞掉就没人知道故障 |
105
+ | 用 `getBatchLarkUserIds` 判断用户是否存在 | 它是 ID 转换,**外部用户本来就没有 employeeId**,会把外部用户误判成不存在 |
106
+ | 服务端拿不到的字段用 `''` 占位塞进响应 | 调用方会以为字段存在只是没值。拿不到就**从响应类型里删掉**,并告诉用户改走飞书开放平台通讯录 API |
107
+
108
+ ```typescript
109
+ // ❌ 错误:包了一层应用现有的用户服务
110
+ const profile = await this.userProfileService.findById(id);
111
+
112
+ // ❌ 错误:OpenAPI 态搜不了人
113
+ const users = await someSearchApi({ query: keyword });
114
+
115
+ // ❌ 错误:读 userId,OpenAPI 态恒为空且失败不报错
116
+ const larkId = await this.authn.getCurrentUserLarkUserId();
117
+
118
+ // ❌ 错误:吞掉平台故障 + 拿不到的字段用空串占位
119
+ let name = '';
120
+ try {
121
+ const [u] = await this.authn.listUsersByIds([id]);
122
+ name = u?.name?.zh_cn ?? '';
123
+ } catch { /* 平台挂了也当查无此人 */ }
124
+ return { userId: id, name, department: '', email: '', jobTitle: '' };
125
+ ```
126
+
127
+ ### `AuthNPaasService` import 不到时
128
+
129
+ 说明当前 `@lark-apaas/fullstack-nestjs-core` 版本还没带上这个能力。**报告阻塞、请人升级 core 版本**——不要加 `@lark-apaas/nestjs-authnpaas` 直接依赖绕过去,也不要退回上面任何一种禁止写法或自己实现替代品。
130
+
131
+ ### 服务端拿不到的字段
132
+
133
+ 手机号 / 职位 / 工号 / 直属上级 / 在职状态、以及按 ID 查群 —— 服务端**没有**这些能力。需要就走飞书开放平台通讯录 API,或把该能力放回前端做,**不要**在 `/openapi` 里自己拼一个。
134
+
135
+ 完整能力边界与字段口径见 [`contacts-service` › 第六节](../contacts-service/SKILL.md)。
136
+
62
137
  ## 模块组织
63
138
 
64
139
  `/openapi` Controller 和 `/api` Controller 放在**同一个 module** 下,共享 Service 层。用文件名 `xxx.openapi.controller.ts` 区分。