vod-devkit 0.4.1 → 0.4.3

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.
package/CHANGELOG.md CHANGED
@@ -226,3 +226,31 @@
226
226
  - fa9c92b refactor(two-phase)+docs: D-resume-commit-1 文档化+场景用例 S83-S86+草稿库读写单源化——docs: decisions.md 决策条目/design.md 承载补充(分层治理口径)/proposal.md 场景用例清单(S83 全链回执逐字、S84 断回合恢复、S85 过期重开链、S86 消费后不可复活);refactor: _drafts_load() 单源化 draft/commit 草稿库读写(现读+TTL 惰性清除,禁双边漂移);+3 场景回归锁;pytest 162 绿+node 9 绿
227
227
  - 9b5e6ec test: golden status 版本快照随 v0.4.0 重录(仅 version 字段,diff 已过目)
228
228
 
229
+
230
+ ## v0.4.2(2026-11-10)
231
+
232
+ - 8d59aa7 chore(ci): 双副本同步门禁三处落地——CI diff 步骤+release.sh 双门禁+npm 包自证
233
+ - 5a8cb00 fix(tools): _warn_if_cloned 可测化——uptime 源注入 + except Exception:pass 收窄
234
+ - a906e82 refactor(tools): 复杂度收敛——submit_voices 四段拆分(207→126 行)+cmd_install 技能/manifest 段抽出+policy 逐规则重读盘收口
235
+ - fdb2f43 docs(pending): D-pending-1 需求/设计文档四件套收尾——S87-S90 场景用例+设计承载补充
236
+ - 03cc4b8 fix(pending): pyflakes f-string 无占位符
237
+ - 4532dee feat(pending): D-pending-1 补强——originalLines 权威拼接,机械剥除模型拼接改字
238
+ - e7660c0 chore(sync): plugins/ 副本同步 D-pending-1 skill 段(双副本同步锁)
239
+ - 14027c4 feat(pending): D-pending-1 无通道场景 pending 反馈队列——落盘+flush+echo 前移(方案 A 四条细节定稿)
240
+ - 53fc675 chore(dsh-release): dsh-vod-devkit 0.2.1——ReceiptGuard 随包(tgz 本地重打包不入 git,dsh-vod-devkit-0.2.1.tgz)
241
+ - baa60b6 feat(scripts): D-behavior-grade-1 e2e_behavior 确认强度分级+分桶+熔断配置化
242
+ - fb62b74 feat(dsh): D-rguard-1 ReceiptGuard 提交侧原文比对闸——会话日志 user 轮原文为真源
243
+ - 3dfdb1c chore(release): golden 随 v0.4.1 重录(仅版本值漂移,人工过目合规)
244
+
245
+
246
+ ## v0.4.3(2026-11-10)
247
+
248
+ - b09a98a fix(dsh): 反馈按钮宽度自测量竞态自锁——右缘锚定根治(只剩文字症状)
249
+ - 5fb7246 fix(dsh): D-uiBase-direct——安装器写 uiBase(浏览器半直连)+ patch 块嵌套铁律
250
+ - 0bbe0dd fix(release): dsh 壳并进发版流程——版本落点表+同版 pack 自证+双包发布清单(实锤:dsh 游离发版外 npm 停 0.1.1 半月,按包名装机全旧)
251
+ - fc32138 fix(behavior): reconcile 双锚点归属——剥前缀行不再误归 fabricated(首夜校准债清偿)
252
+ - 75eda86 feat(behavior): D-behavior-adversarial-1 C 档反例集+引擎接口对账+首夜实测记档
253
+ - 3cd4939 fix(packaging): test_packaging 去未用 import(pyflakes 门禁)
254
+ - 21777fc chore(sync): build-info 对齐 HEAD(golden 重录提交后补跑 sync,包指纹=HEAD 纪律)
255
+ - cb79134 chore(release): golden 随 v0.4.2 重录(仅版本值漂移,人工过目合规)
256
+
package/bin/vod-devkit CHANGED
@@ -363,8 +363,11 @@ def _install_dsh(args, packs: str) -> Path:
363
363
  --product 安装期硬校验(cmd_install 已先行,到达此处必已过)+ 校验先于
364
364
  add + 幂等写 profile cordis.patch.yml config override。
365
365
  生效通道真机实测(2026-11-06,dsh 0.2.1-rc.5):profile cordis.patch.yml
