mtkit 1.16.1__py3-none-any.whl

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.
mtkit/cli.py ADDED
@@ -0,0 +1,885 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ CLI entry: mtkit gen / gen-doc / facts / diff / validate / info / tree
4
+
5
+ Usage:
6
+ mtkit gen -i cases.json -o out.xmind
7
+ mtkit gen -i cases.py --module TREE -o out.xmind --root "Title"
8
+ mtkit gen -i cases.md -o out.xmind --type 功能测试
9
+ mtkit gen -i cases.json -o out.xmind --format tb # TB(Teambition) hierarchy format
10
+ mtkit gen-doc -i 方案.docx --hist 历史.xmind -o out.xmind
11
+ mtkit gen-doc -i 方案.docx --llm http --endpoint URL --model xxx -o out.xmind
12
+ mtkit facts -r repo -o facts.json
13
+ mtkit diff -i out.xmind -f facts.json -d 方案.docx
14
+ mtkit validate -i out.xmind [--format zen|tb]
15
+ mtkit info -i out.xmind
16
+ mtkit tree -i out.xmind -o tree.json
17
+ """
18
+ import argparse
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ from . import __version__
24
+ from .builder import build_sheet, count_cases, count_nodes
25
+ from .coverage import build_report, compare_features, compare_interfaces, coverage_map
26
+ from .db import build_provider, load_db_config, verify_contract_sqls
27
+ from .conf import load_config
28
+ from .review import render_report, review_contract
29
+ from .audit import audit_xmind, render_audit_report
30
+ from .asset import facts_digest, stale_assets, write_meta
31
+ from .selfheal import capture_failure
32
+ from .evolve import backup_files, list_backups, prune_backups, restore_file
33
+ from .track import (
34
+ add_bug,
35
+ asset_execution,
36
+ build_report as build_track_report,
37
+ build_trend,
38
+ close_bug,
39
+ defect_summary,
40
+ list_bugs,
41
+ record_execution,
42
+ render_report as render_track_report,
43
+ render_trend as render_track_trend,
44
+ )
45
+ from .extract.code_facts import (
46
+ count_facts,
47
+ dump_facts,
48
+ load_facts,
49
+ scan_frontend,
50
+ scan_repo,
51
+ )
52
+ from .extract.docx_loader import load_docx
53
+ from .extract.xmind_loader import (
54
+ extract_style_sample,
55
+ load_xmind_tree,
56
+ parse_replace_map,
57
+ skeleton_from_hist,
58
+ )
59
+ from .generate.llm import (
60
+ CliLlmProvider,
61
+ HttpLlmProvider,
62
+ generate_cases_with_llm,
63
+ tree_to_contract,
64
+ )
65
+ from .generate.skeleton import build_skeleton
66
+ from .normalize import (
67
+ detect_style,
68
+ normalize_tree,
69
+ split_preconditions_tree,
70
+ to_history,
71
+ to_zen,
72
+ )
73
+ from .parsers import DEFAULT_MODULE_VAR, parse_input
74
+ from .tb import check_tb_tree, count_tb_cases, to_tb_tree
75
+ from .validator import check_tree, check_xmind_file
76
+ from .writer import read_tree, write_xmind
77
+
78
+
79
+ def cmd_gen(args):
80
+ """Generate xmind: parse input -> normalize -> validate case tree -> build sheet -> package & write"""
81
+ conf = load_config()
82
+ if args.style is None:
83
+ args.style = conf["style"]
84
+ root_title, tree = parse_input(
85
+ args.input,
86
+ module_var=args.module,
87
+ root_title=args.root,
88
+ case_type=args.type,
89
+ )
90
+ # normalize: tolerate dict tree / tuple tree / string leaf mixed input
91
+ tree = normalize_tree(tree)
92
+
93
+ style = args.style
94
+ if style == "auto":
95
+ style = detect_style(tree)
96
+ if style == "mixed":
97
+ style = "zen"
98
+ elif style == "history" and detect_style(tree) == "zen":
99
+ # history output requested but input is zen flat lines (e.g. contract JSON): convert to history multi-level nodes first
100
+ tree = to_history(tree)
101
+
102
+ # auto precondition split: in history style, split data-setup/precondition steps out of operation steps, fill "无" when empty
103
+ if args.auto_pc and style == "history":
104
+ tree = split_preconditions_tree(tree, fill_empty=True)
105
+
106
+ errors = check_tree(tree, style=style, require_sql=args.require_sql, require_pc=args.require_pc)
107
+ if errors and not args.no_validate:
108
+ print("用例树校验失败(风格=%s):" % style)
109
+ for msg in errors:
110
+ print(" -", msg)
111
+ sys.exit(1)
112
+ case_count = count_cases(tree)
113
+ if args.format == "tb":
114
+ # TB format: flat pc/step/expect -> hierarchy (group > case > step > expect)
115
+ if style == "history":
116
+ tree = to_zen(tree)
117
+ tree = to_tb_tree(tree, keep_extra=args.keep_extra)
118
+ tb_errors = check_tb_tree(tree)
119
+ if tb_errors and not args.no_validate:
120
+ print("TB 规则校验失败:")
121
+ for msg in tb_errors:
122
+ print(" -", msg)
123
+ sys.exit(1)
124
+ case_count = count_tb_cases(tree)
125
+ if tb_errors:
126
+ print("警告: 已跳过校验(--no-validate), 存在", len(tb_errors), "个 TB 规则问题")
127
+ payload = build_sheet(tree, root_title)
128
+ write_xmind(args.output, payload)
129
+ # asset metadata sidecar (facts hash empty: gen does not scan code)
130
+ write_meta(args.output, case_count=case_count, tool_version=__version__)
131
+ print("OK ->", args.output)
132
+ print("| 格式:", args.format, "| 风格:", style, "| 根标题:", root_title, "| 章节数:", len(tree), "| 用例总数:", case_count)
133
+ if errors:
134
+ print("警告: 已跳过校验(--no-validate), 存在", len(errors), "个结构问题")
135
+
136
+
137
+ def cmd_gen_doc(args):
138
+ """Generate cases from a design doc: extract doc facts -> skeleton or LLM -> validate -> render xmind"""
139
+ doc_facts = load_docx(args.input) if args.input.lower().endswith(".docx") else None
140
+ if doc_facts is None:
141
+ print("gen-doc 输入仅支持 .docx 技术方案文档")
142
+ sys.exit(1)
143
+
144
+ hist_tree = load_xmind_tree(args.hist) if args.hist else None
145
+ hist_sample = extract_style_sample(hist_tree, args.sample_limit) if hist_tree else ""
146
+ replace_map = parse_replace_map(args.replace_map)
147
+ code_facts = load_facts(args.facts) if args.facts else None
148
+
149
+ if args.llm and args.llm != "none":
150
+ # no facts provided: auto-scan backend repo/frontend project and inject facts into LLM
151
+ if not code_facts and (args.repo or args.front):
152
+ code_facts = scan_repo(args.repo) if args.repo else {"interfaces": [], "sqls": [], "stored_procs": []}
153
+ if args.front:
154
+ code_facts["frontend"] = scan_frontend(args.front)
155
+ # optional database access: inject real table schema metadata
156
+ if args.db:
157
+ provider = build_provider(load_db_config(args.db))
158
+ print("数据库连接:", provider.check_connection())
159
+ if not code_facts:
160
+ code_facts = {"interfaces": [], "sqls": [], "stored_procs": []}
161
+ code_facts["db_schema"] = provider.dump_schema()
162
+ print("LLM 生成模式: provider=%s, 重试=%d" % (args.llm, args.retry))
163
+ provider = _build_llm_provider(args)
164
+ tree = generate_cases_with_llm(
165
+ doc_facts, provider, hist_sample=hist_sample,
166
+ code_facts=code_facts, retry=args.retry,
167
+ )
168
+ else:
169
+ print("骨架生成模式(无 LLM):历史骨架 + 文档功能点清单")
170
+ tree = build_skeleton(doc_facts, hist_tree, replace_map=replace_map)
171
+
172
+ root_title = args.root or doc_facts.get("root") or "测试用例"
173
+ tree = normalize_tree(tree)
174
+ style = args.style
175
+ if style == "auto":
176
+ style = detect_style(tree)
177
+ elif style == "history" and detect_style(tree) == "zen":
178
+ # history output requested but input is zen flat lines (e.g. LLM contract): convert to history multi-level nodes first
179
+ tree = to_history(tree)
180
+ # auto precondition split: in history style, split data-setup/precondition steps out of operation steps, fill "无" when empty
181
+ if args.auto_pc and style == "history":
182
+ tree = split_preconditions_tree(tree, fill_empty=True)
183
+ errors = check_tree(tree, style=style, require_sql=args.require_sql, require_pc=args.require_pc)
184
+ if errors and not args.no_validate:
185
+ print("用例树校验失败(风格=%s):" % style)
186
+ for msg in errors:
187
+ print(" -", msg)
188
+ sys.exit(1)
189
+ if args.format == "tb":
190
+ if style == "history":
191
+ tree = to_zen(tree)
192
+ tree = to_tb_tree(tree, keep_extra=args.keep_extra)
193
+ payload = build_sheet(tree, root_title)
194
+ write_xmind(args.output, payload)
195
+ # asset metadata sidecar (facts hash marks the code-facts version)
196
+ facts_hash = facts_digest(code_facts) if code_facts else ""
197
+ write_meta(args.output, case_count=count_cases(tree), facts_hash=facts_hash, tool_version=__version__)
198
+ print("OK ->", args.output)
199
+ print("| 模式:", "LLM" if args.llm and args.llm != "none" else "骨架",
200
+ "| 根标题:", root_title, "| 章节数:", len(tree), "| 用例总数:", count_cases(tree))
201
+ if errors:
202
+ print("警告: 已跳过校验(--no-validate), 存在", len(errors), "个结构问题")
203
+
204
+
205
+ def _build_llm_provider(args):
206
+ """Build the LLM provider from CLI args."""
207
+ if args.llm == "http":
208
+ if not args.endpoint:
209
+ print("--llm http 需要 --endpoint(OpenAI 兼容接口地址)")
210
+ sys.exit(1)
211
+ api_key = args.api_key or os.environ.get("MTKIT_LLM_API_KEY", "")
212
+ return HttpLlmProvider(args.endpoint, api_key=api_key, model=args.model)
213
+ if args.llm == "cli":
214
+ cmd = args.cli_cmd or os.environ.get("MTKIT_LLM_CMD", "")
215
+ return CliLlmProvider(cmd)
216
+ print("不支持的 --llm 取值: %s(支持 http/cli)" % args.llm)
217
+ sys.exit(1)
218
+
219
+
220
+ def cmd_gather(args):
221
+ """One-shot extraction of generation context: design .docx + historical xmind + backend/frontend code -> context.json.
222
+
223
+ context.json lets Qoder/LLM produce the case contract directly, rendered later by
224
+ `mtkit gen`, avoiding hand-written case data py scripts.
225
+ """
226
+ doc_facts = load_docx(args.input) if args.input.lower().endswith(".docx") else None
227
+ if doc_facts is None:
228
+ print("gather 输入仅支持 .docx 技术方案文档")
229
+ sys.exit(1)
230
+
231
+ hist_tree = load_xmind_tree(args.hist) if args.hist else None
232
+ hist_sample = extract_style_sample(hist_tree, args.sample_limit) if hist_tree else ""
233
+ replace_map = parse_replace_map(args.replace_map)
234
+ hist_skeleton = skeleton_from_hist(hist_tree, replace_map) if hist_tree else []
235
+
236
+ code_facts = scan_repo(args.repo) if args.repo else {"interfaces": [], "sqls": [], "stored_procs": []}
237
+ if args.front:
238
+ code_facts["frontend"] = scan_frontend(args.front)
239
+ if args.db:
240
+ provider = build_provider(load_db_config(args.db))
241
+ print("数据库连接:", provider.check_connection())
242
+ code_facts["db_schema"] = provider.dump_schema()
243
+
244
+ from .generate.prompts import SYSTEM_PROMPT, build_chunk_prompt, facts_to_text
245
+
246
+ doc_text = facts_to_text(doc_facts)
247
+ code_text = facts_to_text(code_facts)
248
+ prompt = build_chunk_prompt("全文", doc_text, hist_sample, code_text)
249
+
250
+ context = {
251
+ "task": "根据技术方案生成集成测试用例(契约格式,供 mtkit gen 渲染)",
252
+ "prompt": prompt,
253
+ "doc_facts": doc_facts,
254
+ "hist_sample": hist_sample,
255
+ "hist_skeleton": hist_skeleton,
256
+ "code_facts": code_facts,
257
+ "replace_map": replace_map,
258
+ }
259
+ dump_facts(context, args.output)
260
+ summary = count_facts(code_facts)
261
+ print("OK ->", args.output)
262
+ print("| 章节:", len(doc_facts.get("sections") or []), "| 接口:", summary["interfaces"],
263
+ "| SQL:", summary["sqls"], "| 存储过程:", summary["stored_procs"],
264
+ "| 前端页面:", len((code_facts.get("frontend") or {}).get("pages") or []))
265
+ print("提示: 将 context.json 交给 Qoder 生成用例契约,再执行:")
266
+ print(' mtkit gen -i 契约.json -o 用例.xmind --style history --auto-pc --require-pc --require-sql')
267
+
268
+
269
+ def cmd_contract(args):
270
+ """xmind case tree <-> contract JSON conversion (iterate legacy cases)."""
271
+ if args.reverse:
272
+ # contract JSON -> xmind case tree JSON (for inspection)
273
+ contract = load_facts(args.input)
274
+ from .generate.llm import contract_to_tree
275
+
276
+ tree = contract_to_tree(contract)
277
+ dump_facts(tree, args.output)
278
+ print("OK ->", args.output, "| 章节数:", len(tree))
279
+ return
280
+ tree = read_tree(args.input)
281
+ contract = tree_to_contract(tree)
282
+ dump_facts(contract, args.output)
283
+ print("OK ->", args.output, "| 章节数:", len(contract.get("chapters") or []))
284
+
285
+
286
+ def cmd_db(args):
287
+ """Database access (strictly readonly): check connectivity / schema snapshot / verify contract SQL."""
288
+ conf = load_config()
289
+ config_path = args.config or conf["db"]
290
+ if not config_path:
291
+ print("缺少数据库配置:请提供 -c db.json 或项目根 .mtkit.json 的 db 字段")
292
+ sys.exit(1)
293
+ config = load_db_config(config_path)
294
+ provider = build_provider(config)
295
+ if args.action == "check":
296
+ print("连接测试:", provider.check_connection())
297
+ print("表数量:", len(provider.list_tables()))
298
+ return
299
+ if args.action == "schema":
300
+ schema = provider.dump_schema()
301
+ with open(args.output, "w", encoding="utf-8") as fp:
302
+ json.dump(schema, fp, ensure_ascii=False, indent=2)
303
+ print("OK ->", args.output, "| 表数量:", len(schema.get("tables") or []))
304
+ return
305
+ if args.action == "verify":
306
+ with open(args.input, "r", encoding="utf-8-sig") as fp:
307
+ contract = json.load(fp)
308
+ # multi-database routing: -c accepts comma-separated db.json files
309
+ config_paths = [p.strip() for p in config_path.split(",") if p.strip()]
310
+ providers = [build_provider(load_db_config(p)) for p in config_paths]
311
+ results = verify_contract_sqls(providers, contract)
312
+ ok_count = sum(1 for r in results if r["status"] == "ok")
313
+ rejected = [r for r in results if r["status"] == "rejected"]
314
+ failed = [r for r in results if r["status"] == "fail"]
315
+ lines = ["SQL 校验结果: 通过 %d / 拒绝 %d / 失败 %d" % (ok_count, len(rejected), len(failed))]
316
+ for r in rejected:
317
+ lines.append(" - [拒绝] %s | %s" % (r["sql"][:80], r["error"]))
318
+ for r in failed:
319
+ lines.append(" - [失败] %s | %s | 用例: %s" % (r["sql"][:80], r["error"], r["case"]))
320
+ report = "\n".join(lines)
321
+ print(report)
322
+ if args.output:
323
+ with open(args.output, "w", encoding="utf-8") as fp:
324
+ fp.write(report + "\n")
325
+ print("报告已写入 ->", args.output)
326
+ if failed:
327
+ sys.exit(1)
328
+ return
329
+
330
+
331
+ def cmd_review(args):
332
+ """Contract quality gate: rule checks + coverage matrix, guards before rendering."""
333
+ with open(args.input, "r", encoding="utf-8-sig") as fp:
334
+ contract = json.load(fp)
335
+ facts = None
336
+ if args.facts:
337
+ with open(args.facts, "r", encoding="utf-8-sig") as fp:
338
+ facts = json.load(fp)
339
+ elif args.doc:
340
+ from .extract.docx_loader import load_docx
341
+
342
+ facts = load_docx(args.doc)
343
+ provider = None
344
+ conf = load_config()
345
+ config_path = args.db or conf["db"]
346
+ if config_path:
347
+ try:
348
+ provider = build_provider(load_db_config(config_path))
349
+ except Exception as exc:
350
+ print("警告: 数据库配置不可用,跳过列级校验: %s" % exc)
351
+ result = review_contract(contract, facts=facts, provider=provider)
352
+ report = render_report(result, contract)
353
+ print(report)
354
+ if args.output:
355
+ with open(args.output, "w", encoding="utf-8") as fp:
356
+ fp.write(report + "\n")
357
+ print("报告已写入 ->", args.output)
358
+ if result["issues"]:
359
+ sys.exit(1)
360
+
361
+
362
+ def cmd_audit(args):
363
+ """Case asset audit: find unsuitable cases in an existing .xmind (structure/SQL/coverage/granularity)."""
364
+ tree = read_tree(args.input)
365
+ facts = None
366
+ if args.facts:
367
+ with open(args.facts, "r", encoding="utf-8-sig") as fp:
368
+ facts = json.load(fp)
369
+ elif args.doc:
370
+ from .extract.docx_loader import load_docx
371
+
372
+ facts = load_docx(args.doc)
373
+ provider = None
374
+ conf = load_config()
375
+ config_path = args.db or conf["db"]
376
+ if config_path:
377
+ try:
378
+ provider = build_provider(load_db_config(config_path))
379
+ except Exception as exc:
380
+ print("警告: 数据库配置不可用,跳过 SQL 可执行性校验: %s" % exc)
381
+ result = audit_xmind(tree, facts=facts, provider=provider, style=args.style)
382
+ report = render_audit_report(result)
383
+ print(report)
384
+ if args.output:
385
+ with open(args.output, "w", encoding="utf-8") as fp:
386
+ fp.write(report + "\n")
387
+ print("报告已写入 ->", args.output)
388
+ # audit updates asset metadata (audited_at)
389
+ write_meta(args.input, audited=True)
390
+ if result["issues"]:
391
+ sys.exit(1)
392
+
393
+
394
+ def cmd_facts(args):
395
+ """Scan the code repo, dump structured facts JSON (interfaces/SQL/stored procs/state enums/middlewares)"""
396
+ facts = scan_repo(args.repo)
397
+ dump_facts(facts, args.output)
398
+ summary = count_facts(facts)
399
+ print("OK ->", args.output)
400
+ print("| 接口:", summary["interfaces"], "| SQL:", summary["sqls"], "| 存储过程:", summary["stored_procs"])
401
+ print("| 状态枚举:", summary.get("enums", 0), "| 中间件:", summary.get("middlewares", 0))
402
+
403
+
404
+ def cmd_diff(args):
405
+ """Case coverage diff: code interfaces/doc features vs case tree"""
406
+ tree = read_tree(args.input)
407
+ result = {}
408
+ if args.facts:
409
+ facts = load_facts(args.facts)
410
+ if facts.get("interfaces"):
411
+ result["interfaces"] = compare_interfaces(facts, tree)
412
+ if args.doc:
413
+ doc_facts = load_docx(args.doc)
414
+ if doc_facts.get("features"):
415
+ result["features"] = compare_features(doc_facts, tree)
416
+ if not result:
417
+ print("无对比数据:请提供 -f facts.json 或 -d 方案.docx")
418
+ sys.exit(1)
419
+ covered = coverage_map(facts, tree) if args.facts else None
420
+ report = build_report(result, covered=covered)
421
+ print(report)
422
+ if args.output:
423
+ with open(args.output, "w", encoding="utf-8") as fp:
424
+ fp.write(report)
425
+ print("报告已写入 ->", args.output)
426
+
427
+
428
+ def cmd_validate(args):
429
+ """Validate a .xmind file (zen or tb format)"""
430
+ if args.format == "tb":
431
+ # TB format: read the case tree then validate by TB rules (group depth/steps/expect length)
432
+ tree = read_tree(args.input)
433
+ errors = check_tb_tree(tree)
434
+ if errors:
435
+ print("TB 校验失败:")
436
+ for msg in errors:
437
+ print(" -", msg)
438
+ sys.exit(1)
439
+ print("OK: TB 校验通过 ->", args.input)
440
+ return
441
+ errors = check_xmind_file(args.input)
442
+ if errors:
443
+ print("校验失败:")
444
+ for msg in errors:
445
+ print(" -", msg)
446
+ sys.exit(1)
447
+ print("OK: 校验通过 ->", args.input)
448
+
449
+
450
+ def cmd_info(args):
451
+ """Stat a .xmind file: sheets/nodes/case count"""
452
+ from .writer import read_xmind
453
+
454
+ sheets = read_xmind(args.input)
455
+ print("文件:", args.input)
456
+ print("sheet 数:", len(sheets))
457
+ for index, sheet in enumerate(sheets):
458
+ root = sheet.get("rootTopic") or {}
459
+ tree = []
460
+ for child in (root.get("children") or {}).get("attached") or []:
461
+ node = topic_to_node(child)
462
+ if node is not None:
463
+ tree.append(node)
464
+ print("sheet[%d] 根标题: %s" % (index, root.get("title")))
465
+ print(" 章节数:", len(tree), "| 用例数:", count_cases(tree), "| 节点总数:", count_nodes(root))
466
+
467
+
468
+ def topic_to_node(topic):
469
+ """Convert a topic into a tree node (tolerant: skip pure image/marker nodes without title)."""
470
+ title = topic.get("title") or ""
471
+ children = (topic.get("children") or {}).get("attached") or []
472
+ valid_children = []
473
+ for child in children:
474
+ node = topic_to_node(child)
475
+ if node is not None:
476
+ valid_children.append(node)
477
+ if not title and not valid_children:
478
+ return None
479
+ node = {"t": title}
480
+ if valid_children:
481
+ node["c"] = valid_children
482
+ return node
483
+
484
+
485
+ def cmd_tree(args):
486
+ """Restore xmind into a case tree JSON (for secondary editing)"""
487
+ tree = read_tree(args.input)
488
+ with open(args.output, "w", encoding="utf-8") as fp:
489
+ json.dump(tree, fp, ensure_ascii=False, indent=2)
490
+ print("OK ->", args.output, "| 章节数:", len(tree))
491
+
492
+
493
+ def cmd_track(args):
494
+ """Test management: execution records/stats report/asset execution rate/quality trend"""
495
+ if args.action == "record":
496
+ record, path = record_execution(
497
+ args.case, args.result, note=args.note or "",
498
+ source=args.asset or "", chapter=args.chapter or "",
499
+ db_path=args.db,
500
+ )
501
+ print("已记录 ->", path, "|", record["case"], "|", record["result"])
502
+ return
503
+ if args.action == "report":
504
+ report = build_track_report(db_path=args.db)
505
+ if args.asset:
506
+ exec_result = asset_execution(args.asset, db_path=args.db)
507
+ report["asset"] = exec_result
508
+ text = render_track_report(report)
509
+ if args.asset and report.get("asset"):
510
+ asset = report["asset"]
511
+ text += "\n资产执行率: %.0f%% (%d/%d),从未执行 %d 个:\n%s\n" % (
512
+ asset["rate"] * 100, asset["total"] - len(asset["never"]), asset["total"],
513
+ len(asset["never"]), "\n".join("- " + c for c in asset["never"]))
514
+ print(text)
515
+ if args.output:
516
+ with open(args.output, "w", encoding="utf-8") as fp:
517
+ fp.write(text + "\n")
518
+ print("报告已写入 ->", args.output)
519
+ return
520
+ if args.action == "trend":
521
+ trend = build_trend(db_path=args.db)
522
+ text = render_track_trend(trend)
523
+ print(text)
524
+ if args.output:
525
+ with open(args.output, "w", encoding="utf-8") as fp:
526
+ fp.write(text + "\n")
527
+ print("报告已写入 ->", args.output)
528
+ return
529
+
530
+
531
+ def cmd_bug(args):
532
+ """Defect library: register/list/close/stats"""
533
+ if args.action == "add":
534
+ bug, path = add_bug(args.title, args.severity,
535
+ case=args.case or "", note=args.note or "", db_path=args.db)
536
+ print("已登记 ->", path, "|", bug["id"], "|", bug["severity"], "|", bug["title"])
537
+ return
538
+ if args.action == "list":
539
+ bugs = list_bugs(status=args.status, db_path=args.db)
540
+ if not bugs:
541
+ print("无缺陷记录" + ("(状态: %s)" % args.status if args.status else ""))
542
+ return
543
+ for bug in bugs:
544
+ print("%s [%s] %s (关联: %s)" % (bug["id"], bug.get("severity") or "?",
545
+ bug.get("title") or "?", bug.get("case") or "-"))
546
+ return
547
+ if args.action == "close":
548
+ bug, path = close_bug(args.bug_id, note=args.note or "", db_path=args.db)
549
+ print("已关闭 ->", bug["id"], "|", bug["title"])
550
+ return
551
+ if args.action == "stats":
552
+ summary = defect_summary(db_path=args.db)
553
+ print("缺陷总数:", summary["total"], "| 未关闭:", summary["status"].get("open", 0),
554
+ "| 已修复:", summary["status"].get("fixed", 0), "| 已关闭:", summary["status"].get("closed", 0))
555
+ if summary["top_cases"]:
556
+ print("缺陷高发用例 Top 10:")
557
+ for item in summary["top_cases"]:
558
+ print(" - %s: %d 个缺陷" % (item["case"], item["count"]))
559
+ return
560
+
561
+
562
+ def cmd_evolve(args):
563
+ """自进化:确定性备份/回滚(自迭代协议配套)"""
564
+ if args.action == "backup":
565
+ backup_dir = backup_files(args.files)
566
+ print("已备份 ->", backup_dir)
567
+ return
568
+ if args.action == "restore":
569
+ backup_path = restore_file(args.file)
570
+ print("已恢复 ->", args.file, "(来源:", backup_path, ")")
571
+ return
572
+ if args.action == "list":
573
+ backups = list_backups()
574
+ if not backups:
575
+ print("无备份记录")
576
+ return
577
+ for item in backups:
578
+ print("[%s] %s" % (item["stamp"], "、".join(item["files"]) or "(空)"))
579
+ return
580
+ if args.action == "prune":
581
+ removed = prune_backups(keep=args.keep)
582
+ print("已清理", removed, "个旧备份(保留最近", args.keep, "次)")
583
+ return
584
+
585
+
586
+ def cmd_asset(args):
587
+ """Case asset staleness check: .xmind assets unaudited for more than N days"""
588
+ stale = stale_assets(args.dir, stale_days=args.days)
589
+ if not stale:
590
+ print("无老化资产(阈值", args.days, "天)")
591
+ return
592
+ print("老化资产", len(stale), "个(超过", args.days, "天未审计):")
593
+ for item in stale:
594
+ print(" - %s(距今 %d 天)" % (item["asset"], item["age_days"]))
595
+ sys.exit(1)
596
+
597
+
598
+ # 内网仓库地址不写入代码/包内(PyPI 公开可见),由环境变量或 --git 参数提供
599
+ DEFAULT_INSTALL_GIT = os.environ.get("MTKIT_INSTALL_GIT", "")
600
+
601
+
602
+ def cmd_install(args):
603
+ """PyPI bootstrap install: git pull the full repo (with Qoder skill files), run its install.py to register the plugin.
604
+
605
+ pip install mtkit only installs the Python CLI; Qoder skill files (skills/.qoder-plugin/commands)
606
+ are not in the wheel, so this command pulls the repo and registers (installPath points to the clone dir).
607
+ """
608
+ import subprocess
609
+
610
+ git_url = args.git or DEFAULT_INSTALL_GIT
611
+ if not git_url:
612
+ print("!! 未提供仓库地址:请使用 mtkit install --git <仓库地址>,或设置环境变量 MTKIT_INSTALL_GIT")
613
+ sys.exit(1)
614
+ target = args.dir or os.path.join(os.getcwd(), "mtkit")
615
+ target = os.path.abspath(target)
616
+ print("mtkit 引导安装:拉取完整仓库并注册 Qoder 插件")
617
+ print("git 地址: %s" % git_url)
618
+ print("目标目录: %s" % target)
619
+ if os.path.isdir(target):
620
+ manifest = os.path.join(target, ".qoder-plugin", "plugin.json")
621
+ if os.path.isfile(manifest):
622
+ print("目标目录已是 mtkit 仓库,直接使用")
623
+ else:
624
+ print("!! 目标目录已存在且不是 mtkit 仓库,请换目录: mtkit install --dir <新目录>")
625
+ sys.exit(1)
626
+ else:
627
+ result = subprocess.run(["git", "clone", "--depth", "1", git_url, target])
628
+ if result.returncode != 0:
629
+ print("!! git clone 失败(退出码 %d),请检查地址与网络/凭据" % result.returncode)
630
+ sys.exit(1)
631
+ install_script = os.path.join(target, "install.py")
632
+ print("==> 执行仓库内安装: %s" % install_script)
633
+ result = subprocess.run([sys.executable or "python", install_script], cwd=target)
634
+ sys.exit(result.returncode)
635
+
636
+
637
+ def build_parser():
638
+ parser = argparse.ArgumentParser(
639
+ prog="mtkit",
640
+ description="通用测试用例 XMind 生成/校验工具 (v%s)" % __version__,
641
+ )
642
+ sub = parser.add_subparsers(dest="command", required=True)
643
+
644
+ gen = sub.add_parser("gen", help="生成 .xmind 文件")
645
+ gen.add_argument("-i", "--input", required=True, help="输入文件(.json/.py/.md)")
646
+ gen.add_argument("-o", "--output", required=True, help="输出 .xmind 文件")
647
+ gen.add_argument("--root", help="覆盖根节点标题")
648
+ gen.add_argument("--module", default=DEFAULT_MODULE_VAR, help=".py 输入时的用例树变量名(默认 TREE)")
649
+ gen.add_argument("--type", default="功能测试", help=".md 输入的用例类型(默认 功能测试)")
650
+ gen.add_argument(
651
+ "--format",
652
+ choices=["zen", "tb"],
653
+ default="zen",
654
+ help="输出格式:zen=扁平描述行(默认);tb=TB 导入层级(分组>用例>步骤>预期)",
655
+ )
656
+ gen.add_argument("--keep-extra", action="store_true", help="tb 格式下保留 SQL核对/日志核对/实际 等附加行(作为步骤)")
657
+ gen.add_argument(
658
+ "--style",
659
+ choices=["zen", "history", "auto"],
660
+ default=None,
661
+ help="用例描述风格:zen=pc/步骤/预期平铺行;history=操作步骤/预期结果多级节点;auto=自动检测(默认,可被项目 .mtkit.json 覆盖)",
662
+ )
663
+ gen.add_argument("--require-sql", action="store_true", help="数据库交互类用例必须包含 SQL 核对内容(严格校验)")
664
+ gen.add_argument(
665
+ "--auto-pc",
666
+ action="store_true",
667
+ help="history 风格下自动把\"造数/前置\"类步骤从操作步骤中拆分为「前置条件」节点",
668
+ )
669
+ gen.add_argument("--require-pc", action="store_true", help="history 风格用例必须包含「前置条件」节点(配合 --auto-pc)")
670
+ gen.add_argument("--no-validate", action="store_true", help="跳过用例树结构校验")
671
+ gen.set_defaults(func=cmd_gen)
672
+
673
+ gen_doc = sub.add_parser("gen-doc", help="从技术方案 .docx 一键生成用例(骨架或 LLM 模式)")
674
+ gen_doc.add_argument("-i", "--input", required=True, help="技术方案 .docx 文档")
675
+ gen_doc.add_argument("-o", "--output", required=True, help="输出 .xmind 文件")
676
+ gen_doc.add_argument("--hist", help="历史用例 .xmind(格式样例 + 骨架复用)")
677
+ gen_doc.add_argument("--root", help="覆盖根节点标题(缺省取文档第一个一级标题)")
678
+ gen_doc.add_argument(
679
+ "--replace-map",
680
+ help="历史骨架标题替换规则,如 员工报销=客户报销,员工=客户",
681
+ )
682
+ gen_doc.add_argument("--facts", help="代码事实 JSON(mtkit facts 产物,注入 LLM prompt)")
683
+ gen_doc.add_argument("-r", "--repo", help="后端代码仓库目录(LLM 模式自动扫描接口/SQL 注入)")
684
+ gen_doc.add_argument("--front", help="前端项目目录(LLM 模式自动扫描页面/接口调用/权限点注入)")
685
+ gen_doc.add_argument("--sample-limit", type=int, default=3, help="历史样例取前 N 个用例(默认 3)")
686
+ gen_doc.add_argument(
687
+ "--llm",
688
+ choices=["none", "http", "cli"],
689
+ default="none",
690
+ help="生成模式:none=骨架(默认);http=OpenAI 兼容接口;cli=本地 agent CLI",
691
+ )
692
+ gen_doc.add_argument("--endpoint", help="LLM 接口地址(如 https://api.openai.com/v1/chat/completions)")
693
+ gen_doc.add_argument("--api-key", help="LLM API Key(或环境变量 MTKIT_LLM_API_KEY)")
694
+ gen_doc.add_argument("--model", default="", help="模型名(缺省为空:跟随使用者/Qoder 选用的模型,工具不自行抉择)")
695
+ gen_doc.add_argument("--cli-cmd", help="本地 agent CLI 命令模板(或环境变量 MTKIT_LLM_CMD),如 'qoder ask'")
696
+ gen_doc.add_argument("--retry", type=int, default=3, help="LLM 单分片最大重试次数(默认 3)")
697
+ gen_doc.add_argument("--db", help="db.json 数据库配置(LLM 模式注入表结构元数据)")
698
+ gen_doc.add_argument(
699
+ "--style",
700
+ choices=["zen", "history", "auto"],
701
+ default="auto",
702
+ help="输出用例描述风格(默认 auto)",
703
+ )
704
+ gen_doc.add_argument(
705
+ "--format",
706
+ choices=["zen", "tb"],
707
+ default="zen",
708
+ help="输出格式:zen(默认);tb=TB 导入层级",
709
+ )
710
+ gen_doc.add_argument("--keep-extra", action="store_true", help="tb 格式下保留附加行")
711
+ gen_doc.add_argument("--require-sql", action="store_true", help="数据库交互类用例必须包含 SQL 核对内容")
712
+ gen_doc.add_argument(
713
+ "--auto-pc",
714
+ action="store_true",
715
+ help="history 风格下自动把\"造数/前置\"类步骤从操作步骤中拆分为「前置条件」节点",
716
+ )
717
+ gen_doc.add_argument("--require-pc", action="store_true", help="history 风格用例必须包含「前置条件」节点(配合 --auto-pc)")
718
+ gen_doc.add_argument("--no-validate", action="store_true", help="跳过用例树结构校验")
719
+ gen_doc.set_defaults(func=cmd_gen_doc)
720
+
721
+ facts = sub.add_parser("facts", help="扫描代码仓库,输出接口/SQL/存储过程事实 JSON")
722
+ facts.add_argument("-r", "--repo", required=True, help="代码仓库根目录")
723
+ facts.add_argument("-o", "--output", required=True, help="输出事实 JSON 文件")
724
+ facts.set_defaults(func=cmd_facts)
725
+
726
+ gather = sub.add_parser("gather", help="一键提取生成上下文(方案+历史+代码) -> context.json")
727
+ gather.add_argument("-i", "--input", required=True, help="技术方案 .docx 文档")
728
+ gather.add_argument("-o", "--output", required=True, help="输出 context.json")
729
+ gather.add_argument("--hist", help="历史用例 .xmind(格式样例 + 骨架)")
730
+ gather.add_argument("-r", "--repo", help="后端代码仓库目录(接口/SQL/存储过程)")
731
+ gather.add_argument("--front", help="前端项目目录(页面/接口调用/权限点)")
732
+ gather.add_argument(
733
+ "--replace-map",
734
+ help="历史骨架标题替换规则,如 员工报销=客户报销,员工=客户",
735
+ )
736
+ gather.add_argument("--sample-limit", type=int, default=3, help="历史样例取前 N 个用例(默认 3)")
737
+ gather.add_argument("--db", help="db.json 数据库配置(注入表结构元数据到 code_facts)")
738
+ gather.set_defaults(func=cmd_gather)
739
+
740
+ contract = sub.add_parser("contract", help="xmind 用例树 <-> 契约 JSON 互转(迭代再生成)")
741
+ contract.add_argument("-i", "--input", required=True, help="输入 .xmind 或契约 JSON")
742
+ contract.add_argument("-o", "--output", required=True, help="输出契约 JSON 或用例树 JSON")
743
+ contract.add_argument("--reverse", action="store_true", help="反向转换:契约 JSON -> 用例树 JSON")
744
+ contract.set_defaults(func=cmd_contract)
745
+
746
+ diff = sub.add_parser("diff", help="用例覆盖度对比(代码接口/文档功能点 vs 用例树)")
747
+ diff.add_argument("-i", "--input", required=True, help="用例 .xmind 文件")
748
+ diff.add_argument("-f", "--facts", help="代码事实 JSON(mtkit facts 产物)")
749
+ diff.add_argument("-d", "--doc", help="技术方案 .docx(文档功能点对比)")
750
+ diff.add_argument("-o", "--output", help="报告输出文件(可选,缺省打印到控制台)")
751
+ diff.set_defaults(func=cmd_diff)
752
+
753
+ val = sub.add_parser("validate", help="校验 .xmind 文件结构")
754
+ val.add_argument("-i", "--input", required=True, help=".xmind 文件")
755
+ val.add_argument(
756
+ "--format",
757
+ choices=["zen", "tb"],
758
+ default="zen",
759
+ help="按哪个格式规则校验(默认 zen)",
760
+ )
761
+ val.set_defaults(func=cmd_validate)
762
+
763
+ dbp = sub.add_parser("db", help="数据库接入(严格只读):check/schema/verify")
764
+ db_sub = dbp.add_subparsers(dest="action", required=True)
765
+ db_check = db_sub.add_parser("check", help="连通性测试")
766
+ db_check.add_argument("-c", "--config", help="db.json 配置文件(缺省取项目 .mtkit.json 的 db 字段)")
767
+ db_schema = db_sub.add_parser("schema", help="导出 schema 快照")
768
+ db_schema.add_argument("-c", "--config", help="db.json 配置文件(缺省取项目 .mtkit.json 的 db 字段)")
769
+ db_schema.add_argument("-o", "--output", required=True, help="输出 schema.json")
770
+ db_verify = db_sub.add_parser("verify", help="校验契约中全部 SQL 的可执行性")
771
+ db_verify.add_argument("-c", "--config", help="db.json 配置文件(缺省取项目 .mtkit.json 的 db 字段)")
772
+ db_verify.add_argument("-i", "--input", required=True, help="契约 JSON 文件")
773
+ db_verify.add_argument("-o", "--output", help="校验报告输出文件(可选)")
774
+ dbp.set_defaults(func=cmd_db)
775
+
776
+ review = sub.add_parser("review", help="契约质量门禁:规则检查 + 覆盖矩阵(渲染前把关)")
777
+ review.add_argument("-i", "--input", required=True, help="契约 JSON 文件")
778
+ review.add_argument("-f", "--facts", help="facts.json(mtkit facts 产物)")
779
+ review.add_argument("-d", "--doc", help="技术方案 .docx(提取功能点做覆盖对比)")
780
+ review.add_argument("-c", "--db", help="db.json(列级 SQL 校验)")
781
+ review.add_argument("-o", "--output", help="门禁报告输出文件(可选)")
782
+ review.set_defaults(func=cmd_review)
783
+
784
+ audit = sub.add_parser("audit", help="用例资产体检:检索已有 .xmind 中不合适用例")
785
+ audit.add_argument("-i", "--input", required=True, help="用例 .xmind 文件")
786
+ audit.add_argument("-f", "--facts", help="facts.json(覆盖对比)")
787
+ audit.add_argument("-d", "--doc", help="技术方案 .docx(提取功能点做覆盖对比)")
788
+ audit.add_argument("-c", "--db", help="db.json(SQL 只读/可执行性校验)")
789
+ audit.add_argument("--style", choices=["zen", "history"], help="用例风格(缺省自动检测)")
790
+ audit.add_argument("-o", "--output", help="体检报告输出文件(可选)")
791
+ audit.set_defaults(func=cmd_audit)
792
+
793
+ info = sub.add_parser("info", help="统计 .xmind 文件信息")
794
+ info.add_argument("-i", "--input", required=True, help=".xmind 文件")
795
+ info.set_defaults(func=cmd_info)
796
+
797
+ tree = sub.add_parser("tree", help="把 .xmind 还原为用例树 JSON")
798
+ tree.add_argument("-i", "--input", required=True, help=".xmind 文件")
799
+ tree.add_argument("-o", "--output", required=True, help="输出 .json 文件")
800
+ tree.set_defaults(func=cmd_tree)
801
+
802
+ track = sub.add_parser("track", help="测试管理:执行记录/统计报告/质量趋势")
803
+ track_sub = track.add_subparsers(dest="action", required=True)
804
+ track_record = track_sub.add_parser("record", help="记录用例执行结果")
805
+ track_record.add_argument("--case", required=True, help="用例标题(与资产一致)")
806
+ track_record.add_argument("--result", required=True, choices=["pass", "fail", "blocked"], help="执行结果")
807
+ track_record.add_argument("--note", help="备注")
808
+ track_record.add_argument("--asset", help="关联用例资产 .xmind(可选)")
809
+ track_record.add_argument("--chapter", help="用例章节(可选)")
810
+ track_record.add_argument("--db", help="testdb.json 路径")
811
+ track_report = track_sub.add_parser("report", help="统计报告")
812
+ track_report.add_argument("--asset", help="用例资产 .xmind(输出从未执行清单)")
813
+ track_report.add_argument("-o", "--output", help="报告输出文件(可选)")
814
+ track_report.add_argument("--db", help="testdb.json 路径")
815
+ track_trend = track_sub.add_parser("trend", help="质量趋势看板")
816
+ track_trend.add_argument("-o", "--output", help="报告输出文件(可选)")
817
+ track_trend.add_argument("--db", help="testdb.json 路径")
818
+ track.set_defaults(func=cmd_track)
819
+
820
+ bug = sub.add_parser("bug", help="缺陷库:登记/清单/关闭/统计")
821
+ bug_sub = bug.add_subparsers(dest="action", required=True)
822
+ bug_add = bug_sub.add_parser("add", help="登记缺陷")
823
+ bug_add.add_argument("--title", required=True, help="缺陷标题")
824
+ bug_add.add_argument("--severity", required=True, choices=["P0", "P1", "P2"], help="严重程度")
825
+ bug_add.add_argument("--case", help="关联用例(可选)")
826
+ bug_add.add_argument("--note", help="备注")
827
+ bug_add.add_argument("--db", help="testdb.json 路径")
828
+ bug_list = bug_sub.add_parser("list", help="缺陷清单")
829
+ bug_list.add_argument("--status", choices=["open", "fixed", "closed"], help="按状态过滤")
830
+ bug_list.add_argument("--db", help="testdb.json 路径")
831
+ bug_close = bug_sub.add_parser("close", help="关闭缺陷")
832
+ bug_close.add_argument("bug_id", help="缺陷编号(如 BUG-001)")
833
+ bug_close.add_argument("--note", help="关闭说明(可选)")
834
+ bug_close.add_argument("--db", help="testdb.json 路径")
835
+ bug_stats = bug_sub.add_parser("stats", help="缺陷分布摘要(缺陷高发用例 Top 10)")
836
+ bug_stats.add_argument("--db", help="testdb.json 路径")
837
+ bug.set_defaults(func=cmd_bug)
838
+
839
+ evolve = sub.add_parser("evolve", help="自进化:确定性备份/回滚(自迭代协议配套)")
840
+ evolve_sub = evolve.add_subparsers(dest="action", required=True)
841
+ evolve_backup = evolve_sub.add_parser("backup", help="备份文件到 .mtkit-work/backup/<时间戳>/")
842
+ evolve_backup.add_argument("files", nargs="+", help="待备份文件路径(可多个)")
843
+ evolve_restore = evolve_sub.add_parser("restore", help="从最近一次备份恢复文件")
844
+ evolve_restore.add_argument("file", help="待恢复文件路径")
845
+ evolve_list = evolve_sub.add_parser("list", help="备份清单")
846
+ evolve_prune = evolve_sub.add_parser("prune", help="清理旧备份")
847
+ evolve_prune.add_argument("--keep", type=int, default=10, help="保留最近 N 次(默认 10)")
848
+ evolve.set_defaults(func=cmd_evolve)
849
+
850
+ assetp = sub.add_parser("asset", help="用例资产治理(老化检测)")
851
+ asset_sub = assetp.add_subparsers(dest="action", required=True)
852
+ asset_stale = asset_sub.add_parser("stale", help="老化检测:目录下超过 N 天未审计的 .xmind 资产")
853
+ asset_stale.add_argument("--dir", required=True, help="资产目录")
854
+ asset_stale.add_argument("--days", type=int, default=30, help="老化阈值天数(默认 30)")
855
+ assetp.set_defaults(func=cmd_asset)
856
+
857
+ installp = sub.add_parser("install", help="PyPI 引导安装:拉取完整仓库并注册 Qoder 插件")
858
+ installp.add_argument("--git", default=DEFAULT_INSTALL_GIT, help="仓库 git 地址(或设置环境变量 MTKIT_INSTALL_GIT)")
859
+ installp.add_argument("--dir", help="克隆目录(缺省 <cwd>/mtkit)")
860
+ installp.set_defaults(func=cmd_install)
861
+
862
+ return parser
863
+
864
+
865
+ def main(argv=None):
866
+ # Windows GBK console guard: prefer UTF-8 output, keep default on failure
867
+ for stream in (sys.stdout, sys.stderr):
868
+ try:
869
+ stream.reconfigure(encoding="utf-8", errors="replace")
870
+ except (AttributeError, ValueError, OSError):
871
+ pass
872
+ parser = build_parser()
873
+ args = parser.parse_args(argv)
874
+ try:
875
+ args.func(args)
876
+ except SystemExit:
877
+ raise
878
+ except Exception as exc:
879
+ # self-healing: unexpected failures auto-recorded as improvement suggestions
880
+ capture_failure(exc, argv=sys.argv)
881
+ raise
882
+
883
+
884
+ if __name__ == "__main__":
885
+ main()