diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68ce4f32..56b83670 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## 0.47.16 - 2026-11-16
+
+- Prepare personal tracking updates before writing and restore their manifest and private ledger when a handled write fails. Keep the selected profile, shared ignore files, Git index and refs unchanged.
+
## 0.47.15 - 2026-11-16
- Keep personal-manifest tracking updates within the selected manifest and its private ledger. Neither tracking value rewrites shared ignore files, changes hooks, stages files or removes the shared manifest README from the index. Preserve unrelated dirty primary files and report actions for the selected manifest.
diff --git a/README.md b/README.md
index 13218be8..048c9240 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.15`
+Current version: `0.47.16`
`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
@@ -146,6 +146,9 @@ With a personal manifest selected, `repo tracking set` changes only that manifes
policy and private ledger. Both tracking values leave shared ignore files, hooks,
the manifest README and Git indexes unchanged. Personal metadata must already be
ignored and untracked; changing its policy does not migrate the shared repository.
+The command prepares the manifest and ledger update before publication and restores
+its own writes if publication raises a handled error. This rollback does not
+provide automatic recovery from process termination or power loss.
`authority` declares how far agents may take a change on their own. A repo
with `mode=ai-managed` and `source_change` allowed lets an agent edit, test,
diff --git a/VERSION b/VERSION
index 676ecf5e..ffb1cf27 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.47.15
+0.47.16
diff --git a/docs/ai-agents.md b/docs/ai-agents.md
index e18ff98e..82548463 100644
--- a/docs/ai-agents.md
+++ b/docs/ai-agents.md
@@ -294,6 +294,9 @@ lives in [`skills/syncwheel/SKILL.md`](../skills/syncwheel/SKILL.md).
Selecting a personal manifest limits `repo tracking set` to that manifest and its
private ledger. It does not migrate shared ignore files, hooks or the Git index.
The selected private metadata must already be ignored and untracked.
+The command prepares the manifest and ledger update before publication and restores
+its own writes if publication raises a handled error. This rollback does not
+provide automatic recovery from process termination or power loss.
## Repository authority
diff --git a/docs/index.html b/docs/index.html
index 0ff44a2e..51bc1d17 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -1826,7 +1826,7 @@
-
AI-ready Git coordination v0.47.15
+
AI-ready Git coordination v0.47.16
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.15 · MIT · a NestDevLab project
+ syncwheel v0.47.16 · MIT · a NestDevLab project
diff --git a/openpack.json b/openpack.json
index b44837c1..80b00b75 100644
--- a/openpack.json
+++ b/openpack.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 2,
"name": "NestDevLab/syncwheel",
- "version": "0.47.15",
+ "version": "0.47.16",
"provides": [
{
"type": "skills",
diff --git a/scripts/syncwheel.py b/scripts/syncwheel.py
index f2d3922b..4ae0487a 100755
--- a/scripts/syncwheel.py
+++ b/scripts/syncwheel.py
@@ -18743,10 +18743,11 @@ def update_repo_tracking(args, repo_root, manifest_path, *, personal):
report['effective_worktree_root'] = str(resolve_worktree_root_path(repo_root, worktree_root))
report['warnings'].extend(warnings)
if args.apply:
- save_manifest_with_ledger(
- repo_root, manifest_path, manifest, 'repo_tracking_set',
+ _manifest_store().save_personal_tracking(
+ repo_root, manifest_path, manifest,
{'syncwheel_tracking': tracking, 'syncwheel_worktree_root': worktree_root},
)
+ report['actions'].clear()
else:
report['actions'].append(f'apply syncwheel_tracking={tracking}')
if personal and args.json:
diff --git a/scripts/syncwheel_manifest_store.py b/scripts/syncwheel_manifest_store.py
index d076a3bc..a06c5c99 100644
--- a/scripts/syncwheel_manifest_store.py
+++ b/scripts/syncwheel_manifest_store.py
@@ -468,6 +468,106 @@ def _write_ledger_checkpoint_unlocked(repo_root, state, manifest_path=None):
temporary.unlink(missing_ok=True)
+def private_tracking_file_image(path):
+ """Observe data and its file identity without following redirects."""
+ try:
+ descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ except FileNotFoundError:
+ return None
+ try:
+ observed = os.fstat(descriptor)
+ if not stat.S_ISREG(observed.st_mode) or observed.st_nlink != 1:
+ raise SyncwheelError(f'private tracking requires a regular, unlinked file: {path}')
+ with os.fdopen(descriptor, 'rb', closefd=False) as stream:
+ return (observed.st_dev, observed.st_ino, stat.S_IMODE(observed.st_mode), stream.read())
+ finally:
+ os.close(descriptor)
+
+
+def remove_private_tracking_temporaries(temporary_paths, *, applied):
+ for path in reversed(temporary_paths):
+ try:
+ path.unlink(missing_ok=True)
+ except OSError as error:
+ outcome = 'applied' if applied else 'interrupted'
+ print(
+ f'warning: personal tracking {outcome}; could not remove temporary file {path}: {error}',
+ file=sys.stderr,
+ )
+
+
+@contextlib.contextmanager
+def private_tracking_temporaries():
+ temporary_paths = []
+ try:
+ yield temporary_paths
+ except BaseException:
+ remove_private_tracking_temporaries(temporary_paths, applied=False)
+ raise
+ else:
+ remove_private_tracking_temporaries(temporary_paths, applied=True)
+
+
+def stage_private_tracking_file(temporary_paths, path, mode, payload, *, append_at=None):
+ ensure_directory_durable(path.parent)
+ descriptor, name = tempfile.mkstemp(prefix='.tracking-', suffix='.tmp', dir=path.parent)
+ temporary = Path(name)
+ temporary_paths.append(temporary)
+ with os.fdopen(descriptor, 'wb') as stream:
+ os.fchmod(stream.fileno(), mode)
+ if append_at is None:
+ stream.write(payload)
+ else:
+ stream.write(payload[:append_at])
+ stream.flush()
+ ledger_io_checkpoint('event_payload_half_written')
+ stream.write(payload[append_at:])
+ stream.flush()
+ _LEDGER_FSYNC(stream.fileno())
+ return temporary, private_tracking_file_image(temporary)
+
+
+def publish_private_tracking_files(writes, temporary_paths):
+ """Publish staged bytes and undo only the files this transaction still owns."""
+ installed = []
+ try:
+ for path, before, staged, after, rollback, phase in writes:
+ if private_tracking_file_image(path) != before:
+ raise SyncwheelError(f'private tracking metadata changed before write: {path}')
+ os.replace(staged, path)
+ installed.append((path, after, rollback))
+ if phase != 'event_fsynced':
+ ledger_io_checkpoint(phase)
+ ledger_fsync_directory_path(path.parent)
+ if phase == 'event_fsynced':
+ ledger_io_checkpoint(phase)
+ except BaseException as failure:
+ rollback_errors = []
+ for path, after, rollback in reversed(installed):
+ restored = False
+ try:
+ if private_tracking_file_image(path) != after:
+ raise SyncwheelError('file changed after write')
+ if rollback is None:
+ path.unlink()
+ else:
+ os.replace(rollback, path)
+ restored = True
+ ledger_fsync_directory_path(path.parent)
+ except (OSError, SyncwheelError) as error:
+ detail = f'{path}: {error}'
+ if rollback is not None and not restored:
+ temporary_paths.remove(rollback)
+ detail += f'; original image retained at {rollback}'
+ rollback_errors.append(detail)
+ if rollback_errors:
+ raise SyncwheelError(
+ f'personal tracking write failed ({failure}); rollback incomplete: '
+ + ', '.join(rollback_errors)
+ ) from failure
+ raise
+
+
def write_ledger_checkpoint(repo_root, state, manifest_path=None):
with ledger_write_lock(repo_root, manifest_path):
_recover_ledger_tail_unlocked(repo_root, manifest_path)
@@ -1050,6 +1150,60 @@ def append_ledger_event(
return event
+ def save_personal_tracking(self, repo_root, manifest_path, manifest, context):
+ """Save a private tracking declaration and its ledger event as one update."""
+ transaction = active_manifest_write_transaction(manifest_path)
+ if transaction is None or not transaction.get('preserveGitignore'):
+ raise SyncwheelError('personal tracking requires a private manifest transaction')
+ applied = False
+ try:
+ with ledger_write_lock(repo_root, manifest_path), private_tracking_temporaries() as temporary_paths:
+ require_manifest_transaction_current(manifest_path)
+ events = load_ledger_events(repo_root, manifest_path)
+ current = reduce_ledger_state(events)
+ event = {
+ 'schema_version': LEDGER_SCHEMA_VERSION,
+ 'seq': current['last_seq'] + 1,
+ 'ts': iso_utc_now(),
+ 'type': 'manifest_saved',
+ 'payload': manifest_event_payload(manifest_path, manifest, 'repo_tracking_set', context),
+ }
+ state = reduce_ledger_state([*events, event])
+ segment = next_ledger_segment_path(repo_root, manifest_path, create_directory=False)
+ checkpoint = ledger_checkpoint_path(repo_root, manifest_path)
+ self.require_ignored_ledger_paths(repo_root, [manifest_path, segment, checkpoint])
+ before_manifest = private_tracking_file_image(manifest_path)
+ before_segment = private_tracking_file_image(segment)
+ before_checkpoint = private_tracking_file_image(checkpoint)
+ if before_manifest is None:
+ raise SyncwheelError('personal manifest disappeared before tracking update')
+ existing_segment = before_segment[3] if before_segment else b''
+ record = (json.dumps(event, sort_keys=True) + '\n').encode('utf-8')
+ plan = (
+ (manifest_path, before_manifest, (json.dumps(manifest, indent=2) + '\n').encode('utf-8'),
+ None, 'personal_tracking_manifest_replaced'),
+ (segment, before_segment, existing_segment + record,
+ len(existing_segment) + max(1, len(record) // 2), 'event_fsynced'),
+ (checkpoint, before_checkpoint, (json.dumps(state, indent=2, sort_keys=True) + '\n').encode('utf-8'),
+ None, 'checkpoint_replaced'),
+ )
+ after_digest = manifest_digest(manifest)
+ writes = []
+ for path, before, payload, append_at, phase in plan:
+ mode = before[2] if before else 0o600
+ staged, after = stage_private_tracking_file(temporary_paths, path, mode, payload, append_at=append_at)
+ rollback = stage_private_tracking_file(temporary_paths, path, mode, before[3])[0] if before else None
+ writes.append((path, before, staged, after, rollback, phase))
+ require_manifest_transaction_current(manifest_path)
+ publish_private_tracking_files(writes, temporary_paths)
+ applied = True
+ transaction['expectedDigest'] = after_digest
+ transaction['manifestWritten'] = True
+ except OSError as error:
+ if not applied:
+ raise SyncwheelError(f'personal tracking write failed: {error}') from error
+ print(f'warning: personal tracking applied; finalization failed: {error}', file=sys.stderr)
+
def save_manifest_with_ledger(self, repo_root, manifest_path, manifest, reason, context=None, event_type='manifest_saved'):
if reason == 'stack_create' and context and context.get('operation_token'):
stack = stack_map(manifest).get(context.get('stack'))
diff --git a/skills/syncwheel/SKILL.md b/skills/syncwheel/SKILL.md
index cb7d4101..6ce4e68b 100644
--- a/skills/syncwheel/SKILL.md
+++ b/skills/syncwheel/SKILL.md
@@ -703,6 +703,9 @@ With a personal manifest selected, either tracking value changes only that
manifest and its private ledger. The command requires already ignored, untracked
private metadata and preserves shared ignore files, hooks, the manifest README
and Git indexes. Do not treat a personal policy change as shared migration approval.
+The command prepares the manifest and ledger update before publication and restores
+its own writes if publication raises a handled error. This rollback does not
+provide automatic recovery from process termination or power loss.
## Handoff checklist
diff --git a/tests/test_personal_tracking_atomic.py b/tests/test_personal_tracking_atomic.py
new file mode 100644
index 00000000..5248edac
--- /dev/null
+++ b/tests/test_personal_tracking_atomic.py
@@ -0,0 +1,245 @@
+import contextlib
+import io
+import json
+import os
+import stat
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import test_personal_tracking as fixtures
+
+
+class PersonalTrackingAtomicTest(unittest.TestCase):
+ def setUp(self):
+ self.fixture = fixtures.PersonalTrackingTest()
+ self.fixture.setUp()
+ self.addCleanup(self.fixture.doCleanups)
+ self.case = self.fixture.case
+ self.root = self.fixture.repo
+ self.module = self.fixture.module
+ self.profile = self.fixture.profile
+ self.case.ignore.write_text('*.cache\n.syncwheel/manifests/\n')
+ self.module.ensure_syncwheel_metadata_excluded(self.root, 'git-tracked', 'var/syncwheel')
+ shared = json.loads(self.case.manifest_path.read_text())
+ shared['syncwheel_worktree_root'] = 'var/syncwheel'
+ self.case.manifest_path.write_text(json.dumps(shared))
+ self.case.git('add', '.gitignore', '.syncwheel/manifest.json')
+ self.case.git('commit', '-qm', 'Record shared tracking layout')
+ self.personal = self.case.create_personal_manifest('site', 'local-only')
+ selected = json.loads(self.personal.read_text())
+ selected.pop('syncwheel_worktree_root', None)
+ self.personal.write_text(json.dumps(selected))
+ self.personal.chmod(0o640)
+ self.profile.write_text(json.dumps({'personal': 'site'}))
+ self.ledger = self.module.ledger_root(self.root, self.personal)
+
+ @staticmethod
+ def image(path):
+ return path.read_bytes(), stat.S_IMODE(path.stat().st_mode)
+
+ def snapshot(self):
+ shared = self.fixture.snapshot()
+ paths = {
+ 'index': self.root / '.git' / 'index',
+ 'ignore': self.case.ignore,
+ 'exclude': self.root / '.git' / 'info' / 'exclude',
+ 'product': self.case.product,
+ 'untracked': self.root / 'untracked-product',
+ 'manifest': self.case.manifest_path,
+ 'readme': self.fixture.readme,
+ }
+ shared['modes'] = {
+ name: stat.S_IMODE(path.stat().st_mode) if path.exists() else None
+ for name, path in paths.items()
+ }
+ return {
+ 'shared': shared,
+ 'manifest': self.image(self.personal),
+ 'profile': self.image(self.profile),
+ # The lock may be established on a first write and must survive for
+ # waiters. Only event/checkpoint files constitute the logical ledger.
+ 'ledger': {
+ str(path.relative_to(self.ledger)): self.image(path)
+ for path in self.ledger.rglob('*')
+ if path.is_file() and path.relative_to(self.ledger).as_posix() != 'ledger.lock'
+ },
+ }
+
+ def test_distinct_worktree_root_and_static_ignore_keep_tracking_private(self):
+ self.case.dirty_product()
+ before = self.snapshot()
+ result = self.fixture.cli(
+ 'repo', 'tracking', 'set', 'git-tracked', '--personal', 'site',
+ '--apply', '--json', extra_env={'GIT_OPTIONAL_LOCKS': '1'},
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertEqual(report['tracking_scope'], 'personal')
+ self.assertFalse(report['manifest_tracked'])
+ self.assertEqual(report['syncwheel_worktree_root'], '.syncwheel/wt')
+ after = self.snapshot()
+ for key in ('shared', 'profile'):
+ self.assertEqual(after[key], before[key], key)
+ self.assertEqual(after['manifest'][1], before['manifest'][1])
+ self.assertEqual(json.loads(self.personal.read_text())['syncwheel_tracking'], 'git-tracked')
+ self.assertEqual(len(self.module.load_ledger_events(self.root, self.personal)), 1)
+
+ def run_fault(self, phase, action=None):
+ store = self.module._manifest_storage
+
+ def fail(checkpoint):
+ if checkpoint == phase:
+ if action:
+ action()
+ raise OSError(f'fault at {phase}')
+
+ stderr = io.StringIO()
+ args = [
+ 'syncwheel', 'repo', 'tracking', 'set', 'git-tracked', '--repo',
+ str(self.root), '--personal', 'site', '--apply',
+ ]
+ with (
+ mock.patch.object(sys, 'argv', args),
+ mock.patch.object(store, 'ledger_io_checkpoint', side_effect=fail),
+ contextlib.redirect_stdout(io.StringIO()),
+ contextlib.redirect_stderr(stderr),
+ ):
+ self.assertEqual(self.module.main(), 2, stderr.getvalue())
+ self.assertIn(f'fault at {phase}', stderr.getvalue())
+ return stderr.getvalue()
+
+ def test_first_save_rolls_back_after_staging_half_event_and_after_each_install(self):
+ before = self.snapshot()
+ for phase in (
+ 'event_payload_half_written', 'personal_tracking_manifest_replaced',
+ 'event_fsynced', 'checkpoint_replaced',
+ ):
+ with self.subTest(phase=phase):
+ error = self.run_fault(phase)
+ self.assertNotIn('rollback incomplete', error)
+ self.assertEqual(self.snapshot(), before)
+ self.assertEqual(self.module.load_ledger_events(self.root, self.personal), [])
+ self.assertTrue((self.ledger / 'ledger.lock').is_file())
+
+ def test_existing_segment_and_checkpoint_revert_after_replacement(self):
+ seeded = self.fixture.cli('repo', 'tracking', 'set', 'local-only', '--personal', 'site', '--apply')
+ self.assertEqual(seeded.returncode, 0, seeded.stderr)
+ segment = next((self.ledger / 'events').glob('*.jsonl'))
+ checkpoint = self.ledger / 'checkpoints' / 'latest.json'
+ segment.chmod(0o640)
+ checkpoint.chmod(0o640)
+ lock = self.ledger / 'ledger.lock'
+ lock_inode = lock.stat().st_ino
+ before = self.snapshot()
+ self.run_fault('checkpoint_replaced')
+ self.assertEqual(self.snapshot(), before)
+ self.assertEqual(lock.stat().st_ino, lock_inode)
+
+ def test_foreign_manifest_replacement_is_preserved_during_rollback(self):
+ before = self.snapshot()
+ foreign = self.personal.with_name('foreign.local.json')
+ data = b'{"owner": "foreign"}\n'
+
+ def replace_manifest():
+ foreign.write_bytes(data)
+ os.replace(foreign, self.personal)
+
+ error = self.run_fault('checkpoint_replaced', replace_manifest)
+ self.assertIn('rollback incomplete', error)
+ self.assertIn('file changed after write', error)
+ backups = list(self.personal.parent.glob('.tracking-*.tmp'))
+ self.assertEqual(len(backups), 1)
+ self.assertEqual(self.image(backups[0]), before['manifest'])
+ self.assertIn(str(backups[0]), error)
+ after = self.snapshot()
+ self.assertEqual(after['manifest'][0], data)
+ for key in ('shared', 'profile', 'ledger'):
+ self.assertEqual(after[key], before[key], key)
+
+
+ def test_personal_manifest_cannot_alias_active_profile(self):
+ for kind, link in (('symbolic link', os.symlink), ('regular, unlinked', os.link)):
+ with self.subTest(kind=kind):
+ self.personal.unlink()
+ link(self.profile, self.personal)
+ before = self.snapshot()
+ identity = self.personal.lstat().st_ino
+ result = self.fixture.cli(
+ 'repo', 'tracking', 'set', 'git-tracked', '--personal', 'site', '--apply',
+ )
+ self.assertEqual(result.returncode, 2, result.stderr)
+ self.assertIn(kind, result.stderr)
+ self.assertEqual(self.personal.lstat().st_ino, identity)
+ self.assertEqual(self.snapshot(), before)
+
+
+ def test_cleanup_failure_after_publication_reports_applied_success(self):
+ before = self.snapshot()
+ failed = []
+ unlink = Path.unlink
+ published = False
+
+ def observe(phase):
+ nonlocal published
+ if phase == 'checkpoint_replaced':
+ published = True
+
+ def refuse_cleanup(path, *args, **kwargs):
+ if published and not failed and path.name.startswith('.tracking-') and path.exists():
+ failed.append(path)
+ raise OSError('fixture cleanup failure')
+ return unlink(path, *args, **kwargs)
+
+ args = [
+ 'syncwheel', 'repo', 'tracking', 'set', 'git-tracked', '--repo',
+ str(self.root), '--personal', 'site', '--apply', '--json',
+ ]
+ out, err = io.StringIO(), io.StringIO()
+ with (
+ mock.patch.object(sys, 'argv', args),
+ mock.patch.object(self.module._manifest_storage, 'ledger_io_checkpoint', side_effect=observe),
+ mock.patch.object(Path, 'unlink', autospec=True, side_effect=refuse_cleanup),
+ contextlib.redirect_stdout(out),
+ contextlib.redirect_stderr(err),
+ ):
+ result = self.module.main()
+ self.assertEqual(result, 0, err.getvalue())
+ self.assertEqual(len(failed), 1)
+ self.assertTrue(failed[0].is_file())
+ self.assertIn('applied', err.getvalue())
+ self.assertIn(str(failed[0]), err.getvalue())
+ report = json.loads(out.getvalue())
+ self.assertTrue(report['apply'])
+ self.assertEqual(report['syncwheel_tracking'], 'git-tracked')
+ events = self.module.load_ledger_events(self.root, self.personal)
+ self.assertEqual(len(events), 1)
+ self.assertEqual(events[0]['payload']['reason'], 'repo_tracking_set')
+ checkpoint = self.ledger / 'checkpoints' / 'latest.json'
+ self.assertEqual(json.loads(checkpoint.read_text()), self.module._manifest_storage.reduce_ledger_state(events))
+ after = self.snapshot()
+ self.assertEqual(after['shared'], before['shared'])
+ self.assertEqual(after['profile'], before['profile'])
+ self.assertEqual(json.loads(self.personal.read_text())['syncwheel_tracking'], 'git-tracked')
+
+
+ def test_cleanup_failure_before_commit_preserves_original_error(self):
+ before = self.snapshot()
+ failed = []
+ unlink = Path.unlink
+
+ def refuse_cleanup(path, *args, **kwargs):
+ if (not failed and path.parent == self.personal.parent
+ and path.name.startswith('.tracking-') and path.exists()):
+ failed.append(path)
+ raise OSError('fixture cleanup failure')
+ return unlink(path, *args, **kwargs)
+
+ with mock.patch.object(Path, 'unlink', autospec=True, side_effect=refuse_cleanup):
+ error = self.run_fault('event_payload_half_written')
+ self.assertIn('interrupted', error)
+ self.assertIn('fixture cleanup failure', error)
+ self.assertIn('fault at event_payload_half_written', error)
+ self.assertEqual(len(failed), 1)
+ self.assertEqual(self.snapshot(), before)