@h-rig/cli 0.0.6-alpha.1 → 0.0.6-alpha.100

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 (120) hide show
  1. package/README.md +18 -19
  2. package/dist/bin/build-rig-binaries.d.ts +2 -0
  3. package/dist/bin/build-rig-binaries.js +22 -10
  4. package/dist/bin/rig.d.ts +72 -0
  5. package/dist/bin/rig.js +15742 -7203
  6. package/dist/config/rig-default-config.yml +5 -0
  7. package/dist/src/app/drone-ui.d.ts +34 -0
  8. package/dist/src/app/drone-ui.js +278 -0
  9. package/dist/src/commands/_async-ui.d.ts +10 -0
  10. package/dist/src/commands/_async-ui.js +121 -0
  11. package/dist/src/commands/_cli-format.d.ts +56 -0
  12. package/dist/src/commands/_cli-format.js +319 -0
  13. package/dist/src/commands/_config-env.d.ts +18 -0
  14. package/dist/src/commands/_config-env.js +22 -0
  15. package/dist/src/commands/_connection-state.d.ts +54 -0
  16. package/dist/src/commands/_connection-state.js +75 -11
  17. package/dist/src/commands/_doctor-checks.d.ts +46 -0
  18. package/dist/src/commands/_doctor-checks.js +95 -244
  19. package/dist/src/commands/_help-catalog.d.ts +29 -0
  20. package/dist/src/commands/_help-catalog.js +146 -0
  21. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  22. package/dist/src/commands/_inprocess-services.js +102 -0
  23. package/dist/src/commands/_json-output.d.ts +11 -0
  24. package/dist/src/commands/_json-output.js +60 -0
  25. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  26. package/dist/src/commands/_lazy-reconcile.js +102 -0
  27. package/dist/src/commands/_parsers.d.ts +15 -0
  28. package/dist/src/commands/_parsers.js +18 -11
  29. package/dist/src/commands/_paths.d.ts +11 -0
  30. package/dist/src/commands/_paths.js +1 -1
  31. package/dist/src/commands/_pi-frontend.d.ts +35 -0
  32. package/dist/src/commands/_pi-frontend.js +64 -0
  33. package/dist/src/commands/_pi-install.d.ts +42 -0
  34. package/dist/src/commands/_pi-install.js +19 -36
  35. package/dist/src/commands/_policy.d.ts +8 -0
  36. package/dist/src/commands/_policy.js +67 -19
  37. package/dist/src/commands/_probes.d.ts +1 -0
  38. package/dist/src/commands/_run-bridge.d.ts +114 -0
  39. package/dist/src/commands/_run-bridge.js +387 -0
  40. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  41. package/dist/src/commands/_run-diagnostics.js +51 -0
  42. package/dist/src/commands/_run-driver-helpers.d.ts +26 -0
  43. package/dist/src/commands/_run-driver-helpers.js +79 -230
  44. package/dist/src/commands/_run-projection.d.ts +50 -0
  45. package/dist/src/commands/_run-projection.js +349 -0
  46. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  47. package/dist/src/commands/_run-subcommands.js +31 -0
  48. package/dist/src/commands/_spinner.d.ts +25 -0
  49. package/dist/src/commands/_spinner.js +65 -0
  50. package/dist/src/commands/agent.d.ts +3 -0
  51. package/dist/src/commands/agent.js +8690 -235
  52. package/dist/src/commands/config.d.ts +3 -0
  53. package/dist/src/commands/config.js +181 -0
  54. package/dist/src/commands/dist.d.ts +28 -0
  55. package/dist/src/commands/dist.js +44 -29
  56. package/dist/src/commands/doctor.d.ts +3 -0
  57. package/dist/src/commands/doctor.js +214 -245
  58. package/dist/src/commands/github.d.ts +3 -0
  59. package/dist/src/commands/github.js +237 -171
  60. package/dist/src/commands/inbox.d.ts +28 -0
  61. package/dist/src/commands/inbox.js +530 -111
  62. package/dist/src/commands/init.d.ts +64 -0
  63. package/dist/src/commands/init.js +941 -654
  64. package/dist/src/commands/inspect.d.ts +20 -0
  65. package/dist/src/commands/inspect.js +709 -119
  66. package/dist/src/commands/pi.d.ts +3 -0
  67. package/dist/src/commands/pi.js +177 -0
  68. package/dist/src/commands/plugin.d.ts +16 -0
  69. package/dist/src/commands/plugin.js +576 -29
  70. package/dist/src/commands/profile-and-review.d.ts +4 -0
  71. package/dist/src/commands/profile-and-review.js +112 -67
  72. package/dist/src/commands/queue.d.ts +3 -0
  73. package/dist/src/commands/queue.js +20 -20
  74. package/dist/src/commands/remote.d.ts +3 -0
  75. package/dist/src/commands/remote.js +883 -50
  76. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  77. package/dist/src/commands/repo-git-harness.js +78 -28
  78. package/dist/src/commands/run.d.ts +21 -0
  79. package/dist/src/commands/run.js +17732 -618
  80. package/dist/src/commands/server.d.ts +3 -0
  81. package/dist/src/commands/server.js +166 -285
  82. package/dist/src/commands/setup.d.ts +16 -0
  83. package/dist/src/commands/setup.js +230 -267
  84. package/dist/src/commands/stats.d.ts +15 -0
  85. package/dist/src/commands/stats.js +632 -0
  86. package/dist/src/commands/task-run-driver.d.ts +94 -0
  87. package/dist/src/commands/task-run-driver.js +120 -1856
  88. package/dist/src/commands/task.d.ts +35 -0
  89. package/dist/src/commands/task.js +676 -1183
  90. package/dist/src/commands/test.d.ts +3 -0
  91. package/dist/src/commands/test.js +15 -8
  92. package/dist/src/commands/triage.d.ts +11 -0
  93. package/dist/src/commands/triage.js +227 -0
  94. package/dist/src/commands/workspace.d.ts +3 -0
  95. package/dist/src/commands/workspace.js +18 -11
  96. package/dist/src/commands.d.ts +13 -0
  97. package/dist/src/commands.js +16760 -7779
  98. package/dist/src/index.d.ts +4 -0
  99. package/dist/src/index.js +16880 -8223
  100. package/dist/src/launcher.d.ts +61 -0
  101. package/dist/src/launcher.js +81 -13
  102. package/dist/src/operator-cli.d.ts +2 -0
  103. package/dist/src/operator-cli.js +17867 -0
  104. package/dist/src/operator-entry.d.ts +1 -0
  105. package/dist/src/operator-entry.js +3 -0
  106. package/dist/src/runner.d.ts +47 -0
  107. package/dist/src/runner.js +19 -24
  108. package/dist/src/withMutedConsole.d.ts +2 -0
  109. package/package.json +21 -7
  110. package/dist/src/commands/_authority-runs.js +0 -110
  111. package/dist/src/commands/_operator-view.js +0 -322
  112. package/dist/src/commands/_preflight.js +0 -460
  113. package/dist/src/commands/_server-client.js +0 -364
  114. package/dist/src/commands/_snapshot-upload.js +0 -313
  115. package/dist/src/commands/_task-picker.js +0 -48
  116. package/dist/src/commands/browser.js +0 -890
  117. package/dist/src/commands/connect.js +0 -180
  118. package/dist/src/commands/inspector.js +0 -256
  119. package/dist/src/commands/task-report-bug.js +0 -1083
  120. package/dist/src/report-bug.js +0 -260
@@ -1,1924 +1,188 @@
1
1
  // @bun
2
2
  // packages/cli/src/commands/task-run-driver.ts
3
- import { copyFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, statSync } from "fs";
4
- import { resolve as resolve4 } from "path";
5
- import { spawn, spawnSync } from "child_process";
6
- import { createInterface as createLineInterface } from "readline";
7
-
8
- // packages/cli/src/runner.ts
9
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
11
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
12
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
13
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
14
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
16
- function formatCommand(parts) {
17
- return parts.map((part) => /[^a-zA-Z0-9_./:-]/.test(part) ? JSON.stringify(part) : part).join(" ");
18
- }
19
-
20
- // packages/cli/src/commands/task-run-driver.ts
21
- import { loadConfig } from "@rig/core/load-config";
22
- import {
23
- listAgentRuntimes,
24
- startRuntimeSnapshotSidecar
25
- } from "@rig/runtime/control-plane/runtime/isolation";
26
- import {
27
- finalizeTaskRunSnapshot,
28
- resolveTaskRunSnapshotSidecar
29
- } from "@rig/runtime/control-plane/runtime/snapshot/task-run";
30
- import { loadRuntimeSnapshotConfig } from "@rig/runtime/control-plane/runtime/guard";
31
- import {
32
- buildClaudeLogsFromRecord,
33
- flushPendingClaudeToolUseLogs
34
- } from "@rig/runtime/control-plane/provider/claude-stream-records";
35
- import {
36
- buildCodexLogsFromRecord,
37
- extractCodexAssistantMessageText,
38
- flushPendingCodexToolUseLogs,
39
- isCodexExecRecord
40
- } from "@rig/runtime/control-plane/provider/codex-exec-records";
41
- import { resolvePreferredShellBinary } from "@rig/runtime/control-plane/native/run-ops";
42
- import { readAuthorityRun as readAuthorityRun3, readJsonFile, resolveTaskArtifactDirs } from "@rig/runtime/control-plane/authority-files";
43
- import {
44
- buildTaskRunLifecycleComment,
45
- updateConfiguredTaskSourceTask
46
- } from "@rig/runtime/control-plane/tasks/source-lifecycle";
47
- import {
48
- closeIssueAfterMergedPr,
49
- commitRunChanges,
50
- runPrAutomation
51
- } from "@rig/runtime/control-plane/native/pr-automation";
52
-
53
- // packages/cli/src/commands/_run-driver-helpers.ts
54
- import { readFileSync } from "fs";
55
- import { resolve as resolve3 } from "path";
56
- import {
57
- appendJsonlRecord,
58
- readAuthorityRun as readAuthorityRun2,
59
- resolveAuthorityRunDir as resolveAuthorityRunDir2,
60
- writeJsonFile as writeJsonFile2
61
- } from "@rig/runtime/control-plane/authority-files";
62
- import { taskLookup } from "@rig/runtime/control-plane/native/task-ops";
63
- import { buildProviderTaskRunInstructionLines } from "@rig/runtime/control-plane/provider/runtime-instructions";
64
- import { loadRigTaskRunSkillBody } from "@rig/runtime/control-plane/provider/rig-task-run-skill";
65
-
66
- // packages/cli/src/commands/_authority-runs.ts
67
- import { existsSync } from "fs";
68
- import { resolve as resolve2 } from "path";
69
- import {
70
- readAuthorityRun,
71
- readJsonlFile,
72
- resolveAuthorityRunDir,
73
- writeJsonFile
74
- } from "@rig/runtime/control-plane/authority-files";
75
-
76
- // packages/cli/src/commands/_paths.ts
3
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "fs";
77
4
  import { resolve } from "path";
