Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: complete retirement for preserved and reused checkouts (#12632)

[._.]/31381525da4e
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 30a7bbb640..0474c15f7e 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -1040,15 +1040,20 @@ readable and Gmail/API IDs retain their existing meaning.
file-primary operational recovery evidence, created only by explicit initialized
checkout retirement. Version 1 immutable numbered JSON steps form a SHA-256
linked journal; each step and containing directory is fsynced. The directory is
-0700 and journal/native manifests are 0600. `archive/` preserves original bytes
-and metadata, `restore/` holds a proven standalone checkout and Git stores, and
-`quarantine/` retains whole original directories. Native manifest version 2 records
-per-path hashes for OS-added `com.apple.provenance` on copies only; original
-attributes cannot change or disappear. Archive additions must keep their exact
-recorded hashes, and the final standalone manifest remains exact. The preservation
-proof journals the SHA-256 of the exact manifest bytes; later native reads verify
-that binding, including when an edited manifest claims an older version. Version 1
-archives retain their original strict comparison. `execution.lock` and
+0700 and journal/native manifests are 0600. `archive/` preserves original file
+bytes and metadata evidence, `restore/` holds a proven standalone checkout and
+Git stores, and `quarantine/` retains whole original directories. Native manifest
+version 3 records per-path hashes for OS-added or replaced `com.apple.provenance`
+on copies only. A replacement additionally stores the exact original attribute
+bytes as canonical base64, hash-checked against the source before copying; the
+source is checked again afterward. Each archive-to-restore replacement preserves
+its own prior value. These original bytes are retained evidence, not installed
+onto the standalone copy. Missing attributes and every other attribute change
+still refuse preservation. Copied attributes must keep their recorded hashes;
+source/quarantine metadata and the final standalone manifest remain exact. The
+preservation proof journals the SHA-256 of the exact manifest bytes; later native
+reads verify that binding, including when an edited manifest claims an older
+version. Version 1 remains strict and version 2 permits only recorded additions. `execution.lock` and
`backend.lock` serialize service executors and surviving native commands. These
are private archives, excluded from federation and never seeded, migrated into
PostgreSQL, expired or automatically purged. No existing-record migration is
diff --git a/docs/features/branch-reconciliation.md b/docs/features/branch-reconciliation.md
index b94b639080..1f7233f124 100644
--- a/docs/features/branch-reconciliation.md
+++ b/docs/features/branch-reconciliation.md
@@ -99,10 +99,15 @@ The native backend preserves file bytes, permissions, ownership, timestamps,
ACLs, xattrs, supported flags, empty directories, hard links and symlink targets
without following symlink dependencies. It retains original identity evidence;
only the standalone copy's Git pointers are rewritten to its isolated stores.
-An OS-added `com.apple.provenance` attribute on a copy is retained and recorded
-with its exact hash; changed existing attributes, missing attributes and other
-additions still refuse preservation. No provenance or quarantine attribute is
-removed or rewritten. Original and quarantined metadata stay exact. Every later
+OS-added `com.apple.provenance` on a copy is retained with its exact hash. When
+the OS replaces an existing provenance value, version 3 also preserves the exact
+original bytes in the bound manifest as canonical base64 and checks their hash
+against the captured source. Archive and restore copies record separate values
+when the OS replaces it twice. These retained original bytes are recovery
+evidence; the backend never installs them onto the copy. Missing attributes,
+changes to any other attribute, and unrecorded additions still refuse preservation.
+No provenance or quarantine attribute is removed or rewritten by this backend.
+Original and quarantined metadata stay exact. Every later
archive verification or move is bound to the exact manifest hash journaled after
preservation. If that journal write is interrupted before any move, status
exposes an unverified-archive hold and a digest for source-verified cancellation;
diff --git a/scripts/lib/initialized_checkout_archive.py b/scripts/lib/initialized_checkout_archive.py
index a5038d673b..3b20893462 100644
--- a/scripts/lib/initialized_checkout_archive.py
+++ b/scripts/lib/initialized_checkout_archive.py
@@ -4,6 +4,8 @@
Never deletes original checkouts or Git administration. A move is one reversible
RENAME_EXCL; the caller must journal and fence each half of the transaction.
"""
+import base64
+import binascii
import ctypes
import errno
import fcntl
@@ -191,8 +193,50 @@ def same_copy(actual, expected):
return portable(actual) == portable(expected)
-def copy_augmentations(actual, expected):
- """Record only OS-added provenance; never discard or normalize source attrs."""
+def provenance_value(encoded):
+ """Decode only bounded canonical metadata evidence, never apply it to a file."""
+ if not isinstance(encoded, str) or len(encoded) > 24 * 1024 ** 2:
+ return None
+ try:
+ raw = base64.b64decode(encoded, validate=True)
+ except (ValueError, binascii.Error):
+ return None
+ if len(raw) > 16 * 1024 ** 2 or base64.b64encode(raw).decode('ascii') != encoded:
+ return None
+ return raw
+
+
+def source_provenance(root, rows):
+ """Save original preimages before copying, bound to the captured source hash."""
+ originals, size = {}, 0
+ for row in rows:
+ expected = row['xattrs'].get('com.apple.provenance')
+ if expected is None:
+ continue
+ raw = raw_xattrs(root / row['path']).get('com.apple.provenance')
+ if raw is None or hashlib.sha256(raw).hexdigest() != expected:
+ fail('source-provenance-changed')
+ size += len(raw)
+ if size > 16 * 1024 ** 2:
+ fail('provenance-evidence-budget-exceeded')
+ originals[row['path']] = base64.b64encode(raw).decode('ascii')
+ return originals
+
+
+def recorded_provenance(records):
+ originals = {}
+ for row in records:
+ if 'originalBase64' not in row:
+ continue
+ values = row['originalBase64']
+ if not isinstance(values, dict) or set(values) != {'com.apple.provenance'} or row['path'] in originals:
+ fail('invalid-provenance-preimage-layout')
+ originals[row['path']] = values['com.apple.provenance']
+ return originals
+
+
+def copy_augmentations(actual, expected, originals=None):
+ """Record provenance additions, or v3 replacements with exact saved preimages."""
if len(actual) != len(expected):
return None
additions = []
@@ -202,13 +246,24 @@ def copy_augmentations(actual, expected):
extra = set(attrs) - set(original)
if extra - {'com.apple.provenance'}:
return None
- if extra:
+ replaced = ('com.apple.provenance' in original and 'com.apple.provenance' in attrs
+ and original['com.apple.provenance'] != attrs['com.apple.provenance'])
+ compared_attrs = {key: value for key, value in attrs.items() if key not in extra}
+ if extra or replaced:
value = attrs['com.apple.provenance']
if not isinstance(value, str) or not re.fullmatch(r'[0-9a-f]{64}', value):
return None
- additions.append({'path': copied['path'], 'xattrs': {'com.apple.provenance': value}})
- without_added = {**copied, 'xattrs': {key: value for key, value in attrs.items() if key not in extra}}
- if not same_copy([without_added], [source]):
+ record = {'path': copied['path'], 'xattrs': {'com.apple.provenance': value}}
+ if replaced:
+ encoded = originals.get(source['path']) if originals is not None else None
+ raw = provenance_value(encoded)
+ if raw is None or hashlib.sha256(raw).hexdigest() != original['com.apple.provenance']:
+ return None
+ record['originalBase64'] = {'com.apple.provenance': encoded}
+ compared_attrs['com.apple.provenance'] = original['com.apple.provenance']
+ additions.append(record)
+ comparison = {**copied, 'xattrs': compared_attrs}
+ if not same_copy([comparison], [source]):
return None
return additions
@@ -568,21 +623,25 @@ def preserve(request):
private_json(root / 'source.json', before)
augmentations = {'archive': {'common': {}}, 'restore': {}}
for label, source in [('working', work), ('administration', admin)]:
+ originals = source_provenance(source, before['sources'][label])
copy_tree(source, root / 'archive' / label)
- added = copy_augmentations(manifest(root / 'archive' / label), before['sources'][label])
+ added = copy_augmentations(manifest(root / 'archive' / label), before['sources'][label], originals)
if added is None:
fail('archive-metadata-mismatch:' + label)
augmentations['archive'][label] = added
(root / 'archive' / 'common').mkdir(mode=0o700)
for name, expected_rows in before['sources']['common'].items():
+ originals = source_provenance(common / name, expected_rows)
copy_tree(common / name, root / 'archive' / 'common' / name)
- added = copy_augmentations(manifest(root / 'archive' / 'common' / name, True), expected_rows)
+ added = copy_augmentations(manifest(root / 'archive' / 'common' / name, True), expected_rows, originals)
if added is None:
fail('shared-archive-metadata-mismatch:' + name)
augmentations['archive']['common'][name] = added
for label in ('working', 'administration', 'common'):
+ archived = manifest(root / 'archive' / label)
+ originals = source_provenance(root / 'archive' / label, archived)
copy_tree(root / 'archive' / label, root / 'restore' / label)
- added = copy_augmentations(manifest(root / 'restore' / label), manifest(root / 'archive' / label))
+ added = copy_augmentations(manifest(root / 'restore' / label), archived, originals)
if added is None:
fail('restore-copy-metadata-mismatch')
# Historical pre-relocation evidence; saved.restored below is the exact
@@ -612,7 +671,7 @@ def preserve(request):
restored = {label: manifest(restore / label) for label in ('working', 'administration', 'common')}
durable_tree(root / 'archive')
durable_tree(restore)
- saved = {'version': 2, 'transactionIdentity': identity(root), 'facts': before,
+ saved = {'version': 3, 'transactionIdentity': identity(root), 'facts': before,
'copyAugmentations': augmentations, 'restored': restored, 'restoreProof': proof}
check_restore_augmentations(root, saved)
manifest_sha = private_json(root / 'manifest.json', saved)
@@ -632,11 +691,11 @@ def load_transaction(request):
if len(encoded) > limit:
fail('invalid-archive-manifest')
saved = json.loads(encoded)
- if saved['version'] not in (1, 2) or saved['transactionIdentity'] != identity(root):
+ if saved['version'] not in (1, 2, 3) or saved['transactionIdentity'] != identity(root):
fail('transaction-incarnation-changed')
# A bound v2 archive cannot evade its journal proof by declaring itself v1.
# Hash the exact bytes parsed, never a second path read after parsing.
- if (saved['version'] == 2 or 'manifestSha256' in request) and request.get('manifestSha256') != hashlib.sha256(encoded).hexdigest():
+ if (saved['version'] >= 2 or 'manifestSha256' in request) and request.get('manifestSha256') != hashlib.sha256(encoded).hexdigest():
fail('archive-manifest-proof-changed')
for label in ('archive', 'restore', 'quarantine'):
safe_path(str(root / label))
@@ -673,7 +732,8 @@ def check_restore_augmentations(root, saved):
for label in ('working', 'administration', 'common'):
archived = manifest(root / 'archive' / label)
attrs = lambda rows: [{'path': row['path'], 'xattrs': row['xattrs']} for row in rows]
- added = copy_augmentations(attrs(saved['restored'][label]), attrs(archived))
+ originals = recorded_provenance(records['restore'][label]) if saved['version'] == 3 else None
+ added = copy_augmentations(attrs(saved['restored'][label]), attrs(archived), originals)
if added is None or added != records['restore'][label]:
fail('restore-copy-augmentation-changed:' + label)
@@ -681,15 +741,17 @@ def check_restore_augmentations(root, saved):
def verify_saved_archive(root, saved):
check_restore_augmentations(root, saved)
facts = saved['facts']
- recorded = saved['copyAugmentations']['archive'] if saved['version'] == 2 else None
+ recorded = saved['copyAugmentations']['archive'] if saved['version'] >= 2 else None
for label in ('working', 'administration'):
expected_added = recorded[label] if recorded is not None else []
- added = copy_augmentations(manifest(root / 'archive' / label), facts['sources'][label])
+ originals = recorded_provenance(expected_added) if saved['version'] == 3 else None
+ added = copy_augmentations(manifest(root / 'archive' / label), facts['sources'][label], originals)
if added is None or added != expected_added:
fail('archive-changed:' + label)
for name, expected in facts['sources']['common'].items():
expected_added = recorded['common'][name] if recorded is not None else []
- added = copy_augmentations(manifest(root / 'archive' / 'common' / name, True), expected)
+ originals = recorded_provenance(expected_added) if saved['version'] == 3 else None
+ added = copy_augmentations(manifest(root / 'archive' / 'common' / name, True), expected, originals)
if added is None or added != expected_added:
fail('common-archive-changed:' + name)
if sorted(p.name for p in (root / 'archive/common').iterdir()) != sorted(facts['sources']['common']):
diff --git a/scripts/lib/initialized_checkout_archive_test.py b/scripts/lib/initialized_checkout_archive_test.py
index 644d7da740..8b35cc2dc2 100644
--- a/scripts/lib/initialized_checkout_archive_test.py
+++ b/scripts/lib/initialized_checkout_archive_test.py
@@ -40,6 +40,28 @@ class CopyMetadata(unittest.TestCase):
self.assertIsNone(archive.copy_augmentations([invalid], [copied]))
self.assertIsNone(archive.copy_augmentations([], [source]))
+ def test_replacement_requires_canonical_exact_original_bytes_and_only_provenance(self):
+ original = b'original provenance'
+ encoded = archive.base64.b64encode(original).decode('ascii')
+ source = {'path': '', 'kind': 'directory', 'mode': 0o700,
+ 'xattrs': {'com.apple.provenance': archive.hashlib.sha256(original).hexdigest(), 'fixture.original': 'b' * 64}}
+ copied = {**source, 'xattrs': {**source['xattrs'], 'com.apple.provenance': 'c' * 64}}
+ record = {'path': '', 'xattrs': {'com.apple.provenance': 'c' * 64},
+ 'originalBase64': {'com.apple.provenance': encoded}}
+ self.assertEqual(archive.copy_augmentations([copied], [source], {'': encoded}), [record])
+ self.assertIsNone(archive.copy_augmentations([copied], [source])) # v1/v2 stay strict.
+ for invalid in ('', encoded + '\n', encoded.rstrip('='), 'not base64', archive.base64.b64encode(b'wrong').decode('ascii')):
+ with self.subTest(invalid=invalid):
+ self.assertIsNone(archive.copy_augmentations([copied], [source], {'': invalid}))
+ for invalid in (
+ {**copied, 'xattrs': {'fixture.original': 'b' * 64}},
+ {**copied, 'xattrs': {**copied['xattrs'], 'fixture.original': 'd' * 64}},
+ {**copied, 'xattrs': {**copied['xattrs'], 'fixture.new': 'e' * 64}},
+ {**copied, 'mode': 0o755},
+ ):
+ self.assertIsNone(archive.copy_augmentations([invalid], [source], {'': encoded}))
+ self.assertEqual(archive.copy_augmentations([source], [source], {'': encoded}), [])
+
@unittest.skipUnless(sys.platform == 'darwin', 'Darwin metadata/rename ABI required')
class NativeArchive(unittest.TestCase):
@@ -194,7 +216,7 @@ class NativeArchive(unittest.TestCase):
with patch.object(archive, 'raw_xattrs', observed):
self.preserve()
saved = json.loads((self.txn / 'manifest.json').read_text())
- self.assertEqual(saved['version'], 2)
+ self.assertEqual(saved['version'], 3)
self.assertTrue(saved['copyAugmentations']['archive']['working'])
config_path = original['modules'][0]['administrationPath'] + '/config'
copied_config = next(row for row in saved['restored']['administration'] if row['path'] == config_path)
@@ -270,6 +292,93 @@ class NativeArchive(unittest.TestCase):
with patch.object(archive.json, 'loads', replace_after_read), self.assertRaisesRegex(RuntimeError, 'archive-manifest-proof-changed'):
archive.load_transaction({**self.request, 'manifestSha256': archive.hashlib.sha256(replacement).hexdigest()})
+ def test_v3_preserves_replaced_common_and_module_provenance_without_installing_attributes(self):
+ original = archive.inspect(self.request, full=True)
+ module_relative = original['modules'][0]['administrationPath'] + '/config'
+ common = Path(original['commonGitDir'])
+ admin = Path(original['privateGitDir'])
+ raw = archive.raw_xattrs
+ values = {
+ common / 'info': b'original common provenance',
+ admin / module_relative: b'original module provenance',
+ self.txn / 'quarantine/administration' / module_relative: b'original module provenance',
+ self.txn / 'archive/common/info': b'archive common provenance',
+ self.txn / 'archive/administration' / module_relative: b'archive module provenance',
+ self.txn / 'restore/common/info': b'restore common provenance',
+ self.txn / 'restore/administration' / module_relative: b'restore module provenance',
+ }
+ def observed(path):
+ attrs = raw(path)
+ return {**attrs, 'com.apple.provenance': values[path]} if path in values else attrs
+ with patch.object(archive, 'raw_xattrs', observed):
+ proof = self.preserve()
+ saved = json.loads((self.txn / 'manifest.json').read_text())
+ self.assertEqual(saved['version'], 3)
+ rows = saved['copyAugmentations']
+ archived = rows['archive']['common']['info'][0]
+ self.assertEqual(archived['path'], '')
+ self.assertEqual(archive.provenance_value(archived['originalBase64']['com.apple.provenance']), values[common / 'info'])
+ restored = next(row for row in rows['restore']['common'] if row['path'] == 'info')
+ self.assertEqual(archive.provenance_value(restored['originalBase64']['com.apple.provenance']), values[self.txn / 'archive/common/info'])
+ module = next(row for row in rows['archive']['administration'] if row['path'] == module_relative)
+ self.assertEqual(archive.provenance_value(module['originalBase64']['com.apple.provenance']), values[admin / module_relative])
+ self.assertTrue(archive.verify(self.request)['verified'])
+ for version in (1, 2):
+ altered = {**saved, 'version': version}
+ with self.subTest(version=version), self.assertRaisesRegex(RuntimeError, 'archive-changed|restore-copy-augmentation-changed'):
+ archive.verify_saved_archive(self.txn, altered)
+ for change in ('missing', 'wrong', 'extra-key', 'duplicate', 'unchanged-copy'):
+ altered = copy.deepcopy(saved)
+ entries = altered['copyAugmentations']['archive']['common']['info']
+ entry = entries[0]
+ if change == 'missing':
+ del entry['originalBase64']
+ elif change == 'wrong':
+ entry['originalBase64']['com.apple.provenance'] = archive.base64.b64encode(b'wrong').decode('ascii')
+ elif change == 'extra-key':
+ entry['originalBase64']['fixture.other'] = ''
+ elif change == 'duplicate':
+ entries.append(copy.deepcopy(entry))
+ else:
+ entry['xattrs']['com.apple.provenance'] = saved['facts']['sources']['common']['info'][0]['xattrs']['com.apple.provenance']
+ with self.subTest(change=change), self.assertRaisesRegex(RuntimeError, 'common-archive-changed|invalid-provenance-preimage-layout'):
+ archive.verify_saved_archive(self.txn, altered)
+ # Altered preimages cannot be re-bound by editing the manifest.
+ altered = copy.deepcopy(saved)
+ altered['copyAugmentations']['archive']['common']['info'][0]['originalBase64']['com.apple.provenance'] = ''
+ path = self.txn / 'manifest.json'
+ preserved_bytes = path.read_bytes()
+ path.write_text(json.dumps(altered))
+ with self.assertRaisesRegex(RuntimeError, 'archive-manifest-proof-changed'):
+ archive.verify(self.request)
+ path.write_bytes(preserved_bytes)
+ self.assertEqual(proof['manifestSha256'], archive.sha(path))
+ values[common / 'info'] = b'changed source'
+ with self.assertRaisesRegex(RuntimeError, 'common-store-changed'):
+ archive.verify(self.request)
+ values[common / 'info'] = b'original common provenance'
+ for part in ('working', 'administration'):
+ archive.move({**self.request, 'part': part, 'direction': 'quarantine'})
+ self.assertTrue(archive.verify(self.request)['verified'])
+ # Recovery proof stays self-contained after live common storage is unavailable.
+ common.rename(self.repo / '.git-unavailable')
+ self.assertTrue(archive.verify({**self.request, 'mode': 'standalone'})['standalone'])
+
+ def test_version_two_keeps_additions_but_refuses_existing_provenance_replacement(self):
+ self.preserve()
+ path = self.txn / 'manifest.json'
+ saved = json.loads(path.read_text())
+ saved['version'] = 2
+ path.write_text(json.dumps(saved))
+ self.request['manifestSha256'] = archive.sha(path)
+ self.assertTrue(archive.verify(self.request)['verified'])
+ raw = archive.raw_xattrs
+ def added(path):
+ attrs = raw(path)
+ return {**attrs, 'com.apple.provenance': b'unrecorded'} if path == self.txn / 'archive/working/base.txt' else attrs
+ with patch.object(archive, 'raw_xattrs', added), self.assertRaisesRegex(RuntimeError, 'archive-changed|restore-copy-augmentation-changed'):
+ archive.verify({**self.request, 'mode': 'standalone'})
+
def test_version_one_archive_does_not_accept_unrecorded_copy_provenance(self):
self.preserve()
saved = json.loads((self.txn / 'manifest.json').read_text())
diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.js
index a1566b6531..d26e940c90 100644
--- a/server/services/branchCompletionPolicy.js
+++ b/server/services/branchCompletionPolicy.js
@@ -3,11 +3,12 @@
* shared forge logins never authorize reconciliation. No parallel policy store.
*/
import { readFile, readdir, stat } from 'node:fs/promises';
-import { join, resolve } from 'node:path';
+import { isAbsolute, join, resolve } from 'node:path';
import { PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
import { isTruthyMeta } from '../lib/metadataFlags.js';
import { PR_COMPLETIONS, explicitPrCompletion } from '../lib/prDisposition.js';
+import { parsePullRequestUrl } from '../lib/gitForge.js';
const samePath = (a, b) => typeof a === 'string' && typeof b === 'string'
&& (process.platform === 'win32' ? resolve(a).toLowerCase() === resolve(b).toLowerCase() : resolve(a) === resolve(b));
@@ -124,22 +125,83 @@ function completionDecision({ repoPath, branch, prUrl, tip, agents }) {
return { release, obligation, policies, reason: handoff ? held : 'pr-completion-review-required' };
}
-/** A new operator review may settle completed legacy review obligations only.
- * This is evidence for the scoped retirement caller, never unattended consent.
+/** A fresh exact-head forge review may distinguish incarnations of a reused
+ * branch. A timestamp alone never excludes an owner: its explicit private
+ * checkout must also differ, and a policy for this PR remains relevant.
+ */
+const reviewTarget = policy => policy.agent.metadata?.reviewLoopMergeTarget;
+const retirementPr = policy => policy.prUrl || reviewTarget(policy)?.url;
+
+function reviewedIncarnation(input, policies) {
+ if (!isAbsolute(input.checkoutPath || '') || samePath(input.checkoutPath, input.repoPath)
+ || !input.prUrl || input.verifiedPrHead !== input.tip
+ || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(input.tip || '')) return null;
+ const owners = policies.filter(policy => policy.agent.status === 'completed' && policy.agent.result?.success === true
+ && policy.completion === PR_COMPLETIONS.REVIEW_THEN_MERGE
+ && samePath(policy.agent.metadata?.workspacePath, input.checkoutPath)
+ && retirementPr(policy) === input.prUrl && (!policy.tip || policy.tip === input.tip)
+ && (!reviewTarget(policy) || (reviewTarget(policy).branch === input.branch && reviewTarget(policy).url === input.prUrl))
+ && Number.isFinite(Date.parse(policy.agent.startedAt))
+ && Date.parse(policy.agent.completedAt) >= Date.parse(policy.agent.startedAt));
+ if (!owners.length) return null;
+ const firstStarted = Math.min(...owners.map(policy => Date.parse(policy.agent.startedAt)));
+ const identity = input.checkoutIdentities?.[input.checkoutPath];
+ const prior = [];
+ const current = policies.filter(policy => {
+ const workspace = policy.agent.metadata?.workspacePath;
+ const target = reviewTarget(policy);
+ const unrelated = policy.agent.status === 'completed'
+ && policy.completion !== PR_COMPLETIONS.LEAVE_OPEN
+ && isAbsolute(workspace || '') && !samePath(workspace, input.repoPath) && !samePath(workspace, input.checkoutPath)
+ && identity && input.checkoutIdentities?.[workspace] && input.checkoutIdentities[workspace] !== identity
+ && input.checkoutIdentities[input.repoPath] && input.checkoutIdentities[workspace] !== input.checkoutIdentities[input.repoPath]
+ && Number.isFinite(Date.parse(policy.agent.startedAt))
+ && Date.parse(policy.agent.completedAt) >= Date.parse(policy.agent.startedAt)
+ && Date.parse(policy.agent.completedAt) < firstStarted
+ && policy.prUrl !== input.prUrl && target?.url !== input.prUrl
+ && (!policy.prUrl || parsePullRequestUrl(policy.prUrl))
+ && (!target || (target.branch === input.branch && parsePullRequestUrl(target.url)
+ && (!policy.prUrl || policy.prUrl === target.url)));
+ if (unrelated) prior.push(policy);
+ return !unrelated;
+ });
+ return { current, prior };
+}
+
+/** Operator review settles successful completed review obligations. PR-bound
+ * obligations additionally need a fresh exact-head, exact-checkout incarnation.
+ * This is review evidence, never unattended consent or a saved policy rewrite.
*/
export function reviewedRetirementPolicy(input) {
- const decision = completionDecision(input);
- if (decision.reason === unavailable || decision.reason === held) return { reason: decision.reason };
- const policies = decision.policies || [];
+ // Keep mismatching known PRs until explicit incarnation checks establish
+ // unrelated history; a current checkout's handoff must never be filtered out.
+ const decision = completionDecision({ ...input, prUrl: undefined });
+ if (decision.reason === unavailable) return { reason: decision.reason };
+ const incarnation = reviewedIncarnation(input, decision.policies || []);
+ const policies = incarnation?.current || decision.policies || [];
+ if (policies.some(p => p.completion === PR_COMPLETIONS.LEAVE_OPEN)) return { reason: held };
if (policies.some(p => p.agent.status !== 'completed' || p.agent.result?.success !== true
- || p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE || p.prUrl)) {
+ || p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE
+ || (retirementPr(p) && (!incarnation || retirementPr(p) !== input.prUrl))
+ || (reviewTarget(p) && (reviewTarget(p).branch !== input.branch || (p.prUrl && p.prUrl !== reviewTarget(p).url)))
+ || (incarnation && p.tip && p.tip !== input.tip))) {
return { reason: 'retirement-policy-not-legacy-completed' };
}
return { reason: null, policies: policies.map(p => ({
id: p.agent.id || p.agent.agentId, startedAt: p.agent.startedAt,
completedAt: p.agent.completedAt, status: p.agent.status, success: p.agent.result.success,
branch: p.branch, completion: p.completion,
- })).sort((a, b) => String(a.id).localeCompare(String(b.id))) };
+ ...(incarnation && { prUrl: retirementPr(p) ?? null, tip: p.tip ?? null, workspacePath: p.agent.metadata?.workspacePath ?? null }),
+ })).sort((a, b) => String(a.id).localeCompare(String(b.id))),
+ ...(incarnation && {
+ reviewedPr: { prUrl: input.prUrl, tip: input.tip, checkoutPath: input.checkoutPath },
+ priorCheckouts: incarnation.prior.map(p => ({
+ id: p.agent.id || p.agent.agentId, startedAt: p.agent.startedAt, completedAt: p.agent.completedAt,
+ status: p.agent.status, success: p.agent.result?.success ?? null, completion: p.completion ?? null,
+ workspacePath: p.agent.metadata.workspacePath, prUrl: retirementPr(p) ?? null,
+ checkoutIdentity: input.checkoutIdentities[p.agent.metadata.workspacePath],
+ })).sort((a, b) => String(a.id).localeCompare(String(b.id))),
+ }) };
}
/** A verified merged receipt may settle automatic completion obligations, but
diff --git a/server/services/branchCompletionPolicy.test.js b/server/services/branchCompletionPolicy.test.js
index 62ec3a998a..81f39bca87 100644
--- a/server/services/branchCompletionPolicy.test.js
+++ b/server/services/branchCompletionPolicy.test.js
@@ -247,3 +247,72 @@ describe('scoped legacy retirement policy', () => {
expect(await snapshotHold(agents)).toBe('pr-completion-review-required');
});
});
+
+describe('reviewed reused-branch checkout incarnation', () => {
+ const checkoutPath = join(tmpdir(), 'synthetic-current-checkout');
+ const input = () => ({ repoPath, branch, checkoutPath, prUrl, tip: runtime.tip, verifiedPrHead: runtime.tip,
+ checkoutIdentities: { [repoPath]: 'primary-filesystem-identity', [checkoutPath]: 'current-filesystem-identity',
+ [join(tmpdir(), 'synthetic-prior-checkout')]: 'prior-missing-path-identity' } });
+ function owners() {
+ register('current', 'review-then-merge', '2026-03-01T00:00:00Z');
+ const current = runtime.agents.current;
+ current.completedAt = '2026-03-01T01:00:00Z';
+ current.metadata.workspacePath = checkoutPath;
+ current.metadata.reviewLoopMergeTarget = { branch, url: prUrl };
+ const prior = { ...structuredClone(current), id: 'prior', startedAt: '2026-02-01T00:00:00Z',
+ completedAt: '2026-02-01T01:00:00Z', result: { success: false } };
+ prior.metadata.workspacePath = join(tmpdir(), 'synthetic-prior-checkout');
+ prior.metadata.prCompletionPolicy = null;
+ prior.metadata.reviewLoopMergeTarget = null;
+ return [current, prior];
+ }
+
+ it('separates explicit prior checkout history only under fresh current PR/head proof', () => {
+ const agents = owners();
+ const result = reviewedRetirementPolicy({ ...input(), agents });
+ expect(result).toMatchObject({ reason: null, policies: [{ id: 'current', prUrl }],
+ priorCheckouts: [{ id: 'prior', success: false }], reviewedPr: { prUrl, checkoutPath, tip: runtime.tip } });
+ expect(reviewedRetirementPolicy({ ...input(), verifiedPrHead: 'b'.repeat(40), agents }).reason).toBeTruthy();
+ expect(reviewedRetirementPolicy({ ...input(), agents: [agents[0]], verifiedPrHead: null }).reason).toBeTruthy();
+ agents[0].metadata.branchCompletionPolicy = { branch, prUrl, tip: runtime.tip, completion: 'review-then-merge' };
+ expect(reviewedRetirementPolicy({ ...input(), agents }).reason).toBeNull();
+ agents[0].metadata.branchCompletionPolicy.tip = 'b'.repeat(40);
+ expect(reviewedRetirementPolicy({ ...input(), agents }).reason).toBeTruthy();
+ });
+
+ it.each(['same-checkout', 'missing-checkout', 'primary-checkout', 'relative-checkout', 'unknown-completion-time',
+ 'overlapping-time', 'running', 'paused', 'same-pr', 'current-failed', 'current-unknown', 'manual-handoff', 'historical-manual',
+ 'contradictory-pr', 'unreadable-identity', 'same-filesystem-identity'])(
+ 'retains current or ambiguous policy history: %s', change => {
+ const agents = owners();
+ const [current, prior] = agents;
+ if (change === 'same-checkout') prior.metadata.workspacePath = checkoutPath;
+ if (change === 'missing-checkout') delete prior.metadata.workspacePath;
+ if (change === 'primary-checkout') prior.metadata.workspacePath = repoPath;
+ if (change === 'relative-checkout') prior.metadata.workspacePath = 'prior';
+ if (change === 'unknown-completion-time') delete prior.completedAt;
+ if (change === 'overlapping-time') prior.completedAt = current.startedAt;
+ if (['running', 'paused'].includes(change)) prior.status = change;
+ if (change === 'same-pr') prior.metadata.reviewLoopMergeTarget = { branch, url: prUrl };
+ if (change === 'current-failed') current.result.success = false;
+ if (change === 'current-unknown') current.metadata.prCompletionPolicy = null;
+ if (change === 'manual-handoff') current.metadata.prCompletionPolicy = 'leave-open';
+ if (change === 'historical-manual') prior.metadata.prCompletionPolicy = 'leave-open';
+ if (change === 'contradictory-pr') {
+ prior.metadata.branchCompletionPolicy = { branch, completion: 'review-then-merge', prUrl: 'https://github.com/example/repository/pull/41' };
+ prior.metadata.reviewLoopMergeTarget = { branch, url: prUrl };
+ }
+ const scope = input();
+ if (change === 'unreadable-identity') delete scope.checkoutIdentities[prior.metadata.workspacePath];
+ if (change === 'same-filesystem-identity') scope.checkoutIdentities[prior.metadata.workspacePath] = scope.checkoutIdentities[checkoutPath];
+ expect(reviewedRetirementPolicy({ ...scope, agents }).reason).toBeTruthy();
+ });
+
+ it('uses the first current incarnation owner, not a later successful recovery, as the overlap cutoff', () => {
+ const agents = owners();
+ agents[1].completedAt = '2026-03-01T00:30:00Z';
+ const recovery = { ...structuredClone(agents[0]), id: 'recovery',
+ startedAt: '2026-03-01T02:00:00Z', completedAt: '2026-03-01T03:00:00Z' };
+ expect(reviewedRetirementPolicy({ ...input(), agents: [...agents, recovery] }).reason).toBeTruthy();
+ });
+});
diff --git a/server/services/branchReconcileRetirement.js b/server/services/branchReconcileRetirement.js
index 9a602a229b..05f81b2c53 100644
--- a/server/services/branchReconcileRetirement.js
+++ b/server/services/branchReconcileRetirement.js
@@ -1,17 +1,41 @@
/** Review work is dispatchable; a review hold is never deletion authority. */
import { agentApiCurl } from '../lib/agentApiToken.js';
import { localApiBaseUrl } from '../lib/networkExposure.js';
+import { parsePullRequestUrl } from '../lib/gitForge.js';
-async function mergedPrUrl(app, branch) {
+async function mergedPrUrl(app, branch, tip) {
const [{ execGh }, { resolveForgeExecOptions }, { getOriginInfo }, { githubRepoSpec }] = await Promise.all([
import('./github.js'), import('./forgeExecOptions.js'), import('../lib/gitRemote.js'), import('../lib/workTracker.js'),
]);
- const spec = githubRepoSpec(await getOriginInfo(app.repoPath));
+ const origin = await getOriginInfo(app.repoPath);
+ const spec = githubRepoSpec(origin);
if (!spec) throw new Error('retirement-forge-unsupported');
const options = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount ?? null });
- const rows = JSON.parse(await execGh(['pr', 'list', '--repo', spec, '--head', branch, '--state', 'merged', '--limit', '2', '--json', 'url'], undefined, options));
- if (!Array.isArray(rows) || rows.length !== 1 || typeof rows[0].url !== 'string') throw new Error('retirement-pr-ambiguous');
- return rows[0].url;
+ if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(tip || '')) throw new Error('retirement-pr-ambiguous');
+ // Query the exact commit, not an unbounded reused-branch history. A capped
+ // association result cannot establish uniqueness and stays held.
+ const rows = JSON.parse(await execGh(['api', '--hostname', origin.host,
+ `repos/${origin.fullName}/commits/${tip}/pulls?per_page=100`], undefined, options));
+ if (!Array.isArray(rows) || rows.length >= 100
+ || new Set(rows.map(row => row?.html_url)).size !== rows.length
+ || rows.some(row => {
+ const parsed = parsePullRequestUrl(row?.html_url);
+ return !parsed || parsed.host !== origin.host || `${parsed.owner}/${parsed.repo}` !== origin.fullName
+ || typeof row.head?.ref !== 'string' || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(row.head?.sha || '');
+ })) throw new Error('retirement-pr-ambiguous');
+ const matches = rows.filter(row => row.head.sha === tip && row.head.ref === branch
+ && row.head.repo?.full_name === origin.fullName && row.base?.repo?.full_name === origin.fullName
+ && row.state === 'closed' && typeof row.merged_at === 'string' && Number.isFinite(Date.parse(row.merged_at)));
+ if (matches.length > 1) throw new Error('retirement-pr-ambiguous');
+ // Selection is not proof: the preview re-reads this exact PR and verifies its
+ // repository, merge, current refs and complete original scope before review.
+ if (matches.length === 1) return matches[0].html_url;
+ // Preserve historical review of an older local tip only when branch history
+ // itself has exactly one candidate. Never choose among mismatching heads.
+ const historical = JSON.parse(await execGh(['pr', 'list', '--repo', spec, '--head', branch, '--state', 'merged',
+ '--limit', '2', '--json', 'url'], undefined, options));
+ if (!Array.isArray(historical) || historical.length !== 1 || typeof historical[0]?.url !== 'string') throw new Error('retirement-pr-ambiguous');
+ return historical[0].url;
}
/** Inventory is persisted first: the same preview used by the live endpoint
@@ -29,7 +53,7 @@ export async function prepareReconcileRetirements(app, result, deps = {}) {
if (!tree || tree.managed !== true || tree.locked !== false || tree.head !== branch.tip) continue;
const release = { branch: tree.branch, path: tree.path, head: tree.head, locked: false, lockReason: tree.lockReason ?? null };
try {
- const prUrl = await readPr(app, branch.branch);
+ const prUrl = await readPr(app, branch.branch, release.head);
const prepared = await prepare({ appId: app.id, release, prUrl });
if (!prepared.ok) { held.push({ ...release, reason: prepared.reason }); continue; }
// The preview's policy gate requires completed successful legacy review
diff --git a/server/services/branchReconcileRetirement.test.js b/server/services/branchReconcileRetirement.test.js
index affbf2242a..76da4aa242 100644
--- a/server/services/branchReconcileRetirement.test.js
+++ b/server/services/branchReconcileRetirement.test.js
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
import { prepareReconcileRetirements, retirementReviewInstructions } from './branchReconcileRetirement.js';
+const forge = vi.hoisted(() => ({ read: vi.fn() }));
+vi.mock('./github.js', () => ({ execGh: forge.read }));
+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: async () => ({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'example/repo' }) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => ({ cwd: '/example/repo', env: { GH_TOKEN: 'synthetic' } }) }));
+
const app = { id: 'example', repoPath: '/example/repo' };
const head = 'a'.repeat(40);
const branch = { branch: 'claim/issue-42', tip: head, worktreePath: '/example/checkout', isMerged: true,
@@ -62,4 +67,41 @@ describe('historical completed-checkout review obligations', () => {
deps.prepare.mockResolvedValue({ ok: true, review: { policy: { policies: [] } } });
expect((await prepareReconcileRetirements(app, scan(), deps)).held[0].reason).toBe('retirement-policy-changed');
});
+
+ it('selects the unique exact head on a reused branch, then requires its fresh preview', async () => {
+ const deps = setup();
+ const row = { html_url: 'https://github.com/example/repo/pull/42', head: { ref: branch.branch, sha: head, repo: { full_name: 'example/repo' } },
+ base: { repo: { full_name: 'example/repo' } }, state: 'closed', merged_at: '2026-01-01T00:00:00Z' };
+ forge.read.mockResolvedValue(JSON.stringify([{ ...row, html_url: 'https://github.com/example/repo/pull/41', head: { ...row.head, sha: 'b'.repeat(40) } }, row]));
+ const result = await prepareReconcileRetirements(app, scan(), { prepare: deps.prepare });
+ expect(result.candidates).toHaveLength(1);
+ expect(deps.prepare).toHaveBeenCalledWith(expect.objectContaining({ prUrl: row.html_url, release: expect.objectContaining({ head }) }));
+ expect(forge.read).toHaveBeenLastCalledWith(['api', '--hostname', 'github.com', `repos/example/repo/commits/${head}/pulls?per_page=100`], undefined,
+ { cwd: '/example/repo', env: { GH_TOKEN: 'synthetic' } });
+ deps.prepare.mockResolvedValue({ ok: false, reason: 'retirement-pr-not-matching-merged' });
+ expect(await prepareReconcileRetirements(app, scan(), { prepare: deps.prepare })).toMatchObject({
+ candidates: [], held: [{ reason: 'retirement-pr-not-matching-merged' }],
+ });
+ });
+
+ it.each(['duplicate-head', 'no-matching-head', 'capped', 'foreign-repository', 'foreign-branch', 'fork', 'duplicate-url', 'unreadable'])(
+ 'retains reused-branch ambiguity instead of dispatching: %s', async change => {
+ const row = { html_url: 'https://github.com/example/repo/pull/42', head: { ref: branch.branch, sha: head, repo: { full_name: 'example/repo' } },
+ base: { repo: { full_name: 'example/repo' } }, state: 'closed', merged_at: '2026-01-01T00:00:00Z' };
+ let rows = [row, { ...row, html_url: 'https://github.com/example/repo/pull/41', head: { ...row.head, sha: 'b'.repeat(40) } }];
+ if (change === 'duplicate-head') rows[1].head.sha = head;
+ if (change === 'no-matching-head') rows[0].head.sha = 'c'.repeat(40);
+ if (change === 'capped') rows = Array.from({ length: 100 }, (_, index) => ({ ...row, html_url: `https://github.com/example/repo/pull/${index + 1}` }));
+ if (change === 'foreign-repository') rows[0].html_url = 'https://github.com/other/repo/pull/42';
+ if (change === 'foreign-branch') rows[0].head.ref = 'another/branch';
+ if (change === 'fork') rows[0].head.repo.full_name = 'fork/repo';
+ if (change === 'duplicate-url') rows[1].html_url = row.html_url;
+ if (change === 'unreadable') rows = null;
+ forge.read.mockResolvedValue(JSON.stringify(rows));
+ const deps = setup();
+ expect(await prepareReconcileRetirements(app, scan(), { prepare: deps.prepare })).toMatchObject({
+ candidates: [], held: [{ reason: 'retirement-pr-ambiguous' }],
+ });
+ expect(deps.prepare).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/git.js b/server/services/git.js
index a64dc5e5aa..b1f5977e00 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1,6 +1,8 @@
import { existsSync } from 'fs';
-import { join, resolve } from 'path';
-import { safeJSONParse, PATHS, sleep } from '../lib/fileUtils.js';
+import { mkdtemp } from 'fs/promises';
+import { tmpdir } from 'os';
+import { delimiter, join, resolve } from 'path';
+import { safeJSONParse, PATHS, sleep, rmGuarded } from '../lib/fileUtils.js';
import { isGitLockError, listWorktrees, reapMergedWorktrees } from './worktreeManager.js';
import { execGit, execGitSafe } from '../lib/execGit.js';
import { clearStaleGitLock } from '../lib/gitStaleLock.js';
@@ -51,6 +53,7 @@ export async function getStatus(dir, { paths = [] } = {}) {
const result = await execGit(
['status', '--porcelain', ...(paths.length ? ['--', ...paths] : [])],
dir,
+ { env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } },
);
// trimEnd (not trim): porcelain status codes use leading spaces (e.g. ' M' = unstaged)
const lines = result.stdout.trimEnd().split('\n').filter(Boolean);
@@ -84,7 +87,8 @@ export async function getStatus(dir, { paths = [] } = {}) {
* of `files[]` would just double the payload on every dirty tree.
*/
export async function getStatusPorcelain(dir) {
- return (await execGit(['status', '--porcelain'], dir)).stdout;
+ return (await execGit(['status', '--porcelain'], dir,
+ { env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } })).stdout;
}
/**
@@ -1536,7 +1540,12 @@ export async function hasBranchMergeEvidence(dir, branch, target) {
// not prove that a feature branch landed anywhere else.
if (!branch || !target || (branch === target && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(branch))) return false;
- const resolve = (ref) => execGit(['rev-parse', '--verify', `${ref}^{commit}`], dir, { ignoreExitCode: true })
+ const env = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' };
+ // An inherited writer's quarantine/object override must not redirect a
+ // repository inspection away from this checkout's own common object store.
+ delete env.GIT_OBJECT_DIRECTORY;
+ const readOptions = { ignoreExitCode: true, env };
+ const resolve = (ref) => execGit(['rev-parse', '--verify', `${ref}^{commit}`], dir, readOptions)
.then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
.catch(() => null);
@@ -1545,14 +1554,14 @@ export async function hasBranchMergeEvidence(dir, branch, target) {
// Fast path: branch tip already reachable from target (normal / ff / no-ff merge,
// or the branch carries no unique commits).
- const ancestor = await execGit(['merge-base', '--is-ancestor', branchSha, targetSha], dir, { ignoreExitCode: true })
+ const ancestor = await execGit(['merge-base', '--is-ancestor', branchSha, targetSha], dir, readOptions)
.then(r => r.exitCode === 0)
.catch(() => false);
if (ancestor) return true;
// Rebase/cherry-pick path: does target contain every branch commit as an
// individual patch-equivalent commit?
- const individualCherry = await execGit(['cherry', targetSha, branchSha], dir, { ignoreExitCode: true })
+ const individualCherry = await execGit(['cherry', targetSha, branchSha], dir, readOptions)
.then(r => r.exitCode === 0 ? r.stdout.trim() : null)
.catch(() => null);
if (individualCherry === null) return false;
@@ -1561,34 +1570,47 @@ export async function hasBranchMergeEvidence(dir, branch, target) {
}
// Squash path: does target already contain the branch's combined patch?
- const mergeBase = await execGit(['merge-base', targetSha, branchSha], dir, { ignoreExitCode: true })
+ const mergeBase = await execGit(['merge-base', targetSha, branchSha], dir, readOptions)
.then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
.catch(() => null);
if (!mergeBase) return false;
// No unique work beyond the merge base → nothing would be lost.
if (mergeBase === branchSha) return true;
- const branchTree = await execGit(['rev-parse', `${branchSha}^{tree}`], dir, { ignoreExitCode: true })
+ const branchTree = await execGit(['rev-parse', `${branchSha}^{tree}`], dir, readOptions)
.then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
.catch(() => null);
if (!branchTree) return false;
- // Write a synthetic commit object with the branch's full tree atop the merge base.
- // commit-tree uses the repo's configured identity; if that's unset it fails and
- // no merge evidence is established (the worktree is preserved).
- // This immutable object addition moves no refs or checkout state. A concurrent
- // complete-checkout archive still refuses if its exact common-store snapshot drifts.
- const synthesized = await execGit(['commit-tree', branchTree, '-p', mergeBase, '-m', 'merged-check-probe'], dir, { ignoreExitCode: true })
- .then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
- .catch(() => null);
- if (!synthesized) return false;
+ // Polling must not add dangling synthetic commits to the shared object store:
+ // that invalidates an otherwise stable preservation snapshot. Both commands
+ // use a private object directory with the original store as a read alternate.
+ return probeCombinedPatch(dir, branchTree, mergeBase, targetSha, readOptions).catch(() => false);
+}
- const combinedCherry = await execGit(['cherry', targetSha, synthesized], dir, { ignoreExitCode: true })
- .then(r => r.exitCode === 0 ? r.stdout.trim() : null)
- .catch(() => null);
- if (combinedCherry === null) return false;
- if (combinedCherry === '') return true; // empty patch (tree already matches) ⇒ merged
- return combinedCherry.split('\n').every(line => line.startsWith('-'));
+async function probeCombinedPatch(dir, branchTree, mergeBase, targetSha, readOptions) {
+ const objects = await execGit(['rev-parse', '--path-format=absolute', '--git-path', 'objects'], dir, readOptions);
+ if (objects.exitCode !== 0 || !objects.stdout.trim()) return false;
+ const scratch = await mkdtemp(join(tmpdir(), 'portos-merge-probe-'));
+ try {
+ const options = { ...readOptions, env: { ...readOptions.env,
+ GIT_OBJECT_DIRECTORY: scratch,
+ // Git accepts C-quoted entries, including paths containing the platform
+ // list separator, quotes or backslashes. Existing alternates remain valid.
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: [JSON.stringify(objects.stdout.trim()),
+ readOptions.env.GIT_ALTERNATE_OBJECT_DIRECTORIES].filter(Boolean).join(delimiter)
+ } };
+ // Preserve configured-identity behavior: an unavailable identity fails closed.
+ const synthetic = await execGit(['commit-tree', branchTree, '-p', mergeBase, '-m', 'merged-check-probe'], dir, options);
+ if (synthetic.exitCode !== 0 || !synthetic.stdout.trim()) return false;
+ const result = await execGit(['cherry', targetSha, synthetic.stdout.trim()], dir, options);
+ if (result.exitCode !== 0) return false;
+ const lines = result.stdout.trim();
+ return lines === '' || lines.split('\n').every(line => line.startsWith('-'));
+ } finally {
+ // Only this invocation's exclusively created scratch directory is removed.
+ await rmGuarded(scratch, { recursive: true, force: true, maxRetries: 3 });
+ }
}
// Backward-compatible name for callers using the original evidence predicate.
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index be15a5a6f4..49ac7258de 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -21,7 +21,7 @@
import { createReadStream, realpathSync } from 'node:fs';
import { lstat, stat, readlink, readdir, readFile, chmod } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
-import { basename, dirname, join, resolve } from 'node:path';
+import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
import { atomicWrite, copyFileGuarded, ensureDir, PATHS, rmGuarded, sha256File, writeFileGuarded } from '../lib/fileUtils.js';
import { execGit } from '../lib/execGit.js';
import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';
@@ -75,14 +75,42 @@ async function snapshotAdministration(path, missingRoot = null) {
return { files, symlinks, fingerprint };
}
-async function retirementPolicy(repoPath, branch, opts) {
+async function retirementPolicy(repoPath, branch, opts, reviewIdentity = {}) {
const { readBranchCompletionPolicies, reviewedRetirementPolicy, mergedReceiptRetirementPolicy } = await import('./branchCompletionPolicy.js');
const policies = await (opts.readPolicies || (() => readBranchCompletionPolicies({ repairIndex: false })))().catch(() => null);
if (opts.mergedReceipt) return mergedReceiptRetirementPolicy({ repoPath, branch, agents: policies,
tip: opts.mergedReceipt.expectedHeadSha });
- return reviewedRetirementPolicy({ repoPath, branch, agents: policies });
+ const checkoutIdentities = {};
+ if (reviewIdentity.verifiedPrHead === reviewIdentity.tip && reviewIdentity.tip && Array.isArray(policies)) {
+ const paths = new Set([reviewIdentity.checkoutPath, repoPath]);
+ for (const agent of policies) {
+ const meta = agent?.metadata || {};
+ const scopes = [meta.worktreeBranch, meta.jiraBranch, meta.claimBranch, meta.branchCompletionPolicy?.branch,
+ ...(Array.isArray(meta.claimBranches) ? meta.claimBranches : []),
+ ...(Array.isArray(meta.claimReleasedBranches) ? meta.claimReleasedBranches : [])];
+ if (scopes.includes(branch) && isAbsolute(meta.workspacePath || '')) paths.add(meta.workspacePath);
+ }
+ // A failed identity read or excessive history cannot prove distinctness.
+ // Missing paths resolve through their existing canonical ancestor, the same
+ // identity rule used to locate missing checkout administration below.
+ if (paths.size <= 1000) {
+ const entries = [...paths];
+ for (let offset = 0; offset < entries.length; offset += 25) {
+ await Promise.all(entries.slice(offset, offset + 25).map(async path => {
+ const facts = await missingPathIdentity(path).catch(() => null);
+ if (facts) checkoutIdentities[path] = JSON.stringify({ dev: facts.dev, ino: facts.ino, tail: facts.tail });
+ }));
+ }
+ }
+ }
+ return reviewedRetirementPolicy({ repoPath, branch, agents: policies, ...reviewIdentity, checkoutIdentities });
}
+const policyReviewIdentity = (release, prUrl, forge) => ({
+ checkoutPath: release.path, tip: release.head, prUrl,
+ verifiedPrHead: forge?.prUrl === prUrl ? forge.prHead : null,
+});
+
async function reviewCurrentCheckout({ repoPath, release, prUrl, unlocked = false }, opts = {}) {
if (!release.branch || PROTECTED_BRANCHES.includes(release.branch)) return { ok: false, reason: 'protected-branch' };
const matched = await matchRelease(repoPath, unlocked ? { ...release, locked: false, lockReason: null } : release);
@@ -90,12 +118,15 @@ async function reviewCurrentCheckout({ repoPath, release, prUrl, unlocked = fals
const owner = await ownerReason({ repoPath, tree: matched.tree, branch: release.branch,
readAgents: opts.readAgents || readClaimOwnershipAgents, reviewed: true });
if (owner) return { ok: false, reason: owner };
- const policy = await retirementPolicy(repoPath, release.branch, opts);
+ const { buildCheckoutRetirementReview, readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
+ const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, release.branch, prUrl, { forgeAccount: opts.forgeAccount })
+ .catch(error => ({ error }));
+ if (forge?.error) return { ok: false, reason: /^retirement-[a-z-]+$/.test(forge.error.message) ? forge.error.message : 'retirement-forge-unavailable' };
+ const policy = await retirementPolicy(repoPath, release.branch, opts, policyReviewIdentity(release, prUrl, forge));
if (policy.reason) return { ok: false, reason: policy.reason };
- const { buildCheckoutRetirementReview } = await import('./heldCheckoutReview.js');
return Promise.all([snapshotContent(release.path), snapshotAdministration(release.path)])
.then(([content, administration]) => buildCheckoutRetirementReview({ repoPath, release, prUrl,
- contentFingerprint: content.fingerprint, administrationFingerprint: administration.fingerprint, policy }, opts))
+ contentFingerprint: content.fingerprint, administrationFingerprint: administration.fingerprint, policy }, { ...opts, readForge: async () => forge }))
.then(review => ({ ok: true, review }), error => ({ ok: false,
reason: /^retirement-[a-z-]+$/.test(error.message) ? error.message : 'retirement-local-evidence-unavailable' }));
}
@@ -505,8 +536,8 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
if (hold) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: hold };
if (review) {
const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
- const policy = await retirementPolicy(repoPath, branch, opts);
const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, branch, review.prUrl, { forgeAccount: opts.forgeAccount }).catch(() => null);
+ const policy = await retirementPolicy(repoPath, branch, opts, policyReviewIdentity(release, review.prUrl, forge));
if (JSON.stringify(policy) !== JSON.stringify(reviewed.review.policy) || JSON.stringify(forge) !== JSON.stringify(reviewed.review.forge)) {
return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'retirement-evidence-changed' };
}
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 32f5b934b8..596723b3da 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -5,10 +5,10 @@
* its lock and its branch as found.
*/
import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
-import { mkdtemp, mkdir, rm, rename, writeFile, readFile, readdir, symlink, utimes } from 'fs/promises';
+import { cp, mkdtemp, mkdir, rm, rename, writeFile, readFile, readdir, symlink, utimes } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
import { tmpdir } from 'os';
-import { join } from 'path';
+import { dirname, join } from 'path';
import { execGit } from '../lib/execGit.js';
import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -639,6 +639,117 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(injected.policies[0].metadata.branchCompletionPolicy).toBeUndefined();
});
+ function reusedBranchOwners(c) {
+ const current = { id: 'current-review-owner', status: 'completed', result: { success: true },
+ startedAt: '2026-03-01T00:00:00Z', completedAt: '2026-03-01T01:00:00Z',
+ metadata: { sourceWorkspace: repo, workspacePath: c.release.path, worktreeBranch: c.release.branch,
+ prCompletionPolicy: 'review-then-merge', reviewLoopMergeTarget: { branch: c.release.branch, url: c.forge.prUrl } } };
+ // Reused quality branches retain older records with no explicit policy,
+ // including unsuccessful launches. Distinct completed checkout incarnations
+ // are history; neither their age nor a success summary grants permission.
+ const prior = Array.from({ length: 33 }, (_, index) => ({
+ id: `prior-owner-${index}`, status: 'completed', result: { success: index !== 0 },
+ startedAt: '2026-02-01T00:00:00Z', completedAt: '2026-02-01T01:00:00Z',
+ metadata: { sourceWorkspace: repo, workspacePath: join(external, `prior-${index}`), worktreeBranch: c.release.branch },
+ }));
+ injected.policies = [current, ...prior, {
+ id: 'unscoped-successful-recovery', status: 'completed', result: { success: true },
+ metadata: { workspacePath: repo, recoveryOrigin: { subsystem: 'repository-cleanup', parentAgentId: current.id } },
+ }];
+ return current;
+ }
+
+ it('retires a freshly reviewed reused-branch incarnation with a standalone archive and exact receipt', async () => {
+ const c = await reviewedCheckout('quality-reused', { gitlink: true });
+ reusedBranchOwners(c);
+ const shared = join(scratch, 'shared-dependencies');
+ await mkdir(shared);
+ await writeFile(join(shared, 'untouched'), 'shared installation\n');
+ if (SYMLINKS) {
+ await writeFile(join(c.path, '.gitignore'), 'ignored.txt\nlinked\nnode_modules\n');
+ for (const relative of ['node_modules', 'server/node_modules', 'client/node_modules', 'autofixer/node_modules']) {
+ await mkdir(dirname(join(c.path, relative)), { recursive: true });
+ await symlink(shared, join(c.path, relative), 'dir');
+ }
+ }
+ await writeFile(join(c.path, 'staged.txt'), 'unique staged content\n');
+ await execGit(['add', 'staged.txt'], c.path);
+ const index = await readFile(join(c.admin, 'index'));
+ const reflog = await readFile(join(c.admin, 'logs/HEAD'));
+ const policiesBefore = structuredClone(injected.policies);
+ const prepared = await c.prepare();
+ expect(prepared).toMatchObject({ ok: true, review: { policy: {
+ policies: [{ id: 'current-review-owner' }], reviewedPr: { tip: c.release.head, prUrl: c.forge.prUrl },
+ } } });
+ expect(prepared.review.policy.priorCheckouts).toHaveLength(33);
+ expect(prepared.review.comparison.localPatch).toContain('original feature');
+ const result = await c.confirm(prepared.review);
+ expect(result).toMatchObject({ ok: true, branchDeleted: true, archiveDir: expect.any(String) });
+ expect(existsSync(c.path)).toBe(false);
+ expect(await registered(c.release.path)).toBe(false);
+ expect((await execGit(['show-ref', '--verify', '--quiet', `refs/heads/${c.release.branch}`], repo, { ignoreExitCode: true })).exitCode).not.toBe(0);
+ expect((await getBranchReconcileOutcome('app-1')).retired).toEqual(expect.arrayContaining([
+ expect.objectContaining({ path: c.release.path, branch: c.release.branch, head: c.release.head,
+ archiveDir: result.archiveDir, branchDeleted: true }),
+ ]));
+ expect(injected.policies).toEqual(policiesBefore);
+ const manifest = JSON.parse(await readFile(join(result.archiveDir, 'manifest.json'), 'utf8'));
+ expect(manifest.captured.gitlinks).toMatchObject([{ path: 'vendor', state: 'empty' }]);
+ if (SYMLINKS) {
+ expect(manifest.captured.symlinks.filter(link => link.path.endsWith('node_modules'))).toHaveLength(4);
+ expect(manifest.captured.files.some(file => file.path.includes('node_modules/'))).toBe(false);
+ }
+ expect(await readFile(join(shared, 'untouched'), 'utf8')).toBe('shared installation\n');
+ expect(await readFile(join(result.archiveDir, 'administration/gitdir/index'))).toEqual(index);
+ expect(await readFile(join(result.archiveDir, 'administration/gitdir/logs/HEAD'))).toEqual(reflog);
+ expect(await readFile(join(result.archiveDir, 'administration/gitdir/portos-review-status'), 'utf8')).toBe('private synthetic review marker');
+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');
+ expect(await readFile(join(result.archiveDir, 'files/untracked.txt'), 'utf8')).toBe('untracked work\n');
+ await rename(repo, `${repo}-unavailable`);
+ const restored = join(scratch, 'standalone');
+ await execGit(['init', restored], scratch);
+ await execGit(['fetch', join(result.archiveDir, 'commits.bundle'), '+refs/portos/archive/*:refs/recovered/*'], restored);
+ await execGit(['checkout', '--detach', c.release.head], restored);
+ await execGit(['apply', '--index', join(result.archiveDir, 'index.diff')], restored);
+ await execGit(['apply', join(result.archiveDir, 'worktree.diff')], restored);
+ await cp(join(result.archiveDir, 'files'), restored, { recursive: true });
+ for (const link of manifest.captured.symlinks) {
+ await mkdir(dirname(join(restored, link.path)), { recursive: true });
+ await symlink(link.target, join(restored, link.path));
+ }
+ expect((await execGit(['rev-parse', 'HEAD'], restored)).stdout.trim()).toBe(c.release.head);
+ expect(await readdir(join(restored, 'vendor'))).toEqual([]);
+ expect((await execGit(['show', ':staged.txt'], restored)).stdout).toBe('unique staged content\n');
+ expect(await readFile(join(restored, 'initial.txt'), 'utf8')).toBe('tracked edit\n');
+ expect(await readFile(join(restored, 'untracked.txt'), 'utf8')).toBe('untracked work\n');
+ expect(await readFile(join(restored, 'ignored.txt'), 'utf8')).toBe('ignored work\n');
+ if (SYMLINKS) expect(await readFile(join(restored, 'server/node_modules/untouched'), 'utf8')).toBe('shared installation\n');
+ await execGit(['fsck', '--full', '--strict'], restored);
+ });
+
+ it.each(['head-mismatch', 'same-checkout-failed', 'ambiguous-history', 'current-manual', 'current-active', 'checkout-alias', 'primary-alias'])(
+ 'keeps the full original checkout when reused-branch proof changes: %s', async change => {
+ const c = await reviewedCheckout('quality-held');
+ const current = reusedBranchOwners(c);
+ const prepared = await c.prepare();
+ expect(prepared.ok).toBe(true);
+ if (change === 'head-mismatch') c.forge.prHead = c.forge.changeBase;
+ if (change === 'same-checkout-failed') injected.policies[1].metadata.workspacePath = c.release.path;
+ if (change === 'ambiguous-history') delete injected.policies[1].metadata.workspacePath;
+ if (change === 'current-manual') current.metadata.prCompletionPolicy = 'leave-open';
+ if (change === 'current-active') current.status = 'running';
+ if (change === 'checkout-alias' || change === 'primary-alias') {
+ const alias = join(external, 'historical-alias');
+ await symlink(change === 'checkout-alias' ? c.path : repo, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ injected.policies[1].metadata.workspacePath = alias;
+ }
+ expect(await c.confirm(prepared.review)).toMatchObject({ ok: false });
+ expect(await lockText(c.release.path)).toBe(c.release.lockReason);
+ expect((await execGit(['rev-parse', `refs/heads/${c.release.branch}`], repo)).stdout.trim()).toBe(c.release.head);
+ expect(await readFile(join(c.path, 'ignored.txt'), 'utf8')).toBe('ignored work\n');
+ expect(await archives()).toEqual([]);
+ });
+
it.each(['content', 'index', 'administration', 'default', 'pr-head', 'forge', 'policy', 'unreadable-policy', 'submodule', 'inventory'])('refuses changed %s evidence between review and confirmation', async change => {
const c = await reviewedCheckout('changed-review', { gitlink: true });
const prepared = await c.prepare();
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 74147cde80..100123a359 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -578,7 +578,8 @@ export async function readWorktreeStatus(worktreePath) {
if (present === null) return null;
const top = await execGit(['rev-parse', '--show-toplevel'], worktreePath).then(r => r.stdout.trim()).catch(() => null);
if (!top || !pathsEqual(top, worktreePath)) return null;
- const status = await execGit(['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], worktreePath, { ignoreExitCode: true }).catch(() => null);
+ const status = await execGit(['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], worktreePath,
+ { ignoreExitCode: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } }).catch(() => null);
return status?.exitCode === 0 ? status.stdout : null;
}
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
index 89380c65bd..fbce24e7fa 100644
--- a/server/services/worktreeReap.test.js
+++ b/server/services/worktreeReap.test.js
@@ -11,8 +11,9 @@
* is excluded from `npm run test:fast` (`VITEST_FAST=1`).
*/
import { describe, it, expect, beforeAll, beforeEach, afterEach, afterAll, vi } from 'vitest';
-import { mkdtemp, rm, writeFile, readFile, readdir, mkdir, chmod } from 'fs/promises';
+import { mkdtemp, rm, writeFile, readFile, readdir, mkdir, chmod, lstat, readlink, utimes, rename } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
+import { createHash } from 'crypto';
import { tmpdir } from 'os';
import { join } from 'path';
import { execGit } from '../lib/execGit.js';
@@ -27,8 +28,8 @@ vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOr
afterAll(cleanupTempDataRoots);
import { PATHS } from '../lib/paths.js';
import { preserveBranchRetirement } from '../lib/branchRetirementArchive.js';
-import { hasBranchMergeEvidence } from './git.js';
-import { reapMergedWorktrees, deleteCompletedLocalBranch } from './worktreeManager.js';
+import { hasBranchMergeEvidence, getStatus, getStatusPorcelain } from './git.js';
+import { reapMergedWorktrees, deleteCompletedLocalBranch, readWorktreeStatus } from './worktreeManager.js';
vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: async () => null }));
vi.mock('./cosState.js', () => ({ readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: {} }) }));
@@ -48,6 +49,22 @@ async function commitFile(dir, name, content, message) {
await execGit(['commit', '-m', message], dir);
}
+// Reading metadata excludes atime, which a filesystem may update on reads.
+async function snapshotTree(root) {
+ const rows = [];
+ const walk = async (path, relative) => {
+ const info = await lstat(path, { bigint: true });
+ rows.push({ path: relative, mode: info.mode, ino: info.ino, mtime: info.mtimeNs, ctime: info.ctimeNs,
+ content: info.isFile() ? createHash('sha256').update(await readFile(path)).digest('hex')
+ : info.isSymbolicLink() ? await readlink(path) : null });
+ if (info.isDirectory()) {
+ for (const child of (await readdir(path)).sort()) await walk(join(path, child), `${relative}/${child}`);
+ }
+ };
+ await walk(root, '');
+ return rows;
+}
+
/**
* @returns {Promise<{dir: string, safePath: string}>} `dir` is the repo root
* spelled the way git itself reports it — needed for the reaper's own
@@ -236,7 +253,31 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('hasBranchMergeEvidence', () => {
const ancestor = await execGit(['merge-base', '--is-ancestor', 'squashed', 'main'], dir, { ignoreExitCode: true });
expect(ancestor.exitCode).not.toBe(0);
- expect(await hasBranchMergeEvidence(dir, 'squashed', 'main')).toBe(true);
+ const before = await snapshotTree(dir);
+ const ownedScratch = await mkdtemp(join(tmpdir(), 'portos-probe-observe-'));
+ const useTemp = path => {
+ for (const key of ['TMPDIR', 'TEMP', 'TMP']) vi.stubEnv(key, path);
+ };
+ try {
+ useTemp(ownedScratch);
+ expect(await Promise.all(Array.from({ length: 3 }, () => hasBranchMergeEvidence(dir, 'squashed', 'main'))))
+ .toEqual([true, true, true]);
+ expect(await snapshotTree(dir)).toEqual(before);
+ expect((await readdir(ownedScratch)).filter(name => name.startsWith('portos-merge-probe-'))).toEqual([]);
+
+ // Allocation and post-allocation Git failures must not establish evidence,
+ // leak scratch, or fall back to writing synthetic objects in the real repo.
+ useTemp(join(dir, 'missing-temp-root'));
+ expect(await hasBranchMergeEvidence(dir, 'squashed', 'main')).toBe(false);
+ useTemp(ownedScratch);
+ vi.stubEnv('GIT_AUTHOR_NAME', '');
+ expect(await hasBranchMergeEvidence(dir, 'squashed', 'main')).toBe(false);
+ expect(await snapshotTree(dir)).toEqual(before);
+ expect((await readdir(ownedScratch)).filter(name => name.startsWith('portos-merge-probe-'))).toEqual([]);
+ } finally {
+ vi.unstubAllEnvs();
+ await rm(ownedScratch, { recursive: true, force: true });
+ }
});
it('detects a multi-commit rebase merge after the target branch advanced', async () => {
@@ -273,6 +314,77 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('hasBranchMergeEvidence', () => {
});
});
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('read-only inspection of initialized linked checkouts', () => {
+ let root;
+ afterEach(async () => {
+ if (root) await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ root = null;
+ });
+
+ it('keeps private indexes and directories unchanged while reporting fresh parent/submodule dirt', async () => {
+ root = await mkdtemp(join(tmpdir(), 'portos-status-readonly-'));
+ const repo = join(root, process.platform === 'win32' ? 'repo space;name' : 'repo space:quoted"name');
+ const moduleRepo = join(root, 'module');
+ const checkout = join(root, 'linked');
+ await materializeGitRepo(repo);
+ await materializeGitRepo(moduleRepo);
+ await execGit(['-c', 'protocol.file.allow=always', 'submodule', 'add', moduleRepo, 'lib/module'], repo);
+ await execGit(['commit', '-am', 'add fixture module'], repo);
+ await execGit(['checkout', '-b', 'squashed'], repo);
+ await commitFile(repo, 'first.txt', 'one\n', 'first');
+ await commitFile(repo, 'second.txt', 'two\n', 'second');
+ await execGit(['checkout', 'main'], repo);
+ await execGit(['merge', '--squash', 'squashed'], repo);
+ await execGit(['commit', '-m', 'combined'], repo);
+ await execGit(['worktree', 'add', '--detach', checkout, 'squashed'], repo);
+ await execGit(['-c', 'protocol.file.allow=always', 'submodule', 'update', '--init'], checkout);
+ const admin = (await execGit(['rev-parse', '--absolute-git-dir'], checkout)).stdout.trim();
+ const moduleAdmin = (await execGit(['rev-parse', '--absolute-git-dir'], join(checkout, 'lib/module'))).stdout.trim();
+ const sharedObjects = join(root, 'shared objects');
+ const alternate = join(root, 'alternate objects');
+ await rename(join(repo, '.git/objects'), sharedObjects);
+ await mkdir(join(repo, '.git/objects/info'), { recursive: true });
+ await mkdir(join(alternate, 'info'), { recursive: true });
+ await writeFile(join(repo, '.git/objects/info/alternates'), `${alternate}\n`);
+ await writeFile(join(alternate, 'info/alternates'), `${sharedObjects}\n`);
+ const files = [join(checkout, 'initial.txt'), join(checkout, 'lib/module/initial.txt')];
+
+ // Reproduce why an apparently read-only status can change preservation
+ // evidence: stale stat caches are refreshed through index.lock by default.
+ for (const file of files) await utimes(file, new Date('2001-01-01'), new Date('2001-01-01'));
+ const indexesBefore = await Promise.all([admin, moduleAdmin].map(path => readFile(join(path, 'index'))));
+ await execGit(['status', '--porcelain', '--ignore-submodules=none'], checkout,
+ { env: { ...process.env, GIT_OPTIONAL_LOCKS: '1' } });
+ const indexesAfter = await Promise.all([admin, moduleAdmin].map(path => readFile(join(path, 'index'))));
+ for (let i = 0; i < indexesBefore.length; i++) expect(indexesAfter[i]).not.toEqual(indexesBefore[i]);
+
+ for (const file of files) await utimes(file, new Date('2002-01-01'), new Date('2002-01-01'));
+ const before = await snapshotTree(root);
+ expect((await getStatus(checkout)).clean).toBe(true);
+ expect(await getStatusPorcelain(checkout)).toBe('');
+ expect(await readWorktreeStatus(checkout)).toBe('');
+ try {
+ vi.stubEnv('GIT_OBJECT_DIRECTORY', join(moduleAdmin, 'objects'));
+ expect(await hasBranchMergeEvidence(checkout, 'squashed', 'main')).toBe(true);
+ } finally { vi.unstubAllEnvs(); }
+ expect(await snapshotTree(root)).toEqual(before);
+
+ await writeFile(files[0], 'changed parent\n');
+ await writeFile(files[1], 'changed module\n');
+ await writeFile(join(checkout, 'untracked.txt'), 'preserve me\n');
+ const dirtyBefore = await snapshotTree(root);
+ const status = await getStatus(checkout);
+ expect(status.clean).toBe(false);
+ expect(status.files.map(file => file.path)).toEqual(expect.arrayContaining(['initial.txt', 'lib/module', 'untracked.txt']));
+ for (const result of [await getStatusPorcelain(checkout), await readWorktreeStatus(checkout)]) {
+ expect(result).toContain(' M initial.txt');
+ expect(result).toContain(' M lib/module');
+ expect(result).toContain('?? untracked.txt');
+ }
+ expect(await snapshotTree(root)).toEqual(dirtyBefore);
+ });
+});
+
describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
let dir;
let safePath;