366
- 的 id-targeted config override 是工具壳读取 product/apiBase/confirmWrites
367
- 的唯一运行时通道(启动 banner + 桩引擎提交链实证)。dsh plugin add 会自建
366
+ 的 id-targeted config override 是工具壳读取 product/apiBase/uiBase/
367
+ confirmWrites 的唯一运行时通道(启动 banner + 桩引擎提交链实证)。
368
+ uiBase(D-uiBase-direct):浏览器半(反馈按钮)直连引擎——apiBase 是
369
+ server 半(Node)自用,浏览器同源策略下用不上;缺 uiBase 时 UI 提交
370
+ 发往 dsh 同源(404→本地暂存),嵌入方真机实锤。dsh plugin add 会自建
368
371
  profile,无需前置。"""
369
372
  dsh = shutil.which("dsh")
370
373
  profile = (getattr(args, "dsh_profile", "") or "").strip()
@@ -390,16 +393,20 @@ def _install_dsh(args, packs: str) -> Path:
390
393
  # name 行必须保留:cordis.patch.yml 的 insert 块靠 name 绑定 client 半
391
394
  # (反馈按钮)——只写 id+config 会在重装幂等替换时把 name 吞掉,UI 静默
392
395
  # 失激活(2026-11-06 真机实锤:重装后入口消失)
393
- block = ("- id: vod-devkit\n"
394
- " name: dsh-vod-devkit\n"
395
- " config:\n"
396
- f" product: {args.product}\n"
397
- f" apiBase: {args.java_api_base}\n"
398
- " # headless 无审批通道:原生 ask 门禁会永久阻断写工具(四宿主实测实锤:\n"
399
- " # requires approval, but no approval channel)。同意确认由 SKILL 话术层\n"
400
- " # 承担(draft→用户确认→commit / 明确指令直发),web 端如需硬门禁按\n"
401
- " # profile 覆盖回 true。\n"
402
- " confirmWrites: false\n")
396
+ # 嵌套铁律(2026-11-10 真机实锤):块必须缩进在 `- insert:` 之下——平铺
397
+ # 形态被 dsh 组合层丢弃,插件掉出组合树(banner/工具/UI 全消失)。
398
+ block = ("- insert:\n"
399
+ " - id: vod-devkit\n"
400
+ " name: dsh-vod-devkit\n"
401
+ " config:\n"
402
+ f" product: {args.product}\n"
403
+ f" apiBase: {args.java_api_base}\n"
404
+ f" uiBase: {args.java_api_base}\n" # D-uiBase-direct:浏览器半直连引擎
405
+ " # headless 无审批通道:原生 ask 门禁会永久阻断写工具(四宿主实测实锤:\n"
406
+ " # requires approval, but no approval channel)。同意确认由 SKILL 话术层\n"
407
+ " # 承担(draft→用户确认→commit / 明确指令直发),web 端如需硬门禁按\n"
408
+ " # profile 覆盖回 true。\n"
409
+ " confirmWrites: false\n")
403
410
  try:
404
411
  written = _upsert_dsh_patch(patch, block)
405
412
  except Exception as e:
@@ -417,18 +424,28 @@ def _install_dsh(args, packs: str) -> Path:
417
424
 
418
425
 
419
426
  def _find_dsh_block(lines):
420
- """定位 cordis.patch.yml 中 `- id: vod-devkit` 顶层块的 (start, end);
421
- 不存在返回 (None, None)。块边界=下一顶层元素行(`- ` 开头)或 EOF。
422
- install 的幂等 upsert 与 uninstall 的摘除共用同一边界语义(单一实现,
423
- 防两处扫描规则漂移——双载体漂移已在本仓 dsh/UI 壳实锤过)。"""
427
+ """定位 cordis.patch.yml 中 vod-devkit 块的 (start, end);不存在返回
428
+ (None, None)。块边界=下一顶层元素行(`- ` 开头)或 EOF。
429
+ 嵌套铁律(真机实锤,2026-11-10 复现):dsh 只认缩进在 `- insert:` 下
430
+ 的块——平铺 `- id:` 会被组合层丢弃=插件整个掉出组合树(banner/工具/
431
+ UI 全消失)。当命中行是嵌套形态(带缩进)时,start 向上归并到其
432
+ `- insert:` 组头,整组替换;平铺旧形态(历史安装器写的)按原语义
433
+ 顶格替换。install 的幂等 upsert 与 uninstall 的摘除共用本边界语义
434
+ (单一实现,防两处扫描规则漂移——双载体漂移已在本仓 dsh/UI 壳实锤过)。"""
424
435
  for i, ln in enumerate(lines):
425
436
  if ln.strip().startswith("- id: vod-devkit"):
437
+ start = i
438
+ if ln[:1] == " ": # 嵌套形态:向上归并组头(- insert: 或其它顶层 -)
439
+ for k in range(i - 1, -1, -1):
440
+ if lines[k].startswith("- "):
441
+ start = k
442
+ break
426
443
  end = len(lines)
427
- for j in range(i + 1, len(lines)):
444
+ for j in range(start + 1, len(lines)):
428
445
  if lines[j].startswith("- "): # 下一顶层元素:本块结束
429
446
  end = j
430
447
  break
431
- return i, end
448
+ return start, end
432
449
  return None, None
433
450
 
434
451
 
@@ -447,6 +464,17 @@ def _upsert_dsh_patch(patch: Path, block: str) -> bool:
447
464
  else:
448
465
  new = lines[:start] + block.splitlines() + lines[end:]
449
466
  new_text = "\n".join(new).rstrip("\n") + "\n"
467
+ # 空 `- insert:` 组头清理(损坏态自愈):孤儿组头(下一个顶层元素前无
468
+ # 子项)来自历史平铺替换的残留——留它在 dsh 组合层是空组,可能拖垮
469
+ # 整个 patch 解析。upsert 后顺手摘除(幂等,不碰正常组)。
470
+ cleaned = []
471
+ for idx, ln in enumerate(new):
472
+ if ln.strip() == "- insert:":
473
+ nxt = new[idx + 1] if idx + 1 < len(new) else ""
474
+ if nxt.startswith("- ") or (not nxt.strip() and idx + 2 >= len(new)):
475
+ continue # 孤儿组头:下一行已是新顶层元素(无子项)→ 摘除
476
+ cleaned.append(ln)
477
+ new_text = "\n".join(cleaned).rstrip("\n") + "\n"
450
478
  old_text = patch.read_text(encoding="utf-8") if patch.exists() else ""
451
479
  if new_text == old_text:
452
480
  return False
@@ -666,6 +694,16 @@ def cmd_install(args):
666
694
  print(f"[vod-devkit] 已显式解除 codex 采集熔断(安装成功),审计已记录:{audit}")
667
695
 
668
696
  # G1 修复:技能全量拷贝(目录型技能+平铺规则文档),按 packs 过滤
697
+ oc_skills, cx_skills = _install_skills(target, packs)
698
+
699
+ _write_install_manifest(args, target, packs, bound_product, mcp_conf,
700
+ oc_skills, cx_skills)
701
+
702
+
703
+ def _install_skills(target: str, packs: str):
704
+ """技能段:全量拷贝(目录型技能+平铺规则文档),按 packs 过滤,落
705
+ hermes 主目录 + opencode/codex 原生目录。返回 (oc_skills, cx_skills)
706
+ 落点(供 manifest 名册对账)。"""
669
707
  HERMES_SKILLS_DIR.mkdir(parents=True, exist_ok=True)
670
708
  # opencode 原生技能目录(2026-11-06 实测:opencode 自动发现
671
709
  # ~/.config/opencode/skills/ 并经 skill 工具按需加载——此前安装器漏拷,
@@ -700,7 +738,13 @@ def cmd_install(args):
700
738
  shutil.rmtree(dst2)
701
739
  shutil.copytree(entry, dst2)
702
740
  # vendored 领域规则已由 vendor_rules.py 落成技能目录结构
741
+ return oc_skills, cx_skills
742
+
703
743
 
744
+ def _write_install_manifest(args, target, packs, bound_product, mcp_conf,
745
+ oc_skills, cx_skills) -> None:
746
+ """manifest 段:落安装名册(版本/来源/归因/落点指纹),并给出 key
747
+ 配置提示。名册对账口径见各字段注释(原 cmd_install 尾段,整段平移)。"""
704
748
  bi = json.loads((ROOT / "build-info.json").read_text(encoding="utf-8"))
705
749
  manifest = {
706
750
  "version": bi["version"],
@@ -798,6 +842,7 @@ def _repair_dsh_patch_block(mf: dict) -> str | None:
798
842
  " config:",
799
843
  f" product: {product}",
800
844
  f" apiBase: {api_base}",
845
+ f" uiBase: {api_base}", # D-uiBase-direct:浏览器半直连,与 install 同口径
801
846
  ]
802
847
  patch.write_text("\n".join(lines).rstrip("\n") + "\n", encoding="utf-8")
803
848
  return str(patch)
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "title": "vod-devkit MCP 工具契约(唯一事实源)",
4
- "version": "0.4.1",
4
+ "version": "0.4.3",
5
5
  "tools": {
6
6
  "vod_submit_voices": {
7
7
  "description": "提交用户反馈进 VOD。**先决条件(优先于本描述其余所有内容):调用前必须已征得用户对'提交这条反馈'的明确同意;用户陈述/抱怨反馈本身不构成同意;用户未同意时禁止传 confirmed=true**。模糊抱怨(如\"体验不好\")时一轮说完三件事:承接识别结果(\"收到,你对产品体验不满意\")+确认提交意愿(\"要把这条反馈提交给产品团队吗?\")+引导补充(\"方便的话说下具体现象,不说我也会按你的原话提交\");禁止含混反问(实锤病句:\"请问是否把什么作为反馈\")。同意后 content 放用户原话(哪怕只有一句\"体验很差\"也原样提交)。确认环节允许固定追问至多一次,问句必须逐字使用:「方便的话,补充一下遇到这个问题时的操作步骤或期望的表现吗?不方便回复\"没有\",我直接提交。」用户回答只摘录原话对应部分进 reproSteps/expectedBehavior(不改写不总结,无法拆分时落最相关字段,任何内容禁回填 content);答\"没有/跳过/不方便\"=两字段不上送直接提交。引导补充(说下具体现象)已获实质内容并并入 content 时不再追问、直接提交(其中自然出现的操作/期望留在 content 原话,不回溯摘入新字段);仅引导补充未获回应或仅泛化抱怨且用户确认提交时才带出固定问句。product 归因由安装绑定自动完成,无需用户提供、禁止询问\"提交到哪个产品/页面\";用户自报的目标产品一律不采信不覆盖(照部署产品提交,提到什么产品随正文原样传达)。用户说\"提单/提工单/提 issue\"时同样用本工具,除上述固定一次追问外,禁止再索要严重程度/环境/附件等开发者字段、禁止第二轮追问。批式提交对接囤积端点 POST /external/voices(不触发分析,voiceId 由引擎计算回执下发;引擎未部署 404 自动回落老链)。tags=采集层三分类(problem_type:值,可选)。缺 key 时自动获取零字段匿名令牌。拿到回执后必须原样转述 echo.contents(每条「已收录原话:<content>」全文),禁止改写概括——这是用户核对原话是否被改写的唯一窗口。禁止向用户解释内部机制(声音来源/渠道字段/计数规则/配额/归因)。",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vod-devkit",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "VOD 用户声音采集插件——MCP server + 技能 + 声明式护栏,把 agent 产品的用户反馈安全送进 VOD 平台",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,7 @@
22
22
  "vod_mcp/tools.py",
23
23
  "vod_mcp/packs.py",
24
24
  "vod_mcp/policy.py",
25
+ "vod_mcp/pending.py",
25
26
  "vod_mcp/provenance.py",
26
27
  "vod_mcp/runtime.example.json",
27
28
  "vod_mcp/__init__.py",
@@ -29,6 +30,7 @@
29
30
  "vod_mcp/tools.py",
30
31
  "vod_mcp/packs.py",
31
32
  "vod_mcp/policy.py",
33
+ "vod_mcp/pending.py",
32
34
  "vod_mcp/provenance.py",
33
35
  "vod_mcp/runtime.example.json",
34
36
  "plugins/vod-devkit/.codex-plugin/plugin.json",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vod-devkit",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "VOD user-feedback collection: structured voice capture and submission to the VOD hoarding endpoint.",
5
5
  "keywords": [
6
6
  "feedback",
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.4.1",
3
- "commitSha": "a0cf5c26e2798205007ae693f2d3400d0dea7729",
4
- "builtAt": "2026-11-09T17:47:25",
2
+ "version": "0.4.3",
3
+ "commitSha": "b09a98a00354785d776e584c2474fa2b96f9ea64",
4
+ "builtAt": "2026-11-10T03:33:12",
5
5
  "sourceRemote": "https://gitcode.com/xiaowu2119/vod-devkit.git"
6
6
  }
@@ -174,6 +174,23 @@ version: 1
174
174
  4. 拿到回执 → 对用户说人话:"已收录,产品团队会看到这条反馈"——
175
175
  **voiceId 不展示给终端用户**(编号噪音),仅供 agent 对账用;
176
176
  用户追问"提交了吗"时 agent 用 voiceId/taskId 核对后回答状态
177
+ 5. **无通道 fallback(D-pending-1,插件未安装/无 vod 工具时)**:
178
+ - 落盘:把反馈追加写入 `~/.vod-devkit/pending-feedback.jsonl`(JSONL 一行
179
+ 一条,字段 idempotencyKey=sha1(content+confirmAt+source)/content/tags/
180
+ confirmAt/createdAt=当前时间/source=宿主名/echoShown/status="pending"/
181
+ originalLines=用户原话逐行数组(多轮/多行原话必填——flush 以它拼接为
182
+ 权威 content,机械剥除模型拼接时新增的标点连接词,S73 改字技术锁;
183
+ 模型自拟 content 仅供比对))。
184
+ **条目级幂等键,内容级去重归引擎**(同内容重提=skipped),禁止用本键
185
+ 判"用户重复反馈"。
186
+ - echo 前移(两场景诚实区分):能拿到用户输入原文 → 落盘前与 content
187
+ 比对,不一致以原文为准;拿不到 → 先向用户逐字回显将暂存的内容再落盘、
188
+ echoShown=true——这是概率性防线非确定性闸,不假装解决保真。
189
+ - 对用户只说人话:"反馈已暂存(内容:……)。当前环境暂不支持直接提交,
190
+ 恢复后会自动补交。" **禁止出现文件路径/profile/工具名/幂等键**(内部
191
+ 细节进日志不进用户提示;路径属 CWE-209 敏感信息)。
192
+ - 补交:插件恢复后任一次 vod_submit_voices 成功会自动 flush pending
193
+ (引擎幂等防重,用户无需操作);超 30 天未补交的条目会被标记过期。
177
194
 
178
195
  ## 纪律
179
196
 
@@ -210,3 +227,13 @@ version: 1
210
227
  - 渠道/来源一律不提交、不向用户提及(引擎按链路固定赋值)
211
228
  - 提单/工单类诉求:不需要"复现步骤/严重程度/优先级"等开发者工单字段——
212
229
  用户原话即完整提交物,缺什么由运营侧补充
230
+
231
+ ## 教训(D-pending-1 落地过程实锤)
232
+
233
+ - **skill 留白即兴实锤**:无通道场景旧版 skill 未规定任何格式,agent 即兴
234
+ 发明 JSON「暂存记录」输出到对话(工具名/枚举外露+伪落盘=有记录的丢失)。
235
+ 定律再次验证:凡留白处模型必自由裁量——fallback/异常路径必须在 skill 里
236
+ 格式定死,能格式锁的绝不交给话术。
237
+ - **拼接改字第 N 次实锤与机械锁**:模型把两行无标点原话拼成「差劲。使用
238
+ …不流畅。」(S73 判定例在仍违)——originalLines 字段+flush 权威拼接=
239
+ 确定性剥除,规则层锁不死的行为下沉技术层。
@@ -5,7 +5,7 @@
5
5
  2. 外部无 DB 直连路径(护栏 deny 兜底)
6
6
  3. 任务 ID 是唯一对账主键,写类工具返回一律携带
7
7
  """
