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,417 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { getConfig } from "../config.js";
3
+ import { createWorktree } from "../goal/worktreeManager.js";
4
+ import { guardWorkspacePath } from "../security/pathGuard.js";
5
+ import { createDirectSession } from "./createDirectSession.js";
6
+ import { createTask } from "./createTask.js";
7
+ import { recommendAgentForTask } from "./recommendAgentForTask.js";
8
+ import { runDirectVerificationBundle } from "./runDirectVerificationBundle.js";
9
+ import { waitForTask } from "./waitForTask.js";
10
+ import { safeAudit, safeAuditDirectSession, safeFinalizeDirectSession, safeResult, safeTestSummary } from "./safeViews.js";
11
+ import { createLineageId, writeTaskLineage, } from "./taskLineage.js";
12
+ const DEFAULT_DEPS = {
13
+ createTask,
14
+ waitForTask,
15
+ safeResult,
16
+ safeAudit,
17
+ safeTestSummary,
18
+ createDirectSession,
19
+ runDirectVerificationBundle,
20
+ safeFinalizeDirectSession,
21
+ safeAuditDirectSession,
22
+ writeTaskLineage,
23
+ createLineageId,
24
+ recommendAgentForTask,
25
+ createWorktree,
26
+ now: () => new Date(),
27
+ sleep,
28
+ };
29
+ const TERMINAL_STATUSES = new Set([
30
+ "done",
31
+ "done_by_agent",
32
+ "failed",
33
+ "failed_verification",
34
+ "failed_scope_violation",
35
+ "failed_policy_violation",
36
+ "canceled",
37
+ ]);
38
+ export async function runTaskLoop(input) {
39
+ return runTaskLoopWithDeps(input, DEFAULT_DEPS);
40
+ }
41
+ export async function runTaskLoopWithDeps(input, deps) {
42
+ const normalized = normalizeInput(input);
43
+ const resolvedRepoPath = guardWorkspacePath(normalized.repo_path, getConfig().workspaceRoot);
44
+ const routing = resolveAgentRouting(normalized, deps);
45
+ const selectedAgent = routing.selected_agent;
46
+ const now = deps.now().toISOString();
47
+ const lineage = {
48
+ lineage_id: deps.createLineageId(deps.now()),
49
+ goal: normalized.goal,
50
+ repo_path: resolvedRepoPath,
51
+ created_at: now,
52
+ updated_at: now,
53
+ final_status: "blocked",
54
+ stop_reason: "policy_blocked",
55
+ next_action: "inspect_lineage",
56
+ main_task: null,
57
+ fix_tasks: [],
58
+ cleanup_tasks: [],
59
+ direct_sessions: [],
60
+ rounds: [],
61
+ warnings: [],
62
+ errors: [],
63
+ worktree: {
64
+ isolation_mode: normalized.isolation_mode,
65
+ cleanup: normalized.worktree_cleanup,
66
+ status: normalized.isolation_mode === "worktree" ? "active" : "not_used",
67
+ requested_base_branch: normalized.worktree_base_branch,
68
+ next_action: normalized.isolation_mode === "worktree"
69
+ ? "Review and explicitly merge or discard the worktree after acceptance."
70
+ : "none",
71
+ },
72
+ agent_routing: routing,
73
+ };
74
+ const finalize = (finalStatus, stopReason, nextAction, error) => {
75
+ lineage.final_status = finalStatus;
76
+ lineage.stop_reason = stopReason;
77
+ lineage.next_action = nextAction;
78
+ lineage.updated_at = deps.now().toISOString();
79
+ if (error)
80
+ lineage.errors.push(error);
81
+ const safe = deps.writeTaskLineage(lineage);
82
+ return {
83
+ ...safe,
84
+ created_task_count: [lineage.main_task, ...lineage.fix_tasks, ...lineage.cleanup_tasks].filter(Boolean).length,
85
+ auto_fix_tests: normalized.auto_fix_tests,
86
+ auto_cleanup_artifacts: normalized.auto_cleanup_artifacts,
87
+ direct_verify: normalized.direct_verify,
88
+ isolation_mode: normalized.isolation_mode,
89
+ worktree: safe.worktree,
90
+ stopped_before_execution: lineage.main_task === null,
91
+ };
92
+ };
93
+ let taskRepoPath = resolvedRepoPath;
94
+ if (normalized.isolation_mode === "worktree") {
95
+ try {
96
+ const worktree = deps.createWorktree(lineage.lineage_id, "task_loop", resolvedRepoPath);
97
+ taskRepoPath = worktree.worktreePath;
98
+ lineage.repo_path = taskRepoPath;
99
+ lineage.worktree = {
100
+ isolation_mode: "worktree",
101
+ worktree_id: worktree.worktreeId,
102
+ worktree_path: worktree.worktreePath,
103
+ branch: worktree.branch,
104
+ requested_base_branch: normalized.worktree_base_branch,
105
+ cleanup: normalized.worktree_cleanup,
106
+ status: "active",
107
+ next_action: "Explicitly inspect and merge_worktree or discard_worktree after reviewing this lineage.",
108
+ };
109
+ }
110
+ catch (err) {
111
+ lineage.worktree = {
112
+ isolation_mode: "worktree",
113
+ cleanup: normalized.worktree_cleanup,
114
+ requested_base_branch: normalized.worktree_base_branch,
115
+ status: "failed",
116
+ next_action: "Fix worktree creation prerequisites or rerun with isolation_mode=current_repo.",
117
+ };
118
+ return finalize("blocked", "policy_blocked", "Fix worktree creation prerequisites or rerun without worktree isolation.", err instanceof Error ? err.message : String(err));
119
+ }
120
+ }
121
+ let role = "main";
122
+ let latestFailurePrompt = normalized.goal;
123
+ for (let iteration = 1; iteration <= normalized.max_iterations; iteration++) {
124
+ const assessmentInput = {
125
+ template: role === "main" ? normalized.template : "fix_tests",
126
+ goal: role === "main" ? normalized.goal : latestFailurePrompt,
127
+ repo_path: taskRepoPath,
128
+ agent: selectedAgent,
129
+ verify_commands: normalized.verify_commands,
130
+ timeout_seconds: normalized.task_timeout_seconds,
131
+ execution_mode: "assess_only",
132
+ };
133
+ const assessment = deps.createTask(assessmentInput);
134
+ if (assessment.decision === "blocked") {
135
+ return finalize("blocked", "high_risk_blocked", "Risk assessment blocked task execution.", assessment.reason_codes?.join(", "));
136
+ }
137
+ if (assessment.decision === "needs_confirm") {
138
+ return finalize("blocked", "user_confirmation_required", "Ask the user to confirm the assessment before executing the loop.");
139
+ }
140
+ const created = deps.createTask({
141
+ execution_mode: "execute",
142
+ assessment_id: String(assessment.assessment_id || ""),
143
+ });
144
+ const taskId = String(created.task_id || "");
145
+ if (!taskId) {
146
+ return finalize("failed", "policy_blocked", "create_task returned no task_id.", "create_task returned no task_id");
147
+ }
148
+ if (role === "main")
149
+ lineage.main_task = taskId;
150
+ else
151
+ lineage.fix_tasks.push(taskId);
152
+ const wait = await waitUntilTerminal(taskId, normalized.task_timeout_seconds, deps);
153
+ if (wait.stop_reason) {
154
+ return finalize("blocked", wait.stop_reason, wait.next_action, wait.error);
155
+ }
156
+ const result = deps.safeResult(taskId, { max_items: 8 });
157
+ const tests = deps.safeTestSummary(taskId);
158
+ const audit = deps.safeAudit(taskId, { max_items: 8 });
159
+ const round = buildRound(iteration, taskId, role, result, tests, audit);
160
+ lineage.rounds.push(round);
161
+ lineage.updated_at = deps.now().toISOString();
162
+ if (isSuccessfulRound(round)) {
163
+ if (normalized.direct_verify) {
164
+ const direct = await runDirectVerification(lineage.lineage_id, normalized, taskRepoPath, deps);
165
+ lineage.direct_sessions.push(direct.evidence);
166
+ if (direct.warning)
167
+ lineage.warnings.push(direct.warning);
168
+ if (direct.stop_reason) {
169
+ return finalize(direct.final_status, direct.stop_reason, direct.next_action, direct.error);
170
+ }
171
+ }
172
+ return finalize("accepted", "success", "accept");
173
+ }
174
+ if (isHardStop(round, result, audit, normalized.stop_on_high_risk)) {
175
+ return finalize("blocked", hardStopReason(round, result), round.next_action || "review_task");
176
+ }
177
+ latestFailurePrompt = buildFixGoal(normalized.goal, result, round);
178
+ if (!normalized.auto_fix_tests || round.status !== "failed_verification") {
179
+ return finalize("needs_fix", "verification_failed", round.next_action || "create_followup_task");
180
+ }
181
+ role = "fix_tests";
182
+ }
183
+ return finalize("needs_fix", "max_iterations_reached", "review_lineage_and_create_manual_followup");
184
+ }
185
+ async function waitUntilTerminal(taskId, timeoutSeconds, deps) {
186
+ const deadline = Date.now() + timeoutSeconds * 1000;
187
+ while (Date.now() < deadline) {
188
+ const waited = await deps.waitForTask(taskId, 30);
189
+ if (waited.terminal || TERMINAL_STATUSES.has(String(waited.status))) {
190
+ return { next_action: waited.next_action || "safe_audit" };
191
+ }
192
+ if (waited.next_tool_call?.name === "health_check" || waited.continuation_required === false) {
193
+ return {
194
+ stop_reason: "watcher_blocked",
195
+ next_action: waited.next_action || "health_check",
196
+ error: waited.progress_summary?.hint || "Watcher is blocked or unavailable.",
197
+ };
198
+ }
199
+ await deps.sleep(250);
200
+ }
201
+ return {
202
+ stop_reason: "agent_timeout",
203
+ next_action: "inspect_task_status",
204
+ error: `Task loop timed out waiting for ${taskId}.`,
205
+ };
206
+ }
207
+ function buildRound(iteration, taskId, role, result, tests, audit) {
208
+ const failChecks = Array.isArray(audit.fail_checks) ? audit.fail_checks.map((entry) => String(entry.name || entry)) : [];
209
+ const warnChecks = Array.isArray(audit.warn_checks) ? audit.warn_checks.map((entry) => String(entry.name || entry)) : [];
210
+ return {
211
+ iteration,
212
+ task_id: taskId,
213
+ role,
214
+ status: String(result.status || "unknown"),
215
+ terminal: Boolean(result.terminal),
216
+ verification_status: String(tests.status || result.verification?.status || "not_available"),
217
+ audit_verdict: String(audit.verdict || audit.acceptance?.verdict || "unknown"),
218
+ fail_checks: failChecks,
219
+ warn_checks: warnChecks,
220
+ next_action: String(result.next_action || audit.recommended_next_actions?.[0] || "review_task"),
221
+ };
222
+ }
223
+ function isSuccessfulRound(round) {
224
+ return (round.terminal &&
225
+ ["done_by_agent", "done", "accepted"].includes(round.status) &&
226
+ round.verification_status === "passed" &&
227
+ round.fail_checks.length === 0 &&
228
+ round.warn_checks.length === 0 &&
229
+ round.audit_verdict === "pass");
230
+ }
231
+ function isHardStop(round, result, audit, stopOnHighRisk) {
232
+ if (["failed_scope_violation", "failed_policy_violation", "canceled"].includes(round.status))
233
+ return true;
234
+ if (!stopOnHighRisk)
235
+ return false;
236
+ const checkNames = [...round.fail_checks, ...round.warn_checks].join(" ").toLowerCase();
237
+ const reason = String(result.failure_reason || audit.acceptance?.reason || "").toLowerCase();
238
+ return /scope|secret|sensitive|publish|release|policy|push/.test(`${checkNames} ${reason}`);
239
+ }
240
+ function hardStopReason(round, result) {
241
+ if (round.status === "failed_scope_violation" || round.status === "failed_policy_violation")
242
+ return "policy_blocked";
243
+ if (String(result.failure_reason || "").toLowerCase().includes("timeout"))
244
+ return "agent_timeout";
245
+ return "high_risk_blocked";
246
+ }
247
+ function buildFixGoal(originalGoal, result, round) {
248
+ const failedCommand = result.failed_command ? ` Failed command: ${result.failed_command}.` : "";
249
+ return [
250
+ `Fix the failing verification for this PatchWarden loop without changing unrelated behavior.`,
251
+ `Original goal: ${originalGoal}`,
252
+ `Previous task: ${round.task_id}. Status: ${round.status}. Verification: ${round.verification_status}.${failedCommand}`,
253
+ "Do not commit, push, publish, weaken tests, or touch files outside the resolved repository path.",
254
+ ].join("\n");
255
+ }
256
+ function resolveAgentRouting(normalized, deps) {
257
+ if (normalized.agent && normalized.agent !== "auto") {
258
+ return {
259
+ requested_agent: normalized.agent,
260
+ selected_agent: normalized.agent,
261
+ reason: "explicit agent supplied",
262
+ fallback: false,
263
+ };
264
+ }
265
+ const recommendation = deps.recommendAgentForTask({
266
+ repo_path: normalized.repo_path,
267
+ goal: normalized.goal,
268
+ scope_files: normalized.scope_files,
269
+ template: normalized.template,
270
+ });
271
+ return {
272
+ requested_agent: normalized.agent || null,
273
+ selected_agent: recommendation.recommended_agent,
274
+ reason: recommendation.reason,
275
+ fallback: recommendation.fallback,
276
+ };
277
+ }
278
+ async function runDirectVerification(lineageId, normalized, repoPath, deps) {
279
+ const config = getConfig();
280
+ if (config.enableDirectProfile !== true) {
281
+ return {
282
+ evidence: {
283
+ session_id: "not_created",
284
+ status: "skipped",
285
+ audit_decision: "not_run",
286
+ next_action: "Enable Direct profile locally before requesting direct_verify.",
287
+ },
288
+ stop_reason: "direct_profile_disabled",
289
+ final_status: "blocked",
290
+ next_action: "Enable enableDirectProfile locally or rerun run_task_loop with direct_verify=false.",
291
+ error: "Direct profile is disabled by local config.",
292
+ };
293
+ }
294
+ let sessionId = "";
295
+ try {
296
+ const session = deps.createDirectSession({
297
+ repo_path: repoPath,
298
+ title: `Direct verification for ${lineageId}`,
299
+ });
300
+ sessionId = session.session_id;
301
+ const bundle = await deps.runDirectVerificationBundle({
302
+ session_id: sessionId,
303
+ commands: normalized.direct_verify_commands,
304
+ timeout_seconds: normalized.direct_verify_timeout_seconds,
305
+ });
306
+ const finalized = deps.safeFinalizeDirectSession(sessionId, { max_items: 8 });
307
+ const audit = deps.safeAuditDirectSession(sessionId, { max_items: 8 });
308
+ const evidence = {
309
+ session_id: sessionId,
310
+ status: bundle.status,
311
+ command_count: bundle.command_count,
312
+ passed_commands: bundle.passed_commands,
313
+ failed_commands: bundle.failed_commands,
314
+ timed_out_commands: bundle.timed_out_commands,
315
+ audit_decision: audit.decision || "not_run",
316
+ changed_files_total: Number(finalized.changed_files_total || audit.evidence?.changed_files_total || 0),
317
+ next_action: String(audit.next_action || bundle.next_action || "review_direct_session"),
318
+ };
319
+ if (bundle.status !== "passed") {
320
+ return {
321
+ evidence,
322
+ stop_reason: "direct_verification_failed",
323
+ final_status: "needs_fix",
324
+ next_action: "Review Direct verification summary and create a normal follow-up task.",
325
+ error: "Direct verification failed.",
326
+ };
327
+ }
328
+ if (audit.decision === "fail") {
329
+ return {
330
+ evidence,
331
+ stop_reason: "direct_audit_failed",
332
+ final_status: "blocked",
333
+ next_action: "Review Direct audit findings before accepting the loop.",
334
+ error: "Direct audit failed.",
335
+ };
336
+ }
337
+ return {
338
+ evidence,
339
+ final_status: "accepted",
340
+ next_action: "accept",
341
+ warning: audit.decision === "warn" ? "Direct audit completed with warnings." : undefined,
342
+ };
343
+ }
344
+ catch (err) {
345
+ const message = err instanceof Error ? err.message : String(err);
346
+ return {
347
+ evidence: {
348
+ session_id: sessionId || "not_created",
349
+ status: "failed",
350
+ audit_decision: "not_run",
351
+ next_action: "Review Direct verification configuration and command allow-list.",
352
+ },
353
+ stop_reason: "direct_verification_failed",
354
+ final_status: "needs_fix",
355
+ next_action: "Review Direct verification configuration and command allow-list.",
356
+ error: message,
357
+ };
358
+ }
359
+ }
360
+ function normalizeInput(input) {
361
+ const config = getConfig();
362
+ const repoPath = String(input.repo_path || "").trim();
363
+ const goal = String(input.goal || "").trim();
364
+ if (!repoPath)
365
+ throw new Error("repo_path is required.");
366
+ if (!goal)
367
+ throw new Error("goal is required.");
368
+ if (!Array.isArray(input.verify_commands) || input.verify_commands.length === 0) {
369
+ throw new Error("verify_commands must contain at least one command.");
370
+ }
371
+ const maxIterations = input.max_iterations ?? 3;
372
+ if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 5) {
373
+ throw new Error("max_iterations must be an integer from 1 to 5.");
374
+ }
375
+ const timeoutSeconds = input.task_timeout_seconds ?? config.defaultTaskTimeoutSeconds;
376
+ if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > config.maxTaskTimeoutSeconds) {
377
+ throw new Error(`task_timeout_seconds must be an integer from 1 to ${config.maxTaskTimeoutSeconds}.`);
378
+ }
379
+ const template = input.template || "feature_small";
380
+ if (template !== "inspect_only" && template !== "feature_small" && template !== "release_check") {
381
+ throw new Error('template must be "inspect_only", "feature_small", or "release_check".');
382
+ }
383
+ const directVerifyCommands = Array.isArray(input.direct_verify_commands) && input.direct_verify_commands.length > 0
384
+ ? input.direct_verify_commands
385
+ : input.verify_commands;
386
+ if (input.direct_verify === true && (!Array.isArray(directVerifyCommands) || directVerifyCommands.length === 0)) {
387
+ throw new Error("direct_verify_commands must contain at least one command when provided.");
388
+ }
389
+ const directVerifyTimeout = input.direct_verify_timeout_seconds ?? 120;
390
+ const maxDirectTimeout = Math.min(config.maxTaskTimeoutSeconds, config.directSessionTtlSeconds);
391
+ if (!Number.isInteger(directVerifyTimeout) || directVerifyTimeout < 1 || directVerifyTimeout > maxDirectTimeout) {
392
+ throw new Error(`direct_verify_timeout_seconds must be an integer from 1 to ${maxDirectTimeout}.`);
393
+ }
394
+ return {
395
+ repo_path: repoPath,
396
+ goal,
397
+ verify_commands: input.verify_commands.map((command) => String(command).trim()),
398
+ agent: input.agent ? String(input.agent) : undefined,
399
+ template,
400
+ max_iterations: maxIterations,
401
+ task_timeout_seconds: timeoutSeconds,
402
+ auto_fix_tests: input.auto_fix_tests !== false,
403
+ auto_cleanup_artifacts: input.auto_cleanup_artifacts !== false,
404
+ stop_on_high_risk: input.stop_on_high_risk !== false,
405
+ direct_verify: input.direct_verify === true,
406
+ direct_verify_commands: directVerifyCommands.map((command) => String(command).trim()),
407
+ direct_verify_timeout_seconds: directVerifyTimeout,
408
+ scope_files: Array.isArray(input.scope_files)
409
+ ? input.scope_files.map((entry) => String(entry).trim()).filter(Boolean).slice(0, 50)
410
+ : undefined,
411
+ isolation_mode: input.isolation_mode === "worktree" ? "worktree" : "current_repo",
412
+ worktree_base_branch: input.worktree_base_branch ? String(input.worktree_base_branch).trim().slice(0, 160) : undefined,
413
+ worktree_cleanup: input.worktree_cleanup === "archive" || input.worktree_cleanup === "delete_ignored_only"
414
+ ? input.worktree_cleanup
415
+ : "keep",
416
+ };
417
+ }
@@ -8,6 +8,10 @@ export interface RunVerificationOutput {
8
8
  exit_code: number | null;
9
9
  passed: boolean;
10
10
  timed_out: boolean;
11
+ redacted: boolean;
12
+ redaction_categories: string[];
13
+ started_at: string;
14
+ finished_at: string;
11
15
  stdout_tail: string;
12
16
  stderr_tail: string;
13
17
  log_path: string;
@@ -22,6 +22,10 @@ export async function runVerification(input) {
22
22
  exit_code: result.run.exit_code,
23
23
  passed: result.run.passed,
24
24
  timed_out: result.run.timed_out,
25
+ redacted: Boolean(result.run.redacted),
26
+ redaction_categories: result.run.redaction_categories || [],
27
+ started_at: result.run.started_at,
28
+ finished_at: result.run.finished_at,
25
29
  stdout_tail: result.run.stdout_tail,
26
30
  stderr_tail: result.run.stderr_tail,
27
31
  log_path: result.run.log_path,
@@ -1,8 +1,21 @@
1
1
  import { type PatchWardenConfig } from "../config.js";
2
- import type { TaskStatus, TaskPhase } from "./createTask.js";
2
+ import type { TaskStatus, TaskPhase, AcceptanceStatus } from "./createTask.js";
3
+ import { type DiagnosisType, type DiagnosisConfidence } from "./diagnoseTask.js";
3
4
  export interface SafeStatusOutput {
4
5
  task_id: string;
5
6
  status: TaskStatus | "not_found";
7
+ /**
8
+ * v0.7.0: For done_by_agent or accepted tasks, legacy_status echoes "done"
9
+ * so older UI/clients that do not understand those statuses still see a familiar value.
10
+ * Null for all other statuses.
11
+ */
12
+ legacy_status: "done" | null;
13
+ /**
14
+ * v0.7.0: Acceptance status — only meaningful for done_by_agent.
15
+ * - "pending": done_by_agent reached but not yet audited/accepted
16
+ * - null: status has no acceptance semantics
17
+ */
18
+ acceptance_status: AcceptanceStatus;
6
19
  phase: TaskPhase | null;
7
20
  created_at: string | null;
8
21
  started_at: string | null;
@@ -15,5 +28,22 @@ export interface SafeStatusOutput {
15
28
  watcher_state: string | null;
16
29
  error_code: string | null;
17
30
  error_summary: string | null;
31
+ /**
32
+ * v0.7.0: Seconds since the last heartbeat. Null when heartbeat is missing
33
+ * or unparseable. Used by callers to detect stale running tasks.
34
+ */
35
+ stale_seconds: number | null;
36
+ /**
37
+ * v0.7.0: Lightweight diagnosis snapshot derived from the same multi-signal
38
+ * logic as diagnose_task. Only the type/confidence are surfaced here;
39
+ * call diagnose_task for the full evidence and safe_actions.
40
+ *
41
+ * This field is null when status is already terminal (no diagnosis needed)
42
+ * or when diagnosis itself fails (do not block safe_status).
43
+ */
44
+ diagnosis: {
45
+ type: DiagnosisType;
46
+ confidence: DiagnosisConfidence;
47
+ } | null;
18
48
  }
19
49
  export declare function safeStatus(taskId: string, config?: PatchWardenConfig): SafeStatusOutput;
@@ -5,6 +5,7 @@ import { guardReadPath } from "../security/pathGuard.js";
5
5
  import { guardSensitivePath } from "../security/sensitiveGuard.js";
6
6
  import { readTaskRuntime } from "../taskRuntime.js";
7
7
  import { readWatcherStatus } from "../watcherStatus.js";
8
+ import { diagnoseTask } from "./diagnoseTask.js";
8
9
  export function safeStatus(taskId, config) {
9
10
  const cfg = config || getConfig();
10
11
  const tasksDir = getTasksDir(cfg);
@@ -16,6 +17,8 @@ export function safeStatus(taskId, config) {
16
17
  return {
17
18
  task_id: taskId,
18
19
  status: "not_found",
20
+ legacy_status: null,
21
+ acceptance_status: null,
19
22
  phase: null,
20
23
  created_at: null,
21
24
  started_at: null,
@@ -28,6 +31,8 @@ export function safeStatus(taskId, config) {
28
31
  watcher_state: null,
29
32
  error_code: null,
30
33
  error_summary: null,
34
+ stale_seconds: null,
35
+ diagnosis: null,
31
36
  };
32
37
  }
33
38
  guardReadPath(statusFile, cfg.workspaceRoot, cfg.tasksDir);
@@ -53,9 +58,44 @@ export function safeStatus(taskId, config) {
53
58
  errorCode = status.status;
54
59
  errorSummary = `Task ended with status: ${status.status}`;
55
60
  }
61
+ // v0.7.2: derive legacy_status and acceptance_status
62
+ const statusStr = status.status || "not_found";
63
+ const legacyStatus = (statusStr === "done_by_agent" || statusStr === "accepted") ? "done" : null;
64
+ const VALID_ACCEPTANCE = ["pending", "accepted", "rejected", "needs_fix", "blocked"];
65
+ const acceptanceStatus = statusStr === "done_by_agent"
66
+ ? (typeof status.acceptance_status === "string" && VALID_ACCEPTANCE.includes(status.acceptance_status)
67
+ ? status.acceptance_status
68
+ : "pending") // default for done_by_agent when field missing
69
+ : null;
70
+ // v0.7.0: compute stale_seconds from the most recent heartbeat
71
+ const heartbeatStr = (typeof runtime.last_heartbeat_at === "string" && runtime.last_heartbeat_at) ||
72
+ (typeof status.last_heartbeat_at === "string" && status.last_heartbeat_at) ||
73
+ (typeof status.updated_at === "string" && status.updated_at) ||
74
+ null;
75
+ let staleSeconds = null;
76
+ if (heartbeatStr) {
77
+ const heartbeatMs = Date.parse(heartbeatStr);
78
+ if (Number.isFinite(heartbeatMs)) {
79
+ staleSeconds = Math.max(0, Math.round((Date.now() - heartbeatMs) / 1000));
80
+ }
81
+ }
82
+ // v0.7.0: lightweight diagnosis snapshot — only for non-terminal tasks.
83
+ // Wrap in try/catch so a diagnosis failure never breaks safe_status.
84
+ let diagnosis = null;
85
+ if (statusStr === "running" || statusStr === "collecting_artifacts" || statusStr === "pending") {
86
+ try {
87
+ const result = diagnoseTask({ task_id: taskId }, cfg);
88
+ diagnosis = { type: result.diagnosis, confidence: result.confidence };
89
+ }
90
+ catch {
91
+ diagnosis = null;
92
+ }
93
+ }
56
94
  return {
57
95
  task_id: taskId,
58
- status: status.status || "not_found",
96
+ status: statusStr,
97
+ legacy_status: legacyStatus,
98
+ acceptance_status: acceptanceStatus,
59
99
  phase,
60
100
  created_at: typeof status.created_at === "string" ? status.created_at : null,
61
101
  started_at: typeof status.started_at === "string" ? status.started_at : null,
@@ -68,5 +108,7 @@ export function safeStatus(taskId, config) {
68
108
  watcher_state: watcher.status,
69
109
  error_code: errorCode,
70
110
  error_summary: errorSummary,
111
+ stale_seconds: staleSeconds,
112
+ diagnosis,
71
113
  };
72
114
  }