@indigoai-us/hq-cloud 6.16.27 → 6.16.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cli/conflict-winner.test.d.ts +7 -0
  2. package/dist/cli/conflict-winner.test.d.ts.map +1 -0
  3. package/dist/cli/conflict-winner.test.js +98 -0
  4. package/dist/cli/conflict-winner.test.js.map +1 -0
  5. package/dist/cli/conflict.d.ts +72 -0
  6. package/dist/cli/conflict.d.ts.map +1 -1
  7. package/dist/cli/conflict.js +107 -0
  8. package/dist/cli/conflict.js.map +1 -1
  9. package/dist/cli/doctor.d.ts +12 -0
  10. package/dist/cli/doctor.d.ts.map +1 -1
  11. package/dist/cli/doctor.js +29 -0
  12. package/dist/cli/doctor.js.map +1 -1
  13. package/dist/cli/doctor.test.js +55 -0
  14. package/dist/cli/doctor.test.js.map +1 -1
  15. package/dist/cli/index.d.ts +4 -2
  16. package/dist/cli/index.d.ts.map +1 -1
  17. package/dist/cli/index.js +4 -1
  18. package/dist/cli/index.js.map +1 -1
  19. package/dist/cli/share.d.ts.map +1 -1
  20. package/dist/cli/share.js +364 -101
  21. package/dist/cli/share.js.map +1 -1
  22. package/dist/cli/share.test.js +85 -15
  23. package/dist/cli/share.test.js.map +1 -1
  24. package/dist/cli/sync.d.ts +3 -1
  25. package/dist/cli/sync.d.ts.map +1 -1
  26. package/dist/cli/sync.js +315 -276
  27. package/dist/cli/sync.js.map +1 -1
  28. package/dist/cli/sync.test.js +94 -47
  29. package/dist/cli/sync.test.js.map +1 -1
  30. package/dist/lib/conflict-file.d.ts +50 -18
  31. package/dist/lib/conflict-file.d.ts.map +1 -1
  32. package/dist/lib/conflict-file.js +63 -34
  33. package/dist/lib/conflict-file.js.map +1 -1
  34. package/dist/lib/conflict-index.d.ts.map +1 -1
  35. package/dist/lib/conflict-index.js +6 -0
  36. package/dist/lib/conflict-index.js.map +1 -1
  37. package/dist/lib/conflict-reconcile.d.ts +106 -0
  38. package/dist/lib/conflict-reconcile.d.ts.map +1 -0
  39. package/dist/lib/conflict-reconcile.js +412 -0
  40. package/dist/lib/conflict-reconcile.js.map +1 -0
  41. package/dist/lib/conflict-reconcile.test.d.ts +7 -0
  42. package/dist/lib/conflict-reconcile.test.d.ts.map +1 -0
  43. package/dist/lib/conflict-reconcile.test.js +246 -0
  44. package/dist/lib/conflict-reconcile.test.js.map +1 -0
  45. package/dist/lib/conflict.test.d.ts +3 -2
  46. package/dist/lib/conflict.test.d.ts.map +1 -1
  47. package/dist/lib/conflict.test.js +60 -3
  48. package/dist/lib/conflict.test.js.map +1 -1
  49. package/dist/types.d.ts +23 -5
  50. package/dist/types.d.ts.map +1 -1
  51. package/package.json +1 -1
