diff --git a/CHANGELOG.md b/CHANGELOG.md
index b5a6443..18e5d9e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## 0.47.22 - 2026-11-16
+
+- Register persistent stack replay desks and provide a reviewed CLI release path. Preserve the desk tip, index and working changes in verified local recovery refs before removing its checkout, with explicit selection for legacy desks. Stack archive names the desk release or pending-release remedy.
+
## 0.47.21 - 2026-11-16
- Keep status without fetch, check with --no-fetch, and worktree list observational on control metadata. Skip implicit startup maintenance, authorization nonce creation or cleanup, and persistent patch-ID cache writes while preserving manifest selection checks and explicit fetch behavior.
diff --git a/README.md b/README.md
index e3fb745..bd0d551 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
Keep many long-lived pull requests clean, rebuildable, and publishable from one
manifest.
-Current version: `0.47.21`
+Current version: `0.47.22`
`syncwheel` is a small CLI and workflow model for maintainers who carry several
PR branches against an upstream repository and need those branches to stay
@@ -477,6 +477,14 @@ lanes that need attention and `--json` adds a count per health code. It is
read-only. When more than three lanes need attention, other commands print one
summary line with those counts instead of one warning per lane.
+Persistent stack replay desks created by Syncwheel also appear in `worktree
+list`; JSON output lists them under `desks`. Use `stack release-desk STACK`
+to preview their recovery and removal before archiving a stack. The apply
+requires the reviewed plan digest and confirmation that writers have stopped.
+It retains the tip, index and working changes in local recovery refs before
+removing the checkout. See [desk release](docs/stack-archive.md#release-a-replay-desk)
+for the command sequence and the explicit path selection for older desks.
+
`status` without `--fetch`, `check --no-fetch`, and `worktree list` preserve
control metadata, including authorization records, persistent caches and
startup state. They do not start update maintenance or clean up stale authorization records. Delivery
diff --git a/VERSION b/VERSION
index 571e045..ccecd68 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.47.21
+0.47.22
diff --git a/docs/index.html b/docs/index.html
index 148ab9a..93767fd 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -1826,7 +1826,7 @@
-
AI-ready Git coordination v0.47.21
+
AI-ready Git coordination v0.47.22
Move at machine speed. Stay in control.
Syncwheel coordinates every Git lane used by humans, AI agents, CI and delivery systems—without sacrificing review, safety or recovery.
@@ -2602,7 +2602,7 @@
Your first verified plan in minutes.
- syncwheel v0.47.21 · MIT · a NestDevLab project
+ syncwheel v0.47.22 · MIT · a NestDevLab project
diff --git a/docs/stack-archive.md b/docs/stack-archive.md
index 1492076..cbbb274 100644
--- a/docs/stack-archive.md
+++ b/docs/stack-archive.md
@@ -47,3 +47,41 @@ completed request is idempotent and cannot archive a newly recreated stack.
Inspect `syncwheel ledger show` for the receipt. To resume, inspect the retained
commits and create a new native stack with the reviewed endpoints; archival does
not automatically restore or apply deferred content.
+
+## Release a replay desk
+
+A source branch checked out in a persistent replay desk must be released before
+archiving its stack. Desks created by `stack rebuild --replay-mode desk` are
+registered separately from writer lanes and appear in `worktree list --json`
+under `desks`. A pre-existing checkout reused during replay is not automatically
+registered as a Syncwheel desk.
+
+Stop the desk's editors, builds and other writers, then preview and apply the
+same request with the returned digest:
+
+```bash
+syncwheel stack release-desk feature --reason "Release completed review checkout"
+syncwheel stack release-desk feature --reason "Release completed review checkout" \
+ --plan-digest DIGEST --confirm-writers-stopped --apply
+```
+
+For a desk created before registration was available, verify its ownership and
+add `--legacy-worktree PATH` to both commands. This explicitly selects one
+checkout; a matching pathname alone does not establish ownership. The primary,
+governed writer lanes and ambiguous checkouts are not eligible for this path.
+Keep the same `--personal` or `--manifest` selection that identified the stack.
+
+The preview binds the selected stack, checkout identity, source tip, index and
+files. Apply rechecks those inputs, saves the tip and separate index, staged and
+working state in local recovery refs, and verifies recovery before removing the
+checkout and Git registration. The source branch remains available. Retain the
+returned `recoveryRefs`; these are local recovery evidence, not a remote backup.
+
+`--confirm-writers-stopped` is an operator attestation. A Git worktree lock does
+not stop a process that already has a file open. Detected changes preserve the
+desk or its reported quarantine instead of completing removal. Unsupported
+states or data must be resolved without discarding them before release. If a
+removal is interrupted, follow the printed recovery instruction for that exact
+plan; a replacement checkout at the same path is not the original desk.
+
+After a successful release, retry the original `stack archive` preview.
diff --git a/openpack.json b/openpack.json
index 2189504..1d32424 100644
--- a/openpack.json
+++ b/openpack.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 2,
"name": "NestDevLab/syncwheel",
- "version": "0.47.21",
+ "version": "0.47.22",
"provides": [
{
"type": "skills",
diff --git a/pyproject.toml b/pyproject.toml
index 04b3d7e..dda19bd 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -33,6 +33,7 @@ py-modules = [
"syncwheel_coordination",
"syncwheel_journal_workflow",
"syncwheel_replay",
+ "syncwheel_desks",
"syncwheel_worktrees",
"syncwheel_coordination_state",
"syncwheel_publication_intents",
diff --git a/scripts/syncwheel.py b/scripts/syncwheel.py
index 5dd61ed..f52563a 100755
--- a/scripts/syncwheel.py
+++ b/scripts/syncwheel.py
@@ -50,6 +50,7 @@
)
import syncwheel_manifest_store as _manifest_storage
+from syncwheel_desks import DeskLifecycle
from syncwheel_manifest_store import (
ManifestStore,
CONTROL_MANIFEST_EXPLICIT_RECOVERY_IDENTITY_VERSION,
@@ -508,6 +509,7 @@
MANAGED_PUSH_SECRET_ENV = 'SYNCWHEEL_PUSH_AUTH_SECRET'
MANAGED_PUSH_AUTH_TTL_SECONDS = 60
_READONLY_DIAGNOSTICS = ContextVar('readonly_diagnostics', default=False)
+_EXPLICIT_REF_AUTHORIZATION = ContextVar('explicit_ref_authorization', default=False)
SYNCWHEEL_OWNS_REF_MOVES = False
SYNCWHEEL_REF_AUTH_REPO = None
SYNCWHEEL_REF_AUTH_TTL_SECONDS = 30
@@ -604,7 +606,11 @@ def managed_process_env(extra=None, authorize=True):
for name in AMBIENT_GIT_LOCATION_ENV:
process_env.pop(name, None)
diagnostics = _READONLY_DIAGNOSTICS.get()
- if not diagnostics and authorize and SYNCWHEEL_OWNS_REF_MOVES and SYNCWHEEL_REF_AUTH_REPO:
+ explicit_authorization = _EXPLICIT_REF_AUTHORIZATION.get()
+ if explicit_authorization:
+ process_env.pop(MANAGED_REF_MOVE_AUTH_ENV, None)
+ if (not diagnostics and not explicit_authorization and authorize
+ and SYNCWHEEL_OWNS_REF_MOVES and SYNCWHEEL_REF_AUTH_REPO):
process_env[MANAGED_REF_MOVE_AUTH_ENV] = authorize_ref_move(SYNCWHEEL_REF_AUTH_REPO)
if extra:
process_env.update(extra)
@@ -11913,16 +11919,20 @@ def command_worktree_list(args):
lane for lane in diagnostics['lanes']
if not args.problems or lane.get('code')
]
+ desks = _desk_lifecycle(repo_root).desks()
if args.json:
print(json.dumps({
'registryPath': diagnostics['registry_path'],
'lanes': lanes,
+ 'desks': desks if not args.problems else [],
'counts': governed_worktree_problem_counts(diagnostics['lanes']),
}, indent=2, sort_keys=True))
return 0
- if not lanes:
+ for desk in desks if not args.problems else ():
+ print(f"{desk['stack']} kind=replay-desk branch={desk['branch']}")
+ print(f" path: {desk['path']}")
+ if not lanes and (not desks or args.problems):
print('no governed worktree lanes' + (' need attention' if args.problems else ''))
- return 0
for lane in lanes:
label = lane.get('id') or lane.get('branch') or lane.get('path')
print(
@@ -12073,6 +12083,10 @@ def command_worktree_open(args):
}
run(['git', 'worktree', 'add', '-b', branch, str(path), base], cwd=repo_root)
try:
+ admin = governed_worktree_admin_dir_for_path(repo_root, path)
+ if not admin:
+ raise SyncwheelError('cannot prove the new governed worktree Git administration')
+ lane['admin_dir'] = str(admin)
if base_ref and can_materialize:
created = git(
repo_root, 'update-ref', '--no-deref', stack_branch_ref, base,
@@ -15483,6 +15497,35 @@ def verify_stack_archive_proof(repo_root, proof, stack=None):
)
+def command_stack_release_desk(args):
+ repo_root, manifest_path = resolve_command_manifest_selection(args)
+ manifest_path = Path(os.path.abspath(manifest_path))
+ require_stack_sync_metadata_paths(repo_root, manifest_path)
+ manifest, _ = _manifest_storage.load_manifest(repo_root, manifest_path)
+ if not manifest:
+ raise SyncwheelError(f'manifest not found: {manifest_path}')
+ require_delivery_manifest(manifest)
+ stack = require_stack(manifest, args.stack)
+
+ def require_no_writer():
+ current, _ = _manifest_storage.load_manifest(repo_root, manifest_path)
+ if not current or manifest_digest(current) != manifest_digest(manifest):
+ raise SyncwheelError('selected manifest changed during desk release')
+ roots = {repo_root, primary_authority_manifest_path(repo_root).parent.parent}
+ for root in roots:
+ _, coordination = coordination_profile(root)
+ if stack['id'] in (coordination.get('locks') or {}) or local_lease_is_active(coordination):
+ raise SyncwheelError('desk release refuses an active worktree lock or coordination lease')
+
+ require_no_writer()
+ try:
+ result = _desk_lifecycle(repo_root).release(args, manifest, manifest_path, stack, require_no_writer)
+ except OSError as error:
+ raise SyncwheelError(f'desk release could not complete: {error}') from error
+ print(json.dumps(result, indent=2, sort_keys=True))
+ return 0
+
+
def command_stack_archive(args):
repo_root = resolve_repo_root(args.repo)
manifest, manifest_path = require_manifest(repo_root, args.repo, args.manifest, args.personal)
@@ -20448,15 +20491,22 @@ def main():
command_hooks_ref_guard,
}
global SYNCWHEEL_OWNS_REF_MOVES, SYNCWHEEL_REF_AUTH_REPO
- readonly_diagnostics = args.func == command_worktree_list or (
- args.func in {command_status, command_check} and not args.fetch
+ desk_release = args.func == command_stack_release_desk
+ readonly_diagnostics = (
+ args.func == command_worktree_list
+ or (args.func in {command_status, command_check} and not args.fetch)
+ or (desk_release and not args.apply)
)
try:
- if readonly_diagnostics:
- diagnostic_scope = _READONLY_DIAGNOSTICS.set(True)
+ if desk_release:
+ args.repo = args.repo or os.environ.get(ENV_REPO)
+ if readonly_diagnostics or desk_release:
+ diagnostic_scope = _READONLY_DIAGNOSTICS.set(readonly_diagnostics)
+ authorization_scope = _EXPLICIT_REF_AUTHORIZATION.set(desk_release and args.apply)
try:
return args.func(args)
finally:
+ _EXPLICIT_REF_AUTHORIZATION.reset(authorization_scope)
_READONLY_DIAGNOSTICS.reset(diagnostic_scope)
if args.func in {command_repo_tracking_set, command_repo_tracking_status}:
args.repo = args.repo or os.environ.get(ENV_REPO)
@@ -20537,7 +20587,7 @@ def main():
print(f'error: {exc}', file=sys.stderr)
return 2
finally:
- if not readonly_diagnostics:
+ if not readonly_diagnostics and not desk_release:
if SYNCWHEEL_REF_AUTH_REPO:
clear_ref_authorizations(SYNCWHEEL_REF_AUTH_REPO)
SYNCWHEEL_REF_AUTH_REPO = None
@@ -20670,6 +20720,7 @@ def command_handlers():
'command_stack_absorb': command_stack_absorb,
'command_stack_add': command_stack_add,
'command_stack_archive': command_stack_archive,
+ 'command_stack_release_desk': command_stack_release_desk,
'command_stack_capture_integration': command_stack_capture_integration,
'command_stack_classify_integration': command_stack_classify_integration,
'command_stack_close': command_stack_close,
@@ -21417,7 +21468,35 @@ def get_current_branch(self, *args, **kwargs):
def get_worktrees(self, *args, **kwargs):
return get_worktrees(*args, **kwargs)
- def capture_ref_transaction(self, operations):
+ def binary_git(self, path, *args, input_data=None, index=None, recovery_identity=False):
+ env = {'GIT_OPTIONAL_LOCKS': '0'}
+ if index is not None:
+ env['GIT_INDEX_FILE'] = str(index)
+ if recovery_identity:
+ for role in ('AUTHOR', 'COMMITTER'):
+ env.update({f'GIT_{role}_NAME': 'Syncwheel',
+ f'GIT_{role}_EMAIL': 'syncwheel@example.invalid',
+ f'GIT_{role}_DATE': '2000-01-01T00:00:00+00:00'})
+ result = subprocess.run(
+ ['git', '-c', 'commit.gpgsign=false', *args], cwd=path, input=input_data,
+ env=managed_process_env(env, authorize=False), capture_output=True,
+ )
+ if result.returncode:
+ raise SyncwheelError(result.stderr.decode(errors='replace').strip() or 'desk snapshot Git command failed')
+ return result.stdout
+
+ def write_desk_intent(self, path, payload):
+ common = git_common_dir(self.root)
+ require_private_tracking_path(common, path)
+ atomic_write_private_json(path, payload, indent=2)
+ fsync_directory_path(path.parent)
+ fsync_directory_path(path.parent.parent)
+
+ def publish_desk_recovery_refs(self, operations):
+ with ref_move_authorization(self.root) as nonce:
+ self.capture_ref_transaction(operations, {MANAGED_REF_MOVE_AUTH_ENV: nonce})
+
+ def capture_ref_transaction(self, operations, authorization=None):
commands = ['start']
for operation in operations:
commands.extend(('option no-deref', operation))
@@ -21425,7 +21504,7 @@ def capture_ref_transaction(self, operations):
# that same OID. Inspect ref kinds after Git has acquired its locks.
with tempfile.TemporaryFile(mode='w+t') as errors, subprocess.Popen(
['git', 'update-ref', '--stdin'],
- cwd=self.root, env=managed_process_env(),
+ cwd=self.root, env=managed_process_env(authorization),
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errors, text=True,
) as process:
def close_transaction():
@@ -21545,6 +21624,36 @@ def load_ledger_events(self, *args, **kwargs):
return _manifest_storage.load_ledger_events(*args, **kwargs)
class _StackProjections:
+ def register_created_desk(self, repo_root, manifest_path, stack, path):
+ return _desk_lifecycle(repo_root).register_created(manifest_path, stack, path)
+
+ def archive_desk_remedy(self, repo_root, manifest_path, stack, worktree):
+ primary = primary_authority_manifest_path(repo_root).parent.parent
+ selected = manifest_path or primary / '.syncwheel/manifest.json'
+ desks = _desk_lifecycle(repo_root)
+ pending = desks.pending_release(selected, stack)
+ args = ['syncwheel', 'stack', 'release-desk', stack['id']]
+ if pending:
+ args.extend(('--reason', pending['reason']))
+ if pending['legacy']:
+ args.extend(('--legacy-worktree', pending['path']))
+ args.extend(('--confirm-writers-stopped', '--plan-digest', pending['planDigest'], '--apply'))
+ elif worktree:
+ worktree = Path(worktree).resolve()
+ if worktree == primary:
+ return 'preserve the primary checkout and move the stack authoring work to a separate desk'
+ registry, _ = _governed_worktrees(repo_root).load_governed_worktree_registry()
+ desks.require_no_lane(registry, stack, worktree, governed_worktree_admin_dir_for_path(repo_root, worktree))
+ args.extend(('--reason', 'Release the stack desk'))
+ if not any(item['path'] == str(Path(worktree).resolve()) and item['stack'] == stack['id']
+ and item['manifest'] == str(selected.resolve()) for item in desks.desks()):
+ args.extend(('--legacy-worktree', str(worktree)))
+ else:
+ return None
+ args.extend(manifest_path_remedy_options(repo_root, selected))
+ action = 'confirm that writers are stopped and resume' if pending else 'inspect ownership and preview'
+ return f'{action} with {shlex.join(args)}'
+
def checkout_reset_destination_lease(self, *args, **kwargs):
return checkout_reset_destination_lease(*args, **kwargs)
@@ -21577,6 +21686,10 @@ def command_stack_close(self, *args, **kwargs):
return command_stack_close(*args, **kwargs)
+def _desk_lifecycle(repo_root):
+ return DeskLifecycle(_StackRepository(repo_root), _governed_worktrees(repo_root))
+
+
def _stack_lifecycle(repo_root):
return StackLifecycle(
_StackRepository(repo_root), _StackControl(), _StackLedger(),
diff --git a/scripts/syncwheel_cli.py b/scripts/syncwheel_cli.py
index 03b00e0..65a0253 100644
--- a/scripts/syncwheel_cli.py
+++ b/scripts/syncwheel_cli.py
@@ -1004,6 +1004,18 @@ def build_parser(commands, version):
stack_merge_pr_p.add_argument('-j', '--json', action='store_true')
stack_merge_pr_p.set_defaults(func=commands['command_stack_merge_pr'])
+ stack_release_desk_p = stack_sub.add_parser(
+ 'release-desk', parents=[common], help='preserve and release a stack replay desk',
+ )
+ stack_release_desk_p.add_argument('stack')
+ stack_release_desk_p.add_argument('--legacy-worktree')
+ stack_release_desk_p.add_argument('--reason', required=True)
+ stack_release_desk_p.add_argument('--confirm-writers-stopped', action='store_true')
+ stack_release_desk_p.add_argument('--plan-digest')
+ stack_release_desk_p.add_argument('-a', '--apply', action='store_true')
+ stack_release_desk_p.add_argument('-j', '--json', action='store_true')
+ stack_release_desk_p.set_defaults(func=commands['command_stack_release_desk'])
+
stack_archive_p = stack_sub.add_parser(
'archive', parents=[common], help='retain source history and defer a stack without delivery claims',
)
@@ -1162,6 +1174,7 @@ def register(
commands['command_worktree_unlock'],
), mutates='always')
register((commands['command_worktree_open'],), mutates='always', remedy=True)
+ register((commands['command_stack_release_desk'],), mutates='apply')
register((commands['command_stack_set'],), mutates='stack-set', manifest_mutates='stack-set')
register((commands['command_stack_close'], commands['command_stack_sync']), mutates='always',
manifest_mutates='always', primary_scope='metadata')
diff --git a/scripts/syncwheel_desks.py b/scripts/syncwheel_desks.py
new file mode 100644
index 0000000..a26a61c
--- /dev/null
+++ b/scripts/syncwheel_desks.py
@@ -0,0 +1,485 @@
+"""Ownership and recoverable removal of persistent stack replay desks."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import stat
+import sys
+import tempfile
+from typing import Protocol
+
+from syncwheel_errors import SyncwheelError
+from syncwheel_manifest import canonical_json_digest, manifest_digest, safe_ref_segment
+
+
+class DeskRepository(Protocol):
+ root: Path
+
+ def git(self, *args, **kwargs): ...
+ def get_worktrees(self, *args, **kwargs): ...
+ def ref_tip(self, *args, **kwargs): ...
+ def publish_desk_recovery_refs(self, operations): ...
+ def binary_git(self, path, *args, **kwargs): ...
+ def write_desk_intent(self, path, payload): ...
+
+
+class DeskLifecycle:
+ def __init__(self, repo, worktrees):
+ self.repo = repo
+ self.worktrees = worktrees
+
+ def desks(self):
+ registry, _ = self.worktrees.load_governed_worktree_registry()
+ return registry.get('desks', [])
+
+ def identity(self, path, stack):
+ root = self.repo.root
+ records = self.repo.get_worktrees(root)
+ matches = [record for record in records
+ if record.get('branch') == stack['branch']]
+ if (not records or not records[0].get('path') or Path(records[0]['path']).resolve() == path
+ or len(matches) != 1 or Path(matches[0]['path']).resolve() != path):
+ raise SyncwheelError('desk requires the exact linked checkout of the selected stack branch')
+ if matches[0].get('locked') or matches[0].get('prunable'):
+ raise SyncwheelError('desk checkout is locked or has a stale Git registration')
+ if Path.cwd().resolve().is_relative_to(path):
+ raise SyncwheelError('run desk release from outside the checkout being released')
+ admin = self.worktrees.governed_worktree_admin_dir_for_path(path)
+ actual = Path(self.repo.git(path, 'rev-parse', '--absolute-git-dir').stdout.strip()).resolve()
+ if (not admin or admin != actual or (path / '.git').is_symlink()
+ or not (path / '.git').is_file()):
+ raise SyncwheelError('desk Git administration identity could not be verified')
+ source_ref = f"refs/heads/{stack['branch']}"
+ tip = self.repo.ref_tip(root, source_ref)
+ if matches[0].get('HEAD') != tip or not tip:
+ raise SyncwheelError('desk source tip changed while reading its registration')
+ if self.repo.git(root, 'symbolic-ref', '--quiet', source_ref, check=False).returncode == 0:
+ raise SyncwheelError('desk requires a direct stack branch')
+ return admin, tip
+
+ def require_no_lane(self, registry, stack, path, admin=None):
+ active = [lane for lane in registry['lanes']
+ if lane.get('state') != 'reaped' or lane.get('pending_reason')]
+ for lane in active:
+ registered_path = Path(lane['path']).resolve()
+ recorded_admin = lane.get('cleanup_admin_dir') or lane.get('admin_dir')
+ if (registered_path == path or lane.get('branch') == stack['branch']
+ or lane.get('target') == stack['id']
+ or (admin and recorded_admin and Path(recorded_admin).resolve() == admin)):
+ raise SyncwheelError(
+ f"governed worktree lane {lane['id']} overlaps the desk; resolve it through worktree list/release"
+ )
+ if admin and not recorded_admin and not self.worktrees.governed_worktree_admin_dir_for_path(
+ registered_path
+ ):
+ records = self.repo.get_worktrees(self.repo.root)
+ if not any(record.get('branch') == lane['branch'] for record in records):
+ raise SyncwheelError(
+ f"cannot prove desk is distinct from governed lane {lane['id']}; inspect syncwheel worktree list"
+ )
+
+ def register_created(self, manifest_path, stack, path):
+ with self.worktrees.governed_worktree_registry_lock():
+ registry, _ = self.worktrees.load_governed_worktree_registry()
+ persist = self.worktrees.governed_worktree_registry_cas_persister(registry)
+ path = Path(path).resolve()
+ self.require_no_lane(registry, stack, path)
+ admin, _ = self.identity(path, stack)
+ self.require_no_lane(registry, stack, path, admin)
+ records = registry.setdefault('desks', [])
+ record = {'stack': stack['id'], 'branch': stack['branch'], 'path': str(path),
+ 'manifest': str(manifest_path.resolve()), 'admin': str(admin),
+ 'identity': list(file_identity(admin)), 'checkoutIdentity': list(file_identity(path)),
+ 'kind': 'replay-desk'}
+ if any(item['path'] == str(path) or item['admin'] == str(admin) for item in records):
+ raise SyncwheelError('desk registration overlaps an existing desk record')
+ records.append(record)
+ persist()
+
+ def select(self, registry, manifest_path, stack, legacy):
+ records = registry.get('desks', [])
+ matching = [item for item in records if item['stack'] == stack['id']
+ and item['manifest'] == str(manifest_path.resolve())]
+ if legacy is None and len(matching) != 1:
+ raise SyncwheelError('no uniquely registered desk; inspect the linked checkout and preview with --legacy-worktree PATH --reason REASON')
+ if legacy is not None and matching:
+ raise SyncwheelError('a registered desk exists for this stack; omit --legacy-worktree')
+ path = Path(legacy).expanduser().absolute() if legacy is not None else Path(matching[0]['path'])
+ if path.resolve() != path:
+ raise SyncwheelError('desk path must name the exact checkout without symbolic aliases')
+ self.require_no_lane(registry, stack, path)
+ if legacy is not None and any(item['path'] == str(path) or item['branch'] == stack['branch']
+ for item in records):
+ raise SyncwheelError('legacy checkout overlaps another registered desk')
+ record = matching[0] if matching else None
+ if record:
+ if not (self.check_identity(path, record['checkoutIdentity'], directory=True)
+ and self.check_identity(Path(record['admin']), record['identity'], directory=True)):
+ raise SyncwheelError('registered desk checkout or Git administration is missing')
+ return path, record
+
+ def observe(self, path, stack):
+ admin, source_tip = self.identity(path, stack)
+ for marker in ('index.lock', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD',
+ 'rebase-apply', 'rebase-merge', 'sequencer', 'BISECT_LOG'):
+ if (admin / marker).exists():
+ raise SyncwheelError(f'desk has an interrupted Git operation ({marker}); finish or abort it before release')
+ if self.repo.git(path, 'rev-parse', '--shared-index-path').stdout.strip():
+ raise SyncwheelError('desk release cannot preserve a split index')
+ if self.repo.binary_git(path, 'ls-files', '-u', '-z'):
+ raise SyncwheelError('desk index has unresolved conflicts')
+ if self.repo.binary_git(path, 'ls-files', '--others', '--ignored', '--exclude-standard', '-z'):
+ raise SyncwheelError('desk has ignored files; preserve or relocate them before release')
+ if b'160000 ' in self.repo.binary_git(path, 'ls-files', '--stage', '-z'):
+ raise SyncwheelError('desk release cannot preserve a submodule checkout')
+ raw_index, index_mode, _ = read_regular(admin / 'index')
+ entries, content = self.scan_checkout(path)
+ untracked = [os.fsdecode(part) for part in self.repo.binary_git(
+ path, 'ls-files', '--others', '--exclude-standard', '-z',
+ ).split(b'\0') if part]
+ return {'admin': str(admin), 'identity': list(file_identity(admin)),
+ 'checkoutIdentity': list(file_identity(path)), 'sourceTip': source_tip,
+ 'indexSha256': hashlib.sha256(raw_index).hexdigest(), 'indexMode': index_mode,
+ 'rootMode': stat.S_IMODE(path.stat(follow_symlinks=False).st_mode), 'files': entries,
+ 'untracked': sorted(untracked)}, raw_index, content
+
+ def scan_checkout(self, path):
+ entries = {}
+ content = {}
+ require_supported_metadata(path)
+ for directory, folders, names in os.walk(path, followlinks=False, onerror=raise_walk_error):
+ base = Path(directory)
+ for name in [*folders, *names]:
+ item = base / name
+ if item == path / '.git':
+ if name in folders:
+ folders.remove(name)
+ continue
+ if name.casefold() == '.git':
+ raise SyncwheelError('desk contains a nested Git checkout')
+ relative = item.relative_to(path).as_posix()
+ require_supported_metadata(item)
+ observed = item.lstat()
+ mode = stat.S_IMODE(observed.st_mode)
+ if stat.S_ISDIR(observed.st_mode):
+ entries[relative] = {'type': 'directory', 'mode': mode}
+ continue
+ if stat.S_ISLNK(observed.st_mode):
+ payload = os.fsencode(os.readlink(item))
+ kind = 'symlink'
+ if name in folders:
+ folders.remove(name)
+ elif stat.S_ISREG(observed.st_mode):
+ payload, mode, _ = read_regular(item)
+ kind = 'file'
+ else:
+ raise SyncwheelError(f'desk contains unsupported special data: {relative}')
+ entries[relative] = {'type': kind, 'mode': mode,
+ 'sha256': hashlib.sha256(payload).hexdigest()}
+ content[relative] = payload
+ return entries, content
+
+ def make_objects(self, path, snapshot, index, content):
+ def write_blob(data):
+ return self.repo.binary_git(path, 'hash-object', '-w', '--stdin', input_data=data).decode().strip()
+
+ def write_commit(tree, parent, message):
+ return self.repo.binary_git(
+ path, 'commit-tree', tree, '-p', parent, '-m', message, recovery_identity=True,
+ ).decode().strip()
+
+ with tempfile.TemporaryDirectory(prefix='syncwheel-desk-index-') as temporary:
+ staged_index = Path(temporary) / 'staged'
+ staged_index.write_bytes(index)
+ staged_tree = self.repo.binary_git(path, 'write-tree', index=staged_index).decode().strip()
+ staged = write_commit(staged_tree, snapshot['sourceTip'], 'Syncwheel desk staged snapshot')
+ working_index = Path(temporary) / 'working'
+ self.repo.binary_git(path, 'read-tree', '--empty', index=working_index)
+ records = []
+ for name, payload in sorted(content.items()):
+ entry = snapshot['files'][name]
+ mode = desk_tree_mode(entry)
+ records.append(f'{mode} {write_blob(payload)}\t'.encode() + os.fsencode(name) + b'\0')
+ self.repo.binary_git(path, 'update-index', '-z', '--index-info',
+ index=working_index, input_data=b''.join(records))
+ working_tree = self.repo.binary_git(path, 'write-tree', index=working_index).decode().strip()
+ working = write_commit(working_tree, staged, 'Syncwheel desk working snapshot')
+ return {'tip': snapshot['sourceTip'], 'index': write_blob(index),
+ 'staged': staged, 'working': working,
+ 'receipt': write_blob(json.dumps(snapshot, sort_keys=True).encode())}
+
+ def release(self, args, manifest, manifest_path, stack, require_no_writer):
+ if not args.reason.strip():
+ raise SyncwheelError('desk release requires a nonempty --reason')
+ if args.apply:
+ if not args.confirm_writers_stopped or not args.plan_digest:
+ raise SyncwheelError('desk release requires --confirm-writers-stopped and the reviewed --plan-digest')
+ if len(args.plan_digest) != 64 or any(char not in '0123456789abcdef' for char in args.plan_digest):
+ raise SyncwheelError('invalid desk release plan digest')
+ with self.worktrees.governed_worktree_registry_lock():
+ require_no_writer()
+ return self.release_locked(args, manifest, manifest_path, stack, require_no_writer)
+ registry, _ = self.worktrees.load_governed_worktree_registry()
+ path, record = self.select(registry, manifest_path, stack, args.legacy_worktree)
+ snapshot, _, _ = self.observe(path, stack)
+ self.require_no_lane(registry, stack, path, Path(snapshot['admin']))
+ return self.plan(args, manifest, manifest_path, stack, path, record, snapshot)
+
+ def plan(self, args, manifest, manifest_path, stack, path, record, snapshot):
+ if record and any(record[key] != snapshot[key] for key in ('admin', 'identity')):
+ raise SyncwheelError('registered desk identity changed')
+ plan = {'status': 'planned', 'stack': stack['id'], 'path': str(path), 'sourceTip': snapshot['sourceTip'],
+ 'sourceRef': f"refs/heads/{stack['branch']}", 'reason': args.reason,
+ 'manifest': str(manifest_path.resolve()), 'manifestDigest': manifest_digest(manifest),
+ 'legacy': args.legacy_worktree is not None, 'desk': record, 'snapshot': snapshot}
+ digest = canonical_json_digest(plan)
+ prefix = f"refs/syncwheel/desk-recovery/{safe_ref_segment(stack['id'])}/{digest}"
+ return {**plan, 'planDigest': digest,
+ 'recoveryRefs': {kind: f'{prefix}/{kind}' for kind in ('tip', 'index', 'staged', 'working', 'receipt')}}
+
+ def intent_directory(self):
+ parent = self.worktrees.governed_worktree_registry_path().parent
+ directory = parent / 'desk-release'
+ for path in (parent, directory):
+ if os.path.lexists(path) and not stat.S_ISDIR(path.lstat().st_mode):
+ raise SyncwheelError(f'desk release intent directory is redirected: {path}')
+ return directory
+
+ def pending_release(self, manifest_path, stack):
+ pending = []
+ for path in sorted(self.intent_directory().glob('*.json')):
+ intent = read_intent(path)
+ plan = intent['plan']
+ if (not intent.get('released') and plan['manifest'] == str(manifest_path.resolve())
+ and plan['stack'] == stack['id'] and plan['sourceRef'] == f"refs/heads/{stack['branch']}"):
+ pending.append(plan)
+ if len(pending) > 1:
+ raise SyncwheelError('multiple pending desk release plans; inspect their recovery receipts')
+ return pending[0] if pending else None
+
+ def check_identity(self, path, expected, *, directory):
+ if path.parent.resolve() != path.parent:
+ raise SyncwheelError(f'desk identity has a symbolic parent; kept {path}')
+ if not os.path.lexists(path):
+ return False
+ value = path.lstat()
+ if stat.S_ISLNK(value.st_mode):
+ raise SyncwheelError(f'desk identity was replaced by a symbolic link; kept {path}')
+ if (directory and not stat.S_ISDIR(value.st_mode)) or [value.st_dev, value.st_ino] != expected:
+ raise SyncwheelError(f'desk identity was replaced; kept {path}')
+ return True
+
+ def release_locked(self, args, manifest, manifest_path, stack, require_no_writer):
+ registry, _ = self.worktrees.load_governed_worktree_registry()
+ persist = self.worktrees.governed_worktree_registry_cas_persister(registry)
+ intent_path = self.intent_directory() / f'{args.plan_digest}.json'
+ pending = self.pending_release(manifest_path, stack)
+ if pending and pending['planDigest'] != args.plan_digest:
+ raise SyncwheelError('another desk release plan is pending; retry that exact plan')
+ if os.path.lexists(intent_path):
+ intent = read_intent(intent_path)
+ plan, objects = intent['plan'], intent['objects']
+ if (plan['stack'] != stack['id'] or plan['reason'] != args.reason
+ or plan['manifest'] != str(manifest_path.resolve())
+ or plan['manifestDigest'] != manifest_digest(manifest)
+ or (args.legacy_worktree is not None) != plan['legacy']
+ or (args.legacy_worktree and str(Path(args.legacy_worktree).expanduser().absolute()) != plan['path'])):
+ raise SyncwheelError('desk release retry must match the prepared request')
+ path = Path(plan['path'])
+ self.require_no_lane(registry, stack, path, Path(plan['snapshot']['admin']))
+ if intent.get('released'):
+ self.verify_refs(plan, objects)
+ self.verify_objects(plan, objects)
+ return {**plan, 'status': 'released'}
+ else:
+ path, record = self.select(registry, manifest_path, stack, args.legacy_worktree)
+ snapshot, index, content = self.observe(path, stack)
+ self.require_no_lane(registry, stack, path, Path(snapshot['admin']))
+ plan = self.plan(args, manifest, manifest_path, stack, path, record, snapshot)
+ if args.plan_digest != plan['planDigest']:
+ raise SyncwheelError('desk release plan is stale; review a new preview')
+ if Path(plan['snapshot']['admin']).is_relative_to(path):
+ raise SyncwheelError('desk Git administration is inside the checkout')
+ objects = self.make_objects(path, snapshot, index, content)
+ self.verify_objects(plan, objects)
+ if self.observe(path, stack)[0] != snapshot:
+ raise SyncwheelError('desk changed while creating recovery snapshots')
+ intent = {'plan': plan, 'objects': objects}
+ self.repo.write_desk_intent(intent_path, intent)
+ quarantine = path.with_name(f'.syncwheel-desk-release-{plan["planDigest"][:16]}')
+ admin = Path(plan['snapshot']['admin'])
+ snapshot = plan['snapshot']
+ relocated = os.path.lexists(quarantine)
+ current = quarantine if relocated else path
+ has_admin = self.check_identity(admin, snapshot['identity'], directory=True)
+ removing = intent.get('removing') is True
+ if removing and not relocated and os.path.lexists(path):
+ # The original path no longer belongs to this operation. Never inspect
+ # or remove a checkout that appeared there after the move.
+ print(f'warning: original desk path has a replacement; kept {path}', file=sys.stderr)
+ current = quarantine
+ has_checkout = self.check_identity(current, snapshot['checkoutIdentity'], directory=True)
+ if removing:
+ self.verify_refs(plan, objects)
+ self.verify_objects(plan, objects)
+ if has_checkout and has_admin:
+ if relocated and os.path.lexists(path):
+ raise SyncwheelError(f'original desk path was replaced; kept it and the relocated desk at {quarantine}')
+ observed, index, content = self.observe(current, stack)
+ if observed != snapshot:
+ raise SyncwheelError(f'desk changed after preview; retained at {current}')
+ if not removing and any(self.repo.git(
+ self.repo.root, 'cat-file', '-e', oid, check=False,
+ ).returncode for oid in objects.values()):
+ recovered = self.make_objects(current, snapshot, index, content)
+ if recovered != objects:
+ raise SyncwheelError('regenerated desk objects differ from the reviewed recovery intent')
+ self.verify_objects(plan, objects)
+ if self.observe(current, stack)[0] != snapshot:
+ raise SyncwheelError(f'desk changed during recovery object regeneration; retained at {current}')
+ commands = [f"verify {plan['sourceRef']} {plan['sourceTip']}"]
+ for kind, ref in plan['recoveryRefs'].items():
+ oid = objects[kind]
+ existing = self.repo.git(self.repo.root, 'show-ref', '--verify', '--hash', ref, check=False).stdout.strip()
+ commands.append(f'verify {ref} {oid}' if existing else f'create {ref} {oid}')
+ self.repo.publish_desk_recovery_refs(commands)
+ self.verify_refs(plan, objects)
+ self.verify_objects(plan, objects)
+ require_no_writer()
+ if self.observe(current, stack)[0] != snapshot:
+ raise SyncwheelError(f'desk changed after recovery refs were published; retained at {current}')
+ if current == path:
+ self.repo.git(self.repo.root, 'worktree', 'move', str(path), str(quarantine))
+ if os.path.lexists(path):
+ raise SyncwheelError(f'original desk path was replaced; kept it and the relocated desk at {quarantine}')
+ self.check_identity(quarantine, snapshot['checkoutIdentity'], directory=True)
+ if self.observe(quarantine, stack)[0] != snapshot:
+ raise SyncwheelError(f'desk changed after relocation; retained at {quarantine}')
+ self.repo.write_desk_intent(intent_path, {**intent, 'removing': True})
+ self.verify_refs(plan, objects)
+ self.repo.git(self.repo.root, 'worktree', 'remove', '--force', str(quarantine))
+ elif removing and has_admin:
+ registrations = [record for record in self.repo.get_worktrees(self.repo.root)
+ if record.get('path') and Path(record['path']) == quarantine]
+ if (len(registrations) != 1 or registrations[0].get('locked')
+ or registrations[0].get('branch') != stack['branch']
+ or self.worktrees.governed_worktree_admin_dir_for_path(quarantine) != admin):
+ raise SyncwheelError('desk administrative residue changed; kept it for inspection')
+ self.repo.git(self.repo.root, 'worktree', 'remove', '--force', str(quarantine))
+ elif removing and has_checkout and relocated:
+ remaining, _ = self.scan_checkout(quarantine)
+ if any(snapshot['files'].get(name) != entry for name, entry in remaining.items()):
+ raise SyncwheelError(f'partial desk removal found new data; kept {quarantine}')
+ shutil.rmtree(quarantine)
+ elif not removing:
+ raise SyncwheelError('desk release registration or checkout changed before removal; recovery files retained')
+ self.verify_refs(plan, objects)
+ if os.path.lexists(quarantine) or os.path.lexists(admin):
+ raise SyncwheelError('desk removal is incomplete; retry the same reviewed plan')
+ record = plan['desk']
+ if record and record in registry.get('desks', []):
+ registry['desks'].remove(record)
+ persist()
+ self.repo.write_desk_intent(intent_path, {'plan': plan, 'objects': objects, 'released': True})
+ return {**plan, 'status': 'released'}
+
+ def verify_refs(self, plan, objects):
+ root = self.repo.root
+ for kind, ref in plan['recoveryRefs'].items():
+ if self.repo.git(root, 'symbolic-ref', '--quiet', ref, check=False).returncode == 0:
+ raise SyncwheelError(f'desk recovery proof became symbolic: {ref}')
+ value = self.repo.git(root, 'show-ref', '--verify', '--hash', ref).stdout.strip()
+ if value != objects[kind]:
+ raise SyncwheelError(f'desk recovery proof changed: {ref}')
+
+
+ def verify_objects(self, plan, objects):
+ root = self.repo.root
+ snapshot = plan['snapshot']
+ read = self.repo.binary_git
+ receipt = read(root, 'cat-file', 'blob', objects['receipt'])
+ index = read(root, 'cat-file', 'blob', objects['index'])
+ if (objects['tip'] != snapshot['sourceTip'] or json.loads(receipt) != snapshot
+ or hashlib.sha256(index).hexdigest() != snapshot['indexSha256']):
+ raise SyncwheelError('desk recovery receipt or raw index failed verification')
+ for kind, parent in (('staged', objects['tip']), ('working', objects['staged'])):
+ ancestry = read(root, 'rev-list', '--parents', '-n', '1', objects[kind]).decode().split()
+ if ancestry != [objects[kind], parent]:
+ raise SyncwheelError(f'desk recovery commit ancestry changed: {kind}')
+ with tempfile.TemporaryDirectory(prefix='syncwheel-desk-proof-') as temporary:
+ index_path = Path(temporary) / 'index'
+ index_path.write_bytes(index)
+ rebuilt = read(root, 'write-tree', index=index_path).decode().strip()
+ staged_tree = read(root, 'rev-parse', f"{objects['staged']}^{{tree}}").decode().strip()
+ if staged_tree != rebuilt:
+ raise SyncwheelError('desk staged tree does not match the recovered index')
+ entries = {}
+ working_tree = read(root, 'ls-tree', '-r', '-z', objects['working'])
+ for row in filter(None, working_tree.split(b'\0')):
+ info, name = row.split(b'\t', 1)
+ mode, kind, oid = info.decode().split()
+ if kind != 'blob':
+ raise SyncwheelError('desk working proof includes unsupported object types')
+ digest = hashlib.sha256(read(root, 'cat-file', 'blob', oid)).hexdigest()
+ entries[os.fsdecode(name)] = (mode, digest)
+ expected = {name: (desk_tree_mode(entry), entry['sha256'])
+ for name, entry in snapshot['files'].items() if entry['type'] != 'directory'}
+ if entries != expected or not set(snapshot['untracked']).issubset(entries):
+ raise SyncwheelError('desk working tree does not reproduce the reviewed snapshot')
+
+
+def desk_tree_mode(entry):
+ if entry['type'] == 'symlink':
+ return '120000'
+ return '100755' if entry['mode'] & 0o100 else '100644'
+
+
+def read_intent(path):
+ try:
+ raw, _, _ = read_regular(path)
+ intent = json.loads(raw)
+ plan = intent['plan']
+ core = {key: value for key, value in plan.items() if key not in {'planDigest', 'recoveryRefs'}}
+ digest = canonical_json_digest(core)
+ kinds = ('tip', 'index', 'staged', 'working', 'receipt')
+ prefix = f"refs/syncwheel/desk-recovery/{safe_ref_segment(plan['stack'])}/{digest}"
+ if (plan['planDigest'] != digest or path.stem != digest
+ or plan['recoveryRefs'] != {kind: f'{prefix}/{kind}' for kind in kinds}
+ or set(intent['objects']) != set(kinds)
+ or any(not isinstance(oid, str) or len(oid) not in (40, 64)
+ or any(ch not in '0123456789abcdef' for ch in oid)
+ for oid in intent['objects'].values())):
+ raise ValueError('intent digest or object identifiers changed')
+ return intent
+ except (OSError, KeyError, ValueError, TypeError) as error:
+ raise SyncwheelError(f'invalid desk release intent at {path}: {error}') from error
+
+
+def require_supported_metadata(path):
+ if hasattr(os, 'listxattr') and os.listxattr(path, follow_symlinks=False):
+ raise SyncwheelError(f'desk contains extended attributes that cannot be preserved: {path}')
+
+
+def raise_walk_error(error):
+ raise error
+
+
+def file_identity(path):
+ value = path.stat(follow_symlinks=False)
+ return value.st_dev, value.st_ino
+
+
+def read_regular(path):
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as handle:
+ before = os.fstat(handle.fileno())
+ if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1:
+ raise SyncwheelError(f'desk snapshot requires a regular file: {path}')
+ payload = handle.read()
+ after = os.fstat(handle.fileno())
+ if (before.st_mtime_ns, before.st_ctime_ns, before.st_size) != (
+ after.st_mtime_ns, after.st_ctime_ns, after.st_size,
+ ):
+ raise SyncwheelError(f'desk file changed during snapshot: {path}')
+ return payload, stat.S_IMODE(before.st_mode), (before.st_dev, before.st_ino)
diff --git a/scripts/syncwheel_replay.py b/scripts/syncwheel_replay.py
index 9fe59bc..3754321 100644
--- a/scripts/syncwheel_replay.py
+++ b/scripts/syncwheel_replay.py
@@ -810,6 +810,9 @@ def execute_replay_steps(self, plan):
raise self.integration_replay_step_failure(
plan, index, exc
) from exc
+ register_desk = plan.get('register_created_desk')
+ if register_desk and argv[:3] == ['git', 'worktree', 'add']:
+ register_desk(Path(argv[-2]))
elif step['kind'] == 'shell':
process_env = self.repository.managed_process_env(step['env'])
result_shell = self.repository.shell(
diff --git a/scripts/syncwheel_stacks.py b/scripts/syncwheel_stacks.py
index 14c2afd..150b3fc 100644
--- a/scripts/syncwheel_stacks.py
+++ b/scripts/syncwheel_stacks.py
@@ -151,6 +151,8 @@ def load_ledger_events(self, *args, **kwargs): ...
class StackProjections(Protocol):
def capture_integration_desk(self, *args, **kwargs): ...
def checkout_reset_destination_lease(self, *args, **kwargs): ...
+ def register_created_desk(self, *args, **kwargs): ...
+ def archive_desk_remedy(self, *args, **kwargs): ...
def ensure_in_place_target(self, *args, **kwargs): ...
def ensure_non_in_place_target_clean(self, *args, **kwargs): ...
def reconcile_worktree_path(self, *args, **kwargs): ...
@@ -503,7 +505,7 @@ def recover_pending_stack_close(self, manifest, manifest_path, pending):
return True
- def stack_archive_writer_guard(self, manifest, stack):
+ def stack_archive_writer_guard(self, manifest, stack, manifest_path=None):
"""An authoring lane or checked-out source must be released before archival."""
repo_root = self.repository.root
registry, _ = self.worktrees.load_governed_worktree_registry()
@@ -512,17 +514,18 @@ def stack_archive_writer_guard(self, manifest, stack):
) for lane in registry['lanes']):
raise SyncwheelError('stack archive refuses an active writer lane; capture and release it first')
worktree = self.repository.find_worktree_for_branch(repo_root, stack['branch'])
- if worktree:
- raise SyncwheelError('stack archive refuses a checked-out source branch; release its writer first')
+ remedy = self.projections.archive_desk_remedy(repo_root, manifest_path, stack, worktree)
+ if remedy:
+ raise SyncwheelError(f'stack archive refuses a checked-out source branch or pending desk release; {remedy}')
_, coordination = self.publication.coordination_profile()
if stack['id'] in (coordination.get('locks') or {}) or local_lease_is_active(coordination):
raise SyncwheelError('stack archive refuses an active worktree lock or coordination lease')
- def build_stack_archive_plan(self, manifest, stack_id, reason, resume_intent):
+ def build_stack_archive_plan(self, manifest, stack_id, reason, resume_intent, manifest_path=None):
repo_root = self.repository.root
stack = require_stack(manifest, stack_id)
- self.stack_archive_writer_guard(manifest, stack)
+ self.stack_archive_writer_guard(manifest, stack, manifest_path)
if not reason or not reason.strip() or not resume_intent or not resume_intent.strip():
raise SyncwheelError('stack archive requires a nonempty --reason and --resume-intent')
if channel_ids_referencing_stack(manifest, stack_id) or any(
@@ -643,10 +646,10 @@ def command_stack_archive(self, args, manifest, manifest_path):
return 0
stack = stack_map(manifest).get(args.stack)
if stack is not None:
- self.stack_archive_writer_guard(manifest, stack)
+ self.stack_archive_writer_guard(manifest, stack, manifest_path)
self.verify_stack_archive_proof(plan, stack)
else:
- plan = self.build_stack_archive_plan(manifest, args.stack, args.reason, args.resume_intent)
+ plan = self.build_stack_archive_plan(manifest, args.stack, args.reason, args.resume_intent, manifest_path)
if not args.apply:
print(json.dumps(plan, indent=2))
return 0
@@ -2883,10 +2886,12 @@ def rebuild_stack_from_manifest(
)
if not dry_run and mode == 'desk':
self.projections.ensure_non_in_place_target_clean(repo_root, stack['branch'], worktree)
- result = self.replay.execute_replay(
- self.replay.replay_plan(manifest, replay_target(stack=stack, worktree=worktree), mode),
- not dry_run,
- )
+ plan = self.replay.replay_plan(manifest, replay_target(stack=stack, worktree=worktree), mode)
+ if not dry_run and mode == 'desk':
+ plan['register_created_desk'] = lambda path: self.projections.register_created_desk(
+ repo_root, manifest_path, stack, path,
+ )
+ result = self.replay.execute_replay(plan, not dry_run)
require_replay_success(result)
if not dry_run:
self.ledger.append_ledger_event(
diff --git a/scripts/syncwheel_worktrees.py b/scripts/syncwheel_worktrees.py
index f2d9357..979ea20 100644
--- a/scripts/syncwheel_worktrees.py
+++ b/scripts/syncwheel_worktrees.py
@@ -401,6 +401,22 @@ def load_governed_worktree_registry(self):
raise SyncwheelError(f'governed worktree lane {lane_id!r} is missing {key!r}: {path}')
if not isinstance(lane.get('full'), bool):
raise SyncwheelError(f'governed worktree lane {lane_id!r} has invalid full mode: {path}')
+ desks = data.get('desks', [])
+ if not isinstance(desks, list):
+ raise SyncwheelError(f'governed worktree registry desks must be a list: {path}')
+ seen_desks = set()
+ for desk in desks:
+ if (not isinstance(desk, dict) or desk.get('kind') != 'replay-desk'
+ or any(not isinstance(desk.get(key), str) or not desk[key]
+ for key in ('stack', 'branch', 'path', 'manifest', 'admin'))
+ or any(not Path(desk[key]).is_absolute() for key in ('path', 'manifest', 'admin'))
+ or any(not isinstance(desk.get(key), list) or len(desk[key]) != 2
+ or any(type(value) is not int or value < 0 for value in desk[key])
+ for key in ('identity', 'checkoutIdentity'))):
+ raise SyncwheelError(f'governed worktree registry contains an invalid desk: {path}')
+ if desk['admin'] in seen_desks:
+ raise SyncwheelError(f'governed worktree registry contains a duplicate desk: {path}')
+ seen_desks.add(desk['admin'])
return data, path
def save_governed_worktree_registry(
diff --git a/skills/syncwheel/SKILL.md b/skills/syncwheel/SKILL.md
index 50c3d9d..3a1ae7c 100644
--- a/skills/syncwheel/SKILL.md
+++ b/skills/syncwheel/SKILL.md
@@ -486,6 +486,16 @@ syncwheel replay-mode # show the repo-local default
syncwheel replay-mode set desk # persist it for this clone
```
+Stack replay desks created by Syncwheel appear in `worktree list --json` under
+`desks`. Before archiving their stack, preview `stack release-desk --reason
+"..."`, stop the desk's writers, then apply the same request with `--plan-digest
+ --confirm-writers-stopped --apply`. Release verifies local recovery
+refs for the tip, index and working changes before removing the checkout. For
+an older unregistered desk, verify ownership and pass `--legacy-worktree `
+in both commands; never use this path to release a governed writer lane. Keep
+the selected manifest and the recovery refs. Follow any printed refusal or
+partial-recovery instruction without raw Git cleanup.
+
Selection is four-tier, most specific first: the `--replay-mode` flag, `replay_mode` in the repo-local
`.syncwheel/profile.local.json`, `defaults.replay_mode` in the manifest, then `auto`. An unavailable
mode falls back rather than failing.
diff --git a/tests/test_desk_release.py b/tests/test_desk_release.py
new file mode 100644
index 0000000..8b14328
--- /dev/null
+++ b/tests/test_desk_release.py
@@ -0,0 +1,646 @@
+import contextlib
+import io
+import json
+import os
+import shlex
+import shutil
+import stat
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import test_syncwheel as fixtures
+
+
+def file_state(path):
+ if path.is_symlink():
+ return 'link', os.readlink(path)
+ if path.is_file():
+ return 'file', stat.S_IMODE(path.stat().st_mode), path.read_bytes()
+ return None
+
+
+def file_tree(root):
+ return {str(path.relative_to(root)): data
+ for path in root.rglob('*') if (data := file_state(path)) is not None}
+
+
+class DeskReleaseTest(unittest.TestCase):
+ stack = 'feature-b'
+ branch = 'pr/feature-b'
+ reason = 'Preserve validated desk work'
+
+ def setUp(self):
+ self.fixture = fixtures.SyncwheelFixtureTest()
+ self.fixture.setUp()
+ self.addCleanup(self.fixture.tearDown)
+ self.repo = self.fixture.repo
+ self.fixture.prepare_reconcile_apply_worktree_scenario()
+ self.module = self.fixture.load_syncwheel_module()
+ self.module.ensure_syncwheel_metadata_excluded(self.repo, 'local-only')
+ self.manifest = self.repo / '.syncwheel' / 'manifest.json'
+ self.desk = self.repo / '.syncwheel' / 'wt' / 'pr-feature-b'
+
+ def git(self, *args, cwd=None):
+ return subprocess.run(
+ ['git', *map(str, args)], cwd=cwd or self.repo, check=True,
+ capture_output=True, env={**os.environ, 'GIT_OPTIONAL_LOCKS': '0'},
+ ).stdout
+
+ def cli(self, *args, expected=0):
+ return self.fixture.run_cli(*args, expected=expected)
+
+ def desk_git(self, *args):
+ return self.git(*args, cwd=self.desk)
+
+ def index_path(self, worktree):
+ return Path(os.fsdecode(self.git(
+ 'rev-parse', '--path-format=absolute', '--git-path', 'index', cwd=worktree,
+ ).strip()))
+
+ def snapshot(self):
+ common = self.repo / '.git'
+ registry = self.module.governed_worktree_registry_path(self.repo)
+ ledger = self.module.ledger_root(self.repo, self.manifest)
+ return {
+ 'refs': self.git('for-each-ref', '--format=%(refname) %(objectname) %(symref)'),
+ 'head': self.git('rev-parse', 'HEAD'),
+ 'registry': file_state(registry),
+ 'git_syncwheel': file_tree(common / 'syncwheel'),
+ 'ledger': file_tree(ledger),
+ 'manifest': file_state(self.manifest),
+ 'index': file_state(self.index_path(self.repo)),
+ 'worktrees': self.git('worktree', 'list', '--porcelain', '-z'),
+ 'desk_exists': self.desk.exists(),
+ 'desk_files': file_tree(self.desk),
+ 'desk_index': file_state(self.index_path(self.desk)) if self.desk.is_dir() else None,
+ 'ignore': (file_state(self.repo / '.gitignore'), file_state(common / 'info' / 'exclude')),
+ 'primary_product': {name: file_state(self.repo / name) for name in ('alpha.txt', 'beta.txt')},
+ }
+
+ def rebuild_desk(self):
+ self.cli('stack', 'rebuild', self.stack, '--replay-mode', 'desk')
+ self.assertTrue(self.desk.is_dir())
+ return self.desk_git('rev-parse', 'HEAD').decode().strip()
+
+ def dirty_desk(self):
+ (self.desk / 'beta.txt').write_bytes(b'staged state\n')
+ self.desk_git('add', 'beta.txt')
+ (self.desk / 'beta.txt').write_bytes(b'working state\n')
+ (self.desk / 'beta.txt').chmod(0o755)
+ (self.desk / 'alpha.txt').unlink()
+ (self.desk / 'link').symlink_to('beta.txt')
+ (self.desk / 'untracked.bin').write_bytes(b'\x00untracked\xff\n')
+
+ def release_args(self, *options):
+ return ('stack', 'release-desk', self.stack, '--reason', self.reason, *options)
+
+ def release_preview(self, *options):
+ return json.loads(self.cli(*self.release_args(*options)).stdout)
+
+ def release_apply(self, plan, *options, expected=0):
+ return self.cli(
+ *self.release_args(*options), '--confirm-writers-stopped',
+ '--plan-digest', plan['planDigest'], '--apply', expected=expected,
+ )
+
+ def invoke_release_apply(self, plan):
+ stderr = io.StringIO()
+ argv = ['syncwheel', *self.release_args(), '--confirm-writers-stopped',
+ '--plan-digest', plan['planDigest'], '--apply']
+ with contextlib.chdir(self.repo), mock.patch.object(
+ sys, 'argv', argv,
+ ), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(stderr):
+ status = self.module.main()
+ return status, stderr.getvalue()
+
+ def verify_removed(self, tip):
+ self.assertFalse(self.desk.exists())
+ self.assertNotIn(os.fsencode(self.desk), self.git('worktree', 'list', '--porcelain', '-z'))
+ self.assertEqual(self.git('rev-parse', self.branch).decode().strip(), tip)
+
+ def test_registered_desk_preview_preserves_everything(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ before = self.snapshot()
+ listed = json.loads(self.cli('worktree', 'list', '--json').stdout)
+ self.assertIn('lanes', listed)
+ self.assertEqual([desk['path'] for desk in listed['desks']], [str(self.desk)])
+ plan = self.release_preview()
+ self.assertEqual(plan['stack'], self.stack)
+ self.assertEqual(plan['path'], str(self.desk))
+ self.assertEqual(plan['sourceRef'], f'refs/heads/{self.branch}')
+ self.assertEqual(plan['sourceTip'], tip)
+ self.assertEqual(set(plan['recoveryRefs']), {'tip', 'index', 'staged', 'working', 'receipt'})
+ self.assertEqual(self.snapshot(), before)
+ self.assertEqual(self.release_preview()['planDigest'], plan['planDigest'])
+
+ def test_nested_release_preserves_caller_authorization(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ reviewed = self.release_preview()
+ auth_key = self.module.MANAGED_REF_MOVE_AUTH_ENV
+ auth_dir = self.module.ref_auth_dir(self.repo)
+ original_env = self.module.managed_process_env
+
+ for apply in (False, True):
+ with self.subTest(apply=apply):
+ nonce = self.module.authorize_ref_move(self.repo, reusable=True)
+ argv = ['syncwheel', *self.release_args()]
+ if apply:
+ argv.extend(('--confirm-writers-stopped', '--plan-digest',
+ reviewed['planDigest'], '--apply'))
+ before = self.snapshot()
+ before_nonces = file_tree(auth_dir)
+ output = io.StringIO()
+ errors = io.StringIO()
+ child_nonces = set()
+
+ def inspect_child_env(*args, **kwargs):
+ result = original_env(*args, **kwargs)
+ if result.get(auth_key):
+ child_nonces.add(result[auth_key])
+ return result
+
+ with (
+ contextlib.chdir(self.repo),
+ contextlib.redirect_stdout(output),
+ contextlib.redirect_stderr(errors),
+ mock.patch.object(sys, 'argv', argv),
+ mock.patch.dict(os.environ, {auth_key: nonce}),
+ mock.patch.object(self.module, 'SYNCWHEEL_REF_AUTH_REPO', self.repo),
+ mock.patch.object(self.module, 'SYNCWHEEL_OWNS_REF_MOVES', True),
+ mock.patch.object(self.module, 'managed_process_env', side_effect=inspect_child_env),
+ ):
+ self.assertEqual(self.module.main(), 0, errors.getvalue())
+ self.assertEqual(self.module.SYNCWHEEL_REF_AUTH_REPO, self.repo)
+ self.assertTrue(self.module.SYNCWHEEL_OWNS_REF_MOVES)
+ self.assertEqual(os.environ[auth_key], nonce)
+
+ self.assertIn(nonce, before_nonces)
+ self.assertEqual(file_tree(auth_dir), before_nonces)
+ self.assertNotIn(nonce, child_nonces)
+ self.assertEqual(len(child_nonces), int(apply))
+ report = json.loads(output.getvalue())
+ if apply:
+ self.assertEqual(report['status'], 'released')
+ self.verify_removed(tip)
+ expected_refs = {ref.encode() for ref in reviewed['recoveryRefs'].values()}
+ before_refs = set(before['refs'].splitlines())
+ after_refs = set(self.snapshot()['refs'].splitlines())
+ self.assertTrue(before_refs.issubset(after_refs))
+ self.assertEqual({ref.split()[0] for ref in after_refs - before_refs}, expected_refs)
+ else:
+ self.assertEqual(report, reviewed)
+ self.assertEqual(self.snapshot(), before)
+
+ def test_apply_removes_registration_and_recovers_distinct_index_and_working_tree(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ files = file_tree(self.desk)
+ files.pop('.git')
+ staged_diff = self.desk_git('diff', '--cached', '--binary')
+ working_diff = self.desk_git('diff', '--binary')
+ before = self.snapshot()
+ plan = self.release_preview()
+ applied = json.loads(self.release_apply(plan).stdout)
+ self.assertEqual(applied['status'], 'released')
+ self.assertEqual(applied['recoveryRefs'], plan['recoveryRefs'])
+ self.verify_removed(tip)
+ self.restore_and_compare(plan['recoveryRefs'], tip, files, staged_diff, working_diff,
+ before['desk_index'][2])
+ after = self.snapshot()
+ for key in ('head', 'index', 'manifest', 'ignore', 'primary_product'):
+ self.assertEqual(after[key], before[key], key)
+
+ def restore_and_compare(self, refs, tip, files, staged_diff, working_diff, index):
+ restored = self.fixture.tmp / 'restored'
+ self.assertEqual(self.git('rev-parse', refs['tip']).decode().strip(), tip)
+ self.assertEqual(self.git('rev-parse', refs['staged'] + '^').decode().strip(), tip)
+ self.assertEqual(self.git('rev-parse', refs['working'] + '^'),
+ self.git('rev-parse', refs['staged']))
+ self.assertEqual(self.git('cat-file', 'blob', refs['index']), index)
+ receipt = json.loads(self.git('cat-file', 'blob', refs['receipt']))
+ self.git('worktree', 'add', '--detach', '--no-checkout', restored, refs['tip'])
+ self.git('read-tree', refs['working'], cwd=restored)
+ self.git('checkout-index', '--all', cwd=restored)
+ for name, attributes in receipt['files'].items():
+ path = restored / name
+ if attributes['type'] == 'directory':
+ path.mkdir(parents=True, exist_ok=True)
+ if attributes['type'] != 'symlink':
+ path.chmod(attributes['mode'])
+ self.index_path(restored).write_bytes(self.git('cat-file', 'blob', refs['index']))
+ recovered = file_tree(restored)
+ recovered.pop('.git')
+ self.assertEqual(recovered, files)
+ self.assertEqual(self.git('rev-parse', 'HEAD', cwd=restored).decode().strip(), tip)
+ self.git('diff', '--cached', '--exit-code', refs['staged'], cwd=restored)
+ self.assertEqual(self.git('diff', '--cached', '--binary', cwd=restored), staged_diff)
+ self.assertEqual(self.git('diff', '--binary', cwd=restored), working_diff)
+
+ def test_explicit_legacy_worktree_release_requires_exact_path(self):
+ self.desk.parent.mkdir(parents=True, exist_ok=True)
+ self.git('worktree', 'add', self.desk, self.branch)
+ tip = self.desk_git('rev-parse', 'HEAD').decode().strip()
+ self.dirty_desk()
+ before = self.snapshot()
+ self.cli(*self.release_args(), expected=2)
+ self.cli(*self.release_args('--legacy-worktree', str(self.desk.parent)), expected=2)
+ self.assertEqual(self.snapshot(), before)
+ legacy = ('--legacy-worktree', str(self.desk))
+ plan = self.release_preview(*legacy)
+ self.assertEqual(self.snapshot(), before)
+ self.assertEqual(json.loads(self.release_apply(plan, *legacy).stdout)['status'], 'released')
+ self.verify_removed(tip)
+
+ def test_archive_remedy_executes_release_then_archive(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ args = ('stack', 'archive', self.stack, '--reason', 'Archive reviewed changes',
+ '--resume-intent', 'Restore if needed')
+ before = self.snapshot()
+
+ blocked = self.cli(*args, expected=2)
+
+ self.assertEqual(self.snapshot(), before)
+ remedy = next(line[line.index('syncwheel stack release-desk'):].strip()
+ for line in blocked.stderr.splitlines() if 'syncwheel stack release-desk' in line)
+ command = shlex.split(remedy)
+ self.assertEqual(command[:4], ['syncwheel', 'stack', 'release-desk', self.stack])
+ release = json.loads(self.cli(*command[1:]).stdout)
+ self.cli(*command[1:], '--confirm-writers-stopped', '--plan-digest',
+ release['planDigest'], '--apply')
+ self.verify_removed(tip)
+ archive = json.loads(self.cli(*args).stdout)
+ self.cli(*args, '--plan-digest', archive['planDigest'], '--apply')
+ self.assertEqual(self.fixture.read_manifest()['stacks'], [])
+ self.assertEqual(self.git('rev-parse', release['recoveryRefs']['tip']).decode().strip(), tip)
+
+ def test_apply_requires_confirmation_of_stopped_writers(self):
+ self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ before = self.snapshot()
+ self.cli(*self.release_args(), '--plan-digest', plan['planDigest'], '--apply', expected=2)
+ self.assertEqual(self.snapshot(), before)
+
+ def test_new_working_edit_invalidates_reviewed_plan(self):
+ self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ (self.desk / 'beta.txt').write_bytes(b'new writer bytes\n')
+ latest = self.snapshot()
+
+ self.release_apply(plan, expected=2)
+
+ self.assertEqual(self.snapshot(), latest)
+
+ def test_source_ref_advance_invalidates_reviewed_plan(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ advanced = self.git('commit-tree', tip + '^{tree}', '-p', tip,
+ '-m', 'Concurrent source advance').decode().strip()
+ self.git('update-ref', f'refs/heads/{self.branch}', advanced, tip)
+ latest = self.snapshot()
+
+ self.release_apply(plan, expected=2)
+
+ self.assertEqual(self.snapshot(), latest)
+
+ def test_legacy_release_refuses_primary_and_manual_ambiguous_path(self):
+ manual = self.fixture.tmp / 'manual'
+ self.git('worktree', 'add', manual, self.branch)
+ self.desk = manual
+ before = self.snapshot()
+ self.cli(*self.release_args(), expected=2)
+ self.cli(*self.release_args('--legacy-worktree', str(self.repo)), expected=2)
+ self.assertEqual(self.snapshot(), before)
+
+ def test_legacy_release_refuses_moved_foreign_governed_lane(self):
+ opened = self.fixture.run_cli(
+ 'worktree', 'open', 'foreign', '--json',
+ extra_env={'SYNCWHEEL_LANE_OWNER': 'fixture-foreign'},
+ )
+ lane = json.loads(opened.stdout)['lane']
+ old_path = Path(lane['path'])
+ self.desk = old_path.with_name('moved-foreign')
+ self.git('worktree', 'move', old_path, self.desk)
+ self.desk_git('switch', '-qc', 'different-checked-out-branch')
+ manifest = self.fixture.read_manifest()
+ manifest['stacks'][0]['branch'] = 'different-checked-out-branch'
+ self.manifest.write_text(json.dumps(manifest))
+ before = self.snapshot()
+
+ refused = self.cli(*self.release_args('--legacy-worktree', str(self.desk)), expected=2)
+
+ self.assertIn('governed worktree lane foreign', refused.stderr)
+ self.assertEqual(self.snapshot(), before)
+
+ def test_pending_lane_cleanup_preview_keeps_metadata_and_desk_identity(self):
+ self.rebuild_desk()
+ self.dirty_desk()
+ self.cli('worktree', 'open', 'unrelated')
+ self.fixture.run_cli_until_cleanup_sigkill(
+ 'after_cleanup_intent', 'worktree', 'release', 'unrelated',
+ '--reason', 'Fixture interruption', '--apply',
+ )
+ before = self.snapshot()
+
+ self.release_preview()
+ self.assertEqual(self.snapshot(), before)
+ listed = json.loads(self.cli('worktree', 'list', '--json').stdout)
+
+ self.assertEqual([desk['path'] for desk in listed['desks']], [str(self.desk)])
+ self.assertEqual(self.snapshot(), before)
+
+ def test_ignored_bytes_refuse_before_any_removal(self):
+ self.rebuild_desk()
+ ignored = self.desk / 'ignored.bin'
+ ignored.write_bytes(b'\x00retained ignored bytes')
+ with (self.repo / '.git' / 'info' / 'exclude').open('a') as stream:
+ stream.write('\nignored.bin\n')
+ self.desk_git('check-ignore', str(ignored))
+ before = self.snapshot()
+
+ self.cli(*self.release_args(), expected=2)
+
+ self.assertEqual(self.snapshot(), before)
+
+ def test_nested_repo_refuses_before_any_removal(self):
+ self.rebuild_desk()
+ nested = self.desk / 'nested'
+ self.git('init', '-q', nested)
+ (nested / 'private.txt').write_text('nested repository work\n')
+ before = self.snapshot()
+
+ self.cli(*self.release_args(), expected=2)
+
+ self.assertEqual(self.snapshot(), before)
+
+ def test_non_regular_file_refuses_before_any_removal(self):
+ self.rebuild_desk()
+ fifo = self.desk / 'pipe'
+ os.mkfifo(fifo)
+ inode = fifo.lstat().st_ino
+ before = self.snapshot()
+
+ self.cli(*self.release_args(), expected=2)
+
+ self.assertEqual(self.snapshot(), before)
+ self.assertEqual(fifo.lstat().st_ino, inode)
+
+ def test_unmerged_index_refuses_before_any_removal(self):
+ self.rebuild_desk()
+ beta = self.desk_git('rev-parse', 'HEAD:beta.txt').strip()
+ alpha = self.desk_git('rev-parse', 'HEAD:alpha.txt').strip()
+ subprocess.run(
+ ['git', 'update-index', '--index-info'], cwd=self.desk, check=True,
+ input=(b'0 ' + b'0' * len(beta) + b'\tbeta.txt\n'
+ + b'100644 ' + beta + b' 1\tbeta.txt\n'
+ + b'100644 ' + alpha + b' 2\tbeta.txt\n'),
+ )
+ self.assertTrue(self.desk_git('ls-files', '-u'))
+ before = self.snapshot()
+
+ self.cli(*self.release_args(), expected=2)
+
+ self.assertEqual(self.snapshot(), before)
+
+ def test_edit_after_recovery_refs_keeps_latest_checkout(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ original = self.module.DeskLifecycle.verify_refs
+ calls = []
+
+ def verify_then_edit(lifecycle, checked_plan, objects):
+ original(lifecycle, checked_plan, objects)
+ calls.append(checked_plan['planDigest'])
+ (self.desk / 'beta.txt').write_bytes(b'latest concurrent writer\n')
+
+ before = self.snapshot()
+ with mock.patch.object(self.module.DeskLifecycle, 'verify_refs', verify_then_edit):
+ status, stderr = self.invoke_release_apply(plan)
+ self.assertEqual(calls, [plan['planDigest']])
+ self.assertEqual(status, 2, stderr)
+ self.assertEqual((self.desk / 'beta.txt').read_bytes(), b'latest concurrent writer\n')
+ self.assertEqual(self.git('rev-parse', self.branch).decode().strip(), tip)
+ after = self.snapshot()
+ for key in ('manifest', 'head', 'index', 'desk_index', 'worktrees'):
+ self.assertEqual(after[key], before[key], key)
+
+ def interrupt_removal(self, plan, mutate=None):
+ original = self.module._StackRepository.git
+ held = []
+
+ def fail_remove(repository, root, *args, **kwargs):
+ if args[:3] == ('worktree', 'remove', '--force'):
+ path = Path(args[3])
+ held.append(path)
+ if mutate is not None:
+ mutate(path)
+ raise self.module.SyncwheelError('fixture removal failed')
+ return original(repository, root, *args, **kwargs)
+
+ with mock.patch.object(self.module._StackRepository, 'git', fail_remove):
+ status, stderr = self.invoke_release_apply(plan)
+ self.assertEqual(status, 2, stderr)
+ self.assertIn('fixture removal failed', stderr)
+ self.assertEqual(len(held), 1)
+ return held[0]
+
+ def test_failed_removal_retries_same_generation_without_touching_replacement(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ held = self.interrupt_removal(plan)
+ self.assertTrue(held.is_dir())
+ self.assertEqual((held / 'beta.txt').read_bytes(), b'working state\n')
+ self.assertFalse(self.desk.exists())
+ proof = {kind: self.git('rev-parse', ref) for kind, ref in plan['recoveryRefs'].items()}
+ self.git('worktree', 'add', '-b', 'replacement', self.desk, 'main')
+ (self.desk / 'replacement.bin').write_bytes(b'new worktree generation\x00')
+ replacement = file_tree(self.desk)
+ replacement_index = file_state(self.index_path(self.desk))
+ refused = self.release_apply(plan, expected=2)
+ self.assertIn('original desk path was replaced', refused.stderr)
+ self.assertTrue(held.is_dir())
+ self.assertEqual(file_tree(self.desk), replacement)
+ self.assertEqual(file_state(self.index_path(self.desk)), replacement_index)
+ (self.desk / 'replacement.bin').unlink()
+ self.git('worktree', 'remove', self.desk)
+
+ applied = json.loads(self.release_apply(plan).stdout)
+
+ self.assertEqual(applied['status'], 'released')
+ self.assertEqual(applied['planDigest'], plan['planDigest'])
+ self.assertFalse(held.exists())
+ self.assertNotIn(os.fsencode(held), self.git('worktree', 'list', '--porcelain', '-z'))
+ self.assertFalse(self.desk.exists())
+ self.assertEqual(self.git('rev-parse', self.branch).decode().strip(), tip)
+ self.assertEqual({kind: self.git('rev-parse', ref) for kind, ref in plan['recoveryRefs'].items()},
+ proof)
+
+ def test_retry_refuses_symbolic_quarantine_path_before_scanning_it(self):
+ self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ held = self.interrupt_removal(plan)
+ destination = held.with_name('desk-preserved-by-owner')
+ held.rename(destination)
+ held.symlink_to(destination, target_is_directory=True)
+ preserved = file_tree(destination)
+ before = self.snapshot()
+
+ with mock.patch.object(self.module.DeskLifecycle, 'scan_checkout') as scan:
+ status, stderr = self.invoke_release_apply(plan)
+
+ self.assertEqual(status, 2, stderr)
+ self.assertIn('symbolic link', stderr)
+ scan.assert_not_called()
+ self.assertEqual(self.snapshot(), before)
+ self.assertEqual(file_tree(destination), preserved)
+ self.assertEqual(held.readlink(), destination)
+
+ def test_archive_after_relocation_prints_exact_retry_for_original_intent(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ held = self.interrupt_removal(plan)
+
+ blocked = self.cli(
+ 'stack', 'archive', self.stack, '--reason', 'Archive reviewed changes',
+ '--resume-intent', 'Restore if needed', expected=2,
+ )
+
+ remedy = next(line[line.index('syncwheel stack release-desk'):].strip()
+ for line in blocked.stderr.splitlines() if 'syncwheel stack release-desk' in line)
+ command = shlex.split(remedy)
+ self.assertEqual(command[:4], ['syncwheel', 'stack', 'release-desk', self.stack])
+ self.assertIn('--apply', command)
+ self.assertEqual(command[command.index('--plan-digest') + 1], plan['planDigest'])
+ applied = json.loads(self.cli(*command[1:]).stdout)
+ self.assertEqual(applied['status'], 'released')
+ self.assertFalse(held.exists())
+ self.verify_removed(tip)
+
+ def test_valid_refs_with_wrong_working_tree_cannot_release_desk(self):
+ self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ original = self.module.DeskLifecycle.make_objects
+ before = self.snapshot()
+
+ def replace_working_tree(lifecycle, *args, **kwargs):
+ objects = original(lifecycle, *args, **kwargs)
+ staged = objects['staged']
+ objects['working'] = self.git(
+ 'commit-tree', staged + '^{tree}', '-p', staged, '-m', 'Wrong recovery tree',
+ ).decode().strip()
+ return objects
+
+ with mock.patch.object(
+ self.module.DeskLifecycle, 'make_objects', autospec=True,
+ side_effect=replace_working_tree,
+ ) as make_objects:
+ status, stderr = self.invoke_release_apply(plan)
+ make_objects.assert_called_once()
+ self.assertEqual(status, 2, stderr)
+ self.assertIn('working tree does not reproduce', stderr)
+ after = self.snapshot()
+ for key in ('manifest', 'head', 'index', 'worktrees', 'desk_files', 'desk_index',
+ 'registry', 'ledger'):
+ self.assertEqual(after[key], before[key], key)
+
+ def test_retry_completes_each_partial_removal_without_recreating_refs(self):
+ for missing in ('checkout', 'admin'):
+ with self.subTest(missing=missing):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ admin = Path(plan['snapshot']['admin'])
+ held = self.interrupt_removal(
+ plan, lambda path: shutil.rmtree(path if missing == 'checkout' else admin),
+ )
+ self.assertEqual(held.exists(), missing == 'admin')
+ self.assertEqual(admin.exists(), missing == 'checkout')
+ proof = {kind: self.git('rev-parse', ref) for kind, ref in plan['recoveryRefs'].items()}
+ if missing == 'checkout':
+ self.git('worktree', 'add', '-b', 'replacement-admin', self.desk, 'main')
+ (self.desk / 'replacement.bin').write_bytes(b'untouched replacement')
+ replacement = file_tree(self.desk)
+
+ result = json.loads(self.release_apply(plan).stdout)
+
+ self.assertEqual(result['status'], 'released')
+ self.assertFalse(admin.exists())
+ self.assertFalse(held.exists())
+ self.assertNotIn(os.fsencode(held), self.git('worktree', 'list', '--porcelain', '-z'))
+ if missing == 'checkout':
+ self.assertEqual(file_tree(self.desk), replacement)
+ self.assertEqual(self.desk_git('branch', '--show-current'), b'replacement-admin\n')
+ (self.desk / 'replacement.bin').unlink()
+ self.git('worktree', 'remove', self.desk)
+ self.verify_removed(tip)
+ self.assertEqual(
+ {kind: self.git('rev-parse', ref) for kind, ref in plan['recoveryRefs'].items()},
+ proof,
+ )
+
+ def test_retry_recreates_unanchored_objects_pruned_after_durable_intent(self):
+ tip = self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ before = self.snapshot()
+ registry = self.module.governed_worktree_registry_path(self.repo)
+ intent = registry.parent / 'desk-release' / (plan['planDigest'] + '.json')
+
+ with mock.patch.object(
+ self.module._StackRepository, 'publish_desk_recovery_refs',
+ side_effect=self.module.SyncwheelError('fixture interrupted before ref publication'),
+ ) as publish:
+ status, stderr = self.invoke_release_apply(plan)
+
+ publish.assert_called_once()
+ self.assertEqual(status, 2, stderr)
+ self.assertIn('fixture interrupted before ref publication', stderr)
+ prepared = json.loads(intent.read_bytes())
+ self.assertEqual(prepared['plan'], plan)
+ after = self.snapshot()
+ for key in ('refs', 'head', 'index', 'manifest', 'worktrees', 'desk_files', 'desk_index'):
+ self.assertEqual(after[key], before[key], key)
+ working = prepared['objects']['working']
+ self.git('cat-file', '-e', working)
+ self.git('prune', '--expire=now')
+ pruned = subprocess.run(
+ ['git', 'cat-file', '-e', working], cwd=self.repo, capture_output=True,
+ )
+ self.assertNotEqual(pruned.returncode, 0)
+
+ applied = json.loads(self.release_apply(plan).stdout)
+
+ self.assertEqual(applied['status'], 'released')
+ self.verify_removed(tip)
+ for kind, ref in plan['recoveryRefs'].items():
+ self.assertEqual(self.git('rev-parse', ref).decode().strip(), prepared['objects'][kind])
+
+ def test_retry_after_removal_started_refuses_missing_recovery_object(self):
+ self.rebuild_desk()
+ self.dirty_desk()
+ plan = self.release_preview()
+ held = self.interrupt_removal(plan)
+ working = self.git('rev-parse', plan['recoveryRefs']['working']).decode().strip()
+ objects = Path(os.fsdecode(self.git('rev-parse', '--absolute-git-dir').strip())) / 'objects'
+ (objects / working[:2] / working[2:]).unlink()
+ preserved = file_tree(held)
+ before = self.snapshot()
+
+ result = self.release_apply(plan, expected=2)
+
+ self.assertTrue(result.stderr)
+ self.assertEqual(file_tree(held), preserved)
+ self.assertEqual(self.snapshot(), before)