@hupan56/wlkj 3.3.0 → 3.3.1

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 (32) hide show
  1. package/package.json +2 -2
  2. package/templates/.qoder/.runtime/hook-errors.log +4 -0
  3. package/templates/qoder/commands/optional/wl-status.md +2 -0
  4. package/templates/qoder/commands/wl-code.md +45 -10
  5. package/templates/qoder/commands/wl-init.md +129 -129
  6. package/templates/qoder/commands/wl-prd.md +27 -12
  7. package/templates/qoder/commands/wl-search.md +32 -0
  8. package/templates/qoder/commands/wl-task.md +8 -4
  9. package/templates/qoder/commands/wl-test.md +4 -0
  10. package/templates/qoder/hooks/post-tool-use.py +31 -1
  11. package/templates/qoder/hooks/pre-tool-use.py +136 -0
  12. package/templates/qoder/hooks/session-start.py +365 -365
  13. package/templates/qoder/scripts/capability/__pycache__/present_html.cpython-39.pyc +0 -0
  14. package/templates/qoder/scripts/capability/__pycache__/registry.cpython-39.pyc +0 -0
  15. package/templates/qoder/scripts/capability/caps/__init__.py +4 -4
  16. package/templates/qoder/scripts/capability/caps/__pycache__/__init__.cpython-39.pyc +0 -0
  17. package/templates/qoder/scripts/capability/caps/__pycache__/notify.cpython-39.pyc +0 -0
  18. package/templates/qoder/scripts/capability/caps/__pycache__/sandbox.cpython-39.pyc +0 -0
  19. package/templates/qoder/scripts/capability/caps/notify.py +64 -0
  20. package/templates/qoder/scripts/capability/caps/sandbox.py +38 -0
  21. package/templates/qoder/scripts/capability/present_html.py +68 -0
  22. package/templates/qoder/scripts/capability/registry.py +6 -2
  23. package/templates/qoder/scripts/capability/registry_mcp.py +4 -6
  24. package/templates/qoder/scripts/domain/integration/__pycache__/return_to_platform.cpython-39.pyc +0 -0
  25. package/templates/qoder/scripts/domain/integration/return_to_platform.py +9 -6
  26. package/templates/qoder/scripts/domain/integration/spec_upload.py +1 -2
  27. package/templates/qoder/scripts/domain/kg/switch_project.py +5 -6
  28. package/templates/qoder/scripts/engine/poller.py +1 -1
  29. package/templates/qoder/scripts/validation/metrics/__pycache__/present_board.cpython-39.pyc +0 -0
  30. package/templates/qoder/scripts/validation/metrics/present_board.py +180 -0
  31. package/templates/qoder/settings.json +10 -0
  32. package/templates/qoder/scripts/domain/kg/extract/extract.py.bak +0 -430