78
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
79
- function resolveControlPlaneMonorepoRoot(projectRoot) {
80
- return resolveMonorepoRoot(projectRoot);
81
- }
82
- function resolveControlPlaneTaskConfigPath(projectRoot) {
83
- return resolve(resolveControlPlaneMonorepoRoot(projectRoot), ".rig", "task-config.json");
84
- }
85
-
86
- // packages/cli/src/commands/_authority-runs.ts
87
- var RIG_WORKSPACE_ID = "rig-local-workspace";
88
- function normalizeRuntimeAdapter(value) {
89
- const normalized = value?.trim().toLowerCase();
90
- if (!normalized) {
91
- return "pi";
92
- }
93
- if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
94
- return "codex";
95
- }
96
- if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
97
- return "pi";
98
- }
99
- return "claude-code";
100
- }
101
- function readLatestBeadRecord(projectRoot, taskId) {
102
- const issuesPath = resolve2(resolveControlPlaneMonorepoRoot(projectRoot), ".beads", "issues.jsonl");
103
- if (!existsSync(issuesPath)) {
104
- return null;
105
- }
106
- let latest = null;
107
- for (const issue of readJsonlFile(issuesPath)) {
108
- if (!issue || typeof issue !== "object") {
109
- continue;
110
- }
111
- const record = issue;
112
- if (record.id === taskId) {
113
- latest = record;
114
- }
115
- }
116
- return latest;
117
- }
118
- function resolveTaskTitleForAuthorityRun(projectRoot, taskId) {
119
- try {
120
- const record = readLatestBeadRecord(projectRoot, taskId);
121
- const title = record && typeof record.title === "string" ? record.title.trim() : "";
122
- if (title) {
123
- return title;
124
- }
125
- } catch {}
126
- return null;
127
- }
128
- function upsertAgentAuthorityRun(projectRoot, input) {
129
- const current = readAuthorityRun(projectRoot, input.runId);
130
- const existing = current;
131
- const createdAt = existing?.createdAt ?? input.createdAt;
132
- const runtimeMode = typeof existing?.runtimeMode === "string" ? existing.runtimeMode : "full-access";
133
- const interactionMode = typeof existing?.interactionMode === "string" ? existing.interactionMode : "default";
134
- const runMode = typeof existing?.runMode === "string" ? existing.runMode : "autonomous";
135
- const runtimeAdapter = normalizeRuntimeAdapter(input.runtimeAdapter ?? existing?.runtimeAdapter ?? "claude-code");
136
- const title = resolveTaskTitleForAuthorityRun(projectRoot, input.taskId) ?? input.taskId;
137
- const next = {
138
- runId: input.runId,
139
- projectRoot,
140
- workspaceId: existing?.workspaceId ?? RIG_WORKSPACE_ID,
141
- taskId: input.taskId,
142
- threadId: existing?.threadId ?? null,
143
- mode: "local",
144
- runtimeAdapter,
145
- status: input.status,
146
- createdAt,
147
- startedAt: input.startedAt ?? existing?.startedAt ?? null,
148
- completedAt: input.completedAt ?? existing?.completedAt ?? null,
149
- endpointId: existing?.endpointId ?? null,
150
- hostId: existing?.hostId ?? null,
151
- worktreePath: input.worktreePath ?? existing?.worktreePath ?? null,
152
- artifactRoot: input.artifactRoot ?? existing?.artifactRoot ?? null,
153
- logRoot: input.logRoot ?? existing?.logRoot ?? null,
154
- sessionPath: input.sessionPath ?? existing?.sessionPath ?? null,
155
- sessionLogPath: input.sessionLogPath ?? existing?.sessionLogPath ?? null,
156
- pid: input.pid ?? existing?.pid ?? null,
157
- updatedAt: input.createdAt,
158
- title,
159
- model: typeof existing?.model === "string" ? existing.model : null,
160
- runtimeMode,
161
- interactionMode,
162
- runMode,
163
- initialPrompt: typeof existing?.initialPrompt === "string" ? existing.initialPrompt : null
164
- };
165
- if (input.errorText !== undefined) {
166
- next.errorText = input.errorText;
167
- } else if ("errorText" in next) {
168
- delete next.errorText;
169
- }
170
- writeJsonFile(resolve2(resolveAuthorityRunDir(projectRoot, input.runId), "run.json"), next);
171
- return next;
172
- }
173
-
174
- // packages/cli/src/commands/_run-driver-helpers.ts
175
- function patchAuthorityRun(projectRoot, runId, patch) {
176
- const current = readAuthorityRun2(projectRoot, runId);
177
- if (!current) {
178
- throw new CliError2(`Run not found: ${runId}`, 2);
179
- }
180
- const next = {
181
- ...current,
182
- ...patch,
183
- updatedAt: new Date().toISOString()
184
- };
185
- writeJsonFile2(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "run.json"), next);
186
- return next;
187
- }
188
- function touchAuthorityRun(projectRoot, runId) {
189
- const current = readAuthorityRun2(projectRoot, runId);
190
- if (!current) {
191
- return;
192
- }
193
- writeJsonFile2(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "run.json"), {
194
- ...current,
195
- updatedAt: new Date().toISOString()
196
- });
197
- }
198
- function appendRunTimeline(projectRoot, runId, value) {
199
- appendJsonlRecord(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "timeline.jsonl"), value);
200
- touchAuthorityRun(projectRoot, runId);
201
- }
202
- function appendRunLog(projectRoot, runId, value) {
203
- appendJsonlRecord(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "logs.jsonl"), value);
204
- touchAuthorityRun(projectRoot, runId);
205
- }
206
- function appendRunAction(projectRoot, runId, value) {
207
- appendJsonlRecord(resolve3(resolveAuthorityRunDir2(projectRoot, runId), "timeline.jsonl"), {
208
- id: value.id,
209
- type: "action",
210
- actionType: value.actionType,
211
- title: value.title,
212
- detail: value.detail ?? null,
213
- state: value.state,
214
- createdAt: value.startedAt,
215
- completedAt: value.completedAt ?? null,
216
- payload: value.payload ?? {}
217
- });
218
- }
219
- function startRunAction(projectRoot, runId, input) {
220
- const startedAt = new Date().toISOString();
221
- appendRunAction(projectRoot, runId, {
222
- id: input.actionId,
223
- actionType: input.actionType,
224
- title: input.title,
225
- detail: input.detail,
226
- state: "running",
227
- startedAt,
228
- payload: input.payload
229
- });
230
- emitServerRunEvent({ type: "timeline", runId });
231
- return {
232
- startedAt,
233
- complete: (detail, payload) => {
234
- appendRunAction(projectRoot, runId, {
235
- id: input.actionId,
236
- actionType: input.actionType,
237
- title: input.title,
238
- detail: detail ?? input.detail ?? null,
239
- state: "completed",
240
- startedAt,
241
- completedAt: new Date().toISOString(),
242
- payload: payload ?? input.payload
243
- });
244
- emitServerRunEvent({ type: "timeline", runId });
245
- },
246
- fail: (detail, payload) => {
247
- appendRunAction(projectRoot, runId, {
248
- id: input.actionId,
249
- actionType: input.actionType,
250
- title: input.title,
251
- detail,
252
- state: "failed",
253
- startedAt,
254
- completedAt: new Date().toISOString(),
255
- payload: payload ?? input.payload
256
- });
257
- emitServerRunEvent({ type: "timeline", runId });
258
- }
259
- };
260
- }
261
- function emitServerRunEvent(event) {
262
- console.log(`__RIG_RUN_EVENT__${JSON.stringify({ ...event, at: new Date().toISOString() })}`);
263
- }
264
- function buildRunPrompt(input) {
265
- const initialPrompt = input.initialPrompt?.trim() || null;
266
- if (!input.taskId) {
267
- return initialPrompt ?? input.fallbackTitle?.trim() ?? "Continue the requested Rig run and complete the work.";
268
- }
269
- const issues = (() => {
270
- try {
271
- return taskLookup(input.projectRoot, input.taskId);
272
- } catch {
273
- return "";
274
- }
275
- })();
276
- const scopeText = (() => {
277
- try {
278
- const parsed = JSON.parse(readFileSync(resolveControlPlaneTaskConfigPath(input.projectRoot), "utf8"));
279
- const entry = parsed[input.taskId] ?? {};
280
- const scope = Array.isArray(entry.scope) ? entry.scope.filter((item) => typeof item === "string") : [];
281
- const validation = Array.isArray(entry.validation) ? entry.validation.filter((item) => typeof item === "string") : [];
282
- const lines = [];
283
- if (scope.length > 0)
284
- lines.push(`Scope:
285
- - ${scope.join(`
286
- - `)}`);
287
- if (validation.length > 0)
288
- lines.push(`Validation:
289
- - ${validation.join(`
290
- - `)}`);
291
- return lines.join(`
292
-
293
- `);
294
- } catch {
295
- return "";
296
- }
297
- })();
298
- const bead = readLatestBeadRecord(input.projectRoot, input.taskId);
299
- const sourceTask = input.sourceTask ?? null;
300
- const sourceDescription = firstPromptString(sourceTask?.description, sourceTask?.body);
301
- const sourceAcceptance = firstPromptString(sourceTask?.acceptanceCriteria, sourceTask?.acceptance_criteria);
302
- const sourceValidation = uniqueStrings([...sourceTask?.validation ?? [], ...sourceTask?.validators ?? []]);
303
- const title = (bead && typeof bead === "object" && typeof bead.title === "string" ? bead.title : null) ?? firstPromptString(sourceTask?.title) ?? input.fallbackTitle ?? issues ?? input.taskId;
304
- const description = (bead && typeof bead === "object" && typeof bead.description === "string" ? bead.description : null) ?? sourceDescription ?? input.fallbackDescription ?? "";
305
- const acceptance = bead && typeof bead === "object" && typeof bead.acceptance_criteria === "string" ? bead.acceptance_criteria : sourceAcceptance ?? input.fallbackAcceptanceCriteria ?? "";
306
- const sourceContractLines = renderSourceTaskContract(sourceTask, sourceValidation);
307
- const providerLines = buildProviderTaskRunInstructionLines(input.runtimeAdapter);
308
- const skillBody = loadRigTaskRunSkillBody();
309
- return [
310
- `You are working on task ${input.taskId}: ${title}.`,
311
- description ? `Description:
312
- ${description}` : null,
313
- acceptance ? `Acceptance criteria:
314
- ${acceptance}` : null,
315
- sourceContractLines.length > 0 ? `Source task contract:
316
- ${sourceContractLines.join(`
317
- `)}` : null,
318
- scopeText || renderSourceScopeValidation(sourceTask, sourceValidation) || null,
319
- initialPrompt ? `Additional operator guidance:
320
- ${initialPrompt}` : null,
321
- providerLines.length > 0 ? `Provider-specific runtime tooling:
322
- ${providerLines.join(" ")}` : null,
323
- skillBody || null
324
- ].filter((value) => Boolean(value)).join(`
325
-
326
- `);
327
- }
328
- function firstPromptString(...values) {
329
- for (const value of values) {
330
- const trimmed = typeof value === "string" ? value.trim() : "";
331
- if (trimmed.length > 0) {
332
- return trimmed;
333
- }
334
- }
335
- return null;
336
- }
337
- function uniqueStrings(values) {
338
- return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)));
339
- }
340
- function renderSourceTaskContract(task, validation) {
341
- if (!task) {
342
- return [];
343
- }
344
- const lines = [];
345
- const sourceIssueId = firstPromptString(task.sourceIssueId);
346
- if (sourceIssueId)
347
- lines.push(`Source issue: ${sourceIssueId}`);
348
- const status = firstPromptString(task.status);
349
- if (status)
350
- lines.push(`Source status: ${status}`);
351
- const issueType = firstPromptString(task.issueType);
352
- if (issueType)
353
- lines.push(`Issue type: ${issueType}`);
354
- const role = firstPromptString(task.role);
355
- if (role)
356
- lines.push(`Role: ${role}`);
357
- const externalRef = firstPromptString(task.externalRef);
358
- if (externalRef)
359
- lines.push(`External ref: ${externalRef}`);
360
- const labels = uniqueStrings(task.labels ?? []);
361
- if (labels.length > 0)
362
- lines.push(`Labels:
363
- - ${labels.join(`
364
- - `)}`);
365
- if (validation.length > 0)
366
- lines.push(`Validators:
367
- - ${validation.join(`
368
- - `)}`);
369
- return lines;
370
- }
371
- function renderSourceScopeValidation(task, validation) {
372
- if (!task) {
373
- return "";
374
- }
375
- const lines = [];
376
- const scope = uniqueStrings(task.scope ?? []);
377
- if (scope.length > 0)
378
- lines.push(`Scope:
379
- - ${scope.join(`
380
- - `)}`);
381
- if (validation.length > 0)
382
- lines.push(`Validation:
383
- - ${validation.join(`
384
- - `)}`);
385
- return lines.join(`
386
-
387
- `);
388
- }
389
-
390
- // packages/cli/src/commands/task-run-driver.ts
391
- var PI_CANONICAL_RUN_STAGES = [
392
- "Connect",
393
- "GitHub/task sync",
394
- "Prepare workspace",
395
- "Launch Pi",
396
- "Plan",
397
- "Implement",
398
- "Validate",
399
- "Commit",
400
- "Open PR",
401
- "Review/CI",
402
- "Merge",
403
- "Complete"
404
- ];
5
+ import { createEnvCloseoutRunners } from "@rig/runtime/control-plane/native/closeout-runners";
6
+ import {
7
+ runInProcessCloseout
8
+ } from "@rig/runtime/control-plane/native/in-process-closeout";
9
+ import { updateRunTaskSourceLifecycle } from "@rig/runtime/control-plane/tasks/source-lifecycle";
10
+ var PI_CANONICAL_RUN_STAGES = ["Connect", "Prepare", "Execute", "Validate", "Review", "Publish", "Complete"];
405
11
  function canonicalPiRunStages() {
406
12
  return [...PI_CANONICAL_RUN_STAGES];
407
13
  }
408
14
  function buildPiRigBridgeEnv(input) {
409
15
  return {
410
- RIG_PROJECT_ROOT: input.projectRoot,
411
16
  PROJECT_RIG_ROOT: input.projectRoot,
412
17
  RIG_RUN_ID: input.runId,
413
- RIG_SERVER_RUN_ID: input.runId,
414
- RIG_TASK_ID: input.taskId,
415
- RIG_RUNTIME_ADAPTER: "pi",
416
- ...input.serverUrl ? { RIG_SERVER_URL: input.serverUrl } : {},
417
- ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
418
- ...input.githubToken ? { RIG_GITHUB_TOKEN: input.githubToken } : {}
18
+ ...input.taskId ? { RIG_TASK_ID: input.taskId } : {},
19
+ ...input.runtimeMode ? { RIG_RUNTIME_MODE: input.runtimeMode } : {},
20
+ ...input.model ? { RIG_MODEL: input.model } : {}
419
21
  };
420
22
  }