package/dist/cli/share.js CHANGED
@@ -17,11 +17,11 @@ import { isUnderAnyRoot, readJournal, readJournalScoped, writeJournal, hashFile,
17
17
  import { createIgnoreFilter, hasControlCharacters, isExpectedIgnore, isWithinSizeLimit, } from "../ignore.js";
18
18
  import { wrapFilterWithPersonalVaultDefaults, } from "../personal-vault-exclusions.js";
19
19
  import { isGeneratedCoreMirrorKey, isPersonalVaultDeletionExcluded, purgeExcludedPersonalVaultJournalEntries, } from "../personal-vault.js";
20
- import { resolveConflict } from "./conflict.js";
20
+ import { pickWinner, resolveConflict, usesVersionAwareWinner } from "./conflict.js";
21
21
  import { fetchFileTombstones, } from "./tombstones.js";
22
22
  import { isCoveredByAny, isDirInScope, } from "../prefix-coalesce.js";
23
23
  import { hasRemoteChanged, isAccessDenied, resolveActiveCompany, resolveTransferConcurrency, resolveUploadByteBudget, readHostLoad, } from "../sync-core.js";
24
- import { buildConflictId, buildConflictPath, readShortMachineId, } from "../lib/conflict-file.js";
24
+ import { buildConflictBackupPath, buildConflictId, buildConflictProbePath, readShortMachineId, } from "../lib/conflict-file.js";
25
25
  import { appendConflictEntry } from "../lib/conflict-index.js";
26
26
  import { isCloudAuthoritative } from "../lib/cloud-authoritative.js";
27
27
  import { VaultAuthError, VaultClient, VaultClientError, VaultPermissionDeniedError, } from "../vault-client.js";
@@ -1591,32 +1591,71 @@ async function executeUploads(run, pushPlan, counters, conflictPaths) {
1591
1591
  // processUploadItem (before HEAD), so anything reaching here is a genuine
1592
1592
  // conflict on a client-owned file.
1593
1593
  conflictPaths.push(relativePath);
1594
- const resolution = await resolveConflictSerialized({
1595
- path: relativePath,
1596
- localHash,
1597
- remoteModified: remoteMeta.lastModified,
1598
- direction: "push",
1599
- });
1594
+ // Version-aware winner (strategy unset or `keep`): fetch the remote
1595
+ // body into scratch and compare it with the local one instead of
1596
+ // letting the flag name a side. `overwrite`, `abort` and
1597
+ // `publish-local` keep their explicit meaning via resolveConflict.
1598
+ const versionAware = usesVersionAwareWinner(run.onConflict);
1599
+ let winnerProbe;
1600
+ let resolution;
1601
+ if (versionAware) {
1602
+ winnerProbe = await probeRemoteForWinner(run, item, remoteMeta.lastModified);
1603
+ resolution = "keep";
1604
+ }
1605
+ else {
1606
+ resolution = await resolveConflictSerialized({
1607
+ path: relativePath,
1608
+ localHash,
1609
+ remoteModified: remoteMeta.lastModified,
1610
+ direction: "push",
1611
+ });
1612
+ }
1613
+ const decision = winnerProbe?.decision;
1600
1614
  run.emit({
1601
1615
  type: "conflict",
1602
1616
  path: relativePath,
1603
1617
  direction: "push",
1604
1618
  resolution,
1619
+ ...(decision ? { decision } : {}),
1605
1620
  });
1606
1621
  if (resolution === "abort") {
1622
+ winnerProbe?.discard();
1607
1623
  aborted = true;
1608
1624
  abortFlightConflictPaths = [...conflictPaths];
1609
1625
  return;
1610
1626
  }
1611
1627
  if (resolution === "keep") {
1612
- await writePushConflictMirror(run, item, normalizeEtag(remoteMeta.etag), "local");
1613
- counters.filesSkipped++;
1614
- return;
1628
+ if (decision?.winner === "local") {
1629
+ // The local body is the newer version. Park the cloud body as the
1630
+ // backup (S3 versioning also retains it), record the decision, and
1631
+ // publish local under a fence on the etag just observed — exactly
1632
+ // the `publish-local` write path, so a remote that advances in
1633
+ // the meantime fails closed instead of being clobbered.
1634
+ const detectedAt = new Date().toISOString();
1635
+ const machineId = readShortMachineId(run.hqRoot);
1636
+ recordPushConflict(run, item, {
1637
+ detectedAt,
1638
+ machineId,
1639
+ conflictPath: winnerProbe?.park(detectedAt, machineId),
1640
+ remoteHash: normalizeEtag(remoteMeta.etag),
1641
+ preserved: "remote",
1642
+ decision,
1643
+ });
1644
+ winnerProbe?.discard(); // no-op once parked; drops a failed park
1645
+ fenceOnObservedRemote = true;
1646
+ }
1647
+ else {
1648
+ // The cloud body wins (higher version / newer mtime, or bodies not
1649
+ // comparable — the historical `keep` outcome): adopt it at the
1650
+ // working name; the displaced local body is preserved out of the
1651
+ // tree, never as a sibling twin.
1652
+ await adoptRemoteOnPush(run, item, normalizeEtag(remoteMeta.etag), decision, winnerProbe);
1653
+ counters.filesSkipped++;
1654
+ return;
1655
+ }
1615
1656
  }
1616
1657
  if (resolution === "skip") {
1617
- if (isFreshCollision) {
1618
- await writePushConflictMirror(run, item, normalizeEtag(remoteMeta.etag), "remote");
1619
- }
1658
+ // Leave both sides alone; no sibling mirror is written any more.
1620
1659
  counters.filesSkipped++;
1621
1660
  return;
1622
1661
  }
@@ -1630,8 +1669,13 @@ async function executeUploads(run, pushPlan, counters, conflictPaths) {
1630
1669
  // The `divergentLocalHonesty` recovery keeps the JOURNAL etag: there the
1631
1670
  // recorded etag is exactly the version the operator saw when they chose
1632
1671
  // to keep, and a mismatch is the signal to fail closed.
1672
+ //
1673
+ // A version-aware `keep` whose LOCAL body won set the flag above: it
1674
+ // compared against the body behind the observed etag, so that etag is
1675
+ // the only version its consent covers.
1633
1676
  fenceOnObservedRemote =
1634
- resolution === "publish-local" && !divergentLocalHonesty;
1677
+ fenceOnObservedRemote ||
1678
+ (resolution === "publish-local" && !divergentLocalHonesty);
1635
1679
  // `overwrite` falls through to the conditional PUT and, on 412, retries
1636
1680
  // with no precondition — unconditional by design.
1637
1681
  //
@@ -1748,6 +1792,89 @@ async function executeUploads(run, pushPlan, counters, conflictPaths) {
1748
1792
  throw err;
1749
1793
  if (isPreconditionFailed(err)) {
1750
1794
  conflictPaths.push(relativePath);
1795
+ if (usesVersionAwareWinner(run.onConflict)) {
1796
+ // The remote advanced past the body the fence was built on. Re-decide
1797
+ // once against the remote as it stands NOW: HEAD for the fresh token,
1798
+ // probe the fresh body, compare. Local winning retries the PUT fenced
1799
+ // on that fresh token only (a second 412 is a plain skip — the next
1800
+ // pass starts over); remote winning adopts it exactly as the
1801
+ // pre-flight conflict path would have.
1802
+ const latest = await headRemoteFile(run.ctx, relativePath);
1803
+ const probe = await probeRemoteForWinner(run, item, latest?.lastModified ?? null);
1804
+ const decision = probe.decision;
1805
+ run.emit({
1806
+ type: "conflict",
1807
+ path: relativePath,
1808
+ direction: "push",
1809
+ resolution: "keep",
1810
+ ...(decision ? { decision } : {}),
1811
+ });
1812
+ if (decision?.winner === "local" && latest?.etag) {
1813
+ const detectedAt = new Date().toISOString();
1814
+ const machineId = readShortMachineId(run.hqRoot);
1815
+ recordPushConflict(run, item, {
1816
+ detectedAt,
1817
+ machineId,
1818
+ conflictPath: probe.park(detectedAt, machineId),
1819
+ remoteHash: normalizeEtag(latest.etag),
1820
+ preserved: "remote",
1821
+ decision,
1822
+ });
1823
+ probe.discard(); // no-op once parked; drops a failed park
1824
+ try {
1825
+ await performUpload({ ifMatch: normalizeEtag(latest.etag) });
1826
+ }
1827
+ catch (retryErr) {
1828
+ if (retryErr instanceof VaultAuthError ||
1829
+ isTerminalIdentityRefusal(retryErr) ||
1830
+ isRetryableIdentityRefusal(retryErr)) {
1831
+ throw retryErr;
1832
+ }
1833
+ if (retryErr instanceof JournalCheckpointError)
1834
+ throw retryErr;
1835
+ if (isPreconditionFailed(retryErr)) {
1836
+ counters.filesSkipped++;
1837
+ return;
1838
+ }
1839
+ hadUploadFailure = true;
1840
+ run.emit({
1841
+ type: "error",
1842
+ path: relativePath,
1843
+ message: describeError(retryErr),
1844
+ });
1845
+ }
1846
+ return;
1847
+ }
1848
+ if (decision?.winner === "local") {
1849
+ // Local won but HEAD returned no fresh etag to fence the retry
1850
+ // on (object vanished or an etag-less HEAD). Falling through to
1851
+ // adopt-remote would discard the WINNING local body, so hold:
1852
+ // keep local as-is, park the probed cloud body as the backup,
1853
+ // record the hold, and let the next pass start over.
1854
+ const detectedAt = new Date().toISOString();
1855
+ const machineId = readShortMachineId(run.hqRoot);
1856
+ recordPushConflict(run, item, {
1857
+ detectedAt,
1858
+ machineId,
1859
+ conflictPath: probe.park(detectedAt, machineId),
1860
+ remoteHash: remoteMeta ? normalizeEtag(remoteMeta.etag) : "",
1861
+ preserved: "remote",
1862
+ decision,
1863
+ });
1864
+ probe.discard(); // no-op once parked; drops a failed park
1865
+ // Deliberately NOT `type: "error"` (a hold is a benign per-file
1866
+ // skip; the conflict event + index row above already record it).
1867
+ counters.filesSkipped++;
1868
+ return;
1869
+ }
1870
+ await adoptRemoteOnPush(run, item, latest?.etag
1871
+ ? normalizeEtag(latest.etag)
1872
+ : remoteMeta
1873
+ ? normalizeEtag(remoteMeta.etag)
1874
+ : "", decision, probe);
1875
+ counters.filesSkipped++;
1876
+ return;
1877
+ }
1751
1878
  const resolution = await resolveConflictSerialized({
1752
1879
  path: relativePath,
1753
1880
  localHash,
@@ -1767,8 +1894,10 @@ async function executeUploads(run, pushPlan, counters, conflictPaths) {
1767
1894
  // A 412 here means the remote advanced between the plan and the PUT.
1768
1895
  // `publish-local` consented to replacing ONE specific version; that
1769
1896
  // version is gone, so the consent no longer covers what is there now.
1770
- // Fail closed — mirror the remote and skip — rather than inheriting
1771
- // `overwrite`'s unfenced retry, which would clobber the peer's write.
1897
+ // Fail closed — skip — rather than inheriting `overwrite`'s unfenced
1898
+ // retry, which would clobber the peer's write. No sibling mirror is
1899
+ // written: the peer's body is in the vault (S3 versioning) and the
1900
+ // next pass re-probes it.
1772
1901
  //
1773
1902
  // Keyed off the FRESH resolution above, not the earlier one: an
1774
1903
  // interactive operator re-prompted at this point may legitimately
@@ -1776,7 +1905,6 @@ async function executeUploads(run, pushPlan, counters, conflictPaths) {
1776
1905
  // as it stands now. Only a repeated `publish-local` — which is what the
1777
1906
  // non-interactive strategy returns — stays fenced.
1778
1907
  if (resolution === "publish-local") {
1779
- await writePushConflictMirror(run, item, remoteMeta ? normalizeEtag(remoteMeta.etag) : "", "remote");
1780
1908
  counters.filesSkipped++;
1781
1909
  return;
1782
1910
  }
@@ -1799,7 +1927,12 @@ async function executeUploads(run, pushPlan, counters, conflictPaths) {
1799
1927
  }
1800
1928
  return;
1801
1929
  }
1802
- await writePushConflictMirror(run, item, remoteMeta ? normalizeEtag(remoteMeta.etag) : "", resolution === "keep" ? "local" : "remote");
1930
+ if (resolution === "keep") {
1931
+ // An interactive `keep` after a 412 still means "take the cloud
1932
+ // body": adopt it now (the local body is preserved out of tree).
1933
+ await adoptRemoteOnPush(run, item, remoteMeta ? normalizeEtag(remoteMeta.etag) : "", undefined);
1934
+ }
1935
+ // `skip` and `diff`: leave both sides for the next pass.
1803
1936
  counters.filesSkipped++;
1804
1937
  return;
1805
1938
  }
@@ -1908,101 +2041,232 @@ function isArchivedSessionLog(relativePath, remoteMeta) {
1908
2041
  return (relativePath.startsWith("workspace/.session-logs/") &&
1909
2042
  remoteMeta?.storageClass === "DEEP_ARCHIVE");
1910
2043
  }
1911
- async function writePushConflictMirror(run, item, remoteHash, preserved) {
2044
+ /**
2045
+ * Fetch the remote body into a scratch path under `.hq/tmp/` and run the
2046
+ * version-aware winner against the local body. The probe is NEVER left beside
2047
+ * the live file: the caller either parks it as the losing side's backup under
2048
+ * `.hq/conflict-backups/` (`park`) or discards it (`discard`) — and must call
2049
+ * one of the two.
2050
+ *
2051
+ * Returns `decision: undefined` when the bodies are not comparable (symlink on
2052
+ * either side, probe failure); the caller then falls back to the historical
2053
+ * `keep` outcome (adopt the remote). Session-level auth refusals propagate.
2054
+ */
2055
+ async function probeRemoteForWinner(run, item, remoteMtime) {
2056
+ const probeAbs = buildConflictProbePath(run.hqRoot);
2057
+ let parked = false;
2058
+ let fetched;
2059
+ const discard = () => {
2060
+ if (parked)
2061
+ return;
2062
+ try {
2063
+ fs.rmSync(probeAbs, { force: true });
2064
+ }
2065
+ catch {
2066
+ /* best-effort cleanup; a stray scratch file under .hq/tmp is harmless */
2067
+ }
2068
+ };
2069
+ const park = (detectedAt, machineId) => {
2070
+ const originalRelative = vaultKeyForLocalPath(run.hqRoot, item.absolutePath);
2071
+ const backupKey = buildConflictBackupPath(originalRelative, detectedAt, machineId);
2072
+ const backupAbs = localPathForVaultKey(run.hqRoot, backupKey);
2073
+ try {
2074
+ fs.mkdirSync(path.dirname(backupAbs), { recursive: true });
2075
+ fs.renameSync(probeAbs, backupAbs);
2076
+ parked = true;
2077
+ return backupKey;
2078
+ }
2079
+ catch (parkErr) {
2080
+ run.emit({
2081
+ type: "error",
2082
+ path: item.relativePath,
2083
+ message: `conflict backup of the cloud body failed: ${describeError(parkErr)}`,
2084
+ });
2085
+ return undefined;
2086
+ }
2087
+ };
2088
+ let decision;
2089
+ try {
2090
+ fs.mkdirSync(path.dirname(probeAbs), { recursive: true });
2091
+ const downloaded = await downloadFile(run.ctx, item.relativePath, probeAbs);
2092
+ fetched = { abs: probeAbs, downloaded };
2093
+ if (item.kind === "file" && !fs.lstatSync(probeAbs).isSymbolicLink()) {
2094
+ const localStat = fs.lstatSync(item.absolutePath);
2095
+ decision = pickWinner({
2096
+ localBytes: fs.readFileSync(item.absolutePath),
2097
+ remoteBytes: fs.readFileSync(probeAbs),
2098
+ localMtime: localStat.mtime,
2099
+ remoteMtime,
2100
+ });
2101
+ }
2102
+ }
2103
+ catch (probeErr) {
2104
+ if (probeErr instanceof VaultAuthError ||
2105
+ isTerminalIdentityRefusal(probeErr) ||
2106
+ isRetryableIdentityRefusal(probeErr)) {
2107
+ discard();
2108
+ throw probeErr;
2109
+ }
2110
+ // The Windows materialization refusals are deliberate skips, not errors;
2111
+ // the adopt path re-fetches and emits the typed skip event for them.
2112
+ if (!(probeErr instanceof WindowsSymlinkPrivilegeError) &&
2113
+ !(probeErr instanceof WindowsRenameBlockedError)) {
2114
+ run.emit({
2115
+ type: "error",
2116
+ path: item.relativePath,
2117
+ message: `conflict winner probe failed: ${describeError(probeErr)}`,
2118
+ });
2119
+ }
2120
+ }
2121
+ return {
2122
+ decision,
2123
+ park,
2124
+ discard,
2125
+ takeBody: () => {
2126
+ if (!fetched || parked)
2127
+ return undefined;
2128
+ const body = fetched;
2129
+ fetched = undefined;
2130
+ parked = true; // the caller now owns the scratch file
2131
+ return body;
2132
+ },
2133
+ };
2134
+ }
2135
+ /**
2136
+ * Record a push-side conflict decision in `.hq-conflicts/index.json`. Errors
2137
+ * are surfaced on the event channel, never thrown — the index is an audit
2138
+ * trail, not the transfer.
2139
+ */
2140
+ function recordPushConflict(run, item, fields) {
2141
+ const originalRelative = vaultKeyForLocalPath(run.hqRoot, item.absolutePath);
2142
+ try {
2143
+ appendConflictEntry(run.hqRoot, {
2144
+ id: buildConflictId(originalRelative, fields.detectedAt),
2145
+ originalPath: originalRelative,
2146
+ ...(fields.conflictPath ? { conflictPath: fields.conflictPath } : {}),
2147
+ detectedAt: fields.detectedAt,
2148
+ side: "push",
2149
+ machineId: fields.machineId,
2150
+ localHash: item.localHash,
2151
+ remoteHash: fields.remoteHash,
2152
+ preserved: fields.preserved,
2153
+ ...(fields.decision ? { decision: fields.decision } : {}),
2154
+ });
2155
+ }
2156
+ catch (indexErr) {
2157
+ run.emit({
2158
+ type: "error",
2159
+ path: item.relativePath,
2160
+ message: "conflict index write failed: " + describeError(indexErr),
2161
+ });
2162
+ }
2163
+ }
2164
+ /**
2165
+ * The cloud body wins a push-side conflict: adopt it at the working name and
2166
+ * preserve the displaced local body OUT of the tree under
2167
+ * `.hq/conflict-backups/` (never as a sibling twin). Rename first, then reuse
2168
+ * the ordinary tested download path for the replacement instead of
2169
+ * hand-rolling a swap around an ad-hoc GET. A transient Windows sharing
2170
+ * violation on the move-aside surfaces as WindowsRenameBlockedError so the
2171
+ * catch below downgrades it to a deliberate skip; nothing has moved yet, so
2172
+ * the skip strands nothing (Sentry HQ-DESKTOP-54).
2173
+ */
2174
+ async function adoptRemoteOnPush(run, item, remoteHash, decision, probe) {
1912
2175
  let localMovedAside = false;
1913
2176
  let remoteAdopted = false;
1914
- let conflictAbs;
2177
+ let backupAbs;
1915
2178
  let effectiveRemoteHash = remoteHash;
2179
+ // Reuse the body the winner probe already fetched (one GET, not two); fall
2180
+ // back to the ordinary download path when the probe fetched nothing.
2181
+ const probeBody = probe?.takeBody();
1916
2182
  try {
1917
2183
  const detectedAt = new Date().toISOString();
1918
2184
  const machineId = readShortMachineId(run.hqRoot);
1919
2185
  const originalRelative = vaultKeyForLocalPath(run.hqRoot, item.absolutePath);
1920
- const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
1921
- conflictAbs = localPathForVaultKey(run.hqRoot, conflictRelative);
1922
- if (!isMaterializationPathStillContained(run.syncRoot, conflictAbs)) {
2186
+ const backupKey = buildConflictBackupPath(originalRelative, detectedAt, machineId);
2187
+ backupAbs = localPathForVaultKey(run.hqRoot, backupKey);
2188
+ if (!isMaterializationPathStillContained(run.syncRoot, item.absolutePath)) {
1923
2189
  run.emit({
1924
2190
  type: "error",
1925
2191
  path: item.relativePath,
1926
- message: "conflict mirror skipped: local parent escaped the sync root",
2192
+ message: "conflict adopt skipped: local parent escaped the sync root",
1927
2193
  });
2194
+ return;
2195
+ }
2196
+ // A keep reached after a 412 may have been planned against no object or
2197
+ // an older one. Refresh the version token before journalling the body we
2198
+ // are about to adopt; retain the observed token if HEAD is unavailable.
2199
+ const latestRemote = await headRemoteFile(run.ctx, item.relativePath);
2200
+ if (latestRemote?.etag) {
2201
+ effectiveRemoteHash = normalizeEtag(latestRemote.etag);
2202
+ }
2203
+ fs.mkdirSync(path.dirname(backupAbs), { recursive: true });
2204
+ renameOrRaiseWindowsBlocked(item.absolutePath, backupAbs);
2205
+ localMovedAside = true;
2206
+ let downloaded;
2207
+ if (probeBody) {
2208
+ fs.renameSync(probeBody.abs, item.absolutePath);
2209
+ downloaded = probeBody.downloaded;
1928
2210
  }
1929
2211
  else {
1930
- if (preserved === "local") {
1931
- // A keep reached after a 412 may have been planned against no object or
1932
- // an older one. Refresh the version token before journalling the body we
1933
- // are about to adopt; retain the observed token if HEAD is unavailable.
1934
- const latestRemote = await headRemoteFile(run.ctx, item.relativePath);
1935
- if (latestRemote?.etag) {
1936
- effectiveRemoteHash = normalizeEtag(latestRemote.etag);
1937
- }
1938
- // `keep` has one meaning in both directions: cloud wins the working
1939
- // name while the displaced local body remains recoverable beside it.
1940
- // Rename first, then reuse the ordinary tested download path for the
1941
- // replacement instead of hand-rolling a swap around an ad-hoc GET. A
1942
- // transient Windows sharing violation on the move-aside surfaces as
1943
- // WindowsRenameBlockedError so the catch below downgrades it to a
1944
- // deliberate skip; nothing has moved yet, so the skip strands nothing
1945
- // (Sentry HQ-DESKTOP-54).
1946
- renameOrRaiseWindowsBlocked(item.absolutePath, conflictAbs);
1947
- localMovedAside = true;
1948
- const downloaded = await downloadFile(run.ctx, item.relativePath, item.absolutePath);
1949
- remoteAdopted = true;
1950
- const localLstat = fs.lstatSync(item.absolutePath);
1951
- const isLocalSymlink = localLstat.isSymbolicLink();
1952
- const remoteBodyHash = isLocalSymlink
1953
- ? hashSymlinkTarget(fs.readlinkSync(item.absolutePath))
1954
- : (downloaded?.contentHash ?? hashFile(item.absolutePath));
1955
- const remoteBodySize = isLocalSymlink
1956
- ? 0
1957
- : (downloaded?.contentSize ?? localLstat.size);
1958
- const createdBySub = downloaded?.metadata?.["created-by-sub"];
1959
- updateEntry(run.journal, item.relativePath, remoteBodyHash, remoteBodySize, "down", item.absolutePath, {
1960
- remoteEtag: effectiveRemoteHash,
1961
- mtimeMs: localLstat.mtimeMs,
1962
- ctimeMs: localLstat.ctimeMs,
1963
- ...(createdBySub !== undefined ? { createdBySub } : {}),
1964
- kind: isLocalSymlink ? "symlink" : "file",
1965
- });
2212
+ downloaded = await downloadFile(run.ctx, item.relativePath, item.absolutePath);
2213
+ }
2214
+ remoteAdopted = true;
2215
+ const localLstat = fs.lstatSync(item.absolutePath);
2216
+ const isLocalSymlink = localLstat.isSymbolicLink();
2217
+ const remoteBodyHash = isLocalSymlink
2218
+ ? hashSymlinkTarget(fs.readlinkSync(item.absolutePath))
2219
+ : (downloaded?.contentHash ?? hashFile(item.absolutePath));
2220
+ const remoteBodySize = isLocalSymlink
2221
+ ? 0
2222
+ : (downloaded?.contentSize ?? localLstat.size);
2223
+ const createdBySub = downloaded?.metadata?.["created-by-sub"];
2224
+ updateEntry(run.journal, item.relativePath, remoteBodyHash, remoteBodySize, "down", item.absolutePath, {
2225
+ remoteEtag: effectiveRemoteHash,
2226
+ mtimeMs: localLstat.mtimeMs,
2227
+ ctimeMs: localLstat.ctimeMs,
2228
+ ...(createdBySub !== undefined ? { createdBySub } : {}),
2229
+ kind: isLocalSymlink ? "symlink" : "file",
2230
+ });
2231
+ recordPushConflict(run, item, {
2232
+ detectedAt,
2233
+ machineId,
2234
+ conflictPath: backupKey,
2235
+ remoteHash: effectiveRemoteHash,
2236
+ preserved: "local",
2237
+ decision,
2238
+ });
2239
+ // Persist the converged remote-backed entry immediately. A conflict
2240
+ // resolution is a completed transfer even though the push counter is
2241
+ // recorded as skipped, and an interrupted pass must not revive it.
2242
+ checkpointShareJournal(run);
2243
+ }
2244
+ catch (adoptErr) {
2245
+ // A probe body that never reached the working name is scratch litter.
2246
+ if (probeBody && !remoteAdopted) {
2247
+ try {
2248
+ fs.rmSync(probeBody.abs, { force: true });
1966
2249
  }
1967
- else {
1968
- await downloadFile(run.ctx, item.relativePath, conflictAbs);
1969
- }
1970
- appendConflictEntry(run.hqRoot, {
1971
- id: buildConflictId(originalRelative, detectedAt),
1972
- originalPath: originalRelative,
1973
- conflictPath: conflictRelative,
1974
- detectedAt,
1975
- side: "push",
1976
- machineId,
1977
- localHash: item.localHash,
1978
- remoteHash: effectiveRemoteHash,
1979
- preserved,
1980
- });
1981
- if (preserved === "local") {
1982
- // Persist the converged remote-backed entry immediately. A conflict
1983
- // resolution is a completed transfer even though the push counter is
1984
- // recorded as skipped, and an interrupted pass must not revive it.
1985
- checkpointShareJournal(run);
2250
+ catch {
2251
+ /* best-effort cleanup */
1986
2252
  }
1987
2253
  }
1988
- }
1989
- catch (mirrorErr) {
1990
2254
  // If adopting the remote failed before it became the working copy, put the
1991
2255
  // local body back. The remote remains authoritative in cloud, so replacing
1992
2256
  // any partial local materialization is safe and leaves this pass no worse
1993
2257
  // than the pre-conflict state.
1994
- if (localMovedAside && !remoteAdopted && conflictAbs) {
2258
+ if (localMovedAside && !remoteAdopted && backupAbs) {
1995
2259
  try {
1996
2260
  fs.rmSync(item.absolutePath, { force: true });
1997
- fs.renameSync(conflictAbs, item.absolutePath);
2261
+ fs.renameSync(backupAbs, item.absolutePath);
1998
2262
  localMovedAside = false;
1999
2263
  }
2000
2264
  catch (rollbackErr) {
2001
2265
  // A rollback failure is NOT a benign skip even when the underlying
2002
2266
  // rename refusal is transient: the local body has already been moved to
2003
- // `conflictAbs` and could not be restored, so the original working path
2004
- // is now absent. Reporting success here would let a later pass read that
2005
- // absence as a deletion. Keep it on the error channel (Codex PR #436).
2267
+ // the backup path and could not be restored, so the original working
2268
+ // path is now absent. Reporting success here would let a later pass
2269
+ // read that absence as a deletion. Keep it on the error channel.
2006
2270
  run.emit({
2007
2271
  type: "error",
2008
2272
  path: item.relativePath,
@@ -2010,14 +2274,14 @@ async function writePushConflictMirror(run, item, remoteHash, preserved) {
2010
2274
  });
2011
2275
  }
2012
2276
  }
2013
- if (mirrorErr instanceof VaultAuthError ||
2014
- isTerminalIdentityRefusal(mirrorErr) ||
2015
- isRetryableIdentityRefusal(mirrorErr)) {
2016
- throw mirrorErr;
2277
+ if (adoptErr instanceof VaultAuthError ||
2278
+ isTerminalIdentityRefusal(adoptErr) ||
2279
+ isRetryableIdentityRefusal(adoptErr)) {
2280
+ throw adoptErr;
2017
2281
  }
2018
- if (mirrorErr instanceof JournalCheckpointError)
2019
- throw mirrorErr;
2020
- if (mirrorErr instanceof WindowsRenameBlockedError) {
2282
+ if (adoptErr instanceof JournalCheckpointError)
2283
+ throw adoptErr;
2284
+ if (adoptErr instanceof WindowsRenameBlockedError) {
2021
2285
  // The local move-aside could not complete because a program is holding
2022
2286
  // the file open. Emit the deliberate skip (never type:"error") so the
2023
2287
  // push stays complete and the one-shot runner exits 0; nothing was moved
@@ -2029,15 +2293,14 @@ async function writePushConflictMirror(run, item, remoteHash, preserved) {
2029
2293
  remedy: WINDOWS_RENAME_BLOCKED_REMEDY,
2030
2294
  });
2031
2295
  }
2032
- else if (mirrorErr instanceof WindowsSymlinkPrivilegeError) {
2033
- // The remote symlink record cannot be materialized to a conflict mirror
2034
- // on this unprivileged Windows host. Emit the deliberate skip (never
2035
- // type:"error") so the push stays complete and the runner exits 0
2036
- // (Sentry HQ-DESKTOP-54); the conflict itself was already recorded above.
2296
+ else if (adoptErr instanceof WindowsSymlinkPrivilegeError) {
2297
+ // The remote symlink record cannot be materialized on this unprivileged
2298
+ // Windows host. Emit the deliberate skip (never type:"error") so the
2299
+ // push stays complete and the runner exits 0 (Sentry HQ-DESKTOP-54).
2037
2300
  run.emit({
2038
2301
  type: "skip-symlink-privilege",
2039
2302
  path: item.relativePath,
2040
- target: mirrorErr.target,
2303
+ target: adoptErr.target,
2041
2304
  remedy: WINDOWS_SYMLINK_PRIVILEGE_REMEDY,
2042
2305
  });
2043
2306
  }
@@ -2045,7 +2308,7 @@ async function writePushConflictMirror(run, item, remoteHash, preserved) {
2045
2308
  run.emit({
2046
2309
  type: "error",
2047
2310
  path: item.relativePath,
2048
- message: "conflict mirror write failed: " + describeError(mirrorErr),
2311
+ message: "conflict adopt failed: " + describeError(adoptErr),
2049
2312
  });
2050
2313
  }
2051
2314
  }