codebee 0.1.101 → 0.1.103

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 (134) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -6
  4. package/app/.playwright-cli/console-2026-09-23T08-26-03-635Z.log +88 -0
  5. package/app/.playwright-cli/page-2026-09-23T08-26-03-845Z.yml +126 -0
  6. package/app/.playwright-cli/page-2026-09-23T08-29-44-203Z.png +0 -0
  7. package/app/.playwright-cli/page-2026-09-23T08-35-42-046Z.yml +210 -0
  8. package/app/.playwright-cli/page-2026-09-23T08-36-52-858Z.png +0 -0
  9. package/app/.playwright-cli/page-2026-09-23T08-37-33-938Z.png +0 -0
  10. package/app/.playwright-cli/run-detail-after.png +0 -0
  11. package/app/core/acceptance.py +100 -100
  12. package/app/core/acp_client.py +457 -426
  13. package/app/core/aiflavor.py +197 -197
  14. package/app/core/analytics.py +38 -38
  15. package/app/core/artifacts.py +148 -148
  16. package/app/core/assets.py +110 -110
  17. package/app/core/attachments.py +623 -623
  18. package/app/core/audit.py +30 -30
  19. package/app/core/backend_profiles.py +188 -188
  20. package/app/core/backup.py +470 -470
  21. package/app/core/beekeeper.py +183 -183
  22. package/app/core/benchstore.py +102 -102
  23. package/app/core/board.py +21 -17
  24. package/app/core/bookmeta.py +1036 -1036
  25. package/app/core/bookmeta_catalog.py +180 -180
  26. package/app/core/branching.py +137 -137
  27. package/app/core/builtin_agent.py +13 -4
  28. package/app/core/capability.py +144 -144
  29. package/app/core/catalog.py +28 -6
  30. package/app/core/chaptersafe.py +32 -32
  31. package/app/core/checkpoints.py +117 -31
  32. package/app/core/cleanup.py +303 -303
  33. package/app/core/command_auth.py +302 -302
  34. package/app/core/compaction.py +201 -201
  35. package/app/core/contracts.py +255 -255
  36. package/app/core/covergen.py +356 -356
  37. package/app/core/defectretro.py +43 -43
  38. package/app/core/diagnostics.py +114 -114
  39. package/app/core/dispatch.py +1 -1
  40. package/app/core/dispatch_log.py +128 -128
  41. package/app/core/env_scrub.py +85 -85
  42. package/app/core/errorlog.py +137 -137
  43. package/app/core/eval_matrix.py +91 -82
  44. package/app/core/evaluation.py +174 -174
  45. package/app/core/failure_notify.py +290 -290
  46. package/app/core/flow_graph.py +33 -33
  47. package/app/core/goal_service.py +167 -167
  48. package/app/core/health.py +389 -389
  49. package/app/core/history.py +38 -38
  50. package/app/core/hooks.py +162 -162
  51. package/app/core/knowledge_pipeline.py +86 -86
  52. package/app/core/manager.py +2385 -2385
  53. package/app/core/mcp_client.py +7 -2
  54. package/app/core/mocks.py +64 -64
  55. package/app/core/notify.py +201 -201
  56. package/app/core/novel_quality.py +181 -181
  57. package/app/core/openapi.py +217 -209
  58. package/app/core/operations.py +228 -228
  59. package/app/core/paihang.py +145 -145
  60. package/app/core/pipeline.py +6 -3
  61. package/app/core/policy.py +9 -0
  62. package/app/core/portguard.py +111 -111
  63. package/app/core/presence.py +77 -77
  64. package/app/core/preview.py +293 -293
  65. package/app/core/project_memory.py +206 -206
  66. package/app/core/prompt_guard.py +78 -78
  67. package/app/core/publish/__init__.py +7 -7
  68. package/app/core/publish/auto.py +659 -562
  69. package/app/core/publish/chaprows.py +138 -138
  70. package/app/core/publish/fanqie.py +16 -10
  71. package/app/core/publish/flow.py +29 -1
  72. package/app/core/publish/flows-fanqie-calibrated.json +442 -442
  73. package/app/core/publish/manager.py +1185 -1177
  74. package/app/core/publish/qimao.py +193 -193
  75. package/app/core/publish/volumes.py +108 -108
  76. package/app/core/publish/ws.py +139 -139
  77. package/app/core/quality_gate.py +201 -201
  78. package/app/core/redact.py +38 -38
  79. package/app/core/repeat_guard.py +129 -129
  80. package/app/core/retrieval.py +137 -137
  81. package/app/core/sandbox_runtime.py +95 -0
  82. package/app/core/selfupdate.py +384 -384
  83. package/app/core/session_log.py +161 -161
  84. package/app/core/sessions.py +312 -312
  85. package/app/core/settings.py +215 -215
  86. package/app/core/settings_schema.py +282 -282
  87. package/app/core/share_page.py +114 -114
  88. package/app/core/skill_scan.py +139 -139
  89. package/app/core/skillpacks/market/character-bible.md +66 -66
  90. package/app/core/skillpacks/market/code-risk-checklist.md +58 -58
  91. package/app/core/skillpacks/market/git-workflow.md +57 -57
  92. package/app/core/skillpacks/market/release-notes.md +72 -72
  93. package/app/core/skillpacks/market/weekly-report.md +71 -71
  94. package/app/core/skillpacks/market/worldview-consistency.md +70 -70
  95. package/app/core/step_runner.py +132 -132
  96. package/app/core/store.py +13 -3
  97. package/app/core/story_tracking.py +275 -275
  98. package/app/core/task_compile.py +199 -199
  99. package/app/core/telemetry.py +292 -292
  100. package/app/core/tlsctx.py +64 -64
  101. package/app/core/token_meter.py +147 -147
  102. package/app/core/tool_outputs.py +107 -107
  103. package/app/core/tracing.py +207 -207
  104. package/app/core/upstream.py +41 -41
  105. package/app/core/usage.py +1038 -1038
  106. package/app/core/volumes.py +389 -389
  107. package/app/core/webhooks.py +89 -89
  108. package/app/core/wxdigest.py +865 -865
  109. package/app/core/zentao.py +2692 -2692
  110. package/app/main.py +1 -0
  111. package/app/mcp_server.py +244 -244
  112. package/app/output/_createbook_body.json +1 -0
  113. package/app/output/_probe_fq_click.py +50 -0
  114. package/app/output/_probe_fq_form.py +42 -0
  115. package/app/output/_probe_fq_modal.py +55 -0
  116. package/app/output/_probe_fq_points.py +71 -0
  117. package/app/output/_probe_fq_submit.py +34 -0
  118. package/app/output/_probe_fq_watch.py +62 -0
  119. package/app/output/workbench-clean-preview.jpg +0 -0
  120. package/app/output/workbench-reference-render.png +0 -0
  121. package/app/output/workbench-shell.png +0 -0
  122. package/app/pick_dialog.py +110 -110
  123. package/app/ui/app.js +165 -29
  124. package/app/ui/artdiff.js +74 -74
  125. package/app/ui/hive3d.js +491 -223
  126. package/app/ui/i18n.js +18 -1
  127. package/app/ui/icons/bee.svg +79 -79
  128. package/app/ui/index.html +24 -4
  129. package/app/ui/manifest.json +16 -16
  130. package/app/ui/qrcode.js +2297 -2297
  131. package/app/ui/style.css +548 -18
  132. package/bin/tutti.js +147 -147
  133. package/package.json +1 -1
  134. package/tools/wx_reader.py +261 -261