421
- function runGitSync(cwd, args, input) {
422
- const result = spawnSync("git", [...args], {
423
- cwd,
424
- input,
425
- encoding: "utf8",
426
- stdio: input === undefined ? ["ignore", "pipe", "pipe"] : ["pipe", "pipe", "pipe"]
427
- });
428
- return {
429
- ok: result.status === 0,
430
- stdout: result.stdout || "",
431
- stderr: result.stderr || (result.error instanceof Error ? result.error.message : "")
432
- };
433
- }
434
- function copyUntrackedDirtyFiles(sourceRoot, targetRoot) {
435
- const listed = runGitSync(sourceRoot, ["ls-files", "--others", "--exclude-standard", "-z"]);
436
- if (!listed.ok || !listed.stdout)
23
+ function copyTree(sourceRoot, targetRoot) {
24
+ if (!existsSync(sourceRoot))
437
25
  return 0;
438
26
  let copied = 0;
439
- for (const relativePath of listed.stdout.split("\x00").filter(Boolean)) {
440
- const sourcePath = resolve4(sourceRoot, relativePath);
441
- const targetPath = resolve4(targetRoot, relativePath);
442
- try {
443
- if (!statSync(sourcePath).isFile())
444
- continue;
445
- mkdirSync(resolve4(targetPath, ".."), { recursive: true });
446
- copyFileSync(sourcePath, targetPath);
447
- copied += 1;
448
- } catch {}
27
+ for (const entry of readdirSync(sourceRoot, { withFileTypes: true })) {
28
+ const sourcePath = resolve(sourceRoot, entry.name);
29
+ const targetPath = resolve(targetRoot, entry.name);
30
+ if (entry.isDirectory()) {
31
+ mkdirSync(targetPath, { recursive: true });
32
+ copied += copyTree(sourcePath, targetPath);
33
+ continue;
34
+ }
35
+ mkdirSync(resolve(targetPath, ".."), { recursive: true });
36
+ copyFileSync(sourcePath, targetPath);
37
+ copied += 1;
449
38
  }
450
39
  return copied;
451
40
  }
452
41
  function applyDirtyBaselineSnapshot(input) {
453
- const diff = runGitSync(input.sourceRoot, ["diff", "--binary", "HEAD"]);
454
- if (!diff.ok) {
455
- return { applied: false, copiedUntracked: 0, detail: diff.stderr || "git diff failed" };
456
- }
457
- let applied = false;
458
- if (diff.stdout.trim()) {
459
- const apply = runGitSync(input.targetRoot, ["apply", "--whitespace=nowarn", "-"], diff.stdout);
460
- if (!apply.ok) {
461
- return { applied: false, copiedUntracked: 0, detail: apply.stderr || "git apply failed" };
462
- }
463
- applied = true;
464
- }
465
- const copiedUntracked = copyUntrackedDirtyFiles(input.sourceRoot, input.targetRoot);
42
+ mkdirSync(input.targetRoot, { recursive: true });
43
+ const copied = copyTree(input.sourceRoot, input.targetRoot);
466
44
  return {
467
- applied: applied || copiedUntracked > 0,
468
- copiedUntracked,
469
- detail: applied || copiedUntracked > 0 ? `Applied dirty baseline snapshot (${copiedUntracked} untracked files).` : "No dirty baseline changes to apply."
45
+ applied: copied > 0,
46
+ copiedUntracked: copied,
47
+ detail: copied > 0 ? `Copied ${copied} file(s) into the runtime workspace.` : "No files copied."
470
48
  };
471
49
  }
472
50
  function buildTaskRunReviewEnv(config) {
473
- const review = config?.review;
474
51
  return {
475
- ...review?.mode ? { AI_REVIEW_MODE: review.mode } : {},
476
- ...review?.provider ? { AI_REVIEW_PROVIDER: review.provider } : {}
52
+ ...config?.review?.mode ? { AI_REVIEW_MODE: config.review.mode } : {},
53
+ ...config?.review?.provider ? { AI_REVIEW_PROVIDER: config.review.provider } : {}
477
54
  };
478
55
  }
479
- function positiveInt(value, fallback) {
480
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
56
+ function buildDirtyBaselineHandshakeEnv(input) {
57
+ return {
58
+ RIG_DIRTY_BASELINE_MODE: input.baselineMode,
59
+ RIG_DIRTY_BASELINE_READY_FILE: resolve(input.projectRoot, ".rig", "state", `${input.runId}.dirty-ready`)
60
+ };
481
61
  }
482
62
  function resolveTaskRunAutomationLimits(config, env = process.env) {
483
- const configuredValidationAttempts = positiveInt(config?.automation?.maxValidationAttempts, 30);
484
- const configuredPrFixIterations = positiveInt(config?.automation?.maxPrFixIterations, 30);
63
+ const maxValidationAttempts = Number.parseInt(env.RIG_MAX_VALIDATION_ATTEMPTS ?? "", 10);
64
+ const maxPrFixIterations = Number.parseInt(env.RIG_MAX_PR_FIX_ITERATIONS ?? "", 10);
485
65
  return {
486
- maxValidationAttempts: parsePositiveInt(env.RIG_TASK_RUN_MAX_ATTEMPTS, "RIG_TASK_RUN_MAX_ATTEMPTS", configuredValidationAttempts),
487
- maxPrFixIterations: configuredPrFixIterations
66
+ maxValidationAttempts: Number.isFinite(maxValidationAttempts) && maxValidationAttempts > 0 ? maxValidationAttempts : config?.automation?.maxValidationAttempts ?? 30,
67
+ maxPrFixIterations: Number.isFinite(maxPrFixIterations) && maxPrFixIterations > 0 ? maxPrFixIterations : config?.automation?.maxPrFixIterations ?? 100500
488
68
  };
489
69
  }
490
70
  function classifyPlanningNeed(input) {
491
- const planning = input.config?.planning ?? {};
492
- const mode = planning.mode ?? "auto";
493
- const labels = new Set((input.sourceTask?.labels ?? []).map((label) => label.trim().toLowerCase()).filter(Boolean));
494
- const requireLabels = planning.requireForLabels ?? ["needs-plan", "epic", "large", "risk:high"];
495
- const skipLabels = planning.skipForLabels ?? ["no-plan", "small", "trivial"];
496
- const bodyLength = `${input.sourceTask?.description ?? ""}
497
- ${input.sourceTask?.body ?? ""}
498
- ${input.sourceTask?.acceptanceCriteria ?? input.sourceTask?.acceptance_criteria ?? ""}`.trim().length;
499
- const forcedLabel = requireLabels.find((label) => labels.has(label.toLowerCase()));
500
- const skippedLabel = skipLabels.find((label) => labels.has(label.toLowerCase()));
501
- const highRisk = labels.has("risk:high") || labels.has("security") || labels.has("migration");
502
- const size = labels.has("large") || bodyLength > 4000 ? "large" : bodyLength > 1000 ? "medium" : "small";
503
- const risk = highRisk ? "high" : labels.has("risk:medium") || size !== "small" ? "medium" : "low";
504
- if (mode === "always") {
505
- return { planningRequired: true, size, risk, reason: "planning.mode=always", policy: "always" };
506
- }
507
- if (mode === "off") {
508
- return { planningRequired: false, size, risk, reason: "planning.mode=off", policy: "off" };
509
- }
510
- if (forcedLabel) {
511
- return { planningRequired: true, size, risk, reason: `label:${forcedLabel}`, policy: "auto" };
512
- }
513
- if (skippedLabel && !highRisk) {
514
- return { planningRequired: false, size, risk, reason: `label:${skippedLabel}`, policy: "auto" };
515
- }
516
- const planningRequired = size !== "small" || risk === "high";
517
- return {
518
- planningRequired,
519
- size,
520
- risk,
521
- reason: planningRequired ? `auto:${size}/${risk}` : "auto:small/low",
522
- policy: "auto"
523
- };
71
+ const text = `${input.prompt}
72
+ ${input.acceptanceCriteria ?? ""}`.toLowerCase();
73
+ const needsPlanning = /plan|design|approach|architecture|multi-step/.test(text);
74
+ return { needsPlanning, reason: needsPlanning ? "operator requested a planning pass" : "no planning trigger detected" };
524
75
  }
525
76
  function buildPiValidationRetrySteeringPrompt(input) {
526
77
  return [
527
- `Retry attempt ${input.attempt + 1}/${input.maxAttempts} for task ${input.taskId}.`,
528
- "The previous attempt failed Rig validation. Continue from the existing runtime workspace and PR state instead of starting over.",
529
- "",
530
- `Latest blocker: ${input.failureDetail}`,
531
- ...input.validationOutput?.trim() ? ["", "Validation output:", input.validationOutput.trim()] : [],
532
- "",
533
- "Fix the concrete failure, rerun the relevant validation, and only report completion when the task is accepted."
78
+ `Validation failed on attempt ${input.attempt}${input.taskId ? ` for task ${input.taskId}` : ""}.`,
79
+ input.failureDetail.trim(),
80
+ "Fix the issue, rerun validation, and continue only after it passes."
534
81
  ].join(`
82
+
535
83
  `);
536
84
  }
537
85
  function classifyValidationRetryOutcome(input) {
538
86
  return {
539
87
  stage: "Validate failed",
540
- status: input.attempt >= input.maxAttempts ? "needs_attention" : "retry",
88
+ status: input.attempt < input.maxAttempts ? "retry" : "needs_attention",
541
89
  failureDetail: input.failureDetail
542
90
  };
543
91
  }
544
- function configuredIssueUpdatesMode(config) {
545
- const github = config?.github;
546
- const mode = github && typeof github === "object" && !Array.isArray(github) ? github.issueUpdates : null;
547
- return mode === "off" || mode === "minimal" || mode === "lifecycle" ? mode : "lifecycle";
548
- }
549
- function shouldWriteDriverIssueUpdate(config, status) {
550
- const mode = configuredIssueUpdatesMode(config);
551
- if (mode === "off")
552
- return false;
553
- if (mode === "lifecycle")
554
- return true;
555
- return ["closed", "failed", "needs_attention"].includes(status);
556
- }
557
- async function loadTaskRunAutomationConfig(projectRoot) {
558
- try {
559
- return await loadConfig(projectRoot);
560
- } catch {
561
- return null;
562
- }
563
- }
564
92
  function taskRunStageLogId(runId, stage) {
565
93
  return `log:${runId}:stage:${stage.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
566
94
  }
567
- function appendPiStageLog(input) {
568
- appendRunLog(input.projectRoot, input.runId, {
569
- id: taskRunStageLogId(input.runId, input.stage),
570
- title: input.stage,
571
- detail: input.detail ?? null,
572
- tone: input.tone ?? "info",
573
- status: input.status ?? "running",
574
- createdAt: new Date().toISOString()
575
- });
576
- emitServerRunEvent({ type: "log", runId: input.runId, title: input.stage });
577
- }
578
- async function runCheckedCommand(command, args, cwd, label = "git") {
579
- const result = await command(args, { cwd });
580
- if (result.exitCode !== 0) {
581
- throw new Error(`${label} ${args.join(" ")} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim());
582
- }
583
- }
584
- function createCommandRunner(binary) {
585
- return async (args, options) => {
586
- const child = spawn(binary, [...args], {
587
- cwd: options?.cwd,
588
- stdio: ["ignore", "pipe", "pipe"]
589
- });
590
- const stdoutChunks = [];
591
- const stderrChunks = [];
592
- child.stdout.on("data", (chunk) => stdoutChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))));
593
- child.stderr.on("data", (chunk) => stderrChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))));
594
- return await new Promise((resolve5) => {
595
- child.once("error", (error) => resolve5({ exitCode: 1, stderr: error.message }));
596
- child.once("close", (code) => resolve5({
597
- exitCode: code ?? 1,
598
- stdout: Buffer.concat(stdoutChunks).toString("utf8"),
599
- stderr: Buffer.concat(stderrChunks).toString("utf8")
600
- }));
601
- });
602
- };
603
- }
604
- async function resolvePostValidationBranch(input) {
605
- if (!input.configuredBranch.startsWith("task-")) {
606
- return input.configuredBranch;
607
- }
608
- const current = await input.gitCommand(["rev-parse", "--abbrev-ref", "HEAD"], { cwd: input.workspace });
609
- const currentBranch = current.stdout?.trim();
610
- if (current.exitCode === 0 && currentBranch && currentBranch !== "HEAD") {
611
- return currentBranch;
612
- }
613
- return input.configuredBranch;
614
- }
615
- async function runTaskRunPostValidationLifecycle(input) {
616
- const taskId = input.taskId?.trim();
617
- if (!taskId) {
618
- return { status: "skipped" };
619
- }
620
- const config = input.config ?? {};
621
- const prMode = config.pr?.mode ?? "auto";
622
- if (prMode === "off" || prMode === "ask") {
623
- input.appendStage?.("Open PR", prMode === "off" ? "PR automation disabled by pr.mode=off." : "PR creation awaiting operator approval by pr.mode=ask.", "skipped", "info");
624
- input.appendStage?.("Complete", "Validation completed; no PR was opened and the issue was left open.", "completed", "info");
625
- return { status: "skipped" };
626
- }
627
- const workspace = input.runtimeWorkspace || input.projectRoot;
628
- const ghCommand = input.ghCommand ?? createCommandRunner("gh");
629
- const gitCommand = input.gitCommand ?? createCommandRunner("git");
630
- const configuredBranch = input.branch || `rig/${input.runtimeTaskId}-${input.runId}`;
631
- const branch = await resolvePostValidationBranch({
632
- workspace,
633
- configuredBranch,
634
- gitCommand
635
- });
636
- const prAutomation = input.prAutomation ?? runPrAutomation;
637
- const updateTaskSource = input.updateTaskSource ?? updateConfiguredTaskSourceTask;
638
- const stage = input.appendStage ?? (() => {
639
- return;
640
- });
641
- const steerPi = input.steerPi ?? (async (message) => {
642
- appendRunLog(input.projectRoot, input.runId, {
643
- id: `log:${input.runId}:pr-steering:${Date.now()}`,
644
- title: "Steering Pi from PR feedback",
645
- detail: message,
646
- tone: "info",
647
- status: "reviewing",
648
- createdAt: new Date().toISOString()
649
- });
650
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Steering Pi from PR feedback" });
651
- });
652
- stage("Commit", `Committing changes in ${workspace}.`, "running", "tool");
653
- const commit = await commitRunChanges({
654
- cwd: workspace,
655
- message: `rig: complete task ${taskId}`,
656
- command: gitCommand
657
- });
658
- stage("Commit", commit.committed ? "Committed run workspace changes." : "No workspace changes to commit.", "completed", "tool");
659
- await runCheckedCommand(gitCommand, ["push", "--set-upstream", "origin", branch], workspace, "git");
660
- stage("Open PR", `Opening PR from ${branch}.`, "running", "tool");
661
- const pr = await prAutomation({
662
- projectRoot: workspace,
663
- taskId,
664
- runId: input.runId,
665
- branch,
666
- config,
667
- sourceTask: input.sourceTask,
668
- uploadedSnapshot: input.uploadedSnapshot,
669
- command: ghCommand,
670
- steerPi,
671
- lifecycle: {
672
- onPrOpened: async ({ prUrl }) => {
673
- stage("Open PR", prUrl, "completed", "tool");
674
- try {
675
- if (shouldWriteDriverIssueUpdate(config, "under_review")) {
676
- await updateTaskSource(input.projectRoot, {
677
- taskId,
678
- sourceTask: runSourceTaskIdentity(input.sourceTask),
679
- update: {
680
- status: "under_review",
681
- comment: buildTaskRunLifecycleComment({
682
- runId: input.runId,
683
- status: "under_review",
684
- summary: "Rig opened a pull request for this task.",
685
- runtimeWorkspace: input.runtimeWorkspace ?? null
686
- })
687
- }
688
- });
689
- }
690
- } catch (error) {
691
- appendRunLog(input.projectRoot, input.runId, {
692
- id: `log:${input.runId}:task-source-under-review-update`,
693
- title: "Task source PR status update failed",
694
- detail: error instanceof Error ? error.message : String(error),
695
- tone: "error",
696
- status: "reviewing",
697
- createdAt: new Date().toISOString()
698
- });
699
- }
700
- },
701
- onReviewCiStarted: ({ prUrl, iteration }) => stage("Review/CI", `${prUrl} (iteration ${iteration})`, "running", "info"),
702
- onFeedback: async ({ feedback }) => {
703
- stage("Review/CI", feedback.join(`
704
- `), "reviewing", "error");
705
- if (shouldWriteDriverIssueUpdate(config, "ci_fixing")) {
706
- await updateTaskSource(input.projectRoot, {
707
- taskId,
708
- sourceTask: runSourceTaskIdentity(input.sourceTask),
709
- update: {
710
- status: "ci_fixing",
711
- comment: buildTaskRunLifecycleComment({
712
- runId: input.runId,
713
- status: "ci_fixing",
714
- summary: "Rig is fixing CI/review feedback for this task.",
715
- runtimeWorkspace: input.runtimeWorkspace ?? null
716
- })
717
- }
718
- }).catch(() => {
719
- return;
720
- });
721
- }
722
- },
723
- onMergeStarted: async ({ prUrl }) => {
724
- stage("Merge", prUrl, "running", "tool");
725
- if (shouldWriteDriverIssueUpdate(config, "merging")) {
726
- await updateTaskSource(input.projectRoot, {
727
- taskId,
728
- sourceTask: runSourceTaskIdentity(input.sourceTask),
729
- update: {
730
- status: "merging",
731
- comment: buildTaskRunLifecycleComment({
732
- runId: input.runId,
733
- status: "merging",
734
- summary: "Rig is merging the pull request for this task.",
735
- runtimeWorkspace: input.runtimeWorkspace ?? null
736
- })
737
- }
738
- }).catch(() => {
739
- return;
740
- });
741
- }
742
- },
743
- onMerged: ({ prUrl }) => stage("Merge", prUrl, "completed", "tool")
744
- }
745
- });
746
- if (pr.status === "opened" && pr.prUrl) {
747
- stage("Complete", `PR ready without merge: ${pr.prUrl}`, "completed", "info");
748
- return { status: "completed", pr };
749
- }
750
- if (pr.status !== "merged" || !pr.prUrl) {
751
- const detail = pr.actionableFeedback.join(`
752
- `) || "PR automation did not merge the PR.";
753
- stage("Needs attention", detail, "needs_attention", "error");
754
- if (shouldWriteDriverIssueUpdate(config, "needs_attention")) {
755
- await updateTaskSource(input.projectRoot, {
756
- taskId,
757
- sourceTask: runSourceTaskIdentity(input.sourceTask),
758
- update: {
759
- status: "needs_attention",
760
- comment: buildTaskRunLifecycleComment({
761
- runId: input.runId,
762
- status: "needs_attention",
763
- summary: "Rig needs operator attention before this task can proceed.",
764
- runtimeWorkspace: input.runtimeWorkspace ?? null,
765
- errorText: detail
766
- })
767
- }
768
- }).catch(() => {
769
- return;
770
- });
771
- }
772
- return { status: "needs_attention", pr };
773
- }
774
- if (shouldWriteDriverIssueUpdate(config, "closed")) {
775
- await closeIssueAfterMergedPr({
776
- projectRoot: input.projectRoot,
777
- taskId,
778
- runId: input.runId,
779
- prUrl: pr.prUrl,
780
- sourceTask: input.sourceTask,
781
- updateTaskSource: async (projectRoot, closeInput) => updateTaskSource(projectRoot, closeInput)
782
- });
783
- }
784
- stage("Complete", `PR merged and issue closed: ${pr.prUrl}`, "completed", "info");
785
- return { status: "completed", pr };
786
- }
787
- function summarizeValidationFailure(projectRoot, taskId) {
788
- if (!taskId) {
789
- return null;
790
- }
791
- for (const artifactDir of resolveTaskArtifactDirs(projectRoot, taskId)) {
792
- const summary = readJsonFile(resolve4(artifactDir, "validation-summary.json"), null);
793
- if (!summary || summary.status !== "fail") {
794
- continue;
795
- }
796
- const failedCategories = Array.isArray(summary.categories) ? summary.categories.filter((entry) => String(entry?.status ?? "") !== "pass").map((entry) => String(entry?.category ?? "").trim()).filter(Boolean) : [];
797
- if (failedCategories.length > 0) {
798
- return `Task validation failed: ${failedCategories.join(", ")}`;
799
- }
800
- return "Task validation failed.";
801
- }
802
- return null;
803
- }
804
- function classifyCompletionVerificationLine(line) {
805
- const trimmed = line.trim();
806
- if (/^=== Completion Verification: /.test(trimmed)) {
807
- return { isCompletionLine: true, isVerifierReview: false };
808
- }
809
- if (/^\[\d+\/\d+\]/.test(trimmed)) {
810
- return {
811
- isCompletionLine: true,
812
- isVerifierReview: /Verifier review/i.test(trimmed)
813
- };
814
- }
815
- return { isCompletionLine: false, isVerifierReview: false };
816
- }
817
95
  function createRunLogIdFactory(runId) {
818
- let sequence = 0;
819
- return () => {
820
- sequence += 1;
821
- return `log:${runId}:${Date.now()}:${sequence}`;
822
- };
96
+ let next = 0;
97
+ return () => `${runId}:log:${++next}`;
823
98
  }
