patchwarden 0.6.4 → 1.5.0

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 (254) hide show
  1. package/README.en.md +54 -20
  2. package/README.md +48 -21
  3. package/dist/agents/agentRouter.d.ts +40 -0
  4. package/dist/agents/agentRouter.js +95 -0
  5. package/dist/config.d.ts +1 -1
  6. package/dist/config.js +6 -2
  7. package/dist/controlCenter.js +212 -3
  8. package/dist/direct/directSessionStore.d.ts +2 -0
  9. package/dist/direct/directVerification.js +7 -0
  10. package/dist/doctor.js +32 -1
  11. package/dist/goal/acceptanceEngine.d.ts +62 -0
  12. package/dist/goal/acceptanceEngine.js +103 -0
  13. package/dist/goal/acceptanceTemplate.d.ts +10 -0
  14. package/dist/goal/acceptanceTemplate.js +104 -0
  15. package/dist/goal/goalGraph.d.ts +58 -0
  16. package/dist/goal/goalGraph.js +189 -0
  17. package/dist/goal/goalProgress.d.ts +81 -0
  18. package/dist/goal/goalProgress.js +216 -0
  19. package/dist/goal/goalStatus.d.ts +60 -0
  20. package/dist/goal/goalStatus.js +137 -0
  21. package/dist/goal/goalStore.d.ts +79 -0
  22. package/dist/goal/goalStore.js +211 -0
  23. package/dist/goal/handoffExport.d.ts +34 -0
  24. package/dist/goal/handoffExport.js +183 -0
  25. package/dist/goal/subgoalSync.d.ts +40 -0
  26. package/dist/goal/subgoalSync.js +72 -0
  27. package/dist/goal/worktreeManager.d.ts +96 -0
  28. package/dist/goal/worktreeManager.js +292 -0
  29. package/dist/logging.d.ts +44 -0
  30. package/dist/logging.js +68 -0
  31. package/dist/policy/projectPolicy.d.ts +55 -0
  32. package/dist/policy/projectPolicy.js +286 -0
  33. package/dist/release/releaseGate.d.ts +99 -0
  34. package/dist/release/releaseGate.js +475 -0
  35. package/dist/runner/postTaskCleanup.d.ts +13 -0
  36. package/dist/runner/postTaskCleanup.js +147 -0
  37. package/dist/runner/runTask.js +50 -10
  38. package/dist/security/discoveryTokenStore.d.ts +62 -0
  39. package/dist/security/discoveryTokenStore.js +100 -0
  40. package/dist/security/toolInvocationGuard.d.ts +35 -0
  41. package/dist/security/toolInvocationGuard.js +153 -0
  42. package/dist/smoke-test.js +18 -10
  43. package/dist/taskRuntime.d.ts +17 -0
  44. package/dist/test/unit/acceptance-engine.test.d.ts +1 -0
  45. package/dist/test/unit/acceptance-engine.test.js +228 -0
  46. package/dist/test/unit/agent-router.test.d.ts +1 -0
  47. package/dist/test/unit/agent-router.test.js +287 -0
  48. package/dist/test/unit/audit-checks.test.d.ts +1 -0
  49. package/dist/test/unit/audit-checks.test.js +350 -0
  50. package/dist/test/unit/diagnose-task.test.d.ts +1 -0
  51. package/dist/test/unit/diagnose-task.test.js +457 -0
  52. package/dist/test/unit/discovery-token-store.test.d.ts +1 -0
  53. package/dist/test/unit/discovery-token-store.test.js +139 -0
  54. package/dist/test/unit/evidence-pack.test.d.ts +1 -0
  55. package/dist/test/unit/evidence-pack.test.js +130 -0
  56. package/dist/test/unit/goal-graph.test.d.ts +1 -0
  57. package/dist/test/unit/goal-graph.test.js +298 -0
  58. package/dist/test/unit/goal-progress.test.d.ts +1 -0
  59. package/dist/test/unit/goal-progress.test.js +381 -0
  60. package/dist/test/unit/goal-status.test.d.ts +1 -0
  61. package/dist/test/unit/goal-status.test.js +215 -0
  62. package/dist/test/unit/goal-store.test.d.ts +1 -0
  63. package/dist/test/unit/goal-store.test.js +253 -0
  64. package/dist/test/unit/goal-subgoal-task.test.d.ts +1 -0
  65. package/dist/test/unit/goal-subgoal-task.test.js +55 -0
  66. package/dist/test/unit/goal-tools-registry.test.d.ts +1 -0
  67. package/dist/test/unit/goal-tools-registry.test.js +190 -0
  68. package/dist/test/unit/handoff-export.test.d.ts +1 -0
  69. package/dist/test/unit/handoff-export.test.js +263 -0
  70. package/dist/test/unit/invoke-discovered-tool.test.d.ts +1 -0
  71. package/dist/test/unit/invoke-discovered-tool.test.js +167 -0
  72. package/dist/test/unit/logging.test.js +127 -5
  73. package/dist/test/unit/post-task-cleanup.test.d.ts +1 -0
  74. package/dist/test/unit/post-task-cleanup.test.js +48 -0
  75. package/dist/test/unit/project-policy-release-mode.test.d.ts +1 -0
  76. package/dist/test/unit/project-policy-release-mode.test.js +125 -0
  77. package/dist/test/unit/reconcile-tasks.test.d.ts +1 -0
  78. package/dist/test/unit/reconcile-tasks.test.js +456 -0
  79. package/dist/test/unit/release-gate.test.d.ts +1 -0
  80. package/dist/test/unit/release-gate.test.js +242 -0
  81. package/dist/test/unit/run-task-loop.test.d.ts +1 -0
  82. package/dist/test/unit/run-task-loop.test.js +380 -0
  83. package/dist/test/unit/safe-views.test.d.ts +1 -0
  84. package/dist/test/unit/safe-views.test.js +171 -0
  85. package/dist/test/unit/schema-drift-check.test.d.ts +1 -0
  86. package/dist/test/unit/schema-drift-check.test.js +176 -0
  87. package/dist/test/unit/subgoal-sync.test.d.ts +1 -0
  88. package/dist/test/unit/subgoal-sync.test.js +183 -0
  89. package/dist/test/unit/tool-invocation-guard.test.d.ts +1 -0
  90. package/dist/test/unit/tool-invocation-guard.test.js +432 -0
  91. package/dist/test/unit/tool-usage-stats.test.d.ts +1 -0
  92. package/dist/test/unit/tool-usage-stats.test.js +300 -0
  93. package/dist/test/unit/toolSearch.test.d.ts +1 -0
  94. package/dist/test/unit/toolSearch.test.js +571 -0
  95. package/dist/test/unit/worktree-manager.test.d.ts +1 -0
  96. package/dist/test/unit/worktree-manager.test.js +176 -0
  97. package/dist/tools/auditTask.d.ts +103 -1
  98. package/dist/tools/auditTask.js +461 -8
  99. package/dist/tools/cancelTask.js +1 -1
  100. package/dist/tools/checkReleaseGate.d.ts +21 -0
  101. package/dist/tools/checkReleaseGate.js +22 -0
  102. package/dist/tools/createTask.d.ts +18 -2
  103. package/dist/tools/createTask.js +29 -1
  104. package/dist/tools/diagnoseTask.d.ts +45 -0
  105. package/dist/tools/diagnoseTask.js +347 -0
  106. package/dist/tools/discardWorktree.d.ts +24 -0
  107. package/dist/tools/discardWorktree.js +27 -0
  108. package/dist/tools/discoverTools.d.ts +11 -0
  109. package/dist/tools/discoverTools.js +39 -0
  110. package/dist/tools/evidencePack.d.ts +39 -0
  111. package/dist/tools/evidencePack.js +168 -0
  112. package/dist/tools/explainTool.d.ts +11 -0
  113. package/dist/tools/explainTool.js +21 -0
  114. package/dist/tools/getTaskSummary.js +2 -1
  115. package/dist/tools/goalSubgoalTask.d.ts +51 -0
  116. package/dist/tools/goalSubgoalTask.js +110 -0
  117. package/dist/tools/healthCheck.d.ts +1 -0
  118. package/dist/tools/healthCheck.js +5 -1
  119. package/dist/tools/invokeDiscoveredTool.d.ts +37 -0
  120. package/dist/tools/invokeDiscoveredTool.js +112 -0
  121. package/dist/tools/listTasks.d.ts +3 -1
  122. package/dist/tools/listTasks.js +14 -1
  123. package/dist/tools/mergeWorktree.d.ts +24 -0
  124. package/dist/tools/mergeWorktree.js +27 -0
  125. package/dist/tools/recommendAgentForTask.d.ts +19 -0
  126. package/dist/tools/recommendAgentForTask.js +56 -0
  127. package/dist/tools/reconcileTasks.d.ts +41 -0
  128. package/dist/tools/reconcileTasks.js +352 -0
  129. package/dist/tools/registry.js +926 -2
  130. package/dist/tools/releaseMode.d.ts +50 -0
  131. package/dist/tools/releaseMode.js +370 -0
  132. package/dist/tools/runDirectVerificationBundle.d.ts +26 -0
  133. package/dist/tools/runDirectVerificationBundle.js +64 -0
  134. package/dist/tools/runTaskLoop.d.ts +57 -0
  135. package/dist/tools/runTaskLoop.js +417 -0
  136. package/dist/tools/runVerification.d.ts +4 -0
  137. package/dist/tools/runVerification.js +4 -0
  138. package/dist/tools/safeStatus.d.ts +31 -1
  139. package/dist/tools/safeStatus.js +43 -1
  140. package/dist/tools/safeViews.d.ts +262 -0
  141. package/dist/tools/safeViews.js +252 -0
  142. package/dist/tools/schemaDriftCheck.d.ts +46 -0
  143. package/dist/tools/schemaDriftCheck.js +80 -0
  144. package/dist/tools/taskLineage.d.ts +91 -0
  145. package/dist/tools/taskLineage.js +175 -0
  146. package/dist/tools/toolCatalog.d.ts +4 -3
  147. package/dist/tools/toolCatalog.js +39 -11
  148. package/dist/tools/toolRegistry.d.ts +61 -0
  149. package/dist/tools/toolRegistry.js +834 -0
  150. package/dist/tools/toolSearch.d.ts +110 -0
  151. package/dist/tools/toolSearch.js +331 -0
  152. package/dist/tools/toolUsageStats.d.ts +41 -0
  153. package/dist/tools/toolUsageStats.js +116 -0
  154. package/dist/tools/waitForTask.js +1 -0
  155. package/dist/version.d.ts +2 -2
  156. package/dist/version.js +2 -2
  157. package/dist/watcherStatus.d.ts +29 -0
  158. package/dist/watcherStatus.js +92 -1
  159. package/docs/chatgpt-usage.md +31 -0
  160. package/docs/control-center/README.md +9 -0
  161. package/package.json +3 -2
  162. package/scripts/checks/control-center-smoke.js +87 -0
  163. package/scripts/checks/control-smoke.js +2 -2
  164. package/scripts/checks/doctor-smoke.js +1 -0
  165. package/scripts/checks/lifecycle-smoke.js +13 -9
  166. package/scripts/checks/mcp-manifest-check.js +65 -6
  167. package/scripts/checks/mcp-smoke.js +60 -9
  168. package/scripts/checks/watcher-supervisor-smoke.js +2 -2
  169. package/src/agents/agentRouter.ts +149 -0
  170. package/src/config.ts +9 -3
  171. package/src/controlCenter.ts +215 -4
  172. package/src/direct/directSessionStore.ts +2 -0
  173. package/src/direct/directVerification.ts +7 -0
  174. package/src/doctor.ts +36 -1
  175. package/src/goal/acceptanceEngine.ts +160 -0
  176. package/src/goal/acceptanceTemplate.ts +121 -0
  177. package/src/goal/goalGraph.ts +225 -0
  178. package/src/goal/goalProgress.ts +301 -0
  179. package/src/goal/goalStatus.ts +234 -0
  180. package/src/goal/goalStore.ts +306 -0
  181. package/src/goal/handoffExport.ts +211 -0
  182. package/src/goal/subgoalSync.ts +82 -0
  183. package/src/goal/worktreeManager.ts +404 -0
  184. package/src/logging.ts +91 -0
  185. package/src/policy/projectPolicy.ts +344 -0
  186. package/src/release/releaseGate.ts +567 -0
  187. package/src/runner/postTaskCleanup.ts +154 -0
  188. package/src/runner/runTask.ts +49 -10
  189. package/src/security/discoveryTokenStore.ts +157 -0
  190. package/src/security/toolInvocationGuard.ts +251 -0
  191. package/src/smoke-test.ts +15 -7
  192. package/src/taskRuntime.ts +17 -0
  193. package/src/test/unit/acceptance-engine.test.ts +261 -0
  194. package/src/test/unit/agent-router.test.ts +342 -0
  195. package/src/test/unit/audit-checks.test.ts +567 -0
  196. package/src/test/unit/diagnose-task.test.ts +544 -0
  197. package/src/test/unit/discovery-token-store.test.ts +181 -0
  198. package/src/test/unit/evidence-pack.test.ts +142 -0
  199. package/src/test/unit/goal-graph.test.ts +347 -0
  200. package/src/test/unit/goal-progress.test.ts +538 -0
  201. package/src/test/unit/goal-status.test.ts +270 -0
  202. package/src/test/unit/goal-store.test.ts +318 -0
  203. package/src/test/unit/goal-subgoal-task.test.ts +72 -0
  204. package/src/test/unit/goal-tools-registry.test.ts +243 -0
  205. package/src/test/unit/handoff-export.test.ts +295 -0
  206. package/src/test/unit/invoke-discovered-tool.test.ts +216 -0
  207. package/src/test/unit/logging.test.ts +177 -5
  208. package/src/test/unit/post-task-cleanup.test.ts +53 -0
  209. package/src/test/unit/project-policy-release-mode.test.ts +156 -0
  210. package/src/test/unit/reconcile-tasks.test.ts +551 -0
  211. package/src/test/unit/release-gate.test.ts +314 -0
  212. package/src/test/unit/run-task-loop.test.ts +425 -0
  213. package/src/test/unit/safe-views.test.ts +184 -0
  214. package/src/test/unit/schema-drift-check.test.ts +260 -0
  215. package/src/test/unit/subgoal-sync.test.ts +236 -0
  216. package/src/test/unit/tool-invocation-guard.test.ts +542 -0
  217. package/src/test/unit/tool-usage-stats.test.ts +384 -0
  218. package/src/test/unit/toolSearch.test.ts +756 -0
  219. package/src/test/unit/worktree-manager.test.ts +247 -0
  220. package/src/tools/auditTask.ts +831 -402
  221. package/src/tools/cancelTask.ts +1 -1
  222. package/src/tools/checkReleaseGate.ts +45 -0
  223. package/src/tools/createTask.ts +64 -6
  224. package/src/tools/diagnoseTask.ts +460 -0
  225. package/src/tools/discardWorktree.ts +42 -0
  226. package/src/tools/discoverTools.ts +51 -0
  227. package/src/tools/evidencePack.ts +205 -0
  228. package/src/tools/explainTool.ts +26 -0
  229. package/src/tools/getTaskSummary.ts +2 -1
  230. package/src/tools/goalSubgoalTask.ts +170 -0
  231. package/src/tools/healthCheck.ts +4 -1
  232. package/src/tools/invokeDiscoveredTool.ts +163 -0
  233. package/src/tools/listTasks.ts +16 -2
  234. package/src/tools/listWorkspace.ts +71 -71
  235. package/src/tools/mergeWorktree.ts +42 -0
  236. package/src/tools/recommendAgentForTask.ts +79 -0
  237. package/src/tools/reconcileTasks.ts +464 -0
  238. package/src/tools/registry.ts +1093 -73
  239. package/src/tools/releaseMode.ts +450 -0
  240. package/src/tools/runDirectVerificationBundle.ts +98 -0
  241. package/src/tools/runTaskLoop.ts +526 -0
  242. package/src/tools/runVerification.ts +8 -0
  243. package/src/tools/safeStatus.ts +73 -2
  244. package/src/tools/safeViews.ts +273 -0
  245. package/src/tools/schemaDriftCheck.ts +120 -0
  246. package/src/tools/taskLineage.ts +300 -0
  247. package/src/tools/toolCatalog.ts +40 -11
  248. package/src/tools/toolRegistry.ts +896 -0
  249. package/src/tools/toolSearch.ts +464 -0
  250. package/src/tools/toolUsageStats.ts +151 -0
  251. package/src/tools/waitForTask.ts +1 -0
  252. package/src/version.ts +2 -2
  253. package/src/watcherStatus.ts +97 -1
  254. package/ui/pages/dashboard.html +143 -2