@@ -1,43 +1,43 @@
1
- # -*- coding: utf-8 -*-
2
- """缺陷复盘报告(defect_retro,借鉴 zl2237/test-defect-retrospective)。
3
-
4
- 禅道/Jira 缺陷导出 → 产品/开发/测试三视角复盘报告。
5
- 数据不走网络:缺陷导出(CSV)作为任务附件注入上下文,这里只负责
6
- 组装分析框架提示词。无附件时提示词会点名要求补附件——报告框架
7
- 照常输出,不留静默空转。
8
-
9
- 对照参考实现的取舍:它是本地脚本确定性算指标(analyzer 同输入同输出),
10
- 我们是 direct 引擎一次性成稿——先跑通「有复盘产物」这一步,指标口径
11
- 固化(状态/严重度归一在提示词里给锚)后续按需升档。
12
- """
13
- from __future__ import annotations
14
-
15
-
16
- def retro_prompt(goal):
17
- """组装缺陷复盘三视角提示词。纯框架无抓取,恒有返回值。"""
18
- return (
19
- "你是资深质量效能专家,负责输出一份缺陷复盘报告。\n\n"
20
- "## 输入\n"
21
- "用户会提供缺陷平台导出数据(推荐禅道/Jira 导出 CSV 作为任务附件;"
22
- "Excel 二进制读不了,请导出 CSV)。字段口径以「标题、严重程度、"
23
- "状态、创建日期、所属模块、解决方案、关闭原因、责任人」为锚,"
24
- "缺失字段按实际有的算并在报告中声明口径。\n\n"
25
- "## 用户关注点\n%s\n\n"
26
- "## 你的产出(Markdown 报告)\n"
27
- "1. **整体画像**:缺陷总量、严重度分布、状态分布、时间走势"
28
- "(按创建日期聚合)、模块 Top5 集中度——只用表格+一句话结论,不复述原始数据\n"
29
- "2. **产品视角**:需求类缺陷(描述不清/变更频繁/逻辑矛盾)占比与典型例;"
30
- "类需求缺陷(被当 Bug 提的优化)点名\n"
31
- "3. **开发视角**:根因聚类(编码疏忽/设计缺陷/环境/数据/回归)占比;"
32
- "重复回归的模块点名;修复后又被激活的缺陷单列\n"
33
- "4. **测试视角**:发现阶段分布(提测后/上线后/用户反馈);漏测推测"
34
- "(上线后才暴露的缺陷缺什么用例);严重度与发现时长的错配\n"
35
- "5. **改进动作**:每个视角 2-3 条,带建议责任角色与可验证的完成标准,"
36
- "拒绝「加强沟通」类空话\n\n"
37
- "## 纪律\n"
38
- "- 所有数字必须从提供的导出数据里数出来,数不出的指标写「数据未提供」"
39
- "而不是编造\n"
40
- "- 若上下文里没有任何缺陷数据,直接说明需要附带导出 CSV 并给出导出步骤"
41
- "(禅道:产品-缺陷-导出-CSV),不要硬写报告\n"
42
- "- 直接输出报告,不要复述本提示词"
43
- % (goal or "(用户未指定,按全量缺陷复盘)"))
1
+ # -*- coding: utf-8 -*-
2
+ """缺陷复盘报告(defect_retro,借鉴 zl2237/test-defect-retrospective)。
3
+
4
+ 禅道/Jira 缺陷导出 → 产品/开发/测试三视角复盘报告。
5
+ 数据不走网络:缺陷导出(CSV)作为任务附件注入上下文,这里只负责
6
+ 组装分析框架提示词。无附件时提示词会点名要求补附件——报告框架
7
+ 照常输出,不留静默空转。
8
+
9
+ 对照参考实现的取舍:它是本地脚本确定性算指标(analyzer 同输入同输出),
10
+ 我们是 direct 引擎一次性成稿——先跑通「有复盘产物」这一步,指标口径
11
+ 固化(状态/严重度归一在提示词里给锚)后续按需升档。
12
+ """
13
+ from __future__ import annotations
14
+
15
+
16
+ def retro_prompt(goal):
17
+ """组装缺陷复盘三视角提示词。纯框架无抓取,恒有返回值。"""
18
+ return (
19
+ "你是资深质量效能专家,负责输出一份缺陷复盘报告。\n\n"
20
+ "## 输入\n"
21
+ "用户会提供缺陷平台导出数据(推荐禅道/Jira 导出 CSV 作为任务附件;"
22
+ "Excel 二进制读不了,请导出 CSV)。字段口径以「标题、严重程度、"
23
+ "状态、创建日期、所属模块、解决方案、关闭原因、责任人」为锚,"
24
+ "缺失字段按实际有的算并在报告中声明口径。\n\n"
25
+ "## 用户关注点\n%s\n\n"
26
+ "## 你的产出(Markdown 报告)\n"
27
+ "1. **整体画像**:缺陷总量、严重度分布、状态分布、时间走势"
28
+ "(按创建日期聚合)、模块 Top5 集中度——只用表格+一句话结论,不复述原始数据\n"
29
+ "2. **产品视角**:需求类缺陷(描述不清/变更频繁/逻辑矛盾)占比与典型例;"
30
+ "类需求缺陷(被当 Bug 提的优化)点名\n"
31
+ "3. **开发视角**:根因聚类(编码疏忽/设计缺陷/环境/数据/回归)占比;"
32
+ "重复回归的模块点名;修复后又被激活的缺陷单列\n"
33
+ "4. **测试视角**:发现阶段分布(提测后/上线后/用户反馈);漏测推测"
34
+ "(上线后才暴露的缺陷缺什么用例);严重度与发现时长的错配\n"
35
+ "5. **改进动作**:每个视角 2-3 条,带建议责任角色与可验证的完成标准,"
36
+ "拒绝「加强沟通」类空话\n\n"
37
+ "## 纪律\n"
38
+ "- 所有数字必须从提供的导出数据里数出来,数不出的指标写「数据未提供」"
39
+ "而不是编造\n"
40
+ "- 若上下文里没有任何缺陷数据,直接说明需要附带导出 CSV 并给出导出步骤"
41
+ "(禅道:产品-缺陷-导出-CSV),不要硬写报告\n"
42
+ "- 直接输出报告,不要复述本提示词"
43
+ % (goal or "(用户未指定,按全量缺陷复盘)"))
@@ -1,115 +1,115 @@
1
- # -*- coding: utf-8 -*-
2
- """运行时不变量注册表:质量闸门从 pytest 测试期提升到运行时。
3
-
4
- 设计稿:docs/migration/01-defense-patterns.md §5F。
5
- 参考 dsh packages/runtime-diagnostics/invariants/src/index.ts:
6
- enabled/package_allowlist/package_blocklist 三过滤;失败抛 InvariantError 含 packageName。
7
-
8
- CodeBee 实施简化为单文件 + pytest 钩子(设计稿说明);register(name, fn) 注册断言,
9
- run_for(source, ctx) 在指定 source 下跑所有断言并返回失败列表。
10
- """
11
- from __future__ import annotations
12
-
13
- import logging
14
- import threading
15
- from typing import Optional
16
-
17
- log = logging.getLogger(__name__)
18
-
19
-
20
- class InvariantError(Exception):
21
- def __init__(self, source: str, check_name: str, msg: str):
22
- super().__init__(f"[{source}/{check_name}] {msg}")
23
- self.source = source
24
- self.check_name = check_name
25
-
26
-
27
- class InvariantRegistry:
28
- """按 source 分组的运行时断言注册表。
29
-
30
- source 是来源标识(如 "pipeline"/"store"),name 是断言名;
31
- fn(ctx) -> Optional[str] 返回 None 表示通过,返回字符串即失败消息。
32
- """
33
-
34
- def __init__(self):
35
- self._lock = threading.Lock()
36
- self._checks: dict = {} # source -> {name: fn}
37
-
38
- def register(self, source: str, name: str, fn):
39
- with self._lock:
40
- self._checks.setdefault(source, {})[name] = fn
41
- log.debug("invariant registered: %s/%s", source, name)
42
-
43
- def unregister(self, source: str, name: str = None):
44
- """移除断言;name=None 时清空整个 source。"""
45
- with self._lock:
46
- if source not in self._checks:
47
- return
48
- if name is None:
49
- del self._checks[source]
50
- else:
51
- self._checks[source].pop(name, None)
52
-
53
- def run_for(self, source: str, ctx: dict, *, fail_fast: bool = False):
54
- """在 source 下跑所有断言。
55
-
56
- Returns:
57
- [(source, name, message), ...] 失败列表(空 = 全过)。
58
-
59
- Raises:
60
- InvariantError: fail_fast=True 且首个失败。
61
- """
62
- fails = []
63
- with self._lock:
64
- checks = dict(self._checks.get(source, {}))
65
- for name, fn in checks.items():
66
- try:
67
- msg = fn(ctx)
68
- except Exception as e:
69
- msg = f"check raised: {e!r}"
70
- if msg:
71
- fails.append((source, name, msg))
72
- log.warning("invariant FAIL: %s/%s: %s", source, name, msg)
73
- if fail_fast:
74
- raise InvariantError(source, name, msg)
75
- return fails
76
-
77
- def list(self, source: Optional[str] = None):
78
- """列出已注册的 source/name;source=None 时全部。"""
79
- with self._lock:
80
- if source is None:
81
- return [(s, n) for s, m in self._checks.items() for n in m]
82
- return [(source, n) for n in self._checks.get(source, {})]
83
-
84
-
85
- invariants = InvariantRegistry() # 单例
86
-
87
-
88
- # === 默认 invariants ===
89
- def register_default_checks():
90
- """注册 CodeBee 默认运行时断言。"""
91
-
92
- def review_no_all_fail_zero(ctx):
93
- """评审全部 0 分但 run 标 success → 不允许(已锁 test_quality_gates:62-75)。"""
94
- if (ctx.get("review_scores")
95
- and all(s == 0 for s in ctx["review_scores"])
96
- and ctx.get("final_status") == "success"):
97
- return "评审全部 0 分但 run 标 success"
98
- return None
99
-
100
- def step_count_consistency(ctx):
101
- """实际 step 数与预期不一致。"""
102
- if ctx.get("actual_steps") != ctx.get("expected_steps"):
103
- return f"step count {ctx.get('actual_steps')} != expected {ctx.get('expected_steps')}"
104
- return None
105
-
106
- def ok_but_error_code(ctx):
107
- """step 级:ok=True 却带非空 error_code —— 解析降级(如 codex 空输出
108
- 回落 stdout 尾部)被当成功,值得告警复核。"""
109
- if ctx.get("ok") and ctx.get("error_code"):
110
- return "step 标记成功但携带 error_code=%s(疑似降级输出)" % ctx["error_code"]
111
- return None
112
-
113
- invariants.register("pipeline", "review_no_all_fail_zero", review_no_all_fail_zero)
114
- invariants.register("pipeline", "step_count_consistency", step_count_consistency)
1
+ # -*- coding: utf-8 -*-
2
+ """运行时不变量注册表:质量闸门从 pytest 测试期提升到运行时。
3
+
4
+ 设计稿:docs/migration/01-defense-patterns.md §5F。
5
+ 参考 dsh packages/runtime-diagnostics/invariants/src/index.ts:
6
+ enabled/package_allowlist/package_blocklist 三过滤;失败抛 InvariantError 含 packageName。
7
+
8
+ CodeBee 实施简化为单文件 + pytest 钩子(设计稿说明);register(name, fn) 注册断言,
9
+ run_for(source, ctx) 在指定 source 下跑所有断言并返回失败列表。
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import threading
15
+ from typing import Optional
16
+
17
+ log = logging.getLogger(__name__)
18
+
19
+
20
+ class InvariantError(Exception):
21
+ def __init__(self, source: str, check_name: str, msg: str):
22
+ super().__init__(f"[{source}/{check_name}] {msg}")
23
+ self.source = source
24
+ self.check_name = check_name
25
+
26
+
27
+ class InvariantRegistry:
28
+ """按 source 分组的运行时断言注册表。
29
+
30
+ source 是来源标识(如 "pipeline"/"store"),name 是断言名;
31
+ fn(ctx) -> Optional[str] 返回 None 表示通过,返回字符串即失败消息。
32
+ """
33
+
34
+ def __init__(self):
35
+ self._lock = threading.Lock()
36
+ self._checks: dict = {} # source -> {name: fn}
37
+
38
+ def register(self, source: str, name: str, fn):
39
+ with self._lock:
40
+ self._checks.setdefault(source, {})[name] = fn
41
+ log.debug("invariant registered: %s/%s", source, name)
42
+
43
+ def unregister(self, source: str, name: str = None):
44
+ """移除断言;name=None 时清空整个 source。"""
45
+ with self._lock:
46
+ if source not in self._checks:
47
+ return
48
+ if name is None:
49
+ del self._checks[source]
50
+ else:
51
+ self._checks[source].pop(name, None)
52
+
53
+ def run_for(self, source: str, ctx: dict, *, fail_fast: bool = False):
54
+ """在 source 下跑所有断言。
55
+
56
+ Returns:
57
+ [(source, name, message), ...] 失败列表(空 = 全过)。
58
+
59
+ Raises:
60
+ InvariantError: fail_fast=True 且首个失败。
61
+ """
62
+ fails = []
63
+ with self._lock:
64
+ checks = dict(self._checks.get(source, {}))
65
+ for name, fn in checks.items():
66
+ try:
67
+ msg = fn(ctx)
68
+ except Exception as e:
69
+ msg = f"check raised: {e!r}"
70
+ if msg:
71
+ fails.append((source, name, msg))
72
+ log.warning("invariant FAIL: %s/%s: %s", source, name, msg)
73
+ if fail_fast:
74
+ raise InvariantError(source, name, msg)
75
+ return fails
76
+
77
+ def list(self, source: Optional[str] = None):
78
+ """列出已注册的 source/name;source=None 时全部。"""
79
+ with self._lock:
80
+ if source is None:
81
+ return [(s, n) for s, m in self._checks.items() for n in m]
82
+ return [(source, n) for n in self._checks.get(source, {})]
83
+
84
+
85
+ invariants = InvariantRegistry() # 单例
86
+
87
+
88
+ # === 默认 invariants ===
89
+ def register_default_checks():
90
+ """注册 CodeBee 默认运行时断言。"""
91
+
92
+ def review_no_all_fail_zero(ctx):
93
+ """评审全部 0 分但 run 标 success → 不允许(已锁 test_quality_gates:62-75)。"""
94
+ if (ctx.get("review_scores")
95
+ and all(s == 0 for s in ctx["review_scores"])
96
+ and ctx.get("final_status") == "success"):
97
+ return "评审全部 0 分但 run 标 success"
98
+ return None
99
+
100
+ def step_count_consistency(ctx):
101
+ """实际 step 数与预期不一致。"""
102
+ if ctx.get("actual_steps") != ctx.get("expected_steps"):
103
+ return f"step count {ctx.get('actual_steps')} != expected {ctx.get('expected_steps')}"
104
+ return None
105
+
106
+ def ok_but_error_code(ctx):
107
+ """step 级:ok=True 却带非空 error_code —— 解析降级(如 codex 空输出
108
+ 回落 stdout 尾部)被当成功,值得告警复核。"""
109
+ if ctx.get("ok") and ctx.get("error_code"):
110
+ return "step 标记成功但携带 error_code=%s(疑似降级输出)" % ctx["error_code"]
111
+ return None
112
+
113
+ invariants.register("pipeline", "review_no_all_fail_zero", review_no_all_fail_zero)
114
+ invariants.register("pipeline", "step_count_consistency", step_count_consistency)
115
115
  invariants.register("step", "ok_but_error_code", ok_but_error_code)
@@ -27,7 +27,7 @@ TYPE_DIMENSIONS = {
27
27
  "tech_proposal": "reasoning",
28
28
  "resume": "writing",
29
29
  "bid_doc": "writing", # 标书:正文应答写作量大(合规判断由契约规则约束)
30
- "defect_retro": "reasoning", # 禅道工单:排查定责推理向
30
+ "defect_retro": "reasoning", # 缺陷复盘:排查定责推理向
31
31
  }
32
32
 
33
33
  _KIND_AFFINITY = {
@@ -1,128 +1,128 @@
1
- # -*- coding: utf-8 -*-
2
- """调度事件台账:记录脱敏的候选、决策和结果,支持按运行回放。"""
3
- from __future__ import annotations
4
-
5
- import json
6
- import hashlib
7
- import threading
8
- import time
9
-
10
- from . import paths
11
- from .redact import scrub_text
12
-
13
- LOCK = threading.RLock()
14
-
15
-
16
- def _dispatch_dir():
17
- # 读取动态 DATA_DIR,测试和多实例运行可在启动后重定向数据目录。
18
- return paths.DATA_DIR / "dispatch"
19
-
20
-
21
- def _month_file(day):
22
- return _dispatch_dir() / ("dispatch-%s.jsonl" % day[:7].replace("-", ""))
23
-
24
-
25
- def _text(value, limit=240):
26
- value = str(value or "").replace("\r", " ").replace("\n", " ")
27
- return scrub_text(value, limit=limit)
28
-
29
-
30
- def _candidate(row):
31
- if not isinstance(row, dict):
32
- return {}
33
- return {"agent_id": _text(row.get("agent_id"), 64),
34
- "label": _text(row.get("label"), 80),
35
- "kind": _text(row.get("kind"), 32),
36
- "score": row.get("score", 0),
37
- "reason": _text(row.get("reason"), 240),
38
- "order": row.get("order", 0)}
39
-
40
-
41
- def record_event(run_id="", task_id="", task_type="", difficulty="", role="",
42
- phase="selected", selected="", participants=(), candidates=(),
43
- fallback=(), selection_reason="", result="", verify_pass=None,
44
- review_pass=None, trace_id="", span_id="", parent_event_id=""):
45
- """追加一条事件;仅保存路由元数据,不保存正文、提示词、密钥或文件内容。"""
46
- try:
47
- day = time.strftime("%Y-%m-%d")
48
- event = {
49
- "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
50
- "run_id": _text(run_id, 64), "task_id": _text(task_id, 64),
51
- "task_type": _text(task_type, 32), "difficulty": _text(difficulty, 16),
52
- "role": _text(role, 40), "phase": _text(phase, 16),
53
- "selected": _text(selected, 64),
54
- "participants": [_text(x.get("id") if isinstance(x, dict) else x, 64)
55
- for x in (participants or ())],
56
- "candidates": [_candidate(x) for x in (candidates or ()) if isinstance(x, dict)],
57
- "fallback": [_text(x, 64) for x in (fallback or ())],
58
- "selection_reason": _text(selection_reason, 400),
59
- "result": _text(result, 32),
60
- }
61
- # Trace identifiers are routing metadata only. They deliberately do
62
- # not carry prompt/output contents and remain optional for old callers.
63
- if run_id:
64
- from . import tracing
65
- event["trace_id"] = _text(trace_id or tracing.trace_id(run_id), 64)
66
- if span_id:
67
- event["span_id"] = _text(span_id, 32)
68
- if parent_event_id:
69
- event["parent_event_id"] = _text(parent_event_id, 64)
70
- event["event_id"] = hashlib.sha256(
71
- ("%s|%s|%s|%s|%s|%s" % (
72
- time.time_ns(), run_id, phase, role, selected, result
73
- )).encode("utf-8")
74
- ).hexdigest()[:24]
75
- if verify_pass is not None:
76
- event["verify_pass"] = bool(verify_pass)
77
- if review_pass is not None:
78
- event["review_pass"] = bool(review_pass)
79
- with LOCK:
80
- _dispatch_dir().mkdir(parents=True, exist_ok=True)
81
- with open(_month_file(day), "a", encoding="utf-8") as fh:
82
- fh.write(json.dumps(event, ensure_ascii=False) + "\n")
83
- return event
84
- except Exception:
85
- return None
86
-
87
-
88
- def _iter_events(run_id="", task_type="", limit=100):
89
- """从新到旧读取,满足 limit 即停,避免回放请求解析全部历史。"""
90
- try:
91
- directory = _dispatch_dir()
92
- files = sorted(directory.glob("dispatch-*.jsonl"), reverse=True) \
93
- if directory.is_dir() else []
94
- except Exception:
95
- return []
96
- events = []
97
- for path in files:
98
- try:
99
- lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
100
- for line in reversed(lines):
101
- if not line.strip().startswith("{"):
102
- continue
103
- try:
104
- item = json.loads(line)
105
- except Exception:
106
- continue
107
- if not isinstance(item, dict):
108
- continue
109
- if run_id and item.get("run_id") != run_id:
110
- continue
111
- if task_type and item.get("task_type") != task_type:
112
- continue
113
- events.append(item)
114
- if len(events) >= limit:
115
- return events
116
- except Exception:
117
- continue
118
- return events
119
-
120
-
121
- def replay(run_id="", task_type="", limit=100):
122
- """返回最新的脱敏调度事件,支持按 run_id/task_type 筛选。"""
123
- try:
124
- limit = max(1, min(1000, int(limit)))
125
- except (TypeError, ValueError):
126
- limit = 100
127
- rid, ttype = _text(run_id, 64), _text(task_type, 32)
128
- return _iter_events(rid, ttype, limit)
1
+ # -*- coding: utf-8 -*-
2
+ """调度事件台账:记录脱敏的候选、决策和结果,支持按运行回放。"""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import hashlib
7
+ import threading
8
+ import time
9
+
10
+ from . import paths
11
+ from .redact import scrub_text
12
+
13
+ LOCK = threading.RLock()
14
+
15
+
16
+ def _dispatch_dir():
17
+ # 读取动态 DATA_DIR,测试和多实例运行可在启动后重定向数据目录。
18
+ return paths.DATA_DIR / "dispatch"
19
+
20
+
21
+ def _month_file(day):
22
+ return _dispatch_dir() / ("dispatch-%s.jsonl" % day[:7].replace("-", ""))
23
+
24
+
25
+ def _text(value, limit=240):
26
+ value = str(value or "").replace("\r", " ").replace("\n", " ")
27
+ return scrub_text(value, limit=limit)
28
+
29
+
30
+ def _candidate(row):
31
+ if not isinstance(row, dict):
32
+ return {}
33
+ return {"agent_id": _text(row.get("agent_id"), 64),
34
+ "label": _text(row.get("label"), 80),
35
+ "kind": _text(row.get("kind"), 32),
36
+ "score": row.get("score", 0),
37
+ "reason": _text(row.get("reason"), 240),
38
+ "order": row.get("order", 0)}
39
+
40
+
41
+ def record_event(run_id="", task_id="", task_type="", difficulty="", role="",
42
+ phase="selected", selected="", participants=(), candidates=(),
43
+ fallback=(), selection_reason="", result="", verify_pass=None,
44
+ review_pass=None, trace_id="", span_id="", parent_event_id=""):
45
+ """追加一条事件;仅保存路由元数据,不保存正文、提示词、密钥或文件内容。"""
46
+ try:
47
+ day = time.strftime("%Y-%m-%d")
48
+ event = {
49
+ "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
50
+ "run_id": _text(run_id, 64), "task_id": _text(task_id, 64),
51
+ "task_type": _text(task_type, 32), "difficulty": _text(difficulty, 16),
52
+ "role": _text(role, 40), "phase": _text(phase, 16),
53
+ "selected": _text(selected, 64),
54
+ "participants": [_text(x.get("id") if isinstance(x, dict) else x, 64)
55
+ for x in (participants or ())],
56
+ "candidates": [_candidate(x) for x in (candidates or ()) if isinstance(x, dict)],
57
+ "fallback": [_text(x, 64) for x in (fallback or ())],
58
+ "selection_reason": _text(selection_reason, 400),
59
+ "result": _text(result, 32),
60
+ }
61
+ # Trace identifiers are routing metadata only. They deliberately do
62
+ # not carry prompt/output contents and remain optional for old callers.
63
+ if run_id:
64
+ from . import tracing
65
+ event["trace_id"] = _text(trace_id or tracing.trace_id(run_id), 64)
66
+ if span_id:
67
+ event["span_id"] = _text(span_id, 32)
68
+ if parent_event_id:
69
+ event["parent_event_id"] = _text(parent_event_id, 64)
70
+ event["event_id"] = hashlib.sha256(
71
+ ("%s|%s|%s|%s|%s|%s" % (
72
+ time.time_ns(), run_id, phase, role, selected, result
73
+ )).encode("utf-8")
74
+ ).hexdigest()[:24]
75
+ if verify_pass is not None:
76
+ event["verify_pass"] = bool(verify_pass)
77
+ if review_pass is not None:
78
+ event["review_pass"] = bool(review_pass)
79
+ with LOCK:
80
+ _dispatch_dir().mkdir(parents=True, exist_ok=True)
81
+ with open(_month_file(day), "a", encoding="utf-8") as fh:
82
+ fh.write(json.dumps(event, ensure_ascii=False) + "\n")
83
+ return event
84
+ except Exception:
85
+ return None
86
+
87
+
88
+ def _iter_events(run_id="", task_type="", limit=100):
89
+ """从新到旧读取,满足 limit 即停,避免回放请求解析全部历史。"""
90
+ try:
91
+ directory = _dispatch_dir()
92
+ files = sorted(directory.glob("dispatch-*.jsonl"), reverse=True) \
93
+ if directory.is_dir() else []
94
+ except Exception:
95
+ return []
96
+ events = []
97
+ for path in files:
98
+ try:
99
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
100
+ for line in reversed(lines):
101
+ if not line.strip().startswith("{"):
102
+ continue
103
+ try:
104
+ item = json.loads(line)
105
+ except Exception:
106
+ continue
107
+ if not isinstance(item, dict):
108
+ continue
109
+ if run_id and item.get("run_id") != run_id:
110
+ continue
111
+ if task_type and item.get("task_type") != task_type:
112
+ continue
113
+ events.append(item)
114
+ if len(events) >= limit:
115
+ return events
116
+ except Exception:
117
+ continue
118
+ return events
119
+
120
+
121
+ def replay(run_id="", task_type="", limit=100):
122
+ """返回最新的脱敏调度事件,支持按 run_id/task_type 筛选。"""
123
+ try:
124
+ limit = max(1, min(1000, int(limit)))
125
+ except (TypeError, ValueError):
126
+ limit = 100
127
+ rid, ttype = _text(run_id, 64), _text(task_type, 32)
128
+ return _iter_events(rid, ttype, limit)