824
99
  function summarizeTaskRunProcessFailure(input) {
825
- const fallback = `Task run failed (${String(input.exitCode ?? "unknown")}${input.signal ? ` ${input.signal}` : ""})`;
826
- const stderrLines = input.stderrLines ?? [];
827
- const meaningfulLines = [...stderrLines].map((line) => line.trim()).filter(Boolean).filter((line) => !/^Task run failed \([^)]*\)$/i.test(line));
828
- const taskSourceFailure = meaningfulLines.find((line) => /failed to update task source/i.test(line));
829
- if (taskSourceFailure) {
830
- return `Task source update failed: ${taskSourceFailure}`;
831
- }
832
- const moduleFailure = meaningfulLines.find((line) => /cannot find module/i.test(line));
833
- if (moduleFailure) {
834
- return `Runtime module resolution failed: ${moduleFailure}`;
835
- }
836
- for (const line of [...meaningfulLines].reverse()) {
837
- const trimmed = line.trim();
838
- if (/server-managed task run cannot finish successfully/i.test(trimmed)) {
839
- return `Task source remained open: ${trimmed}`;
840
- }
841
- if (/no api key found/i.test(trimmed)) {
842
- return `Missing provider credentials: ${trimmed}`;
843
- }
844
- if (/no claude credentials found/i.test(trimmed)) {
845
- return `Missing provider credentials: ${trimmed}`;
846
- }
847
- if (/unauthorized|authentication failed|invalid api key|api key is invalid/i.test(trimmed)) {
848
- return `Provider authentication failed: ${trimmed}`;
849
- }
850
- if (/command not found|no such file or directory|enoent/i.test(trimmed)) {
851
- return `Missing runtime executable: ${trimmed}`;
852
- }
853
- if (/bubblewrap|\bbwrap\b|sandbox-exec|sandbox/i.test(trimmed) && /missing|not found|failed|denied/i.test(trimmed)) {
854
- return `Sandbox backend unavailable: ${trimmed}`;
855
- }
856
- }
857
- return fallback;
100
+ const detail = [input.stderr?.trim(), input.stdout?.trim()].filter(Boolean)[0];
101
+ return `${input.stage} failed${input.exitCode !== null && input.exitCode !== undefined ? ` (exit ${input.exitCode})` : ""}${detail ? `: ${detail}` : input.fallback ? `: ${input.fallback}` : ""}`;
858
102
  }