8
- __version__ = "0.4.1"
8
+ __version__ = "0.4.3"
9
9
  # 默认上游:VOD 测试环境。外部用户本机无 VOD,回环默认值=装完即坏;
10
10
  # 生产地址定型后只改这一处(tools.py 与 bin/vod-devkit 共用本常量)。
11
11
  DEFAULT_JAVA_BASE = "https://vod-dev.topxtopx.com"
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env python3
2
+ """D-pending-1 无通道场景 pending 反馈队列(2026-11-09,方案 A 四条执行细节定稿)。
3
+
4
+ 背景:宿主 VOD 插件未安装时,vod-feedback-collect skill 兜底把「用户已确认
5
+ 意愿的反馈」落盘为 pending,等插件/通道恢复后由 submit_voices 顺手 flush。
6
+ 此前「暂存」只存在于会话输出(全盘 grep 零落盘实锤),会话结束=有记录的丢失。
7
+
8
+ 四条定稿口径:
9
+ 1. 幂等键 = sha1(content + confirmAt + source):**条目级去重**(同一条 flush
10
+ 两次可识别);**内容级去重由引擎 uk_voice_id 负责**(voiceId=f(source,
11
+ content,nonce),同内容重提=skipped)——两 层分工,禁止混用。
12
+ 2. flush 清理 = 重写 + 原子 rename(tmp+os.replace):文件里永远只有真正
13
+ 待提交的条目;失败的条目保留 status=pending,不因尝试过就标已处理。
14
+ flush 同步执行但失败只记日志、不回滚主提交(文件个位数行,毫秒级;
15
+ 异步留作扩展点,当前规模不值得引入并发写竞态)。
16
+ 3. echo 两场景(skill 层口径,本模块只承载 echoShown 标记):能拿到用户
17
+ 输入原文 → 落盘前比对不一致以原文为准;拿不到 → echoShown=true,
18
+ 承认是概率性防线非确定性闸非安全边界。
19
+ 4. 生命周期:createdAt 超过 EXPIRE_DAYS(30) 的条目 flush 时标记 expired
20
+ 并从文件剔除(不搞定时任务);单次 flush 上限 CAP=100 条(按 createdAt
21
+ 最早优先),文件过大是已知扩展点。
22
+
23
+ 双通道消息分离:用户侧只见「已暂存,恢复后自动补交」,路径/profile/
24
+ 幂等键/flush 结果全部只进日志。
25
+ """
26
+ import datetime
27
+ import hashlib
28
+ import json
29
+ import os
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ PENDING_DIRNAME = ".vod-devkit"
34
+ PENDING_FILENAME = "pending-feedback.jsonl"
35
+ CAP = 100
36
+ EXPIRE_DAYS = 30
37
+ STATUS_PENDING = "pending"
38
+ STATUS_DONE = "done"
39
+ STATUS_EXPIRED = "expired"
40
+
41
+
42
+ def default_path() -> Path:
43
+ return Path(os.path.expanduser("~")) / PENDING_DIRNAME / PENDING_FILENAME
44
+
45
+
46
+ def entry_key(content: str, confirm_at: str, source: str) -> str:
47
+ """条目级幂等键(内容级去重由引擎 uk_voice_id 负责,见模块 docstring)。"""
48
+ return hashlib.sha1(
49
+ (str(content) + "\x00" + str(confirm_at) + "\x00" + str(source)).encode("utf-8")
50
+ ).hexdigest()
51
+
52
+
53
+ def make_entry(content: str, tags: list | None, confirm_at: str, source: str,
54
+ echo_shown: bool = False, original_lines: list | None = None) -> dict:
55
+ now = datetime.datetime.now().isoformat(timespec="seconds")
56
+ return {
57
+ "idempotencyKey": entry_key(content, confirm_at, source),
58
+ "content": str(content),
59
+ "tags": list(tags or []),
60
+ "confirmAt": str(confirm_at),
61
+ "createdAt": now,
62
+ "source": str(source),
63
+ "echoShown": bool(echo_shown),
64
+ "status": STATUS_PENDING,
65
+ **({"originalLines": [str(x) for x in original_lines]}
66
+ if original_lines else {}),
67
+ }
68
+
69
+
70
+ def canonical_content(entry: dict) -> str:
71
+ """权威 content:带 originalLines 的条目以分行原文 `\n` 拼接为真源
72
+ (S73 判定例的技术锁——模型拼接时新增的标点/连接词在此被机械剥除,
73
+ 实锤:模型把两行无标点原话拼成「差劲。使用…不流畅。」)。无
74
+ originalLines 的条目回落 entry 自身 content(行为不变)。"""
75
+ lines = entry.get("originalLines")
76
+ if isinstance(lines, list) and lines:
77
+ return "\n".join(str(x) for x in lines)
78
+ return str(entry.get("content", ""))
79
+
80
+
81
+ def load_entries(path: Path) -> list[dict]:
82
+ """读全量(坏行容忍跳过——手工写入/中断不炸 flush)。"""
83
+ if not path.exists():
84
+ return []
85
+ out = []
86
+ for line in path.read_text(encoding="utf-8").splitlines():
87
+ line = line.strip()
88
+ if not line:
89
+ continue
90
+ try:
91
+ obj = json.loads(line)
92
+ if isinstance(obj, dict):
93
+ out.append(obj)
94
+ except (ValueError, TypeError):
95
+ continue
96
+ return out
97
+
98
+
99
+ def append_entry(path: Path, entry: dict) -> None:
100
+ """追加一行(原子性由「单行一次 write+flush」保证;坏行由 load 容忍)。"""
101
+ path.parent.mkdir(parents=True, exist_ok=True)
102
+ with open(path, "a", encoding="utf-8") as f:
103
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
104
+ f.flush()
105
+ os.fsync(f.fileno())
106
+
107
+
108
+ def save_entries(path: Path, entries: list[dict]) -> None:
109
+ """重写 + 原子 rename(D-pending-1 口径 2:tmp + os.replace)。"""
110
+ path.parent.mkdir(parents=True, exist_ok=True)
111
+ tmp = path.with_suffix(path.suffix + ".tmp")
112
+ with open(tmp, "w", encoding="utf-8") as f:
113
+ for e in entries:
114
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
115
+ f.flush()
116
+ os.fsync(f.fileno())
117
+ os.replace(tmp, path)
118
+
119
+
120
+ def plan_flush(entries: list[dict], now: datetime.datetime | None = None,
121
+ cap: int = CAP, expire_days: int = EXPIRE_DAYS) -> dict[str, Any]:
122
+ """flush 计划(纯函数):to_flush(pending、未过期、最早优先、上限 cap)、
123
+ expired(超期条目,调用方剔除+告知)、kept(留在文件里的其余条目)。"""
124
+ now = now or datetime.datetime.now()
125
+ deadline = now - datetime.timedelta(days=expire_days)
126
+ pending, expired = [], []
127
+ for e in entries:
128
+ created = str(e.get("createdAt", ""))[:19]
129
+ try:
130
+ created_dt = datetime.datetime.fromisoformat(created)
131
+ except ValueError:
132
+ created_dt = now # 无 createdAt 的手工行不误杀
133
+ if e.get("status") == STATUS_PENDING and created_dt < deadline:
134
+ expired.append(e)
135
+ elif e.get("status") == STATUS_PENDING:
136
+ pending.append(e)
137
+ pending.sort(key=lambda e: str(e.get("createdAt", "")) or "9999-12-31T23:59:59")
138
+ return {"to_flush": pending[:cap], "expired": expired,
139
+ "kept": [e for e in pending[cap:]]}
@@ -23,7 +23,7 @@ def _resolve_ref(policy: dict, value):
23
23
  return value