@@ -0,0 +1,181 @@
1
+ import { describe, it, beforeEach } from "node:test";
2
+ import { strict as assert } from "node:assert";
3
+ import {
4
+ issueToken,
5
+ consumeToken,
6
+ peekToken,
7
+ revokeToken,
8
+ clearAllTokens,
9
+ getActiveTokenCount,
10
+ type IssueTokenInput,
11
+ } from "../../security/discoveryTokenStore.js";
12
+ import { PatchWardenError } from "../../errors.js";
13
+
14
+ // ── Helpers ───────────────────────────────────────────────────────
15
+
16
+ function todayDatePart(): string {
17
+ const now = new Date();
18
+ const y = now.getFullYear();
19
+ const m = String(now.getMonth() + 1).padStart(2, "0");
20
+ const d = String(now.getDate()).padStart(2, "0");
21
+ return `${y}${m}${d}`;
22
+ }
23
+
24
+ function sampleInput(overrides: Partial<IssueTokenInput> = {}): IssueTokenInput {
25
+ return {
26
+ toolName: "read_workspace_file",
27
+ risk: "workspace_read_sensitive",
28
+ query: "read file",
29
+ schemaDigest: "sha256:abc123",
30
+ profile: "full",
31
+ ...overrides,
32
+ };
33
+ }
34
+
35
+ // ── Tests ─────────────────────────────────────────────────────────
36
+
37
+ describe("discoveryTokenStore", () => {
38
+ beforeEach(() => {
39
+ clearAllTokens();
40
+ });
41
+
42
+ describe("issueToken", () => {
43
+ it("返回 dst_ 前缀 + 日期 + 12 位 hex 格式", () => {
44
+ const token = issueToken(sampleInput());
45
+ const regex = new RegExp(`^dst_${todayDatePart()}_[a-f0-9]{12}$`);
46
+ assert.ok(regex.test(token), `token "${token}" should match dst_YYYYMMDD_hex12`);
47
+ });
48
+
49
+ it("默认 expiresAt 为 issuedAt + 10 分钟", () => {
50
+ const token = issueToken(sampleInput());
51
+ const record = peekToken(token);
52
+ assert.ok(record, "record should exist");
53
+ const diff = Date.parse(record!.expiresAt) - Date.parse(record!.issuedAt);
54
+ // 允许 50ms 容差(两次 Date.now 调用间微小差异)
55
+ assert.ok(
56
+ Math.abs(diff - 600000) <= 50,
57
+ `expected diff ~600000ms, got ${diff}ms`
58
+ );
59
+ });
60
+
61
+ it("自定义 ttlMs 反映到 expiresAt", () => {
62
+ const token = issueToken(sampleInput({ ttlMs: 30000 }));
63
+ const record = peekToken(token);
64
+ assert.ok(record);
65
+ const diff = Date.parse(record!.expiresAt) - Date.parse(record!.issuedAt);
66
+ assert.ok(
67
+ Math.abs(diff - 30000) <= 50,
68
+ `expected diff ~30000ms, got ${diff}ms`
69
+ );
70
+ });
71
+
72
+ it("保存 record 字段完整", () => {
73
+ const token = issueToken(sampleInput({ allowedScope: ["src/"] }));
74
+ const record = peekToken(token);
75
+ assert.ok(record);
76
+ assert.equal(record!.token, token);
77
+ assert.equal(record!.toolName, "read_workspace_file");
78
+ assert.equal(record!.risk, "workspace_read_sensitive");
79
+ assert.deepEqual(record!.allowedScope, ["src/"]);
80
+ assert.equal(record!.query, "read file");
81
+ assert.equal(record!.schemaDigest, "sha256:abc123");
82
+ assert.equal(record!.profile, "full");
83
+ });
84
+ });
85
+
86
+ describe("consumeToken", () => {
87
+ it("成功返回 record 并删除(单次使用)", () => {
88
+ const token = issueToken(sampleInput());
89
+ const record = consumeToken(token);
90
+ assert.equal(record.token, token);
91
+ // 再次 consume 应抛 token_not_found
92
+ assert.throws(
93
+ () => consumeToken(token),
94
+ (err: unknown) => {
95
+ assert.ok(err instanceof PatchWardenError);
96
+ assert.equal(err.reason, "token_not_found");
97
+ return true;
98
+ }
99
+ );
100
+ });
101
+
102
+ it("不存在抛 token_not_found", () => {
103
+ assert.throws(
104
+ () => consumeToken("dst_nonexistent_000000000000"),
105
+ (err: unknown) => {
106
+ assert.ok(err instanceof PatchWardenError);
107
+ assert.equal(err.reason, "token_not_found");
108
+ return true;
109
+ }
110
+ );
111
+ });
112
+
113
+ it("过期抛 token_expired", () => {
114
+ // 用负 ttlMs 构造已过期 token
115
+ const token = issueToken(sampleInput({ ttlMs: -1000 }));
116
+ assert.throws(
117
+ () => consumeToken(token),
118
+ (err: unknown) => {
119
+ assert.ok(err instanceof PatchWardenError);
120
+ assert.equal(err.reason, "token_expired");
121
+ return true;
122
+ }
123
+ );
124
+ });
125
+
126
+ it("过期 token 被消费后从 store 删除", () => {
127
+ const token = issueToken(sampleInput({ ttlMs: -1000 }));
128
+ assert.throws(() => consumeToken(token));
129
+ // peek 应返回 null(已删除)
130
+ assert.equal(peekToken(token), null);
131
+ });
132
+ });
133
+
134
+ describe("peekToken", () => {
135
+ it("不消费 token(peek 后 consume 仍成功)", () => {
136
+ const token = issueToken(sampleInput());
137
+ const peeked = peekToken(token);
138
+ assert.ok(peeked);
139
+ assert.equal(peeked!.token, token);
140
+ // peek 后 consume 仍能成功
141
+ const consumed = consumeToken(token);
142
+ assert.equal(consumed.token, token);
143
+ });
144
+
145
+ it("不存在返回 null", () => {
146
+ assert.equal(peekToken("dst_nonexistent_000000000000"), null);
147
+ });
148
+ });
149
+
150
+ describe("revokeToken", () => {
151
+ it("删除 token,返回 true", () => {
152
+ const token = issueToken(sampleInput());
153
+ assert.equal(revokeToken(token), true);
154
+ assert.equal(peekToken(token), null);
155
+ });
156
+
157
+ it("不存在返回 false", () => {
158
+ assert.equal(revokeToken("dst_nonexistent_000000000000"), false);
159
+ });
160
+ });
161
+
162
+ describe("clearAllTokens", () => {
163
+ it("清空所有 token", () => {
164
+ issueToken(sampleInput());
165
+ issueToken(sampleInput());
166
+ assert.equal(getActiveTokenCount(), 2);
167
+ clearAllTokens();
168
+ assert.equal(getActiveTokenCount(), 0);
169
+ });
170
+ });
171
+
172
+ describe("getActiveTokenCount", () => {
173
+ it("正确返回当前 token 数量", () => {
174
+ assert.equal(getActiveTokenCount(), 0);
175
+ issueToken(sampleInput());
176
+ assert.equal(getActiveTokenCount(), 1);
177
+ issueToken(sampleInput());
178
+ assert.equal(getActiveTokenCount(), 2);
179
+ });
180
+ });
181
+ });
@@ -0,0 +1,142 @@
1
+ import { describe, it, beforeEach, afterEach } from "node:test";
2
+ import { strict as assert } from "node:assert";
3
+ import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { reloadConfig } from "../../config.js";
7
+ import { recommendAgentForTask } from "../../tools/recommendAgentForTask.js";
8
+ import { exportTaskEvidencePack, listEvidencePacks, readEvidencePack } from "../../tools/evidencePack.js";
9
+ import { writeTaskLineage } from "../../tools/taskLineage.js";
10
+
11
+ let tempDir: string;
12
+ let prevConfigEnv: string | undefined;
13
+
14
+ function writeConfig() {
15
+ const configPath = join(tempDir, "patchwarden.config.json");
16
+ writeFileSync(
17
+ configPath,
18
+ JSON.stringify({
19
+ workspaceRoot: tempDir,
20
+ tasksDir: ".patchwarden/tasks",
21
+ plansDir: ".patchwarden/plans",
22
+ assessmentsDir: ".patchwarden/assessments",
23
+ agents: {
24
+ codex: { command: "codex", args: [] },
25
+ opencode: { command: "opencode", args: [] },
26
+ },
27
+ allowedTestCommands: ["npm test", "npm run build"],
28
+ defaultTaskTimeoutSeconds: 30,
29
+ maxTaskTimeoutSeconds: 120,
30
+ }),
31
+ "utf-8"
32
+ );
33
+ prevConfigEnv = process.env.PATCHWARDEN_CONFIG;
34
+ process.env.PATCHWARDEN_CONFIG = configPath;
35
+ reloadConfig();
36
+ }
37
+
38
+ describe("v1.5 evidence packs and agent recommendations", () => {
39
+ beforeEach(() => {
40
+ tempDir = mkdtempSync(join(tmpdir(), "pw-evidence-"));
41
+ writeConfig();
42
+ });
43
+
44
+ afterEach(() => {
45
+ if (prevConfigEnv === undefined) delete process.env.PATCHWARDEN_CONFIG;
46
+ else process.env.PATCHWARDEN_CONFIG = prevConfigEnv;
47
+ reloadConfig();
48
+ rmSync(tempDir, { recursive: true, force: true });
49
+ });
50
+
51
+ it("recommends an agent without creating task evidence", () => {
52
+ const recommendation = recommendAgentForTask({
53
+ repo_path: ".",
54
+ goal: "Refactor two modules safely",
55
+ scope_files: ["src/a.ts", "src/b.ts"],
56
+ });
57
+
58
+ assert.equal(recommendation.bounded, true);
59
+ assert.ok(["codex", "opencode"].includes(recommendation.recommended_agent));
60
+ assert.ok(Array.isArray(recommendation.suggested_verify_commands));
61
+ const payload = JSON.stringify(recommendation);
62
+ assert.ok(!payload.includes("stdout"));
63
+ assert.ok(!payload.includes("stderr"));
64
+ assert.ok(!payload.includes("diff"));
65
+ });
66
+
67
+ it("exports bounded BOM-free evidence pack from lineage", () => {
68
+ writeTaskLineage({
69
+ lineage_id: "lineage_v15_pack",
70
+ goal: "Export evidence",
71
+ repo_path: ".",
72
+ created_at: "2026-07-05T12:00:00.000Z",
73
+ updated_at: "2026-07-05T12:01:00.000Z",
74
+ final_status: "accepted",
75
+ stop_reason: "success",
76
+ next_action: "accept",
77
+ main_task: "task-main",
78
+ fix_tasks: [],
79
+ cleanup_tasks: [],
80
+ direct_sessions: [{
81
+ session_id: "direct-one",
82
+ status: "passed",
83
+ command_count: 1,
84
+ passed_commands: 1,
85
+ failed_commands: 0,
86
+ timed_out_commands: 0,
87
+ audit_decision: "pass",
88
+ changed_files_total: 0,
89
+ next_action: "accept",
90
+ }],
91
+ rounds: [{
92
+ iteration: 1,
93
+ task_id: "task-main",
94
+ role: "main",
95
+ status: "done_by_agent",
96
+ terminal: true,
97
+ verification_status: "passed",
98
+ audit_verdict: "pass",
99
+ fail_checks: [],
100
+ warn_checks: [],
101
+ next_action: "accept",
102
+ }],
103
+ warnings: [],
104
+ errors: [],
105
+ worktree: {
106
+ isolation_mode: "worktree",
107
+ worktree_id: "wt-one",
108
+ worktree_path: join(tempDir, "_workspacetrees", "wt-one"),
109
+ branch: "pw-test",
110
+ cleanup: "keep",
111
+ status: "active",
112
+ next_action: "merge or discard explicitly",
113
+ },
114
+ agent_routing: {
115
+ requested_agent: "auto",
116
+ selected_agent: "codex",
117
+ reason: "test route",
118
+ fallback: false,
119
+ },
120
+ });
121
+
122
+ const pack = exportTaskEvidencePack({ lineage_id: "lineage_v15_pack" });
123
+ assert.equal(pack.bounded, true);
124
+ assert.equal(pack.lineage.worktree.worktree_id, "wt-one");
125
+ assert.equal(pack.lineage.agent_routing?.selected_agent, "codex");
126
+ const raw = readFileSync(pack.files.json);
127
+ assert.notEqual(raw[0], 0xef);
128
+ JSON.parse(raw.toString("utf-8"));
129
+
130
+ const payload = JSON.stringify(pack);
131
+ assert.ok(!payload.includes("stdout_tail"));
132
+ assert.ok(!payload.includes("stderr_tail"));
133
+ assert.ok(!payload.includes("diff.patch"));
134
+ assert.ok(!payload.includes("verification.log"));
135
+
136
+ const readBack = readEvidencePack("lineage_v15_pack");
137
+ assert.equal(readBack?.lineage_id, "lineage_v15_pack");
138
+ const listed = listEvidencePacks();
139
+ assert.equal(listed.total, 1);
140
+ assert.equal(listed.evidence_packs[0].lineage_id, "lineage_v15_pack");
141
+ });
142
+ });
@@ -0,0 +1,347 @@
1
+ import { describe, it } from "node:test";
2
+ import { strict as assert } from "node:assert";
3
+ import {
4
+ getReadySubgoals,
5
+ getBlockedSubgoals,
6
+ suggestNextSubgoal,
7
+ detectCycle,
8
+ topologicalSort,
9
+ } from "../../goal/goalGraph.js";
10
+ import type { GoalStatus, Subgoal, SubgoalStatus } from "../../goal/goalStatus.js";
11
+ import { PatchWardenError } from "../../errors.js";
12
+
13
+ // ── Helpers ───────────────────────────────────────────────────────
14
+
15
+ function makeSubgoal(overrides: Partial<Subgoal> & { id: string }): Subgoal {
16
+ return {
17
+ title: "Subgoal " + overrides.id,
18
+ status: "ready",
19
+ depends_on: [],
20
+ task_ids: [],
21
+ ...overrides,
22
+ };
23
+ }
24
+
25
+ function makeGoalStatus(subgoals: Subgoal[], overrides: Partial<GoalStatus> = {}): GoalStatus {
26
+ const now = new Date().toISOString();
27
+ return {
28
+ goal_id: "goal_test_001",
29
+ title: "Test Goal",
30
+ status: "active",
31
+ repo_path: "/repo/test",
32
+ created_at: now,
33
+ updated_at: now,
34
+ subgoals,
35
+ ...overrides,
36
+ };
37
+ }
38
+
39
+ // ── Tests ─────────────────────────────────────────────────────────
40
+
41
+ describe("goalGraph", () => {
42
+
43
+ describe("getReadySubgoals", () => {
44
+
45
+ it("无 subgoal 返回空数组", () => {
46
+ const goal = makeGoalStatus([]);
47
+ assert.deepEqual(getReadySubgoals(goal), []);
48
+ });
49
+
50
+ it("ready 且无依赖 → 返回", () => {
51
+ const goal = makeGoalStatus([
52
+ makeSubgoal({ id: "subgoal-001", depends_on: [] }),
53
+ ]);
54
+ const ready = getReadySubgoals(goal);
55
+ assert.equal(ready.length, 1);
56
+ assert.equal(ready[0].id, "subgoal-001");
57
+ });
58
+
59
+ it("ready 但依赖未 accepted → 不返回", () => {
60
+ const goal = makeGoalStatus([
61
+ makeSubgoal({ id: "subgoal-001", status: "running" }),
62
+ makeSubgoal({ id: "subgoal-002", depends_on: ["subgoal-001"] }),
63
+ ]);
64
+ const ready = getReadySubgoals(goal);
65
+ assert.equal(ready.length, 0);
66
+ });
67
+
68
+ it("ready 且依赖已 accepted → 返回", () => {
69
+ const goal = makeGoalStatus([
70
+ makeSubgoal({ id: "subgoal-001", status: "accepted", accepted_at: "2026-01-01T00:00:00.000Z" }),
71
+ makeSubgoal({ id: "subgoal-002", depends_on: ["subgoal-001"] }),
72
+ ]);
73
+ const ready = getReadySubgoals(goal);
74
+ assert.equal(ready.length, 1);
75
+ assert.equal(ready[0].id, "subgoal-002");
76
+ });
77
+
78
+ it("非 ready 状态(running 等)→ 不返回", () => {
79
+ const goal = makeGoalStatus([
80
+ makeSubgoal({ id: "subgoal-001", status: "running" }),
81
+ makeSubgoal({ id: "subgoal-002", status: "done_by_agent" }),
82
+ makeSubgoal({ id: "subgoal-003", status: "accepted" }),
83
+ ]);
84
+ const ready = getReadySubgoals(goal);
85
+ assert.equal(ready.length, 0);
86
+ });
87
+
88
+ it("依赖引用不存在的 subgoal → 不返回", () => {
89
+ const goal = makeGoalStatus([
90
+ makeSubgoal({ id: "subgoal-001", depends_on: ["subgoal-999"] }),
91
+ ]);
92
+ const ready = getReadySubgoals(goal);
93
+ assert.equal(ready.length, 0);
94
+ });
95
+
96
+ it("不修改传入的 goalStatus(不可变)", () => {
97
+ const goal = makeGoalStatus([
98
+ makeSubgoal({ id: "subgoal-001", depends_on: [] }),
99
+ ]);
100
+ const snapshot = JSON.stringify(goal);
101
+ getReadySubgoals(goal);
102
+ assert.equal(JSON.stringify(goal), snapshot);
103
+ });
104
+ });
105
+
106
+ describe("getBlockedSubgoals", () => {
107
+
108
+ it("无 blocked 返回空数组", () => {
109
+ const goal = makeGoalStatus([
110
+ makeSubgoal({ id: "subgoal-001", depends_on: [] }),
111
+ makeSubgoal({ id: "subgoal-002", status: "running" }),
112
+ ]);
113
+ assert.deepEqual(getBlockedSubgoals(goal), []);
114
+ });
115
+
116
+ it("ready 但依赖 running → 返回,blocked_by 包含该 id", () => {
117
+ const goal = makeGoalStatus([
118
+ makeSubgoal({ id: "subgoal-001", status: "running" }),
119
+ makeSubgoal({ id: "subgoal-002", depends_on: ["subgoal-001"] }),
120
+ ]);
121
+ const blocked = getBlockedSubgoals(goal);
122
+ assert.equal(blocked.length, 1);
123
+ assert.equal(blocked[0].subgoal.id, "subgoal-002");
124
+ assert.deepEqual(blocked[0].blocked_by, ["subgoal-001"]);
125
+ });
126
+
127
+ it("依赖引用不存在 → blocked_by 包含该不存在的 id", () => {
128
+ const goal = makeGoalStatus([
129
+ makeSubgoal({ id: "subgoal-001", depends_on: ["subgoal-999"] }),
130
+ ]);
131
+ const blocked = getBlockedSubgoals(goal);
132
+ assert.equal(blocked.length, 1);
133
+ assert.equal(blocked[0].subgoal.id, "subgoal-001");
134
+ assert.deepEqual(blocked[0].blocked_by, ["subgoal-999"]);
135
+ });
136
+
137
+ it("依赖部分 accepted 部分 running → blocked_by 只含未 accepted 的", () => {
138
+ const goal = makeGoalStatus([
139
+ makeSubgoal({ id: "subgoal-001", status: "accepted", accepted_at: "2026-01-01T00:00:00.000Z" }),
140
+ makeSubgoal({ id: "subgoal-002", status: "running" }),
141
+ makeSubgoal({ id: "subgoal-003", depends_on: ["subgoal-001", "subgoal-002"] }),
142
+ ]);
143
+ const blocked = getBlockedSubgoals(goal);
144
+ assert.equal(blocked.length, 1);
145
+ assert.deepEqual(blocked[0].blocked_by, ["subgoal-002"]);
146
+ });
147
+
148
+ it("非 ready 状态的 subgoal 不计入 blocked", () => {
149
+ const goal = makeGoalStatus([
150
+ makeSubgoal({ id: "subgoal-001", status: "running", depends_on: ["subgoal-999"] }),
151
+ ]);
152
+ const blocked = getBlockedSubgoals(goal);
153
+ assert.equal(blocked.length, 0);
154
+ });
155
+ });
156
+
157
+ describe("suggestNextSubgoal", () => {
158
+
159
+ it("有 ready → 返回第一个 ready", () => {
160
+ const goal = makeGoalStatus([
161
+ makeSubgoal({ id: "subgoal-001", depends_on: [] }),
162
+ ]);
163
+ const suggestion = suggestNextSubgoal(goal);
164
+ assert.equal(suggestion.subgoal_id, "subgoal-001");
165
+ assert.equal(suggestion.title, "Subgoal subgoal-001");
166
+ assert.deepEqual(suggestion.depends_on, []);
167
+ assert.equal(suggestion.reason, undefined);
168
+ });
169
+
170
+ it("无 ready 有 blocked → 返回 null + blocked_by", () => {
171
+ const goal = makeGoalStatus([
172
+ makeSubgoal({ id: "subgoal-001", status: "running" }),
173
+ makeSubgoal({ id: "subgoal-002", depends_on: ["subgoal-001"] }),
174
+ ]);
175
+ const suggestion = suggestNextSubgoal(goal);
176
+ assert.equal(suggestion.subgoal_id, null);
177
+ assert.equal(suggestion.reason, "dependencies_not_met");
178
+ assert.deepEqual(suggestion.blocked_by, ["subgoal-002"]);
179
+ });
180
+
181
+ it("无 ready 无 blocked → 返回 null + no_ready_subgoal", () => {
182
+ const goal = makeGoalStatus([
183
+ makeSubgoal({ id: "subgoal-001", status: "accepted", accepted_at: "2026-01-01T00:00:00.000Z" }),
184
+ makeSubgoal({ id: "subgoal-002", status: "running" }),
185
+ ]);
186
+ const suggestion = suggestNextSubgoal(goal);
187
+ assert.equal(suggestion.subgoal_id, null);
188
+ assert.equal(suggestion.reason, "no_ready_subgoal");
189
+ assert.equal(suggestion.blocked_by, undefined);
190
+ });
191
+
192
+ it("多个 ready → 返回数组顺序第一个", () => {
193
+ const goal = makeGoalStatus([
194
+ makeSubgoal({ id: "subgoal-001", depends_on: [] }),
195
+ makeSubgoal({ id: "subgoal-002", depends_on: [] }),
196
+ makeSubgoal({ id: "subgoal-003", depends_on: [] }),
197
+ ]);
198
+ const suggestion = suggestNextSubgoal(goal);
199
+ assert.equal(suggestion.subgoal_id, "subgoal-001");
200
+ });
201
+
202
+ it("空 subgoals → no_ready_subgoal", () => {
203
+ const goal = makeGoalStatus([]);
204
+ const suggestion = suggestNextSubgoal(goal);
205
+ assert.equal(suggestion.subgoal_id, null);
206
+ assert.equal(suggestion.reason, "no_ready_subgoal");
207
+ });
208
+ });
209
+
210
+ describe("detectCycle", () => {
211
+
212
+ it("无依赖无环", () => {
213
+ const goal = makeGoalStatus([
214
+ makeSubgoal({ id: "subgoal-001", depends_on: [] }),
215
+ makeSubgoal({ id: "subgoal-002", depends_on: [] }),
216
+ ]);
217
+ assert.equal(detectCycle(goal), null);
218
+ });
219
+
220
+ it("线性依赖 A→B 无环(B depends_on A)", () => {
221
+ const goal = makeGoalStatus([
222
+ makeSubgoal({ id: "A", depends_on: [] }),
223
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
224
+ ]);
225
+ assert.equal(detectCycle(goal), null);
226
+ });
227
+
228
+ it("A→B→A 有环,返回环路径", () => {
229
+ const goal = makeGoalStatus([
230
+ makeSubgoal({ id: "A", depends_on: ["B"] }),
231
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
232
+ ]);
233
+ const cycle = detectCycle(goal);
234
+ assert.ok(cycle !== null);
235
+ assert.ok(cycle.length >= 2);
236
+ assert.ok(cycle.includes("A"));
237
+ assert.ok(cycle.includes("B"));
238
+ });
239
+
240
+ it("自环 A→A 有环", () => {
241
+ const goal = makeGoalStatus([
242
+ makeSubgoal({ id: "A", depends_on: ["A"] }),
243
+ ]);
244
+ const cycle = detectCycle(goal);
245
+ assert.ok(cycle !== null);
246
+ assert.ok(cycle.includes("A"));
247
+ });
248
+
249
+ it("引用不存在的 subgoal 不算环", () => {
250
+ const goal = makeGoalStatus([
251
+ makeSubgoal({ id: "A", depends_on: ["nonexistent"] }),
252
+ ]);
253
+ assert.equal(detectCycle(goal), null);
254
+ });
255
+
256
+ it("三节点环 A→B→C→A", () => {
257
+ const goal = makeGoalStatus([
258
+ makeSubgoal({ id: "A", depends_on: ["C"] }),
259
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
260
+ makeSubgoal({ id: "C", depends_on: ["B"] }),
261
+ ]);
262
+ const cycle = detectCycle(goal);
263
+ assert.ok(cycle !== null);
264
+ assert.ok(cycle.includes("A"));
265
+ assert.ok(cycle.includes("B"));
266
+ assert.ok(cycle.includes("C"));
267
+ });
268
+
269
+ it("无环的复杂依赖图", () => {
270
+ const goal = makeGoalStatus([
271
+ makeSubgoal({ id: "A", depends_on: [] }),
272
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
273
+ makeSubgoal({ id: "C", depends_on: ["A"] }),
274
+ makeSubgoal({ id: "D", depends_on: ["B", "C"] }),
275
+ ]);
276
+ assert.equal(detectCycle(goal), null);
277
+ });
278
+ });
279
+
280
+ describe("topologicalSort", () => {
281
+
282
+ it("线性 A→B(B 依赖 A)→ 返回 [A, B]", () => {
283
+ const goal = makeGoalStatus([
284
+ makeSubgoal({ id: "A", depends_on: [] }),
285
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
286
+ ]);
287
+ const sorted = topologicalSort(goal);
288
+ assert.equal(sorted.length, 2);
289
+ const aIndex = sorted.indexOf("A");
290
+ const bIndex = sorted.indexOf("B");
291
+ assert.ok(aIndex < bIndex, "A should come before B");
292
+ });
293
+
294
+ it("有环抛错", () => {
295
+ const goal = makeGoalStatus([
296
+ makeSubgoal({ id: "A", depends_on: ["B"] }),
297
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
298
+ ]);
299
+ assert.throws(
300
+ () => topologicalSort(goal),
301
+ (err: unknown) => {
302
+ assert.ok(err instanceof PatchWardenError);
303
+ assert.equal(err.reason, "dependency_cycle");
304
+ return true;
305
+ }
306
+ );
307
+ });
308
+
309
+ it("单节点无依赖", () => {
310
+ const goal = makeGoalStatus([
311
+ makeSubgoal({ id: "A", depends_on: [] }),
312
+ ]);
313
+ assert.deepEqual(topologicalSort(goal), ["A"]);
314
+ });
315
+
316
+ it("菱形依赖:D 依赖 B、C,B/C 依赖 A → A 最前,D 最后", () => {
317
+ const goal = makeGoalStatus([
318
+ makeSubgoal({ id: "A", depends_on: [] }),
319
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
320
+ makeSubgoal({ id: "C", depends_on: ["A"] }),
321
+ makeSubgoal({ id: "D", depends_on: ["B", "C"] }),
322
+ ]);
323
+ const sorted = topologicalSort(goal);
324
+ assert.equal(sorted.length, 4);
325
+ const aIndex = sorted.indexOf("A");
326
+ const bIndex = sorted.indexOf("B");
327
+ const cIndex = sorted.indexOf("C");
328
+ const dIndex = sorted.indexOf("D");
329
+ assert.ok(aIndex < bIndex, "A before B");
330
+ assert.ok(aIndex < cIndex, "A before C");
331
+ assert.ok(bIndex < dIndex, "B before D");
332
+ assert.ok(cIndex < dIndex, "C before D");
333
+ });
334
+
335
+ it("引用不存在的 subgoal 不影响排序", () => {
336
+ const goal = makeGoalStatus([
337
+ makeSubgoal({ id: "A", depends_on: ["nonexistent"] }),
338
+ makeSubgoal({ id: "B", depends_on: ["A"] }),
339
+ ]);
340
+ const sorted = topologicalSort(goal);
341
+ assert.equal(sorted.length, 2);
342
+ const aIndex = sorted.indexOf("A");
343
+ const bIndex = sorted.indexOf("B");
344
+ assert.ok(aIndex < bIndex, "A before B");
345
+ });
346
+ });
347
+ });