@tea-agent/loop-agent 0.40.0-next.2 → 0.40.0-next.4

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 (140) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +9 -2
  3. package/README.md +2 -2
  4. package/dist/application/task-lifecycle/advance.js +12 -0
  5. package/dist/build-stamp.json +3 -3
  6. package/dist/cli/update/runtime-activity.js +1 -29
  7. package/dist/commands/dag-rerun.js +1 -1
  8. package/dist/executors/dag-pi-executor.js +46 -5
  9. package/dist/executors/shell-executor.js +28 -0
  10. package/dist/executors/workspace-write-snapshot.js +68 -0
  11. package/dist/shared/dag-prompt-override.js +4 -5
  12. package/dist/shared/update/npm-client.js +33 -11
  13. package/dist/task/config-types.js +10 -0
  14. package/dist/task/contract/apply.js +11 -1
  15. package/dist/task/contract/constants.js +2 -0
  16. package/dist/task/contract/hash.js +3 -0
  17. package/dist/task/contract/observe.js +25 -4
  18. package/dist/task/contract/paths.js +2 -1
  19. package/dist/task/contract/project.js +15 -1
  20. package/dist/task/contract/schema.js +2 -0
  21. package/dist/task/contract/transaction.js +12 -0
  22. package/dist/task/source-prepare/completeness.js +188 -0
  23. package/dist/task/source-prepare/fragment-inventory.js +474 -0
  24. package/dist/task/source-prepare/index.js +3 -0
  25. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  26. package/dist/task/source-prepare/ledger-review.js +214 -0
  27. package/dist/task/source-prepare/ledger.js +545 -0
  28. package/dist/task/source-prepare/prepare.js +262 -1
  29. package/dist/task/source-prepare/semantic-intake.js +19 -3
  30. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  31. package/dist/task/source-prepare/types.js +22 -0
  32. package/dist/worker/cli.js +12 -26
  33. package/dist/worker/console/console-handoff.js +82 -0
  34. package/dist/worker/console/console-update-and-init.js +115 -0
  35. package/dist/worker/console/console-update-runtime.js +84 -0
  36. package/dist/worker/console/draft-store.js +49 -0
  37. package/dist/worker/console/operation-store.js +1 -1
  38. package/dist/worker/console/operator-actions.js +129 -4
  39. package/dist/worker/console/operator-surface-health.js +1 -0
  40. package/dist/worker/console/prd-intake-bridge.js +13 -0
  41. package/dist/worker/console/routes.js +3 -0
  42. package/dist/worker/console/server.js +73 -5
  43. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DLMldIE8.js → abnfDiagram-N423BO3Z-CTx1TrNa.js} +1 -1
  44. package/dist/worker/console/static/assets/{arc-DVOg1dSW.js → arc-B4i9cVxX.js} +1 -1
  45. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-715v7joo.js → architectureDiagram-T3A2C74G-BAXE8_Rl.js} +1 -1
  46. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BtMEGtAQ.js → blockDiagram-VBNYF7ZC-C5Xh59at.js} +1 -1
  47. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-qUxXsdxu.js → c4Diagram-5PPSVZJV-B_asOzAu.js} +1 -1
  48. package/dist/worker/console/static/assets/channel-Dj_4Moei.js +1 -0
  49. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BYMag72f.js → chunk-2GRJ4B5K-wRO_iRNc.js} +1 -1
  50. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-C5jt5rtx.js → chunk-2Q5K7J3B-ByOaSh_G.js} +1 -1
  51. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DvZghfS2.js → chunk-5RXB4S5H-DjLzudan.js} +1 -1
  52. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CXutxAmY.js → chunk-5VM5RSS4-JCNGkXYT.js} +1 -1
  53. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-BkANIDWk.js → chunk-6Q2QTUOP-BhrPXXMZ.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-Bwy1wwlr.js → chunk-GF5L2VYU-TJ5JuEBT.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-D3pWYVCG.js → chunk-JWPE2WC7-VVthn_mD.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DRzjzmFD.js → chunk-KBJHAD2P-D60-Mny4.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-C4xXDxXL.js → chunk-RYQCIY6F-zXv7aVye.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BngIZ90b.js → chunk-XXDRQBXY-By9VQoi1.js} +1 -1
  59. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-C0YYAyCa.js +1 -0
  60. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-C0YYAyCa.js +1 -0
  61. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-B40ACoFn.js → cose-bilkent-JH36ORCC-C4zQLe-M.js} +1 -1
  62. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BE-1ZRAI.js → cynefin-VYW2F7L2-wh5N2ReN.js} +1 -1
  63. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BoYbwVTh.js → cynefinDiagram-MW4NZA55-Dlu5wIqs.js} +1 -1
  64. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B5-KA0fK.js → dagre-VZM6K2ZE-CrDgthc6.js} +1 -1
  65. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DJpCToT5.js → diagram-7IWD3JNH-zN1clg27.js} +1 -1
  66. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-De8R04Ng.js → diagram-B4RE2ZJO-BN-o7J7-.js} +1 -1
  67. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-BU1N8DiA.js → diagram-LBJQPF4R-C8SuPt0d.js} +1 -1
  68. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BUUUzSYI.js → diagram-Q27KOJAE-BoizuHbZ.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-UB23O5K3-zLoT1RC4.js → diagram-UB23O5K3-BzUzXixG.js} +1 -1
  70. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-_q4-4N8c.js → ebnfDiagram-BXEA7PRR-Ev3lA4Cf.js} +1 -1
  71. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CTqzoNSL.js → erDiagram-JOGREHBK-GALUzRbs.js} +1 -1
  72. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CMKSYKJM.js → flowDiagram-UKHOOZJN-CZJN65Sb.js} +1 -1
  73. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Dj6U8Sb7.js → ganttDiagram-PKOTCBZU-JLB9OESl.js} +1 -1
  74. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-BfoxVYky.js → gitGraphDiagram-DS77QQ5N-CcvCr4GD.js} +1 -1
  75. package/dist/worker/console/static/assets/{index-CA0nQEbb.js → index-CW88Fjbw.js} +81 -81
  76. package/dist/worker/console/static/assets/index-DP0ZJl39.css +1 -0
  77. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-T5NfvHGV.js → infoDiagram-6WML65LV-HG5z7aVg.js} +1 -1
  78. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BEhUMkut.js → ishikawaDiagram-WSZJBQD7-BHEu9chR.js} +1 -1
  79. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-B2Ld6nNt.js → journeyDiagram-NVQOT4AX-Cp_Up8-a.js} +1 -1
  80. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-nV9T85yS.js → kanban-definition-27J2QSJJ-DvVeY-em.js} +1 -1
  81. package/dist/worker/console/static/assets/{linear-CIO1zDYh.js → linear-aGmcjgTn.js} +1 -1
  82. package/dist/worker/console/static/assets/{mermaid.core-B_ucAqLq.js → mermaid.core-Biyo-tqA.js} +5 -5
  83. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-BIA3VNcZ.js → mindmap-definition-FAOFIHXS-DyxY2pIb.js} +1 -1
  84. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CNzLjNV3.js → pegDiagram-VL7TDLO6-CkdGuc50.js} +1 -1
  85. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-PWytzfc_.js → pieDiagram-7S7Q4E2Y-NNQI9xVR.js} +1 -1
  86. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-CS0wGoIq.js → quadrantDiagram-CIZ2JOQS-PAJkuz_G.js} +1 -1
  87. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-C3Wsqph8.js → railroadDiagram-AXF67PYL-ZwrQod0O.js} +1 -1
  88. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DF6FDTYg.js → requirementDiagram-LRYGKXZP-D3ZfrzM2.js} +1 -1
  89. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BdQUJm6y.js → sankeyDiagram-W5VNT64P-DDGFmWk5.js} +1 -1
  90. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-Bv9rppGg.js → sequenceDiagram-SI44F4Z6-DO6mmXTA.js} +1 -1
  91. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-C3Hpvb_B.js → sizeCapture-X5ZJPWSS-DMbCQiJt.js} +1 -1
  92. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-CZOWLpno.js → stateDiagram-OKZ733FA-Di_YUEfC.js} +1 -1
  93. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DrdDvela.js +1 -0
  94. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-CPQRIZx5.js → swimlanes-SLNWSIFB-Bn2PphNJ.js} +2 -2
  95. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DPkEAULl.js +8 -0
  96. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-CkwM9BgA.js → timeline-definition-Z64GVDOM-DPh8pRsp.js} +1 -1
  97. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-wGSoDzYc.js → vennDiagram-T6HMQDX7-GMfl26pW.js} +1 -1
  98. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-GNVas2gx.js → wardleyDiagram-T6FBY63Y-DTlmVrmF.js} +1 -1
  99. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-C5USnHw7.js → xychartDiagram-ELKLHX3M-YGBjKAS5.js} +1 -1
  100. package/dist/worker/console/static/index.html +2 -2
  101. package/dist/worker/console/static-src/app/console-types.js +40 -1
  102. package/dist/worker/console/static-src/app/useOperatorActions.js +5 -0
  103. package/dist/worker/console/static-src/app/useTaskWizard.js +73 -1
  104. package/dist/worker/observability/init-runtime-activity.js +26 -0
  105. package/dist/worker/observe/node-input.js +88 -2
  106. package/dist/worker/observe/routes.js +188 -0
  107. package/dist/worker/observe/static/api.js +3 -3
  108. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  109. package/dist/worker/observe/static/dag-node-purpose.js +203 -0
  110. package/dist/worker/observe/static/format.js +37 -0
  111. package/dist/worker/observe/static/index.html +5 -0
  112. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  113. package/dist/worker/observe/static/prompt-restart-candidates.js +36 -0
  114. package/dist/worker/observe/static/state.js +2 -2
  115. package/dist/worker/observe/static/styles.css +357 -35
  116. package/dist/worker/observe/static/views/dag-graph.js +4 -2
  117. package/dist/worker/observe/static/views/dag-inspector.js +531 -78
  118. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  119. package/dist/worker/observe/static/views/dag.js +4 -3
  120. package/dist/worker/observe/static/views/task.js +55 -0
  121. package/dist/workflows/dag/frontend-implementation-contract.js +88 -2
  122. package/dist/workflows/dag/frontend-plan-render.js +24 -0
  123. package/dist/workflows/dag/frontend-prewrite-gate.js +197 -0
  124. package/dist/workflows/dag/frontend-review-context.js +92 -10
  125. package/dist/workflows/dag/init-hybrid.js +144 -4
  126. package/dist/workflows/dag/node-execution.js +45 -0
  127. package/dist/workflows/dag/types.js +45 -12
  128. package/docs/README.md +1 -0
  129. package/docs/architecture/evolution.md +45 -0
  130. package/docs/init-surface.manifest.json +1 -0
  131. package/docs/templates/README.md +1 -1
  132. package/docs/templates/frontend-implementation-contract.schema.json +681 -24
  133. package/package.json +1 -1
  134. package/skills/loop-agent/references/hybrid-dag.md +7 -0
  135. package/dist/worker/console/static/assets/channel-BG6TLen_.js +0 -1
  136. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-GuyUqs0h.js +0 -1
  137. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-GuyUqs0h.js +0 -1
  138. package/dist/worker/console/static/assets/index-C3GgHg-g.css +0 -1
  139. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Dgsvn63q.js +0 -1
  140. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DaNfG1BJ.js +0 -8
