@loucompanion/forge-bridge 0.1.4-dev.9ddc336f8a9d → 0.1.4-dev.a690038a6849
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/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +7 -13
- package/dist/session/provider-cli/provider-cli.process.d.ts +25 -1
- package/dist/session/provider-cli/provider-cli.process.js +110 -26
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +13 -0
- package/dist/session/provider-cli/provider-cli.service.js +92 -19
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/publishable-worktree-changes.d.ts +45 -0
- package/dist/session/publishable-worktree-changes.js +177 -0
- package/dist/session/session.types.js +9 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { redactSecrets } from "../shared/redaction/redaction.js";
|
|
5
5
|
import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
|
|
6
|
+
import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
|
|
6
7
|
import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
|
|
7
8
|
import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaStringArray, readOptionalFile, reportMarkdown, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
|
|
8
9
|
export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
|
|
@@ -158,6 +159,9 @@ export async function writeCompletionArtifact(config, toolName, input) {
|
|
|
158
159
|
}
|
|
159
160
|
validatePayloadShape(phase, validationPayload);
|
|
160
161
|
validateOptionalWorkItemId(validationPayload, config.workItemId);
|
|
162
|
+
if (phase === "comment_repair" && status === "pass") {
|
|
163
|
+
await assertClaimedChangedFilesMatchPublishableDiff(config.worktreePath, validationPayload, toolName);
|
|
164
|
+
}
|
|
161
165
|
const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
|
|
162
166
|
assertStructuralFieldsUnchanged(validationPayload, redactedPayload);
|
|
163
167
|
validatePostRedaction(() => {
|
|
@@ -2,6 +2,7 @@ import { GitClient } from "../../shared/git/git.js";
|
|
|
2
2
|
import { type CompletionPhase, type CompletionToolRuntime, type DebugCompletionPhase, type QaCompletionGate } from "../phase-completion.js";
|
|
3
3
|
import type { RunOnceDispatchPacket, RunnerDispatchArtifact, RunnerDispatchSidecar } from "../session.types.js";
|
|
4
4
|
import type { ProviderCliRunContext } from "./provider-cli.types.js";
|
|
5
|
+
import { type ProviderProcessRunResult } from "./provider-cli.process.js";
|
|
5
6
|
export declare function emitDraftGateArtifacts(emit: ProviderCliRunContext["emit"], worktreePath: string, workItemId: string): Promise<void>;
|
|
6
7
|
export declare function emitDecomposeGateArtifacts(emit: ProviderCliRunContext["emit"], worktreePath: string, workItemId: string): Promise<void>;
|
|
7
8
|
export declare function fileExists(filePath: string): Promise<boolean>;
|
|
@@ -91,5 +92,5 @@ export declare class LiveCompletionArtifactEmitter {
|
|
|
91
92
|
private pollQueued;
|
|
92
93
|
private poll;
|
|
93
94
|
}
|
|
94
|
-
export declare function readCompletionArtifactsForRun(worktreePath: string, workItemId: string, phase: CompletionPhase, developCycle: boolean, debugCycle: boolean): Promise<RunnerDispatchArtifact[]>;
|
|
95
|
+
export declare function readCompletionArtifactsForRun(worktreePath: string, workItemId: string, phase: CompletionPhase, developCycle: boolean, debugCycle: boolean, providerResult?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): Promise<RunnerDispatchArtifact[]>;
|
|
95
96
|
export {};
|
|
@@ -2,12 +2,13 @@ import fs from "node:fs/promises";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder, readCompletionArtifact } from "../phase-completion.js";
|
|
4
4
|
import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
|
|
5
|
+
import { stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
|
|
6
|
+
import { providerCompletionToolMissingFailure } from "./provider-cli.process.js";
|
|
5
7
|
import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
|
|
6
8
|
import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
|
|
7
9
|
const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
|
|
8
10
|
const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
|
|
9
11
|
const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
|
|
10
|
-
const nonPublishableWorktreePaths = [".forge", ".local"];
|
|
11
12
|
export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
|
|
12
13
|
const draftArtifactFiles = {
|
|
13
14
|
draft_intent: "draft.intent.json",
|
|
@@ -157,14 +158,7 @@ export async function commitWorktreeChanges(git, worktreePath, workItemId, alrea
|
|
|
157
158
|
return { commitSha, changedFiles };
|
|
158
159
|
}
|
|
159
160
|
export async function stagePublishableWorktreeChanges(git, worktreePath) {
|
|
160
|
-
await git
|
|
161
|
-
for (const reservedPath of nonPublishableWorktreePaths) {
|
|
162
|
-
await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
|
|
163
|
-
}
|
|
164
|
-
return (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
|
|
165
|
-
.split(/\r?\n/)
|
|
166
|
-
.map((line) => line.trim())
|
|
167
|
-
.filter(Boolean);
|
|
161
|
+
return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
|
|
168
162
|
}
|
|
169
163
|
export function phaseCompleteEventType(phase) {
|
|
170
164
|
return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
|
|
@@ -779,11 +773,11 @@ export class LiveCompletionArtifactEmitter {
|
|
|
779
773
|
}
|
|
780
774
|
}
|
|
781
775
|
}
|
|
782
|
-
export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
|
|
776
|
+
export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle, providerResult) {
|
|
783
777
|
if (!developCycle && !debugCycle) {
|
|
784
778
|
const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
|
|
785
779
|
if (!artifact) {
|
|
786
|
-
throw
|
|
780
|
+
throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${phase} completion tool.`, providerResult);
|
|
787
781
|
}
|
|
788
782
|
return [artifact];
|
|
789
783
|
}
|
|
@@ -795,11 +789,11 @@ export async function readCompletionArtifactsForRun(worktreePath, workItemId, ph
|
|
|
795
789
|
const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
|
|
796
790
|
if (!artifact) {
|
|
797
791
|
if (artifacts.length === 0) {
|
|
798
|
-
throw
|
|
792
|
+
throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
|
|
799
793
|
}
|
|
800
794
|
const previous = artifacts[artifacts.length - 1];
|
|
801
795
|
if ((previous.status ?? "").trim().toLowerCase() === "pass") {
|
|
802
|
-
throw
|
|
796
|
+
throw providerCompletionToolMissingFailure(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
|
|
803
797
|
}
|
|
804
798
|
return artifacts;
|
|
805
799
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type LaunchCommand } from "../../shared/process/windows-launch.js";
|
|
2
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
2
3
|
export declare const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS: number;
|
|
3
4
|
export type ProviderCliCommand = LaunchCommand;
|
|
4
5
|
export interface ProviderProcessRunRequest {
|
|
@@ -14,7 +15,15 @@ export interface ProviderProcessRunRequest {
|
|
|
14
15
|
* supervisor and is never forwarded to the child process.
|
|
15
16
|
*/
|
|
16
17
|
readonly failureRedactionValues?: readonly string[];
|
|
18
|
+
/**
|
|
19
|
+
* The run resumes an existing provider thread. Such a run can replay a queued
|
|
20
|
+
* notification turn before the prompt's turn, and that replayed turn must not
|
|
21
|
+
* start the success ceiling.
|
|
22
|
+
*/
|
|
23
|
+
readonly resumesProviderThread?: boolean;
|
|
17
24
|
}
|
|
25
|
+
/** Why Forge stopped a provider that was still resident after a successful turn. */
|
|
26
|
+
export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling";
|
|
18
27
|
export interface ProviderProcessRunResult {
|
|
19
28
|
readonly exitCode: number;
|
|
20
29
|
readonly stdout: string;
|
|
@@ -25,6 +34,8 @@ export interface ProviderProcessRunResult {
|
|
|
25
34
|
readonly memoryObservedAt?: string;
|
|
26
35
|
/** Present when the caller's cancellation stopped the process before it exited on its own. */
|
|
27
36
|
readonly cancelled?: true;
|
|
37
|
+
/** Present when Forge stopped a provider that stayed resident after a successful turn. */
|
|
38
|
+
readonly terminalStopReason?: ProviderTerminalStopReason;
|
|
28
39
|
}
|
|
29
40
|
export interface ProviderProcessRunner {
|
|
30
41
|
run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
|
|
@@ -33,6 +44,12 @@ export interface ProviderProcessHandlers {
|
|
|
33
44
|
onStarted?(): Promise<void> | void;
|
|
34
45
|
onStdoutLine?(line: string): Promise<void> | void;
|
|
35
46
|
onStderrLine?(line: string): Promise<void> | void;
|
|
47
|
+
/**
|
|
48
|
+
* True while the provider has a tool call (such as an MCP tool call) in flight. While it
|
|
49
|
+
* is, or while an attempt-owned managed command is non-terminal, Forge suspends the
|
|
50
|
+
* end-of-turn exit grace and the success ceiling.
|
|
51
|
+
*/
|
|
52
|
+
isToolCallInFlight?(): boolean;
|
|
36
53
|
}
|
|
37
54
|
/** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
|
|
38
55
|
* relaunch needs a new fenced child generation and exclusive launch files. */
|
|
@@ -73,9 +90,16 @@ export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Reco
|
|
|
73
90
|
export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
|
|
74
91
|
private readonly terminalExitGraceMs;
|
|
75
92
|
private readonly terminalSuccessCeilingMs;
|
|
76
|
-
|
|
93
|
+
private readonly terminalWorkPollMs;
|
|
94
|
+
constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
|
|
77
95
|
run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
|
|
78
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* The typed failure for a provider run that ended without calling its required Forge
|
|
99
|
+
* completion tool. A run Forge stopped at the success ceiling is reported as such, so it
|
|
100
|
+
* is not mistaken for an agent that simply ended its turn.
|
|
101
|
+
*/
|
|
102
|
+
export declare function providerCompletionToolMissingFailure(message: string, result?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): ForgeFailureError;
|
|
79
103
|
/** Returns aggregate resident bytes for the exact supervised Unix process group. */
|
|
80
104
|
export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
|
|
81
105
|
export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
|
|
@@ -10,6 +10,7 @@ import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunc
|
|
|
10
10
|
import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
|
|
11
11
|
import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
|
|
12
12
|
import { ForgeFailureError } from "../session.types.js";
|
|
13
|
+
import { hasNonterminalManagedCommand } from "./provider-in-flight-work.js";
|
|
13
14
|
const execFileAsync = promisify(execFile);
|
|
14
15
|
// Provider processes can emit many gigabytes over a long-running session. The
|
|
15
16
|
// line handlers stream that output to Forge as it arrives; the completed result
|
|
@@ -17,8 +18,11 @@ const execFileAsync = promisify(execFile);
|
|
|
17
18
|
export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
|
|
18
19
|
const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
|
|
19
20
|
// A provider that keeps starting turns after its first successful one (background-task
|
|
20
|
-
// notifications) is still stopped this
|
|
21
|
+
// notifications) is still stopped once this much time without supervised work in flight
|
|
22
|
+
// has passed since that first success.
|
|
21
23
|
const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
|
|
24
|
+
// How often the end-of-turn timers re-check whether supervised work is still in flight.
|
|
25
|
+
const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
|
|
22
26
|
const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
|
|
23
27
|
/** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
|
|
24
28
|
* relaunch needs a new fenced child generation and exclusive launch files. */
|
|
@@ -317,9 +321,11 @@ function setEnvironmentValueIfMissing(env, name, value) {
|
|
|
317
321
|
export class StreamingProviderProcessRunner {
|
|
318
322
|
terminalExitGraceMs;
|
|
319
323
|
terminalSuccessCeilingMs;
|
|
320
|
-
|
|
324
|
+
terminalWorkPollMs;
|
|
325
|
+
constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
|
|
321
326
|
this.terminalExitGraceMs = terminalExitGraceMs;
|
|
322
327
|
this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
|
|
328
|
+
this.terminalWorkPollMs = terminalWorkPollMs;
|
|
323
329
|
}
|
|
324
330
|
async run(request, handlers = {}, signal) {
|
|
325
331
|
assertHostDatabaseCapabilityBoundary();
|
|
@@ -376,19 +382,22 @@ export class StreamingProviderProcessRunner {
|
|
|
376
382
|
let cancellationRequested = false;
|
|
377
383
|
let cancelledBeforeClose = false;
|
|
378
384
|
let terminalTerminationStarted = false;
|
|
379
|
-
let
|
|
380
|
-
|
|
385
|
+
let terminalStopReason = null;
|
|
386
|
+
// Idle time (no supervised work in flight) accrued against the end-of-turn grace and
|
|
387
|
+
// the success ceiling; null while that timer is not armed.
|
|
388
|
+
let graceIdleMs = null;
|
|
389
|
+
let ceilingIdleMs = null;
|
|
390
|
+
let terminalSuccessCount = 0;
|
|
391
|
+
let replayedTurnCeilingSkipped = false;
|
|
392
|
+
let terminalWorkTimer = null;
|
|
393
|
+
let terminalWorkTickAt = 0;
|
|
394
|
+
let terminalWorkTickRunning = false;
|
|
381
395
|
let latestTurnFailed = false;
|
|
382
396
|
let readiness = null;
|
|
383
397
|
const cleanup = () => {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
}
|
|
388
|
-
if (terminalCeilingTimer) {
|
|
389
|
-
clearTimeout(terminalCeilingTimer);
|
|
390
|
-
terminalCeilingTimer = null;
|
|
391
|
-
}
|
|
398
|
+
stopTerminalWorkTimer();
|
|
399
|
+
graceIdleMs = null;
|
|
400
|
+
ceilingIdleMs = null;
|
|
392
401
|
signal?.removeEventListener("abort", abort);
|
|
393
402
|
};
|
|
394
403
|
const fail = (error) => {
|
|
@@ -490,22 +499,80 @@ export class StreamingProviderProcessRunner {
|
|
|
490
499
|
});
|
|
491
500
|
}
|
|
492
501
|
}
|
|
493
|
-
const finishAfterTerminalSuccess = () => {
|
|
502
|
+
const finishAfterTerminalSuccess = (reason) => {
|
|
494
503
|
if (closed || settled || cancellationRequested || terminalTerminationStarted)
|
|
495
504
|
return;
|
|
496
505
|
terminalTerminationStarted = true;
|
|
506
|
+
terminalStopReason = reason;
|
|
507
|
+
stopTerminalWorkTimer();
|
|
497
508
|
void terminate().catch(fail);
|
|
498
509
|
};
|
|
510
|
+
const workInFlight = async () => {
|
|
511
|
+
try {
|
|
512
|
+
if (handlers.isToolCallInFlight?.())
|
|
513
|
+
return true;
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
// A failing probe must not keep the provider open or stop it early on its own.
|
|
517
|
+
}
|
|
518
|
+
return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
|
|
519
|
+
};
|
|
520
|
+
// The grace and the ceiling only count time in which no supervised work is in flight:
|
|
521
|
+
// a provider waiting on an MCP tool call or on a managed command it started is not
|
|
522
|
+
// finished, even when its turn has ended. The grace restarts once that work is done.
|
|
523
|
+
const terminalWorkTick = async () => {
|
|
524
|
+
if (terminalWorkTickRunning)
|
|
525
|
+
return;
|
|
526
|
+
terminalWorkTickRunning = true;
|
|
527
|
+
try {
|
|
528
|
+
const inFlight = await workInFlight();
|
|
529
|
+
const now = performance.now();
|
|
530
|
+
const elapsed = Math.max(0, now - terminalWorkTickAt);
|
|
531
|
+
terminalWorkTickAt = now;
|
|
532
|
+
if (closed || settled || terminalTerminationStarted)
|
|
533
|
+
return;
|
|
534
|
+
if (inFlight) {
|
|
535
|
+
if (graceIdleMs !== null)
|
|
536
|
+
graceIdleMs = 0;
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (graceIdleMs !== null)
|
|
540
|
+
graceIdleMs += elapsed;
|
|
541
|
+
if (ceilingIdleMs !== null)
|
|
542
|
+
ceilingIdleMs += elapsed;
|
|
543
|
+
if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
|
|
544
|
+
finishAfterTerminalSuccess("turn_exit_grace");
|
|
545
|
+
}
|
|
546
|
+
else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
|
|
547
|
+
finishAfterTerminalSuccess("success_ceiling");
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
finally {
|
|
551
|
+
terminalWorkTickRunning = false;
|
|
552
|
+
if (graceIdleMs === null && ceilingIdleMs === null)
|
|
553
|
+
stopTerminalWorkTimer();
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
function stopTerminalWorkTimer() {
|
|
557
|
+
if (terminalWorkTimer) {
|
|
558
|
+
clearInterval(terminalWorkTimer);
|
|
559
|
+
terminalWorkTimer = null;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
const startTerminalWorkTimer = () => {
|
|
563
|
+
if (terminalWorkTimer)
|
|
564
|
+
return;
|
|
565
|
+
terminalWorkTickAt = performance.now();
|
|
566
|
+
const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
|
|
567
|
+
terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
|
|
568
|
+
terminalWorkTimer.unref?.();
|
|
569
|
+
};
|
|
499
570
|
const armTerminalExit = () => {
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
terminalExitTimer = setTimeout(finishAfterTerminalSuccess, this.terminalExitGraceMs);
|
|
503
|
-
terminalExitTimer.unref?.();
|
|
571
|
+
terminalSuccessCount += 1;
|
|
572
|
+
graceIdleMs = 0;
|
|
504
573
|
// Later turns may postpone the grace period, but never past this ceiling.
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
terminalCeilingTimer.unref?.();
|
|
508
|
-
}
|
|
574
|
+
ceilingIdleMs ??= 0;
|
|
575
|
+
startTerminalWorkTimer();
|
|
509
576
|
};
|
|
510
577
|
const readers = [
|
|
511
578
|
readProcessLines(childStdout, (line) => {
|
|
@@ -521,14 +588,19 @@ export class StreamingProviderProcessRunner {
|
|
|
521
588
|
// A later turn that fails reports its failure even after an earlier success.
|
|
522
589
|
latestTurnFailed = true;
|
|
523
590
|
}
|
|
524
|
-
else if (
|
|
591
|
+
else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
|
|
525
592
|
// A terminal event ends a turn, not necessarily the provider. Claude Code
|
|
526
593
|
// stays resident while background tasks it started are pending and begins a
|
|
527
|
-
// new turn when one reports
|
|
528
|
-
// notification turn first). A provider that is working again is not finished;
|
|
594
|
+
// new turn when one reports. A provider that is working again is not finished;
|
|
529
595
|
// the grace period restarts at its next terminal event.
|
|
530
|
-
|
|
531
|
-
|
|
596
|
+
graceIdleMs = null;
|
|
597
|
+
// A resumed session can replay a queued notification turn before the
|
|
598
|
+
// prompt's own turn. That replayed turn must not start the ceiling, or the
|
|
599
|
+
// resumed agent is stopped mid-work; the prompt's turn arms it instead.
|
|
600
|
+
if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
|
|
601
|
+
replayedTurnCeilingSkipped = true;
|
|
602
|
+
ceilingIdleMs = null;
|
|
603
|
+
}
|
|
532
604
|
}
|
|
533
605
|
}
|
|
534
606
|
return handled;
|
|
@@ -585,12 +657,24 @@ export class StreamingProviderProcessRunner {
|
|
|
585
657
|
stderr: stderr.toString(),
|
|
586
658
|
...(memory ?? {}),
|
|
587
659
|
...(cancelledBeforeClose ? { cancelled: true } : {}),
|
|
660
|
+
...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
|
|
588
661
|
});
|
|
589
662
|
}).catch(fail);
|
|
590
663
|
});
|
|
591
664
|
});
|
|
592
665
|
}
|
|
593
666
|
}
|
|
667
|
+
/**
|
|
668
|
+
* The typed failure for a provider run that ended without calling its required Forge
|
|
669
|
+
* completion tool. A run Forge stopped at the success ceiling is reported as such, so it
|
|
670
|
+
* is not mistaken for an agent that simply ended its turn.
|
|
671
|
+
*/
|
|
672
|
+
export function providerCompletionToolMissingFailure(message, result) {
|
|
673
|
+
if (result?.terminalStopReason === "success_ceiling") {
|
|
674
|
+
return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
|
|
675
|
+
}
|
|
676
|
+
return new ForgeFailureError("provider_completion_tool_missing", message);
|
|
677
|
+
}
|
|
594
678
|
/** A stream event that shows the provider is working on a turn: model output or a tool result. */
|
|
595
679
|
function isProviderTurnActivity(line) {
|
|
596
680
|
const trimmed = line.trim();
|
|
@@ -35,6 +35,11 @@ export declare function buildArchitectPrompt(dispatch: RunOnceDispatchPacket): s
|
|
|
35
35
|
export declare function architectDependencyInstruction(dispatch: RunOnceDispatchPacket): string;
|
|
36
36
|
export declare function designerRefInstruction(dispatch: RunOnceDispatchPacket): string;
|
|
37
37
|
export declare function architectRevisionInstruction(dispatch: RunOnceDispatchPacket): string;
|
|
38
|
+
/**
|
|
39
|
+
* Headless providers must not end a turn to wait: Forge stops the provider shortly after
|
|
40
|
+
* a turn ends, and nothing started in the background reports back.
|
|
41
|
+
*/
|
|
42
|
+
export declare function providerTurnEndRule(completionStep: string): string;
|
|
38
43
|
export declare function buildImplementationPrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
|
|
39
44
|
export declare function buildDevelopCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
|
|
40
45
|
export declare function buildDebugCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
|
|
@@ -392,6 +392,13 @@ Architect revision context:
|
|
|
392
392
|
- Reviewer feedback: ${dispatch.architectRevision.feedback}
|
|
393
393
|
Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
|
|
394
394
|
}
|
|
395
|
+
/**
|
|
396
|
+
* Headless providers must not end a turn to wait: Forge stops the provider shortly after
|
|
397
|
+
* a turn ends, and nothing started in the background reports back.
|
|
398
|
+
*/
|
|
399
|
+
export function providerTurnEndRule(completionStep) {
|
|
400
|
+
return `Ending your turn ends this run. Forge runs you headless and stops the provider process shortly after a turn ends, together with any managed command it is still running. Background tasks, Monitor, \`run_in_background\` shells and other watchers never report back after that. Do not end your turn to wait for anything: block on \`forge.wait_managed_command\` until it returns a terminal receipt (call it again while \`command_continues=true\`), then ${completionStep} in the same turn.`;
|
|
401
|
+
}
|
|
395
402
|
export function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
396
403
|
return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
|
|
397
404
|
|
|
@@ -403,6 +410,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
|
|
|
403
410
|
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
404
411
|
|
|
405
412
|
${completionPromptForPhase(phase)}
|
|
413
|
+
${providerTurnEndRule("call the completion tool")}
|
|
406
414
|
|
|
407
415
|
Finish with a concise summary of changed files and verification after calling the completion tool.`;
|
|
408
416
|
}
|
|
@@ -417,6 +425,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
|
|
|
417
425
|
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
418
426
|
|
|
419
427
|
${completionPromptForDevelopCycle(phase)}
|
|
428
|
+
${providerTurnEndRule("call the current phase's completion tool")}
|
|
420
429
|
|
|
421
430
|
Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
|
|
422
431
|
}
|
|
@@ -431,6 +440,7 @@ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills,
|
|
|
431
440
|
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
|
|
432
441
|
|
|
433
442
|
${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
|
|
443
|
+
${providerTurnEndRule("call the current Debug gate's completion tool")}
|
|
434
444
|
|
|
435
445
|
Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
|
|
436
446
|
}
|
|
@@ -587,6 +597,7 @@ Report in-scope defects as actionable findings with repro steps, expected/actual
|
|
|
587
597
|
Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item. If a broad regression command fails only on a surface outside both the current diff and acceptance criteria, reproduce that failure with a focused command. The regression gate may pass only when the current item has independent passing evidence and the failed command is preserved with classification out_of_scope_failure, candidate_bug_id, scope_evidence, acceptance_criteria_independent: true, repro_command, and a non-zero repro_exit_code. Never use this classification for an unexplained failure, a runner/environment failure, or a failure that can affect the current item.
|
|
588
598
|
|
|
589
599
|
${completionPromptForQaCycle("qa_plan", artifactRoot)}
|
|
600
|
+
${providerTurnEndRule("call the next QA gate's completion tool, through forge.complete_qa_verdict,")}
|
|
590
601
|
|
|
591
602
|
Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
|
|
592
603
|
}
|
|
@@ -644,6 +655,7 @@ Forge prepared two required inputs before this agent started:
|
|
|
644
655
|
Read both first. The readiness contract supplies attempt-scoped E2E URLs, Playwright/browser readiness, runnable local preflight commands, and provider-only spec patterns. Run every listed local preflight. Do not override the readiness environment or bypass its provider-only exclusions: those specs require infrastructure unavailable inside this managed attempt. Record each applicable provider-only step and the provider check that supplies its proof, and leave provider CI authoritative without weakening its coverage.
|
|
645
656
|
|
|
646
657
|
After repair and validation, call forge.complete_ci_repair with the complete structured handoff. Forge Bridge will validate it and will not commit, push, or report success until that gate passes. If the tool rejects the payload, correct the exact missing evidence it reports and call it again.
|
|
658
|
+
${providerTurnEndRule("call forge.complete_ci_repair")}
|
|
647
659
|
|
|
648
660
|
Keep the original work item intent intact:
|
|
649
661
|
- Work item: ${dispatch.workItem.id}
|
|
@@ -695,6 +707,7 @@ Before handing a changed diff back for publication:
|
|
|
695
707
|
4. Fix validation failures locally before requesting publication. Preserve acceptance criteria and assertions; do not skip tests, weaken checks, change retry budgets, or edit the trusted validation contract to get green. A tier that is still running has not failed to finish: Forge terminates a hung command at its runner-owned limit, which the receipt reports as timeout_ms (${managedMaximumCommandTimeoutMs / 60_000} minutes for dotnet_affected, ${managedQuickTierTimeoutMs / 60_000} minutes for Unit and Contract, ${managedLongTierTimeoutMs / 60_000} minutes for one shard of another tier, and more for an all-shard run, scaled to its shard waves), and its receipt then reports timed_out. Never stop waiting, or record needs_rework, because a required tier is still running. Record a blocker only when infrastructure is unavailable; when a required check ends with a terminal timed_out, timeout_termination_failed, or runner_error receipt that a rerun cannot clear; when a receipt's elapsed time stops rising across waits; or when a real failure cannot be fixed after diagnosis. Then record the exact blocker and preserve the diff without claiming validation passed.
|
|
696
708
|
5. Inspect the final diff after all fixes and generated-file changes, run git diff --check, and rerun checks affected by any subsequent edit. Record commands, the affected-test selection it printed, exit statuses, and terminal evidence paths in the completion evidence. Finalize changed_files from that final diff, not an earlier repair draft.
|
|
697
709
|
Only after applicable local validation passes, call forge.complete_comment_repair with the exact head, issue key, finding identities, and evidence. Legitimate no-code rejection or already-addressed outcomes are successful dispositions and do not require an empty commit or unrelated test suites; provide evidence for each disposition.
|
|
710
|
+
${providerTurnEndRule("call forge.complete_comment_repair")}
|
|
698
711
|
Forge Bridge owns any commit and compare-and-swap push after its independent pre-publication gate succeeds, then selectively resolves only review threads dispositioned fixed, already_addressed, or server-verified accepted_transfer while all fences still match. The accepted-transfer receipt remains in durable repair evidence and source/target scope; Forge does not post a provider reply automatically. A local pass is not a GitHub CI pass: provider-only checks remain pending until CI runs on the pushed head. Do not request another review yourself; Forge owns the green-CI-before-review sequence.
|
|
699
712
|
Keep the original work item intent intact:
|
|
700
713
|
- Work item: ${dispatch.workItem.id}
|
|
@@ -6,10 +6,11 @@ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-inject
|
|
|
6
6
|
import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
|
|
7
7
|
import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
|
|
8
8
|
import { ForgeFailureError } from "../session.types.js";
|
|
9
|
-
import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle,
|
|
9
|
+
import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
|
|
10
|
+
import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
|
|
10
11
|
import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
11
12
|
import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
|
|
12
|
-
import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
13
|
+
import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
13
14
|
import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
14
15
|
import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
|
|
15
16
|
import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
|
|
@@ -68,12 +69,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
|
|
|
68
69
|
const claimed = [...new Set(claimedChangedFiles)].sort();
|
|
69
70
|
const actual = [...new Set(normalizedActual)].sort();
|
|
70
71
|
if (hasFixedDisposition && actual.length === 0) {
|
|
71
|
-
throw
|
|
72
|
+
throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
|
|
72
73
|
}
|
|
73
74
|
if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
|
|
74
|
-
|
|
75
|
+
const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
|
|
76
|
+
throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
|
|
75
77
|
}
|
|
76
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
|
|
81
|
+
* published commit; otherwise the thread would be resolved without its fix. That covers
|
|
82
|
+
* runtime output Forge unstaged and untracked or git-ignored files it never stages.
|
|
83
|
+
*/
|
|
84
|
+
async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
|
|
85
|
+
const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
|
|
86
|
+
`${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
|
|
87
|
+
finding.path ? normalizeChangedFilePath(finding.path) : "",
|
|
88
|
+
]));
|
|
89
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
90
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
91
|
+
const fixed = dispositions.flatMap(value => {
|
|
92
|
+
const record = value;
|
|
93
|
+
if (record.disposition !== "fixed")
|
|
94
|
+
return [];
|
|
95
|
+
const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
|
|
96
|
+
const findingPath = findingPaths.get(identity);
|
|
97
|
+
return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
|
|
98
|
+
});
|
|
99
|
+
if (fixed.length === 0)
|
|
100
|
+
return;
|
|
101
|
+
const unpublished = new Set([
|
|
102
|
+
...changeSet.excluded.map(normalizeChangedFilePath),
|
|
103
|
+
...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
|
|
104
|
+
]);
|
|
105
|
+
const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
|
|
106
|
+
if (dropped.length > 0) {
|
|
107
|
+
throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function commentRepairChangedFilesMismatch(message) {
|
|
111
|
+
return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
|
|
112
|
+
}
|
|
113
|
+
function formatChangedFilesDelta(missing, unexpected) {
|
|
114
|
+
const parts = [
|
|
115
|
+
missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
|
|
116
|
+
unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
|
|
117
|
+
].filter(Boolean);
|
|
118
|
+
return parts.length > 0 ? ` (${parts.join("; ")})` : "";
|
|
119
|
+
}
|
|
77
120
|
async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
|
|
78
121
|
const payload = JSON.parse(artifact.verdictJson);
|
|
79
122
|
const claimedRecords = Array.isArray(payload.changed_files)
|
|
@@ -90,11 +133,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
|
|
|
90
133
|
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
91
134
|
const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
|
|
92
135
|
if (hasFixedDisposition && authoritativePaths.length === 0) {
|
|
93
|
-
throw
|
|
136
|
+
throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
|
|
94
137
|
}
|
|
95
138
|
for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
|
|
96
139
|
if (baselinePath && !authoritative.has(baselinePath)) {
|
|
97
|
-
throw
|
|
140
|
+
throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
|
|
98
141
|
}
|
|
99
142
|
}
|
|
100
143
|
payload.changed_files = authoritativePaths.map(filePath => {
|
|
@@ -429,10 +472,15 @@ class ProviderToolActivityHeartbeat {
|
|
|
429
472
|
emit;
|
|
430
473
|
intervalMs;
|
|
431
474
|
timer = null;
|
|
475
|
+
/** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
|
|
476
|
+
isToolCallInFlight = () => this.outputState.hasActiveToolCall;
|
|
432
477
|
constructor(outputState, emit, intervalMs) {
|
|
433
478
|
this.outputState = outputState;
|
|
434
479
|
this.emit = emit;
|
|
435
480
|
this.intervalMs = intervalMs;
|
|
481
|
+
// Each heartbeat watches one provider generation. Calls an earlier generation left
|
|
482
|
+
// open died with it; inheriting them would hold the new generation's timers forever.
|
|
483
|
+
this.outputState.resetActiveToolCalls();
|
|
436
484
|
}
|
|
437
485
|
async consume(line) {
|
|
438
486
|
const events = this.outputState.consume(line);
|
|
@@ -586,6 +634,7 @@ export class ProcessBackedProviderCliService {
|
|
|
586
634
|
args: command.args,
|
|
587
635
|
cwd: worktree.worktreePath,
|
|
588
636
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
637
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
589
638
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
590
639
|
}, {
|
|
591
640
|
onStarted: async () => {
|
|
@@ -596,6 +645,7 @@ export class ProcessBackedProviderCliService {
|
|
|
596
645
|
eventType: "provider_cli_started"
|
|
597
646
|
});
|
|
598
647
|
},
|
|
648
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
599
649
|
onStdoutLine: async (line) => {
|
|
600
650
|
await toolHeartbeat.consume(line);
|
|
601
651
|
}
|
|
@@ -645,7 +695,7 @@ export class ProcessBackedProviderCliService {
|
|
|
645
695
|
await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
646
696
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
|
|
647
697
|
if (!proposalArtifact) {
|
|
648
|
-
throw
|
|
698
|
+
throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
|
|
649
699
|
}
|
|
650
700
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
651
701
|
const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
|
|
@@ -668,7 +718,7 @@ export class ProcessBackedProviderCliService {
|
|
|
668
718
|
await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
669
719
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
|
|
670
720
|
if (!proposalArtifact) {
|
|
671
|
-
throw
|
|
721
|
+
throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
|
|
672
722
|
}
|
|
673
723
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
674
724
|
const draftJson = proposal["draft_json"];
|
|
@@ -755,6 +805,7 @@ export class ProcessBackedProviderCliService {
|
|
|
755
805
|
args: command.args,
|
|
756
806
|
cwd: worktree.worktreePath,
|
|
757
807
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
808
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
758
809
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
759
810
|
}, {
|
|
760
811
|
onStarted: async () => {
|
|
@@ -765,6 +816,7 @@ export class ProcessBackedProviderCliService {
|
|
|
765
816
|
eventType: "provider_cli_started"
|
|
766
817
|
});
|
|
767
818
|
},
|
|
819
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
768
820
|
onStdoutLine: async (line) => {
|
|
769
821
|
await toolHeartbeat.consume(line);
|
|
770
822
|
}
|
|
@@ -806,7 +858,7 @@ export class ProcessBackedProviderCliService {
|
|
|
806
858
|
eventType: "worktree_branch_pushed"
|
|
807
859
|
});
|
|
808
860
|
}
|
|
809
|
-
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
|
|
861
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
|
|
810
862
|
for (const artifact of completionArtifacts) {
|
|
811
863
|
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
812
864
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
@@ -893,6 +945,7 @@ export class ProcessBackedProviderCliService {
|
|
|
893
945
|
args: command.args,
|
|
894
946
|
cwd: worktree.worktreePath,
|
|
895
947
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
948
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
896
949
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
897
950
|
}, {
|
|
898
951
|
onStarted: async () => {
|
|
@@ -903,6 +956,7 @@ export class ProcessBackedProviderCliService {
|
|
|
903
956
|
eventType: "provider_cli_started"
|
|
904
957
|
});
|
|
905
958
|
},
|
|
959
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
906
960
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
907
961
|
}, context.signal);
|
|
908
962
|
}
|
|
@@ -923,7 +977,7 @@ export class ProcessBackedProviderCliService {
|
|
|
923
977
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
924
978
|
const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
|
|
925
979
|
if (!architectArtifact) {
|
|
926
|
-
throw
|
|
980
|
+
throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
|
|
927
981
|
}
|
|
928
982
|
if (!liveArchitectEvents.hasEmitted()) {
|
|
929
983
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
|
|
@@ -997,6 +1051,7 @@ export class ProcessBackedProviderCliService {
|
|
|
997
1051
|
args: command.args,
|
|
998
1052
|
cwd: worktree.worktreePath,
|
|
999
1053
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
1054
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
1000
1055
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
1001
1056
|
}, {
|
|
1002
1057
|
onStarted: async () => {
|
|
@@ -1007,6 +1062,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1007
1062
|
eventType: "provider_cli_started"
|
|
1008
1063
|
});
|
|
1009
1064
|
},
|
|
1065
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1010
1066
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
1011
1067
|
}, context.signal);
|
|
1012
1068
|
}
|
|
@@ -1026,17 +1082,19 @@ export class ProcessBackedProviderCliService {
|
|
|
1026
1082
|
eventType: "provider_cli_completed"
|
|
1027
1083
|
});
|
|
1028
1084
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
1085
|
+
const lastRun = { result };
|
|
1029
1086
|
let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1030
1087
|
if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
|
|
1031
1088
|
// A headless provider that ends its turn to "wait for a background watcher"
|
|
1032
1089
|
// exits for good. Resume the same thread instead of failing the session.
|
|
1033
|
-
qaArtifact = await this.recoverMissingQaCompletion({ context, outputState });
|
|
1090
|
+
qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
|
|
1034
1091
|
}
|
|
1035
1092
|
if (!qaArtifact) {
|
|
1036
1093
|
const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1094
|
+
if (verdictOnly) {
|
|
1095
|
+
throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
|
|
1096
|
+
}
|
|
1097
|
+
throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
|
|
1040
1098
|
}
|
|
1041
1099
|
await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
1042
1100
|
if (!liveQaEvents.hasEmitted()) {
|
|
@@ -1149,6 +1207,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1149
1207
|
args: command.args,
|
|
1150
1208
|
cwd: worktree.worktreePath,
|
|
1151
1209
|
env: providerProcessEnv(dispatch, repairEnvironment),
|
|
1210
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
1152
1211
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
1153
1212
|
}, {
|
|
1154
1213
|
onStarted: async () => {
|
|
@@ -1160,6 +1219,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1160
1219
|
});
|
|
1161
1220
|
providerStarted = true;
|
|
1162
1221
|
},
|
|
1222
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1163
1223
|
onStdoutLine: async (line) => {
|
|
1164
1224
|
await toolHeartbeat.consume(line);
|
|
1165
1225
|
}
|
|
@@ -1194,7 +1254,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1194
1254
|
if (repairChecks) {
|
|
1195
1255
|
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
|
|
1196
1256
|
if (!repairArtifact) {
|
|
1197
|
-
throw
|
|
1257
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
|
|
1198
1258
|
}
|
|
1199
1259
|
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1200
1260
|
throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
|
|
@@ -1202,16 +1262,18 @@ export class ProcessBackedProviderCliService {
|
|
|
1202
1262
|
}
|
|
1203
1263
|
if (addressComments) {
|
|
1204
1264
|
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1265
|
+
const lastRun = { result };
|
|
1205
1266
|
if (!repairArtifact) {
|
|
1206
1267
|
repairArtifact = await this.recoverMissingCommentRepairCompletion({
|
|
1207
1268
|
context,
|
|
1208
1269
|
repairEnvironment,
|
|
1209
1270
|
outputState,
|
|
1210
1271
|
preparedHeadSha,
|
|
1272
|
+
lastRun,
|
|
1211
1273
|
});
|
|
1212
1274
|
}
|
|
1213
1275
|
if (!repairArtifact) {
|
|
1214
|
-
throw
|
|
1276
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
|
|
1215
1277
|
}
|
|
1216
1278
|
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1217
1279
|
throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
|
|
@@ -1220,7 +1282,9 @@ export class ProcessBackedProviderCliService {
|
|
|
1220
1282
|
}
|
|
1221
1283
|
let commentRepairBaselineChangedFiles = null;
|
|
1222
1284
|
if (addressComments && repairArtifact) {
|
|
1223
|
-
|
|
1285
|
+
const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1286
|
+
commentRepairBaselineChangedFiles = baseline.publishable;
|
|
1287
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
|
|
1224
1288
|
assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
|
|
1225
1289
|
}
|
|
1226
1290
|
const validationProfile = repairChecks
|
|
@@ -1236,8 +1300,10 @@ export class ProcessBackedProviderCliService {
|
|
|
1236
1300
|
preparedHeadSha,
|
|
1237
1301
|
repairScope: "pull_request",
|
|
1238
1302
|
});
|
|
1239
|
-
const
|
|
1303
|
+
const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1304
|
+
const stagedChangedFiles = stagedChangeSet.publishable;
|
|
1240
1305
|
if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
|
|
1306
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
|
|
1241
1307
|
repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
|
|
1242
1308
|
}
|
|
1243
1309
|
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
|
|
@@ -1334,13 +1400,15 @@ export class ProcessBackedProviderCliService {
|
|
|
1334
1400
|
args: command.args,
|
|
1335
1401
|
cwd: worktree.worktreePath,
|
|
1336
1402
|
env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
|
|
1403
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1337
1404
|
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1338
|
-
}, { onStdoutLine: async (line) => await toolHeartbeat.consume(line) }, context.signal);
|
|
1405
|
+
}, { onStdoutLine: async (line) => await toolHeartbeat.consume(line), isToolCallInFlight: toolHeartbeat.isToolCallInFlight }, context.signal);
|
|
1339
1406
|
}
|
|
1340
1407
|
finally {
|
|
1341
1408
|
toolHeartbeat.stop();
|
|
1342
1409
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
1343
1410
|
}
|
|
1411
|
+
options.lastRun.result = result;
|
|
1344
1412
|
if (result.exitCode !== 0)
|
|
1345
1413
|
throw providerCliExitFailure(command.command, result);
|
|
1346
1414
|
const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
@@ -1438,6 +1506,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1438
1506
|
args: command.args,
|
|
1439
1507
|
cwd: worktree.worktreePath,
|
|
1440
1508
|
env: providerProcessEnv(recoveryDispatch, repairEnvironment),
|
|
1509
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1441
1510
|
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1442
1511
|
}, {
|
|
1443
1512
|
onStarted: async () => {
|
|
@@ -1449,6 +1518,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1449
1518
|
eventType: "provider_cli_started",
|
|
1450
1519
|
});
|
|
1451
1520
|
},
|
|
1521
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1452
1522
|
onStdoutLine: async (line) => {
|
|
1453
1523
|
await toolHeartbeat.consume(line);
|
|
1454
1524
|
},
|
|
@@ -1470,6 +1540,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1470
1540
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
1471
1541
|
}
|
|
1472
1542
|
}
|
|
1543
|
+
options.lastRun.result = result;
|
|
1473
1544
|
if (result.exitCode !== 0)
|
|
1474
1545
|
throw providerCliExitFailure(command.command, result);
|
|
1475
1546
|
const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
@@ -1555,6 +1626,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1555
1626
|
args: command.args,
|
|
1556
1627
|
cwd: worktree.worktreePath,
|
|
1557
1628
|
env: environment,
|
|
1629
|
+
resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
|
|
1558
1630
|
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1559
1631
|
}, {
|
|
1560
1632
|
onStarted: async () => {
|
|
@@ -1566,6 +1638,7 @@ export class ProcessBackedProviderCliService {
|
|
|
1566
1638
|
});
|
|
1567
1639
|
providerStarted = true;
|
|
1568
1640
|
},
|
|
1641
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1569
1642
|
onStdoutLine: async (line) => {
|
|
1570
1643
|
await toolHeartbeat.consume(line);
|
|
1571
1644
|
},
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True while an attempt-owned managed command (a receipt under
|
|
3
|
+
* `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
|
|
4
|
+
* Unreadable or stale receipts do not count.
|
|
5
|
+
*/
|
|
6
|
+
export declare function hasNonterminalManagedCommand(logDirectory: string | undefined, nowMs?: number): Promise<boolean>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
const nonterminalManagedCommandStatuses = new Set(["starting", "running", "waiting_for_build_slot"]);
|
|
4
|
+
// A running receipt is rewritten every 5 s. One that has not changed for a minute
|
|
5
|
+
// belongs to a command whose supervisor is gone, so it no longer holds the provider open.
|
|
6
|
+
const runningReceiptStaleMs = 60_000;
|
|
7
|
+
// Starting and queued receipts are written once. They hold the provider open for at most
|
|
8
|
+
// the command's own timeout (the managed-command maximum when absent) plus a margin.
|
|
9
|
+
const maximumManagedCommandTimeoutMs = 2 * 60 * 60_000;
|
|
10
|
+
const queuedReceiptMarginMs = 60_000;
|
|
11
|
+
/**
|
|
12
|
+
* True while an attempt-owned managed command (a receipt under
|
|
13
|
+
* `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
|
|
14
|
+
* Unreadable or stale receipts do not count.
|
|
15
|
+
*/
|
|
16
|
+
export async function hasNonterminalManagedCommand(logDirectory, nowMs = Date.now()) {
|
|
17
|
+
if (!logDirectory?.trim())
|
|
18
|
+
return false;
|
|
19
|
+
const directory = path.join(logDirectory, "managed-commands");
|
|
20
|
+
const names = await fs.readdir(directory).catch(() => []);
|
|
21
|
+
for (const name of names) {
|
|
22
|
+
if (!name.endsWith(".receipt.json"))
|
|
23
|
+
continue;
|
|
24
|
+
if (await receiptHoldsProvider(path.join(directory, name), nowMs))
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
async function receiptHoldsProvider(receiptPath, nowMs) {
|
|
30
|
+
try {
|
|
31
|
+
const [stat, content] = await Promise.all([fs.stat(receiptPath), fs.readFile(receiptPath, "utf8")]);
|
|
32
|
+
const receipt = JSON.parse(content);
|
|
33
|
+
const status = typeof receipt.status === "string" ? receipt.status : "";
|
|
34
|
+
if (!nonterminalManagedCommandStatuses.has(status))
|
|
35
|
+
return false;
|
|
36
|
+
const ageMs = nowMs - stat.mtimeMs;
|
|
37
|
+
if (status === "running")
|
|
38
|
+
return ageMs <= runningReceiptStaleMs;
|
|
39
|
+
const timeoutMs = typeof receipt.timeout_ms === "number" && Number.isFinite(receipt.timeout_ms)
|
|
40
|
+
? receipt.timeout_ms
|
|
41
|
+
: maximumManagedCommandTimeoutMs;
|
|
42
|
+
return ageMs <= timeoutMs + queuedReceiptMarginMs;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -9,6 +9,12 @@ export interface ProviderOutputState {
|
|
|
9
9
|
finalMessage: string | null;
|
|
10
10
|
/** True only while the provider has reported a tool/command start without a matching completion. */
|
|
11
11
|
readonly hasActiveToolCall: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Forgets tool calls a previous provider generation started but never completed. A
|
|
14
|
+
* generation that exits mid-call reports no completion, and the next generation must not
|
|
15
|
+
* inherit that call as still in flight.
|
|
16
|
+
*/
|
|
17
|
+
resetActiveToolCalls(): void;
|
|
12
18
|
/** Accumulated provider-reported token usage for this run, or null when none was reported. */
|
|
13
19
|
readonly usage: ProviderUsage | null;
|
|
14
20
|
consume(line: string): readonly RunnerDispatchEvent[];
|
|
@@ -43,6 +43,9 @@ class CursorStreamJsonState {
|
|
|
43
43
|
get hasActiveToolCall() {
|
|
44
44
|
return this.activeToolCallCount > 0;
|
|
45
45
|
}
|
|
46
|
+
resetActiveToolCalls() {
|
|
47
|
+
this.activeToolCallCount = 0;
|
|
48
|
+
}
|
|
46
49
|
consume(line) {
|
|
47
50
|
const event = parseJsonLine(line);
|
|
48
51
|
if (!event) {
|
|
@@ -264,6 +267,9 @@ class ClaudeStreamJsonState {
|
|
|
264
267
|
get hasActiveToolCall() {
|
|
265
268
|
return this.activeToolUses.size > 0;
|
|
266
269
|
}
|
|
270
|
+
resetActiveToolCalls() {
|
|
271
|
+
this.activeToolUses.clear();
|
|
272
|
+
}
|
|
267
273
|
consume(line) {
|
|
268
274
|
const event = parseJsonLine(line);
|
|
269
275
|
if (!event) {
|
|
@@ -544,6 +550,9 @@ class CodexJsonState {
|
|
|
544
550
|
get hasActiveToolCall() {
|
|
545
551
|
return this.activeToolCallCount > 0;
|
|
546
552
|
}
|
|
553
|
+
resetActiveToolCalls() {
|
|
554
|
+
this.activeToolCallCount = 0;
|
|
555
|
+
}
|
|
547
556
|
consume(line) {
|
|
548
557
|
const event = parseJsonLine(line);
|
|
549
558
|
if (!event) {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { GitClient } from "../shared/git/git.js";
|
|
2
|
+
import { type ProcessRunner } from "../shared/process/process.js";
|
|
3
|
+
export interface PublishableWorktreeChangeSet {
|
|
4
|
+
/** Paths staged for publication, as `git diff --cached --name-only` reports them. */
|
|
5
|
+
readonly publishable: readonly string[];
|
|
6
|
+
/** Worktree changes Forge treats as runtime output and leaves unstaged. */
|
|
7
|
+
readonly excluded: readonly string[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Decides whether a staged change is Forge runtime output rather than an author edit.
|
|
11
|
+
*
|
|
12
|
+
* `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
|
|
13
|
+
* other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
|
|
14
|
+
* that covers injected managed commands, hooks and skills. The injector never overwrites a
|
|
15
|
+
* tracked `.forge/` file and restores one that matches the managed body, so a tracked
|
|
16
|
+
* `.forge/` file that differs from HEAD is an author edit and must be published.
|
|
17
|
+
*/
|
|
18
|
+
export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
|
|
19
|
+
/** Stages every publishable worktree change in the real index and returns both sets. */
|
|
20
|
+
export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
|
|
21
|
+
/**
|
|
22
|
+
* Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
|
|
23
|
+
* touching the worktree's index, using a throwaway copy of it. Returns null when
|
|
24
|
+
* `worktreePath` is not the root of a git worktree.
|
|
25
|
+
*/
|
|
26
|
+
export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
|
|
27
|
+
/** Compares claimed `changed_files` paths with the publishable diff. */
|
|
28
|
+
export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
|
|
29
|
+
readonly missing: readonly string[];
|
|
30
|
+
readonly unexpected: readonly string[];
|
|
31
|
+
};
|
|
32
|
+
export declare function normalizeChangedFilePath(value: string): string;
|
|
33
|
+
/**
|
|
34
|
+
* In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
|
|
35
|
+
* `changed_files` differs from what Forge would publish, so the agent can correct it
|
|
36
|
+
* in the same turn instead of failing at publication.
|
|
37
|
+
*/
|
|
38
|
+
export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Returns the given paths whose worktree content differs from HEAD but is not in the
|
|
41
|
+
* publishable set: excluded runtime output, and untracked or git-ignored files that are
|
|
42
|
+
* never staged at all (for example an injected `.forge/` file in a repository that ignores
|
|
43
|
+
* `.forge/`). A review finding on such a path cannot be fixed by the published commit.
|
|
44
|
+
*/
|
|
45
|
+
export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { GitClient } from "../shared/git/git.js";
|
|
5
|
+
import { NodeProcessRunner } from "../shared/process/process.js";
|
|
6
|
+
/**
|
|
7
|
+
* Forge runtime output that is never published, whether or not the target repository
|
|
8
|
+
* tracks other `.forge/` content. Completion artifacts and evidence live here.
|
|
9
|
+
*/
|
|
10
|
+
const runtimeOnlyPathPrefixes = [".local/", ".forge/work-items/", ".forge/stories/"];
|
|
11
|
+
const resetBatchSize = 200;
|
|
12
|
+
/**
|
|
13
|
+
* Decides whether a staged change is Forge runtime output rather than an author edit.
|
|
14
|
+
*
|
|
15
|
+
* `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
|
|
16
|
+
* other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
|
|
17
|
+
* that covers injected managed commands, hooks and skills. The injector never overwrites a
|
|
18
|
+
* tracked `.forge/` file and restores one that matches the managed body, so a tracked
|
|
19
|
+
* `.forge/` file that differs from HEAD is an author edit and must be published.
|
|
20
|
+
*/
|
|
21
|
+
export function isNonPublishableWorktreeChange(relativePath, status) {
|
|
22
|
+
const normalized = relativePath.trim().replaceAll("\\", "/");
|
|
23
|
+
if (normalized === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalized.startsWith(prefix))) {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
if (normalized === ".forge" || normalized.startsWith(".forge/")) {
|
|
27
|
+
return status.trim().toUpperCase().startsWith("A");
|
|
28
|
+
}
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
/** Stages every publishable worktree change in the real index and returns both sets. */
|
|
32
|
+
export async function stagePublishableWorktreeChangeSet(git, worktreePath) {
|
|
33
|
+
await git.run(worktreePath, ["add", "-A"]);
|
|
34
|
+
const excluded = (await readStagedChanges(git, worktreePath))
|
|
35
|
+
.filter(change => isNonPublishableWorktreeChange(change.path, change.status))
|
|
36
|
+
.map(change => change.path);
|
|
37
|
+
for (let index = 0; index < excluded.length; index += resetBatchSize) {
|
|
38
|
+
const batch = excluded.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
|
|
39
|
+
await git.run(worktreePath, ["reset", "-q", "--", ...batch]);
|
|
40
|
+
}
|
|
41
|
+
const publishable = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
|
|
42
|
+
.split(/\r?\n/)
|
|
43
|
+
.map(line => line.trim())
|
|
44
|
+
.filter(Boolean);
|
|
45
|
+
return { publishable, excluded: [...new Set(excluded)].sort() };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
|
|
49
|
+
* touching the worktree's index, using a throwaway copy of it. Returns null when
|
|
50
|
+
* `worktreePath` is not the root of a git worktree.
|
|
51
|
+
*/
|
|
52
|
+
export async function readPublishableWorktreeChangeSet(worktreePath, processRunner = new NodeProcessRunner()) {
|
|
53
|
+
const resolvedWorktree = path.resolve(worktreePath);
|
|
54
|
+
const git = new GitClient(processRunner);
|
|
55
|
+
let topLevel;
|
|
56
|
+
try {
|
|
57
|
+
topLevel = (await git.run(resolvedWorktree, ["rev-parse", "--show-toplevel"])).trim();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (!topLevel || !await samePath(topLevel, resolvedWorktree)) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
const realIndex = path.resolve(resolvedWorktree, (await git.run(resolvedWorktree, ["rev-parse", "--git-path", "index"])).trim());
|
|
66
|
+
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "forge-publishable-index-"));
|
|
67
|
+
try {
|
|
68
|
+
const tempIndex = path.join(tempRoot, "index");
|
|
69
|
+
await fs.copyFile(realIndex, tempIndex).catch((error) => {
|
|
70
|
+
if (error.code !== "ENOENT")
|
|
71
|
+
throw error;
|
|
72
|
+
});
|
|
73
|
+
const tempIndexGit = new GitClient({
|
|
74
|
+
run: request => processRunner.run({
|
|
75
|
+
...request,
|
|
76
|
+
env: { ...(request.env ?? process.env), GIT_INDEX_FILE: tempIndex },
|
|
77
|
+
}),
|
|
78
|
+
});
|
|
79
|
+
return await stagePublishableWorktreeChangeSet(tempIndexGit, resolvedWorktree);
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
await fs.rm(tempRoot, { recursive: true, force: true });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Compares claimed `changed_files` paths with the publishable diff. */
|
|
86
|
+
export function diffClaimedChangedFiles(claimedPaths, publishablePaths) {
|
|
87
|
+
const claimed = new Set(claimedPaths.map(normalizeChangedFilePath).filter(Boolean));
|
|
88
|
+
const actual = new Set(publishablePaths.map(normalizeChangedFilePath).filter(Boolean));
|
|
89
|
+
return {
|
|
90
|
+
missing: [...actual].filter(filePath => !claimed.has(filePath)).sort(),
|
|
91
|
+
unexpected: [...claimed].filter(filePath => !actual.has(filePath)).sort(),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export function normalizeChangedFilePath(value) {
|
|
95
|
+
return value.trim().replaceAll("\\", "/");
|
|
96
|
+
}
|
|
97
|
+
async function readStagedChanges(git, worktreePath) {
|
|
98
|
+
const fields = (await git.run(worktreePath, ["diff", "--cached", "--name-status", "--no-renames", "-z"]))
|
|
99
|
+
.split("\0");
|
|
100
|
+
const changes = [];
|
|
101
|
+
for (let index = 0; index + 1 < fields.length; index += 2) {
|
|
102
|
+
const status = fields[index].trim();
|
|
103
|
+
const filePath = fields[index + 1];
|
|
104
|
+
if (status && filePath)
|
|
105
|
+
changes.push({ status, path: filePath });
|
|
106
|
+
}
|
|
107
|
+
return changes;
|
|
108
|
+
}
|
|
109
|
+
async function samePath(left, right) {
|
|
110
|
+
const [realLeft, realRight] = await Promise.all([
|
|
111
|
+
fs.realpath(left).catch(() => path.resolve(left)),
|
|
112
|
+
fs.realpath(right).catch(() => path.resolve(right)),
|
|
113
|
+
]);
|
|
114
|
+
return process.platform === "win32"
|
|
115
|
+
? realLeft.toLowerCase() === realRight.toLowerCase()
|
|
116
|
+
: realLeft === realRight;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
|
|
120
|
+
* `changed_files` differs from what Forge would publish, so the agent can correct it
|
|
121
|
+
* in the same turn instead of failing at publication.
|
|
122
|
+
*/
|
|
123
|
+
export async function assertClaimedChangedFilesMatchPublishableDiff(worktreePath, payload, toolName, processRunner) {
|
|
124
|
+
const changeSet = await readPublishableWorktreeChangeSet(worktreePath, processRunner);
|
|
125
|
+
if (!changeSet)
|
|
126
|
+
return;
|
|
127
|
+
const claimed = Array.isArray(payload.changed_files)
|
|
128
|
+
? payload.changed_files.map(value => String(value?.path ?? ""))
|
|
129
|
+
: [];
|
|
130
|
+
const { missing, unexpected } = diffClaimedChangedFiles(claimed, changeSet.publishable);
|
|
131
|
+
if (missing.length === 0 && unexpected.length === 0)
|
|
132
|
+
return;
|
|
133
|
+
const details = [
|
|
134
|
+
missing.length > 0 ? `Publishable changes missing from changed_files: ${missing.join(", ")}.` : "",
|
|
135
|
+
unexpected.length > 0 ? `changed_files entries that Forge will not publish: ${unexpected.join(", ")}.` : "",
|
|
136
|
+
].filter(Boolean).join(" ");
|
|
137
|
+
throw new Error(`changed_files must list exactly the files Forge will publish. ${details} `
|
|
138
|
+
+ "Forge publishes every source change, including edits to tracked .forge/ files; it never publishes "
|
|
139
|
+
+ ".local/, .forge/work-items/, .forge/stories/, or new untracked .forge/ files. "
|
|
140
|
+
+ `Correct changed_files (or the worktree) and call ${toolName} again.`);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Returns the given paths whose worktree content differs from HEAD but is not in the
|
|
144
|
+
* publishable set: excluded runtime output, and untracked or git-ignored files that are
|
|
145
|
+
* never staged at all (for example an injected `.forge/` file in a repository that ignores
|
|
146
|
+
* `.forge/`). A review finding on such a path cannot be fixed by the published commit.
|
|
147
|
+
*/
|
|
148
|
+
export async function findUnpublishedWorktreePaths(git, worktreePath, paths, publishablePaths) {
|
|
149
|
+
const candidates = [...new Set(paths.map(normalizeChangedFilePath).filter(Boolean))];
|
|
150
|
+
if (candidates.length === 0)
|
|
151
|
+
return [];
|
|
152
|
+
const publishable = new Set(publishablePaths.map(normalizeChangedFilePath));
|
|
153
|
+
const unpublished = new Set();
|
|
154
|
+
for (let index = 0; index < candidates.length; index += resetBatchSize) {
|
|
155
|
+
const batch = candidates.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
|
|
156
|
+
const output = await git.run(worktreePath, [
|
|
157
|
+
// `traditional` with `--untracked-files=all` lists each file inside an ignored directory.
|
|
158
|
+
"status", "--porcelain=v1", "-z", "--no-renames", "--ignored=traditional", "--untracked-files=all", "--", ...batch,
|
|
159
|
+
]);
|
|
160
|
+
for (const entry of output.split("\0")) {
|
|
161
|
+
if (entry.length < 4)
|
|
162
|
+
continue;
|
|
163
|
+
const reported = normalizeChangedFilePath(entry.slice(3));
|
|
164
|
+
if (!reported)
|
|
165
|
+
continue;
|
|
166
|
+
// A collapsed directory entry ("dir/") covers every candidate beneath it.
|
|
167
|
+
const matches = reported.endsWith("/")
|
|
168
|
+
? candidates.filter(candidate => candidate.startsWith(reported))
|
|
169
|
+
: [reported];
|
|
170
|
+
for (const filePath of matches) {
|
|
171
|
+
if (!publishable.has(filePath))
|
|
172
|
+
unpublished.add(filePath);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return [...unpublished].sort();
|
|
177
|
+
}
|
|
@@ -481,6 +481,9 @@ function unvalidatedFailureFactsForCode(code, source) {
|
|
|
481
481
|
if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
|
|
482
482
|
return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
|
|
483
483
|
}
|
|
484
|
+
if (code === "comment_repair_changed_files_mismatch") {
|
|
485
|
+
return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
|
|
486
|
+
}
|
|
484
487
|
if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
|
|
485
488
|
return facts(code, "transport", "prepare", source, "retryable", "retry_dispatch");
|
|
486
489
|
}
|
|
@@ -519,6 +522,12 @@ function unvalidatedFailureFactsForCode(code, source) {
|
|
|
519
522
|
if (code === "provider_capacity_unavailable") {
|
|
520
523
|
return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
|
|
521
524
|
}
|
|
525
|
+
if (code === "provider_completion_tool_missing") {
|
|
526
|
+
return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
|
|
527
|
+
}
|
|
528
|
+
if (code === "provider_terminated_at_turn_ceiling") {
|
|
529
|
+
return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
|
|
530
|
+
}
|
|
522
531
|
if (code === "provider_context_window_exhausted") {
|
|
523
532
|
return facts(code, "provider", "agent", source, "retryable", "retry_dispatch");
|
|
524
533
|
}
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const forgeBridgeVersion = "0.1.4-dev.
|
|
1
|
+
export declare const forgeBridgeVersion = "0.1.4-dev.a690038a6849";
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const forgeBridgeVersion = "0.1.4-dev.
|
|
1
|
+
export const forgeBridgeVersion = "0.1.4-dev.a690038a6849";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loucompanion/forge-bridge",
|
|
3
|
-
"version": "0.1.4-dev.
|
|
3
|
+
"version": "0.1.4-dev.a690038a6849",
|
|
4
4
|
"description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|