@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,169 @@
|
|
|
1
|
+
// Private WIP refs: where Forge keeps uncommitted work it could otherwise lose.
|
|
2
|
+
//
|
|
3
|
+
// The bridge owns the only commit and push on a story branch, so unfinished work never goes there.
|
|
4
|
+
// Before anything could destroy uncommitted changes (a session that stops, fails, pauses or hits
|
|
5
|
+
// its repair limit; a reset, a release or a cleanup of the worktree), the bridge snapshots them into
|
|
6
|
+
// a commit and pushes it to
|
|
7
|
+
//
|
|
8
|
+
// refs/forge/wip/<owner key>/<attempt>-<session id | [session id-]reason-timestamp-nonce>
|
|
9
|
+
//
|
|
10
|
+
// <attempt> is ten zero-padded digits, so refs sort by it: the dispatch's wipAttempt, which Forge
|
|
11
|
+
// issues from a database sequence when it admits the dispatch attempt, so a later attempt on a story
|
|
12
|
+
// always has a larger one. Newest work wins: a restore takes the highest attempt first. Snapshots
|
|
13
|
+
// taken without an issued attempt (older servers, attempts admitted before it existed, cleanup and
|
|
14
|
+
// branch-reset guards) carry attempt 0.
|
|
15
|
+
//
|
|
16
|
+
// The owner key is the story's short id for a `story/<12 hex>` branch, and `b_` plus the branch
|
|
17
|
+
// name with `_` → `_u` and `/` → `_s` for any other branch (`b_task_s0123456789ab`), so it is
|
|
18
|
+
// unique per branch. The server deletes a key's refs when the pull request for that branch merges
|
|
19
|
+
// or closes (GitHubWipRefCleanup.cs).
|
|
20
|
+
//
|
|
21
|
+
// A snapshot is a commit W whose tree is the worktree (staged, unstaged and untracked files that
|
|
22
|
+
// are not ignored; never Forge runtime output). Its first parent is the HEAD it was based on, its
|
|
23
|
+
// second an index commit I whose tree is the staged state, and its third, when a merge was in
|
|
24
|
+
// progress, MERGE_HEAD. Its message carries the metadata below as JSON.
|
|
25
|
+
import { randomBytes } from "node:crypto";
|
|
26
|
+
export const wipRefRoot = "refs/forge/wip";
|
|
27
|
+
export const wipMetadataSchema = "forge.wip.v1";
|
|
28
|
+
const defaultWipSnapshotMaxBytes = 100 * 1024 * 1024;
|
|
29
|
+
const wipSnapshotMaxBytesEnv = "FORGE_WIP_SNAPSHOT_MAX_BYTES";
|
|
30
|
+
const storyBranchPattern = /^story\/([0-9a-f]{12})$/u;
|
|
31
|
+
const refSegmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
32
|
+
/**
|
|
33
|
+
* Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
|
|
34
|
+
* (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
|
|
35
|
+
* a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
|
|
36
|
+
* refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
|
|
37
|
+
* a restore writes it back; a restore that finds the worktree clean removes it.
|
|
38
|
+
*/
|
|
39
|
+
export const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
|
|
40
|
+
export function parseReapplyConflictRecord(content) {
|
|
41
|
+
return content ? [...new Set(content.split("\0").filter(Boolean))].sort() : [];
|
|
42
|
+
}
|
|
43
|
+
const conflictMarkerPattern = /^<{7}(?: |$)[\s\S]*^>{7}(?: |$)/mu;
|
|
44
|
+
/** True when the text has a Git conflict block: a `<<<<<<<` line followed later by a `>>>>>>>` line. */
|
|
45
|
+
export function hasConflictMarkerLines(text) {
|
|
46
|
+
return conflictMarkerPattern.test(text);
|
|
47
|
+
}
|
|
48
|
+
const conflictBlockPattern = /^<{7}(?: [^\n]*)?\r?\n[\s\S]*?^>{7}(?: [^\n]*)?$/gmu;
|
|
49
|
+
/**
|
|
50
|
+
* True when `text` has a conflict block (`<<<<<<<` through the next `>>>>>>>`) that `base` does not:
|
|
51
|
+
* blocks are compared by their exact text, as many times as each occurs, so a file whose base
|
|
52
|
+
* already holds a marker fixture still counts when another block is added to it.
|
|
53
|
+
*/
|
|
54
|
+
export function hasNewConflictBlocks(text, base) {
|
|
55
|
+
const remaining = new Map();
|
|
56
|
+
for (const block of base?.match(conflictBlockPattern) ?? [])
|
|
57
|
+
remaining.set(block, (remaining.get(block) ?? 0) + 1);
|
|
58
|
+
for (const block of text.match(conflictBlockPattern) ?? []) {
|
|
59
|
+
const left = remaining.get(block) ?? 0;
|
|
60
|
+
if (left === 0)
|
|
61
|
+
return true;
|
|
62
|
+
remaining.set(block, left - 1);
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
/** The attempt of a snapshot taken without a Forge-issued attempt number. */
|
|
67
|
+
export const unorderedWipAttempt = 0;
|
|
68
|
+
const maxWipAttempt = 9_999_999_999;
|
|
69
|
+
/** Snapshotting or pushing uncommitted work failed; whatever would have destroyed it must not run. */
|
|
70
|
+
export class WipPreservationError extends Error {
|
|
71
|
+
code;
|
|
72
|
+
constructor(code, message, options) {
|
|
73
|
+
super(`${code}: ${message}`, options);
|
|
74
|
+
this.code = code;
|
|
75
|
+
this.name = "WipPreservationError";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* `story/<12 hex>` → the 12 hex; any other branch → `b_` and its name with `_` written as `_u` and
|
|
80
|
+
* `/` as `_s`. The encoding is reversible and a story key never starts with `b_`, so no two branches
|
|
81
|
+
* share a key (`task/a-b` and `task-a/b` would under a plain `/` → `-`). GitHubWipRefCleanup.cs
|
|
82
|
+
* computes the same key.
|
|
83
|
+
*/
|
|
84
|
+
export function wipOwnerKey(branchName) {
|
|
85
|
+
const branch = branchName.trim().replace(/^refs\/heads\//u, "");
|
|
86
|
+
const story = storyBranchPattern.exec(branch);
|
|
87
|
+
const key = story ? story[1] : `b_${branch.replaceAll("_", "_u").replaceAll("/", "_s")}`;
|
|
88
|
+
if (!branch || !refSegmentPattern.test(key) || key.includes("..") || key.endsWith(".lock") || key.endsWith(".")) {
|
|
89
|
+
throw new WipPreservationError("wip_snapshot_failed", `branch '${branchName}' has no valid WIP ref key.`);
|
|
90
|
+
}
|
|
91
|
+
return key;
|
|
92
|
+
}
|
|
93
|
+
/** The ref namespace holding every WIP snapshot for a branch, with a trailing slash. */
|
|
94
|
+
export function wipRefPrefix(branchName) {
|
|
95
|
+
return `${wipRefRoot}/${wipOwnerKey(branchName)}/`;
|
|
96
|
+
}
|
|
97
|
+
export function wipRefName(branchName, id) {
|
|
98
|
+
if (!refSegmentPattern.test(id) || id.endsWith(".lock") || id.endsWith(".")) {
|
|
99
|
+
throw new WipPreservationError("wip_snapshot_failed", `'${id}' is not a valid WIP ref id.`);
|
|
100
|
+
}
|
|
101
|
+
return `${wipRefPrefix(branchName)}${id}`;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* `<attempt>-<session id>` for a session's own snapshot; `<attempt>-[<session id>-]<reason>-<time>-<nonce>`
|
|
105
|
+
* for a guard snapshot.
|
|
106
|
+
*/
|
|
107
|
+
export function wipRefId(reason, sessionId, now, attempt = unorderedWipAttempt) {
|
|
108
|
+
if (!Number.isSafeInteger(attempt) || attempt < 0 || attempt > maxWipAttempt) {
|
|
109
|
+
throw new WipPreservationError("wip_snapshot_failed", `${attempt} is not a valid WIP attempt number.`);
|
|
110
|
+
}
|
|
111
|
+
const prefix = `${String(attempt).padStart(10, "0")}-`;
|
|
112
|
+
const session = sessionId?.trim();
|
|
113
|
+
if (session && isSessionReason(reason))
|
|
114
|
+
return `${prefix}${session}`;
|
|
115
|
+
const owner = session ? `${session}-` : "";
|
|
116
|
+
return `${prefix}${owner}${reason.replaceAll("_", "-")}-${now.getTime().toString(36)}-${randomBytes(3).toString("hex")}`;
|
|
117
|
+
}
|
|
118
|
+
function isSessionReason(reason) {
|
|
119
|
+
return reason === "session_failed" || reason === "repair_limit"
|
|
120
|
+
|| reason === "session_paused" || reason === "session_stopped";
|
|
121
|
+
}
|
|
122
|
+
/** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
|
|
123
|
+
export function issuedWipAttempt(value) {
|
|
124
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= maxWipAttempt ? value : unorderedWipAttempt;
|
|
125
|
+
}
|
|
126
|
+
/** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
|
|
127
|
+
export function wipRefAttempt(ref) {
|
|
128
|
+
const id = ref.slice(ref.lastIndexOf("/") + 1);
|
|
129
|
+
const match = /^(\d{10})-/u.exec(id);
|
|
130
|
+
return match ? Number(match[1]) : unorderedWipAttempt;
|
|
131
|
+
}
|
|
132
|
+
/** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
|
|
133
|
+
export function wipSnapshotMaxBytes(env = process.env) {
|
|
134
|
+
const configured = Number.parseInt(env[wipSnapshotMaxBytesEnv] ?? "", 10);
|
|
135
|
+
return Number.isSafeInteger(configured) && configured > 0 ? configured : defaultWipSnapshotMaxBytes;
|
|
136
|
+
}
|
|
137
|
+
export function formatWipCommitMessage(metadata) {
|
|
138
|
+
return `forge wip snapshot (${metadata.reason}) of ${metadata.branch} at ${metadata.baseHead.slice(0, 12)}\n\n`
|
|
139
|
+
+ `${JSON.stringify(metadata)}\n`;
|
|
140
|
+
}
|
|
141
|
+
/** The metadata of a WIP commit message, or null when the message is not one. */
|
|
142
|
+
export function parseWipCommitMessage(message) {
|
|
143
|
+
const start = message.indexOf("\n\n");
|
|
144
|
+
if (start < 0)
|
|
145
|
+
return null;
|
|
146
|
+
try {
|
|
147
|
+
const parsed = JSON.parse(message.slice(start + 2).trim());
|
|
148
|
+
if (parsed.schema !== wipMetadataSchema || typeof parsed.baseHead !== "string"
|
|
149
|
+
|| typeof parsed.branch !== "string" || typeof parsed.createdAtMs !== "number") {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
...parsed,
|
|
154
|
+
unmerged: Array.isArray(parsed.unmerged) ? parsed.unmerged : [],
|
|
155
|
+
autoRestore: parsed.autoRestore === true,
|
|
156
|
+
reapplyConflicts: Array.isArray(parsed.reapplyConflicts)
|
|
157
|
+
? parsed.reapplyConflicts.filter(conflict => typeof conflict === "string")
|
|
158
|
+
: [],
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** A raw commit object's message: everything after its header block. */
|
|
166
|
+
export function commitMessageOf(rawCommit) {
|
|
167
|
+
const separator = rawCommit.indexOf("\n\n");
|
|
168
|
+
return separator < 0 ? "" : rawCommit.slice(separator + 2);
|
|
169
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { ProcessRunner } from "../shared/process/process.js";
|
|
2
|
+
export interface WipRestoreRequest {
|
|
3
|
+
readonly worktreePath: string;
|
|
4
|
+
readonly repoPath: string;
|
|
5
|
+
readonly branchName: string;
|
|
6
|
+
readonly processRunner?: ProcessRunner;
|
|
7
|
+
}
|
|
8
|
+
export type WipRestoreOutcome = {
|
|
9
|
+
readonly status: "none";
|
|
10
|
+
} | {
|
|
11
|
+
readonly status: "restored";
|
|
12
|
+
readonly ref: string;
|
|
13
|
+
readonly commitSha: string;
|
|
14
|
+
readonly baseHead: string;
|
|
15
|
+
readonly sourceSessionId: string | null;
|
|
16
|
+
readonly changedPaths: number;
|
|
17
|
+
readonly mergeInProgress: boolean;
|
|
18
|
+
/** Set when the branch had moved and the snapshot was re-applied onto its new HEAD with a 3-way merge. */
|
|
19
|
+
readonly reapplied: WipReapply | null;
|
|
20
|
+
/**
|
|
21
|
+
* Every path left for the agent to resolve with no MERGE_HEAD to show it (the worktree's re-apply
|
|
22
|
+
* conflict record): this re-apply's conflicts and any an earlier re-apply left in the snapshot.
|
|
23
|
+
*/
|
|
24
|
+
readonly reapplyConflicts: readonly string[];
|
|
25
|
+
} | {
|
|
26
|
+
readonly status: "not_restored";
|
|
27
|
+
readonly ref: string;
|
|
28
|
+
readonly commitSha: string;
|
|
29
|
+
readonly reason: "branch_moved" | "apply_failed";
|
|
30
|
+
readonly baseHead: string;
|
|
31
|
+
readonly currentHead: string;
|
|
32
|
+
readonly detail: string;
|
|
33
|
+
} | {
|
|
34
|
+
readonly status: "skipped_dirty";
|
|
35
|
+
readonly ref: string;
|
|
36
|
+
readonly commitSha: string;
|
|
37
|
+
} | {
|
|
38
|
+
readonly status: "unavailable";
|
|
39
|
+
readonly detail: string;
|
|
40
|
+
};
|
|
41
|
+
export interface WipReapply {
|
|
42
|
+
/** The HEAD the snapshot was taken on, used as the merge base. */
|
|
43
|
+
readonly snapshotBaseHead: string;
|
|
44
|
+
/** Paths the merge left unmerged, with conflict markers where Git writes them, for the agent to resolve. */
|
|
45
|
+
readonly conflictedPaths: readonly string[];
|
|
46
|
+
}
|
|
47
|
+
export declare function restoreLatestWip(request: WipRestoreRequest): Promise<WipRestoreOutcome>;
|
|
48
|
+
/** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
|
|
49
|
+
export declare function deleteWipRef(repoPath: string, ref: string, processRunner?: ProcessRunner): Promise<boolean>;
|
|
50
|
+
/** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
|
|
51
|
+
export declare function hasNoUnsavedWork(worktreePath: string, processRunner?: ProcessRunner): Promise<boolean>;
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, readOptionalFile, splitNul, WipGit, writeReapplyConflictRecord, } from "./wip-git.js";
|
|
5
|
+
import { commitMessageOf, hasConflictMarkerLines, hasNewConflictBlocks, issuedWipAttempt, parseWipCommitMessage, wipRefAttempt, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
|
|
6
|
+
export async function restoreLatestWip(request) {
|
|
7
|
+
const git = new WipGit(request.processRunner);
|
|
8
|
+
let candidates;
|
|
9
|
+
try {
|
|
10
|
+
candidates = await listWipCandidates(git, request);
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
return { status: "unavailable", detail: errorMessage(error) };
|
|
14
|
+
}
|
|
15
|
+
const newest = newestRestorable(candidates, request.branchName);
|
|
16
|
+
if (!newest)
|
|
17
|
+
return { status: "none" };
|
|
18
|
+
if (!await isCleanWorktree(git, request.worktreePath)) {
|
|
19
|
+
return { status: "skipped_dirty", ref: newest.ref, commitSha: newest.commitSha };
|
|
20
|
+
}
|
|
21
|
+
// Clean again (the reset after a failed restore): its later snapshots may be applied as usual, and
|
|
22
|
+
// no earlier re-apply's conflicts are left.
|
|
23
|
+
await fs.rm(await partialRestoreMarkerPath(git, request.worktreePath), { force: true });
|
|
24
|
+
await writeReapplyConflictRecord(git, request.worktreePath, []);
|
|
25
|
+
const currentHead = (await git.run(request.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
26
|
+
const notRestored = (reason, detail) => ({
|
|
27
|
+
status: "not_restored", ref: newest.ref, commitSha: newest.commitSha, reason,
|
|
28
|
+
baseHead: newest.metadata.baseHead, currentHead, detail,
|
|
29
|
+
});
|
|
30
|
+
let plan = null;
|
|
31
|
+
if (newest.metadata.baseHead !== currentHead) {
|
|
32
|
+
const moved = `${request.branchName} is at ${currentHead.slice(0, 12)}, but the snapshot was taken on ${newest.metadata.baseHead.slice(0, 12)}.`;
|
|
33
|
+
if (newest.metadata.mergeHead || newest.metadata.unmerged.length > 0) {
|
|
34
|
+
return notRestored("branch_moved", `${moved} It was taken during a merge, so it is not re-applied onto the moved branch.`);
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
plan = await planReapply(git, request.worktreePath, newest, currentHead);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
return notRestored("branch_moved", `${moved} It could not be re-applied onto the new HEAD (${errorMessage(error)}).`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const changedPaths = plan
|
|
45
|
+
? await applyReapply(git, request.worktreePath, currentHead, plan)
|
|
46
|
+
: await applySnapshot(git, request.worktreePath, newest);
|
|
47
|
+
// Conflicts with no MERGE_HEAD to show them: this re-apply's, and any the snapshot carried.
|
|
48
|
+
const reapplyConflicts = await restoredReapplyConflicts(git, request.worktreePath, newest, plan);
|
|
49
|
+
await writeReapplyConflictRecord(git, request.worktreePath, reapplyConflicts);
|
|
50
|
+
return {
|
|
51
|
+
status: "restored",
|
|
52
|
+
ref: newest.ref,
|
|
53
|
+
commitSha: newest.commitSha,
|
|
54
|
+
baseHead: currentHead,
|
|
55
|
+
sourceSessionId: newest.metadata.sessionId,
|
|
56
|
+
changedPaths,
|
|
57
|
+
mergeInProgress: Boolean(newest.metadata.mergeHead),
|
|
58
|
+
reapplied: plan
|
|
59
|
+
? { snapshotBaseHead: newest.metadata.baseHead, conflictedPaths: [...new Set(plan.unmerged.map(entry => entry.path))].sort() }
|
|
60
|
+
: null,
|
|
61
|
+
reapplyConflicts,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
// A pass must never start on a half-applied snapshot: when the partial apply can't be undone,
|
|
66
|
+
// the prepare fails. Nothing is lost; the ref stays, and the next prepare saves this worktree
|
|
67
|
+
// before it resets it. That snapshot holds the mixed state, so it is marked never to be applied
|
|
68
|
+
// automatically (partialRestoreMarkerPath): the next pass restores the original ref instead.
|
|
69
|
+
await rollBack(git, request.worktreePath, currentHead, plan?.worktreeTree ?? newest.commitSha).catch(async (rollbackError) => {
|
|
70
|
+
await partialRestoreMarkerPath(git, request.worktreePath)
|
|
71
|
+
.then(marker => fs.writeFile(marker, `${newest.ref}\n`, "utf8"))
|
|
72
|
+
.catch(() => undefined);
|
|
73
|
+
throw new Error(`Could not apply ${newest.ref} to ${request.worktreePath} (${errorMessage(error)}), and could not undo the partial apply `
|
|
74
|
+
+ `(${errorMessage(rollbackError)}); the worktree is not in a known state, so the provider will not start on it.`, { cause: rollbackError });
|
|
75
|
+
});
|
|
76
|
+
return notRestored("apply_failed", errorMessage(error));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
|
|
80
|
+
export async function deleteWipRef(repoPath, ref, processRunner) {
|
|
81
|
+
if (!ref.startsWith(`${wipRefRoot}/`))
|
|
82
|
+
return false;
|
|
83
|
+
const git = new WipGit(processRunner);
|
|
84
|
+
const origin = (await git.tryRun(repoPath, ["remote", "get-url", "origin"]))?.trim();
|
|
85
|
+
const deleted = origin
|
|
86
|
+
? await git.tryRun(repoPath, ["push", "--porcelain", "origin", `:${ref}`])
|
|
87
|
+
: await git.tryRun(repoPath, ["update-ref", "-d", ref]);
|
|
88
|
+
return deleted !== null;
|
|
89
|
+
}
|
|
90
|
+
/** Every snapshot for the branch: origin's (fetched into a private namespace) and any kept locally. */
|
|
91
|
+
async function listWipCandidates(git, request) {
|
|
92
|
+
const prefix = wipRefPrefix(request.branchName);
|
|
93
|
+
const staging = `refs/forge/wip-restore/${randomUUID()}/`;
|
|
94
|
+
const origin = (await git.tryRun(request.repoPath, ["remote", "get-url", "origin"]))?.trim();
|
|
95
|
+
try {
|
|
96
|
+
if (origin) {
|
|
97
|
+
await git.run(request.repoPath, ["fetch", "--no-tags", "--no-write-fetch-head", "origin", `+${prefix}*:${staging}*`]);
|
|
98
|
+
}
|
|
99
|
+
const fetched = await readRefs(git, request.repoPath, staging, prefix);
|
|
100
|
+
const local = await readRefs(git, request.repoPath, prefix, prefix);
|
|
101
|
+
const byRef = new Map([...local, ...fetched].map(candidate => [candidate.ref, candidate]));
|
|
102
|
+
return [...byRef.values()];
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
const staged = splitLines(await git.tryRun(request.repoPath, ["for-each-ref", "--format=%(refname)", staging]) ?? "");
|
|
106
|
+
for (const ref of staged)
|
|
107
|
+
await git.tryRun(request.repoPath, ["update-ref", "-d", ref]);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function readRefs(git, repoPath, namespace, wipPrefix) {
|
|
111
|
+
const listing = await git.run(repoPath, ["for-each-ref", "--format=%(refname) %(objectname)", namespace]);
|
|
112
|
+
const candidates = [];
|
|
113
|
+
for (const line of splitLines(listing)) {
|
|
114
|
+
const [refName, commitSha] = line.split(" ");
|
|
115
|
+
if (!refName || !commitSha)
|
|
116
|
+
continue;
|
|
117
|
+
const raw = await git.tryRun(repoPath, ["cat-file", "commit", commitSha]);
|
|
118
|
+
const metadata = raw === null ? null : parseWipCommitMessage(commitMessageOf(raw));
|
|
119
|
+
if (metadata)
|
|
120
|
+
candidates.push({ ref: `${wipPrefix}${refName.slice(namespace.length)}`, commitSha, metadata });
|
|
121
|
+
}
|
|
122
|
+
return candidates;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The newest snapshot of this branch a pass may apply; one recorded for any other branch never is.
|
|
126
|
+
* Newest work wins: Forge's attempt number first (a later dispatch attempt always has a larger one,
|
|
127
|
+
* and a snapshot without one is attempt 0), then the snapshot's own time within an attempt.
|
|
128
|
+
*/
|
|
129
|
+
function newestRestorable(candidates, branchName) {
|
|
130
|
+
const branch = branchRefName(branchName);
|
|
131
|
+
return [...candidates]
|
|
132
|
+
.filter(candidate => candidate.metadata.autoRestore && branchRefName(candidate.metadata.branch) === branch)
|
|
133
|
+
.sort((left, right) => candidateAttempt(right) - candidateAttempt(left)
|
|
134
|
+
|| right.metadata.createdAtMs - left.metadata.createdAtMs || right.ref.localeCompare(left.ref))[0]
|
|
135
|
+
?? null;
|
|
136
|
+
}
|
|
137
|
+
// The metadata attempt counts only when it is one Forge could have issued (0 through the ref's ten digits);
|
|
138
|
+
// anything else is attempt 0, so a malformed snapshot can never outrank a real one.
|
|
139
|
+
function candidateAttempt(candidate) {
|
|
140
|
+
return Math.max(wipRefAttempt(candidate.ref), issuedWipAttempt(candidate.metadata.attempt));
|
|
141
|
+
}
|
|
142
|
+
/** True when the worktree holds nothing a snapshot would save (Forge runtime output aside), and no merge. */
|
|
143
|
+
export async function hasNoUnsavedWork(worktreePath, processRunner) {
|
|
144
|
+
return await isCleanWorktree(new WipGit(processRunner), worktreePath);
|
|
145
|
+
}
|
|
146
|
+
async function isCleanWorktree(git, worktreePath) {
|
|
147
|
+
if (await git.tryRun(worktreePath, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]) !== null)
|
|
148
|
+
return false;
|
|
149
|
+
const forgePaths = await baseTrackedForgePaths(git, worktreePath, "HEAD");
|
|
150
|
+
const status = splitNul(await git.run(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]));
|
|
151
|
+
return status.every(entry => isWipExcludedPath(entry.slice(3), forgePaths));
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* The re-apply conflicts the restored worktree holds: the snapshot's record, and this re-apply's
|
|
155
|
+
* conflicts. A snapshot taken outside a merge can only hold conflict stages or markers that an
|
|
156
|
+
* earlier re-apply left (the agent never got to resolve them, as when a prepare step failed before
|
|
157
|
+
* it started), so its stages count too. One with no record and no stages (taken before snapshots
|
|
158
|
+
* carried the record), restored as it was or re-applied across a move, counts the paths whose
|
|
159
|
+
* snapshot version added conflict blocks its base did not have and whose restored file still has
|
|
160
|
+
* markers: Git merges marker text as ordinary content, so a re-apply can carry them over cleanly.
|
|
161
|
+
*/
|
|
162
|
+
async function restoredReapplyConflicts(git, worktreePath, candidate, plan) {
|
|
163
|
+
const { metadata } = candidate;
|
|
164
|
+
const paths = new Set([...metadata.reapplyConflicts, ...(plan?.unmerged ?? []).map(entry => entry.path)]);
|
|
165
|
+
if (metadata.mergeHead)
|
|
166
|
+
return [...paths].sort();
|
|
167
|
+
if (!plan)
|
|
168
|
+
for (const entry of metadata.unmerged)
|
|
169
|
+
paths.add(entry.path);
|
|
170
|
+
if (metadata.reapplyConflicts.length === 0 && metadata.unmerged.length === 0) {
|
|
171
|
+
for (const filePath of await newConflictMarkerPaths(git, worktreePath, candidate))
|
|
172
|
+
paths.add(filePath);
|
|
173
|
+
}
|
|
174
|
+
return [...paths].sort();
|
|
175
|
+
}
|
|
176
|
+
/** Paths whose snapshot version added conflict blocks to its base version, still marked in the worktree. */
|
|
177
|
+
async function newConflictMarkerPaths(git, worktreePath, candidate) {
|
|
178
|
+
const { baseHead } = candidate.metadata;
|
|
179
|
+
const changes = await snapshotChanges(git, worktreePath, baseHead, candidate.commitSha);
|
|
180
|
+
const found = [];
|
|
181
|
+
for (const change of changes.filter(entry => entry.status !== "D")) {
|
|
182
|
+
const saved = await git.tryRun(worktreePath, ["cat-file", "blob", `${candidate.commitSha}:${change.path}`]);
|
|
183
|
+
if (saved === null || !hasConflictMarkerLines(saved))
|
|
184
|
+
continue;
|
|
185
|
+
const base = await git.tryRun(worktreePath, ["cat-file", "blob", `${baseHead}:${change.path}`]);
|
|
186
|
+
if (!hasNewConflictBlocks(saved, base))
|
|
187
|
+
continue;
|
|
188
|
+
// Only an absent file has no markers; any other read failure fails the restore (rolled back).
|
|
189
|
+
const restored = await readOptionalFile(path.join(worktreePath, change.path));
|
|
190
|
+
if (restored !== null && hasConflictMarkerLines(restored))
|
|
191
|
+
found.push(change.path);
|
|
192
|
+
}
|
|
193
|
+
return found;
|
|
194
|
+
}
|
|
195
|
+
/** Writes the snapshot's files and index (and merge state) onto the clean worktree. */
|
|
196
|
+
async function applySnapshot(git, worktreePath, candidate) {
|
|
197
|
+
const { commitSha, metadata } = candidate;
|
|
198
|
+
const changedPaths = await writeWorktreeTree(git, worktreePath, metadata.baseHead, commitSha);
|
|
199
|
+
await git.run(worktreePath, ["read-tree", `${commitSha}^2^{tree}`]);
|
|
200
|
+
if (metadata.unmerged.length > 0)
|
|
201
|
+
await writeUnmergedEntries(git, worktreePath, metadata.unmerged, metadata.baseHead.length);
|
|
202
|
+
if (metadata.mergeHead)
|
|
203
|
+
await writeMergeState(git, worktreePath, metadata);
|
|
204
|
+
await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
|
|
205
|
+
return changedPaths;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Merges the snapshot onto the moved branch without touching the worktree. The worktree's tree is
|
|
209
|
+
* `git merge-tree` of the snapshot's base, the new HEAD and the snapshot (W); the index is the same
|
|
210
|
+
* merge of the snapshot's staged state (W^2) when that is clean, else the new HEAD's tree (all the
|
|
211
|
+
* content is in the worktree either way). A conflict comes back as the merge's stage 1-3 entries.
|
|
212
|
+
*/
|
|
213
|
+
async function planReapply(git, worktreePath, candidate, currentHead) {
|
|
214
|
+
const base = candidate.metadata.baseHead;
|
|
215
|
+
const worktree = await mergeTree(git, worktreePath, base, currentHead, candidate.commitSha);
|
|
216
|
+
const index = await mergeTree(git, worktreePath, base, currentHead, `${candidate.commitSha}^2`);
|
|
217
|
+
return {
|
|
218
|
+
worktreeTree: worktree.tree,
|
|
219
|
+
indexTree: index.unmerged.length === 0 ? index.tree : `${currentHead}^{tree}`,
|
|
220
|
+
unmerged: worktree.unmerged,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/** Writes a re-apply's merged files, index and conflict stages onto the clean worktree at `currentHead`. */
|
|
224
|
+
async function applyReapply(git, worktreePath, currentHead, plan) {
|
|
225
|
+
const changedPaths = await writeWorktreeTree(git, worktreePath, currentHead, plan.worktreeTree);
|
|
226
|
+
await git.run(worktreePath, ["read-tree", plan.indexTree]);
|
|
227
|
+
if (plan.unmerged.length > 0)
|
|
228
|
+
await writeUnmergedEntries(git, worktreePath, plan.unmerged, currentHead.length);
|
|
229
|
+
await git.tryRun(worktreePath, ["update-index", "-q", "--refresh"]);
|
|
230
|
+
return changedPaths;
|
|
231
|
+
}
|
|
232
|
+
/** `git merge-tree --write-tree` (Git 2.40+): the merged tree, with its conflict stages when it conflicts. */
|
|
233
|
+
async function mergeTree(git, worktreePath, base, ours, theirs) {
|
|
234
|
+
const args = ["merge-tree", "--write-tree", "-z", "--no-messages", `--merge-base=${base}`, ours, theirs];
|
|
235
|
+
const result = await git.runWithStatus(worktreePath, args);
|
|
236
|
+
if (result.exitCode !== 0 && result.exitCode !== 1) {
|
|
237
|
+
throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
|
|
238
|
+
}
|
|
239
|
+
// <tree> NUL, then one "<mode> <object> <stage>\t<path>" NUL per conflict stage, then an empty field.
|
|
240
|
+
const [tree = "", ...records] = result.stdout.split("\0");
|
|
241
|
+
const unmerged = [];
|
|
242
|
+
for (const record of records) {
|
|
243
|
+
const match = /^(\d{6}) ([0-9a-f]+) ([123])\t([\s\S]+)$/u.exec(record);
|
|
244
|
+
if (!match)
|
|
245
|
+
break;
|
|
246
|
+
unmerged.push({ mode: match[1], sha: match[2], stage: Number(match[3]), path: match[4] });
|
|
247
|
+
}
|
|
248
|
+
if (!/^[0-9a-f]+$/u.test(tree.trim()))
|
|
249
|
+
throw new Error(`git merge-tree returned no tree (${result.stderr.trim()})`);
|
|
250
|
+
if (result.exitCode === 1 && unmerged.length === 0)
|
|
251
|
+
throw new Error("git merge-tree reported a conflict without conflict stages");
|
|
252
|
+
return { tree: tree.trim(), unmerged };
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Turns a clean worktree at `from` into the tree `to` (files only; the caller sets the index): writes
|
|
256
|
+
* the paths `to` adds or changes and deletes the ones it drops. Returns how many paths changed.
|
|
257
|
+
*/
|
|
258
|
+
async function writeWorktreeTree(git, worktreePath, from, to) {
|
|
259
|
+
const changes = await snapshotChanges(git, worktreePath, from, to);
|
|
260
|
+
const tempDir = await makeWipTempDir();
|
|
261
|
+
try {
|
|
262
|
+
const snapshotIndex = git.with({ GIT_INDEX_FILE: path.join(tempDir, "snapshot.index") });
|
|
263
|
+
await snapshotIndex.run(worktreePath, ["read-tree", to]);
|
|
264
|
+
const written = changes.filter(change => change.status !== "D").map(change => change.path);
|
|
265
|
+
await snapshotIndex.runForPaths(worktreePath, ["checkout-index", "-f"], written, false);
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
|
|
269
|
+
}
|
|
270
|
+
for (const change of changes.filter(entry => entry.status === "D")) {
|
|
271
|
+
await fs.rm(path.join(worktreePath, change.path), { force: true });
|
|
272
|
+
}
|
|
273
|
+
return changes.length;
|
|
274
|
+
}
|
|
275
|
+
async function snapshotChanges(git, worktreePath, base, commitSha) {
|
|
276
|
+
const fields = splitNul(await git.run(worktreePath, ["diff-tree", "-r", "-z", "--no-renames", "--name-status", base, commitSha]));
|
|
277
|
+
const changes = [];
|
|
278
|
+
for (let index = 0; index + 1 < fields.length; index += 2) {
|
|
279
|
+
changes.push({ status: fields[index].trim(), path: fields[index + 1] });
|
|
280
|
+
}
|
|
281
|
+
return changes;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Puts conflict stages into the index: a restored half-done merge resumes exactly where it stopped,
|
|
285
|
+
* and a conflicting re-apply is left unmerged for the agent.
|
|
286
|
+
*/
|
|
287
|
+
async function writeUnmergedEntries(git, worktreePath, unmerged, hashLength) {
|
|
288
|
+
const zero = "0".repeat(hashLength);
|
|
289
|
+
const conflicted = [...new Set(unmerged.map(entry => entry.path))];
|
|
290
|
+
const records = [
|
|
291
|
+
...conflicted.map(filePath => `0 ${zero} 0\t${filePath}`),
|
|
292
|
+
...unmerged.map(entry => `${entry.mode} ${entry.sha} ${entry.stage}\t${entry.path}`),
|
|
293
|
+
];
|
|
294
|
+
await git.runWithInput(worktreePath, ["update-index", "-z", "--index-info"], `${records.join("\0")}\0`);
|
|
295
|
+
}
|
|
296
|
+
async function writeMergeState(git, worktreePath, metadata) {
|
|
297
|
+
await fs.writeFile(await gitPath(git, worktreePath, "MERGE_HEAD"), `${metadata.mergeHead}\n`, "utf8");
|
|
298
|
+
await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MSG"), metadata.mergeMessage ?? `Merge ${metadata.mergeHead}\n`, "utf8");
|
|
299
|
+
if (metadata.mergeMode)
|
|
300
|
+
await fs.writeFile(await gitPath(git, worktreePath, "MERGE_MODE"), `${metadata.mergeMode}\n`, "utf8");
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Undoes a partial apply of `target` (the snapshot, or a re-apply's merged tree): the worktree was
|
|
304
|
+
* clean at `head` before it started.
|
|
305
|
+
*/
|
|
306
|
+
async function rollBack(git, worktreePath, head, target) {
|
|
307
|
+
for (const name of ["MERGE_HEAD", "MERGE_MSG", "MERGE_MODE"]) {
|
|
308
|
+
await fs.rm(await gitPath(git, worktreePath, name), { force: true });
|
|
309
|
+
}
|
|
310
|
+
await git.run(worktreePath, ["read-tree", "--reset", "-u", head]);
|
|
311
|
+
const changes = await snapshotChanges(git, worktreePath, head, target);
|
|
312
|
+
for (const change of changes.filter(entry => entry.status === "A")) {
|
|
313
|
+
await fs.rm(path.join(worktreePath, change.path), { force: true });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function branchRefName(branchName) {
|
|
317
|
+
return branchName.trim().replace(/^refs\/heads\//u, "");
|
|
318
|
+
}
|
|
319
|
+
function splitLines(value) {
|
|
320
|
+
return value.split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
|
|
321
|
+
}
|
|
322
|
+
function errorMessage(error) {
|
|
323
|
+
return error instanceof Error ? error.message : String(error);
|
|
324
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ProcessRunner } from "../shared/process/process.js";
|
|
2
|
+
import { type WipSnapshotReason } from "./wip-refs.js";
|
|
3
|
+
export interface WipSnapshotRequest {
|
|
4
|
+
readonly worktreePath: string;
|
|
5
|
+
readonly branchName: string;
|
|
6
|
+
readonly reason: WipSnapshotReason;
|
|
7
|
+
readonly sessionId?: string | null;
|
|
8
|
+
readonly lane?: string | null;
|
|
9
|
+
/**
|
|
10
|
+
* Forge's attempt number for the dispatch (sandbox.wipAttempt), stamped on the ref and metadata so
|
|
11
|
+
* the newest work wins on restore; without one (or out of range) the snapshot is attempt 0.
|
|
12
|
+
*/
|
|
13
|
+
readonly attempt?: number | null;
|
|
14
|
+
/** Whether a later pass may apply this snapshot by itself (wip-restore.ts). */
|
|
15
|
+
readonly autoRestore: boolean;
|
|
16
|
+
/** Overrides FORGE_WIP_SNAPSHOT_MAX_BYTES. */
|
|
17
|
+
readonly maxBytes?: number;
|
|
18
|
+
/**
|
|
19
|
+
* A checkout whose Git administrative directory is gone, so Git no longer knows its HEAD or
|
|
20
|
+
* index: it is read through the shared repository against `baseRef` instead.
|
|
21
|
+
*/
|
|
22
|
+
readonly orphan?: {
|
|
23
|
+
readonly repoPath: string;
|
|
24
|
+
readonly baseRef: string;
|
|
25
|
+
};
|
|
26
|
+
readonly processRunner?: ProcessRunner;
|
|
27
|
+
readonly now?: () => Date;
|
|
28
|
+
}
|
|
29
|
+
export type WipSnapshotResult = {
|
|
30
|
+
readonly status: "clean";
|
|
31
|
+
} | {
|
|
32
|
+
readonly status: "saved" | "already_saved";
|
|
33
|
+
readonly ref: string;
|
|
34
|
+
readonly commitSha: string;
|
|
35
|
+
readonly baseHead: string;
|
|
36
|
+
readonly changedPaths: number;
|
|
37
|
+
readonly bytes: number;
|
|
38
|
+
/** False when the repository has no origin and the ref was kept in the local repository. */
|
|
39
|
+
readonly pushed: boolean;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Saves the worktree's uncommitted work to a WIP ref. Returns `clean` (and pushes nothing) when
|
|
43
|
+
* there is nothing to save. Throws {@link WipPreservationError} when the work could not be saved,
|
|
44
|
+
* including when it is over the size cap: the caller must then not destroy the worktree.
|
|
45
|
+
*/
|
|
46
|
+
export declare function preserveWorktreeWip(requested: WipSnapshotRequest): Promise<WipSnapshotResult>;
|
|
47
|
+
/** Forgets what this process pushed for a worktree, e.g. once the worktree is gone. */
|
|
48
|
+
export declare function forgetPreservedWip(worktreePath: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* Forgets every snapshot this process pushed to `ref`, before that ref is deleted: a later guard
|
|
51
|
+
* that finds the same state must push it again rather than report it saved in a ref that is gone.
|
|
52
|
+
*/
|
|
53
|
+
export declare function forgetPreservedWipRef(ref: string): void;
|