@mndrk/agx 1.4.20 → 1.4.22

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 (104) hide show
  1. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/BUILD_ID +1 -1
  2. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/app-build-manifest.json +29 -29
  3. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/app-path-routes-manifest.json +4 -4
  4. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/build-manifest.json +2 -2
  5. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/prerender-manifest.json +22 -22
  6. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  7. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/_not-found.html +1 -1
  8. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/_not-found.rsc +2 -2
  9. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/audit/route_client-reference-manifest.js +1 -1
  10. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/auth/[...nextauth]/route_client-reference-manifest.js +1 -1
  11. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/auth/daemon-secret/route_client-reference-manifest.js +1 -1
  12. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/auth/device/code/route_client-reference-manifest.js +1 -1
  13. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/auth/device/token/route_client-reference-manifest.js +1 -1
  14. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/auth/refresh/route_client-reference-manifest.js +1 -1
  15. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/auth/status/route_client-reference-manifest.js +1 -1
  16. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/learnings/route_client-reference-manifest.js +1 -1
  17. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/logs/stream/route_client-reference-manifest.js +1 -1
  18. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/orchestrator/tasks/[taskId]/cancel/route_client-reference-manifest.js +1 -1
  19. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/orchestrator/tasks/[taskId]/signal/route_client-reference-manifest.js +1 -1
  20. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/orchestrator/tasks/[taskId]/start/route_client-reference-manifest.js +1 -1
  21. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/orchestrator/tasks/[taskId]/status/route_client-reference-manifest.js +1 -1
  22. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/projects/[id]/route_client-reference-manifest.js +1 -1
  23. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/projects/route_client-reference-manifest.js +1 -1
  24. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/providers/route_client-reference-manifest.js +1 -1
  25. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/queue/complete/route_client-reference-manifest.js +1 -1
  26. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/queue/route_client-reference-manifest.js +1 -1
  27. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/stage-prompts/route_client-reference-manifest.js +1 -1
  28. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/[id]/comments/[commentId]/route_client-reference-manifest.js +1 -1
  29. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/[id]/comments/route_client-reference-manifest.js +1 -1
  30. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/[id]/heartbeat/route_client-reference-manifest.js +1 -1
  31. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/[id]/history/route_client-reference-manifest.js +1 -1
  32. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/[id]/logs/route_client-reference-manifest.js +1 -1
  33. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/[id]/route_client-reference-manifest.js +1 -1
  34. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/route_client-reference-manifest.js +1 -1
  35. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/tasks/stream/route_client-reference-manifest.js +1 -1
  36. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/user-settings/route_client-reference-manifest.js +1 -1
  37. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/workflows/[id]/nodes/route_client-reference-manifest.js +1 -1
  38. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/workflows/[id]/route_client-reference-manifest.js +1 -1
  39. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/api/workflows/route_client-reference-manifest.js +1 -1
  40. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/auth/callback/route_client-reference-manifest.js +1 -1
  41. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/auth/device/page.js +5 -5
  42. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/auth/device/page_client-reference-manifest.js +1 -1
  43. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/auth/device.html +1 -1
  44. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/auth/device.rsc +3 -3
  45. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/dashboard/page.js +8 -3
  46. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/dashboard/page_client-reference-manifest.js +1 -1
  47. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/dashboard.html +1 -1
  48. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/dashboard.rsc +3 -3
  49. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/index.html +1 -1
  50. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/index.rsc +2 -2
  51. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/login/page_client-reference-manifest.js +1 -1
  52. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/login.html +1 -1
  53. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/login.rsc +2 -2
  54. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/page_client-reference-manifest.js +1 -1
  55. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects/[slug]/page.js +4 -4
  56. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects/[slug]/page_client-reference-manifest.js +1 -1
  57. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects/[slug]/tasks/page_client-reference-manifest.js +1 -1
  58. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects/[slug]/workflow/page_client-reference-manifest.js +1 -1
  59. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  60. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects.html +1 -1
  61. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/projects.rsc +3 -3
  62. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  63. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/settings.html +1 -1
  64. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app/settings.rsc +2 -2
  65. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/app-paths-manifest.json +4 -4
  66. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/chunks/3009.js +5 -6
  67. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/chunks/6125.js +1 -1
  68. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/middleware-manifest.json +5 -5
  69. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/pages/404.html +1 -1
  70. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/pages/500.html +1 -1
  71. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/server-reference-manifest.js +1 -1
  72. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/server/server-reference-manifest.json +1 -1
  73. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/{9337-5d3c6b1828da8ec3.js → 9337-09000d8a6c85f40c.js} +1 -1
  74. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/9719-0fda94fde411f574.js +1 -0
  75. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/app/auth/device/page-e2c2560ec12b421d.js +1 -0
  76. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/app/dashboard/page-7437499eb05d5ce8.js +1 -0
  77. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/app/projects/[slug]/page-253ca8286e8f1d68.js +1 -0
  78. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/css/72371329e4c91108.css +1 -0
  79. package/index.js +212 -63
  80. package/lib/cli/cloud/aggregate.js +162 -0
  81. package/lib/cli/cloud/command.js +230 -0
  82. package/lib/cli/cloud/executeVerifySingle.js +293 -0
  83. package/lib/cli/cloud/executeVerifySwarm.js +302 -0
  84. package/lib/cli/cloud/index.js +68 -0
  85. package/lib/cli/cloud/iterations.js +155 -0
  86. package/lib/cli/cloud/persist.js +123 -0
  87. package/lib/cli/cloud/prompts.js +229 -0
  88. package/lib/cli/cloud/simpleLoops.js +203 -0
  89. package/lib/cli/cloud/taskLogger.js +159 -0
  90. package/lib/cli/cloudArtifacts.js +478 -0
  91. package/lib/cli/onboarding.js +23 -4
  92. package/lib/cli/runCli.js +205 -2200
  93. package/lib/cli/util.js +68 -1
  94. package/lib/cloud/client.js +3 -30
  95. package/lib/config/cloudConfig.js +110 -6
  96. package/lib/config/paths.js +1 -1
  97. package/package.json +1 -1
  98. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/9719-1d7bdd112db709cc.js +0 -1
  99. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/app/auth/device/page-1191b5d80fb53701.js +0 -1
  100. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/app/dashboard/page-2403721dcf6fac4f.js +0 -1
  101. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/chunks/app/projects/[slug]/page-e5b42f6a38ee1959.js +0 -1
  102. package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/css/97623b2fc4a523a7.css +0 -1
  103. /package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/{_UEH0bf2vZJdfFbGlB9rM → M4AQWpnhTFqFD3HFlSHd9}/_buildManifest.js +0 -0
  104. /package/cloud-runtime/standalone/Projects/Agents/agx-cloud/.next/static/{_UEH0bf2vZJdfFbGlB9rM → M4AQWpnhTFqFD3HFlSHd9}/_ssgManifest.js +0 -0