24
24
 
25
25
 
26
- def _match_tool_rule(rule: dict, tool: str, params: dict) -> bool:
26
+ def _match_tool_rule(policy: dict, rule: dict, tool: str, params: dict) -> bool:
27
27
  m = rule["match"]
28
28
  if m.get("tool") != tool:
29
29
  return False
@@ -36,7 +36,7 @@ def _match_tool_rule(rule: dict, tool: str, params: dict) -> bool:
36
36
  if "equals" in m:
37
37
  return actual == m["equals"]
38
38
  if "gt" in m:
39
- limit = _resolve_ref(load_policy(), m["gt"])
39
+ limit = _resolve_ref(policy, m["gt"])
40
40
  try:
41
41
  if isinstance(actual, list):
42
42
  return len(actual) > int(limit)
@@ -44,7 +44,7 @@ def _match_tool_rule(rule: dict, tool: str, params: dict) -> bool:
44
44
  except (TypeError, ValueError):
45
45
  return False
46
46
  if "notIn" in m:
47
- whitelist = _resolve_ref(load_policy(), m["notIn"])
47
+ whitelist = _resolve_ref(policy, m["notIn"])
48
48
  if not isinstance(whitelist, (list, tuple)):
49
49
  return False
50
50
  return actual not in whitelist
@@ -56,7 +56,7 @@ def check_tool_call(policy: dict, tool: str, params: dict) -> list:
56
56
  hits = []
57
57
  for rule in policy.get("rules", []):
58
58
  if "tool" in rule.get("match", {}):
59
- if _match_tool_rule(rule, tool, params):
59
+ if _match_tool_rule(policy, rule, tool, params):
60
60
  hits.append(rule)
61
61
  return hits
62
62