pi-goal-delegate 0.1.0 → 0.3.1
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.
- package/CHANGELOG.md +147 -0
- package/README.md +409 -280
- package/package.json +2 -2
- package/skills/delegate/SKILL.md +128 -47
- package/src/command.ts +124 -32
- package/src/contract.ts +137 -11
- package/src/doctor.ts +385 -0
- package/src/events.ts +22 -1
- package/src/index.ts +466 -271
- package/src/registry.ts +108 -29
- package/src/result-schema.ts +143 -0
- package/src/retention.ts +132 -34
- package/src/run.ts +93 -21
- package/src/spawn.ts +6 -2
- package/src/supervisor.mjs +113 -4
- package/src/verify.ts +16 -1
- package/src/worker.ts +128 -59
- package/src/worktree.ts +107 -3
package/src/worker.ts
CHANGED
|
@@ -16,16 +16,21 @@
|
|
|
16
16
|
|
|
17
17
|
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
18
18
|
import { Type } from "typebox";
|
|
19
|
+
import { Value } from "typebox/value";
|
|
19
20
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
20
21
|
import {
|
|
21
22
|
addUsage,
|
|
22
23
|
budgetStatus,
|
|
23
24
|
budgetSummary,
|
|
24
25
|
buildContinuation,
|
|
26
|
+
buildSteeringMessage,
|
|
27
|
+
canonicalCallSignature,
|
|
25
28
|
childBudgetVerdict,
|
|
29
|
+
DEFAULT_VERIFY_TIMEOUT_MS,
|
|
26
30
|
emptyBreaker,
|
|
27
31
|
emptyUsage,
|
|
28
32
|
FOREIGN_GOAL_TOOLS,
|
|
33
|
+
MAX_STRUCTURED_RESULT_CHARS,
|
|
29
34
|
noteIdleTurn,
|
|
30
35
|
noteToolCall,
|
|
31
36
|
noteToolResult,
|
|
@@ -34,11 +39,20 @@ import {
|
|
|
34
39
|
SPEC_ENV,
|
|
35
40
|
type BreakerState,
|
|
36
41
|
type BudgetLimits,
|
|
42
|
+
type JsonValue,
|
|
37
43
|
type RunSpec,
|
|
38
44
|
type RunStatus,
|
|
39
45
|
type Usage,
|
|
46
|
+
type VerificationRecord,
|
|
40
47
|
} from "./contract.ts";
|
|
48
|
+
import { describeSchemaErrors } from "./result-schema.ts";
|
|
41
49
|
import type { ChildResult } from "./run.ts";
|
|
50
|
+
import { runVerification } from "./verify.ts";
|
|
51
|
+
|
|
52
|
+
/** One tool-shaped refusal: the child sees why, and the run keeps going. */
|
|
53
|
+
function toolError(text: string): { content: Array<{ type: "text"; text: string }>; details: Record<string, never>; isError: true } {
|
|
54
|
+
return { content: [{ type: "text", text }], details: {}, isError: true };
|
|
55
|
+
}
|
|
42
56
|
|
|
43
57
|
interface Terminal {
|
|
44
58
|
status: RunStatus;
|
|
@@ -46,6 +60,8 @@ interface Terminal {
|
|
|
46
60
|
evidence?: string;
|
|
47
61
|
/** What the parent must provide. Only a blocked verdict carries one. */
|
|
48
62
|
needs?: string;
|
|
63
|
+
result?: JsonValue;
|
|
64
|
+
childVerification?: VerificationRecord;
|
|
49
65
|
}
|
|
50
66
|
|
|
51
67
|
/** One steering message the parent wrote into this run's inbox. */
|
|
@@ -106,7 +122,16 @@ function readInbox(path: string | undefined, consumed: { count: number }): strin
|
|
|
106
122
|
function assistantTextOf(messages: unknown[]): string {
|
|
107
123
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
108
124
|
const message = messages[index] as { role?: string; content?: unknown };
|
|
109
|
-
if (message?.role !== "assistant"
|
|
125
|
+
if (message?.role !== "assistant") continue;
|
|
126
|
+
// The text arrives as one string or as content blocks. Reading only the
|
|
127
|
+
// block form left lastAssistantText empty for a host that sends a string,
|
|
128
|
+
// which silently disabled the idle-answer breaker on those runs.
|
|
129
|
+
if (typeof message.content === "string") {
|
|
130
|
+
const text = message.content.trim();
|
|
131
|
+
if (text) return text;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (!Array.isArray(message.content)) continue;
|
|
110
135
|
const text = message.content
|
|
111
136
|
.filter((block): block is { type: "text"; text: string } => {
|
|
112
137
|
const candidate = block as { type?: string; text?: unknown };
|
|
@@ -131,49 +156,6 @@ function errorOf(messages: unknown[]): string | undefined {
|
|
|
131
156
|
return undefined;
|
|
132
157
|
}
|
|
133
158
|
|
|
134
|
-
/** A value this module is willing to compare: JSON, with cycles already cut. */
|
|
135
|
-
type Canonical = string | number | boolean | null | Canonical[] | { [key: string]: Canonical };
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Canonical form of a tool call's input.
|
|
139
|
-
*
|
|
140
|
-
* Two calls with the same content in a different key order are the same call.
|
|
141
|
-
* A signature that depends on insertion order would let a loop retry the same
|
|
142
|
-
* command forever by rewriting its arguments, and JSON.stringify throws on a
|
|
143
|
-
* circular value that a tool managed to pass.
|
|
144
|
-
*/
|
|
145
|
-
function callSignature(toolName: unknown, input: unknown): string {
|
|
146
|
-
const seen = new WeakSet<object>();
|
|
147
|
-
const walk = (value: unknown): Canonical => {
|
|
148
|
-
if (value === null || value === undefined) return null;
|
|
149
|
-
if (Array.isArray(value)) return value.map(walk);
|
|
150
|
-
switch (typeof value) {
|
|
151
|
-
case "string":
|
|
152
|
-
case "boolean":
|
|
153
|
-
return value;
|
|
154
|
-
case "number":
|
|
155
|
-
return Number.isFinite(value) ? value : String(value);
|
|
156
|
-
case "object": {
|
|
157
|
-
if (seen.has(value)) return "[circular]";
|
|
158
|
-
seen.add(value);
|
|
159
|
-
const source = value as Record<string, unknown>;
|
|
160
|
-
const sorted: Record<string, Canonical> = {};
|
|
161
|
-
for (const key of Object.keys(source).sort()) sorted[key] = walk(source[key]);
|
|
162
|
-
return sorted;
|
|
163
|
-
}
|
|
164
|
-
default:
|
|
165
|
-
// Functions, symbols, bigints: name them rather than dropping them,
|
|
166
|
-
// so two different calls never collapse into one signature.
|
|
167
|
-
return String(value);
|
|
168
|
-
}
|
|
169
|
-
};
|
|
170
|
-
try {
|
|
171
|
-
return `${String(toolName ?? "?")}:${JSON.stringify(walk(input ?? {}))}`;
|
|
172
|
-
} catch {
|
|
173
|
-
return `${String(toolName ?? "?")}:unserialisable`;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
159
|
export default function delegateWorker(pi: ExtensionAPI) {
|
|
178
160
|
// A hoisted function declaration below cannot rely on the narrowing of an
|
|
179
161
|
// optional binding, so the checked value is rebound to a required local.
|
|
@@ -203,7 +185,6 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
203
185
|
/** Steering messages the parent wrote, and how many lines were already read. */
|
|
204
186
|
const inboxPath = spec.inboxPath;
|
|
205
187
|
const inboxSeen = { count: 0 };
|
|
206
|
-
let pendingSteering: string[] = [];
|
|
207
188
|
|
|
208
189
|
const limits = (): BudgetLimits => ({
|
|
209
190
|
maxTurns: spec.maxTurns,
|
|
@@ -223,6 +204,8 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
223
204
|
summary: (terminal?.summary ?? lastAssistantText).slice(-4000),
|
|
224
205
|
evidence: terminal?.evidence,
|
|
225
206
|
needs: terminal?.needs,
|
|
207
|
+
result: terminal?.result,
|
|
208
|
+
childVerification: terminal?.childVerification,
|
|
226
209
|
turns,
|
|
227
210
|
maxTurns: spec.maxTurns,
|
|
228
211
|
toolCalls,
|
|
@@ -243,12 +226,23 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
243
226
|
}
|
|
244
227
|
}
|
|
245
228
|
|
|
246
|
-
function finish(
|
|
229
|
+
function finish(
|
|
230
|
+
status: RunStatus,
|
|
231
|
+
summary: string,
|
|
232
|
+
extra?: { evidence?: string; needs?: string; result?: JsonValue; childVerification?: VerificationRecord },
|
|
233
|
+
): void {
|
|
247
234
|
if (terminal) {
|
|
248
235
|
writeResult();
|
|
249
236
|
return;
|
|
250
237
|
}
|
|
251
|
-
terminal = {
|
|
238
|
+
terminal = {
|
|
239
|
+
status,
|
|
240
|
+
summary,
|
|
241
|
+
evidence: extra?.evidence,
|
|
242
|
+
needs: extra?.needs,
|
|
243
|
+
result: extra?.result,
|
|
244
|
+
childVerification: extra?.childVerification,
|
|
245
|
+
};
|
|
252
246
|
writeResult();
|
|
253
247
|
}
|
|
254
248
|
|
|
@@ -266,17 +260,88 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
266
260
|
name: "delegate_complete",
|
|
267
261
|
label: "Delegation Complete",
|
|
268
262
|
description:
|
|
269
|
-
"Declare the delegated goal complete.
|
|
263
|
+
"Declare the delegated goal complete. Include concrete evidence and the requested structured result. Any configured verification command gates this call: on failure, repair the work and retry.",
|
|
270
264
|
parameters: Type.Object({
|
|
271
265
|
summary: Type.String({ description: "What was achieved, in 1-3 sentences." }),
|
|
272
266
|
evidence: Type.Optional(
|
|
273
267
|
Type.String({ description: "Concrete proof: commands and results, files changed, tests or checks that pass." }),
|
|
274
268
|
),
|
|
269
|
+
result: Type.Optional(Type.Any({ description: "Structured JSON result for the parent or a codemode orchestrator." })),
|
|
275
270
|
}),
|
|
276
|
-
async execute(_toolCallId, params) {
|
|
277
|
-
|
|
271
|
+
async execute(_toolCallId, params, signal) {
|
|
272
|
+
let structured: JsonValue | undefined;
|
|
273
|
+
if (params.result !== undefined) {
|
|
274
|
+
try {
|
|
275
|
+
const serialized = JSON.stringify(params.result);
|
|
276
|
+
if (serialized === undefined) throw new Error("the result is not JSON");
|
|
277
|
+
if (serialized.length > MAX_STRUCTURED_RESULT_CHARS) {
|
|
278
|
+
return toolError(
|
|
279
|
+
`The structured result exceeds ${MAX_STRUCTURED_RESULT_CHARS} characters. Return a bounded result and put large artifacts in files.`,
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
structured = JSON.parse(serialized) as JsonValue;
|
|
283
|
+
} catch (error) {
|
|
284
|
+
return toolError(`The structured result is not valid JSON: ${String(error)}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (spec.resultSchema) {
|
|
288
|
+
let valid = false;
|
|
289
|
+
try {
|
|
290
|
+
valid = structured !== undefined && Value.Check(spec.resultSchema as never, structured);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
// A schema that cannot be evaluated rejects every value, so no
|
|
293
|
+
// repair of the value can pass it. Say which failure this is.
|
|
294
|
+
return toolError(
|
|
295
|
+
`The run's result schema could not be evaluated: ${String(error).slice(0, 300)}. No result can satisfy it; report this with delegate_blocked instead of retrying.`,
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
if (!valid) {
|
|
299
|
+
return toolError(
|
|
300
|
+
`The structured result does not satisfy the run's result schema. ${describeSchemaErrors(spec.resultSchema, structured)} Correct the \`result\` value and call delegate_complete again.`,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
let childVerification: VerificationRecord | undefined;
|
|
305
|
+
if (spec.verify) {
|
|
306
|
+
// The gate is a command, so it can outlive the budget it is running
|
|
307
|
+
// under: an aborted or expired run must not spend two more minutes
|
|
308
|
+
// in a check whose answer can no longer be recorded.
|
|
309
|
+
if (signal?.aborted) {
|
|
310
|
+
return toolError("The delegation was cancelled before its completion gate ran; no verdict was recorded.");
|
|
311
|
+
}
|
|
312
|
+
const remaining = spec.deadline - Date.now();
|
|
313
|
+
if (Number.isFinite(remaining) && remaining <= 0) {
|
|
314
|
+
return toolError("The run's deadline has already passed, so its completion gate was not run.");
|
|
315
|
+
}
|
|
316
|
+
const configured = Number(process.env.PI_DELEGATE_VERIFY_TIMEOUT_MS ?? DEFAULT_VERIFY_TIMEOUT_MS);
|
|
317
|
+
const limitMs = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_VERIFY_TIMEOUT_MS;
|
|
318
|
+
const timeoutMs = Number.isFinite(remaining) ? Math.max(1000, Math.min(limitMs, remaining)) : limitMs;
|
|
319
|
+
childVerification = await runVerification({
|
|
320
|
+
command: spec.verify.command,
|
|
321
|
+
cwd: spec.cwd,
|
|
322
|
+
timeoutMs,
|
|
323
|
+
signal,
|
|
324
|
+
});
|
|
325
|
+
if (terminal) {
|
|
326
|
+
return toolError("The delegation ended while its completion gate ran; this claim was not recorded.");
|
|
327
|
+
}
|
|
328
|
+
if (childVerification.timedOut || childVerification.exitCode !== 0) {
|
|
329
|
+
const outcome = childVerification.timedOut
|
|
330
|
+
? `timed out after ${childVerification.durationMs}ms`
|
|
331
|
+
: `exited ${childVerification.exitCode === null ? "without a status" : childVerification.exitCode}`;
|
|
332
|
+
return toolError(
|
|
333
|
+
`Completion verification failed: \`${spec.verify.command}\` ${outcome}. Fix the cause and call delegate_complete again.\n${childVerification.output}`,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
finish("complete", params.summary, { evidence: params.evidence, result: structured, childVerification });
|
|
338
|
+
// A run with no gate has nothing for the parent to re-run: claiming an
|
|
339
|
+
// independent recheck would overstate what this run proved.
|
|
340
|
+
const closing = spec.verify
|
|
341
|
+
? "Goal recorded as complete after the child-side completion gate. Stop working now; the parent independently re-checks the claim."
|
|
342
|
+
: "Goal recorded as complete. Stop working now; the parent receives your summary and evidence.";
|
|
278
343
|
return {
|
|
279
|
-
content: [{ type: "text" as const, text:
|
|
344
|
+
content: [{ type: "text" as const, text: closing }],
|
|
280
345
|
details: {},
|
|
281
346
|
terminate: true,
|
|
282
347
|
};
|
|
@@ -331,10 +396,6 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
331
396
|
// agent_settled never bounds the loop it exists to bound.
|
|
332
397
|
pi.on("turn_start", (_event, ctx) => {
|
|
333
398
|
ctxAbort = () => ctx.abort();
|
|
334
|
-
// Steering is read here, at the boundary between turns: a message that
|
|
335
|
-
// arrives mid-turn must not be lost, and it must not be injected into a
|
|
336
|
-
// request that is already in flight.
|
|
337
|
-
for (const message of readInbox(inboxPath, inboxSeen)) pendingSteering.push(message);
|
|
338
399
|
if (terminal) return;
|
|
339
400
|
const verdict = childBudgetVerdict(limits(), observed());
|
|
340
401
|
if (verdict !== "ok") {
|
|
@@ -342,6 +403,16 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
342
403
|
stopRun();
|
|
343
404
|
return;
|
|
344
405
|
}
|
|
406
|
+
const steering = readInbox(inboxPath, inboxSeen);
|
|
407
|
+
if (steering.length > 0) {
|
|
408
|
+
try {
|
|
409
|
+
pi.sendUserMessage(buildSteeringMessage(steering), { deliverAs: "steer" });
|
|
410
|
+
} catch (error) {
|
|
411
|
+
finish("error", `Could not queue parent steering: ${String(error)}`);
|
|
412
|
+
stopRun();
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
345
416
|
turns += 1;
|
|
346
417
|
// Only the per-turn counter resets here. The breaker state survives a turn
|
|
347
418
|
// boundary on purpose: the usual way a goal loop gets stuck is one
|
|
@@ -381,7 +452,7 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
381
452
|
pi.on("tool_call", (event, ctx) => {
|
|
382
453
|
ctxAbort = () => ctx.abort();
|
|
383
454
|
const call = event as { toolName?: string; input?: unknown };
|
|
384
|
-
const signature =
|
|
455
|
+
const signature = canonicalCallSignature(call.toolName, call.input);
|
|
385
456
|
toolCalls += 1;
|
|
386
457
|
toolCallsThisTurn += 1;
|
|
387
458
|
const verdict = noteToolCall(breaker, signature, call.toolName ?? "");
|
|
@@ -430,10 +501,8 @@ export default function delegateWorker(pi: ExtensionAPI) {
|
|
|
430
501
|
return;
|
|
431
502
|
}
|
|
432
503
|
// One more run of the goal loop, not a new goal: the child keeps its context.
|
|
433
|
-
const steering = pendingSteering;
|
|
434
|
-
pendingSteering = [];
|
|
435
504
|
try {
|
|
436
|
-
pi.sendUserMessage(buildContinuation(spec, turns + 1
|
|
505
|
+
pi.sendUserMessage(buildContinuation(spec, turns + 1), { deliverAs: "followUp" });
|
|
437
506
|
} catch (error) {
|
|
438
507
|
finish("error", `Could not queue the next goal turn: ${String(error)}`);
|
|
439
508
|
}
|
package/src/worktree.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { spawnSync } from "node:child_process";
|
|
17
|
-
import { existsSync } from "node:fs";
|
|
17
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
18
18
|
import { join } from "node:path";
|
|
19
19
|
import { delegateRoot } from "./spawn.ts";
|
|
20
20
|
|
|
@@ -24,6 +24,21 @@ export interface WorktreeRef {
|
|
|
24
24
|
branch: string;
|
|
25
25
|
/** The repository the worktree was added to. */
|
|
26
26
|
repo: string;
|
|
27
|
+
/** Commit from which the delegation started. */
|
|
28
|
+
base?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface WorktreeIntegration {
|
|
32
|
+
base?: string;
|
|
33
|
+
head: string;
|
|
34
|
+
clean: boolean;
|
|
35
|
+
status: string;
|
|
36
|
+
diffStat: string;
|
|
37
|
+
patchPath?: string;
|
|
38
|
+
applyCommand?: string;
|
|
39
|
+
checkCommand?: string;
|
|
40
|
+
applyCheck?: { ok: boolean; output: string };
|
|
41
|
+
error?: string;
|
|
27
42
|
}
|
|
28
43
|
|
|
29
44
|
export interface GitResult {
|
|
@@ -41,6 +56,23 @@ export function git(args: readonly string[], cwd: string): GitResult {
|
|
|
41
56
|
};
|
|
42
57
|
}
|
|
43
58
|
|
|
59
|
+
/**
|
|
60
|
+
* `git status --porcelain`, with its leading spaces intact.
|
|
61
|
+
*
|
|
62
|
+
* The porcelain format is positional: `" M path"` is an unstaged change and
|
|
63
|
+
* `"M path"` is a staged one. Trimming the output - which the ordinary helper
|
|
64
|
+
* does, because a diff stat has no meaningful edge whitespace - rewrote the
|
|
65
|
+
* first entry of every report into a different status than git wrote.
|
|
66
|
+
*/
|
|
67
|
+
function gitStatus(cwd: string): GitResult {
|
|
68
|
+
const result = spawnSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", timeout: 60_000, windowsHide: true });
|
|
69
|
+
return {
|
|
70
|
+
ok: result.status === 0,
|
|
71
|
+
stdout: (result.stdout ?? "").replace(/\s+$/u, ""),
|
|
72
|
+
stderr: (result.stderr ?? "").trim() || (result.error ? String(result.error) : ""),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
44
76
|
/** True when `git` runs at all, which is what a worktree request needs. */
|
|
45
77
|
export function gitAvailable(): boolean {
|
|
46
78
|
try {
|
|
@@ -77,7 +109,8 @@ export function createWorktree(runId: string, cwd: string): WorktreeRef {
|
|
|
77
109
|
if (!added.ok) {
|
|
78
110
|
throw new Error(`worktree: git worktree add failed: ${added.stderr || added.stdout || "unknown error"}`);
|
|
79
111
|
}
|
|
80
|
-
|
|
112
|
+
const base = git(["rev-parse", "HEAD"], path).stdout || undefined;
|
|
113
|
+
return { path, branch, repo, base };
|
|
81
114
|
}
|
|
82
115
|
|
|
83
116
|
/**
|
|
@@ -88,11 +121,82 @@ export function createWorktree(runId: string, cwd: string): WorktreeRef {
|
|
|
88
121
|
*/
|
|
89
122
|
export function removeWorktree(worktree: WorktreeRef): boolean {
|
|
90
123
|
if (!existsSync(worktree.path)) return false;
|
|
91
|
-
const status =
|
|
124
|
+
const status = gitStatus(worktree.path);
|
|
92
125
|
if (!status.ok || status.stdout !== "") return false;
|
|
93
126
|
return git(["worktree", "remove", "--force", worktree.path], worktree.repo).ok;
|
|
94
127
|
}
|
|
95
128
|
|
|
129
|
+
function shellQuote(value: string): string {
|
|
130
|
+
return "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Export the child's committed and uncommitted work without committing it.
|
|
135
|
+
* Untracked files are appended as no-index patches, so a dirty checkout remains
|
|
136
|
+
* a first-class deliverable rather than an invisible part of the result.
|
|
137
|
+
*/
|
|
138
|
+
export function exportWorktreeIntegration(worktree: WorktreeRef, runDir: string): WorktreeIntegration {
|
|
139
|
+
const head = git(["rev-parse", "HEAD"], worktree.path).stdout;
|
|
140
|
+
const status = gitStatus(worktree.path);
|
|
141
|
+
const base = worktree.base;
|
|
142
|
+
const integration: WorktreeIntegration = {
|
|
143
|
+
base,
|
|
144
|
+
head,
|
|
145
|
+
clean: status.ok && status.stdout === "",
|
|
146
|
+
status: status.stdout,
|
|
147
|
+
diffStat: base ? git(["diff", "--stat", base], worktree.path).stdout : "",
|
|
148
|
+
};
|
|
149
|
+
if (!head || !status.ok) {
|
|
150
|
+
integration.error = status.stderr || "cannot read the worktree HEAD";
|
|
151
|
+
return integration;
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
let patch = "";
|
|
155
|
+
if (base) {
|
|
156
|
+
const tracked = spawnSync("git", ["diff", "--binary", "--full-index", base], {
|
|
157
|
+
cwd: worktree.path,
|
|
158
|
+
encoding: "utf8",
|
|
159
|
+
timeout: 60_000,
|
|
160
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
161
|
+
windowsHide: true,
|
|
162
|
+
});
|
|
163
|
+
if (tracked.status !== 0) throw new Error(tracked.stderr || "git diff failed");
|
|
164
|
+
patch += tracked.stdout;
|
|
165
|
+
}
|
|
166
|
+
const untracked = spawnSync("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
|
|
167
|
+
cwd: worktree.path,
|
|
168
|
+
encoding: "utf8",
|
|
169
|
+
timeout: 60_000,
|
|
170
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
171
|
+
windowsHide: true,
|
|
172
|
+
});
|
|
173
|
+
if (untracked.status !== 0) throw new Error(untracked.stderr || "git ls-files failed");
|
|
174
|
+
for (const file of untracked.stdout.split("\0").filter(Boolean)) {
|
|
175
|
+
const addition = spawnSync("git", ["diff", "--binary", "--no-index", "--", "/dev/null", file], {
|
|
176
|
+
cwd: worktree.path,
|
|
177
|
+
encoding: "utf8",
|
|
178
|
+
timeout: 60_000,
|
|
179
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
180
|
+
windowsHide: true,
|
|
181
|
+
});
|
|
182
|
+
if (addition.status !== 0 && addition.status !== 1) throw new Error(addition.stderr || `cannot export ${file}`);
|
|
183
|
+
patch += addition.stdout;
|
|
184
|
+
}
|
|
185
|
+
if (patch.trim()) {
|
|
186
|
+
const patchPath = join(runDir, "changes.patch");
|
|
187
|
+
writeFileSync(patchPath, patch, { mode: 0o600 });
|
|
188
|
+
integration.patchPath = patchPath;
|
|
189
|
+
integration.applyCommand = `git apply --3way ${shellQuote(patchPath)}`;
|
|
190
|
+
integration.checkCommand = `git apply --check ${shellQuote(patchPath)}`;
|
|
191
|
+
const check = git(["apply", "--check", patchPath], worktree.repo);
|
|
192
|
+
integration.applyCheck = { ok: check.ok, output: check.stderr || check.stdout };
|
|
193
|
+
}
|
|
194
|
+
} catch (error) {
|
|
195
|
+
integration.error = String(error);
|
|
196
|
+
}
|
|
197
|
+
return integration;
|
|
198
|
+
}
|
|
199
|
+
|
|
96
200
|
/** Whether cleanup is enabled for this process. */
|
|
97
201
|
export function worktreeCleanupEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
98
202
|
const raw = env.PI_DELEGATE_KEEP_WORKTREES;
|