@@ -0,0 +1,302 @@
1
+ /* eslint-disable no-console */
2
+ 'use strict';
3
+
4
+ function createCloudExecuteVerifySwarm(env) {
5
+ const {
6
+ path,
7
+ fs,
8
+ SWARM_RETRIES,
9
+ SWARM_MAX_ITERS,
10
+ VERIFY_TIMEOUT_MS,
11
+ pRetryFn,
12
+ logExecutionFlow,
13
+ resolveStageObjective,
14
+ buildStageRequirementPrompt,
15
+ enforceStageRequirement,
16
+ detectVerifyCommands,
17
+ runVerifyCommands,
18
+ getGitSummary,
19
+ createDaemonArtifactsRecorder,
20
+ runAgxCommand,
21
+ runSwarmIteration,
22
+ buildExecuteIterationPrompt,
23
+ buildVerifyPrompt,
24
+ persistIterationArtifacts,
25
+ finalizeRunSafe,
26
+ buildLocalRunIndexEntry,
27
+ postTaskComment,
28
+ extractJsonLast,
29
+ ensureExplanation,
30
+ ensureNextPrompt,
31
+ abortIfCancelled,
32
+ resolveAggregatorModel,
33
+ signalTemporalTask,
34
+ buildNextPromptWithDecisionContext,
35
+ } = env || {};
36
+
37
+ async function runSwarmExecuteVerifyLoop({ taskId, task, logger, storage, projectSlug, taskSlug, stageLocal, initialPromptContext, cancellationWatcher }) {
38
+ logExecutionFlow('runSwarmExecuteVerifyLoop', 'input', `taskId=${taskId}`);
39
+ const stageKey = task?.stage || 'unknown';
40
+ const stagePrompt = resolveStageObjective(task, stageKey, '');
41
+ const stageRequirement = buildStageRequirementPrompt({ stage: stageKey, stagePrompt });
42
+
43
+ let iteration = 1;
44
+ let nextPrompt = '';
45
+ let lastDecision = null;
46
+ let lastRun = null;
47
+ let lastRunEntry = null;
48
+
49
+ const verifierProvider = String(task?.engine || task?.provider || 'claude').toLowerCase();
50
+ const verifierModel = resolveAggregatorModel(task);
51
+
52
+ while (iteration <= SWARM_MAX_ITERS) {
53
+ logger?.log('system', `[swarm] execute/verify iteration ${iteration} start\n`);
54
+ await abortIfCancelled(cancellationWatcher);
55
+
56
+ const executeRun = await storage.createRun({
57
+ projectSlug,
58
+ taskSlug,
59
+ stage: stageLocal,
60
+ engine: verifierProvider,
61
+ model: verifierModel || undefined,
62
+ });
63
+ lastRun = executeRun;
64
+ const runContainerPath = executeRun?.paths?.root ? path.dirname(executeRun.paths.root) : null;
65
+
66
+ const executeArtifacts = createDaemonArtifactsRecorder({ storage, run: executeRun, taskId });
67
+ if (iteration === 1 && initialPromptContext) {
68
+ executeArtifacts.recordPrompt('Initial Task Context', initialPromptContext);
69
+ }
70
+
71
+ // Tee spawned agx output into files under execute artifacts.
72
+ const execStdoutPath = executeRun?.paths?.artifacts ? path.join(executeRun.paths.artifacts, 'spawned.stdout.log') : null;
73
+ const execStderrPath = executeRun?.paths?.artifacts ? path.join(executeRun.paths.artifacts, 'spawned.stderr.log') : null;
74
+ const execStdoutStream = execStdoutPath ? fs.createWriteStream(execStdoutPath, { flags: 'a' }) : null;
75
+ const execStderrStream = execStderrPath ? fs.createWriteStream(execStderrPath, { flags: 'a' }) : null;
76
+
77
+ // EXECUTE (swarm iteration)
78
+ let results;
79
+ try {
80
+ results = await runSwarmIteration({
81
+ taskId,
82
+ task,
83
+ prompt: nextPrompt ? buildExecuteIterationPrompt(nextPrompt, iteration) : buildExecuteIterationPrompt('', iteration),
84
+ logger,
85
+ artifacts: executeArtifacts,
86
+ cancellationWatcher,
87
+ onProviderStdout: (provider, chunk) => {
88
+ if (!execStdoutStream) return;
89
+ execStdoutStream.write(`[${provider}] ${chunk.toString()}`);
90
+ },
91
+ onProviderStderr: (provider, chunk) => {
92
+ if (!execStderrStream) return;
93
+ execStderrStream.write(`[${provider}] ${chunk.toString()}`);
94
+ },
95
+ });
96
+ } catch (err) {
97
+ executeArtifacts.recordOutput('Execute Error', String(err?.message || err));
98
+ await executeArtifacts.flush();
99
+ try { execStdoutStream?.end(); } catch { }
100
+ try { execStderrStream?.end(); } catch { }
101
+ await storage.failRun(executeRun, { error: err?.message || 'swarm execute failed', code: 'EXECUTE_FAILED' });
102
+ lastDecision = {
103
+ done: false,
104
+ decision: 'failed',
105
+ explanation: err?.message || 'Swarm execute phase failed.',
106
+ final_result: err?.message || 'Swarm execute phase failed.',
107
+ next_prompt: '',
108
+ summary: err?.message || 'Swarm execute phase failed.',
109
+ };
110
+ return { code: 1, decision: lastDecision, lastRun, runIndexEntry: lastRunEntry };
111
+ } finally {
112
+ try { execStdoutStream?.end(); } catch { }
113
+ try { execStderrStream?.end(); } catch { }
114
+ }
115
+
116
+ const combinedOutput = Array.isArray(results)
117
+ ? results.map((r) => `[${r.provider}]\n${r.output || ''}`).join('\n\n')
118
+ : '';
119
+ executeArtifacts.recordOutput(`Swarm Output (iter ${iteration})`, combinedOutput);
120
+ await executeArtifacts.flush();
121
+
122
+ // VERIFY (local commands)
123
+ const verifyCommands = detectVerifyCommands({ cwd: process.cwd() });
124
+ const gitSummary = getGitSummary({ cwd: process.cwd() });
125
+ const verifyResults = await runVerifyCommands(verifyCommands, { cwd: process.cwd(), max_output_chars: 20000 });
126
+
127
+ const verifyRun = await storage.createRun({
128
+ projectSlug,
129
+ taskSlug,
130
+ stage: 'verify',
131
+ runId: executeRun.run_id,
132
+ engine: verifierProvider,
133
+ model: verifierModel || undefined,
134
+ });
135
+ lastRun = verifyRun;
136
+
137
+ // Tee verifier stdout/stderr to files under verify artifacts.
138
+ const verifyStdoutPath = verifyRun?.paths?.artifacts ? path.join(verifyRun.paths.artifacts, 'spawned.stdout.log') : null;
139
+ const verifyStderrPath = verifyRun?.paths?.artifacts ? path.join(verifyRun.paths.artifacts, 'spawned.stderr.log') : null;
140
+ const verifyStdoutStream = verifyStdoutPath ? fs.createWriteStream(verifyStdoutPath, { flags: 'a' }) : null;
141
+ const verifyStderrStream = verifyStderrPath ? fs.createWriteStream(verifyStderrPath, { flags: 'a' }) : null;
142
+
143
+ // VERIFY (LLM)
144
+ const verifyPrompt = buildVerifyPrompt({
145
+ taskId,
146
+ task,
147
+ stagePrompt,
148
+ stageRequirement,
149
+ gitSummary,
150
+ verifyResults,
151
+ iteration,
152
+ lastRunPath: runContainerPath || verifyRun?.paths?.root || null,
153
+ });
154
+ const verifyArtifacts = createDaemonArtifactsRecorder({ storage, run: verifyRun, taskId });
155
+ verifyArtifacts.recordPrompt(`Verification Prompt (${verifierProvider}${verifierModel ? `/${verifierModel}` : ''}, iter ${iteration})`, verifyPrompt);
156
+
157
+ const verifyArgs = [verifierProvider, '--prompt', verifyPrompt, '--print'];
158
+ if (verifierModel) verifyArgs.push('--model', verifierModel);
159
+
160
+ let verifyRes;
161
+ try {
162
+ await abortIfCancelled(cancellationWatcher);
163
+ verifyRes = await pRetryFn(
164
+ () => runAgxCommand(verifyArgs, VERIFY_TIMEOUT_MS, `agx ${verifierProvider} verify`, {
165
+ onStdout: (data) => {
166
+ try { verifyStdoutStream?.write(data.toString()); } catch { }
167
+ logger?.log('checkpoint', data);
168
+ },
169
+ onStderr: (data) => {
170
+ try { verifyStderrStream?.write(data.toString()); } catch { }
171
+ logger?.log('error', data);
172
+ },
173
+ onTrace: (event) => {
174
+ void verifyArtifacts?.recordEngineTrace?.({ provider: verifierProvider, model: verifierModel || null, role: 'swarm-verify' }, event);
175
+ void signalTemporalTask(taskId, 'daemonStep', {
176
+ kind: 'runAgxCommand',
177
+ task_id: taskId,
178
+ provider: verifierProvider,
179
+ model: verifierModel || null,
180
+ role: 'swarm-verify',
181
+ iteration,
182
+ ...event,
183
+ });
184
+ },
185
+ cancellationWatcher,
186
+ }),
187
+ { retries: SWARM_RETRIES }
188
+ );
189
+ } catch (err) {
190
+ verifyArtifacts.recordOutput('Verifier Error', String(err?.message || err));
191
+ await persistIterationArtifacts(storage, { runContainerPath, executeRun, verifyRun, decision: {}, verifyCommands, verifyResults, gitSummary });
192
+ await verifyArtifacts.flush();
193
+ try { verifyStdoutStream?.end(); } catch { }
194
+ try { verifyStderrStream?.end(); } catch { }
195
+ await storage.failRun(verifyRun, { error: err?.message || 'verify failed', code: 'VERIFY_FAILED' });
196
+ await finalizeRunSafe(storage, executeRun, { status: 'failed', reason: `Verification failed: ${err?.message || 'verify failed'}` });
197
+ lastDecision = {
198
+ done: false,
199
+ decision: 'failed',
200
+ explanation: err?.message || 'Verifier failed.',
201
+ final_result: err?.message || 'Verifier failed.',
202
+ next_prompt: '',
203
+ summary: err?.message || 'Verifier failed.',
204
+ };
205
+ return { code: 1, decision: lastDecision, lastRun, runIndexEntry: lastRunEntry };
206
+ } finally {
207
+ try { verifyStdoutStream?.end(); } catch { }
208
+ try { verifyStderrStream?.end(); } catch { }
209
+ }
210
+
211
+ const verifierText = verifyRes?.stdout || verifyRes?.stderr || '';
212
+ verifyArtifacts.recordOutput(`Verifier Output (${verifierProvider}${verifierModel ? `/${verifierModel}` : ''}, iter ${iteration})`, verifierText);
213
+
214
+ let decision = extractJsonLast(verifierText);
215
+ if (!decision) decision = extractJsonLast(verifyRes?.stderr || '');
216
+ if (!decision) {
217
+ decision = {
218
+ done: false,
219
+ decision: 'failed',
220
+ explanation: 'Verifier returned invalid JSON.',
221
+ final_result: 'Verifier returned invalid JSON.',
222
+ next_prompt: '',
223
+ summary: 'Verifier returned invalid JSON.',
224
+ };
225
+ }
226
+
227
+ decision = ensureExplanation(ensureNextPrompt(enforceStageRequirement({
228
+ done: Boolean(decision.done),
229
+ decision: typeof decision.decision === 'string' ? decision.decision : '',
230
+ explanation: typeof decision.explanation === 'string' ? decision.explanation : '',
231
+ final_result: typeof decision.final_result === 'string' ? decision.final_result : '',
232
+ next_prompt: typeof decision.next_prompt === 'string' ? decision.next_prompt : '',
233
+ summary: typeof decision.summary === 'string' ? decision.summary : '',
234
+ plan_md: typeof decision.plan_md === 'string' ? decision.plan_md : '',
235
+ implementation_summary_md: typeof decision.implementation_summary_md === 'string' ? decision.implementation_summary_md : '',
236
+ verification_md: typeof decision.verification_md === 'string' ? decision.verification_md : '',
237
+ }, { stage: stageKey, stagePrompt })));
238
+
239
+ lastDecision = decision;
240
+ await persistIterationArtifacts(storage, { runContainerPath, executeRun, verifyRun, decision, verifyCommands, verifyResults, gitSummary });
241
+
242
+ verifyArtifacts.recordOutput('Daemon Decision', JSON.stringify(decision || {}, null, 2));
243
+ await verifyArtifacts.flush();
244
+
245
+ const statusMap = {
246
+ done: 'done',
247
+ blocked: 'blocked',
248
+ not_done: 'continue',
249
+ failed: 'failed',
250
+ };
251
+ const localDecisionStatus = statusMap[String(decision?.decision || 'failed')] || 'failed';
252
+ await finalizeRunSafe(storage, executeRun, {
253
+ status: localDecisionStatus,
254
+ reason: 'Execute phase completed; see verify stage for decision.',
255
+ });
256
+ await storage.finalizeRun(verifyRun, {
257
+ status: localDecisionStatus,
258
+ reason: decision?.explanation || decision?.summary || '',
259
+ });
260
+
261
+ lastRunEntry = await buildLocalRunIndexEntry(storage, verifyRun, localDecisionStatus);
262
+
263
+ const localTaskStatusMap = {
264
+ done: 'done',
265
+ blocked: 'blocked',
266
+ not_done: 'running',
267
+ failed: 'failed',
268
+ };
269
+ const nextLocalStatus = localTaskStatusMap[String(decision?.decision || 'failed')] || 'failed';
270
+ await storage.updateTaskState(projectSlug, taskSlug, { status: nextLocalStatus });
271
+
272
+ await postTaskComment(taskId, decision.summary || decision.explanation || '');
273
+
274
+ if (['done', 'blocked', 'failed'].includes(String(decision?.decision || ''))) {
275
+ const code = decision?.decision === 'done' ? 0 : 1;
276
+ return { code, decision: lastDecision, lastRun, runIndexEntry: lastRunEntry };
277
+ }
278
+
279
+ nextPrompt = (typeof buildNextPromptWithDecisionContext === 'function'
280
+ ? buildNextPromptWithDecisionContext(decision)
281
+ : (decision?.next_prompt || ''));
282
+ iteration += 1;
283
+ }
284
+
285
+ if (!lastDecision) {
286
+ lastDecision = {
287
+ done: false,
288
+ decision: 'not_done',
289
+ explanation: `Swarm run reached max iterations (${SWARM_MAX_ITERS}).`,
290
+ final_result: `Swarm run reached max iterations (${SWARM_MAX_ITERS}).`,
291
+ next_prompt: '',
292
+ summary: `Swarm run reached max iterations (${SWARM_MAX_ITERS}).`,
293
+ };
294
+ }
295
+
296
+ return { code: 1, decision: lastDecision, lastRun, runIndexEntry: lastRunEntry };
297
+ }
298
+
299
+ return { runSwarmExecuteVerifyLoop };
300
+ }
301
+
302
+ module.exports = { createCloudExecuteVerifySwarm };
@@ -0,0 +1,68 @@
1
+ /* eslint-disable no-console */
2
+ 'use strict';
3
+
4
+ const { createCloudCommandHelpers } = require('./command');
5
+ const { createCloudPromptHelpers } = require('./prompts');
6
+ const { createCloudPersistenceHelpers } = require('./persist');
7
+ const { createCloudIterationHelpers } = require('./iterations');
8
+ const { createCloudAggregateHelpers } = require('./aggregate');
9
+ const { createCloudExecuteVerifySingle } = require('./executeVerifySingle');
10
+ const { createCloudExecuteVerifySwarm } = require('./executeVerifySwarm');
11
+ const { createCloudSimpleLoops } = require('./simpleLoops');
12
+ const { createCloudTaskHelpers } = require('./taskLogger');
13
+
14
+ function createCloudRunner(env) {
15
+ const baseEnv = env || {};
16
+
17
+ const task = createCloudTaskHelpers(baseEnv);
18
+ baseEnv.patchTaskState = task.patchTaskState;
19
+ baseEnv.createTaskLogger = task.createTaskLogger;
20
+
21
+ const command = createCloudCommandHelpers(baseEnv);
22
+ baseEnv.updateCloudTask = command.updateCloudTask;
23
+ baseEnv.runAgxCommand = command.runAgxCommand;
24
+
25
+ const prompts = createCloudPromptHelpers(baseEnv);
26
+ baseEnv.resolveAggregatorModel = prompts.resolveAggregatorModel;
27
+ baseEnv.buildAggregatorPrompt = prompts.buildAggregatorPrompt;
28
+ baseEnv.truncateForPrompt = prompts.truncateForPrompt;
29
+ baseEnv.buildExecuteIterationPrompt = prompts.buildExecuteIterationPrompt;
30
+ baseEnv.buildVerifyPrompt = prompts.buildVerifyPrompt;
31
+
32
+ const persistence = createCloudPersistenceHelpers(baseEnv);
33
+ baseEnv.appendRunContainerLog = persistence.appendRunContainerLog;
34
+ baseEnv.finalizeRunSafe = persistence.finalizeRunSafe;
35
+ baseEnv.persistIterationArtifacts = persistence.persistIterationArtifacts;
36
+
37
+ const iterations = createCloudIterationHelpers(baseEnv);
38
+ baseEnv.runSwarmIteration = iterations.runSwarmIteration;
39
+ baseEnv.runSingleAgentIteration = iterations.runSingleAgentIteration;
40
+
41
+ const aggregate = createCloudAggregateHelpers(baseEnv);
42
+ baseEnv.runSingleAgentAggregate = aggregate.runSingleAgentAggregate;
43
+ baseEnv.runSwarmAggregate = aggregate.runSwarmAggregate;
44
+
45
+ const execVerifySingle = createCloudExecuteVerifySingle(baseEnv);
46
+ baseEnv.runSingleAgentExecuteVerifyLoop = execVerifySingle.runSingleAgentExecuteVerifyLoop;
47
+
48
+ const execVerifySwarm = createCloudExecuteVerifySwarm(baseEnv);
49
+ baseEnv.runSwarmExecuteVerifyLoop = execVerifySwarm.runSwarmExecuteVerifyLoop;
50
+
51
+ const simpleLoops = createCloudSimpleLoops(baseEnv);
52
+ baseEnv.runSingleAgentLoop = simpleLoops.runSingleAgentLoop;
53
+ baseEnv.runSwarmLoop = simpleLoops.runSwarmLoop;
54
+
55
+ return {
56
+ ...task,
57
+ ...command,
58
+ ...prompts,
59
+ ...persistence,
60
+ ...iterations,
61
+ ...aggregate,
62
+ ...execVerifySingle,
63
+ ...execVerifySwarm,
64
+ ...simpleLoops,
65
+ };
66
+ }
67
+
68
+ module.exports = { createCloudRunner };
@@ -0,0 +1,155 @@
1
+ /* eslint-disable no-console */
2
+ 'use strict';
3
+
4
+ function createCloudIterationHelpers(env) {
5
+ const {
6
+ SWARM_PROVIDERS,
7
+ SWARM_TIMEOUT_MS,
8
+ SWARM_RETRIES,
9
+ pMap,
10
+ pRetryFn,
11
+ commandExists,
12
+ logExecutionFlow,
13
+ runAgxCommand,
14
+ updateCloudTask,
15
+ abortIfCancelled,
16
+ // Note: additional helpers (comments, artifacts) are handled by higher-level loops.
17
+ } = env || {};
18
+
19
+ async function runSwarmIteration({ taskId, task, prompt, logger, artifacts, cancellationWatcher, onProviderStdout, onProviderStderr }) {
20
+ logExecutionFlow('runSwarmIteration', 'input', `taskId=${taskId}, prompt=${Boolean(prompt)}`);
21
+ const swarmModels = Array.isArray(task?.swarm_models)
22
+ ? task.swarm_models
23
+ .filter((entry) => entry && entry.provider && entry.model)
24
+ .map((entry) => ({
25
+ provider: String(entry.provider).toLowerCase(),
26
+ model: String(entry.model)
27
+ }))
28
+ : [];
29
+
30
+ const providers = (swarmModels.length ? swarmModels.map((m) => m.provider) : SWARM_PROVIDERS)
31
+ .map((p) => p.toLowerCase());
32
+
33
+ const missing = providers.filter((p) => !commandExists(p));
34
+ if (missing.length) {
35
+ throw new Error(`Missing providers for swarm run: ${missing.join(', ')}`);
36
+ }
37
+
38
+ logExecutionFlow('runSwarmIteration', 'processing', `providers=${providers.join(',')}`);
39
+ logger?.log('system', `[swarm] iteration start\n`);
40
+
41
+ const results = await pMap(providers, (provider, index) => {
42
+ const args = [provider, '--cloud-task', taskId];
43
+ const modelForProvider = swarmModels.length
44
+ ? swarmModels[index]?.model || null
45
+ : null;
46
+ if (modelForProvider) {
47
+ args.push('--model', modelForProvider);
48
+ }
49
+ if (prompt) {
50
+ // The agent already receives full task context via --cloud-task; keep the per-iteration
51
+ // prompt narrowly scoped to the next instruction to avoid duplicating context.
52
+ args.push('--prompt', String(prompt));
53
+ }
54
+
55
+ return pRetryFn(
56
+ () => runAgxCommand(args, SWARM_TIMEOUT_MS, `agx ${provider}`, {
57
+ onStdout: (data) => {
58
+ if (typeof onProviderStdout === 'function') onProviderStdout(provider, data);
59
+ logger?.log('output', data);
60
+ },
61
+ onStderr: (data) => {
62
+ if (typeof onProviderStderr === 'function') onProviderStderr(provider, data);
63
+ logger?.log('error', data);
64
+ },
65
+ onTrace: (event) => {
66
+ void artifacts?.recordEngineTrace?.({ provider, model: swarmModels.length ? (swarmModels[index]?.model || null) : null, role: 'swarm-iteration' }, event);
67
+
68
+ if (taskId) {
69
+ if (event.phase === 'start' && event.pid) {
70
+ void updateCloudTask(taskId, { pid: event.pid, started_at: event.started_at });
71
+ }
72
+ if (event.phase === 'exit') {
73
+ void updateCloudTask(taskId, { exit_code: event.exit_code, completed_at: event.finished_at });
74
+ }
75
+ }
76
+ }
77
+ ,
78
+ cancellationWatcher,
79
+ }),
80
+ {
81
+ retries: SWARM_RETRIES,
82
+ }
83
+ ).then((res) => ({
84
+ provider,
85
+ output: res.stdout || res.stderr || ''
86
+ }));
87
+ }, { concurrency: providers.length });
88
+
89
+ for (const result of results) {
90
+ logger?.log('output', `\n[${result.provider}] ${result.output}\n`);
91
+ }
92
+
93
+ logExecutionFlow('runSwarmIteration', 'output', `providers finished count=${results.length}`);
94
+ return results;
95
+ }
96
+
97
+ async function runSingleAgentIteration({ taskId, task, provider, model, prompt, logger, onStdout, onStderr, artifacts, cancellationWatcher }) {
98
+ logExecutionFlow('runSingleAgentIteration', 'input', `taskId=${taskId}, provider=${provider}, model=${model}, prompt=${Boolean(prompt) ? 'present' : 'none'}`);
99
+ logExecutionFlow('runSingleAgentIteration', 'processing', 'preparing runAgxCommand');
100
+ const args = [provider, '--cloud-task', taskId];
101
+ if (model) {
102
+ args.push('--model', model);
103
+ }
104
+
105
+ // Record iteration prompt for artifacts
106
+ // For iteration 1, prompt is empty because context comes via --cloud-task
107
+ // For subsequent iterations, prompt contains the next_prompt from aggregation
108
+ const iterationLabel = `Agent Iteration Prompt (${provider}${model ? `/${model}` : ''})`;
109
+ if (prompt) {
110
+ const iterPrompt = String(prompt);
111
+ artifacts?.recordPrompt(iterationLabel, iterPrompt);
112
+ args.push('--prompt', iterPrompt);
113
+ } else {
114
+ // First iteration uses --cloud-task context (already recorded as Initial Task Context)
115
+ artifacts?.recordPrompt(iterationLabel, `(First iteration: using --cloud-task ${taskId} context)`);
116
+ }
117
+
118
+
119
+ await abortIfCancelled(cancellationWatcher);
120
+ const res = await pRetryFn(
121
+ () => runAgxCommand(args, SWARM_TIMEOUT_MS, `agx ${provider}`, {
122
+ onStdout: (data) => {
123
+ if (onStdout) onStdout(data);
124
+ logger?.log('output', data);
125
+ },
126
+ onStderr: (data) => {
127
+ if (onStderr) onStderr(data);
128
+ logger?.log('error', data);
129
+ },
130
+ onTrace: (event) => {
131
+ void artifacts?.recordEngineTrace?.({ provider, model: model || null, role: 'single-iteration' }, event);
132
+
133
+ if (taskId) {
134
+ if (event.phase === 'start' && event.pid) {
135
+ void updateCloudTask(taskId, { pid: event.pid, started_at: event.started_at });
136
+ }
137
+ if (event.phase === 'exit') {
138
+ void updateCloudTask(taskId, { exit_code: event.exit_code, completed_at: event.finished_at });
139
+ }
140
+ }
141
+ },
142
+ cancellationWatcher,
143
+ }),
144
+ { retries: SWARM_RETRIES }
145
+ );
146
+
147
+ const outputSource = res.stdout || res.stderr || '';
148
+ logExecutionFlow('runSingleAgentIteration', 'output', `response length=${outputSource.length}`);
149
+ return res.stdout || res.stderr || '';
150
+ }
151
+
152
+ return { runSwarmIteration, runSingleAgentIteration };
153
+ }
154
+
155
+ module.exports = { createCloudIterationHelpers };
@@ -0,0 +1,123 @@
1
+ /* eslint-disable no-console */
2
+ 'use strict';
3
+
4
+ function createCloudPersistenceHelpers(env) {
5
+ const { fs, path, buildLocalRunIndexEntry } = env || {};
6
+
7
+ async function appendRunContainerLog(runContainerPath, relativePath, text) {
8
+ if (!runContainerPath || !relativePath || !text) return;
9
+ const filePath = path.join(runContainerPath, relativePath);
10
+ try {
11
+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
12
+ const payload = String(text);
13
+ await fs.promises.appendFile(filePath, payload.endsWith('\n') ? payload : `${payload}\n`, 'utf8');
14
+ } catch { }
15
+ }
16
+
17
+ async function finalizeRunSafe(storage, run, decision) {
18
+ if (!storage || !run || run.finalized) return;
19
+ try {
20
+ await storage.finalizeRun(run, decision);
21
+ } catch { }
22
+ }
23
+
24
+ async function persistIterationArtifacts(storage, { runContainerPath, executeRun, verifyRun, decision, verifyCommands, verifyResults, gitSummary }) {
25
+ if (!storage) return;
26
+
27
+ const safeText = (v) => (typeof v === 'string' ? v : '');
28
+
29
+ // Ensure the run container has a plan folder so the layout is always:
30
+ // <task_slug>/<run_id>/{plan,execute,verify}
31
+ if (runContainerPath) {
32
+ try {
33
+ await fs.promises.mkdir(path.join(runContainerPath, 'plan'), { recursive: true });
34
+ } catch { }
35
+ }
36
+
37
+ const planMd = safeText(decision?.plan_md) || '# Plan\n\n- (not provided)\n';
38
+ const implMd = safeText(decision?.implementation_summary_md) || '# Implementation Summary\n\n- (not provided)\n';
39
+ const verificationMd = safeText(decision?.verification_md) || '# Verification\n\nDONE: no\n\n- (not provided)\n';
40
+
41
+ // Write the plan markdown into the plan folder (not under execute/verify).
42
+ if (runContainerPath) {
43
+ try {
44
+ await fs.promises.writeFile(path.join(runContainerPath, 'plan', 'plan.md'), planMd.endsWith('\n') ? planMd : `${planMd}\n`, 'utf8');
45
+ } catch { }
46
+ }
47
+
48
+ // Implementation summary belongs with the execution phase.
49
+ if (executeRun?.paths?.artifacts) {
50
+ try {
51
+ await storage.writeArtifact(executeRun, 'implementation_summary.md', implMd.endsWith('\n') ? implMd : `${implMd}\n`);
52
+ } catch (err) {
53
+ await appendRunContainerLog(runContainerPath, 'daemon/artifact_errors.log', `[${new Date().toISOString()}] execute artifact write failed: ${err?.message || err}`);
54
+ }
55
+ }
56
+
57
+ // Verification outputs (including command logs) belong with the verify phase.
58
+ if (verifyRun?.paths?.artifacts) {
59
+ try {
60
+ await storage.writeArtifact(verifyRun, 'verification.md', verificationMd.endsWith('\n') ? verificationMd : `${verificationMd}\n`);
61
+ } catch (err) {
62
+ await appendRunContainerLog(runContainerPath, 'daemon/artifact_errors.log', `[${new Date().toISOString()}] verify artifact write failed (verification.md): ${err?.message || err}`);
63
+ }
64
+
65
+ const payload = {
66
+ commands: Array.isArray(verifyCommands) ? verifyCommands : [],
67
+ results: Array.isArray(verifyResults) ? verifyResults.map((r) => ({
68
+ id: r.id,
69
+ label: r.label,
70
+ cmd: r.cmd,
71
+ args: r.args,
72
+ cwd: r.cwd,
73
+ exit_code: r.exit_code,
74
+ duration_ms: r.duration_ms,
75
+ error: r.error,
76
+ })) : [],
77
+ git: gitSummary || null,
78
+ };
79
+
80
+ try {
81
+ await storage.writeArtifact(verifyRun, 'verify_commands.json', JSON.stringify(payload, null, 2) + '\n');
82
+ } catch (err) {
83
+ await appendRunContainerLog(runContainerPath, 'daemon/artifact_errors.log', `[${new Date().toISOString()}] verify artifact write failed (verify_commands.json): ${err?.message || err}`);
84
+ }
85
+
86
+ if (Array.isArray(verifyResults)) {
87
+ for (let i = 0; i < verifyResults.length; i += 1) {
88
+ const r = verifyResults[i];
89
+ const base = `verify_results/${String(i + 1).padStart(2, '0')}-${String(r.id || `cmd_${i + 1}`).replace(/[^a-z0-9_-]/gi, '_')}`;
90
+ try { await storage.writeArtifact(verifyRun, `${base}.stdout.txt`, (r.stdout || '').toString()); } catch { }
91
+ try { await storage.writeArtifact(verifyRun, `${base}.stderr.txt`, (r.stderr || '').toString()); } catch { }
92
+ }
93
+ }
94
+
95
+ if (gitSummary?.status_porcelain) {
96
+ try { await storage.writeArtifact(verifyRun, 'git_status.txt', String(gitSummary.status_porcelain)); } catch { }
97
+ }
98
+ if (gitSummary?.diff_stat) {
99
+ try { await storage.writeArtifact(verifyRun, 'git_diffstat.txt', String(gitSummary.diff_stat)); } catch { }
100
+ }
101
+ }
102
+ }
103
+
104
+ async function buildRunIndexEntrySafe(storage, verifyRun, localDecisionStatus) {
105
+ if (!storage || !verifyRun || !localDecisionStatus) return null;
106
+ if (typeof buildLocalRunIndexEntry !== 'function') return null;
107
+ try {
108
+ return await buildLocalRunIndexEntry(storage, verifyRun, localDecisionStatus);
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ return {
115
+ appendRunContainerLog,
116
+ finalizeRunSafe,
117
+ persistIterationArtifacts,
118
+ buildRunIndexEntrySafe,
119
+ };
120
+ }
121
+
122
+ module.exports = { createCloudPersistenceHelpers };
123
+