@@ -1,430 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Shared extraction utilities for the QODER knowledge graph.
4
-
5
- Centralizes regex-based extraction that was previously copy-pasted across
6
- build_style_index.py and git_sync.py. The headline feature is the **call-chain
7
- extractor**: given a project's source tree, it builds a table mapping each
8
- clickable UI element (button @click + label) to the backend API endpoint it
9
- triggers, so test automation and impact analysis can answer:
10
-
11
- - "点击'新增'按钮会调哪个接口?" (test automation / QoderWork)
12
- - "改这个接口会影响哪些页面/按钮?" (dev impact analysis)
13
-
14
- Two passes:
15
- 1. ``build_api_fn_table`` — scan ``src/api/**/*.ts``, parse ``enum Api``
16
- + ``export function`` → {fnName: {url, verb, file}}. ~100% reliable.
17
- 2. ``trace_clicks`` — scan ``src/views/**/*.vue``, resolve each
18
- ``@click="handleX"`` to an api function via 4 patterns (direct / drawer
19
- onConfirm / Modal.confirm onOk / router.push deferred).
20
-
21
- Confidence is tagged per edge (high/medium/low/deferred) so consumers know
22
- which traces are statically certain vs need runtime confirmation.
23
- """
24
- import os
25
- import re
26
-
27
-
28
- # ── Reusable extraction regexes (previously duplicated) ──────────────
29
-
30
- # Table column: title + field (VxeGrid/Vben schema). Used by build_style_index.
31
- RE_TABLE_COL_TF = re.compile(
32
- r"title:\s*['\"]([^'\"]+)['\"]\s*,\s*field:\s*['\"]([^'\"]+)['\"]")
33
- RE_TABLE_COL_FT = re.compile(
34
- r"field:\s*['\"]([^'\"]+)['\"]\s*,\s*title:\s*['\"]([^'\"]+)['\"]")
35
-
36
- # Form field: fieldName + label
37
- RE_FORM_FIELD = re.compile(
38
- r"fieldName:\s*['\"]([^'\"]+)['\"]\s*,\s*label:\s*['\"]([^'\"]+)['\"]")
39
-
40
- # Ant Design Vue component imports
41
- RE_ANT_IMPORTS = re.compile(
42
- r"import\s+\{([^}]+)\}\s+from\s+['\"]ant-design-vue['\"]")
43
-
44
-
45
- # ── Call-chain extraction ────────────────────────────────────────────
46
-
47
- # enum Api { key = '/url', ... } — the URL constant block
48
- RE_ENUM_API = re.compile(r"enum\s+Api\s*\{([^}]*)\}", re.S)
49
- RE_ENUM_ENTRY = re.compile(r"(\w+)\s*=\s*['\"`]([^'\"`]+)['\"`]")
50
-
51
- # export function fnName(...) { return requestClient.<verb>(<urlExpr>, ...) }
52
- # urlExpr can be Api.key (symbolic) or a template literal `${Api.key}/...`
53
- # export function fnName(...) { ... }
54
- # Also matches: export const fnName = (async)? (...) => { (arrow function consts,
55
- # used for commonExport wrappers like `export const exportFactoryList = async (p) => ...`)
56
- RE_EXPORT_FN = re.compile(
57
- r"(?:export\s+(?:async\s+)?function\s+(\w+)\s*\(|"
58
- r"export\s+const\s+(\w+)\s*=\s*(?:async\s*)?\([^)]*\)\s*=>\s*\{?)", re.M)
59
- RE_REQUEST_CALL = re.compile(
60
- r"requestClient\.(\w+)(?:<[^)]*?>)?\s*\(\s*(Api\.\w+|`[^`]*`|'[^']*'|\"[^\"]*\")")
61
-
62
- # commonExport(Api.key, ...) / commonDownloadExcel(fn, ...) — wrapper that
63
- # delegates to requestClient. commonExport takes a URL; commonDownloadExcel
64
- # takes an api *function* as first arg.
65
- RE_COMMON_EXPORT = re.compile(r"commonExport\s*\(\s*(Api\.\w+)")
66
- RE_COMMON_DOWNLOAD = re.compile(r"commonDownloadExcel\s*\(\s*(\w+)")
67
-
68
- # Vue template: @click="handler" or @click.stop="handler(...)"
69
- RE_CLICK = re.compile(r"@click(?:\.\w+)?\s*=\s*['\"]([^'\"]+)['\"]")
70
-
71
- # Button text between tags (after @click line, take nearest text node)
72
- # We grab the text right after the clickable element opening tag.
73
- RE_BTN_TEXT_AFTER_CLICK = re.compile(
74
- r"@click(?:\.\w+)?\s*=\s*['\"][^'\"]*['\"][^>]*>\s*([^\n<]{1,20})", re.S)
75
-
76
- # import { fn1, fn2 } from '#/api/...' — api imports in a Vue SFC
77
- RE_API_IMPORT = re.compile(
78
- r"import\s+\{([^}]+)\}\s+from\s+['\"](?:#|@)/(?:api|@/api)/([^'\"]+)['\"]")
79
-
80
- # connectedComponent: localImport (drawer/modal wiring)
81
- RE_CONNECTED_COMP = re.compile(r"connectedComponent:\s*(\w+)")
82
-
83
- # import localName from './xxx.vue' (local default import for drawer)
84
- RE_LOCAL_VUE_IMPORT = re.compile(
85
- r"import\s+(\w+)\s+from\s+['\"]([^'\"]+\.vue)['\"]")
86
-
87
- # function handlerName(...) { ... } — capture full function body (greedy to next function/export/</script)
88
- RE_FN_BODY = re.compile(
89
- r"(?:async\s+)?function\s+(\w+)\s*\([^)]*\)\s*\{", re.M)
90
-
91
- # modalApi.open() / drawerApi.open() — drawer trigger
92
- RE_DRAWER_OPEN = re.compile(r"(\w*[Aa]pi)\??\.open\s*\(\s*\)")
93
-
94
- # Modal.confirm({ onOk: ... }) — delete confirmation
95
- RE_MODAL_CONFIRM = re.compile(r"Modal\.confirm\s*\(\s*\{", re.S)
96
-
97
- # useVbenDrawer({ connectedComponent: X }) — drawer declaration
98
- RE_USE_DRAWER = re.compile(
99
- r"useVbenDrawer\s*\(\s*\{[^}]*connectedComponent:\s*(\w+)", re.S)
100
-
101
- # router.push({ path: '...' })
102
- RE_ROUTER_PUSH = re.compile(r"router\.push\s*\(")
103
-
104
- # Pattern G: proxyConfig.ajax.query 函数 — ICS VxeGrid 表格数据加载入口
105
- # 真实写法 (审核 601 个文件确认):
106
- # proxyConfig: { ajax: { query: async ({page}, formValues) => {
107
- # return await getUnconventionalDetailList({...}) ← 导入的 api 函数
108
- # }}}
109
- # 这不是 proxyConfig.ajax({url}) 内联 url, 而是在 query 函数体里调用已导入的 api 函数。
110
- # 提取 query 函数体, 交给 _find_api_calls_in_text 匹配。
111
- RE_PROXY_AJAX = re.compile(
112
- r"proxyConfig\s*:\s*\{\s*ajax\s*:\s*\{\s*"
113
- r"(?:query|queryAll|queryPage)\s*:\s*async\s*\(", re.S)
114
-
115
-
116
- def parse_api_enum_block(content):
117
- """Extract {enumKey: '/url'} from an ``enum Api { ... }`` block.
118
-
119
- Handles enum values containing template literals with ${VAR} — the nested
120
- braces would break a naive [^}]* regex, so we use brace-depth matching.
121
- """
122
- urls = {}
123
- # Find "enum Api {" then manually match braces to find the closing }
124
- for m in re.finditer(r'enum\s+Api\s*\{', content):
125
- start = m.end()
126
- depth = 1
127
- i = start
128
- while i < len(content) and depth > 0:
129
- if content[i] == '{':
130
- depth += 1
131
- elif content[i] == '}':
132
- depth -= 1
133
- i += 1
134
- block = content[start:i-1] if depth == 0 else content[start:]
135
- for em in RE_ENUM_ENTRY.finditer(block):
136
- urls[em.group(1)] = em.group(2)
137
- return urls
138
-
139
-
140
- def build_api_fn_table(api_dir):
141
- """Scan ``src/api/**/*.ts`` and build {fnName: {url, verb, file}}.
142
-
143
- Resolves symbolic ``Api.key`` references via the file's ``enum Api`` block.
144
- Handles ``commonExport(Api.key)`` wrappers. Returns dict + the enum map
145
- per file (for cross-file resolution).
146
- """
147
- table = {}
148
- if not api_dir or not os.path.isdir(api_dir):
149
- return table
150
-
151
- for root, dirs, files in os.walk(api_dir):
152
- dirs[:] = [d for d in dirs if d not in ('node_modules', 'dist', '__pycache__')]
153
- for f in files:
154
- if not f.endswith('.ts'):
155
- continue
156
- fpath = os.path.join(root, f)
157
- try:
158
- content = open(fpath, encoding='utf-8', errors='ignore').read()
159
- except Exception:
160
- continue
161
- urls = parse_api_enum_block(content)
162
-
163
- # For each exported function, find requestClient call inside its
164
- # EXACT body (brace-matched, not a fixed-length snippet — a snippet
165
- # would bleed into the next function and mis-resolve the Api key).
166
- for fm in RE_EXPORT_FN.finditer(content):
167
- fn_name = fm.group(1) or fm.group(2) # function name or const name
168
- if not fn_name:
169
- continue
170
- body = _get_fn_body(content, fn_name, max_len=500)
171
- if not body:
172
- continue
173
- entry = None
174
- # Direct requestClient.<verb>(Api.key or 'literal')
175
- rm = RE_REQUEST_CALL.search(body)
176
- if rm:
177
- verb = rm.group(1)
178
- url_expr = rm.group(2)
179
- url = _resolve_url_expr(url_expr, urls)
180
- if url:
181
- entry = {'url': url, 'verb': verb, 'file': fpath.replace('\\', '/')}
182
- # commonExport(Api.key) wrapper
183
- if not entry:
184
- cm = RE_COMMON_EXPORT.search(body)
185
- if cm:
186
- url = _resolve_url_expr(cm.group(1), urls)
187
- if url:
188
- entry = {'url': url, 'verb': 'post', 'file': fpath.replace('\\', '/')}
189
- if entry:
190
- table[fn_name] = entry
191
- return table
192
-
193
-
194
- def _resolve_url_expr(expr, urls):
195
- """Resolve ``Api.key`` or template literal to a concrete URL string."""
196
- expr = expr.strip()
197
- if expr.startswith('Api.'):
198
- key = expr[4:]
199
- return urls.get(key)
200
- # Template literal `${Api.key}/xxx` or plain string
201
- if expr.startswith('`') or expr.startswith("'") or expr.startswith('"'):
202
- inner = expr.strip('`\'"')
203
- # Replace ${Api.key} placeholders
204
- def repl(m):
205
- return urls.get(m.group(1), m.group(0))
206
- inner = re.sub(r"\$\{Api\.(\w+)\}", repl, inner)
207
- # If still has Api. references, try direct
208
- inner = re.sub(r"Api\.(\w+)", lambda m: urls.get(m.group(1), m.group(0)), inner)
209
- return inner if '/' in inner else None
210
- return None
211
-
212
-
213
- def _get_fn_body(content, fn_name, max_len=800):
214
- """Get the body text of a named function (best-effort, ~max_len chars).
215
-
216
- Handles both ``function fnName() {`` and ``const fnName = () => {`` forms.
217
- """
218
- # Try: function fnName( OR const fnName = (async) (...) => {
219
- for pat in [
220
- re.compile(r"(?:async\s+)?function\s+" + re.escape(fn_name) + r"\s*\([^)]*\)\s*\{"),
221
- re.compile(r"const\s+" + re.escape(fn_name) + r"\s*=\s*(?:async\s*)?\([^)]*\)\s*=>\s*\{?"),
222
- ]:
223
- m = pat.search(content)
224
- if m:
225
- break
226
- else:
227
- return ''
228
- start = m.end()
229
- # If arrow fn without explicit {, grab the expression line instead
230
- if '=>' in m.group(0) and '{' not in m.group(0):
231
- return content[start:start + max_len]
232
- # Simple brace matching
233
- depth = 1
234
- i = start
235
- end = min(len(content), start + max_len)
236
- while i < end and depth > 0:
237
- if content[i] == '{':
238
- depth += 1
239
- elif content[i] == '}':
240
- depth -= 1
241
- i += 1
242
- return content[start:i]
243
-
244
-
245
- def _find_api_calls_in_text(text, api_table, api_imports):
246
- """Return list of (api_fn, endpoint, verb) found in a text snippet."""
247
- hits = []
248
- for fn in api_imports:
249
- if fn in api_table and re.search(r'\b' + re.escape(fn) + r'\b', text):
250
- info = api_table[fn]
251
- hits.append((fn, info['url'], info.get('verb', '?')))
252
- # commonDownloadExcel(fnName, ...) — first arg is an api function
253
- for dm in RE_COMMON_DOWNLOAD.finditer(text):
254
- fn = dm.group(1)
255
- if fn in api_table:
256
- info = api_table[fn]
257
- hits.append((fn, info['url'], info.get('verb', '?')))
258
- return hits
259
-
260
-
261
- def _resolve_drawer_api(content, drawer_var):
262
- """Given a drawer/modal api var name, find its connectedComponent import path."""
263
- # useVbenDrawer({ connectedComponent: CompName }) declared as [CompName, drawerVar]
264
- # Pattern: const [CompName, drawerVar] = useVbenDrawer({ connectedComponent: compImport })
265
- pat = re.compile(
266
- r"const\s+\[\s*(\w+)\s*,\s*" + re.escape(drawer_var) + r"\s*\]\s*=\s*useVbenDrawer",
267
- re.S)
268
- m = pat.search(content)
269
- if not m:
270
- # Fallback: find connectedComponent near the drawer var
271
- for cm in RE_CONNECTED_COMP.finditer(content):
272
- comp = cm.group(1)
273
- # Verify this comp's drawer var matches by proximity (within 200 chars)
274
- if drawer_var in content[max(0, cm.start()-200):cm.start()+200]:
275
- m = type('x', (), {'group': lambda self, i: comp})()
276
- break
277
- if not m:
278
- return None
279
- comp_name = m.group(1) if hasattr(m, 'group') else None
280
- if not comp_name:
281
- return None
282
- # Find import localName from './xxx.vue' matching comp_name
283
- for im in RE_LOCAL_VUE_IMPORT.finditer(content):
284
- if im.group(1) == comp_name:
285
- return im.group(2)
286
- return None
287
-
288
-
289
- def trace_clicks(vue_path, vue_content, api_table):
290
- """Extract click→api traces from a single Vue SFC.
291
-
292
- Returns list of trace dicts:
293
- {vue_file, button, handler, api_fn, endpoint, verb, confidence}
294
- confidence: 'high' (direct), 'medium' (drawer 1-hop), 'low' (modal confirm),
295
- 'deferred' (router.push).
296
- """
297
- traces = []
298
- dirname = os.path.dirname(vue_path)
299
-
300
- # 1. Collect api imports in this SFC
301
- api_imports = set()
302
- for im in RE_API_IMPORT.finditer(vue_content):
303
- for name in im.group(1).split(','):
304
- name = name.strip().split(' as ')[0].strip()
305
- if name and name in api_table:
306
- api_imports.add(name)
307
-
308
- # 2. Find all @click handlers + nearest button text
309
- clicks = list(RE_CLICK.finditer(vue_content))
310
- if not clicks:
311
- return traces
312
-
313
- # Build drawer map: drawerVar → connected component .vue path.
314
- # Pattern: const [Comp, drawerVar] = useVbenDrawer({ connectedComponent: compImport })
315
- # Note: Comp name may differ from compImport (e.g. [FactoryModal, modalApi] with
316
- # connectedComponent: factoryModal). So we link drawerVar → compImport → import path.
317
- drawer_map = {}
318
- # Find all useVbenDrawer declarations and capture the drawer var + connectedComponent
319
- for dm in re.finditer(
320
- r"const\s+\[\s*\w+\s*,\s*(\w+)\s*\]\s*=\s*useVbenDrawer\s*\(\s*\{([^}]*)\}",
321
- vue_content, re.S):
322
- drawer_var = dm.group(1)
323
- decl_body = dm.group(2)
324
- cm = re.search(r"connectedComponent:\s*(\w+)", decl_body)
325
- if not cm:
326
- continue
327
- comp_import_name = cm.group(1)
328
- # Resolve comp_import_name → './xxx.vue' via local imports
329
- for im in RE_LOCAL_VUE_IMPORT.finditer(vue_content):
330
- if im.group(1) == comp_import_name:
331
- drawer_map[drawer_var] = im.group(2)
332
- break
333
-
334
- # 3. For each click, resolve to api
335
- for i, cm in enumerate(clicks):
336
- handler_expr = cm.group(1).strip()
337
- # Button text: text right after the element, or previous text node
338
- btn_text = ''
339
- tm = RE_BTN_TEXT_AFTER_CLICK.search(vue_content, cm.start())
340
- if tm:
341
- btn_text = tm.group(1).strip()[:12]
342
- # Strip Vue interpolation {{ }} from button text (e.g. "{{ item.name }}")
343
- btn_text = re.sub(r'\{\{[^}]*\}\}', '', btn_text).strip()[:12]
344
-
345
- # Skip inline expressions that aren't function calls:
346
- # $emit, item.remove(), splice, push — pure frontend, no API
347
- if handler_expr.startswith('$') or '.splice(' in handler_expr or '.push(' in handler_expr:
348
- continue
349
-
350
- # Get handler function name (strip args/calls)
351
- handler_name = handler_expr.split('(')[0].split('.')[0].strip()
352
- if not handler_name or handler_name in ('undefined', '', 'true', 'false'):
353
- continue
354
- # Skip single-word inline handlers (add, remove, item, emit) that are
355
- # likely data/methods shorthand, not named handler functions
356
- if handler_name in ('item', 'emit', 'row', 'data') and '.' not in handler_expr:
357
- continue
358
-
359
- fn_body = _get_fn_body(vue_content, handler_name)
360
-
361
- trace = {
362
- 'vue_file': vue_path.replace('\\', '/'),
363
- 'button': btn_text,
364
- 'handler': handler_name,
365
- 'api_fn': None, 'endpoint': None, 'verb': None,
366
- 'confidence': None,
367
- }
368
-
369
- # Pattern B: direct api call in handler body
370
- hits = _find_api_calls_in_text(fn_body, api_table, api_imports)
371
- if hits:
372
- fn, url, verb = hits[0]
373
- trace.update(api_fn=fn, endpoint=url, verb=verb, confidence='high')
374
- traces.append(trace)
375
- continue
376
-
377
- # Pattern D: drawer/modal open → resolve connected component
378
- open_m = RE_DRAWER_OPEN.search(fn_body)
379
- if open_m:
380
- drawer_var = open_m.group(1)
381
- comp_rel = drawer_map.get(drawer_var)
382
- if comp_rel:
383
- comp_path = os.path.normpath(os.path.join(dirname, comp_rel))
384
- if os.path.isfile(comp_path):
385
- try:
386
- comp_content = open(comp_path, encoding='utf-8', errors='ignore').read()
387
- comp_api_imports = set()
388
- for im in RE_API_IMPORT.finditer(comp_content):
389
- for name in im.group(1).split(','):
390
- name = name.strip().split(' as ')[0].strip()
391
- if name in api_table:
392
- comp_api_imports.add(name)
393
- # Find onConfirm/handleConfirm body in the component
394
- for confirm_name in ('handleConfirm', 'onConfirm', 'handleSubmit', 'onOk'):
395
- cbody = _get_fn_body(comp_content, confirm_name)
396
- if cbody:
397
- chits = _find_api_calls_in_text(cbody, api_table, comp_api_imports)
398
- if chits:
399
- fn, url, verb = chits[0]
400
- trace.update(api_fn=fn, endpoint=url, verb=verb,
401
- confidence='medium')
402
- break
403
- except Exception:
404
- pass
405
- if trace['endpoint']:
406
- traces.append(trace)
407
- continue
408
-
409
- # Modal.confirm({ onOk }) pattern
410
- mc_m = RE_MODAL_CONFIRM.search(fn_body)
411
- if mc_m:
412
- onok_body = fn_body[mc_m.end():]
413
- hits = _find_api_calls_in_text(onok_body[:400], api_table, api_imports)
414
- if hits:
415
- fn, url, verb = hits[0]
416
- trace.update(api_fn=fn, endpoint=url, verb=verb, confidence='low')
417
- traces.append(trace)
418
- continue
419
-
420
- # router.push — deferred
421
- if RE_ROUTER_PUSH.search(fn_body):
422
- trace['confidence'] = 'deferred'
423
- traces.append(trace)
424
- continue
425
-
426
- # Unresolved — record as low confidence (handler exists but no api found)
427
- trace['confidence'] = 'unresolved'
428
- traces.append(trace)
429
-
430
- return traces