859
- function parsePositiveInt(value, option, fallback) {
860
- if (!value) {
861
- return fallback;
862
- }
863
- const parsed = Number.parseInt(value, 10);
864
- if (!Number.isFinite(parsed) || parsed <= 0) {
865
- throw new CliError2(`Invalid ${option} value: ${value}`);
103
+ function classifyCompletionVerificationLine(line) {
104
+ if (line.startsWith("=== Completion Verification:")) {
105
+ return { isCompletionLine: true, stage: line.replace(/^=== Completion Verification:\s*/, "").replace(/\s*=+$/, "").trim(), status: "started" };
866
106
  }
867
- return parsed;
107
+ if (/^PASS\b/.test(line))
108
+ return { isCompletionLine: true, stage: null, status: "passed" };
109
+ if (/^FAIL\b/.test(line))
110
+ return { isCompletionLine: true, stage: null, status: "failed" };
111
+ return { isCompletionLine: false, stage: null, status: null };
868
112
  }
869
113
  function readTaskRunAcceptedArtifactState(input) {
870
- if (!input.taskId || !input.workspaceDir) {
871
- return { accepted: false, reason: null };
872
- }
873
- const artifactDir = resolve4(input.workspaceDir, "artifacts", input.taskId);
874
- const reviewStatusPath = resolve4(artifactDir, "review-status.txt");
875
- const taskResultPath = resolve4(artifactDir, "task-result.json");
876
- const reviewStatus = readTaskRunReviewStatus(reviewStatusPath);
877
- if (reviewStatus !== "APPROVED") {
114
+ if (!existsSync(input.artifactPath))
878
115
  return { accepted: false, reason: null };
879
- }
880
- const taskResult = readJsonFile(taskResultPath, null);
881
- if (taskResult?.status !== "completed") {
882
- return { accepted: false, reason: null };
883
- }
884
- if (typeof input.artifactNotBeforeMs === "number" && Number.isFinite(input.artifactNotBeforeMs)) {
885
- try {
886
- const reviewStatusMtime = statSync(reviewStatusPath).mtimeMs;
887
- if (reviewStatusMtime + 1000 < input.artifactNotBeforeMs) {
888
- return { accepted: false, reason: null };
889
- }
890
- } catch {
891
- return { accepted: false, reason: null };
892
- }
893
- }
894
- return {
895
- accepted: true,
896
- reason: `task-result.json is completed and review-status.txt is APPROVED for task ${input.taskId}`
897
- };
898
- }
899
- function resolvePiAcceptedArtifactExitGraceMs(env = process.env) {
900
- const raw = env.RIG_PI_ACCEPTED_ARTIFACT_EXIT_GRACE_MS;
901
- if (raw === undefined || raw.trim() === "")
902
- return 30000;
903
- const parsed = Number.parseInt(raw, 10);
904
- if (!Number.isFinite(parsed) || parsed < 0)
905
- return 30000;
906
- return parsed;
907
- }
908
- function resolveTaskRunRetryContext(input) {
909
- if (!input.taskId || !input.workspaceDir) {
910
- return { shouldRetry: false, failureDetail: null, nextPrompt: null };
911
- }
912
- const artifactDir = resolve4(input.workspaceDir, "artifacts", input.taskId);
913
- const reviewStatePath = resolve4(artifactDir, "review-state.json");
914
- const reviewFeedbackPath = resolve4(artifactDir, "review-feedback.md");
915
- const reviewStatusPath = resolve4(artifactDir, "review-status.txt");
916
- const failedApproachesPath = resolve4(input.workspaceDir, ".rig", "state", "failed_approaches.md");
917
- const validationSummaryPath = resolve4(artifactDir, "validation-summary.json");
918
- const reviewState = readJsonFile(reviewStatePath, null);
919
- const reviewStatus = readTaskRunReviewStatus(reviewStatusPath);
920
- const reviewRejected = isTaskRunReviewRejected(reviewState);
921
- if (reviewStatus === "APPROVED") {
922
- return { shouldRetry: false, failureDetail: null, nextPrompt: null };
923
- }
924
- if (reviewStatus !== "REJECTED" && !reviewRejected) {
925
- return { shouldRetry: false, failureDetail: null, nextPrompt: null };
926
- }
927
- const failureDetail = summarizeTaskRunReviewFailure(reviewState);
928
- if (input.attempt >= input.maxAttempts) {
929
- return { shouldRetry: false, failureDetail, nextPrompt: null };
930
- }
931
- return {
932
- shouldRetry: true,
933
- failureDetail,
934
- nextPrompt: [
935
- input.basePrompt,
936
- "",
937
- `Retry attempt ${input.attempt + 1}/${input.maxAttempts} for task ${input.taskId}.`,
938
- "The previous attempt did not satisfy completion verification. Continue from the existing runtime workspace and PR state instead of starting over.",
939
- "",
940
- `Latest blocker: ${failureDetail}`,
941
- "",
942
- "Inspect these artifacts first:",
943
- `- ${reviewStatusPath}`,
944
- `- ${reviewStatePath}`,
945
- `- ${reviewFeedbackPath}`,
946
- `- ${failedApproachesPath}`,
947
- `- ${validationSummaryPath}`,
948
- "",
949
- "Resolve the concrete issues recorded there, refresh the task artifacts if needed, rerun validation and completion verification, and do not stop until the task is actually accepted. When Greptile review is required, keep iterating until the review verdict is APPROVE with no unresolved comments."
950
- ].join(`
951
- `)
952
- };
953
- }
954
- function summarizeTaskRunReviewFailure(reviewState) {
955
- if (!reviewState) {
956
- return "Completion verification rejected the task. Read review-feedback.md for required fixes.";
957
- }
958
- const reasons = [
959
- ...reviewState.local_reasons ?? [],
960
- ...reviewState.ai_reasons ?? [],
961
- ...reviewState.ai_warnings ?? []
962
- ].map((value) => value.trim()).filter(Boolean);
963
- if (reasons.length > 0) {
964
- return reasons[0];
965
- }
966
- if (reviewState.mode === "required" && reviewState.verdict && reviewState.verdict !== "APPROVE") {
967
- return `[AI Review] Required mode needs a completed Greptile approval; current verdict is ${reviewState.verdict}.`;
968
- }
969
- return "Completion verification rejected the task. Read review-feedback.md for required fixes.";
970
- }
971
- function readTaskRunReviewStatus(reviewStatusPath) {
972
- if (!existsSync2(reviewStatusPath)) {
973
- return null;
974
- }
975
116
  try {
976
- const status = readFileSync2(reviewStatusPath, "utf8").trim().toUpperCase();
977
- return status === "APPROVED" || status === "REJECTED" ? status : null;
117
+ const parsed = JSON.parse(readFileSync(input.artifactPath, "utf8"));
118
+ return {
119
+ accepted: parsed.accepted === true,
120
+ reason: typeof parsed.reason === "string" ? parsed.reason : null
121
+ };
978
122
  } catch {
979
- return null;
980
- }
981
- }
982
- function isTaskRunReviewRejected(reviewState) {
983
- if (!reviewState) {
984
- return false;
985
- }
986
- if (reviewState.approved === false) {
987
- return true;
123
+ return { accepted: false, reason: null };
988
124
  }
989
- return reviewState.mode === "required" && !!reviewState.verdict && reviewState.verdict !== "APPROVE";
990
- }
991
- function runSourceTaskIdentity(sourceTask) {
992
- return sourceTask;
993
125
  }
994
- async function updateTaskSourceAfterDriverRun(projectRoot, runId, taskId, sourceTask, status, summary, input, updateTaskSource = updateConfiguredTaskSourceTask) {
126
+ async function runTaskRunPostValidationLifecycle(input) {
127
+ const projectRoot = cleanString(input.projectRoot) ?? process.cwd();
128
+ const runId = cleanString(input.runId) ?? "run";
129
+ const taskId = cleanString(input.runtimeTaskId) ?? cleanString(input.taskId);
995
130
  if (!taskId)
996
- return;
997
- const config = await loadTaskRunAutomationConfig(projectRoot);
998
- if (!shouldWriteDriverIssueUpdate(config, status))
999
- return;
1000
- const result = await updateTaskSource(projectRoot, {
131
+ throw new Error("Task run post-validation lifecycle requires a task id.");
132
+ const workspace = cleanString(input.runtimeWorkspace) ?? cleanString(input.workspace) ?? projectRoot;
133
+ const branch = cleanString(input.branch) ?? `rig/${taskId}-${runId}`;
134
+ const config = input.config && typeof input.config === "object" && !Array.isArray(input.config) ? input.config : {};
135
+ const sourceTask = input.sourceTask && typeof input.sourceTask === "object" && !Array.isArray(input.sourceTask) ? input.sourceTask : null;
136
+ const runners = createEnvCloseoutRunners(process.env);
137
+ const appendStage = typeof input.appendStage === "function" ? input.appendStage : null;
138
+ const result = await runInProcessCloseout({
139
+ projectRoot,
140
+ runId,
1001
141
  taskId,
1002
- sourceTask: runSourceTaskIdentity(sourceTask),
1003
- update: {
1004
- status,
1005
- comment: buildTaskRunLifecycleComment({
1006
- runId,
1007
- status,
1008
- summary,
1009
- runtimeWorkspace: input.latestRuntimeWorkspace,
1010
- logsDir: input.latestLogsDir,
1011
- sessionDir: input.latestSessionDir,
1012
- errorText: input.errorText
1013
- })
1014
- }
1015
- });
1016
- if (!result.updated && (result.source === "plugin" || result.sourceKind)) {
1017
- throw new Error(`Configured task source${result.sourceKind ? ` (${result.sourceKind})` : ""} did not accept lifecycle update for ${result.taskId}.`);
1018
- }
1019
- }
1020
- function readRunSourceTaskContract(projectRoot, runId, taskId) {
1021
- const run = readAuthorityRun3(projectRoot, runId);
1022
- const raw = run?.sourceTask;
1023
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1024
- return null;
1025
- }
1026
- const record = raw;
1027
- const id = typeof record.id === "string" && record.id.trim() ? record.id.trim() : taskId?.trim();
1028
- if (!id) {
1029
- return null;
1030
- }
1031
- return {
1032
- id,
1033
- ...optionalStringField(record, "title"),
1034
- ...optionalStringField(record, "description"),
1035
- ...optionalStringField(record, "body"),
1036
- ...optionalStringField(record, "acceptanceCriteria"),
1037
- ...optionalStringField(record, "acceptance_criteria"),
1038
- ...optionalStringField(record, "sourceIssueId"),
1039
- ...optionalStringField(record, "status"),
1040
- ...optionalStringField(record, "issueType"),
1041
- ...optionalStringField(record, "role"),
1042
- ...optionalStringField(record, "externalRef"),
1043
- scope: stringArrayField(record, "scope"),
1044
- validation: stringArrayField(record, "validation"),
1045
- validators: stringArrayField(record, "validators"),
1046
- labels: stringArrayField(record, "labels")
1047
- };
1048
- }
1049
- function optionalStringField(record, key) {
1050
- const value = record[String(key)];
1051
- return typeof value === "string" ? { [key]: value } : {};
1052
- }
1053
- function stringArrayField(record, key) {
1054
- const value = record[key];
1055
- return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
1056
- }
1057
- async function executeRigOwnedTaskRun(context, input) {
1058
- const runtimeTaskId = input.taskId?.trim() || `adhoc-${input.runId}`;
1059
- const sourceTask = readRunSourceTaskContract(context.projectRoot, input.runId, input.taskId);
1060
- const prompt = buildRunPrompt({
1061
- projectRoot: context.projectRoot,
1062
- taskId: input.taskId,
1063
- fallbackTitle: input.title,
1064
- fallbackDescription: sourceTask?.description ?? sourceTask?.body ?? null,
1065
- fallbackAcceptanceCriteria: sourceTask?.acceptanceCriteria ?? sourceTask?.acceptance_criteria ?? null,
142
+ branch,
143
+ workspace,
144
+ artifactRoot: cleanString(input.artifactRoot),
145
+ config,
1066
146
  sourceTask,
1067
- initialPrompt: input.initialPrompt,
1068
- runtimeAdapter: input.runtimeAdapter
1069
- });
1070
- const startedAt = new Date().toISOString();
1071
- const hostAgentBinary = await resolvePreferredShellBinary(context.projectRoot);
1072
- const baseAgentArgs = input.runtimeAdapter === "codex" ? [
1073
- "__rig_codex_app_server_task_run__",
1074
- "--runtime-mode",
1075
- input.runtimeMode,
1076
- "--interaction-mode",
1077
- input.interactionMode,
1078
- ...input.model ? ["--model", input.model] : [],
1079
- "--prompt"
1080
- ] : input.runtimeAdapter === "pi" ? [
1081
- "--print",
1082
- "--verbose",
1083
- "--mode",
1084
- "json",
1085
- "--no-session",
1086
- ...input.model ? ["--model", input.model] : []
1087
- ] : [
1088
- "--print",
1089
- "--verbose",
1090
- "--output-format",
1091
- "stream-json",
1092
- "--dangerously-skip-permissions"
1093
- ];
1094
- const buildHostAgentCommand = (attemptPrompt) => input.runtimeAdapter === "codex" ? [hostAgentBinary, ...baseAgentArgs, attemptPrompt] : [hostAgentBinary, ...baseAgentArgs];
1095
- const hostAgentCommand = buildHostAgentCommand(prompt);
1096
- const hostAgentCommandText = formatCommand(hostAgentCommand);
1097
- const provisioningAction = startRunAction(context.projectRoot, input.runId, {
1098
- actionId: `action:${input.runId}:runtime-provision`,
1099
- actionType: "engine.runtime.provision",
1100
- title: "Provision dedicated runtime",
1101
- detail: input.taskId ? `Preparing isolated worktree for ${input.taskId}` : "Preparing isolated runtime",
1102
- payload: {
1103
- hostAgentCommand,
1104
- formattedCommand: hostAgentCommandText,
1105
- taskId: input.taskId ?? null,
1106
- mode: "worktree"
1107
- }
1108
- });
1109
- upsertAgentAuthorityRun(context.projectRoot, {
1110
- runId: input.runId,
1111
- taskId: runtimeTaskId,
1112
- createdAt: startedAt,
1113
- runtimeAdapter: input.runtimeAdapter,
1114
- status: "created"
1115
- });
1116
- patchAuthorityRun(context.projectRoot, input.runId, {
1117
- status: "preparing",
1118
- startedAt,
1119
- completedAt: null,
1120
- errorText: null,
1121
- artifactRoot: null,
1122
- runtimeAdapter: input.runtimeAdapter,
1123
- runtimeMode: input.runtimeMode,
1124
- interactionMode: input.interactionMode,
1125
- runMode: input.runtimeMode === "full-access" ? "autonomous" : "interactive",
1126
- initialPrompt: input.initialPrompt ?? null,
1127
- title: input.taskId ? undefined : input.title ?? `Run ${input.runId}`,
1128
- pid: process.pid
1129
- });
1130
- emitServerRunEvent({
1131
- type: "status",
1132
- runId: input.runId,
1133
- status: "preparing",
1134
- detail: input.taskId ?? input.title ?? runtimeTaskId
1135
- });
1136
- appendRunLog(context.projectRoot, input.runId, {
1137
- id: `log:${input.runId}:start`,
1138
- title: "Rig task run started",
1139
- detail: input.taskId ?? input.title ?? runtimeTaskId,
1140
- tone: "info",
1141
- status: "preparing",
1142
- createdAt: startedAt
1143
- });
1144
- appendRunLog(context.projectRoot, input.runId, {
1145
- id: `log:${input.runId}:wrapper-command`,
1146
- title: "Agent wrapper command",
1147
- detail: hostAgentCommandText,
1148
- tone: "tool",
1149
- status: "preparing",
1150
- payload: {
1151
- command: hostAgentCommand,
1152
- formattedCommand: hostAgentCommandText
147
+ command: typeof input.command === "function" ? input.command : runners.command,
148
+ gitCommand: typeof input.gitCommand === "function" ? input.gitCommand : runners.gitCommand,
149
+ steerPi: async (message) => {
150
+ appendStage?.("Review/CI", message, "running");
151
+ if (typeof input.steerPi === "function") {
152
+ await input.steerPi(message);
153
+ }
1153
154
  },
1154
- createdAt: new Date().toISOString()
1155
- });
1156
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Agent wrapper command" });
1157
- const loadedAutomationConfig = await loadTaskRunAutomationConfig(context.projectRoot);
1158
- const automationConfig = input.prMode ? { ...loadedAutomationConfig ?? {}, pr: { ...loadedAutomationConfig?.pr ?? {}, mode: input.prMode } } : loadedAutomationConfig;
1159
- const planningClassification = classifyPlanningNeed({ config: automationConfig, sourceTask });
1160
- patchAuthorityRun(context.projectRoot, input.runId, { planning: planningClassification });
1161
- if (input.runtimeAdapter === "pi") {
1162
- for (const stage of ["Connect", "GitHub/task sync", "Prepare workspace", "Launch Pi", "Plan", "Implement"]) {
1163
- appendPiStageLog({
1164
- projectRoot: context.projectRoot,
1165
- runId: input.runId,
1166
- stage,
1167
- detail: stage === "Launch Pi" ? "Pi runtime bridge starting with pi-rig environment." : stage === "Plan" ? `${planningClassification.planningRequired ? "recorded" : "skipped"} (${planningClassification.reason}; size=${planningClassification.size}; risk=${planningClassification.risk})` : stage === "Implement" ? "Pi implementation pass is running." : null,
1168
- status: stage === "Implement" || stage === "Launch Pi" ? "running" : "completed"
1169
- });
1170
- }
1171
- }
1172
- appendRunTimeline(context.projectRoot, input.runId, {
1173
- id: `message:${input.runId}:user`,
1174
- type: "user_message",
1175
- text: prompt,
1176
- createdAt: startedAt,
1177
- state: "completed",
1178
- completedAt: startedAt
1179
- });
1180
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1181
- await context.emitEvent("command.started", {
1182
- command: [
1183
- "rig",
1184
- "server",
1185
- "task-run",
1186
- ...input.taskId ? ["--task", input.taskId] : [],
1187
- ...input.title ? ["--title", input.title] : []
1188
- ],
1189
- formattedCommand: input.taskId ? `rig server task-run --task ${input.taskId}` : `rig server task-run --title ${JSON.stringify(input.title ?? `Run ${input.runId}`)}`,
1190
- startedAt,
1191
- dryRun: false
1192
- });
1193
- const assistantMessageId = `message:${input.runId}:assistant`;
1194
- let assistantText = "";
1195
- const pendingClaudeToolUses = new Map;
1196
- const pendingCodexToolUses = new Map;
1197
- let launchAction;
1198
- let verificationAction;
1199
- let reviewAction;
1200
- let verificationStarted = false;
1201
- let reviewStarted = false;
1202
- let latestRuntimeWorkspace = null;
1203
- let latestSessionDir = null;
1204
- let latestLogsDir = null;
1205
- let latestProviderCommand = null;
1206
- let latestRuntimeBranch = null;
1207
- let snapshotSidecarPromise = null;
1208
- let dirtyBaselineApplied = false;
1209
- const childEnv = {
1210
- ...process.env,
1211
- ...input.runtimeAdapter === "pi" ? buildPiRigBridgeEnv({
1212
- projectRoot: context.projectRoot,
1213
- runId: input.runId,
1214
- taskId: runtimeTaskId,
1215
- serverUrl: process.env.RIG_SERVER_URL ?? null,
1216
- authToken: process.env.RIG_AUTH_TOKEN ?? null,
1217
- githubToken: process.env.RIG_GITHUB_TOKEN ?? process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? null
1218
- }) : {
1219
- PROJECT_RIG_ROOT: context.projectRoot,
1220
- RIG_TASK_ID: runtimeTaskId,
1221
- RIG_RUNTIME_ADAPTER: input.runtimeAdapter,
1222
- RIG_SERVER_RUN_ID: input.runId
155
+ journalPhase: (phase, outcome, detail) => {
156
+ const status = outcome === "completed" ? "completed" : outcome === "failed" ? "needs_attention" : "running";
157
+ appendStage?.(phase, detail ?? null, status);
1223
158
  },
1224
- ...sourceTask ? { RIG_SOURCE_TASK_JSON: JSON.stringify(sourceTask) } : {}
1225
- };
1226
- Object.assign(childEnv, buildTaskRunReviewEnv(automationConfig));
1227
- const automationLimits = resolveTaskRunAutomationLimits(automationConfig);
1228
- const maxAttempts = automationLimits.maxValidationAttempts;
1229
- const promoteToValidating = (detail) => {
1230
- if (verificationStarted)
1231
- return;
1232
- verificationStarted = true;
1233
- patchAuthorityRun(context.projectRoot, input.runId, { status: "validating" });
1234
- emitServerRunEvent({ type: "status", runId: input.runId, status: "validating", detail: detail ?? null });
1235
- verificationAction = startRunAction(context.projectRoot, input.runId, {
1236
- actionId: `action:${input.runId}:completion-verification`,
1237
- actionType: "completion-verification",
1238
- title: "Run completion verification",
1239
- detail: detail ?? "Rig completion-verification hook is running."
1240
- });
1241
- };
1242
- const promoteToReviewing = (detail) => {
1243
- if (reviewStarted)
1244
- return;
1245
- reviewStarted = true;
1246
- patchAuthorityRun(context.projectRoot, input.runId, { status: "reviewing" });
1247
- emitServerRunEvent({ type: "status", runId: input.runId, status: "reviewing", detail: detail ?? null });
1248
- reviewAction = startRunAction(context.projectRoot, input.runId, {
1249
- actionId: `action:${input.runId}:review-closeout`,
1250
- actionType: "run.review",
1251
- title: "Finalize run review",
1252
- detail: detail ?? "Verifier review is running."
1253
- });
1254
- };
1255
- const handleWrapperEvent = (rawPayload) => {
1256
- let event = null;
1257
- try {
1258
- event = JSON.parse(rawPayload);
1259
- } catch {
1260
- return false;
1261
- }
1262
- if (!event?.type)
1263
- return false;
1264
- const payload = event.payload ?? {};
1265
- if (event.type === "runtime.provision.completed") {
1266
- latestRuntimeWorkspace = typeof payload.workspaceDir === "string" ? payload.workspaceDir : latestRuntimeWorkspace;
1267
- latestSessionDir = typeof payload.sessionDir === "string" ? payload.sessionDir : latestSessionDir;
1268
- latestLogsDir = typeof payload.logsDir === "string" ? payload.logsDir : latestLogsDir;
1269
- const runtimeId = typeof payload.runtimeId === "string" ? payload.runtimeId : null;
1270
- latestRuntimeBranch = runtimeId;
1271
- provisioningAction.complete(latestRuntimeWorkspace ?? "Runtime ready.", {
1272
- runtimeId: runtimeId ?? null,
1273
- workspaceDir: latestRuntimeWorkspace,
1274
- sessionDir: latestSessionDir,
1275
- logsDir: latestLogsDir,
1276
- contextFile: payload.contextFile ?? null
1277
- });
1278
- patchAuthorityRun(context.projectRoot, input.runId, {
1279
- status: "running",
1280
- worktreePath: latestRuntimeWorkspace,
1281
- artifactRoot: latestRuntimeWorkspace && input.taskId ? resolve4(latestRuntimeWorkspace, "artifacts", input.taskId) : null,
1282
- logRoot: latestLogsDir,
1283
- sessionPath: latestSessionDir ? resolve4(latestSessionDir, "session.json") : null,
1284
- sessionLogPath: latestLogsDir ? resolve4(latestLogsDir, "agent-stdout.log") : null,
1285
- branch: runtimeId
1286
- });
1287
- if (!dirtyBaselineApplied && input.baselineMode === "dirty-snapshot" && latestRuntimeWorkspace) {
1288
- dirtyBaselineApplied = true;
1289
- const dirty = applyDirtyBaselineSnapshot({ sourceRoot: context.projectRoot, targetRoot: latestRuntimeWorkspace });
1290
- appendRunLog(context.projectRoot, input.runId, {
1291
- id: `log:${input.runId}:dirty-baseline`,
1292
- title: "Dirty baseline snapshot",
1293
- detail: dirty.detail,
1294
- tone: dirty.applied ? "tool" : "info",
1295
- status: dirty.applied ? "completed" : "skipped",
1296
- createdAt: new Date().toISOString()
1297
- });
1298
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Dirty baseline snapshot" });
1299
- }
1300
- if (!snapshotSidecarPromise && runtimeId && loadRuntimeSnapshotConfig(context.projectRoot).enabled) {
1301
- snapshotSidecarPromise = (async () => {
1302
- const { sidecar, error } = await resolveTaskRunSnapshotSidecar({
1303
- projectRoot: context.projectRoot,
1304
- runtimeId,
1305
- workspaceDir: latestRuntimeWorkspace,
1306
- listRuntimes: listAgentRuntimes,
1307
- startSidecar: (runtime) => startRuntimeSnapshotSidecar(runtime, { instanceId: `${runtime.id}-run-${input.runId}` })
1308
- });
1309
- if (!sidecar) {
1310
- appendRunLog(context.projectRoot, input.runId, {
1311
- id: `log:${input.runId}:snapshot-unavailable`,
1312
- title: "Runtime snapshotting unavailable",
1313
- detail: error ?? `Could not locate runtime metadata for ${runtimeId}.`,
1314
- tone: "error",
1315
- status: "running",
1316
- createdAt: new Date().toISOString()
1317
- });
1318
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Runtime snapshotting unavailable" });
1319
- return null;
1320
- }
1321
- return sidecar;
1322
- })();
1323
- }
1324
- emitServerRunEvent({
1325
- type: "status",
1326
- runId: input.runId,
1327
- status: "running",
1328
- detail: latestRuntimeWorkspace
1329
- });
1330
- return true;
1331
- }
1332
- if (event.type === "runtime.provision.failed") {
1333
- const detail = typeof payload.error === "string" ? payload.error : "Runtime provisioning failed.";
1334
- provisioningAction.fail(detail, payload);
1335
- emitServerRunEvent({ type: "failed", runId: input.runId, error: detail });
1336
- return true;
1337
- }
1338
- if (event.type === "provider.launch") {
1339
- const command = Array.isArray(payload.command) ? payload.command.filter((value) => typeof value === "string") : [];
1340
- latestProviderCommand = command.length > 0 ? command : null;
1341
- const commandText = command.length > 0 ? formatCommand(command) : String(payload.provider ?? "provider");
1342
- launchAction = startRunAction(context.projectRoot, input.runId, {
1343
- actionId: `action:${input.runId}:provider-launch`,
1344
- actionType: "agent.launch",
1345
- title: "Launch agent runtime",
1346
- detail: commandText,
1347
- payload: {
1348
- runtimeAdapter: input.runtimeAdapter,
1349
- runtimeMode: input.runtimeMode,
1350
- interactionMode: input.interactionMode,
1351
- workspaceDir: payload.workspaceDir ?? latestRuntimeWorkspace,
1352
- command,
1353
- formattedCommand: commandText
1354
- }
1355
- });
1356
- appendRunLog(context.projectRoot, input.runId, {
1357
- id: `log:${input.runId}:provider-command`,
1358
- title: "Agent launch command",
1359
- detail: commandText,
1360
- tone: "tool",
1361
- status: "running",
1362
- payload: {
1363
- command,
1364
- formattedCommand: commandText
1365
- },
1366
- createdAt: new Date().toISOString()
1367
- });
1368
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Agent launch command" });
1369
- return true;
1370
- }
1371
- if (event.type === "provider.completed") {
1372
- const exitCode = typeof payload.exitCode === "number" ? payload.exitCode : null;
1373
- if (launchAction) {
1374
- if (exitCode === 0) {
1375
- launchAction.complete("Agent runtime finished.");
1376
- } else {
1377
- launchAction.fail(`Agent runtime failed (${String(exitCode ?? "unknown")})`, payload);
1378
- }
1379
- }
1380
- return true;
1381
- }
1382
- return false;
1383
- };
1384
- const nextRunLogId = createRunLogIdFactory(input.runId);
1385
- const handleAgentStdoutLine = (line) => {
1386
- const trimmed = line.trim();
1387
- if (!trimmed)
1388
- return;
1389
- if (trimmed.startsWith("__RIG_WRAPPER_EVENT__")) {
1390
- if (handleWrapperEvent(trimmed.slice("__RIG_WRAPPER_EVENT__".length))) {
1391
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1392
- return;
1393
- }
1394
- }
1395
- const completionLine = classifyCompletionVerificationLine(trimmed);
1396
- if (completionLine.isCompletionLine) {
1397
- promoteToValidating(trimmed);
1398
- if (completionLine.isVerifierReview) {
1399
- if (verificationAction) {
1400
- verificationAction.complete("Completion verification checks finished.");
1401
- }
1402
- promoteToReviewing(trimmed);
1403
- }
1404
- appendRunLog(context.projectRoot, input.runId, {
1405
- id: nextRunLogId(),
1406
- title: verificationStarted ? "Completion verification" : "Agent output",
1407
- detail: trimmed,
1408
- tone: "info",
1409
- status: reviewStarted ? "reviewing" : verificationStarted ? "validating" : "running",
1410
- createdAt: new Date().toISOString()
1411
- });
1412
- emitServerRunEvent({ type: "log", runId: input.runId, title: verificationStarted ? "Completion verification" : "Agent output" });
1413
- return;
1414
- }
1415
- try {
1416
- const record = JSON.parse(trimmed);
1417
- const liveLogStatus = reviewStarted ? "reviewing" : verificationStarted ? "validating" : "running";
1418
- const providerLogs = input.runtimeAdapter === "codex" ? buildCodexLogsFromRecord({
1419
- runId: input.runId,
1420
- record,
1421
- createdAtFallback: new Date().toISOString(),
1422
- status: liveLogStatus,
1423
- pendingToolUses: pendingCodexToolUses
1424
- }) : buildClaudeLogsFromRecord({
1425
- runId: input.runId,
1426
- record,
1427
- createdAtFallback: new Date().toISOString(),
1428
- status: liveLogStatus,
1429
- pendingToolUses: pendingClaudeToolUses
1430
- });
1431
- if (providerLogs.length > 0) {
1432
- for (const providerLog of providerLogs) {
1433
- appendRunLog(context.projectRoot, input.runId, providerLog);
1434
- emitServerRunEvent({ type: "log", runId: input.runId, title: providerLog.title });
1435
- }
1436
- }
1437
- if (input.runtimeAdapter === "codex") {
1438
- const nextAssistantText = extractCodexAssistantMessageText(record);
1439
- if (nextAssistantText) {
1440
- assistantText = nextAssistantText;
1441
- appendRunTimeline(context.projectRoot, input.runId, {
1442
- id: assistantMessageId,
1443
- type: "assistant_message",
1444
- text: assistantText,
1445
- state: "streaming",
1446
- createdAt: new Date().toISOString()
1447
- });
1448
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1449
- return;
1450
- }
1451
- if (providerLogs.length > 0 || isCodexExecRecord(record)) {
1452
- return;
1453
- }
1454
- }
1455
- if (record.type === "message_update") {
1456
- const assistantMessageEvent = record.assistantMessageEvent && typeof record.assistantMessageEvent === "object" ? record.assistantMessageEvent : null;
1457
- if (assistantMessageEvent?.type === "text_delta" && typeof assistantMessageEvent.delta === "string") {
1458
- assistantText += assistantMessageEvent.delta;
1459
- appendRunTimeline(context.projectRoot, input.runId, {
1460
- id: assistantMessageId,
1461
- type: "assistant_message",
1462
- text: assistantText,
1463
- state: "streaming",
1464
- createdAt: new Date().toISOString()
1465
- });
1466
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1467
- return;
1468
- }
1469
- }
1470
- if (record.type === "stream_event") {
1471
- const event = record.event && typeof record.event === "object" ? record.event : null;
1472
- const delta = event?.delta && typeof event.delta === "object" ? event.delta : null;
1473
- if (delta?.type === "text_delta" && typeof delta.text === "string") {
1474
- assistantText += delta.text;
1475
- appendRunTimeline(context.projectRoot, input.runId, {
1476
- id: assistantMessageId,
1477
- type: "assistant_message",
1478
- text: assistantText,
1479
- state: "streaming",
1480
- createdAt: new Date().toISOString()
1481
- });
1482
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1483
- return;
1484
- }
1485
- }
1486
- if (record.type === "assistant") {
1487
- const message = record.message && typeof record.message === "object" ? record.message : record;
1488
- const content = Array.isArray(message.content) ? message.content : [];
1489
- const nextText = content.map((entry) => entry && typeof entry === "object" && entry.type === "text" ? String(entry.text ?? "") : "").join("");
1490
- if (nextText.length > assistantText.length) {
1491
- assistantText = nextText;
1492
- appendRunTimeline(context.projectRoot, input.runId, {
1493
- id: assistantMessageId,
1494
- type: "assistant_message",
1495
- text: assistantText,
1496
- state: "streaming",
1497
- createdAt: new Date().toISOString()
1498
- });
1499
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1500
- }
1501
- return;
1502
- }
1503
- if (providerLogs.length > 0) {
1504
- return;
1505
- }
1506
- } catch {}
1507
- appendRunLog(context.projectRoot, input.runId, {
1508
- id: nextRunLogId(),
1509
- title: verificationStarted ? "Completion verification" : "Agent output",
1510
- detail: trimmed,
1511
- tone: "info",
1512
- status: reviewStarted ? "reviewing" : verificationStarted ? "validating" : "running",
1513
- createdAt: new Date().toISOString()
1514
- });
1515
- emitServerRunEvent({ type: "log", runId: input.runId, title: verificationStarted ? "Completion verification" : "Agent output" });
1516
- };
1517
- let currentPrompt = prompt;
1518
- let exit = null;
1519
- let reviewFailureDetail = null;
1520
- const stderrLines = [];
1521
- const piAcceptedArtifactExitGraceMs = resolvePiAcceptedArtifactExitGraceMs(childEnv);
1522
- for (let attempt = 1;attempt <= maxAttempts; attempt += 1) {
1523
- const attemptHostAgentCommand = buildHostAgentCommand(currentPrompt);
1524
- const child = spawn(attemptHostAgentCommand[0], attemptHostAgentCommand.slice(1), {
1525
- cwd: context.projectRoot,
1526
- env: childEnv,
1527
- stdio: ["pipe", "pipe", "pipe"]
1528
- });
1529
- const forwardSigterm = () => {
1530
- try {
1531
- child.kill("SIGTERM");
1532
- } catch {}
1533
- };
1534
- process.once("SIGTERM", forwardSigterm);
1535
- if (input.runtimeAdapter === "claude-code" || input.runtimeAdapter === "pi") {
1536
- child.stdin.write(currentPrompt);
1537
- child.stdin.end();
1538
- } else {
1539
- child.stdin.end();
1540
- }
1541
- const stdout = createLineInterface({ input: child.stdout });
1542
- stdout.on("line", handleAgentStdoutLine);
1543
- const stderr = createLineInterface({ input: child.stderr });
1544
- stderr.on("line", (line) => {
1545
- const trimmed = line.trim();
1546
- if (!trimmed)
1547
- return;
1548
- stderrLines.push(trimmed);
1549
- appendRunLog(context.projectRoot, input.runId, {
1550
- id: nextRunLogId(),
1551
- title: "Agent stderr",
1552
- detail: trimmed,
1553
- tone: "error",
1554
- status: reviewStarted ? "reviewing" : verificationStarted ? "validating" : "running",
1555
- createdAt: new Date().toISOString()
1556
- });
1557
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Agent stderr" });
1558
- });
1559
- let acceptedArtifactExit = false;
1560
- let acceptedArtifactObservedAt = null;
1561
- let acceptedArtifactPollTimer = null;
1562
- let acceptedArtifactKillTimer = null;
1563
- const attemptExit = await new Promise((resolve5) => {
1564
- let settled = false;
1565
- const settle = (result) => {
1566
- if (settled)
1567
- return;
1568
- settled = true;
1569
- if (acceptedArtifactPollTimer)
1570
- clearInterval(acceptedArtifactPollTimer);
1571
- resolve5(result);
1572
- };
1573
- const pollAcceptedArtifacts = () => {
1574
- const artifactState = readTaskRunAcceptedArtifactState({
1575
- taskId: input.taskId ?? runtimeTaskId,
1576
- workspaceDir: latestRuntimeWorkspace,
1577
- artifactNotBeforeMs: Date.parse(startedAt)
1578
- });
1579
- if (!artifactState.accepted) {
1580
- acceptedArtifactObservedAt = null;
1581
- return;
1582
- }
1583
- acceptedArtifactObservedAt ??= Date.now();
1584
- if (Date.now() - acceptedArtifactObservedAt < piAcceptedArtifactExitGraceMs || acceptedArtifactExit) {
1585
- return;
1586
- }
1587
- acceptedArtifactExit = true;
1588
- const detail = [
1589
- artifactState.reason ?? "Rig accepted task artifacts are present.",
1590
- `Pi has not exited after ${piAcceptedArtifactExitGraceMs}ms; terminating the stale Pi process so Rig can continue PR/issue closeout.`
1591
- ].join(" ");
1592
- appendRunLog(context.projectRoot, input.runId, {
1593
- id: `log:${input.runId}:pi-accepted-artifacts-exit`,
1594
- title: "Pi accepted artifacts; continuing closeout",
1595
- detail,
1596
- tone: "info",
1597
- status: "running",
1598
- createdAt: new Date().toISOString()
1599
- });
1600
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Pi accepted artifacts; continuing closeout" });
1601
- try {
1602
- child.kill("SIGTERM");
1603
- } catch {}
1604
- acceptedArtifactKillTimer = setTimeout(() => {
1605
- try {
1606
- child.kill("SIGKILL");
1607
- } catch {}
1608
- settle({ code: 0, signal: "SIGKILL" });
1609
- }, 5000);
1610
- };
1611
- child.once("error", (error) => {
1612
- if (acceptedArtifactKillTimer)
1613
- clearTimeout(acceptedArtifactKillTimer);
1614
- console.error(`[rig] agent process error: ${error.message}`);
1615
- settle({ code: 1, signal: null, error });
1616
- });
1617
- child.once("close", (code, signal) => {
1618
- if (acceptedArtifactKillTimer)
1619
- clearTimeout(acceptedArtifactKillTimer);
1620
- settle(acceptedArtifactExit ? { code: 0, signal: signal ?? "SIGTERM" } : { code, signal });
1621
- });
1622
- if (input.runtimeAdapter === "pi") {
1623
- acceptedArtifactPollTimer = setInterval(pollAcceptedArtifacts, 5000);
1624
- acceptedArtifactPollTimer.unref?.();
1625
- }
1626
- });
1627
- await finalizeTaskRunSnapshot({
1628
- snapshotSidecarPromise,
1629
- latestProviderCommand,
1630
- hostAgentCommand: attemptHostAgentCommand,
1631
- exit: attemptExit
1632
- });
1633
- const pendingLogs = input.runtimeAdapter === "codex" ? flushPendingCodexToolUseLogs({
1634
- runId: input.runId,
1635
- status: typeof attemptExit.code === "number" && attemptExit.code === 0 ? "completed" : "failed",
1636
- pendingToolUses: pendingCodexToolUses
1637
- }) : flushPendingClaudeToolUseLogs({
1638
- runId: input.runId,
1639
- status: typeof attemptExit.code === "number" && attemptExit.code === 0 ? "completed" : "failed",
1640
- pendingToolUses: pendingClaudeToolUses
1641
- });
1642
- for (const pendingLog of pendingLogs) {
1643
- appendRunLog(context.projectRoot, input.runId, pendingLog);
1644
- emitServerRunEvent({ type: "log", runId: input.runId, title: pendingLog.title });
1645
- }
1646
- process.off("SIGTERM", forwardSigterm);
1647
- if (attemptExit.error) {
1648
- throw new CliError2(`Task run failed to start: ${attemptExit.error.message}`, 1);
1649
- }
1650
- const retryContext = resolveTaskRunRetryContext({
1651
- projectRoot: context.projectRoot,
1652
- taskId: input.taskId ?? null,
1653
- workspaceDir: latestRuntimeWorkspace,
1654
- attempt,
1655
- maxAttempts,
1656
- basePrompt: prompt
1657
- });
1658
- if (retryContext.shouldRetry && retryContext.nextPrompt) {
1659
- const failureDetail = retryContext.failureDetail ?? summarizeValidationFailure(context.projectRoot, input.taskId ?? null) ?? "Rig validation failed.";
1660
- const retrySteering = buildPiValidationRetrySteeringPrompt({
1661
- taskId: input.taskId ?? runtimeTaskId,
1662
- attempt,
1663
- maxAttempts,
1664
- failureDetail,
1665
- validationOutput: summarizeValidationFailure(context.projectRoot, input.taskId ?? null)
1666
- });
1667
- currentPrompt = [retryContext.nextPrompt, "", "Rig Pi steering message:", retrySteering].join(`
1668
- `);
1669
- reviewFailureDetail = failureDetail;
1670
- patchAuthorityRun(context.projectRoot, input.runId, {
1671
- status: "validating",
1672
- completedAt: null,
1673
- errorText: null
1674
- });
1675
- appendPiStageLog({
1676
- projectRoot: context.projectRoot,
1677
- runId: input.runId,
1678
- stage: "Validate",
1679
- detail: failureDetail,
1680
- tone: "error",
1681
- status: "validating"
1682
- });
1683
- appendRunLog(context.projectRoot, input.runId, {
1684
- id: `log:${input.runId}:retry:${attempt + 1}`,
1685
- title: `Steering Pi to retry validation (attempt ${attempt + 1}/${maxAttempts})`,
1686
- detail: retrySteering,
1687
- tone: "info",
1688
- status: "running",
1689
- createdAt: new Date().toISOString()
1690
- });
1691
- emitServerRunEvent({
1692
- type: "status",
1693
- runId: input.runId,
1694
- status: "validating",
1695
- detail: failureDetail
1696
- });
1697
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Validate failed" });
1698
- emitServerRunEvent({ type: "log", runId: input.runId, title: `Steering Pi to retry validation (attempt ${attempt + 1}/${maxAttempts})` });
1699
- continue;
1700
- }
1701
- exit = attemptExit;
1702
- reviewFailureDetail = retryContext.failureDetail;
1703
- break;
1704
- }
1705
- if (!exit) {
1706
- throw new CliError2(`Task run for ${runtimeTaskId} exhausted ${maxAttempts} attempts without a terminal result.`, 1);
1707
- }
1708
- if (exit.error) {
1709
- throw new CliError2(`Task run failed to start: ${exit.error.message}`, 1);
1710
- }
1711
- if (assistantText.trim()) {
1712
- appendRunTimeline(context.projectRoot, input.runId, {
1713
- id: assistantMessageId,
1714
- type: "assistant_message",
1715
- text: assistantText,
1716
- state: "completed",
1717
- createdAt: new Date().toISOString(),
1718
- completedAt: new Date().toISOString()
1719
- });
1720
- emitServerRunEvent({ type: "timeline", runId: input.runId });
1721
- }
1722
- if (exit.code !== 0 || reviewFailureDetail) {
1723
- const failedAt = new Date().toISOString();
1724
- const failureDetail = reviewFailureDetail ?? summarizeValidationFailure(context.projectRoot, input.taskId ?? null) ?? summarizeTaskRunProcessFailure({
1725
- exitCode: exit.code,
1726
- signal: exit.signal,
1727
- stderrLines
1728
- });
1729
- if (verificationAction && !reviewStarted) {
1730
- verificationAction.fail(failureDetail);
1731
- }
1732
- if (reviewAction) {
1733
- reviewAction.fail(failureDetail);
1734
- }
1735
- let terminalFailureDetail = failureDetail;
1736
- const terminalRunStatus = reviewFailureDetail ? "needs_attention" : "failed";
1737
- try {
1738
- await updateTaskSourceAfterDriverRun(context.projectRoot, input.runId, input.taskId, sourceTask, "failed", terminalRunStatus === "needs_attention" ? "Rig task run needs attention." : "Rig task run failed.", {
1739
- latestRuntimeWorkspace,
1740
- latestLogsDir,
1741
- latestSessionDir,
1742
- errorText: failureDetail
1743
- });
1744
- } catch (error) {
1745
- terminalFailureDetail = `${failureDetail}
1746
- Failed to update task source for ${input.taskId ?? runtimeTaskId} to failed: ${error instanceof Error ? error.message : String(error)}`;
1747
- }
1748
- patchAuthorityRun(context.projectRoot, input.runId, {
1749
- status: terminalRunStatus,
1750
- completedAt: failedAt,
1751
- errorText: terminalFailureDetail
1752
- });
1753
- appendRunLog(context.projectRoot, input.runId, {
1754
- id: `log:${input.runId}:${terminalRunStatus}`,
1755
- title: terminalRunStatus === "needs_attention" ? "Task run needs attention" : "Task run failed",
1756
- detail: terminalFailureDetail,
1757
- tone: "error",
1758
- status: terminalRunStatus,
1759
- createdAt: failedAt
1760
- });
1761
- emitServerRunEvent({
1762
- type: "failed",
1763
- runId: input.runId,
1764
- error: terminalFailureDetail
1765
- });
1766
- throw new CliError2(terminalFailureDetail, exit.code ?? 1);
1767
- }
1768
- const runPiPrFeedbackFix = async (message) => {
1769
- appendPiStageLog({
1770
- projectRoot: context.projectRoot,
1771
- runId: input.runId,
1772
- stage: "Implement",
1773
- detail: "Pi is applying PR review/CI feedback.",
1774
- status: "running"
1775
- });
1776
- appendRunLog(context.projectRoot, input.runId, {
1777
- id: `log:${input.runId}:pr-feedback-pi:${Date.now()}`,
1778
- title: "Steering Pi from PR feedback",
1779
- detail: message,
1780
- tone: "info",
1781
- status: "reviewing",
1782
- createdAt: new Date().toISOString()
1783
- });
1784
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Steering Pi from PR feedback" });
1785
- const feedbackCommand = buildHostAgentCommand(message);
1786
- const child = spawn(feedbackCommand[0], feedbackCommand.slice(1), {
1787
- cwd: latestRuntimeWorkspace ?? context.projectRoot,
1788
- env: childEnv,
1789
- stdio: ["pipe", "pipe", "pipe"]
1790
- });
1791
- if (input.runtimeAdapter === "claude-code" || input.runtimeAdapter === "pi") {
1792
- child.stdin.write(message);
1793
- }
1794
- child.stdin.end();
1795
- const stdout = createLineInterface({ input: child.stdout });
1796
- stdout.on("line", (line) => {
1797
- const trimmed = line.trim();
1798
- if (!trimmed)
159
+ reflect: async (status, summary, options) => {
160
+ const github = config.github && typeof config.github === "object" && !Array.isArray(config.github) ? config.github : null;
161
+ if (github?.issueUpdates === "off")
1799
162
  return;
1800
- appendRunLog(context.projectRoot, input.runId, {
1801
- id: nextRunLogId(),
1802
- title: "Pi PR feedback fix output",
1803
- detail: trimmed,
1804
- tone: "info",
1805
- status: "reviewing",
1806
- createdAt: new Date().toISOString()
1807
- });
1808
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Pi PR feedback fix output" });
1809
- });
1810
- const stderr = createLineInterface({ input: child.stderr });
1811
- stderr.on("line", (line) => {
1812
- const trimmed = line.trim();
1813
- if (!trimmed)
1814
- return;
1815
- appendRunLog(context.projectRoot, input.runId, {
1816
- id: nextRunLogId(),
1817
- title: "Pi PR feedback fix stderr",
1818
- detail: trimmed,
1819
- tone: "error",
1820
- status: "reviewing",
1821
- createdAt: new Date().toISOString()
1822
- });
1823
- emitServerRunEvent({ type: "log", runId: input.runId, title: "Pi PR feedback fix stderr" });
1824
- });
1825
- const exitCode = await new Promise((resolve5) => {
1826
- child.once("error", () => resolve5(1));
1827
- child.once("close", (code) => resolve5(code ?? 1));
1828
- });
1829
- if (exitCode !== 0) {
1830
- throw new Error(`Pi PR feedback fix failed with exit code ${exitCode}.`);
1831
- }
1832
- };
1833
- try {
1834
- appendPiStageLog({
1835
- projectRoot: context.projectRoot,
1836
- runId: input.runId,
1837
- stage: "Validate",
1838
- detail: "Rig validation accepted the task run.",
1839
- status: "completed"
1840
- });
1841
- const postValidation = await runTaskRunPostValidationLifecycle({
1842
- projectRoot: context.projectRoot,
1843
- runId: input.runId,
1844
- taskId: input.taskId,
1845
- runtimeTaskId,
1846
- runtimeWorkspace: latestRuntimeWorkspace,
1847
- branch: latestRuntimeBranch,
1848
- config: automationConfig,
1849
- sourceTask,
1850
- steerPi: input.runtimeAdapter === "pi" ? runPiPrFeedbackFix : undefined,
1851
- appendStage: (stage, detail, status, tone) => appendPiStageLog({
1852
- projectRoot: context.projectRoot,
1853
- runId: input.runId,
1854
- stage,
1855
- detail,
1856
- status,
1857
- tone
1858
- })
1859
- });
1860
- if (postValidation.status === "needs_attention") {
1861
- const failureDetail = postValidation.pr?.actionableFeedback.join(`
1862
- `) || "PR automation needs attention.";
1863
- const failedAt = new Date().toISOString();
1864
- patchAuthorityRun(context.projectRoot, input.runId, {
1865
- status: "needs_attention",
1866
- completedAt: failedAt,
1867
- errorText: failureDetail
1868
- });
1869
- emitServerRunEvent({ type: "failed", runId: input.runId, error: failureDetail });
1870
- throw new CliError2(failureDetail, 1);
1871
- }
1872
- } catch (error) {
1873
- if (error instanceof CliError2) {
1874
- throw error;
163
+ await updateRunTaskSourceLifecycle(projectRoot, {
164
+ runId,
165
+ taskId,
166
+ sourceTask,
167
+ worktreePath: workspace,
168
+ logRoot: cleanString(input.logRoot),
169
+ sessionPath: cleanString(input.sessionPath)
170
+ }, status, summary, options);
1875
171
  }
1876
- const failureDetail = `Failed to complete PR/issue closeout for ${input.taskId ?? runtimeTaskId}: ${error instanceof Error ? error.message : String(error)}`;
1877
- const failedAt = new Date().toISOString();
1878
- patchAuthorityRun(context.projectRoot, input.runId, {
1879
- status: "failed",
1880
- completedAt: failedAt,
1881
- errorText: failureDetail
1882
- });
1883
- appendRunLog(context.projectRoot, input.runId, {
1884
- id: `log:${input.runId}:pr-closeout-failed`,
1885
- title: "PR/issue closeout failed",
1886
- detail: failureDetail,
1887
- tone: "error",
1888
- status: "failed",
1889
- createdAt: failedAt
1890
- });
1891
- emitServerRunEvent({ type: "failed", runId: input.runId, error: failureDetail });
1892
- throw new CliError2(failureDetail, 1);
1893
- }
1894
- if (verificationAction && !reviewStarted) {
1895
- verificationAction.complete("Completion verification checks finished.");
1896
- }
1897
- if (!reviewAction) {
1898
- promoteToReviewing("Task finished; finalizing run state.");
1899
- }
1900
- if (reviewAction) {
1901
- reviewAction.complete("Run marked completed.");
1902
- }
1903
- patchAuthorityRun(context.projectRoot, input.runId, {
1904
- status: "completed",
1905
- completedAt: new Date().toISOString()
1906
- });
1907
- emitServerRunEvent({ type: "completed", runId: input.runId });
1908
- await context.emitEvent("command.finished", {
1909
- command: [
1910
- "rig",
1911
- "server",
1912
- "task-run",
1913
- ...input.taskId ? ["--task", input.taskId] : [],
1914
- ...input.title ? ["--title", input.title] : []
1915
- ],
1916
- formattedCommand: input.taskId ? `rig server task-run --task ${input.taskId}` : `rig server task-run --title ${JSON.stringify(input.title ?? `Run ${input.runId}`)}`,
1917
- exitCode: 0,
1918
- durationMs: 0,
1919
- startedAt,
1920
- finishedAt: new Date().toISOString()
1921
172
  });
173
+ return {
174
+ ok: true,
175
+ runId,
176
+ taskId,
177
+ branch,
178
+ merged: result.status === "merged",
179
+ closedIssue: result.status === "merged",
180
+ prUrl: result.prUrl,
181
+ status: result.status
182
+ };
183
+ }
184
+ function cleanString(value) {
185
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
1922
186
  }
1923
187
  export {
1924
188
  taskRunStageLogId,
@@ -1926,7 +190,6 @@ export {
1926
190
  runTaskRunPostValidationLifecycle,
1927
191
  resolveTaskRunAutomationLimits,
1928
192
  readTaskRunAcceptedArtifactState,
1929
- executeRigOwnedTaskRun,
1930
193
  createRunLogIdFactory,
1931
194
  classifyValidationRetryOutcome,
1932
195
  classifyPlanningNeed,
@@ -1935,5 +198,6 @@ export {
1935
198
  buildTaskRunReviewEnv,
1936
199
  buildPiValidationRetrySteeringPrompt,
1937
200
  buildPiRigBridgeEnv,
201
+ buildDirtyBaselineHandshakeEnv,
1938
202
  applyDirtyBaselineSnapshot
1939
203
  };