@fitlab-ai/agent-infra 0.9.14 → 0.10.0
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 +10 -0
- package/README.zh-CN.md +10 -0
- package/bin/internal-cli.sh +45 -0
- package/dist/bin/internal-cli.js +93 -30
- package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +165 -27
- package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +9 -4
- package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +43 -3
- package/dist/lib/defaults.json +103 -103
- package/dist/lib/fs/durable-write.js +39 -0
- package/dist/lib/fs/file-lock.js +111 -0
- package/dist/lib/host-control/audit.js +19 -0
- package/dist/lib/host-control/client.js +142 -0
- package/dist/lib/host-control/command.js +49 -0
- package/dist/lib/host-control/path.js +160 -0
- package/dist/lib/host-control/secure-fs.js +140 -0
- package/dist/lib/host-control/server.js +159 -0
- package/dist/lib/host-control/service.js +112 -0
- package/dist/lib/init.js +11 -2
- package/dist/lib/internal/cli-route-inventory.js +4 -2
- package/dist/lib/internal/codex-lifecycle.js +6 -6
- package/dist/lib/internal/demo-promotion.js +322 -0
- package/dist/lib/internal/demo-transcript.js +454 -0
- package/dist/lib/internal/host-control.js +28 -0
- package/dist/lib/internal/manual-validation.js +331 -0
- package/dist/lib/internal/platform-pr.js +18 -4
- package/dist/lib/internal/release-workflow.js +63 -84
- package/dist/lib/internal/sandbox-control.js +149 -2
- package/dist/lib/internal/task-artifact.js +16 -263
- package/dist/lib/internal/task-create.js +6 -5
- package/dist/lib/internal/task-event.js +37 -37
- package/dist/lib/internal/task-lifecycle.js +2 -2
- package/dist/lib/internal/task-operation-registry.js +101 -4
- package/dist/lib/internal/task-review.js +11 -56
- package/dist/lib/internal/task-validate.js +30 -10
- package/dist/lib/owned-path.js +33 -0
- package/dist/lib/platform/check-status.js +11 -0
- package/dist/lib/platform/comment-safety.js +4 -1
- package/dist/lib/platform/completion-backfill.js +1 -1
- package/dist/lib/platform/github-data.js +241 -0
- package/dist/lib/platform/github-provider.js +15 -20
- package/dist/lib/platform/issue-comments.js +18 -12
- package/dist/lib/platform/issues.js +2 -180
- package/dist/lib/platform/pr-change-report.js +5 -4
- package/dist/lib/platform/pr-checks.js +12 -65
- package/dist/lib/platform/pr-summary.js +117 -33
- package/dist/lib/platform/pull-requests.js +5 -108
- package/dist/lib/platform/snapshots.js +2 -0
- package/dist/lib/platform/task-identities.js +2 -9
- package/dist/lib/platform/verification-sync.js +132 -143
- package/dist/lib/pr-review/evidence-grading.js +4 -8
- package/dist/lib/release/workflow.js +1 -1
- package/dist/lib/sandbox/commands/create.js +7 -2
- package/dist/lib/sandbox/commands/rm.js +19 -1511
- package/dist/lib/sandbox/control/audit.js +203 -0
- package/dist/lib/sandbox/control/client.js +93 -54
- package/dist/lib/sandbox/control/executor.js +129 -65
- package/dist/lib/sandbox/control/finalization-response.js +27 -0
- package/dist/lib/sandbox/control/identity-sentinel.js +107 -0
- package/dist/lib/sandbox/control/lifecycle.js +36 -2
- package/dist/lib/sandbox/control/native-file-lock.js +6 -98
- package/dist/lib/sandbox/control/protocol.js +55 -4
- package/dist/lib/sandbox/control/server.js +518 -127
- package/dist/lib/sandbox/control/state.js +64 -0
- package/dist/lib/sandbox/control/task-workflow.js +74 -0
- package/dist/lib/sandbox/control/workflow-executor.js +89 -0
- package/dist/lib/sandbox/index.js +1 -2
- package/dist/lib/sandbox/recovery.js +28 -4
- package/dist/lib/sandbox/removal.js +822 -0
- package/dist/lib/sandbox/task-cleanup.js +217 -0
- package/dist/lib/sandbox/workspace-identity.js +17 -1
- package/dist/lib/sandbox/workspace-view.js +13 -14
- package/dist/lib/task/activity-intent.js +2 -1
- package/dist/lib/task/activity-log.js +30 -24
- package/dist/lib/task/artifact-command.js +79 -0
- package/dist/lib/task/artifact-lifecycle.js +30 -28
- package/dist/lib/task/artifact-name.js +36 -0
- package/dist/lib/task/artifact-operations.js +29 -289
- package/dist/lib/task/artifact-receipts.js +3 -15
- package/dist/lib/task/artifact-recovery.js +430 -0
- package/dist/lib/task/artifact-repair-intent.js +134 -29
- package/dist/lib/task/artifact-schema.js +6 -14
- package/dist/lib/task/capabilities.js +12 -19
- package/dist/lib/task/codex-orchestration.js +71 -25
- package/dist/lib/task/commit-identity.js +28 -0
- package/dist/lib/task/commit-operation.js +33 -20
- package/dist/lib/task/control-authority.js +403 -6
- package/dist/lib/task/control-recovery.js +140 -0
- package/dist/lib/task/create-service.js +1 -8
- package/dist/lib/task/create.js +62 -9
- package/dist/lib/task/decision-details.js +2 -46
- package/dist/lib/task/delegation-receipts.js +64 -3
- package/dist/lib/task/events.js +275 -22
- package/dist/lib/task/finalization-state.js +9 -0
- package/dist/lib/task/human-override.js +8 -14
- package/dist/lib/task/implementation-inputs.js +3 -3
- package/dist/lib/task/intermediate-cleanup.js +441 -0
- package/dist/lib/task/invalidation.js +18 -65
- package/dist/lib/task/ledger-intents.js +7 -22
- package/dist/lib/task/ledger.js +1 -3
- package/dist/lib/task/lifecycle-recovery.js +549 -0
- package/dist/lib/task/lifecycle.js +31 -4
- package/dist/lib/task/local-artifact-finalization.js +197 -197
- package/dist/lib/task/manual-validation-completion.js +26 -0
- package/dist/lib/task/manual-validation-evidence.js +130 -0
- package/dist/lib/task/manual-validation-receipt.js +105 -0
- package/dist/lib/task/manual-validation-shared.js +40 -0
- package/dist/lib/task/manual-validation-transaction.js +243 -0
- package/dist/lib/task/markdown.js +47 -0
- package/dist/lib/task/orchestration.js +66 -19
- package/dist/lib/task/pr-delivery-fact.js +12 -56
- package/dist/lib/task/qualification-audit.js +20 -34
- package/dist/lib/task/recovery-warning.js +19 -0
- package/dist/lib/task/review-artifacts.js +2 -18
- package/dist/lib/task/review-command.js +26 -0
- package/dist/lib/task/review-finalization.js +175 -216
- package/dist/lib/task/review-fingerprint.js +2 -2
- package/dist/lib/task/sections.js +34 -56
- package/dist/lib/task/short-id.js +15 -7
- package/dist/lib/task/task-execution-lock.js +1 -1
- package/dist/lib/task/verification-engine.js +119 -337
- package/dist/lib/task/verification.js +1 -1
- package/dist/lib/task/workflow-command.js +16 -0
- package/dist/lib/task/workflow-warning-intents.js +0 -16
- package/dist/lib/task/workflow-warnings.js +28 -2
- package/dist/lib/update.js +2 -0
- package/dist/lib/version.js +1 -11
- package/dist/lifecycle-build-manifest.json +3 -3
- package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +223 -33
- package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +10 -4
- package/lib/agent-clients/adapters/codex-lifecycle/store.ts +55 -3
- package/lib/fs/durable-write.ts +30 -0
- package/lib/fs/file-lock.ts +113 -0
- package/lib/host-control/audit.ts +22 -0
- package/lib/host-control/client.ts +172 -0
- package/lib/host-control/command.ts +60 -0
- package/lib/host-control/path.ts +167 -0
- package/lib/host-control/secure-fs.ts +135 -0
- package/lib/host-control/server.ts +180 -0
- package/lib/host-control/service.ts +133 -0
- package/lib/init.ts +15 -2
- package/lib/internal/cli-route-inventory.ts +4 -2
- package/lib/internal/codex-lifecycle.ts +6 -6
- package/lib/internal/demo-promotion.ts +354 -0
- package/lib/internal/demo-transcript.ts +419 -0
- package/lib/internal/host-control.ts +28 -0
- package/lib/internal/manual-validation.ts +315 -0
- package/lib/internal/platform-pr.ts +15 -4
- package/lib/internal/release-workflow.ts +74 -82
- package/lib/internal/sandbox-control.ts +162 -1
- package/lib/internal/task-artifact.ts +14 -217
- package/lib/internal/task-create.ts +5 -5
- package/lib/internal/task-event.ts +20 -11
- package/lib/internal/task-lifecycle.ts +4 -3
- package/lib/internal/task-operation-registry.ts +111 -4
- package/lib/internal/task-review.ts +9 -54
- package/lib/internal/task-validate.ts +26 -10
- package/lib/owned-path.ts +26 -0
- package/lib/platform/check-status.ts +9 -0
- package/lib/platform/comment-safety.ts +5 -0
- package/lib/platform/completion-backfill.ts +1 -1
- package/lib/platform/github-data.ts +322 -0
- package/lib/platform/github-provider.ts +15 -20
- package/lib/platform/issue-comments.ts +21 -14
- package/lib/platform/issues.ts +5 -246
- package/lib/platform/pr-change-report.ts +7 -5
- package/lib/platform/pr-checks.ts +13 -77
- package/lib/platform/pr-summary.ts +123 -35
- package/lib/platform/pull-requests.ts +6 -173
- package/lib/platform/snapshots.ts +53 -0
- package/lib/platform/task-identities.ts +3 -14
- package/lib/platform/verification-sync.ts +150 -156
- package/lib/pr-review/evidence-grading.ts +4 -9
- package/lib/release/workflow.ts +3 -3
- package/lib/sandbox/commands/create.ts +7 -6
- package/lib/sandbox/commands/rm.ts +21 -1895
- package/lib/sandbox/control/audit.ts +253 -0
- package/lib/sandbox/control/client.ts +109 -66
- package/lib/sandbox/control/executor.ts +134 -74
- package/lib/sandbox/control/finalization-response.ts +29 -0
- package/lib/sandbox/control/identity-sentinel.ts +137 -0
- package/lib/sandbox/control/lifecycle.ts +45 -3
- package/lib/sandbox/control/native-file-lock.ts +6 -107
- package/lib/sandbox/control/protocol.ts +80 -6
- package/lib/sandbox/control/server.ts +567 -132
- package/lib/sandbox/control/state.ts +86 -0
- package/lib/sandbox/control/task-workflow.ts +95 -0
- package/lib/sandbox/control/workflow-executor.ts +92 -0
- package/lib/sandbox/index.ts +1 -2
- package/lib/sandbox/recovery.ts +28 -5
- package/lib/sandbox/removal.ts +1142 -0
- package/lib/sandbox/task-cleanup.ts +209 -0
- package/lib/sandbox/workspace-identity.ts +19 -3
- package/lib/sandbox/workspace-view.ts +17 -15
- package/lib/task/activity-intent.ts +2 -2
- package/lib/task/activity-log.ts +27 -19
- package/lib/task/artifact-command.ts +85 -0
- package/lib/task/artifact-lifecycle.ts +31 -26
- package/lib/task/artifact-name.ts +55 -0
- package/lib/task/artifact-operations.ts +34 -310
- package/lib/task/artifact-receipts.ts +3 -14
- package/lib/task/artifact-recovery.ts +519 -0
- package/lib/task/artifact-repair-intent.ts +162 -33
- package/lib/task/artifact-schema.ts +5 -34
- package/lib/task/capabilities.ts +13 -22
- package/lib/task/codex-orchestration.ts +85 -24
- package/lib/task/commit-identity.ts +31 -0
- package/lib/task/commit-operation.ts +37 -20
- package/lib/task/control-authority.ts +540 -10
- package/lib/task/control-recovery.ts +186 -0
- package/lib/task/create-service.ts +1 -10
- package/lib/task/create.ts +63 -8
- package/lib/task/decision-details.ts +3 -71
- package/lib/task/delegation-receipts.ts +73 -2
- package/lib/task/events.ts +309 -24
- package/lib/task/finalization-state.ts +11 -0
- package/lib/task/human-override.ts +8 -16
- package/lib/task/implementation-inputs.ts +3 -3
- package/lib/task/intermediate-cleanup.ts +493 -0
- package/lib/task/invalidation.ts +18 -62
- package/lib/task/ledger-intents.ts +7 -24
- package/lib/task/ledger.ts +1 -3
- package/lib/task/lifecycle-recovery.ts +691 -0
- package/lib/task/lifecycle.ts +30 -5
- package/lib/task/local-artifact-finalization.ts +244 -234
- package/lib/task/manual-validation-completion.ts +40 -0
- package/lib/task/manual-validation-evidence.ts +209 -0
- package/lib/task/manual-validation-receipt.ts +156 -0
- package/lib/task/manual-validation-shared.ts +50 -0
- package/lib/task/manual-validation-transaction.ts +304 -0
- package/lib/task/markdown.ts +70 -0
- package/lib/task/orchestration.ts +84 -19
- package/lib/task/pr-delivery-fact.ts +15 -62
- package/lib/task/qualification-audit.ts +22 -33
- package/lib/task/recovery-warning.ts +21 -0
- package/lib/task/review-artifacts.ts +1 -20
- package/lib/task/review-command.ts +24 -0
- package/lib/task/review-finalization.ts +183 -292
- package/lib/task/review-fingerprint.ts +2 -2
- package/lib/task/sections.ts +33 -54
- package/lib/task/short-id.ts +27 -5
- package/lib/task/task-execution-lock.ts +1 -1
- package/lib/task/verification-engine.ts +113 -383
- package/lib/task/verification-types.ts +15 -0
- package/lib/task/verification.ts +1 -1
- package/lib/task/workflow-command.ts +17 -0
- package/lib/task/workflow-warning-intents.ts +0 -13
- package/lib/task/workflow-warnings.ts +21 -2
- package/lib/update.ts +6 -0
- package/lib/version.ts +1 -15
- package/package.json +6 -6
- package/templates/.agents/hooks/lifecycle-delegation.js +6 -6
- package/templates/.agents/rules/create-issue.en.md +1 -1
- package/templates/.agents/rules/create-issue.zh-CN.md +1 -1
- package/templates/.agents/rules/issue-sync.en.md +4 -2
- package/templates/.agents/rules/issue-sync.zh-CN.md +4 -3
- package/templates/.agents/rules/local-artifact-repair.en.md +46 -39
- package/templates/.agents/rules/local-artifact-repair.zh-CN.md +43 -36
- package/templates/.agents/rules/testing-discipline.en.md +2 -0
- package/templates/.agents/rules/testing-discipline.zh-CN.md +2 -0
- package/templates/.agents/scripts/package.json +3 -0
- package/templates/.agents/skills/analyze-task/SKILL.en.md +6 -6
- package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +6 -6
- package/templates/.agents/skills/analyze-task/config/verify.en.json +1 -1
- package/templates/.agents/skills/analyze-task/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/block-task/SKILL.en.md +2 -2
- package/templates/.agents/skills/block-task/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/block-task/config/verify.json +1 -1
- package/templates/.agents/skills/cancel-task/SKILL.en.md +3 -3
- package/templates/.agents/skills/cancel-task/SKILL.zh-CN.md +3 -3
- package/templates/.agents/skills/cancel-task/config/verify.json +1 -1
- package/templates/.agents/skills/code-task/SKILL.en.md +7 -7
- package/templates/.agents/skills/code-task/SKILL.zh-CN.md +7 -7
- package/templates/.agents/skills/code-task/config/verify.en.json +1 -1
- package/templates/.agents/skills/code-task/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/commit/reference/issue-metadata-sync.en.md +1 -1
- package/templates/.agents/skills/commit/reference/issue-metadata-sync.zh-CN.md +1 -1
- package/templates/.agents/skills/complete-manual-validation/SKILL.en.md +33 -21
- package/templates/.agents/skills/complete-manual-validation/SKILL.zh-CN.md +33 -21
- package/templates/.agents/skills/complete-manual-validation/config/verify.en.json +1 -1
- package/templates/.agents/skills/complete-manual-validation/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/complete-manual-validation/reference/report-template.en.md +2 -0
- package/templates/.agents/skills/complete-manual-validation/reference/report-template.zh-CN.md +2 -0
- package/templates/.agents/skills/complete-manual-validation/reference/summary-update.en.md +16 -7
- package/templates/.agents/skills/complete-manual-validation/reference/summary-update.zh-CN.md +16 -7
- package/templates/.agents/skills/complete-task/SKILL.en.md +3 -3
- package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +3 -3
- package/templates/.agents/skills/complete-task/config/verify.en.json +2 -2
- package/templates/.agents/skills/complete-task/config/verify.zh-CN.json +2 -2
- package/templates/.agents/skills/complete-task/reference/external-delivery.en.md +1 -1
- package/templates/.agents/skills/complete-task/reference/external-delivery.zh-CN.md +1 -1
- package/templates/.agents/skills/create-pr/SKILL.en.md +2 -2
- package/templates/.agents/skills/create-pr/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/create-pr/config/verify.json +1 -1
- package/templates/.agents/skills/create-pr/reference/pr-body-template.en.md +2 -2
- package/templates/.agents/skills/create-pr/reference/pr-body-template.zh-CN.md +2 -2
- package/templates/.agents/skills/create-task/SKILL.en.md +5 -5
- package/templates/.agents/skills/create-task/SKILL.zh-CN.md +5 -5
- package/templates/.agents/skills/create-task/config/verify.json +1 -1
- package/templates/.agents/skills/import-issue/SKILL.en.md +8 -8
- package/templates/.agents/skills/import-issue/SKILL.zh-CN.md +8 -8
- package/templates/.agents/skills/import-issue/config/verify.json +2 -2
- package/templates/.agents/skills/plan-task/SKILL.en.md +4 -4
- package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +4 -4
- package/templates/.agents/skills/plan-task/config/verify.en.json +1 -1
- package/templates/.agents/skills/plan-task/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/release/SKILL.en.md +7 -3
- package/templates/.agents/skills/release/SKILL.zh-CN.md +7 -3
- package/templates/.agents/skills/restore-task/SKILL.en.md +2 -2
- package/templates/.agents/skills/restore-task/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/restore-task/config/verify.json +1 -1
- package/templates/.agents/skills/review-analysis/SKILL.en.md +2 -2
- package/templates/.agents/skills/review-analysis/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/review-analysis/config/verify.en.json +1 -1
- package/templates/.agents/skills/review-analysis/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/review-analysis/reference/report-template.en.md +7 -7
- package/templates/.agents/skills/review-analysis/reference/report-template.zh-CN.md +6 -6
- package/templates/.agents/skills/review-code/SKILL.en.md +2 -2
- package/templates/.agents/skills/review-code/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/review-code/config/verify.en.json +1 -1
- package/templates/.agents/skills/review-code/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/review-code/reference/report-template.en.md +12 -12
- package/templates/.agents/skills/review-code/reference/report-template.zh-CN.md +12 -12
- package/templates/.agents/skills/review-plan/SKILL.en.md +2 -2
- package/templates/.agents/skills/review-plan/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/review-plan/config/verify.en.json +1 -1
- package/templates/.agents/skills/review-plan/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/review-plan/reference/report-template.en.md +7 -7
- package/templates/.agents/skills/review-plan/reference/report-template.zh-CN.md +7 -7
- package/templates/.agents/skills/review-pr/config/verify.en.json +1 -1
- package/templates/.agents/skills/review-pr/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/review-pr/reference/evidence-grading.en.md +3 -3
- package/templates/.agents/skills/review-pr/reference/evidence-grading.zh-CN.md +3 -3
- package/templates/.agents/skills/run-manual-validation/SKILL.en.md +20 -3
- package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +20 -3
- package/templates/.agents/skills/run-manual-validation/config/verify.en.json +1 -1
- package/templates/.agents/skills/run-manual-validation/config/verify.zh-CN.json +1 -1
- package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.en.md +4 -1
- package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.zh-CN.md +4 -1
- package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +2 -0
- package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +2 -0
- package/templates/.agents/skills/run-task/SKILL.en.md +1 -1
- package/templates/.agents/skills/run-task/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/test/SKILL.en.md +17 -6
- package/templates/.agents/skills/test/SKILL.zh-CN.md +17 -6
- package/templates/.agents/templates/task.en.md +1 -1
- package/templates/.agents/templates/task.zh-CN.md +1 -1
- package/templates/.claude/commands/import-issue.en.md +1 -1
- package/templates/.claude/commands/import-issue.zh-CN.md +1 -1
- package/templates/.claude/commands/restore-task.en.md +1 -1
- package/templates/.claude/commands/restore-task.zh-CN.md +1 -1
- package/templates/.claude/commands/run-manual-validation.en.md +1 -1
- package/templates/.claude/commands/run-manual-validation.zh-CN.md +1 -1
- package/dist/lib/platform/adapters.js +0 -56
- package/lib/platform/adapters.ts +0 -197
|
@@ -1,1521 +1,27 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { createHash } from 'node:crypto';
|
|
4
1
|
import { parseArgs } from 'node:util';
|
|
5
|
-
import * as p from '@clack/prompts';
|
|
6
|
-
import pc from 'picocolors';
|
|
7
2
|
import { loadConfig } from '../config.js';
|
|
8
|
-
import { assertValidBranchName, containerNameCandidates, sandboxBranchLabel, sandboxLabel, sandboxTaskIdLabel, sandboxWorkspaceModeLabel, shareBranchDir, shellConfigDirCandidates, worktreeDirCandidates } from '../constants.js';
|
|
9
|
-
import { ENGINES, detectEngine, engineDisplayName, isManagedEngine, stopManagedVm } from '../engine.js';
|
|
10
|
-
import { pruneSandboxDanglingImages } from '../image-prune.js';
|
|
11
|
-
import { assertManagedPath, removeManagedDir, removeWorktreeDir } from '../managed-fs.js';
|
|
12
|
-
import { run, runEngine, runOk, runOkEngine, runSafe, runSafeEngine } from '../shell.js';
|
|
13
|
-
import { parseSandboxWorkspaceIdentity, resolveSandboxCleanupTarget, sameSandboxWorkspaceIdentity } from '../workspace-identity.js';
|
|
14
|
-
import { sandboxControlPaths, sandboxWorkspaceViewPaths } from '../workspace-view.js';
|
|
15
|
-
import { SANDBOX_REMOVAL_JOURNAL_PHASES, advanceSandboxRemovalJournalPhase, claimSandboxRemovalJournal, clearSandboxRemovalJournalRecord, listSandboxRemovalJournals, removeSandboxControlRoot, readSandboxControlManifest, sandboxRemovalPhaseIndex } from '../control/lifecycle.js';
|
|
16
|
-
import { inspectSandboxControlContainer } from '../control/container-identity.js';
|
|
17
|
-
import { commandForSandboxAuthority } from '../engines/authority.js';
|
|
18
|
-
import { acquireSandboxResourceLock } from '../control/native-file-lock.js';
|
|
19
|
-
import { toolConfigDirCandidates, toolProjectDirCandidates } from '../tools.js';
|
|
20
3
|
import { createSandboxCapabilityPlan } from '../agent-client-reconciler.js';
|
|
4
|
+
import { resolveSandboxCleanupTarget } from '../workspace-identity.js';
|
|
5
|
+
import { detectEngine } from '../engine.js';
|
|
6
|
+
import { sandboxBranchLabel, sandboxLabel, sandboxTaskIdLabel, sandboxWorkspaceModeLabel } from '../constants.js';
|
|
21
7
|
import { fetchSandboxRows } from './list-running.js';
|
|
22
|
-
import {
|
|
8
|
+
import { rmOne, rmPurge, rmUnbound } from '../removal.js';
|
|
23
9
|
const USAGE = `Usage:
|
|
24
10
|
ai sandbox rm <branch | TASK-id | short id> Remove one sandbox; use a full TASK-id for a task-bound sandbox and a branch for branch-only sandboxes
|
|
25
|
-
ai sandbox rm --unbound [--dry-run] [--yes] Remove
|
|
11
|
+
ai sandbox rm --unbound [--dry-run] [--yes] Remove discovered task-bound and branch-only sandboxes
|
|
26
12
|
ai sandbox rm --purge Tear down ALL sandboxes for the project (containers, worktrees, image, VM)`;
|
|
27
|
-
|
|
28
|
-
function projectToolDirs(config, tools) {
|
|
29
|
-
return tools.flatMap((tool) => toolProjectDirCandidates(tool, config.project));
|
|
30
|
-
}
|
|
31
|
-
function isMissingPathError(error) {
|
|
32
|
-
return Boolean(error && typeof error === 'object' && 'code' in error
|
|
33
|
-
&& error.code === 'ENOENT');
|
|
34
|
-
}
|
|
35
|
-
function digestCleanupValue(value) {
|
|
36
|
-
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
37
|
-
}
|
|
38
|
-
function removalTargetDigest(config, target) {
|
|
39
|
-
return digestCleanupValue({
|
|
40
|
-
project: config.project,
|
|
41
|
-
branch: target.effectiveBranch,
|
|
42
|
-
workspace: target.workspace,
|
|
43
|
-
controlRoots: target.controlRoots.map((candidate) => path.resolve(candidate)),
|
|
44
|
-
workspaceViewRoots: target.workspaceViewRoots.map((candidate) => path.resolve(candidate)),
|
|
45
|
-
managedPathCandidates: (target.managedPathCandidates ?? []).map((candidate) => path.resolve(candidate)).sort()
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
function removalPermitDigest(permits) {
|
|
49
|
-
return digestCleanupValue([...permits.entries()]
|
|
50
|
-
.map(([worktree, permit]) => [path.resolve(worktree), permit.mode, permit.snapshot.identity])
|
|
51
|
-
.sort(([left], [right]) => String(left).localeCompare(String(right))));
|
|
52
|
-
}
|
|
53
|
-
function removalPermitCommits(permits) {
|
|
54
|
-
return [...permits.entries()]
|
|
55
|
-
.map(([worktree, permit]) => ({
|
|
56
|
-
path: path.resolve(worktree),
|
|
57
|
-
mode: permit.mode,
|
|
58
|
-
snapshot: permit.snapshot
|
|
59
|
-
}))
|
|
60
|
-
.sort((left, right) => left.path.localeCompare(right.path));
|
|
61
|
-
}
|
|
62
|
-
function removalTargetCommit(config, target, permits, removeWorktree, removeBranch, removeShare) {
|
|
63
|
-
return {
|
|
64
|
-
branch: target.effectiveBranch,
|
|
65
|
-
project: config.project,
|
|
66
|
-
controlRoot: path.resolve(target.controlRoots[0] ?? path.join(config.controlBase, config.project)),
|
|
67
|
-
targetDigest: removalTargetDigest(config, target),
|
|
68
|
-
permitDigest: removalPermitDigest(permits),
|
|
69
|
-
removeWorktree,
|
|
70
|
-
removeBranch,
|
|
71
|
-
removeShare,
|
|
72
|
-
worktreePaths: target.existingWorktrees.map((candidate) => path.resolve(candidate)).sort(),
|
|
73
|
-
workspaceViewPaths: target.workspaceViewRoots.map((candidate) => path.resolve(candidate)).sort(),
|
|
74
|
-
toolPaths: target.toolCandidates.flatMap(({ candidates }) => candidates.map((candidate) => path.resolve(candidate))).sort(),
|
|
75
|
-
shellPaths: shellConfigDirCandidates(config, target.effectiveBranch).map((candidate) => path.resolve(candidate)).sort(),
|
|
76
|
-
sharePath: path.resolve(shareBranchDir(config, target.effectiveBranch)),
|
|
77
|
-
permits: removalPermitCommits(permits)
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
function assertRemovalSelectionMatches(expected, actual) {
|
|
81
|
-
const normalize = (value) => ({
|
|
82
|
-
...value,
|
|
83
|
-
controlRoot: '',
|
|
84
|
-
permits: value.permits
|
|
85
|
-
});
|
|
86
|
-
if (JSON.stringify(normalize(expected)) !== JSON.stringify(normalize(actual))) {
|
|
87
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH');
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
function advanceRemovalJournals(project, target, targetDigest, phase, resourceLocks) {
|
|
91
|
-
const targetIndex = sandboxRemovalPhaseIndex(phase);
|
|
92
|
-
return listSandboxRemovalJournals({
|
|
93
|
-
branch: target.effectiveBranch,
|
|
94
|
-
project,
|
|
95
|
-
targetDigest
|
|
96
|
-
}).map((journal) => {
|
|
97
|
-
let current = journal;
|
|
98
|
-
while (sandboxRemovalPhaseIndex(current.phase) < targetIndex) {
|
|
99
|
-
if (current.phase === 'target-committed' && phase === 'container-absent') {
|
|
100
|
-
const lock = resourceLocks.get(current.target.controlRoot);
|
|
101
|
-
if (!lock)
|
|
102
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_LOCK_MISMATCH');
|
|
103
|
-
current = advanceSandboxRemovalJournalPhase(current, phase, { resourceLock: lock });
|
|
104
|
-
continue;
|
|
105
|
-
}
|
|
106
|
-
const next = SANDBOX_REMOVAL_JOURNAL_PHASES[sandboxRemovalPhaseIndex(current.phase) + 1];
|
|
107
|
-
if (!next)
|
|
108
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_PHASE_TRANSITION_INVALID');
|
|
109
|
-
const lock = resourceLocks.get(current.target.controlRoot);
|
|
110
|
-
if (!lock)
|
|
111
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_LOCK_MISMATCH');
|
|
112
|
-
current = advanceSandboxRemovalJournalPhase(current, next, { resourceLock: lock });
|
|
113
|
-
}
|
|
114
|
-
return current;
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
function prepareRemovalAction(project, target, targetDigest, startPhase, completedPhase, resourceLocks) {
|
|
118
|
-
const journals = listSandboxRemovalJournals({
|
|
119
|
-
branch: target.effectiveBranch,
|
|
120
|
-
project,
|
|
121
|
-
targetDigest
|
|
122
|
-
});
|
|
123
|
-
const startIndex = sandboxRemovalPhaseIndex(startPhase);
|
|
124
|
-
const completedIndex = sandboxRemovalPhaseIndex(completedPhase);
|
|
125
|
-
const shouldRun = journals.length === 0
|
|
126
|
-
|| journals.some((journal) => sandboxRemovalPhaseIndex(journal.phase) < completedIndex);
|
|
127
|
-
const recovering = journals.some((journal) => {
|
|
128
|
-
const index = sandboxRemovalPhaseIndex(journal.phase);
|
|
129
|
-
return index >= startIndex && index < completedIndex;
|
|
130
|
-
});
|
|
131
|
-
advanceRemovalJournals(project, target, targetDigest, startPhase, resourceLocks);
|
|
132
|
-
return { run: shouldRun, recovering };
|
|
133
|
-
}
|
|
134
|
-
function assertRemovalPathsAbsent(paths) {
|
|
135
|
-
const remaining = paths.filter((candidate) => fs.existsSync(candidate));
|
|
136
|
-
if (remaining.length > 0) {
|
|
137
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${remaining[0]}`);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
function assertBranchRemovalIdentity(config, branch, permits) {
|
|
141
|
-
if (!runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', `refs/heads/${branch}`]))
|
|
142
|
-
return;
|
|
143
|
-
const expectedHeads = new Set([...permits.values()]
|
|
144
|
-
.filter((permit) => permit.snapshot.branch === branch)
|
|
145
|
-
.map((permit) => permit.snapshot.head));
|
|
146
|
-
if (expectedHeads.size === 0) {
|
|
147
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
148
|
-
}
|
|
149
|
-
const actualHead = runSafe('git', ['-C', config.repoRoot, 'rev-parse', `refs/heads/${branch}`]);
|
|
150
|
-
if (!expectedHeads.has(actualHead)) {
|
|
151
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
function removalTombstonePath(targetDigest, kind, source) {
|
|
155
|
-
const sourceDigest = createHash('sha256')
|
|
156
|
-
.update(`${kind}\0${path.resolve(source)}`)
|
|
157
|
-
.digest('hex')
|
|
158
|
-
.slice(0, 24);
|
|
159
|
-
return path.join(path.dirname(path.resolve(source)), `.agent-infra-removal-${targetDigest.slice(0, 16)}-${kind}-${sourceDigest}`);
|
|
160
|
-
}
|
|
161
|
-
const REMOVAL_TOMBSTONE_MARKER = '.agent-infra-removal-ownership.json';
|
|
162
|
-
const REMOVAL_TOMBSTONE_PAYLOAD = 'payload';
|
|
163
|
-
function removalSourceClaimPath(source, ownership) {
|
|
164
|
-
const claimDigest = createHash('sha256')
|
|
165
|
-
.update(JSON.stringify(ownership))
|
|
166
|
-
.digest('hex')
|
|
167
|
-
.slice(0, 24);
|
|
168
|
-
return path.join(source, `.agent-infra-removal-source-${claimDigest}.json`);
|
|
169
|
-
}
|
|
170
|
-
function removalSourceIdentity(source) {
|
|
171
|
-
const stat = fs.lstatSync(source, { bigint: true });
|
|
172
|
-
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev === 0n || stat.ino === 0n) {
|
|
173
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
174
|
-
}
|
|
175
|
-
return { dev: String(stat.dev), ino: String(stat.ino) };
|
|
176
|
-
}
|
|
177
|
-
function sameRemovalSourceIdentity(left, right) {
|
|
178
|
-
return left.dev === right.dev && left.ino === right.ino;
|
|
179
|
-
}
|
|
180
|
-
function removalSourceClaimMatches(source, ownership, identity) {
|
|
181
|
-
try {
|
|
182
|
-
const claimPath = removalSourceClaimPath(source, ownership);
|
|
183
|
-
const claimStat = fs.lstatSync(claimPath);
|
|
184
|
-
if (!claimStat.isFile() || claimStat.isSymbolicLink())
|
|
185
|
-
return false;
|
|
186
|
-
const record = JSON.parse(fs.readFileSync(claimPath, 'utf8'));
|
|
187
|
-
return record.version === ownership.version
|
|
188
|
-
&& record.targetDigest === ownership.targetDigest
|
|
189
|
-
&& record.permitDigest === ownership.permitDigest
|
|
190
|
-
&& record.kind === ownership.kind
|
|
191
|
-
&& typeof record.source === 'string'
|
|
192
|
-
&& path.resolve(record.source) === path.resolve(ownership.source)
|
|
193
|
-
&& record.sourceIdentity?.dev === identity.dev
|
|
194
|
-
&& record.sourceIdentity?.ino === identity.ino;
|
|
195
|
-
}
|
|
196
|
-
catch {
|
|
197
|
-
return false;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
function isOwnedRemovalSourceClaim(source, ownership) {
|
|
201
|
-
try {
|
|
202
|
-
const claimPath = removalSourceClaimPath(source, ownership);
|
|
203
|
-
const claimStat = fs.lstatSync(claimPath);
|
|
204
|
-
if (!claimStat.isFile() || claimStat.isSymbolicLink())
|
|
205
|
-
return false;
|
|
206
|
-
const record = JSON.parse(fs.readFileSync(claimPath, 'utf8'));
|
|
207
|
-
return record.version === ownership.version
|
|
208
|
-
&& record.targetDigest === ownership.targetDigest
|
|
209
|
-
&& record.permitDigest === ownership.permitDigest
|
|
210
|
-
&& record.kind === ownership.kind
|
|
211
|
-
&& typeof record.source === 'string'
|
|
212
|
-
&& path.resolve(record.source) === path.resolve(ownership.source);
|
|
213
|
-
}
|
|
214
|
-
catch {
|
|
215
|
-
return false;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
function removeOwnedSourceClaim(source, ownership) {
|
|
219
|
-
try {
|
|
220
|
-
const claimPath = removalSourceClaimPath(source, ownership);
|
|
221
|
-
if (isOwnedRemovalSourceClaim(source, ownership))
|
|
222
|
-
fs.unlinkSync(claimPath);
|
|
223
|
-
}
|
|
224
|
-
catch {
|
|
225
|
-
// Preserve the source when the claim cannot be revalidated.
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
function readRemovalTombstoneRecord(root, tombstone) {
|
|
229
|
-
assertManagedPath(root, tombstone);
|
|
230
|
-
try {
|
|
231
|
-
const tombstoneStat = fs.lstatSync(tombstone);
|
|
232
|
-
const markerStat = fs.lstatSync(removalTombstoneMarker(tombstone));
|
|
233
|
-
if (!tombstoneStat.isDirectory() || tombstoneStat.isSymbolicLink()
|
|
234
|
-
|| !markerStat.isFile() || markerStat.isSymbolicLink())
|
|
235
|
-
return null;
|
|
236
|
-
const record = JSON.parse(fs.readFileSync(removalTombstoneMarker(tombstone), 'utf8'));
|
|
237
|
-
if (record.version !== 1
|
|
238
|
-
|| typeof record.targetDigest !== 'string'
|
|
239
|
-
|| typeof record.permitDigest !== 'string'
|
|
240
|
-
|| typeof record.kind !== 'string'
|
|
241
|
-
|| typeof record.source !== 'string'
|
|
242
|
-
|| record.sourceIdentity?.dev === undefined
|
|
243
|
-
|| record.sourceIdentity.ino === undefined)
|
|
244
|
-
return null;
|
|
245
|
-
return record;
|
|
246
|
-
}
|
|
247
|
-
catch {
|
|
248
|
-
return null;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
function removalTombstonePayload(tombstone) {
|
|
252
|
-
return path.join(tombstone, REMOVAL_TOMBSTONE_PAYLOAD);
|
|
253
|
-
}
|
|
254
|
-
function removalTombstoneMarker(tombstone) {
|
|
255
|
-
return path.join(tombstone, REMOVAL_TOMBSTONE_MARKER);
|
|
256
|
-
}
|
|
257
|
-
function isOwnedRemovalTombstone(root, tombstone, ownership) {
|
|
258
|
-
const record = readRemovalTombstoneRecord(root, tombstone);
|
|
259
|
-
return record !== null
|
|
260
|
-
&& record.version === 1
|
|
261
|
-
&& record.targetDigest === ownership.targetDigest
|
|
262
|
-
&& record.permitDigest === ownership.permitDigest
|
|
263
|
-
&& record.kind === ownership.kind
|
|
264
|
-
&& typeof record.source === 'string'
|
|
265
|
-
&& path.resolve(record.source) === path.resolve(ownership.source);
|
|
266
|
-
}
|
|
267
|
-
function isOwnedRemovalPayload(root, tombstone, ownership) {
|
|
268
|
-
const record = readRemovalTombstoneRecord(root, tombstone);
|
|
269
|
-
if (!record || record.targetDigest !== ownership.targetDigest
|
|
270
|
-
|| record.permitDigest !== ownership.permitDigest
|
|
271
|
-
|| record.kind !== ownership.kind
|
|
272
|
-
|| path.resolve(record.source) !== path.resolve(ownership.source))
|
|
273
|
-
return false;
|
|
274
|
-
try {
|
|
275
|
-
const payload = removalTombstonePayload(tombstone);
|
|
276
|
-
const payloadIdentity = removalSourceIdentity(payload);
|
|
277
|
-
return sameRemovalSourceIdentity(payloadIdentity, record.sourceIdentity)
|
|
278
|
-
&& removalSourceClaimMatches(payload, ownership, record.sourceIdentity);
|
|
279
|
-
}
|
|
280
|
-
catch {
|
|
281
|
-
return false;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
function assertOwnedRemovalTombstone(root, tombstone, ownership) {
|
|
285
|
-
if (!isOwnedRemovalTombstone(root, tombstone, ownership)) {
|
|
286
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${ownership.source}`);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
function shouldStageManagedRemoval(source, tombstone, recovering) {
|
|
290
|
-
return fs.existsSync(source) || (recovering && fs.existsSync(tombstone));
|
|
291
|
-
}
|
|
292
|
-
function stageManagedRemoval(root, source, tombstone, recovering, ownership) {
|
|
293
|
-
assertManagedPath(root, source);
|
|
294
|
-
assertManagedPath(root, tombstone);
|
|
295
|
-
const sourceExists = fs.existsSync(source);
|
|
296
|
-
const tombstoneExists = fs.existsSync(tombstone);
|
|
297
|
-
if (tombstoneExists) {
|
|
298
|
-
assertOwnedRemovalTombstone(root, tombstone, ownership);
|
|
299
|
-
if (sourceExists) {
|
|
300
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
301
|
-
}
|
|
302
|
-
if (recovering) {
|
|
303
|
-
if (!isOwnedRemovalPayload(root, tombstone, ownership)) {
|
|
304
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
305
|
-
}
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
309
|
-
}
|
|
310
|
-
if (recovering) {
|
|
311
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${source}`);
|
|
312
|
-
}
|
|
313
|
-
if (!sourceExists)
|
|
314
|
-
return;
|
|
315
|
-
// The operator authorizes cleanup of this managed target after execution stops.
|
|
316
|
-
// Path checks detect conflicts; they do not provide an atomic source-instance move.
|
|
317
|
-
const expectedIdentity = removalSourceIdentity(source);
|
|
318
|
-
const claimPath = removalSourceClaimPath(source, ownership);
|
|
319
|
-
try {
|
|
320
|
-
fs.writeFileSync(claimPath, `${JSON.stringify({ ...ownership, sourceIdentity: expectedIdentity })}\n`, {
|
|
321
|
-
encoding: 'utf8',
|
|
322
|
-
mode: 0o600,
|
|
323
|
-
flag: 'wx'
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
|
-
catch {
|
|
327
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
328
|
-
}
|
|
329
|
-
if (!sameRemovalSourceIdentity(expectedIdentity, removalSourceIdentity(source))) {
|
|
330
|
-
removeOwnedSourceClaim(source, ownership);
|
|
331
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
332
|
-
}
|
|
333
|
-
let moved = false;
|
|
334
|
-
try {
|
|
335
|
-
fs.mkdirSync(tombstone, { mode: 0o700 });
|
|
336
|
-
fs.writeFileSync(removalTombstoneMarker(tombstone), `${JSON.stringify({ ...ownership, sourceIdentity: expectedIdentity })}\n`, {
|
|
337
|
-
encoding: 'utf8',
|
|
338
|
-
mode: 0o600,
|
|
339
|
-
flag: 'wx'
|
|
340
|
-
});
|
|
341
|
-
fs.renameSync(source, removalTombstonePayload(tombstone));
|
|
342
|
-
moved = true;
|
|
343
|
-
if (!isOwnedRemovalPayload(root, tombstone, ownership)) {
|
|
344
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
catch (error) {
|
|
348
|
-
if (!moved)
|
|
349
|
-
removeOwnedSourceClaim(source, ownership);
|
|
350
|
-
throw error;
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
function cleanupManagedTombstones(root, targetDigest, permitDigest, kind, sources) {
|
|
354
|
-
for (const source of sources) {
|
|
355
|
-
const tombstone = removalTombstonePath(targetDigest, kind, source);
|
|
356
|
-
if (!fs.existsSync(tombstone))
|
|
357
|
-
continue;
|
|
358
|
-
const ownership = { version: 1, targetDigest, permitDigest, kind, source };
|
|
359
|
-
if (!isOwnedRemovalTombstone(root, tombstone, ownership))
|
|
360
|
-
continue;
|
|
361
|
-
if (!isOwnedRemovalPayload(root, tombstone, ownership)) {
|
|
362
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
|
|
363
|
-
}
|
|
364
|
-
removeManagedDir(root, tombstone);
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
function branchRemovalTombstoneRef(targetDigest) {
|
|
368
|
-
return `refs/agent-infra/sandbox-removal/${targetDigest}/branch`;
|
|
369
|
-
}
|
|
370
|
-
function branchPermitHead(branch, permits) {
|
|
371
|
-
const heads = new Set([...permits.values()]
|
|
372
|
-
.filter((permit) => permit.snapshot.branch === branch)
|
|
373
|
-
.map((permit) => permit.snapshot.head));
|
|
374
|
-
return heads.size === 1 ? [...heads][0] : null;
|
|
375
|
-
}
|
|
376
|
-
function stageBranchRemoval(config, branch, targetDigest, permits, recovering) {
|
|
377
|
-
const expectedHead = branchPermitHead(branch, permits);
|
|
378
|
-
if (!expectedHead)
|
|
379
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
380
|
-
const branchName = `refs/heads/${branch}`;
|
|
381
|
-
const tombstone = branchRemovalTombstoneRef(targetDigest);
|
|
382
|
-
const branchExists = runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', branchName]);
|
|
383
|
-
const tombstoneExists = runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', tombstone]);
|
|
384
|
-
if (branchExists && tombstoneExists) {
|
|
385
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
386
|
-
}
|
|
387
|
-
if (recovering) {
|
|
388
|
-
if (branchExists && !tombstoneExists) {
|
|
389
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${branch}`);
|
|
390
|
-
}
|
|
391
|
-
if (tombstoneExists && runSafe('git', ['-C', config.repoRoot, 'rev-parse', tombstone]) !== expectedHead) {
|
|
392
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
393
|
-
}
|
|
394
|
-
return;
|
|
395
|
-
}
|
|
396
|
-
if (!branchExists)
|
|
397
|
-
return;
|
|
398
|
-
assertBranchRemovalIdentity(config, branch, permits);
|
|
399
|
-
const actualHead = runSafe('git', ['-C', config.repoRoot, 'rev-parse', branchName]);
|
|
400
|
-
if (!runOk('git', ['-C', config.repoRoot, 'update-ref', tombstone, actualHead, '0'.repeat(40)])) {
|
|
401
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
402
|
-
}
|
|
403
|
-
if (!runOk('git', ['-C', config.repoRoot, 'update-ref', '-d', branchName, actualHead])) {
|
|
404
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
function cleanupBranchTombstone(config, branch, targetDigest, permits) {
|
|
408
|
-
const tombstone = branchRemovalTombstoneRef(targetDigest);
|
|
409
|
-
if (!runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', tombstone]))
|
|
410
|
-
return;
|
|
411
|
-
const expectedHead = branchPermitHead(branch, permits);
|
|
412
|
-
if (!expectedHead || runSafe('git', ['-C', config.repoRoot, 'rev-parse', tombstone]) !== expectedHead) {
|
|
413
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
414
|
-
}
|
|
415
|
-
if (!runOk('git', ['-C', config.repoRoot, 'update-ref', '-d', tombstone, expectedHead])) {
|
|
416
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
function worktreeRegistration(config, worktree) {
|
|
420
|
-
const lines = runSafe('git', ['-C', config.repoRoot, 'worktree', 'list', '--porcelain']).split('\n');
|
|
421
|
-
let current = null;
|
|
422
|
-
const flush = () => {
|
|
423
|
-
if (!current || path.resolve(current.path) !== path.resolve(worktree))
|
|
424
|
-
return null;
|
|
425
|
-
return { head: current.head, branch: current.branch };
|
|
426
|
-
};
|
|
427
|
-
for (const line of lines) {
|
|
428
|
-
if (line.startsWith('worktree ')) {
|
|
429
|
-
const previous = flush();
|
|
430
|
-
if (previous)
|
|
431
|
-
return previous;
|
|
432
|
-
current = { path: line.slice('worktree '.length), head: '', branch: null };
|
|
433
|
-
}
|
|
434
|
-
else if (current && line.startsWith('HEAD ')) {
|
|
435
|
-
current.head = line.slice('HEAD '.length);
|
|
436
|
-
}
|
|
437
|
-
else if (current && line.startsWith('branch ')) {
|
|
438
|
-
current.branch = line.slice('branch '.length);
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
return flush();
|
|
442
|
-
}
|
|
443
|
-
function assertWorktreeRegistrationIdentity(config, worktree, permit) {
|
|
444
|
-
const registration = worktreeRegistration(config, worktree);
|
|
445
|
-
if (!registration)
|
|
446
|
-
return;
|
|
447
|
-
if (registration.head !== permit.snapshot.head
|
|
448
|
-
|| registration.branch !== `refs/heads/${permit.snapshot.branch}`) {
|
|
449
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${worktree}`);
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
function pruneWorktreeRegistration(config, worktree) {
|
|
453
|
-
runSafe('git', ['-C', config.repoRoot, 'worktree', 'prune']);
|
|
454
|
-
if (worktreeRegistration(config, worktree)) {
|
|
455
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${worktree}`);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
function stageWorktreeRemoval(config, worktree, permit, tombstone, recovering, ownership) {
|
|
459
|
-
assertManagedPath(config.worktreeBase, worktree);
|
|
460
|
-
assertManagedPath(config.worktreeBase, tombstone);
|
|
461
|
-
const worktreeExists = fs.existsSync(worktree);
|
|
462
|
-
const tombstoneExists = fs.existsSync(tombstone);
|
|
463
|
-
if (worktreeExists || !recovering)
|
|
464
|
-
verifyWorktreePermit(permit);
|
|
465
|
-
if (recovering) {
|
|
466
|
-
if (worktreeExists || !tombstoneExists) {
|
|
467
|
-
if (worktreeExists && tombstoneExists) {
|
|
468
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${worktree}`);
|
|
469
|
-
}
|
|
470
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${worktree}`);
|
|
471
|
-
}
|
|
472
|
-
assertOwnedRemovalTombstone(config.worktreeBase, tombstone, ownership);
|
|
473
|
-
assertWorktreeRegistrationIdentity(config, worktree, permit);
|
|
474
|
-
pruneWorktreeRegistration(config, worktree);
|
|
475
|
-
return;
|
|
476
|
-
}
|
|
477
|
-
if (!worktreeExists)
|
|
478
|
-
return;
|
|
479
|
-
stageManagedRemoval(config.worktreeBase, worktree, tombstone, false, ownership);
|
|
480
|
-
pruneWorktreeRegistration(config, worktree);
|
|
481
|
-
}
|
|
482
|
-
function cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest) {
|
|
483
|
-
const journals = listSandboxRemovalJournals({
|
|
484
|
-
branch: target.effectiveBranch,
|
|
485
|
-
project: config.project,
|
|
486
|
-
targetDigest
|
|
487
|
-
});
|
|
488
|
-
if (journals.length === 0)
|
|
489
|
-
return;
|
|
490
|
-
const completed = (phase) => journals.every((journal) => (sandboxRemovalPhaseIndex(journal.phase) >= sandboxRemovalPhaseIndex(phase)));
|
|
491
|
-
if (completed('workspace-removed')) {
|
|
492
|
-
cleanupManagedTombstones(config.workspaceViewBase, targetDigest, committedTarget.permitDigest, 'workspace', target.workspaceViewRoots);
|
|
493
|
-
cleanupManagedTombstones(path.join(config.controlBase, config.project), targetDigest, committedTarget.permitDigest, 'workspace', target.controlRoots);
|
|
494
|
-
cleanupManagedTombstones(config.worktreeBase, targetDigest, committedTarget.permitDigest, 'worktree', committedTarget.worktreePaths);
|
|
495
|
-
}
|
|
496
|
-
if (completed('branch-removed')) {
|
|
497
|
-
cleanupBranchTombstone(config, target.effectiveBranch, targetDigest, new Map(committedTarget.permits.map((permit) => [path.resolve(permit.path), {
|
|
498
|
-
mode: permit.mode,
|
|
499
|
-
snapshot: permit.snapshot
|
|
500
|
-
}])));
|
|
501
|
-
}
|
|
502
|
-
if (completed('tool-removed')) {
|
|
503
|
-
cleanupManagedTombstones(config.home, targetDigest, committedTarget.permitDigest, 'tool', committedTarget.toolPaths);
|
|
504
|
-
}
|
|
505
|
-
if (completed('shell-removed')) {
|
|
506
|
-
cleanupManagedTombstones(config.shellConfigBase, targetDigest, committedTarget.permitDigest, 'shell', committedTarget.shellPaths);
|
|
507
|
-
}
|
|
508
|
-
if (completed('share-removed')) {
|
|
509
|
-
cleanupManagedTombstones(config.shareBase, targetDigest, committedTarget.permitDigest, 'share', [committedTarget.sharePath]);
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
function removalActionPaths(target, config, phase) {
|
|
513
|
-
if (phase === 'workspace-removed') {
|
|
514
|
-
return [...target.workspaceViewRoots, ...target.controlRoots];
|
|
515
|
-
}
|
|
516
|
-
if (phase === 'tool-removed') {
|
|
517
|
-
return target.toolCandidates.flatMap(({ candidates }) => candidates);
|
|
518
|
-
}
|
|
519
|
-
if (phase === 'shell-removed') {
|
|
520
|
-
return shellConfigDirCandidates(config, target.effectiveBranch);
|
|
521
|
-
}
|
|
522
|
-
if (phase === 'share-removed') {
|
|
523
|
-
return [shareBranchDir(config, target.effectiveBranch)];
|
|
524
|
-
}
|
|
525
|
-
return [];
|
|
526
|
-
}
|
|
527
|
-
function permitsFromJournal(journals, target, expectedTargetDigest) {
|
|
528
|
-
const permits = new Map();
|
|
529
|
-
for (const journal of journals) {
|
|
530
|
-
if (journal.target.targetDigest !== expectedTargetDigest)
|
|
531
|
-
continue;
|
|
532
|
-
if (journal.target.branch !== target.effectiveBranch) {
|
|
533
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH');
|
|
534
|
-
}
|
|
535
|
-
for (const entry of journal.target.permits) {
|
|
536
|
-
if (path.resolve(entry.path) !== path.resolve(entry.snapshot.worktree)) {
|
|
537
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_PERMIT_MISMATCH');
|
|
538
|
-
}
|
|
539
|
-
permits.set(path.resolve(entry.path), {
|
|
540
|
-
mode: entry.mode,
|
|
541
|
-
snapshot: entry.snapshot
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
return permits;
|
|
546
|
-
}
|
|
547
|
-
export function sandboxManagedPathKey(candidate, platform = process.platform, resolveExistingPath = (resolved) => fs.realpathSync.native(resolved)) {
|
|
548
|
-
const resolved = path.resolve(candidate);
|
|
549
|
-
let identity = resolved;
|
|
550
|
-
try {
|
|
551
|
-
identity = resolveExistingPath(resolved);
|
|
552
|
-
}
|
|
553
|
-
catch (error) {
|
|
554
|
-
if (!isMissingPathError(error)) {
|
|
555
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: unable to determine managed path identity for '${resolved}'`);
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
return platform === 'win32' ? identity.toLowerCase() : identity;
|
|
559
|
-
}
|
|
560
|
-
function recoveryContexts(config, target, worktrees) {
|
|
561
|
-
const candidates = worktreeDirCandidates(config, target.effectiveBranch).map((candidate) => path.resolve(candidate));
|
|
562
|
-
const existingCandidates = candidates.filter((candidate) => fs.existsSync(candidate));
|
|
563
|
-
if (existingCandidates.length !== 1)
|
|
564
|
-
return new Map();
|
|
565
|
-
const contexts = new Map();
|
|
566
|
-
for (const worktree of worktrees) {
|
|
567
|
-
const resolvedWorktree = path.resolve(worktree);
|
|
568
|
-
if (resolvedWorktree !== existingCandidates[0])
|
|
569
|
-
continue;
|
|
570
|
-
for (const root of target.controlRoots.filter((candidate) => fs.existsSync(candidate))) {
|
|
571
|
-
assertLegacyCandidateEvidence(root, config.controlBase, config, target.effectiveBranch, target.matchedContainers);
|
|
572
|
-
assertControlRootMatchesTarget(root, target.effectiveBranch, target.workspace);
|
|
573
|
-
}
|
|
574
|
-
contexts.set(resolvedWorktree, {
|
|
575
|
-
repoRoot: config.repoRoot,
|
|
576
|
-
worktreeBase: config.worktreeBase,
|
|
577
|
-
branch: target.effectiveBranch,
|
|
578
|
-
identitySource: target.workspace.mode,
|
|
579
|
-
taskId: target.workspace.mode === 'task-bound' ? target.workspace.taskId : null
|
|
580
|
-
});
|
|
581
|
-
}
|
|
582
|
-
return contexts;
|
|
583
|
-
}
|
|
584
|
-
function resolveRmTarget(config, tools, cleanupTarget, options = {}) {
|
|
585
|
-
assertValidBranchName(cleanupTarget.branch);
|
|
13
|
+
function resolveMissingTaskSandboxBranch(taskId, config) {
|
|
586
14
|
const engine = detectEngine(config);
|
|
587
|
-
const
|
|
588
|
-
const
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
const existing = runEngine(engine, 'docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
|
|
596
|
-
const matchedContainers = options.discoveredContainers
|
|
597
|
-
? options.discoveredContainers.map((container) => {
|
|
598
|
-
if (!existing.includes(container)) {
|
|
599
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: discovered container '${container}' is no longer present`);
|
|
600
|
-
}
|
|
601
|
-
return container;
|
|
602
|
-
})
|
|
603
|
-
: containerNameCandidates(config, branch).filter((name) => existing.includes(name));
|
|
604
|
-
const workspace = cleanupTarget.workspace;
|
|
605
|
-
const identities = [workspace];
|
|
606
|
-
const containers = options.discoveredContainers
|
|
607
|
-
? matchedContainers
|
|
608
|
-
: [...new Set([...containerNameCandidates(config, effectiveBranch), ...matchedContainers])];
|
|
609
|
-
const controlRoots = containers.flatMap((container) => identities.map((identity) => sandboxControlPaths({
|
|
610
|
-
base: config.controlBase, project: config.project, container, identity
|
|
611
|
-
}).root));
|
|
612
|
-
const workspaceViewRoots = containers.flatMap((container) => identities.map((identity) => sandboxWorkspaceViewPaths({
|
|
613
|
-
base: config.workspaceViewBase, project: config.project, container, identity
|
|
614
|
-
}).root));
|
|
615
|
-
const managedPathCandidates = [...new Set([
|
|
616
|
-
...worktreeCandidates,
|
|
617
|
-
...toolCandidates.flatMap(({ candidates }) => candidates),
|
|
618
|
-
...shellCandidates,
|
|
619
|
-
shareBranchDir(config, branch),
|
|
620
|
-
...controlRoots,
|
|
621
|
-
...workspaceViewRoots
|
|
622
|
-
].map((candidate) => path.resolve(candidate)))];
|
|
623
|
-
return {
|
|
624
|
-
branch,
|
|
625
|
-
effectiveBranch,
|
|
626
|
-
engine,
|
|
627
|
-
matchedContainers,
|
|
628
|
-
existingWorktrees: worktreeCandidates.filter((candidate) => fs.existsSync(candidate)),
|
|
629
|
-
toolCandidates,
|
|
630
|
-
managedPathCandidates,
|
|
631
|
-
workspace,
|
|
632
|
-
controlRoots: [...new Set(controlRoots)],
|
|
633
|
-
workspaceViewRoots: [...new Set(workspaceViewRoots)]
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
function inspectNamedContainerIdentity(target, container) {
|
|
637
|
-
const raw = runSafeEngine(target.engine, 'docker', [
|
|
638
|
-
'inspect', '--format', '{{json .}}', container
|
|
639
|
-
]).trim();
|
|
640
|
-
let parsed;
|
|
641
|
-
try {
|
|
642
|
-
parsed = JSON.parse(raw);
|
|
643
|
-
}
|
|
644
|
-
catch {
|
|
645
|
-
throw new Error(`SANDBOX_WORKSPACE_IDENTITY_UNKNOWN: container '${container}' inspection is invalid`);
|
|
646
|
-
}
|
|
647
|
-
const value = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
|
|
648
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
649
|
-
throw new Error(`SANDBOX_WORKSPACE_IDENTITY_UNKNOWN: container '${container}' inspection is incomplete`);
|
|
650
|
-
}
|
|
651
|
-
const candidate = value;
|
|
652
|
-
if (typeof candidate.Id !== 'string' || !candidate.Id
|
|
653
|
-
|| !candidate.Config?.Labels || typeof candidate.Config.Labels !== 'object'
|
|
654
|
-
|| Array.isArray(candidate.Config.Labels)
|
|
655
|
-
|| Object.values(candidate.Config.Labels).some((value) => typeof value !== 'string')) {
|
|
656
|
-
throw new Error(`SANDBOX_WORKSPACE_IDENTITY_UNKNOWN: container '${container}' inspection is incomplete`);
|
|
657
|
-
}
|
|
658
|
-
return { id: candidate.Id, labels: candidate.Config.Labels };
|
|
659
|
-
}
|
|
660
|
-
function assertMatchedContainerIdentities(config, target) {
|
|
661
|
-
const current = new Map();
|
|
662
|
-
for (const container of target.matchedContainers) {
|
|
663
|
-
const observation = inspectNamedContainerIdentity(target, container);
|
|
664
|
-
const stringLabels = observation.labels;
|
|
665
|
-
const branch = stringLabels[sandboxBranchLabel(config)];
|
|
666
|
-
if (branch !== target.branch) {
|
|
667
|
-
throw new Error(`SANDBOX_WORKSPACE_IDENTITY_CONFLICT: container '${container}' branch is ${JSON.stringify(branch ?? null)}, `
|
|
668
|
-
+ `but this request is ${JSON.stringify(target.branch)}`);
|
|
669
|
-
}
|
|
670
|
-
const identity = parseSandboxWorkspaceIdentity(stringLabels, {
|
|
671
|
-
mode: sandboxWorkspaceModeLabel(config),
|
|
672
|
-
taskId: sandboxTaskIdLabel(config)
|
|
673
|
-
});
|
|
674
|
-
if (identity.mode === 'legacy-invalid' || !sameSandboxWorkspaceIdentity(identity, target.workspace)) {
|
|
675
|
-
const existingDescription = identity.mode === 'task-bound'
|
|
676
|
-
? `task-bound:${identity.taskId}`
|
|
677
|
-
: identity.mode;
|
|
678
|
-
const requestedDescription = target.workspace.mode === 'task-bound'
|
|
679
|
-
? `task-bound:${target.workspace.taskId}`
|
|
680
|
-
: target.workspace.mode;
|
|
681
|
-
throw new Error(`SANDBOX_WORKSPACE_IDENTITY_CONFLICT: container '${container}' is ${existingDescription}, `
|
|
682
|
-
+ `but this request is ${requestedDescription}`);
|
|
683
|
-
}
|
|
684
|
-
current.set(container, observation);
|
|
685
|
-
}
|
|
686
|
-
return current;
|
|
687
|
-
}
|
|
688
|
-
function controlRootContainer(config, root) {
|
|
689
|
-
const relative = path.relative(path.join(config.controlBase, config.project), root);
|
|
690
|
-
const [container, identity, ...extra] = relative.split(path.sep);
|
|
691
|
-
if (!container || !identity || extra.length > 0) {
|
|
692
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_INVALID: ${root}`);
|
|
693
|
-
}
|
|
694
|
-
return container;
|
|
695
|
-
}
|
|
696
|
-
function assertControlRootMatchesTarget(root, effectiveBranch, workspace) {
|
|
697
|
-
const manifestPath = path.join(root, 'manifest.json');
|
|
698
|
-
if (!fs.existsSync(manifestPath)) {
|
|
699
|
-
if (workspace.mode === 'task-bound') {
|
|
700
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: ${root}`);
|
|
701
|
-
}
|
|
702
|
-
return;
|
|
703
|
-
}
|
|
704
|
-
const manifest = readSandboxControlManifest(manifestPath);
|
|
705
|
-
const identityMatches = workspace.mode === 'task-bound'
|
|
706
|
-
? manifest.mode === 'task-bound' && manifest.taskId === workspace.taskId
|
|
707
|
-
: manifest.mode === 'branch-only';
|
|
708
|
-
if (manifest.branch !== effectiveBranch || !identityMatches) {
|
|
709
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_MISMATCH: ${root}`);
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
function preflightRmTarget(config, target) {
|
|
713
|
-
const current = assertMatchedContainerIdentities(config, target);
|
|
714
|
-
const manifests = [];
|
|
715
|
-
for (const root of target.controlRoots.filter((candidate) => fs.existsSync(candidate))) {
|
|
716
|
-
assertLegacyCandidateEvidence(root, config.controlBase, config, target.effectiveBranch, target.matchedContainers);
|
|
717
|
-
assertControlRootMatchesTarget(root, target.effectiveBranch, target.workspace);
|
|
718
|
-
const manifestPath = path.join(root, 'manifest.json');
|
|
719
|
-
if (!fs.existsSync(manifestPath))
|
|
720
|
-
continue;
|
|
721
|
-
const manifest = readSandboxControlManifest(manifestPath);
|
|
722
|
-
const rootContainer = controlRootContainer(config, root);
|
|
723
|
-
if (manifest.container !== rootContainer) {
|
|
724
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_MISMATCH: ${root}`);
|
|
725
|
-
}
|
|
726
|
-
const observed = current.get(manifest.container);
|
|
727
|
-
if (observed && (observed.id !== manifest.containerIdentity.id
|
|
728
|
-
|| Object.entries(manifest.containerIdentity.labels).some(([key, value]) => observed.labels[key] !== value))) {
|
|
729
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_MISMATCH: ${root}`);
|
|
730
|
-
}
|
|
731
|
-
manifests.push(manifest);
|
|
732
|
-
}
|
|
733
|
-
if (target.workspace.mode !== 'task-bound')
|
|
734
|
-
return;
|
|
735
|
-
const matched = new Set(target.matchedContainers);
|
|
736
|
-
const manifestContainers = manifests.map((manifest) => manifest.container);
|
|
737
|
-
if (matched.size > 0 && manifestContainers.some((container) => !matched.has(container))) {
|
|
738
|
-
throw new Error('SANDBOX_CONTROL_TARGET_MISMATCH: manifest container is outside the cleanup target');
|
|
739
|
-
}
|
|
740
|
-
for (const container of matched) {
|
|
741
|
-
const matches = manifests.filter((manifest) => manifest.container === container);
|
|
742
|
-
if (matches.length !== 1) {
|
|
743
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: container '${container}'`);
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
if (matched.size === 0 && manifests.length > 0) {
|
|
747
|
-
const supported = new Set(containerNameCandidates(config, target.effectiveBranch));
|
|
748
|
-
if (manifests.some((manifest) => !supported.has(manifest.container))) {
|
|
749
|
-
throw new Error('SANDBOX_CONTROL_TARGET_MISMATCH: manifest container is outside the cleanup target');
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
function assertCleanupGroupPathsDoNotOverlap(groups) {
|
|
754
|
-
const owners = new Map();
|
|
755
|
-
for (const group of groups) {
|
|
756
|
-
for (const candidate of group.target.managedPathCandidates ?? []) {
|
|
757
|
-
const key = sandboxManagedPathKey(candidate);
|
|
758
|
-
const existingBranch = owners.get(key);
|
|
759
|
-
if (existingBranch && existingBranch !== group.cleanupTarget.branch) {
|
|
760
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: managed path '${candidate}' is shared by branches `
|
|
761
|
-
+ `${JSON.stringify(existingBranch)} and ${JSON.stringify(group.cleanupTarget.branch)}`);
|
|
762
|
-
}
|
|
763
|
-
owners.set(key, group.cleanupTarget.branch);
|
|
764
|
-
}
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
function assertWorktreeBranchesMatchGroups(groups, inspections) {
|
|
768
|
-
const byPath = new Map(inspections.flatMap((inspection) => inspection.status === 'failed'
|
|
769
|
-
? []
|
|
770
|
-
: [[sandboxManagedPathKey(inspection.snapshot.worktree), inspection.snapshot.branch]]));
|
|
771
|
-
for (const group of groups) {
|
|
772
|
-
for (const worktree of group.target.existingWorktrees) {
|
|
773
|
-
const registeredBranch = byPath.get(sandboxManagedPathKey(worktree));
|
|
774
|
-
if (registeredBranch && registeredBranch !== group.cleanupTarget.branch) {
|
|
775
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: worktree '${worktree}' is registered to branch `
|
|
776
|
-
+ `${JSON.stringify(registeredBranch)}, but cleanup targets ${JSON.stringify(group.cleanupTarget.branch)}`);
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
function assertLegacyCandidateEvidence(candidate, base, config, effectiveBranch, matchedContainers) {
|
|
782
|
-
const relative = path.relative(path.join(base, config.project), candidate);
|
|
783
|
-
const [container, identity] = relative.split(path.sep);
|
|
784
|
-
const [canonical, legacy] = containerNameCandidates(config, effectiveBranch);
|
|
785
|
-
if (!container || !identity || legacy === canonical || container !== legacy || matchedContainers.includes(container))
|
|
786
|
-
return;
|
|
787
|
-
const manifestPath = path.join(config.controlBase, config.project, container, identity, 'manifest.json');
|
|
788
|
-
if (!fs.existsSync(manifestPath)) {
|
|
789
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: ${candidate}`);
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
function assertRemoved(target, label) {
|
|
793
|
-
if (fs.existsSync(target))
|
|
794
|
-
throw new Error(`${label} still exists after removal: ${target}`);
|
|
795
|
-
}
|
|
796
|
-
function removeEmptyManagedParent(base, directory) {
|
|
797
|
-
const parent = path.dirname(directory);
|
|
798
|
-
if (path.resolve(parent) === path.resolve(base))
|
|
799
|
-
return;
|
|
800
|
-
assertManagedPath(base, parent);
|
|
801
|
-
try {
|
|
802
|
-
fs.rmdirSync(parent);
|
|
803
|
-
}
|
|
804
|
-
catch (error) {
|
|
805
|
-
if (['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
|
|
806
|
-
return;
|
|
807
|
-
throw error;
|
|
808
|
-
}
|
|
809
|
-
assertRemoved(parent, 'Empty sandbox container directory');
|
|
810
|
-
}
|
|
811
|
-
async function removeExactSandboxContainer(engine, manifest, timeoutMs) {
|
|
812
|
-
const deadlineAt = Date.now() + timeoutMs;
|
|
813
|
-
const remaining = () => Math.max(1, deadlineAt - Date.now());
|
|
814
|
-
const inspect = () => inspectSandboxControlContainer(manifest, { timeoutMs: remaining() });
|
|
815
|
-
const runAuthorityCommand = (args) => {
|
|
816
|
-
const command = manifest.authorityEvidence
|
|
817
|
-
? commandForSandboxAuthority(manifest.authorityEvidence, 'docker', args)
|
|
818
|
-
: null;
|
|
819
|
-
return command ? runOk(command.cmd, command.args, { timeout: remaining() })
|
|
820
|
-
: runOkEngine(engine, 'docker', args, { timeout: remaining() });
|
|
821
|
-
};
|
|
822
|
-
const before = await inspect();
|
|
823
|
-
if (before.state === 'unknown')
|
|
824
|
-
throw new Error(`SANDBOX_CONTROL_CONTAINER_UNKNOWN: ${before.reason}`);
|
|
825
|
-
if (before.state === 'absent')
|
|
826
|
-
return;
|
|
827
|
-
if (before.running && !runAuthorityCommand(['stop', '--timeout', '1', manifest.containerIdentity.id])) {
|
|
828
|
-
const afterStop = await inspect();
|
|
829
|
-
if (afterStop.state !== 'absent' && afterStop.state !== 'found') {
|
|
830
|
-
throw new Error(`SANDBOX_CONTROL_CONTAINER_UNKNOWN: ${afterStop.reason}`);
|
|
831
|
-
}
|
|
832
|
-
if (afterStop.state === 'found' && afterStop.running) {
|
|
833
|
-
throw new Error(`Failed to stop sandbox container: ${manifest.containerIdentity.id}`);
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
const afterStop = await inspect();
|
|
837
|
-
if (afterStop.state === 'unknown')
|
|
838
|
-
throw new Error(`SANDBOX_CONTROL_CONTAINER_UNKNOWN: ${afterStop.reason}`);
|
|
839
|
-
if (afterStop.state === 'found' && !runAuthorityCommand(['rm', manifest.containerIdentity.id])) {
|
|
840
|
-
const afterRemove = await inspect();
|
|
841
|
-
if (afterRemove.state !== 'absent') {
|
|
842
|
-
throw new Error(`Failed to remove sandbox container: ${manifest.containerIdentity.id}`);
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
async function removeProjectControlRoots(config, engine) {
|
|
847
|
-
const containers = new Set();
|
|
848
|
-
const projectRoot = path.join(config.controlBase, config.project);
|
|
849
|
-
if (!fs.existsSync(projectRoot))
|
|
850
|
-
return containers;
|
|
851
|
-
assertManagedPath(config.controlBase, projectRoot);
|
|
852
|
-
const projectStat = fs.lstatSync(projectRoot);
|
|
853
|
-
if (!projectStat.isDirectory() || projectStat.isSymbolicLink())
|
|
854
|
-
throw new Error('SANDBOX_CONTROL_CHANNEL_INVALID');
|
|
855
|
-
for (const container of fs.readdirSync(projectRoot, { withFileTypes: true })) {
|
|
856
|
-
if (!container.isDirectory() || container.isSymbolicLink())
|
|
857
|
-
continue;
|
|
858
|
-
const containerRoot = path.join(projectRoot, container.name);
|
|
859
|
-
for (const identity of fs.readdirSync(containerRoot, { withFileTypes: true })) {
|
|
860
|
-
if (!identity.isDirectory() || identity.isSymbolicLink())
|
|
861
|
-
continue;
|
|
862
|
-
const root = path.join(containerRoot, identity.name);
|
|
863
|
-
const manifestPath = path.join(root, 'manifest.json');
|
|
864
|
-
if (!fs.existsSync(manifestPath))
|
|
865
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: ${root}`);
|
|
866
|
-
const manifest = readSandboxControlManifest(manifestPath);
|
|
867
|
-
containers.add(manifest.container);
|
|
868
|
-
await removeSandboxControlRoot(root, {
|
|
869
|
-
inspectContainer: (timeoutMs) => inspectSandboxControlContainer(manifest, { timeoutMs }),
|
|
870
|
-
removeContainer: (timeoutMs) => removeExactSandboxContainer(engine, manifest, timeoutMs)
|
|
871
|
-
});
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
return containers;
|
|
875
|
-
}
|
|
876
|
-
function inspectionBlockers(inspections) {
|
|
877
|
-
return inspections.filter((inspection) => inspection.status !== 'clean');
|
|
878
|
-
}
|
|
879
|
-
function blockerMessage(blockers) {
|
|
880
|
-
return blockers.map((blocker) => {
|
|
881
|
-
if (blocker.status === 'failed')
|
|
882
|
-
return `${JSON.stringify(blocker.worktree)}: ${blocker.message}`;
|
|
883
|
-
return `${formatWorktreeSnapshot(blocker.snapshot)}\n Action: commit, stash, clean, or remove this sandbox interactively.`;
|
|
884
|
-
}).join('\n');
|
|
885
|
-
}
|
|
886
|
-
function cleanPermits(inspections) {
|
|
887
|
-
const permits = new Map();
|
|
888
|
-
for (const inspection of inspections) {
|
|
889
|
-
if (inspection.status === 'clean')
|
|
890
|
-
permits.set(inspection.snapshot.worktree, createCleanPermit(inspection.snapshot));
|
|
891
|
-
}
|
|
892
|
-
return permits;
|
|
893
|
-
}
|
|
894
|
-
async function authorizeWorktrees(worktrees, { allowDirtyDiscard, assumeYes }, { interactive = Boolean(process.stdin.isTTY), confirm = p.confirm, isCancel = p.isCancel, recovery = new Map() } = {}) {
|
|
895
|
-
const inspections = worktrees.map((worktree) => {
|
|
896
|
-
const inspection = inspectWorktrees([worktree])[0];
|
|
897
|
-
const context = recovery.get(path.resolve(worktree));
|
|
898
|
-
return inspection.status === 'failed' && context
|
|
899
|
-
? inspectRecoveredWorktree(worktree, context)
|
|
900
|
-
: inspection;
|
|
901
|
-
});
|
|
902
|
-
const failures = inspections.filter((inspection) => inspection.status === 'failed');
|
|
903
|
-
if (failures.length > 0)
|
|
904
|
-
throw new Error(`Unable to inspect worktree(s):\n${blockerMessage(failures)}`);
|
|
905
|
-
const permits = cleanPermits(inspections);
|
|
906
|
-
for (const inspection of inspections) {
|
|
907
|
-
if (inspection.status !== 'dirty')
|
|
908
|
-
continue;
|
|
909
|
-
if (!allowDirtyDiscard || assumeYes || !interactive) {
|
|
910
|
-
throw new Error(`Refusing to remove dirty worktree(s):\n${blockerMessage([inspection])}`);
|
|
911
|
-
}
|
|
912
|
-
p.log.warn(formatWorktreeSnapshot(inspection.snapshot));
|
|
913
|
-
const confirmed = await confirm({
|
|
914
|
-
message: 'Discard this worktree and all its uncommitted changes, including later changes?',
|
|
915
|
-
initialValue: false
|
|
916
|
-
});
|
|
917
|
-
if (isCancel(confirmed) || !confirmed)
|
|
918
|
-
throw new Error('Dirty worktree removal cancelled; nothing was deleted');
|
|
919
|
-
permits.set(inspection.snapshot.worktree, createDiscardPermit(inspection.snapshot));
|
|
920
|
-
}
|
|
921
|
-
return permits;
|
|
922
|
-
}
|
|
923
|
-
async function rmOne(config, tools, branch, options = {}) {
|
|
924
|
-
const target = options.target ?? resolveRmTarget(config, tools, options.cleanupTarget ?? resolveSandboxCleanupTarget(branch, config.repoRoot));
|
|
925
|
-
const { effectiveBranch, engine, matchedContainers, existingWorktrees, toolCandidates } = target;
|
|
926
|
-
const { workspace, controlRoots, workspaceViewRoots } = target;
|
|
927
|
-
preflightRmTarget(config, target);
|
|
928
|
-
const confirm = options.prompt?.confirm ?? p.confirm;
|
|
929
|
-
const isCancel = options.prompt?.isCancel ?? p.isCancel;
|
|
930
|
-
if (!options.quiet) {
|
|
931
|
-
p.intro(pc.cyan(`Removing sandbox for ${branch}`));
|
|
932
|
-
}
|
|
933
|
-
const targetDigest = removalTargetDigest(config, target);
|
|
934
|
-
const existingJournals = listSandboxRemovalJournals({
|
|
935
|
-
branch: effectiveBranch,
|
|
936
|
-
project: config.project,
|
|
937
|
-
targetDigest
|
|
938
|
-
});
|
|
939
|
-
const persistedTarget = existingJournals[0]?.target;
|
|
940
|
-
for (const journal of existingJournals) {
|
|
941
|
-
if (!persistedTarget)
|
|
942
|
-
break;
|
|
943
|
-
assertRemovalSelectionMatches(persistedTarget, journal.target);
|
|
944
|
-
}
|
|
945
|
-
const recovery = options.permits
|
|
946
|
-
? new Map()
|
|
947
|
-
: recoveryContexts(config, target, existingWorktrees);
|
|
948
|
-
const journalPermits = options.permits ? new Map()
|
|
949
|
-
: permitsFromJournal(existingJournals, target, targetDigest);
|
|
950
|
-
const permits = options.permits
|
|
951
|
-
? new Map(options.permits)
|
|
952
|
-
: journalPermits.size > 0
|
|
953
|
-
? journalPermits
|
|
954
|
-
: await authorizeWorktrees(existingWorktrees, {
|
|
955
|
-
allowDirtyDiscard: options.allowDirtyDiscard ?? true,
|
|
956
|
-
assumeYes: Boolean(options.assumeYes)
|
|
957
|
-
}, {
|
|
958
|
-
...options.prompt,
|
|
959
|
-
interactive: options.interactive ?? Boolean(process.stdin.isTTY),
|
|
960
|
-
recovery
|
|
961
|
-
});
|
|
962
|
-
for (const worktree of existingWorktrees) {
|
|
963
|
-
const permit = permits.get(path.resolve(worktree));
|
|
964
|
-
if (!permit)
|
|
965
|
-
throw new Error(`Missing worktree removal permit: ${worktree}`);
|
|
966
|
-
const worktreeTombstone = removalTombstonePath(targetDigest, 'worktree', worktree);
|
|
967
|
-
const workspacePhasePending = existingJournals.some((journal) => (sandboxRemovalPhaseIndex(journal.phase) < sandboxRemovalPhaseIndex('workspace-removed')));
|
|
968
|
-
if (fs.existsSync(worktree)
|
|
969
|
-
|| (workspacePhasePending
|
|
970
|
-
&& !isOwnedRemovalTombstone(config.worktreeBase, worktreeTombstone, {
|
|
971
|
-
version: 1,
|
|
972
|
-
targetDigest,
|
|
973
|
-
permitDigest: removalPermitDigest(permits),
|
|
974
|
-
kind: 'worktree',
|
|
975
|
-
source: worktree
|
|
976
|
-
}))) {
|
|
977
|
-
verifyWorktreePermit(permit);
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
const recoveredRemovalChoice = persistedTarget;
|
|
981
|
-
const shouldRemoveWorktree = recoveredRemovalChoice
|
|
982
|
-
? recoveredRemovalChoice.removeWorktree
|
|
983
|
-
: existingWorktrees.length === 0
|
|
984
|
-
? false
|
|
985
|
-
: options.assumeYes
|
|
986
|
-
? true
|
|
987
|
-
: await confirm({
|
|
988
|
-
message: `Remove worktree(s): ${existingWorktrees.join(', ')}?`,
|
|
989
|
-
initialValue: true
|
|
990
|
-
});
|
|
991
|
-
if (isCancel(shouldRemoveWorktree)) {
|
|
992
|
-
p.outro('Cancelled');
|
|
993
|
-
return;
|
|
994
|
-
}
|
|
995
|
-
const shouldDeleteBranch = recoveredRemovalChoice
|
|
996
|
-
? recoveredRemovalChoice.removeBranch
|
|
997
|
-
: shouldRemoveWorktree && existingWorktrees.length > 0
|
|
998
|
-
? options.assumeYes
|
|
999
|
-
? true
|
|
1000
|
-
: await confirm({
|
|
1001
|
-
message: `Also delete local branch '${effectiveBranch}'?`,
|
|
1002
|
-
initialValue: true
|
|
1003
|
-
})
|
|
1004
|
-
: false;
|
|
1005
|
-
if (isCancel(shouldDeleteBranch)) {
|
|
1006
|
-
p.outro('Cancelled');
|
|
1007
|
-
return;
|
|
1008
|
-
}
|
|
1009
|
-
const sharePath = path.resolve(shareBranchDir(config, effectiveBranch));
|
|
1010
|
-
const shouldRemoveShare = recoveredRemovalChoice
|
|
1011
|
-
? recoveredRemovalChoice.removeShare
|
|
1012
|
-
: fs.existsSync(sharePath)
|
|
1013
|
-
? options.assumeYes
|
|
1014
|
-
? true
|
|
1015
|
-
: await confirm({
|
|
1016
|
-
message: `Remove share dir for branch '${effectiveBranch}' (${sharePath})?`,
|
|
1017
|
-
initialValue: true
|
|
1018
|
-
})
|
|
1019
|
-
: false;
|
|
1020
|
-
if (isCancel(shouldRemoveShare)) {
|
|
1021
|
-
p.outro('Cancelled');
|
|
1022
|
-
return;
|
|
1023
|
-
}
|
|
1024
|
-
const committedTarget = persistedTarget
|
|
1025
|
-
? {
|
|
1026
|
-
...persistedTarget,
|
|
1027
|
-
permitDigest: removalPermitDigest(permits),
|
|
1028
|
-
permits: removalPermitCommits(permits)
|
|
1029
|
-
}
|
|
1030
|
-
: removalTargetCommit(config, target, permits, Boolean(shouldRemoveWorktree), Boolean(shouldDeleteBranch), Boolean(shouldRemoveShare));
|
|
1031
|
-
if (persistedTarget)
|
|
1032
|
-
assertRemovalSelectionMatches(persistedTarget, committedTarget);
|
|
1033
|
-
const coordinatedManifests = controlRoots
|
|
1034
|
-
.filter((candidate) => fs.existsSync(candidate))
|
|
1035
|
-
.flatMap((root) => {
|
|
1036
|
-
const manifestPath = path.join(root, 'manifest.json');
|
|
1037
|
-
return fs.existsSync(manifestPath)
|
|
1038
|
-
? [[root, readSandboxControlManifest(manifestPath), fs.readFileSync(manifestPath, 'utf8')]]
|
|
1039
|
-
: [];
|
|
1040
|
-
});
|
|
1041
|
-
const resourceLocks = new Map();
|
|
1042
|
-
const recoveredContainerNames = new Set();
|
|
1043
|
-
try {
|
|
1044
|
-
for (const [root, manifest] of [...coordinatedManifests].sort(([left], [right]) => left.localeCompare(right))) {
|
|
1045
|
-
resourceLocks.set(root, acquireSandboxResourceLock(`${manifest.engine}:${manifest.containerIdentity.id}`, { lockDomain: manifest.authorityEvidence.lockDomain }));
|
|
1046
|
-
}
|
|
1047
|
-
for (const journal of existingJournals.filter((candidate) => !fs.existsSync(candidate.target.controlRoot))) {
|
|
1048
|
-
if (!target.controlRoots.some((root) => path.resolve(root) === path.resolve(journal.target.controlRoot))) {
|
|
1049
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH');
|
|
1050
|
-
}
|
|
1051
|
-
assertRemovalSelectionMatches(committedTarget, journal.target);
|
|
1052
|
-
if (journal.target.permitDigest !== removalPermitDigest(permits)) {
|
|
1053
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_PERMIT_MISMATCH');
|
|
1054
|
-
}
|
|
1055
|
-
const lock = acquireSandboxResourceLock(`${journal.engine}:${journal.containerId}`, {
|
|
1056
|
-
lockDomain: journal.lockDomain
|
|
1057
|
-
});
|
|
1058
|
-
resourceLocks.set(journal.target.controlRoot, lock);
|
|
1059
|
-
const current = listSandboxRemovalJournals({
|
|
1060
|
-
branch: journal.target.branch,
|
|
1061
|
-
project: journal.target.project,
|
|
1062
|
-
targetDigest: journal.target.targetDigest
|
|
1063
|
-
}).find((candidate) => candidate.carrierIdentityDigest === journal.carrierIdentityDigest);
|
|
1064
|
-
if (!current || current.revision !== journal.revision || current.handoffId !== journal.handoffId) {
|
|
1065
|
-
throw new Error('SANDBOX_CONTROL_REMOVAL_JOURNAL_REVISION_MISMATCH');
|
|
1066
|
-
}
|
|
1067
|
-
const claimed = claimSandboxRemovalJournal(current, { resourceLock: lock });
|
|
1068
|
-
if (!['carrier-finalizing', 'carrier-removed', 'workspace-finalizing', 'workspace-removed',
|
|
1069
|
-
'branch-finalizing', 'branch-removed', 'tool-finalizing', 'tool-removed',
|
|
1070
|
-
'shell-finalizing', 'shell-removed', 'share-finalizing', 'share-removed', 'completed']
|
|
1071
|
-
.includes(claimed.phase)) {
|
|
1072
|
-
throw new Error('SANDBOX_CONTROL_REMOVE_RECOVERY_PENDING');
|
|
1073
|
-
}
|
|
1074
|
-
const recovered = claimed.phase === 'carrier-finalizing'
|
|
1075
|
-
? advanceSandboxRemovalJournalPhase(claimed, 'carrier-removed', { resourceLock: lock })
|
|
1076
|
-
: claimed;
|
|
1077
|
-
recoveredContainerNames.add(controlRootContainer(config, journal.target.controlRoot));
|
|
1078
|
-
}
|
|
1079
|
-
cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
|
|
1080
|
-
preflightRmTarget(config, target);
|
|
1081
|
-
const coordinatedContainers = new Set(recoveredContainerNames);
|
|
1082
|
-
for (const root of controlRoots.filter((candidate) => fs.existsSync(candidate))) {
|
|
1083
|
-
assertLegacyCandidateEvidence(root, config.controlBase, config, effectiveBranch, matchedContainers);
|
|
1084
|
-
assertControlRootMatchesTarget(root, effectiveBranch, workspace);
|
|
1085
|
-
const manifestPath = path.join(root, 'manifest.json');
|
|
1086
|
-
if (!fs.existsSync(manifestPath))
|
|
1087
|
-
continue;
|
|
1088
|
-
const currentRaw = fs.readFileSync(manifestPath, 'utf8');
|
|
1089
|
-
const manifest = readSandboxControlManifest(manifestPath);
|
|
1090
|
-
const initial = coordinatedManifests.find(([candidate]) => candidate === root);
|
|
1091
|
-
if (!initial || currentRaw !== initial[2])
|
|
1092
|
-
throw new Error('SANDBOX_CONTROL_MANIFEST_CHANGED');
|
|
1093
|
-
coordinatedContainers.add(manifest.container);
|
|
1094
|
-
await removeSandboxControlRoot(root, {
|
|
1095
|
-
inspectContainer: (timeoutMs) => inspectSandboxControlContainer(manifest, { timeoutMs }),
|
|
1096
|
-
removeContainer: (timeoutMs) => removeExactSandboxContainer(engine, manifest, timeoutMs),
|
|
1097
|
-
resourceLock: resourceLocks.get(root),
|
|
1098
|
-
retainRemovalJournal: true,
|
|
1099
|
-
removalTarget: { ...committedTarget, controlRoot: path.resolve(root) }
|
|
1100
|
-
});
|
|
1101
|
-
removeEmptyManagedParent(path.join(config.controlBase, config.project), root);
|
|
1102
|
-
}
|
|
1103
|
-
if ([...recoveredContainerNames].some((name) => matchedContainers.includes(name))) {
|
|
1104
|
-
throw new Error('SANDBOX_CONTROL_CONTAINER_REAPPEARED');
|
|
1105
|
-
}
|
|
1106
|
-
const uncoordinatedContainers = matchedContainers.filter((name) => !coordinatedContainers.has(name));
|
|
1107
|
-
if (uncoordinatedContainers.length > 0) {
|
|
1108
|
-
if (workspace.mode === 'task-bound') {
|
|
1109
|
-
throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: container '${uncoordinatedContainers[0]}'`);
|
|
1110
|
-
}
|
|
1111
|
-
const spinner = p.spinner();
|
|
1112
|
-
spinner.start(`Stopping container(s): ${uncoordinatedContainers.join(', ')}`);
|
|
1113
|
-
for (const name of uncoordinatedContainers) {
|
|
1114
|
-
if (!runOkEngine(engine, 'docker', ['stop', name]))
|
|
1115
|
-
throw new Error(`Failed to stop sandbox container: ${name}`);
|
|
1116
|
-
if (!runOkEngine(engine, 'docker', ['rm', name]))
|
|
1117
|
-
throw new Error(`Failed to remove sandbox container: ${name}`);
|
|
1118
|
-
}
|
|
1119
|
-
const remaining = runEngine(engine, 'docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
|
|
1120
|
-
const leftovers = uncoordinatedContainers.filter((name) => remaining.includes(name));
|
|
1121
|
-
if (leftovers.length > 0)
|
|
1122
|
-
throw new Error(`Sandbox container(s) still exist after removal: ${leftovers.join(', ')}`);
|
|
1123
|
-
spinner.stop(pc.green(`Removed container(s): ${uncoordinatedContainers.join(', ')}`));
|
|
1124
|
-
}
|
|
1125
|
-
else {
|
|
1126
|
-
p.log.warn(`No sandbox container found for '${branch}'`);
|
|
1127
|
-
}
|
|
1128
|
-
const runWorkspaceCleanup = prepareRemovalAction(config.project, target, targetDigest, 'workspace-finalizing', 'workspace-removed', resourceLocks);
|
|
1129
|
-
if (runWorkspaceCleanup.run) {
|
|
1130
|
-
for (const [roots, base, label] of [
|
|
1131
|
-
[workspaceViewRoots, path.join(config.workspaceViewBase, config.project), 'Workspace view'],
|
|
1132
|
-
[controlRoots, path.join(config.controlBase, config.project), 'Control channel']
|
|
1133
|
-
]) {
|
|
1134
|
-
for (const directory of roots.filter((candidate) => shouldStageManagedRemoval(candidate, removalTombstonePath(targetDigest, 'workspace', candidate), runWorkspaceCleanup.recovering))) {
|
|
1135
|
-
assertLegacyCandidateEvidence(directory, base === path.join(config.controlBase, config.project)
|
|
1136
|
-
? config.controlBase : config.workspaceViewBase, config, effectiveBranch, matchedContainers);
|
|
1137
|
-
stageManagedRemoval(base, directory, removalTombstonePath(targetDigest, 'workspace', directory), runWorkspaceCleanup.recovering, {
|
|
1138
|
-
version: 1,
|
|
1139
|
-
targetDigest,
|
|
1140
|
-
permitDigest: committedTarget.permitDigest,
|
|
1141
|
-
kind: 'workspace',
|
|
1142
|
-
source: directory
|
|
1143
|
-
});
|
|
1144
|
-
if (!options.quiet)
|
|
1145
|
-
p.log.success(`${label} removed: ${directory}`);
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
if (shouldRemoveWorktree) {
|
|
1149
|
-
for (const worktree of existingWorktrees) {
|
|
1150
|
-
const permit = permits.get(path.resolve(worktree));
|
|
1151
|
-
if (!permit)
|
|
1152
|
-
throw new Error(`Missing worktree removal permit: ${worktree}`);
|
|
1153
|
-
stageWorktreeRemoval(config, worktree, permit, removalTombstonePath(targetDigest, 'worktree', worktree), runWorkspaceCleanup.recovering, {
|
|
1154
|
-
version: 1,
|
|
1155
|
-
targetDigest,
|
|
1156
|
-
permitDigest: committedTarget.permitDigest,
|
|
1157
|
-
kind: 'worktree',
|
|
1158
|
-
source: worktree
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
else {
|
|
1164
|
-
assertRemovalPathsAbsent([
|
|
1165
|
-
...removalActionPaths(target, config, 'workspace-removed'),
|
|
1166
|
-
...(shouldRemoveWorktree ? existingWorktrees : [])
|
|
1167
|
-
]);
|
|
1168
|
-
}
|
|
1169
|
-
advanceRemovalJournals(config.project, target, targetDigest, 'workspace-removed', resourceLocks);
|
|
1170
|
-
cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
|
|
1171
|
-
for (const [roots, base] of [
|
|
1172
|
-
[workspaceViewRoots, path.join(config.workspaceViewBase, config.project)],
|
|
1173
|
-
[controlRoots, path.join(config.controlBase, config.project)]
|
|
1174
|
-
]) {
|
|
1175
|
-
for (const directory of roots) {
|
|
1176
|
-
if (!fs.existsSync(directory))
|
|
1177
|
-
removeEmptyManagedParent(base, directory);
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
const runBranchCleanup = prepareRemovalAction(config.project, target, targetDigest, 'branch-finalizing', 'branch-removed', resourceLocks);
|
|
1181
|
-
if (runBranchCleanup.run) {
|
|
1182
|
-
if (shouldRemoveWorktree && shouldDeleteBranch) {
|
|
1183
|
-
stageBranchRemoval(config, effectiveBranch, targetDigest, permits, runBranchCleanup.recovering);
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
else if (shouldRemoveWorktree && shouldDeleteBranch
|
|
1187
|
-
&& runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', `refs/heads/${effectiveBranch}`])) {
|
|
1188
|
-
throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${effectiveBranch}`);
|
|
1189
|
-
}
|
|
1190
|
-
advanceRemovalJournals(config.project, target, targetDigest, 'branch-removed', resourceLocks);
|
|
1191
|
-
cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
|
|
1192
|
-
const runToolCleanup = prepareRemovalAction(config.project, target, targetDigest, 'tool-finalizing', 'tool-removed', resourceLocks);
|
|
1193
|
-
if (runToolCleanup.run) {
|
|
1194
|
-
for (const { tool, candidates } of toolCandidates) {
|
|
1195
|
-
for (const dir of candidates.filter((candidate) => shouldStageManagedRemoval(candidate, removalTombstonePath(targetDigest, 'tool', candidate), runToolCleanup.recovering))) {
|
|
1196
|
-
stageManagedRemoval(tool.sandboxBase, dir, removalTombstonePath(targetDigest, 'tool', dir), runToolCleanup.recovering, {
|
|
1197
|
-
version: 1,
|
|
1198
|
-
targetDigest,
|
|
1199
|
-
permitDigest: committedTarget.permitDigest,
|
|
1200
|
-
kind: 'tool',
|
|
1201
|
-
source: dir
|
|
1202
|
-
});
|
|
1203
|
-
p.log.success(`${tool.name} state removed: ${dir}`);
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
}
|
|
1207
|
-
else {
|
|
1208
|
-
assertRemovalPathsAbsent(removalActionPaths(target, config, 'tool-removed'));
|
|
1209
|
-
}
|
|
1210
|
-
advanceRemovalJournals(config.project, target, targetDigest, 'tool-removed', resourceLocks);
|
|
1211
|
-
cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
|
|
1212
|
-
const runShellCleanup = prepareRemovalAction(config.project, target, targetDigest, 'shell-finalizing', 'shell-removed', resourceLocks);
|
|
1213
|
-
if (runShellCleanup.run) {
|
|
1214
|
-
for (const dir of shellConfigDirCandidates(config, effectiveBranch).filter((candidate) => shouldStageManagedRemoval(candidate, removalTombstonePath(targetDigest, 'shell', candidate), runShellCleanup.recovering))) {
|
|
1215
|
-
stageManagedRemoval(config.shellConfigBase, dir, removalTombstonePath(targetDigest, 'shell', dir), runShellCleanup.recovering, {
|
|
1216
|
-
version: 1,
|
|
1217
|
-
targetDigest,
|
|
1218
|
-
permitDigest: committedTarget.permitDigest,
|
|
1219
|
-
kind: 'shell',
|
|
1220
|
-
source: dir
|
|
1221
|
-
});
|
|
1222
|
-
p.log.success(`Shell config removed: ${dir}`);
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
else {
|
|
1226
|
-
assertRemovalPathsAbsent(removalActionPaths(target, config, 'shell-removed'));
|
|
1227
|
-
}
|
|
1228
|
-
advanceRemovalJournals(config.project, target, targetDigest, 'shell-removed', resourceLocks);
|
|
1229
|
-
cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
|
|
1230
|
-
const runShareCleanup = prepareRemovalAction(config.project, target, targetDigest, 'share-finalizing', 'share-removed', resourceLocks);
|
|
1231
|
-
if (runShareCleanup.run) {
|
|
1232
|
-
if (shouldRemoveShare && shouldStageManagedRemoval(sharePath, removalTombstonePath(targetDigest, 'share', sharePath), runShareCleanup.recovering)) {
|
|
1233
|
-
stageManagedRemoval(config.shareBase, sharePath, removalTombstonePath(targetDigest, 'share', sharePath), runShareCleanup.recovering, {
|
|
1234
|
-
version: 1,
|
|
1235
|
-
targetDigest,
|
|
1236
|
-
permitDigest: committedTarget.permitDigest,
|
|
1237
|
-
kind: 'share',
|
|
1238
|
-
source: sharePath
|
|
1239
|
-
});
|
|
1240
|
-
p.log.success(`Share dir removed: ${sharePath}`);
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
else if (shouldRemoveShare) {
|
|
1244
|
-
assertRemovalPathsAbsent(removalActionPaths(target, config, 'share-removed'));
|
|
1245
|
-
}
|
|
1246
|
-
advanceRemovalJournals(config.project, target, targetDigest, 'share-removed', resourceLocks);
|
|
1247
|
-
cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
|
|
1248
|
-
const completedJournals = advanceRemovalJournals(config.project, target, targetDigest, 'completed', resourceLocks);
|
|
1249
|
-
for (const journal of completedJournals)
|
|
1250
|
-
clearSandboxRemovalJournalRecord(journal);
|
|
1251
|
-
if (!options.quiet) {
|
|
1252
|
-
p.outro(pc.green('Sandbox removed'));
|
|
1253
|
-
}
|
|
1254
|
-
}
|
|
1255
|
-
finally {
|
|
1256
|
-
for (const lock of [...resourceLocks.values()].reverse())
|
|
1257
|
-
lock.release();
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
async function rmPurge(config, tools, prompt = {}) {
|
|
1261
|
-
const engine = detectEngine(config);
|
|
1262
|
-
const confirm = prompt.confirm ?? p.confirm;
|
|
1263
|
-
const isCancel = prompt.isCancel ?? p.isCancel;
|
|
1264
|
-
p.intro(pc.cyan(`Removing all sandboxes for ${config.project}`));
|
|
1265
|
-
const worktrees = fs.existsSync(config.worktreeBase)
|
|
1266
|
-
? fs.readdirSync(config.worktreeBase)
|
|
1267
|
-
.map((entry) => path.join(config.worktreeBase, entry))
|
|
1268
|
-
.filter((entry) => {
|
|
1269
|
-
try {
|
|
1270
|
-
return fs.statSync(entry).isDirectory();
|
|
1271
|
-
}
|
|
1272
|
-
catch {
|
|
1273
|
-
return false;
|
|
1274
|
-
}
|
|
1275
|
-
})
|
|
1276
|
-
: [];
|
|
1277
|
-
const inspections = inspectWorktrees(worktrees);
|
|
1278
|
-
const blockers = inspectionBlockers(inspections);
|
|
1279
|
-
if (blockers.length > 0) {
|
|
1280
|
-
throw new Error(`Refusing to purge because worktree preflight found blocker(s):\n${blockerMessage(blockers)}`);
|
|
1281
|
-
}
|
|
1282
|
-
const permits = cleanPermits(inspections);
|
|
1283
|
-
const coordinatedContainers = await removeProjectControlRoots(config, engine);
|
|
1284
|
-
const containers = runEngine(engine, 'docker', [
|
|
1285
|
-
'ps',
|
|
1286
|
-
'-a',
|
|
1287
|
-
'--filter',
|
|
1288
|
-
`label=${sandboxLabel(config)}`,
|
|
1289
|
-
'--format',
|
|
1290
|
-
'{{.Names}}'
|
|
1291
|
-
]);
|
|
1292
|
-
const uncoordinatedContainers = containers.split('\n').filter((name) => name && !coordinatedContainers.has(name));
|
|
1293
|
-
if (uncoordinatedContainers.length > 0) {
|
|
1294
|
-
const spinner = p.spinner();
|
|
1295
|
-
spinner.start('Stopping project sandbox containers...');
|
|
1296
|
-
for (const name of uncoordinatedContainers) {
|
|
1297
|
-
if (!runOkEngine(engine, 'docker', ['stop', name]))
|
|
1298
|
-
throw new Error(`Failed to stop sandbox container: ${name}`);
|
|
1299
|
-
if (!runOkEngine(engine, 'docker', ['rm', name]))
|
|
1300
|
-
throw new Error(`Failed to remove sandbox container: ${name}`);
|
|
1301
|
-
}
|
|
1302
|
-
const remaining = runEngine(engine, 'docker', [
|
|
1303
|
-
'ps', '-a', '--filter', `label=${sandboxLabel(config)}`, '--format', '{{.Names}}'
|
|
1304
|
-
]);
|
|
1305
|
-
const leftovers = remaining.split('\n').filter((name) => name && !coordinatedContainers.has(name));
|
|
1306
|
-
if (leftovers.length > 0)
|
|
1307
|
-
throw new Error(`Project sandbox container(s) still exist after removal: ${leftovers.join(', ')}`);
|
|
1308
|
-
spinner.stop(pc.green('Project sandbox containers removed'));
|
|
1309
|
-
}
|
|
1310
|
-
else {
|
|
1311
|
-
p.log.warn('No project sandbox containers found');
|
|
1312
|
-
}
|
|
1313
|
-
if (worktrees.length > 0) {
|
|
1314
|
-
const shouldRemoveWorktrees = await confirm({
|
|
1315
|
-
message: `Remove all worktrees in ${config.worktreeBase}?`,
|
|
1316
|
-
initialValue: true
|
|
1317
|
-
});
|
|
1318
|
-
if (!isCancel(shouldRemoveWorktrees) && shouldRemoveWorktrees) {
|
|
1319
|
-
for (const dir of worktrees) {
|
|
1320
|
-
const permit = permits.get(path.resolve(dir));
|
|
1321
|
-
if (!permit)
|
|
1322
|
-
throw new Error(`Missing worktree removal permit: ${dir}`);
|
|
1323
|
-
removeWorktreeDir(config.repoRoot, config.worktreeBase, dir, permit, {
|
|
1324
|
-
allowRegisteredPathFallback: engine === ENGINES.WSL2
|
|
1325
|
-
});
|
|
1326
|
-
assertRemoved(dir, 'Worktree');
|
|
1327
|
-
}
|
|
1328
|
-
runSafe('git', ['-C', config.repoRoot, 'worktree', 'prune']);
|
|
1329
|
-
const registered = new Set(runSafe('git', ['-C', config.repoRoot, 'worktree', 'list', '--porcelain'])
|
|
1330
|
-
.split('\n').filter((line) => line.startsWith('worktree ')).map((line) => path.resolve(line.slice(9))));
|
|
1331
|
-
const leftovers = worktrees.filter((dir) => registered.has(path.resolve(dir)));
|
|
1332
|
-
if (leftovers.length > 0)
|
|
1333
|
-
throw new Error(`Worktree(s) still registered after removal: ${leftovers.join(', ')}`);
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
for (const dir of projectToolDirs(config, tools)) {
|
|
1337
|
-
if (fs.existsSync(dir)) {
|
|
1338
|
-
removeManagedDir(path.dirname(dir), dir);
|
|
1339
|
-
assertRemoved(dir, 'Tool state');
|
|
1340
|
-
p.log.success(`Removed tool state: ${dir}`);
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
if (fs.existsSync(config.shellConfigBase) && fs.readdirSync(config.shellConfigBase).length > 0) {
|
|
1344
|
-
const shouldRemoveShellConfigs = await confirm({
|
|
1345
|
-
message: `Remove all shell config dirs in ${config.shellConfigBase}?`,
|
|
1346
|
-
initialValue: true
|
|
1347
|
-
});
|
|
1348
|
-
if (!isCancel(shouldRemoveShellConfigs) && shouldRemoveShellConfigs) {
|
|
1349
|
-
for (const entry of fs.readdirSync(config.shellConfigBase)) {
|
|
1350
|
-
const dir = path.join(config.shellConfigBase, entry);
|
|
1351
|
-
removeManagedDir(config.shellConfigBase, dir);
|
|
1352
|
-
assertRemoved(dir, 'Shell config');
|
|
1353
|
-
}
|
|
1354
|
-
p.log.success(`Project shell config dirs removed: ${config.shellConfigBase}`);
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
if (fs.existsSync(config.shareBase) && fs.readdirSync(config.shareBase).length > 0) {
|
|
1358
|
-
const shouldRemoveAllShares = await confirm({
|
|
1359
|
-
message: `Remove all share dirs for project (${config.shareBase})?`,
|
|
1360
|
-
initialValue: true
|
|
1361
|
-
});
|
|
1362
|
-
if (!isCancel(shouldRemoveAllShares) && shouldRemoveAllShares) {
|
|
1363
|
-
removeManagedDir(path.dirname(config.shareBase), config.shareBase);
|
|
1364
|
-
assertRemoved(config.shareBase, 'Project share dir');
|
|
1365
|
-
p.log.success(`Project share dirs removed: ${config.shareBase}`);
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
for (const [base, label] of [
|
|
1369
|
-
[config.workspaceViewBase, 'workspace views'],
|
|
1370
|
-
[config.controlBase, 'control channels']
|
|
1371
|
-
]) {
|
|
1372
|
-
const projectDir = path.join(base, config.project);
|
|
1373
|
-
if (fs.existsSync(projectDir)) {
|
|
1374
|
-
removeManagedDir(base, projectDir);
|
|
1375
|
-
assertRemoved(projectDir, `Project ${label}`);
|
|
1376
|
-
p.log.success(`Removed project ${label}: ${projectDir}`);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
const shouldRemoveImage = await confirm({
|
|
1380
|
-
message: `Remove image ${config.imageName}?`,
|
|
1381
|
-
initialValue: false
|
|
1382
|
-
});
|
|
1383
|
-
if (!isCancel(shouldRemoveImage) && shouldRemoveImage) {
|
|
1384
|
-
runSafeEngine(engine, 'docker', ['rmi', config.imageName]);
|
|
1385
|
-
}
|
|
1386
|
-
pruneSandboxDanglingImages(config, engine);
|
|
1387
|
-
if (isManagedEngine(engine)) {
|
|
1388
|
-
if (engine === ENGINES.WSL2) {
|
|
1389
|
-
p.log.warn('Windows uses Docker Desktop with WSL2. Stop it from Docker Desktop or run "wsl --shutdown" manually.');
|
|
1390
|
-
p.outro(pc.green('All project sandboxes removed'));
|
|
1391
|
-
return;
|
|
1392
|
-
}
|
|
1393
|
-
const name = engineDisplayName(engine);
|
|
1394
|
-
const shouldStopVm = await confirm({
|
|
1395
|
-
message: `Stop ${name} VM?`,
|
|
1396
|
-
initialValue: false
|
|
1397
|
-
});
|
|
1398
|
-
if (!isCancel(shouldStopVm) && shouldStopVm) {
|
|
1399
|
-
stopManagedVm(config);
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
p.outro(pc.green('All project sandboxes removed'));
|
|
1403
|
-
}
|
|
1404
|
-
async function rmUnbound(config, tools, options) {
|
|
1405
|
-
const engine = detectEngine(config);
|
|
1406
|
-
const { running, nonRunning } = fetchSandboxRows(engine, sandboxLabel(config), sandboxBranchLabel(config), { mode: sandboxWorkspaceModeLabel(config), taskId: sandboxTaskIdLabel(config) });
|
|
1407
|
-
const rows = [...running, ...nonRunning];
|
|
1408
|
-
p.intro(pc.cyan(`Removing sandboxes not bound to an active task for ${config.project}`));
|
|
1409
|
-
if (rows.length === 0) {
|
|
1410
|
-
p.outro('No removable sandboxes: every container is bound to an active task (or none exist)');
|
|
1411
|
-
return;
|
|
1412
|
-
}
|
|
1413
|
-
const candidates = rows.map((row) => {
|
|
1414
|
-
if (!row.branch || !row.workspaceMode || row.workspaceMode === 'legacy-invalid') {
|
|
1415
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: container '${row.name}' has incomplete workspace identity`);
|
|
1416
|
-
}
|
|
1417
|
-
if (row.workspaceMode === 'task-bound') {
|
|
1418
|
-
if (!row.taskId) {
|
|
1419
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: container '${row.name}' has no task id`);
|
|
1420
|
-
}
|
|
1421
|
-
const cleanupTarget = resolveSandboxCleanupTarget(row.taskId, config.repoRoot, { allowProtected: true });
|
|
1422
|
-
if (cleanupTarget.branch !== row.branch
|
|
1423
|
-
|| cleanupTarget.workspace.mode !== 'task-bound'
|
|
1424
|
-
|| cleanupTarget.workspace.taskId !== row.taskId) {
|
|
1425
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: container '${row.name}' task identity conflicts with task.md`);
|
|
1426
|
-
}
|
|
1427
|
-
return { row, cleanupTarget };
|
|
1428
|
-
}
|
|
1429
|
-
return {
|
|
1430
|
-
row,
|
|
1431
|
-
cleanupTarget: {
|
|
1432
|
-
requestedRef: row.branch,
|
|
1433
|
-
branch: row.branch,
|
|
1434
|
-
workspace: { mode: 'branch-only' },
|
|
1435
|
-
taskState: 'branch-only'
|
|
1436
|
-
}
|
|
1437
|
-
};
|
|
1438
|
-
});
|
|
1439
|
-
const branchIdentities = new Map();
|
|
1440
|
-
const groupedCandidates = new Map();
|
|
1441
|
-
for (const candidate of candidates) {
|
|
1442
|
-
const identity = candidate.cleanupTarget.workspace.mode === 'task-bound'
|
|
1443
|
-
? `task-bound:${candidate.cleanupTarget.workspace.taskId}`
|
|
1444
|
-
: 'branch-only';
|
|
1445
|
-
const existingIdentity = branchIdentities.get(candidate.cleanupTarget.branch);
|
|
1446
|
-
if (existingIdentity && existingIdentity !== identity) {
|
|
1447
|
-
throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: branch '${candidate.cleanupTarget.branch}' has conflicting workspace identities`);
|
|
1448
|
-
}
|
|
1449
|
-
branchIdentities.set(candidate.cleanupTarget.branch, identity);
|
|
1450
|
-
const groupKey = `${candidate.cleanupTarget.branch}\0${identity}`;
|
|
1451
|
-
const group = groupedCandidates.get(groupKey) ?? [];
|
|
1452
|
-
group.push(candidate);
|
|
1453
|
-
groupedCandidates.set(groupKey, group);
|
|
1454
|
-
}
|
|
1455
|
-
const groups = [...groupedCandidates.values()].map((groupCandidates) => {
|
|
1456
|
-
const cleanupTarget = groupCandidates[0].cleanupTarget;
|
|
1457
|
-
const target = resolveRmTarget(config, tools, cleanupTarget, {
|
|
1458
|
-
discoveredContainers: groupCandidates.map(({ row }) => row.name)
|
|
1459
|
-
});
|
|
1460
|
-
preflightRmTarget(config, target);
|
|
1461
|
-
return { candidates: groupCandidates, cleanupTarget, target };
|
|
1462
|
-
});
|
|
1463
|
-
assertCleanupGroupPathsDoNotOverlap(groups);
|
|
1464
|
-
const removableGroups = groups.filter(({ cleanupTarget }) => cleanupTarget.taskState === 'completed' || cleanupTarget.taskState === 'branch-only');
|
|
1465
|
-
const removable = removableGroups.flatMap(({ candidates: groupCandidates }) => groupCandidates);
|
|
1466
|
-
for (const { candidates: groupCandidates, cleanupTarget } of groups.filter(({ cleanupTarget }) => cleanupTarget.taskState !== 'completed' && cleanupTarget.taskState !== 'branch-only')) {
|
|
1467
|
-
for (const { row } of groupCandidates) {
|
|
1468
|
-
p.log.message(`Skipped protected sandbox ${row.name} (${cleanupTarget.taskState})`);
|
|
1469
|
-
}
|
|
1470
|
-
}
|
|
1471
|
-
if (removableGroups.length === 0) {
|
|
1472
|
-
p.outro('No removable sandboxes: every container is bound to a protected task (or none exist)');
|
|
1473
|
-
return;
|
|
1474
|
-
}
|
|
1475
|
-
const inspections = inspectWorktrees(removableGroups.flatMap(({ target }) => target.existingWorktrees));
|
|
1476
|
-
assertWorktreeBranchesMatchGroups(removableGroups, inspections);
|
|
1477
|
-
const blockers = inspectionBlockers(inspections);
|
|
1478
|
-
const permits = cleanPermits(inspections);
|
|
1479
|
-
for (const { row } of removable) {
|
|
1480
|
-
p.log.message(`${row.name} ${row.branch}`);
|
|
1481
|
-
}
|
|
1482
|
-
if (blockers.length > 0)
|
|
1483
|
-
p.log.error(blockerMessage(blockers));
|
|
1484
|
-
if (options.dryRun) {
|
|
1485
|
-
p.outro(`Dry run: ${removable.length} sandbox(es) inspected, nothing deleted`);
|
|
1486
|
-
return;
|
|
1487
|
-
}
|
|
1488
|
-
if (blockers.length > 0) {
|
|
1489
|
-
throw new Error(`Refusing batch removal because worktree preflight found blocker(s):\n${blockerMessage(blockers)}`);
|
|
1490
|
-
}
|
|
1491
|
-
if (!options.assumeYes && !process.stdin.isTTY) {
|
|
1492
|
-
throw new Error('Refusing to remove sandboxes without confirmation in a non-interactive shell; pass --yes to proceed.');
|
|
1493
|
-
}
|
|
1494
|
-
const failures = [];
|
|
1495
|
-
let failedRows = 0;
|
|
1496
|
-
for (const group of removableGroups) {
|
|
1497
|
-
try {
|
|
1498
|
-
await rmOne(config, tools, group.cleanupTarget.branch, {
|
|
1499
|
-
assumeYes: options.assumeYes,
|
|
1500
|
-
quiet: true,
|
|
1501
|
-
target: group.target,
|
|
1502
|
-
cleanupTarget: group.cleanupTarget,
|
|
1503
|
-
permits,
|
|
1504
|
-
allowDirtyDiscard: false
|
|
1505
|
-
});
|
|
1506
|
-
}
|
|
1507
|
-
catch (error) {
|
|
1508
|
-
failedRows += group.candidates.length;
|
|
1509
|
-
failures.push({ branch: group.cleanupTarget.branch, message: error instanceof Error ? error.message : String(error) });
|
|
1510
|
-
}
|
|
1511
|
-
}
|
|
1512
|
-
if (failures.length > 0) {
|
|
1513
|
-
for (const failure of failures) {
|
|
1514
|
-
p.log.error(`Failed to remove '${failure.branch}': ${failure.message}`);
|
|
1515
|
-
}
|
|
1516
|
-
throw new Error(`Removed ${removable.length - failedRows}/${removable.length} sandbox(es); ${failures.length} failed`);
|
|
15
|
+
const listed = fetchSandboxRows(engine, sandboxLabel(config), sandboxBranchLabel(config), { mode: sandboxWorkspaceModeLabel(config), taskId: sandboxTaskIdLabel(config) });
|
|
16
|
+
const branches = new Set([...listed.running, ...listed.nonRunning]
|
|
17
|
+
.filter((row) => row.workspaceMode === 'task-bound' && row.taskId === taskId && row.branch)
|
|
18
|
+
.map((row) => row.branch));
|
|
19
|
+
if (branches.size === 0)
|
|
20
|
+
return null;
|
|
21
|
+
if (branches.size > 1) {
|
|
22
|
+
throw new Error(`SANDBOX_CLEANUP_TASK_ID_AMBIGUOUS: task ${taskId} matches multiple sandbox branches`);
|
|
1517
23
|
}
|
|
1518
|
-
|
|
24
|
+
return branches.values().next().value ?? null;
|
|
1519
25
|
}
|
|
1520
26
|
export async function rm(args) {
|
|
1521
27
|
const { values, positionals } = parseArgs({
|
|
@@ -1563,8 +69,10 @@ export async function rm(args) {
|
|
|
1563
69
|
});
|
|
1564
70
|
return;
|
|
1565
71
|
}
|
|
1566
|
-
const cleanupTarget = resolveSandboxCleanupTarget(positionals[0] ?? '', config.repoRoot
|
|
72
|
+
const cleanupTarget = resolveSandboxCleanupTarget(positionals[0] ?? '', config.repoRoot, {
|
|
73
|
+
allowProtected: true,
|
|
74
|
+
resolveMissingTask: (taskId) => resolveMissingTaskSandboxBranch(taskId, config)
|
|
75
|
+
});
|
|
1567
76
|
await rmOne(config, tools, cleanupTarget.branch, { cleanupTarget });
|
|
1568
77
|
}
|
|
1569
|
-
export { authorizeWorktrees, rmOne, rmPurge };
|
|
1570
78
|
//# sourceMappingURL=rm.js.map
|