@@ -0,0 +1,474 @@
1
+ import { createHash } from "node:crypto";
2
+ // ---------------------------------------------------------------------------
3
+ // Deterministic fragment inventory (AC-001 / AC-FIDELITY-001)
4
+ // 对 .md/.markdown/.txt 按标题、段落、列表项、checklist、表格行确定性切分。
5
+ // 稳定 fragment ID:显式 AC ID 原样保留(含 `#### AC-*` 标题式);无 ID 片段生成
6
+ // 跨文档稳定 REQ-SRC-*(基于 path+行号+文本的确定性哈希,与文档枚举顺序无关,
7
+ // 消除 per-document counter reset 碰撞)。不按文档前 24K 字符裁剪——尾部片段仍
8
+ // 进入 inventory(覆盖统计证明)。
9
+ // ---------------------------------------------------------------------------
10
+ export const FRAGMENT_ID_PREFIX = "REQ-SRC";
11
+ /** 生成 fragment ID 的合法形态(防伪造:拒绝自由格式 ID)。 */
12
+ export const FRAGMENT_ID_PATTERN = /^(?:AC(?:-[A-Z0-9]+)+|REQ-SRC-[A-Z0-9-]+)$/;
13
+ const ACCEPTANCE_HEADING_RE = /(?:^|\s)(?:验收标准|acceptance criteria|acceptance|完成标准|完成定义|验收条件|验收准则|dod|definition of done|验收)(?:\s|$)/iu;
14
+ const CONSTRAINT_HEADING_RE = /(?:^|\s)(?:约束|constraints|invariants|不变式)(?:\s|$)/iu;
15
+ const NON_GOAL_HEADING_RE = /(?:^|\s)(?:非目标|out of scope|non-goals|non goals)(?:\s|$)/iu;
16
+ const OBJECTIVE_HEADING_RE = /(?:^|\s)(?:目标|objective|问题与目标|业务目标|需求概述)(?:\s|$)/iu;
17
+ /** 可执行片段启发式(AC 风格/祈使语气):命中则不可按 context-only 降级。 */
18
+ const EXECUTABLE_HINT_RE = /(?:必须|应当|应支持|需要|需|不得|should|must|shall|will|require|support|implement|provide|ensure|verify|当.*?时|when.*?then)/iu;
19
+ /** 显式 AC 式 ID 前缀:AC-001 / AC-FE-001 / AC-FE-INS-001 等(允许 bullet 标记后空格
20
+ * 与 checklist 勾选框)。收紧解析(AC-001 / AC-HARD-001):AC 后必须跟分隔符
21
+ * (-/_)+ 大写字母/数字 id 形态(含可选 FE/BE/UI/API 作用域前缀与 V4 `#### AC-*`
22
+ * 标题归属);`## Acceptance Criteria` / `## Acceptance` / Ac 开头普通单词永不产生
23
+ * 伪造 id(ACCEPTANCE 类 id 全量消失)。捕获组 1 = AC id,捕获组 2 = 余下文本。 */
24
+ const EXPLICIT_AC_ID_RE = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(AC(?:[-_](?:FE|BE|UI|API))?[-_][A-Z0-9]+(?:[-_][A-Z0-9]+)*)\s*[::]?\s*(.*)$/iu;
25
+ /** 显式 AC 标题式:`#### AC-FE-001 Save nickname` / `### AC-001:正文`。
26
+ * AC 后必须跟分隔符(-/_)+ id 形态;普通单词(Acceptance Criteria / Acceptance)
27
+ * 永不匹配,按 ACCEPTANCE_HEADING_RE 章节分类生成稳定 REQ-SRC-* 片段。
28
+ * 捕获组 1 = AC id,捕获组 2 = 标题余下文本。 */
29
+ const EXPLICIT_AC_HEADING_RE = /^\s*(AC(?:[-_](?:FE|BE|UI|API))?[-_][A-Z0-9]+(?:[-_][A-Z0-9]+)*)\s*[::]?\s*(.*)$/iu;
30
+ /** Markdown 表格数据行(非分隔行)。 */
31
+ const TABLE_DATA_ROW_RE = /^\s*\|.*\|\s*$/;
32
+ const TABLE_SEPARATOR_ROW_RE = /^\s*\|[\s:|-]+\|\s*$/;
33
+ /** 表格表头行:数据行且下一行是分隔行(`| 列 | 列 |` + `| --- | --- |`)。 */
34
+ function isTableHeaderRow(line, nextLine) {
35
+ return isTableDataRow(line) && TABLE_SEPARATOR_ROW_RE.test(nextLine.trim());
36
+ }
37
+ /** 表格行首格显式 AC ID:`| AC-001 | 订单列表加载完成 |` → id=AC-001, rest=订单列表加载完成。 */
38
+ function matchTableRowAcId(line) {
39
+ const trimmed = line.trim().replace(/^\|/, "");
40
+ const cells = trimmed.split("|");
41
+ const first = cells[0]?.trim() ?? "";
42
+ const idMatch = EXPLICIT_AC_HEADING_RE.exec(first);
43
+ if (!idMatch)
44
+ return null;
45
+ const id = (idMatch[1] ?? "").trim().toUpperCase().replace(/_/g, "-");
46
+ if (!id)
47
+ return null;
48
+ const rest = cells
49
+ .slice(1)
50
+ .join("|")
51
+ .replace(/\|\s*$/, "")
52
+ .trim();
53
+ return { id, rest: rest || id };
54
+ }
55
+ export function sha256Text(text) {
56
+ return createHash("sha256").update(text, "utf8").digest("hex");
57
+ }
58
+ export function normalizeFragmentText(text) {
59
+ return text
60
+ .replace(/\r\n/g, "\n")
61
+ .split("\n")
62
+ .map((line) => line.trim())
63
+ .filter(Boolean)
64
+ .join(" ")
65
+ .replace(/\s+/g, " ")
66
+ .trim();
67
+ }
68
+ export function matchExplicitAcId(line) {
69
+ const match = EXPLICIT_AC_ID_RE.exec(line.trim());
70
+ if (!match)
71
+ return null;
72
+ const rawId = match[1] ?? "";
73
+ const id = rawId.trim().toUpperCase().replace(/_/g, "-");
74
+ if (!id)
75
+ return null;
76
+ return { id, rest: (match[2] ?? "").trim() };
77
+ }
78
+ /** V4 显式 AC 标题式匹配:`#### AC-FE-001 Save nickname` → id=AC-FE-001, rest=Save nickname。 */
79
+ export function matchExplicitAcHeading(headingText) {
80
+ const match = EXPLICIT_AC_HEADING_RE.exec(headingText.trim());
81
+ if (!match)
82
+ return null;
83
+ const rawId = match[1] ?? "";
84
+ const id = rawId.trim().toUpperCase().replace(/_/g, "-");
85
+ if (!id)
86
+ return null;
87
+ return { id, rest: (match[2] ?? "").trim() };
88
+ }
89
+ function isAtxHeading(line) {
90
+ const match = /^(#{1,6})\s+(.+?)\s*$/u.exec(line);
91
+ if (!match)
92
+ return null;
93
+ return { level: match[1].length, text: match[2].trim() };
94
+ }
95
+ function isListItem(line) {
96
+ return /^\s*(?:[-*+]|\d+[.)])\s+(?:\[(?: |x|X)\]\s+)?/.test(line);
97
+ }
98
+ function isTableDataRow(line) {
99
+ const trimmed = line.trim();
100
+ return TABLE_DATA_ROW_RE.test(trimmed) && !TABLE_SEPARATOR_ROW_RE.test(trimmed);
101
+ }
102
+ function classifySectionHeading(headingPath) {
103
+ const normalized = headingPath.toLowerCase();
104
+ if (ACCEPTANCE_HEADING_RE.test(normalized))
105
+ return "acceptance";
106
+ if (CONSTRAINT_HEADING_RE.test(normalized))
107
+ return "constraint";
108
+ if (NON_GOAL_HEADING_RE.test(normalized))
109
+ return "non-goal";
110
+ if (OBJECTIVE_HEADING_RE.test(normalized))
111
+ return "objective";
112
+ return "other";
113
+ }
114
+ /**
115
+ * 确定性生成 fragment ID:REQ-SRC-<sha256(path+行号+文本) 前 12 位大写>。
116
+ * 与文档枚举顺序无关(跨文档不碰撞、重排不换 ID),相同输入恒等复现。
117
+ */
118
+ export function generatedFragmentId(pathValue, lineRange, text) {
119
+ const digest = sha256Text(`${pathValue}\u0000${lineRange.start}\u0000${lineRange.end}\u0000${text}`);
120
+ return `${FRAGMENT_ID_PREFIX}-${digest.slice(0, 12).toUpperCase()}`;
121
+ }
122
+ /**
123
+ * 将单个文档切分为标题段落(section),再按列表项/段落/表格行切分为原始片段。
124
+ * 完全确定性:相同输入总是产出相同片段序列。generated ID 使用跨文档稳定哈希,
125
+ * 不依赖文档内自增 counter(消除多文档 counter reset 碰撞)。
126
+ */
127
+ export function splitDocumentIntoFragments(doc) {
128
+ const normalized = doc.content.replace(/\r\n/g, "\n");
129
+ const lines = normalized.split("\n");
130
+ const sections = [];
131
+ const headingStack = [];
132
+ let current = null;
133
+ const flushSection = (endLine) => {
134
+ if (!current)
135
+ return;
136
+ current.endLine = Math.max(current.startLine, endLine);
137
+ current.lines = lines.slice(current.startLine - 1, Math.min(current.endLine, lines.length));
138
+ sections.push(current);
139
+ current = null;
140
+ };
141
+ for (let index = 0; index < lines.length; index += 1) {
142
+ const line = lines[index] ?? "";
143
+ const heading = isAtxHeading(line);
144
+ if (heading) {
145
+ flushSection(index - 1);
146
+ while (headingStack.length > 0 &&
147
+ headingStack[headingStack.length - 1].level >= heading.level) {
148
+ headingStack.pop();
149
+ }
150
+ headingStack.push({ level: heading.level, text: heading.text });
151
+ current = {
152
+ headingPath: headingStack.map((h) => h.text).join(" > "),
153
+ level: heading.level,
154
+ startLine: index + 1,
155
+ endLine: index + 1,
156
+ lines: [],
157
+ };
158
+ continue;
159
+ }
160
+ if (!current) {
161
+ current = {
162
+ headingPath: "",
163
+ level: 0,
164
+ startLine: index + 1,
165
+ endLine: index + 1,
166
+ lines: [],
167
+ };
168
+ }
169
+ }
170
+ flushSection(lines.length);
171
+ const rawFragments = [];
172
+ for (const section of sections) {
173
+ // V4 显式 AC 标题(`#### AC-*`)本身即验收段:标题行的 ID 原样保留。
174
+ const lastHeadingSegment = section.headingPath.split(" > ").pop() ?? section.headingPath;
175
+ const explicitSectionAc = matchExplicitAcHeading(lastHeadingSegment);
176
+ const sectionKind = classifySectionHeading(section.headingPath);
177
+ const effectiveKind = explicitSectionAc ? "acceptance" : sectionKind;
178
+ const bodyStart = section.headingPath
179
+ ? section.startLine + (explicitSectionAc ? 0 : 1)
180
+ : section.startLine;
181
+ const bodyEnd = section.endLine;
182
+ const bodyLines = lines.slice(Math.max(0, bodyStart - 1), Math.min(bodyEnd, lines.length));
183
+ // 当前验收章节内最近的显式 AC ID(V4 标题或 AC 条目),正文片段继承它。
184
+ let pendingAcId = null;
185
+ const emit = (fragment) => {
186
+ const explicit = fragment.explicitId ?? null;
187
+ let id = explicit;
188
+ if (!id) {
189
+ id = generatedFragmentId(doc.path, fragment.lineRange, fragment.text);
190
+ }
191
+ rawFragments.push({
192
+ id,
193
+ path: doc.path,
194
+ headingPath: fragment.headingPath,
195
+ lineRange: fragment.lineRange,
196
+ text: fragment.text,
197
+ ...(explicit
198
+ ? {}
199
+ : fragment.inheritAcId && pendingAcId
200
+ ? { explicitAcId: pendingAcId }
201
+ : {}),
202
+ });
203
+ };
204
+ if (explicitSectionAc) {
205
+ // 标题式 AC 段:标题行本身是一个 acceptance 片段(ID 原样保留)。
206
+ pendingAcId = explicitSectionAc.id;
207
+ emit({
208
+ headingPath: section.headingPath,
209
+ lineRange: { start: section.startLine, end: section.startLine },
210
+ text: explicitSectionAc.rest || explicitSectionAc.id,
211
+ explicitId: explicitSectionAc.id,
212
+ });
213
+ }
214
+ if (effectiveKind === "acceptance") {
215
+ // acceptance 章节:每个列表项/checklist/AC 标题行/表格数据行 = 一个片段。
216
+ let paragraphStart = null;
217
+ const flushParagraph = (endLine) => {
218
+ if (paragraphStart === null)
219
+ return;
220
+ const text = lines
221
+ .slice(paragraphStart - 1, Math.min(endLine, lines.length))
222
+ .map((line) => line.trim())
223
+ .filter(Boolean)
224
+ .join(" ")
225
+ .trim();
226
+ if (text) {
227
+ emit({
228
+ headingPath: section.headingPath,
229
+ lineRange: { start: paragraphStart, end: Math.max(paragraphStart, endLine) },
230
+ text,
231
+ inheritAcId: true,
232
+ });
233
+ }
234
+ paragraphStart = null;
235
+ };
236
+ for (let index = bodyStart; index <= bodyEnd; index += 1) {
237
+ const line = lines[index - 1] ?? "";
238
+ const trimmed = line.trim();
239
+ if (!trimmed) {
240
+ flushParagraph(index - 1);
241
+ continue;
242
+ }
243
+ if (TABLE_SEPARATOR_ROW_RE.test(trimmed)) {
244
+ // 表格分隔行不进入 inventory。
245
+ flushParagraph(index - 1);
246
+ continue;
247
+ }
248
+ const heading = isAtxHeading(trimmed);
249
+ if (heading) {
250
+ flushParagraph(index - 1);
251
+ const explicit = matchExplicitAcHeading(heading.text);
252
+ if (explicit) {
253
+ pendingAcId = explicit.id;
254
+ emit({
255
+ headingPath: section.headingPath,
256
+ lineRange: { start: index, end: index },
257
+ text: explicit.rest || explicit.id,
258
+ explicitId: explicit.id,
259
+ });
260
+ }
261
+ else {
262
+ pendingAcId = null;
263
+ }
264
+ continue;
265
+ }
266
+ if (isTableDataRow(trimmed)) {
267
+ const nextLine = lines[index] ?? "";
268
+ if (isTableHeaderRow(trimmed, nextLine)) {
269
+ // 表头行(后随分隔行)不进入 inventory。
270
+ flushParagraph(index - 1);
271
+ continue;
272
+ }
273
+ flushParagraph(index - 1);
274
+ const rowExplicit = matchTableRowAcId(trimmed);
275
+ emit({
276
+ headingPath: section.headingPath,
277
+ lineRange: { start: index, end: index },
278
+ text: rowExplicit ? rowExplicit.rest : trimmed,
279
+ explicitId: rowExplicit?.id,
280
+ ...(rowExplicit ? {} : { inheritAcId: true }),
281
+ });
282
+ continue;
283
+ }
284
+ if (isListItem(trimmed)) {
285
+ flushParagraph(index - 1);
286
+ const explicit = matchExplicitAcId(trimmed);
287
+ // 列表项自包含:显式 AC ID 只属于该项,不改变 heading 作用域
288
+ // (pendingAcId 仅由 V4 `#### AC-*` 标题设置)。
289
+ const text = explicit
290
+ ? explicit.rest
291
+ : trimmed.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, "");
292
+ if (text.trim()) {
293
+ emit({
294
+ headingPath: section.headingPath,
295
+ lineRange: { start: index, end: index },
296
+ text: text.trim(),
297
+ explicitId: explicit?.id,
298
+ ...(explicit ? {} : { inheritAcId: true }),
299
+ });
300
+ }
301
+ continue;
302
+ }
303
+ if (paragraphStart === null)
304
+ paragraphStart = index;
305
+ }
306
+ flushParagraph(bodyEnd);
307
+ continue;
308
+ }
309
+ // 非 acceptance 章节:连续非空行 = 一个段落片段(空行分隔);表格数据行独立成片。
310
+ let paragraphStart = null;
311
+ const flushParagraph = (endLine) => {
312
+ if (paragraphStart === null)
313
+ return;
314
+ const text = lines
315
+ .slice(paragraphStart - 1, Math.min(endLine, lines.length))
316
+ .map((line) => line.trim())
317
+ .filter(Boolean)
318
+ .join(" ")
319
+ .trim();
320
+ if (text) {
321
+ emit({
322
+ headingPath: section.headingPath,
323
+ lineRange: { start: paragraphStart, end: Math.max(paragraphStart, endLine) },
324
+ text,
325
+ });
326
+ }
327
+ paragraphStart = null;
328
+ };
329
+ for (let index = bodyStart; index <= bodyEnd; index += 1) {
330
+ const line = lines[index - 1] ?? "";
331
+ const trimmed = line.trim();
332
+ if (!trimmed) {
333
+ flushParagraph(index - 1);
334
+ continue;
335
+ }
336
+ if (isAtxHeading(trimmed)) {
337
+ flushParagraph(index - 1);
338
+ continue;
339
+ }
340
+ if (TABLE_SEPARATOR_ROW_RE.test(trimmed)) {
341
+ flushParagraph(index - 1);
342
+ continue;
343
+ }
344
+ if (isTableDataRow(trimmed)) {
345
+ const nextLine = lines[index] ?? "";
346
+ if (isTableHeaderRow(trimmed, nextLine)) {
347
+ flushParagraph(index - 1);
348
+ continue;
349
+ }
350
+ flushParagraph(index - 1);
351
+ emit({
352
+ headingPath: section.headingPath,
353
+ lineRange: { start: index, end: index },
354
+ text: trimmed,
355
+ });
356
+ continue;
357
+ }
358
+ if (paragraphStart === null)
359
+ paragraphStart = index;
360
+ }
361
+ flushParagraph(bodyEnd);
362
+ }
363
+ return rawFragments;
364
+ }
365
+ /**
366
+ * 对多个原始文档确定性切分并做 disposition 分类(AC-001)。
367
+ * 每个非空有效片段携带稳定 fragment ID、原始路径、标题路径、行号、原文哈希、
368
+ * 分级风险与且仅一个 disposition。duplicate 保留全部来源。文档先按 path 排序,
369
+ * 使 duplicate 判定与文档枚举顺序无关(同一输入恒等复现)。
370
+ */
371
+ export function buildFragmentInventory(input) {
372
+ const sortedDocuments = [...input.documents].sort((a, b) => a.path.localeCompare(b.path));
373
+ const fragments = [];
374
+ for (const doc of sortedDocuments) {
375
+ fragments.push(...splitDocumentIntoFragments(doc));
376
+ }
377
+ const canonicalById = new Map(input.canonicalRequirements.map((req) => [req.id, req.text]));
378
+ const canonicalTextSet = new Set(input.canonicalRequirements.map((req) => normalizeFragmentText(req.text)));
379
+ const seenText = new Map();
380
+ const records = fragments.map((fragment) => {
381
+ const text = normalizeFragmentText(fragment.text);
382
+ const sectionKind = classifySectionHeading(fragment.headingPath);
383
+ // 切分器已把显式 AC ID 放入 fragment.id 并从文本剥离前缀;此处从 id 恢复。
384
+ const explicitIdFromId = /^AC(?:-[A-Z0-9]+)+$/iu.test(fragment.id)
385
+ ? fragment.id
386
+ : null;
387
+ const explicit = explicitIdFromId
388
+ ? { id: explicitIdFromId, rest: fragment.text }
389
+ : matchExplicitAcId(fragment.text);
390
+ // V4 标题/条目下正文继承的显式 AC ID(不生成取代它的 REQ-SRC-*)。
391
+ const inherited = !explicit && fragment.explicitAcId
392
+ ? { id: fragment.explicitAcId, rest: fragment.text }
393
+ : null;
394
+ const effectiveExplicit = explicit ?? inherited;
395
+ const mappedIds = [];
396
+ if (effectiveExplicit && canonicalById.has(effectiveExplicit.id)) {
397
+ mappedIds.push(effectiveExplicit.id);
398
+ }
399
+ else if (effectiveExplicit && !canonicalById.has(effectiveExplicit.id)) {
400
+ // 显式 AC ID 但不在 canonical 集合:按文本匹配兜底,仍不中则 unresolved。
401
+ if (canonicalTextSet.has(text)) {
402
+ for (const req of input.canonicalRequirements) {
403
+ if (normalizeFragmentText(req.text) === text) {
404
+ mappedIds.push(req.id);
405
+ }
406
+ }
407
+ }
408
+ }
409
+ else if (canonicalTextSet.has(text)) {
410
+ for (const req of input.canonicalRequirements) {
411
+ if (normalizeFragmentText(req.text) === text) {
412
+ mappedIds.push(req.id);
413
+ }
414
+ }
415
+ }
416
+ let disposition;
417
+ let reason;
418
+ if (effectiveExplicit && canonicalById.has(effectiveExplicit.id) && mappedIds.length === 0) {
419
+ disposition = "acceptance";
420
+ reason = `explicit id ${effectiveExplicit.id} declared in source but canonical requirement has no fragment text match`;
421
+ }
422
+ else if (sectionKind === "acceptance" || effectiveExplicit) {
423
+ disposition = mappedIds.length > 0 ? "acceptance" : "unresolved";
424
+ if (disposition === "unresolved") {
425
+ reason =
426
+ effectiveExplicit && !canonicalById.has(effectiveExplicit.id)
427
+ ? `explicit AC id ${effectiveExplicit.id} not present in canonical requirements`
428
+ : "acceptance fragment without a canonical requirement mapping";
429
+ }
430
+ }
431
+ else if (sectionKind === "objective") {
432
+ disposition = "requirement";
433
+ }
434
+ else if (sectionKind === "constraint") {
435
+ disposition = "constraint";
436
+ }
437
+ else if (sectionKind === "non-goal") {
438
+ disposition = "non-goal";
439
+ }
440
+ else {
441
+ const executable = EXECUTABLE_HINT_RE.test(text);
442
+ disposition = executable ? "unresolved" : "context-only";
443
+ if (disposition === "unresolved") {
444
+ reason = "executable fragment outside recognized requirement/acceptance section";
445
+ }
446
+ else {
447
+ reason = "context-only fragment; excluded from canonical requirement coverage";
448
+ }
449
+ }
450
+ const priorId = seenText.get(text);
451
+ if (priorId) {
452
+ disposition = "duplicate";
453
+ reason = `duplicate of fragment ${priorId} (duplicate 保留全部来源)`;
454
+ }
455
+ else if (!priorId && text) {
456
+ seenText.set(text, fragment.id);
457
+ }
458
+ const risk = disposition === "context-only" || disposition === "duplicate"
459
+ ? "low"
460
+ : "high";
461
+ return {
462
+ id: fragment.id,
463
+ path: fragment.path,
464
+ headingPath: fragment.headingPath,
465
+ lineRange: fragment.lineRange,
466
+ sha256: sha256Text(fragment.text),
467
+ risk,
468
+ disposition,
469
+ ...(reason ? { reason } : {}),
470
+ canonicalRequirementIds: mappedIds,
471
+ };
472
+ });
473
+ return { fragments, records, documents: sortedDocuments };
474
+ }
@@ -7,4 +7,7 @@ export * from "./semantic-intake.js";
7
7
  export * from "./reference-integrity.js";
