@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0f07274d438b
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/README.md +183 -4
- package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
- package/dist/bridge/bridge-chat-giphy-look.js +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
- package/dist/bridge/bridge-chat-provider-command.js +230 -0
- package/dist/bridge/bridge-chat.types.d.ts +20 -0
- package/dist/bridge/bridge-chat.types.js +28 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +15 -0
- package/dist/bridge/bridge-state-io.js +68 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +102 -14
- package/dist/bridge/bridge.service.js +499 -471
- package/dist/bridge/bridge.types.d.ts +37 -0
- package/dist/bridge/bridge.types.js +2 -1
- package/dist/bridge/default-session-service.d.ts +13 -0
- package/dist/bridge/default-session-service.js +22 -0
- package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
- package/dist/bridge/dispatch-offer-policy.js +58 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +31 -1
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/bridge/windows-bash-resolution.d.ts +31 -0
- package/dist/bridge/windows-bash-resolution.js +153 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -0
- package/dist/cleanup/forge-owned-paths.d.ts +11 -0
- package/dist/cleanup/forge-owned-paths.js +62 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +75 -13
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +161 -228
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +18 -1
- package/dist/cli/local-config.js +67 -5
- package/dist/cli/provider-cli-advertising.d.ts +24 -0
- package/dist/cli/provider-cli-advertising.js +88 -0
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-load-admission.d.ts +72 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-capacity.d.ts +198 -0
- package/dist/runtime/host-load-capacity.js +353 -0
- package/dist/runtime/host-load-child-environment.d.ts +40 -0
- package/dist/runtime/host-load-child-environment.js +110 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +82 -0
- package/dist/runtime/host-load-governor-config.js +104 -0
- package/dist/runtime/host-load-governor.d.ts +273 -0
- package/dist/runtime/host-load-governor.js +831 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
- package/dist/runtime/host-load-live-test-slots.js +193 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +92 -2
- package/dist/runtime/host-load-sampler.js +166 -8
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +107 -0
- package/dist/runtime/host-load-step-run.js +158 -0
- package/dist/runtime/host-load-test-slot.d.ts +46 -0
- package/dist/runtime/host-load-test-slot.js +100 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +15 -0
- package/dist/runtime/host-runtime-contract.js +39 -6
- package/dist/runtime/host-runtime-lease.d.ts +101 -6
- package/dist/runtime/host-runtime-lease.js +408 -294
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +101 -2
- package/dist/runtime/host-runtime-promotion.js +355 -14
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
- package/dist/runtime/prepared-runtime-identity.js +130 -9
- package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
- package/dist/runtime/prepared-runtime-readiness.js +89 -18
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.d.ts +11 -3
- package/dist/sandbox/runtime.js +53 -20
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox-input.d.ts +22 -0
- package/dist/sandbox/sandbox-input.js +49 -0
- package/dist/sandbox/workspace.service.js +15 -2
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -7
- package/dist/session/managed-attempt-tools.js +204 -141
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +7 -0
- package/dist/session/managed-build-receipt.js +11 -3
- package/dist/session/managed-command-environment.d.ts +8 -0
- package/dist/session/managed-command-environment.js +28 -0
- package/dist/session/managed-command-host-load.d.ts +52 -0
- package/dist/session/managed-command-host-load.js +87 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
- package/dist/session/phase-completion.artifact-bundle.js +167 -0
- package/dist/session/phase-completion.artifacts.d.ts +9 -17
- package/dist/session/phase-completion.artifacts.js +158 -190
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +31 -2
- package/dist/session/phase-completion.helpers.js +18 -65
- package/dist/session/phase-completion.js +19 -32
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +195 -0
- package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
- package/dist/session/phase-completion.phase-aliases.js +43 -0
- package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
- package/dist/session/phase-completion.pr-review-schema.js +75 -0
- package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
- package/dist/session/phase-completion.pr-review-validation.js +212 -0
- package/dist/session/phase-completion.pr-review.d.ts +36 -0
- package/dist/session/phase-completion.pr-review.js +294 -0
- package/dist/session/phase-completion.prompts.d.ts +1 -1
- package/dist/session/phase-completion.prompts.js +20 -1
- package/dist/session/phase-completion.runtime.d.ts +13 -12
- package/dist/session/phase-completion.runtime.js +113 -214
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +219 -232
- package/dist/session/phase-completion.validation.d.ts +3 -3
- package/dist/session/phase-completion.validation.js +58 -94
- package/dist/session/pr-review-diff-base.d.ts +18 -0
- package/dist/session/pr-review-diff-base.js +44 -0
- package/dist/session/pr-review-placement.d.ts +50 -0
- package/dist/session/pr-review-placement.js +91 -0
- package/dist/session/pre-publication-change-set.d.ts +62 -0
- package/dist/session/pre-publication-change-set.js +166 -0
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +112 -0
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +32 -19
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +39 -22
- package/dist/session/pre-publication-validation.js +241 -207
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
- package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
- package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
- package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
- package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
- package/dist/session/provider-cli/pr-review-prompt.js +119 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +281 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
- package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +41 -432
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -3
- package/dist/session/provider-cli/provider-cli.prompts.js +183 -90
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +43 -1
- package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
- package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +18 -18
- package/dist/session/provider-cli/provider-cli.service.js +127 -317
- package/dist/session/provider-cli/provider-cli.types.d.ts +35 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +279 -0
- package/dist/session/session-host-project.d.ts +22 -0
- package/dist/session/session-host-project.js +98 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.parse-helpers.d.ts +10 -0
- package/dist/session/session.parse-helpers.js +84 -0
- package/dist/session/session.runtime-refresh.d.ts +46 -0
- package/dist/session/session.runtime-refresh.js +116 -0
- package/dist/session/session.service.d.ts +16 -2
- package/dist/session/session.service.js +208 -155
- package/dist/session/session.types.d.ts +8 -0
- package/dist/session/session.types.js +13 -83
- package/dist/session/session.types.pr-review.d.ts +48 -0
- package/dist/session/session.types.pr-review.js +51 -0
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.d.ts +2 -0
- package/dist/shared/provider-capabilities.js +23 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.js +24 -0
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +58 -0
- package/dist/worktree/wip-git.js +182 -0
- package/dist/worktree/wip-refs.d.ts +85 -0
- package/dist/worktree/wip-refs.js +169 -0
- package/dist/worktree/wip-restore.d.ts +51 -0
- package/dist/worktree/wip-restore.js +324 -0
- package/dist/worktree/wip-snapshot.d.ts +53 -0
- package/dist/worktree/wip-snapshot.js +270 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +35 -0
- package/dist/worktree/worktree-origin-sync.js +128 -0
- package/dist/worktree/worktree-wip-events.d.ts +20 -0
- package/dist/worktree/worktree-wip-events.js +148 -0
- package/dist/worktree/worktree-wip.d.ts +57 -0
- package/dist/worktree/worktree-wip.js +200 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +58 -5
- package/dist/worktree/worktree.service.js +237 -161
- package/dist/worktree/worktree.types.d.ts +54 -0
- package/package.json +2 -2
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { baseTrackedForgePaths, gitPath, hasPartialRestoreMarker, isWipExcludedPath, makeWipTempDir, readOptionalFile, readReapplyConflictRecord, splitNul, WipGit, } from "./wip-git.js";
|
|
4
|
+
import { formatWipCommitMessage, issuedWipAttempt, WipPreservationError, wipMetadataSchema, wipRefId, wipRefName, wipSnapshotMaxBytes, } from "./wip-refs.js";
|
|
5
|
+
const mergeMessageLimit = 16 * 1024;
|
|
6
|
+
// Snapshots this process already pushed, keyed by worktree: a guard that finds the same state
|
|
7
|
+
// (for example the release right after a failed session's snapshot) does not push it twice. An
|
|
8
|
+
// entry is reused only for the same branch, only when it is at least as restorable as the request
|
|
9
|
+
// asks for, and only while its ref still points at it (wip-snapshot cache checks below).
|
|
10
|
+
const savedSnapshots = new Map();
|
|
11
|
+
/**
|
|
12
|
+
* Saves the worktree's uncommitted work to a WIP ref. Returns `clean` (and pushes nothing) when
|
|
13
|
+
* there is nothing to save. Throws {@link WipPreservationError} when the work could not be saved,
|
|
14
|
+
* including when it is over the size cap: the caller must then not destroy the worktree.
|
|
15
|
+
*/
|
|
16
|
+
export async function preserveWorktreeWip(requested) {
|
|
17
|
+
const baseGit = new WipGit(requested.processRunner);
|
|
18
|
+
const git = requested.orphan
|
|
19
|
+
? baseGit.with({ GIT_DIR: await commonGitDir(baseGit, requested.orphan.repoPath), GIT_WORK_TREE: requested.worktreePath })
|
|
20
|
+
: baseGit;
|
|
21
|
+
// A half-applied restore is saved like any other state, but never for a later pass to apply.
|
|
22
|
+
const degraded = requested.autoRestore && !requested.orphan && await hasPartialRestoreMarker(git, requested.worktreePath);
|
|
23
|
+
const request = degraded ? { ...requested, autoRestore: false } : requested;
|
|
24
|
+
const repoPath = request.orphan?.repoPath ?? request.worktreePath;
|
|
25
|
+
const tempDir = await makeWipTempDir();
|
|
26
|
+
try {
|
|
27
|
+
const capture = await captureWorktree(request, { git, cwd: request.worktreePath, repoPath, tempDir })
|
|
28
|
+
.catch(error => { throw asPreservationError(error, "wip_snapshot_failed"); });
|
|
29
|
+
if (!capture)
|
|
30
|
+
return { status: "clean" };
|
|
31
|
+
const fingerprint = captureFingerprint(capture);
|
|
32
|
+
const cached = savedSnapshots.get(snapshotKey(request.worktreePath));
|
|
33
|
+
if (cached && await cachedSnapshotServes(baseGit, repoPath, cached, fingerprint, request)) {
|
|
34
|
+
const { fingerprint: _fingerprint, branchName: _branch, autoRestore: _autoRestore, ...saved } = cached;
|
|
35
|
+
return { ...saved, status: "already_saved" };
|
|
36
|
+
}
|
|
37
|
+
const commitSha = await writeSnapshotCommits(request, capture, { git, cwd: request.worktreePath, repoPath, tempDir })
|
|
38
|
+
.catch(error => { throw asPreservationError(error, "wip_snapshot_failed"); });
|
|
39
|
+
const published = await publishSnapshot(baseGit, repoPath, request, commitSha);
|
|
40
|
+
const result = {
|
|
41
|
+
status: "saved",
|
|
42
|
+
...published,
|
|
43
|
+
commitSha,
|
|
44
|
+
baseHead: capture.base,
|
|
45
|
+
changedPaths: capture.changedPaths,
|
|
46
|
+
bytes: capture.bytes,
|
|
47
|
+
};
|
|
48
|
+
savedSnapshots.set(snapshotKey(request.worktreePath), {
|
|
49
|
+
...result, fingerprint, branchName: request.branchName, autoRestore: request.autoRestore,
|
|
50
|
+
});
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Forgets what this process pushed for a worktree, e.g. once the worktree is gone. */
|
|
58
|
+
export function forgetPreservedWip(worktreePath) {
|
|
59
|
+
savedSnapshots.delete(snapshotKey(worktreePath));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Forgets every snapshot this process pushed to `ref`, before that ref is deleted: a later guard
|
|
63
|
+
* that finds the same state must push it again rather than report it saved in a ref that is gone.
|
|
64
|
+
*/
|
|
65
|
+
export function forgetPreservedWipRef(ref) {
|
|
66
|
+
for (const [key, saved] of savedSnapshots) {
|
|
67
|
+
if (saved.ref === ref)
|
|
68
|
+
savedSnapshots.delete(key);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function captureWorktree(request, context) {
|
|
72
|
+
const { git, cwd } = context;
|
|
73
|
+
const base = (await git.run(cwd, ["rev-parse", "--verify", `${request.orphan?.baseRef ?? "HEAD"}^{commit}`])).trim();
|
|
74
|
+
const baseTree = (await git.run(cwd, ["rev-parse", `${base}^{tree}`])).trim();
|
|
75
|
+
const merge = request.orphan ? null : await readMergeState(git, cwd);
|
|
76
|
+
const unmerged = request.orphan ? [] : splitNul(await git.run(cwd, ["ls-files", "-u", "-z"])).map(parseUnmergedEntry);
|
|
77
|
+
const reapplyConflicts = request.orphan ? [] : await readReapplyConflictRecord(git, cwd);
|
|
78
|
+
const forgePaths = await baseTrackedForgePaths(git, cwd, base);
|
|
79
|
+
const excluded = (filePath) => isWipExcludedPath(filePath, forgePaths);
|
|
80
|
+
const worktreeIndex = path.join(context.tempDir, "worktree.index");
|
|
81
|
+
await seedIndex(context, request, base, worktreeIndex);
|
|
82
|
+
const indexGit = git.with({ GIT_INDEX_FILE: worktreeIndex });
|
|
83
|
+
const bytes = await measureChanges(indexGit, cwd, base, excluded, request.maxBytes ?? wipSnapshotMaxBytes());
|
|
84
|
+
const stagedIndex = path.join(context.tempDir, "staged.index");
|
|
85
|
+
await copyIndex(worktreeIndex, stagedIndex);
|
|
86
|
+
const indexTree = request.orphan
|
|
87
|
+
? baseTree
|
|
88
|
+
: await writeStagedTree(git.with({ GIT_INDEX_FILE: stagedIndex }), cwd, base, unmerged, excluded);
|
|
89
|
+
await indexGit.run(cwd, ["add", "-A"]);
|
|
90
|
+
const changed = await resetExcluded(indexGit, cwd, base, excluded);
|
|
91
|
+
const worktreeTree = (await indexGit.run(cwd, ["write-tree"])).trim();
|
|
92
|
+
if (worktreeTree === baseTree && indexTree === baseTree && !merge && unmerged.length === 0)
|
|
93
|
+
return null;
|
|
94
|
+
return { base, worktreeTree, indexTree, merge, unmerged, reapplyConflicts, changedPaths: changed.length, bytes };
|
|
95
|
+
}
|
|
96
|
+
/** A copy of the worktree's real index; the base tree when it has none or the checkout is orphaned. */
|
|
97
|
+
async function seedIndex(context, request, base, target) {
|
|
98
|
+
if (!request.orphan) {
|
|
99
|
+
const realIndex = await gitPath(context.git, context.cwd, "index");
|
|
100
|
+
const copied = await copyIndex(realIndex, target).then(() => true, (error) => {
|
|
101
|
+
if (error.code === "ENOENT")
|
|
102
|
+
return false;
|
|
103
|
+
throw error;
|
|
104
|
+
});
|
|
105
|
+
if (copied)
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
await context.git.with({ GIT_INDEX_FILE: target }).run(context.cwd, ["read-tree", base]);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Copies an index file with its modification time. Git treats an entry whose file changed in the
|
|
112
|
+
* same second the index was written as "racily clean" and compares its content; a copy stamped
|
|
113
|
+
* with a later time would hide such a change behind matching stat data (same size, same second).
|
|
114
|
+
*/
|
|
115
|
+
async function copyIndex(source, target) {
|
|
116
|
+
await fs.copyFile(source, target);
|
|
117
|
+
const stat = await fs.stat(source);
|
|
118
|
+
await fs.utimes(target, stat.atime, stat.mtime);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Sums the size of every changed file that would be saved and refuses a snapshot over the cap,
|
|
122
|
+
* before any of it is hashed into the object store.
|
|
123
|
+
*/
|
|
124
|
+
async function measureChanges(git, cwd, base, excluded, maxBytes) {
|
|
125
|
+
const [untracked, modified, staged] = await Promise.all([
|
|
126
|
+
git.run(cwd, ["ls-files", "-o", "--exclude-standard", "-z"]),
|
|
127
|
+
git.run(cwd, ["diff", "--name-only", "--no-renames", "-z"]),
|
|
128
|
+
git.run(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", base]),
|
|
129
|
+
]);
|
|
130
|
+
const paths = [...new Set([...splitNul(untracked), ...splitNul(modified), ...splitNul(staged)])]
|
|
131
|
+
.filter(filePath => !excluded(filePath));
|
|
132
|
+
const sizes = [];
|
|
133
|
+
for (const filePath of paths) {
|
|
134
|
+
const stat = await fs.lstat(path.join(cwd, filePath)).catch(() => null);
|
|
135
|
+
if (stat?.isFile())
|
|
136
|
+
sizes.push({ path: filePath, bytes: stat.size });
|
|
137
|
+
}
|
|
138
|
+
const total = sizes.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
139
|
+
if (total > maxBytes) {
|
|
140
|
+
const largest = sizes.sort((left, right) => right.bytes - left.bytes).slice(0, 5)
|
|
141
|
+
.map(entry => `${entry.path} (${entry.bytes} bytes)`).join(", ");
|
|
142
|
+
throw new WipPreservationError("wip_snapshot_too_large", `uncommitted work in ${cwd} is ${total} bytes across ${sizes.length} file(s), over the ${maxBytes}-byte WIP snapshot cap `
|
|
143
|
+
+ `(${"FORGE_WIP_SNAPSHOT_MAX_BYTES"}); largest: ${largest}. Nothing was saved, so the worktree is kept as it is.`);
|
|
144
|
+
}
|
|
145
|
+
return total;
|
|
146
|
+
}
|
|
147
|
+
/** The staged state: the real index with unresolved conflicts and runtime output put back to the base. */
|
|
148
|
+
async function writeStagedTree(git, cwd, base, unmerged, excluded) {
|
|
149
|
+
const conflicted = [...new Set(unmerged.map(entry => entry.path))];
|
|
150
|
+
await git.runForPaths(cwd, ["reset", "-q", base], conflicted);
|
|
151
|
+
await resetExcluded(git, cwd, base, excluded);
|
|
152
|
+
return (await git.run(cwd, ["write-tree"])).trim();
|
|
153
|
+
}
|
|
154
|
+
/** Puts excluded paths back to the base in this index and returns the paths that still differ. */
|
|
155
|
+
async function resetExcluded(git, cwd, base, excluded) {
|
|
156
|
+
const listChanged = async () => splitNul(await git.run(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", base]));
|
|
157
|
+
const changed = await listChanged();
|
|
158
|
+
const toReset = changed.filter(excluded);
|
|
159
|
+
if (toReset.length === 0)
|
|
160
|
+
return changed;
|
|
161
|
+
await git.runForPaths(cwd, ["reset", "-q", base], toReset);
|
|
162
|
+
return await listChanged();
|
|
163
|
+
}
|
|
164
|
+
async function readMergeState(git, cwd) {
|
|
165
|
+
const head = (await git.tryRun(cwd, ["rev-parse", "-q", "--verify", "MERGE_HEAD^{commit}"]))?.trim();
|
|
166
|
+
if (!head)
|
|
167
|
+
return null;
|
|
168
|
+
const message = await readOptionalFile(await gitPath(git, cwd, "MERGE_MSG"));
|
|
169
|
+
const mode = await readOptionalFile(await gitPath(git, cwd, "MERGE_MODE"));
|
|
170
|
+
return {
|
|
171
|
+
head,
|
|
172
|
+
message: message === null ? null : message.slice(0, mergeMessageLimit),
|
|
173
|
+
mode: mode?.trim() || null,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function parseUnmergedEntry(record) {
|
|
177
|
+
const tab = record.indexOf("\t");
|
|
178
|
+
const [mode, sha, stage] = record.slice(0, tab).split(" ");
|
|
179
|
+
return { mode: mode, sha: sha, stage: Number(stage), path: record.slice(tab + 1) };
|
|
180
|
+
}
|
|
181
|
+
async function writeSnapshotCommits(request, capture, context) {
|
|
182
|
+
const { git, cwd, tempDir } = context;
|
|
183
|
+
const indexCommit = (await git.run(cwd, [
|
|
184
|
+
"commit-tree", capture.indexTree, "-p", capture.base, "-m", "forge wip index snapshot",
|
|
185
|
+
])).trim();
|
|
186
|
+
const now = (request.now ?? (() => new Date()))();
|
|
187
|
+
const metadata = {
|
|
188
|
+
schema: wipMetadataSchema,
|
|
189
|
+
branch: request.branchName,
|
|
190
|
+
baseHead: capture.base,
|
|
191
|
+
sessionId: request.sessionId?.trim() || null,
|
|
192
|
+
lane: request.lane?.trim() || null,
|
|
193
|
+
reason: request.reason,
|
|
194
|
+
attempt: issuedWipAttempt(request.attempt),
|
|
195
|
+
autoRestore: request.autoRestore,
|
|
196
|
+
createdAt: now.toISOString(),
|
|
197
|
+
createdAtMs: now.getTime(),
|
|
198
|
+
mergeHead: capture.merge?.head ?? null,
|
|
199
|
+
mergeMessage: capture.merge?.message ?? null,
|
|
200
|
+
mergeMode: capture.merge?.mode ?? null,
|
|
201
|
+
unmerged: capture.unmerged,
|
|
202
|
+
reapplyConflicts: capture.reapplyConflicts,
|
|
203
|
+
changedPaths: capture.changedPaths,
|
|
204
|
+
bytes: capture.bytes,
|
|
205
|
+
};
|
|
206
|
+
const messageFile = path.join(tempDir, "message.txt");
|
|
207
|
+
await fs.writeFile(messageFile, formatWipCommitMessage(metadata), "utf8");
|
|
208
|
+
const parents = [capture.base, indexCommit, ...(capture.merge ? [capture.merge.head] : [])]
|
|
209
|
+
.flatMap(parent => ["-p", parent]);
|
|
210
|
+
return (await git.run(cwd, ["commit-tree", capture.worktreeTree, ...parents, "-F", messageFile])).trim();
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Pushes the snapshot to origin. A repository without an origin keeps the ref locally instead,
|
|
214
|
+
* since there is nowhere else it could go and the repository itself outlives the worktree.
|
|
215
|
+
*/
|
|
216
|
+
async function publishSnapshot(git, repoPath, request, commitSha) {
|
|
217
|
+
const now = (request.now ?? (() => new Date()))();
|
|
218
|
+
const ref = wipRefName(request.branchName, wipRefId(request.reason, request.sessionId, now, issuedWipAttempt(request.attempt)));
|
|
219
|
+
const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
|
|
220
|
+
if (!origin) {
|
|
221
|
+
await git.run(repoPath, ["update-ref", ref, commitSha]);
|
|
222
|
+
return { ref, pushed: false };
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
await git.run(repoPath, ["push", "--porcelain", "origin", `${commitSha}:${ref}`]);
|
|
226
|
+
return { ref, pushed: true };
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
// A session's ref can already exist when the same session was snapshotted before (a retried
|
|
230
|
+
// dispatch); keep both rather than overwrite one.
|
|
231
|
+
const retryRef = `${ref}-${now.getTime().toString(36)}`;
|
|
232
|
+
const retried = await git.tryRun(repoPath, ["push", "--porcelain", "origin", `${commitSha}:${retryRef}`]);
|
|
233
|
+
if (retried !== null)
|
|
234
|
+
return { ref: retryRef, pushed: true };
|
|
235
|
+
throw asPreservationError(error, "wip_push_failed");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function commonGitDir(git, repoPath) {
|
|
239
|
+
const raw = (await git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
|
|
240
|
+
return path.isAbsolute(raw) ? raw : path.resolve(repoPath, raw);
|
|
241
|
+
}
|
|
242
|
+
function captureFingerprint(capture) {
|
|
243
|
+
const stages = capture.unmerged.map(entry => `${entry.stage}${entry.sha}${entry.path}`).join(",");
|
|
244
|
+
return [capture.base, capture.worktreeTree, capture.indexTree, capture.merge?.head ?? "", stages, capture.reapplyConflicts.join(",")].join(":");
|
|
245
|
+
}
|
|
246
|
+
function snapshotKey(worktreePath) {
|
|
247
|
+
const resolved = path.resolve(worktreePath);
|
|
248
|
+
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Whether a snapshot this process pushed can stand in for the one requested: the same state of the
|
|
252
|
+
* same branch, restorable whenever the request must be, and still at its ref (it may have been
|
|
253
|
+
* retired, or deleted on origin by the server's cleanup). A ref that can't be confirmed is pushed again.
|
|
254
|
+
*/
|
|
255
|
+
async function cachedSnapshotServes(git, repoPath, cached, fingerprint, request) {
|
|
256
|
+
if (cached.fingerprint !== fingerprint || cached.branchName !== request.branchName)
|
|
257
|
+
return false;
|
|
258
|
+
if (request.autoRestore && !cached.autoRestore)
|
|
259
|
+
return false;
|
|
260
|
+
const listed = cached.pushed
|
|
261
|
+
? await git.tryRun(repoPath, ["ls-remote", "--refs", "origin", cached.ref])
|
|
262
|
+
: await git.tryRun(repoPath, ["rev-parse", "-q", "--verify", `${cached.ref}^{commit}`]);
|
|
263
|
+
return (listed?.trim().split(/\s+/u)[0] ?? "") === cached.commitSha;
|
|
264
|
+
}
|
|
265
|
+
function asPreservationError(error, code) {
|
|
266
|
+
if (error instanceof WipPreservationError)
|
|
267
|
+
return error;
|
|
268
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
269
|
+
return new WipPreservationError(code, message, { cause: error });
|
|
270
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { GitClient } from "../shared/git/git.js";
|
|
2
|
+
import type { WorktreePrepareRequest } from "./worktree.types.js";
|
|
3
|
+
/** Materializes the run's inputs into a prepared worktree (outside the repository lock). */
|
|
4
|
+
export declare function materializeWorktreeInputs(worktreePath: string, request: WorktreePrepareRequest, git: GitClient): Promise<{
|
|
5
|
+
readonly hydratedPriorPhaseArtifactCount: number;
|
|
6
|
+
readonly qaReworkPacketPath?: string;
|
|
7
|
+
}>;
|
|
8
|
+
export declare function clearRunArtifactRoots(worktreePath: string, request: WorktreePrepareRequest): Promise<void>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isSubPath, safeSegment } from "../shared/path/path.js";
|
|
4
|
+
import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-injector.js";
|
|
5
|
+
import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
|
|
6
|
+
import { materializeStoryQaReferences } from "./story-qa-reference-hydrator.js";
|
|
7
|
+
// What a prepared worktree is given before the provider starts, once its source is in place:
|
|
8
|
+
// the Story QA reference inputs, a clean artifact root for this run, the prior phases' artifacts,
|
|
9
|
+
// the QA rework packet and the lane's resolved artifacts.
|
|
10
|
+
/** Materializes the run's inputs into a prepared worktree (outside the repository lock). */
|
|
11
|
+
export async function materializeWorktreeInputs(worktreePath, request, git) {
|
|
12
|
+
// Reference inputs and an exact-tree local repair checkpoint must survive output cleanup.
|
|
13
|
+
await materializeStoryQaReferences(worktreePath, request, git);
|
|
14
|
+
if (!request.preserveExistingState) {
|
|
15
|
+
await clearRunArtifactRoots(worktreePath, request);
|
|
16
|
+
}
|
|
17
|
+
const hydratedPriorPhaseArtifactCount = await hydratePriorPhaseArtifacts(worktreePath, request.priorPhaseArtifacts);
|
|
18
|
+
const qaReworkPacketPath = await materializeQaReworkPacket(worktreePath, request);
|
|
19
|
+
const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
|
|
20
|
+
if (artifacts.length > 0) {
|
|
21
|
+
await injectWorktreeArtifacts(worktreePath, artifacts, await trackedForgePaths(git, worktreePath));
|
|
22
|
+
}
|
|
23
|
+
return { hydratedPriorPhaseArtifactCount, qaReworkPacketPath };
|
|
24
|
+
}
|
|
25
|
+
async function trackedForgePaths(git, worktreePath) {
|
|
26
|
+
const output = await git.run(worktreePath, ["ls-files", "-z", "--", ".forge"]);
|
|
27
|
+
return new Set(output.split("\0").filter(Boolean).map(value => value.replaceAll("\\", "/")));
|
|
28
|
+
}
|
|
29
|
+
export async function clearRunArtifactRoots(worktreePath, request) {
|
|
30
|
+
const roots = new Set();
|
|
31
|
+
roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
|
|
32
|
+
for (const artifact of request.priorPhaseArtifacts ?? []) {
|
|
33
|
+
roots.add(workItemArtifactRoot(worktreePath, artifact.workItemId));
|
|
34
|
+
}
|
|
35
|
+
const ownerType = normalizeOwnerType(request.ownerType);
|
|
36
|
+
const ownerId = request.ownerId?.trim();
|
|
37
|
+
if (ownerType && ownerId) {
|
|
38
|
+
roots.add(ownerArtifactRoot(worktreePath, ownerType, ownerId));
|
|
39
|
+
}
|
|
40
|
+
for (const root of roots) {
|
|
41
|
+
const resolvedRoot = path.resolve(root);
|
|
42
|
+
if (!isSubPath(worktreePath, resolvedRoot)) {
|
|
43
|
+
throw new Error(`Artifact root must stay under ${worktreePath}.`);
|
|
44
|
+
}
|
|
45
|
+
await ensureNoSymlinkPathSegments(worktreePath, resolvedRoot, "Artifact root must not traverse symlinked path segments.");
|
|
46
|
+
await fs.rm(resolvedRoot, { recursive: true, force: true });
|
|
47
|
+
await fs.mkdir(resolvedRoot, { recursive: true });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function materializeQaReworkPacket(worktreePath, request) {
|
|
51
|
+
const qaRework = request.qaRework;
|
|
52
|
+
if (!qaRework) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
const artifactRoot = artifactRootForRequest(worktreePath, request);
|
|
56
|
+
const packetFileName = qaReworkPacketFileName(qaRework.packetPath);
|
|
57
|
+
const packetPath = path.join(artifactRoot, packetFileName);
|
|
58
|
+
const paths = new Set([packetPath, path.join(artifactRoot, "qa-rework-packet.json")]);
|
|
59
|
+
const packetJson = qaRework.packetJson.endsWith("\n") ? qaRework.packetJson : `${qaRework.packetJson}\n`;
|
|
60
|
+
for (const target of paths) {
|
|
61
|
+
const resolvedTarget = path.resolve(target);
|
|
62
|
+
if (!isSubPath(worktreePath, resolvedTarget)) {
|
|
63
|
+
throw new Error(`QA rework packet path must stay under ${worktreePath}.`);
|
|
64
|
+
}
|
|
65
|
+
await ensureNoSymlinkPathSegments(worktreePath, path.dirname(resolvedTarget), "QA rework packet path must not traverse symlinked path segments.");
|
|
66
|
+
await fs.mkdir(path.dirname(resolvedTarget), { recursive: true });
|
|
67
|
+
await fs.writeFile(resolvedTarget, packetJson, "utf8");
|
|
68
|
+
}
|
|
69
|
+
return path.resolve(packetPath);
|
|
70
|
+
}
|
|
71
|
+
function artifactRootForRequest(worktreePath, request) {
|
|
72
|
+
const ownerType = normalizeOwnerType(request.ownerType);
|
|
73
|
+
const ownerId = request.ownerId?.trim();
|
|
74
|
+
if (ownerType && ownerId) {
|
|
75
|
+
return ownerArtifactRoot(worktreePath, ownerType, ownerId);
|
|
76
|
+
}
|
|
77
|
+
return workItemArtifactRoot(worktreePath, request.workItem.id);
|
|
78
|
+
}
|
|
79
|
+
function workItemArtifactRoot(worktreePath, workItemId) {
|
|
80
|
+
return path.join(worktreePath, ".forge", "work-items", safeSegment(workItemId, "work item id"), "artifacts");
|
|
81
|
+
}
|
|
82
|
+
function ownerArtifactRoot(worktreePath, ownerType, ownerId) {
|
|
83
|
+
return path.join(worktreePath, ".forge", ownerType === "story" ? "stories" : "work-items", safeSegment(ownerId, "owner id"), "artifacts");
|
|
84
|
+
}
|
|
85
|
+
function normalizeOwnerType(value) {
|
|
86
|
+
const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
|
|
87
|
+
if (normalized === "story") {
|
|
88
|
+
return "story";
|
|
89
|
+
}
|
|
90
|
+
if (normalized === "work_item" || normalized === "workitem" || normalized === "work item") {
|
|
91
|
+
return "work_item";
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
function qaReworkPacketFileName(packetPath) {
|
|
96
|
+
const normalized = packetPath.trim().replace(/\\/g, "/");
|
|
97
|
+
const fileName = normalized.split("/").filter(Boolean).at(-1) ?? "";
|
|
98
|
+
return /^qa-rework-packet(?:\.attempt-\d+)?\.json$/i.test(fileName)
|
|
99
|
+
? fileName
|
|
100
|
+
: "qa-rework-packet.json";
|
|
101
|
+
}
|
|
102
|
+
async function ensureNoSymlinkPathSegments(root, targetPath, errorMessage) {
|
|
103
|
+
const resolvedRoot = path.resolve(root);
|
|
104
|
+
const resolvedTarget = path.resolve(targetPath);
|
|
105
|
+
const relative = path.relative(resolvedRoot, resolvedTarget);
|
|
106
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
107
|
+
throw new Error(errorMessage);
|
|
108
|
+
}
|
|
109
|
+
let current = resolvedRoot;
|
|
110
|
+
const rootStat = await fs.lstat(current);
|
|
111
|
+
if (rootStat.isSymbolicLink()) {
|
|
112
|
+
throw new Error(errorMessage);
|
|
113
|
+
}
|
|
114
|
+
if (!relative) {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
for (const segment of relative.split(path.sep)) {
|
|
118
|
+
if (!segment) {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
current = path.join(current, segment);
|
|
122
|
+
const stat = await fs.lstat(current).catch((error) => {
|
|
123
|
+
if (error.code === "ENOENT")
|
|
124
|
+
return null;
|
|
125
|
+
throw error;
|
|
126
|
+
});
|
|
127
|
+
if (!stat) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (stat.isSymbolicLink()) {
|
|
131
|
+
throw new Error(errorMessage);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { GitClient } from "../shared/git/git.js";
|
|
2
|
+
import type { RunnerDispatchEvent } from "../session/session.types.js";
|
|
3
|
+
import type { OriginSync, WorktreeHandle } from "./worktree.types.js";
|
|
4
|
+
export type BridgeLog = (message: string) => void;
|
|
5
|
+
export declare const writeBridgeLog: BridgeLog;
|
|
6
|
+
export interface ReusedWorktreeSyncRequest {
|
|
7
|
+
readonly git: GitClient;
|
|
8
|
+
readonly worktreePath: string;
|
|
9
|
+
readonly branchName: string;
|
|
10
|
+
readonly sessionId?: string | null;
|
|
11
|
+
readonly lane: string;
|
|
12
|
+
readonly wipAttempt?: number | null;
|
|
13
|
+
readonly log: BridgeLog;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Brings a reused worktree that is only behind origin up to origin's head (see the rules above).
|
|
17
|
+
* Returns what moved, or undefined when nothing did. Throws when the worktree diverged from origin
|
|
18
|
+
* or its uncommitted work could not be saved: a failed prepare is better than a pass on stale code.
|
|
19
|
+
*/
|
|
20
|
+
export declare function syncReusedWorktreeToOrigin(request: ReusedWorktreeSyncRequest): Promise<OriginSync | undefined>;
|
|
21
|
+
/**
|
|
22
|
+
* Logs what a new worktree starts from. When a local copy of the branch is re-pointed at its own
|
|
23
|
+
* origin head (guardBranchReset has already saved any commits only it had), says so and returns
|
|
24
|
+
* the move when the local copy was only behind.
|
|
25
|
+
*/
|
|
26
|
+
export declare function describeNewWorktreeStart(git: GitClient, repoPath: string, branchName: string, startPoint: string, log: BridgeLog): Promise<OriginSync | undefined>;
|
|
27
|
+
/**
|
|
28
|
+
* After a failed `git fetch origin`: refuses to go on when origin is known to have any of
|
|
29
|
+
* `branches` (it has a remote-tracking ref for it), since the local state may then be stale.
|
|
30
|
+
*/
|
|
31
|
+
export declare function refuseStaleFallbackAfterFetchFailure(git: GitClient, repoPath: string, branches: readonly string[], fetchError: unknown, log: BridgeLog): Promise<void>;
|
|
32
|
+
type Emit = (event: RunnerDispatchEvent) => Promise<void>;
|
|
33
|
+
/** Reports what prepare did to the worktree's source and saved WIP, before the provider starts. */
|
|
34
|
+
export declare function emitWorktreePreparedEvents(worktree: WorktreeHandle, emit: Emit): Promise<void>;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { preserveWorktreeWip } from "./wip-snapshot.js";
|
|
2
|
+
import { emitWipRestoreEvent } from "./worktree-wip-events.js";
|
|
3
|
+
export const writeBridgeLog = message => {
|
|
4
|
+
process.stderr.write(`[${new Date().toISOString()}] ${message}\n`);
|
|
5
|
+
};
|
|
6
|
+
/** Compares a local commit with the remote-tracking head of `branchName`. */
|
|
7
|
+
async function compareWithOrigin(git, cwd, local, branchName) {
|
|
8
|
+
const origin = await revParse(git, cwd, `refs/remotes/origin/${branchName}^{commit}`);
|
|
9
|
+
if (!origin)
|
|
10
|
+
return { relation: "no_origin_branch", local, origin: null };
|
|
11
|
+
if (origin === local)
|
|
12
|
+
return { relation: "equal", local, origin };
|
|
13
|
+
if (await isAncestor(git, cwd, local, origin))
|
|
14
|
+
return { relation: "behind", local, origin };
|
|
15
|
+
if (await isAncestor(git, cwd, origin, local))
|
|
16
|
+
return { relation: "ahead", local, origin };
|
|
17
|
+
return { relation: "diverged", local, origin };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Brings a reused worktree that is only behind origin up to origin's head (see the rules above).
|
|
21
|
+
* Returns what moved, or undefined when nothing did. Throws when the worktree diverged from origin
|
|
22
|
+
* or its uncommitted work could not be saved: a failed prepare is better than a pass on stale code.
|
|
23
|
+
*/
|
|
24
|
+
export async function syncReusedWorktreeToOrigin(request) {
|
|
25
|
+
const { git, worktreePath, branchName, log } = request;
|
|
26
|
+
const head = await revParse(git, worktreePath, "HEAD^{commit}");
|
|
27
|
+
if (!head)
|
|
28
|
+
throw new Error(`Reused worktree ${worktreePath} has no committed HEAD on '${branchName}'.`);
|
|
29
|
+
const comparison = await compareWithOrigin(git, worktreePath, head, branchName);
|
|
30
|
+
const where = `Reused worktree ${worktreePath} on '${branchName}'`;
|
|
31
|
+
if (comparison.relation === "diverged") {
|
|
32
|
+
const message = `${where} has diverged from origin: local HEAD ${head} and origin/${branchName} ${comparison.origin} `
|
|
33
|
+
+ "each have commits the other lacks. Forge will not reset it or pick a side; reconcile the branch, then retry.";
|
|
34
|
+
log(`Worktree prepare: ${message}`);
|
|
35
|
+
throw new Error(message);
|
|
36
|
+
}
|
|
37
|
+
if (comparison.relation !== "behind" || !comparison.origin) {
|
|
38
|
+
log(`Worktree prepare: ${where} kept at ${short(head)} (${describeKept(comparison, branchName)}).`);
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
const snapshot = await preserveWorktreeWip({
|
|
42
|
+
worktreePath,
|
|
43
|
+
branchName,
|
|
44
|
+
reason: "pre_sync",
|
|
45
|
+
sessionId: request.sessionId,
|
|
46
|
+
lane: request.lane,
|
|
47
|
+
attempt: request.wipAttempt,
|
|
48
|
+
// It was based on the old head, so a later pass must never apply it on the new one by itself.
|
|
49
|
+
autoRestore: false,
|
|
50
|
+
}).catch((error) => {
|
|
51
|
+
throw new Error(`Refusing to move ${worktreePath} from ${head} to origin/${branchName} ${comparison.origin}: `
|
|
52
|
+
+ `its uncommitted work could not be saved to a WIP ref (${errorMessage(error)}).`, { cause: error });
|
|
53
|
+
});
|
|
54
|
+
await git.run(worktreePath, ["reset", "--hard", comparison.origin]);
|
|
55
|
+
await git.run(worktreePath, ["clean", "-fd"]);
|
|
56
|
+
const saved = snapshot.status === "clean" ? null : snapshot;
|
|
57
|
+
log(`Worktree prepare: ${where} was behind origin; synced from ${short(head)} to ${short(comparison.origin)}`
|
|
58
|
+
+ `${saved ? ` after saving its uncommitted work to ${saved.ref}` : " (it had no uncommitted work)"}.`);
|
|
59
|
+
return { from: head, to: comparison.origin, wipRef: saved?.ref ?? null };
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Logs what a new worktree starts from. When a local copy of the branch is re-pointed at its own
|
|
63
|
+
* origin head (guardBranchReset has already saved any commits only it had), says so and returns
|
|
64
|
+
* the move when the local copy was only behind.
|
|
65
|
+
*/
|
|
66
|
+
export async function describeNewWorktreeStart(git, repoPath, branchName, startPoint, log) {
|
|
67
|
+
const target = await revParse(git, repoPath, `${startPoint}^{commit}`);
|
|
68
|
+
const local = await revParse(git, repoPath, `refs/heads/${branchName}^{commit}`);
|
|
69
|
+
const ownOrigin = startPoint === `refs/remotes/origin/${branchName}`;
|
|
70
|
+
const comparison = local && ownOrigin ? await compareWithOrigin(git, repoPath, local, branchName) : null;
|
|
71
|
+
const previous = local && local !== target ? `; the local branch was at ${short(local)}${comparison ? ` (${comparison.relation})` : ""}` : "";
|
|
72
|
+
log(`Worktree prepare: creating a worktree on '${branchName}' at ${startPoint} ${short(target)}${previous}.`);
|
|
73
|
+
return comparison?.relation === "behind" && comparison.origin
|
|
74
|
+
? { from: comparison.local, to: comparison.origin, wipRef: null }
|
|
75
|
+
: undefined;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* After a failed `git fetch origin`: refuses to go on when origin is known to have any of
|
|
79
|
+
* `branches` (it has a remote-tracking ref for it), since the local state may then be stale.
|
|
80
|
+
*/
|
|
81
|
+
export async function refuseStaleFallbackAfterFetchFailure(git, repoPath, branches, fetchError, log) {
|
|
82
|
+
for (const branch of new Set(branches)) {
|
|
83
|
+
const known = await revParse(git, repoPath, `refs/remotes/origin/${branch}^{commit}`);
|
|
84
|
+
if (!known)
|
|
85
|
+
continue;
|
|
86
|
+
const message = `Could not fetch origin (${errorMessage(fetchError)}), so '${branch}' may be stale here `
|
|
87
|
+
+ `(origin last seen at ${short(known)}). Refusing to prepare from possibly stale state; retry once origin is reachable.`;
|
|
88
|
+
log(`Worktree prepare: ${message}`);
|
|
89
|
+
throw new Error(message, { cause: fetchError });
|
|
90
|
+
}
|
|
91
|
+
log(`Worktree prepare: could not fetch origin (${errorMessage(fetchError)}); no remote-tracking ref exists for `
|
|
92
|
+
+ `${[...new Set(branches)].join(" or ")}, so the local branch is used.`);
|
|
93
|
+
}
|
|
94
|
+
/** Reports what prepare did to the worktree's source and saved WIP, before the provider starts. */
|
|
95
|
+
export async function emitWorktreePreparedEvents(worktree, emit) {
|
|
96
|
+
const sync = worktree.originSync;
|
|
97
|
+
if (sync) {
|
|
98
|
+
await emit({
|
|
99
|
+
role: "runner",
|
|
100
|
+
kind: "checkpoint",
|
|
101
|
+
content: `Synced ${worktree.branchName} from ${short(sync.from)} to origin's head ${short(sync.to)} before the provider started`
|
|
102
|
+
+ `${sync.wipRef ? `; its uncommitted work was saved to ${sync.wipRef} first.` : "."}`,
|
|
103
|
+
eventType: "worktree_synced_to_origin",
|
|
104
|
+
data: JSON.stringify({ ...sync, branchName: worktree.branchName, worktreePath: worktree.worktreePath }),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
await emitWipRestoreEvent(worktree, emit);
|
|
108
|
+
}
|
|
109
|
+
function describeKept(comparison, branchName) {
|
|
110
|
+
switch (comparison.relation) {
|
|
111
|
+
case "no_origin_branch": return `origin has no '${branchName}'`;
|
|
112
|
+
case "equal": return "already at origin's head";
|
|
113
|
+
default: return `ahead of origin/${branchName} ${short(comparison.origin)}; its unpublished commits are kept`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function revParse(git, cwd, rev) {
|
|
117
|
+
const value = (await git.run(cwd, ["rev-parse", "-q", "--verify", rev]).catch(() => "")).trim();
|
|
118
|
+
return value.length > 0 ? value : null;
|
|
119
|
+
}
|
|
120
|
+
async function isAncestor(git, cwd, ancestor, descendant) {
|
|
121
|
+
return await git.run(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]).then(() => true, () => false);
|
|
122
|
+
}
|
|
123
|
+
function short(sha) {
|
|
124
|
+
return sha ? sha.slice(0, 12) : "(none)";
|
|
125
|
+
}
|
|
126
|
+
function errorMessage(error) {
|
|
127
|
+
return error instanceof Error ? error.message : String(error);
|
|
128
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { RunnerDispatchEvent } from "../session/session.types.js";
|
|
2
|
+
import type { WorktreeService } from "./worktree.base.js";
|
|
3
|
+
import type { WipSessionOutcome, WorktreeHandle } from "./worktree.types.js";
|
|
4
|
+
type Emit = (event: RunnerDispatchEvent) => Promise<void>;
|
|
5
|
+
/** Reports what the prepare did with the story's saved WIP, before the provider starts. */
|
|
6
|
+
export declare function emitWipRestoreEvent(worktree: WorktreeHandle, emit: Emit): Promise<void>;
|
|
7
|
+
/** How a session ended, for the snapshot it leaves behind. */
|
|
8
|
+
export declare function sessionWipOutcome(signal: AbortSignal | undefined, events: readonly RunnerDispatchEvent[], succeeded: boolean): WipSessionOutcome;
|
|
9
|
+
/**
|
|
10
|
+
* Ends a session's use of its worktree: first saves its WIP (or retires the snapshot it started
|
|
11
|
+
* from) and reports that, then, as a separate step, releases the worktree unless the session
|
|
12
|
+
* paused or its WIP could not be saved. Nothing here throws over the session's own result or
|
|
13
|
+
* failure: a release that refuses to delete unsaved work, or that fails (a Windows process still
|
|
14
|
+
* holding a cwd in the worktree makes the rename fail), keeps the worktree on this runner and is
|
|
15
|
+
* reported as a cleanup failure.
|
|
16
|
+
*/
|
|
17
|
+
export declare function settleWorktree(worktrees: WorktreeService, worktree: WorktreeHandle, outcome: WipSessionOutcome, signal: AbortSignal | undefined, emit: Emit): Promise<void>;
|
|
18
|
+
/** The checkpoint for a project start held back until the agent resolves the re-apply conflicts. */
|
|
19
|
+
export declare function deferredProjectStartEvent(paths: readonly string[]): RunnerDispatchEvent;
|
|
20
|
+
export {};
|