@h-rig/cli 0.0.6-alpha.13 → 0.0.6-alpha.130

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