8
8
  export * from "./completeness.js";
9
9
  export * from "./build-draft.js";
10
+ export * from "./ledger-reconciliation.js";
11
+ export * from "./ledger-review.js";
12
+ export * from "./source-fidelity-pi.js";
10
13
  export * from "./prepare.js";
@@ -0,0 +1,127 @@
1
+ import { normalizeFragmentText } from "./fragment-inventory.js";
2
+ // ---------------------------------------------------------------------------
3
+ // 顺序 reconciliation(AC-006 / AC-FIDELITY-REPAIR-006)
4
+ // 结构化确定性片段走代码映射(显式 AC ID / 文本精确匹配),绝不调用 executor;
5
+ // 仅叙述性/歧义 chunk 调用可注入 executor,按标题顺序串行、逐块有界处理
6
+ // (budgetChars 按 chunk 截断,绝不整文件裁 24K)。executor 超时/异常/无效
7
+ // 返回/identity 越界一律 fail closed(SOURCE_FIDELITY_RECONCILIATION_FAILED),
8
+ // 不回退 heuristics。
9
+ // ---------------------------------------------------------------------------
10
+ export const LEDGER_RECONCILIATION_DEFAULT_BUDGET_CHARS = 4000;
11
+ export const LEDGER_RECONCILIATION_FAILED_CODE = "SOURCE_FIDELITY_RECONCILIATION_FAILED";
12
+ /** reconciliation 失败(executor 错误/无效输出/identity 越界/重复失败)。 */
13
+ export class LedgerReconciliationError extends Error {
14
+ code = LEDGER_RECONCILIATION_FAILED_CODE;
15
+ constructor(message, options) {
16
+ super(message, options);
17
+ this.name = "LedgerReconciliationError";
18
+ }
19
+ }
20
+ const VALID_DISPOSITIONS = new Set([
21
+ "requirement",
22
+ "acceptance",
23
+ "constraint",
24
+ "non-goal",
25
+ "duplicate",
26
+ "context-only",
27
+ "unresolved",
28
+ ]);
29
+ function isExclusionDisposition(disposition) {
30
+ return (disposition === "context-only" ||
31
+ disposition === "duplicate" ||
32
+ disposition === "unresolved");
33
+ }
34
+ /**
35
+ * 结构化确定性片段判定:显式 AC ID 存在于 canonical 集合,或文本与任一
36
+ * canonical requirement 规范化后精确一致。命中则走代码映射,不调 executor。
37
+ */
38
+ export function isStructuredMappableFragment(item, canonicalById, canonicalTexts) {
39
+ if (item.canonicalRequirementIds.length > 0)
40
+ return true;
41
+ if (/^AC(?:-[A-Z0-9]+)+$/iu.test(item.id) && canonicalById.has(item.id))
42
+ return true;
43
+ const text = normalizeFragmentText(item.text);
44
+ return canonicalTexts.has(text);
45
+ }
46
+ /**
47
+ * 顺序 reconciliation:仅叙述性/歧义片段(无结构化映射)调用 executor,按输入
48
+ * 顺序(标题顺序)串行、逐块有界。返回更新后的片段与调用日志(fixture 断言顺序)。
49
+ */
50
+ export async function reconcileLedgerFragments(input) {
51
+ const { canonicalRequirements, executor, budgetChars = LEDGER_RECONCILIATION_DEFAULT_BUDGET_CHARS, } = input;
52
+ const calls = input.calls ?? [];
53
+ const canonicalById = new Map(canonicalRequirements.map((req) => [req.id, req.text]));
54
+ const canonicalTexts = new Set(canonicalRequirements.map((req) => normalizeFragmentText(req.text)));
55
+ const canonicalIds = new Set(canonicalById.keys());
56
+ const reconciled = [];
57
+ for (const fragment of input.fragments) {
58
+ if (isStructuredMappableFragment(fragment, canonicalById, canonicalTexts)) {
59
+ reconciled.push(fragment);
60
+ continue;
61
+ }
62
+ const request = {
63
+ fragment: {
64
+ id: fragment.id,
65
+ path: fragment.path,
66
+ headingPath: fragment.headingPath,
67
+ lineRange: fragment.lineRange,
68
+ text: fragment.text.slice(0, budgetChars),
69
+ },
70
+ canonicalRequirements,
71
+ budgetChars,
72
+ };
73
+ let result;
74
+ try {
75
+ result = await executor(request);
76
+ }
77
+ catch (error) {
78
+ throw new LedgerReconciliationError(`reconciliation executor failed for fragment ${fragment.id}: ${error instanceof Error ? error.message : String(error)}`);
79
+ }
80
+ if (!result ||
81
+ typeof result !== "object" ||
82
+ !Array.isArray(result.mappedIds) ||
83
+ !VALID_DISPOSITIONS.has(result.disposition)) {
84
+ throw new LedgerReconciliationError(`reconciliation executor returned an invalid result for fragment ${fragment.id}`);
85
+ }
86
+ const outOfBounds = result.mappedIds.filter((id) => !canonicalIds.has(id));
87
+ if (outOfBounds.length > 0) {
88
+ throw new LedgerReconciliationError(`reconciliation executor returned out-of-bounds canonical ids for fragment ${fragment.id}: ${outOfBounds.join(", ")}`);
89
+ }
90
+ if (isExclusionDisposition(result.disposition) && !result.reason?.trim()) {
91
+ throw new LedgerReconciliationError(`reconciliation executor omitted the required exclusion reason for fragment ${fragment.id} (${result.disposition})`);
92
+ }
93
+ calls.push(fragment.id);
94
+ // 风险不降级(AC-003 / AC-HARD-003):风险保留为 max(原始 risk, disposition
95
+ // 派生 risk);context-only / duplicate 不再把高风险片段降为 low。
96
+ const derivedRisk = result.disposition === "context-only" ||
97
+ result.disposition === "duplicate"
98
+ ? "low"
99
+ : "high";
100
+ const risk = fragment.risk === "high" || derivedRisk === "high"
101
+ ? "high"
102
+ : "low";
103
+ reconciled.push({
104
+ ...fragment,
105
+ disposition: result.disposition,
106
+ ...(result.reason ? { reason: result.reason } : {}),
107
+ risk,
108
+ canonicalRequirementIds: result.mappedIds,
109
+ });
110
+ }
111
+ return { fragments: reconciled, calls };
112
+ }
113
+ /** 供 ledger.ts 接入:把 inventory records 与 raw fragments 合并为可 reconciliation 项。 */
114
+ export function mergeInventoryItems(input) {
115
+ const textById = new Map(input.fragments.map((fragment) => [fragment.id, fragment.text]));
116
+ return input.records.map((record) => ({
117
+ id: record.id,
118
+ path: record.path,
119
+ headingPath: record.headingPath,
120
+ lineRange: record.lineRange,
121
+ text: textById.get(record.id) ?? "",
122
+ disposition: record.disposition,
123
+ ...(record.reason ? { reason: record.reason } : {}),
124
+ risk: record.risk,
125
+ canonicalRequirementIds: record.canonicalRequirementIds,
126
+ }));
127
+ }