@indigoai-us/hq-cloud 6.16.27 → 6.16.29

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 (62) 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 +109 -47
  29. package/dist/cli/sync.test.js.map +1 -1
  30. package/dist/journal-store.test.js +59 -0
  31. package/dist/journal-store.test.js.map +1 -1
  32. package/dist/journal.d.ts +8 -0
  33. package/dist/journal.d.ts.map +1 -1
  34. package/dist/journal.js +19 -5
  35. package/dist/journal.js.map +1 -1
  36. package/dist/lib/conflict-file.d.ts +50 -18
  37. package/dist/lib/conflict-file.d.ts.map +1 -1
  38. package/dist/lib/conflict-file.js +63 -34
  39. package/dist/lib/conflict-file.js.map +1 -1
  40. package/dist/lib/conflict-index.d.ts.map +1 -1
  41. package/dist/lib/conflict-index.js +6 -0
  42. package/dist/lib/conflict-index.js.map +1 -1
  43. package/dist/lib/conflict-reconcile.d.ts +106 -0
  44. package/dist/lib/conflict-reconcile.d.ts.map +1 -0
  45. package/dist/lib/conflict-reconcile.js +412 -0
  46. package/dist/lib/conflict-reconcile.js.map +1 -0
  47. package/dist/lib/conflict-reconcile.test.d.ts +7 -0
  48. package/dist/lib/conflict-reconcile.test.d.ts.map +1 -0
  49. package/dist/lib/conflict-reconcile.test.js +246 -0
  50. package/dist/lib/conflict-reconcile.test.js.map +1 -0
  51. package/dist/lib/conflict.test.d.ts +3 -2
  52. package/dist/lib/conflict.test.d.ts.map +1 -1
  53. package/dist/lib/conflict.test.js +60 -3
  54. package/dist/lib/conflict.test.js.map +1 -1
  55. package/dist/sync/area-ledger.d.ts.map +1 -1
  56. package/dist/sync/area-ledger.js +50 -7
  57. package/dist/sync/area-ledger.js.map +1 -1
  58. package/dist/sync/area-ledger.test.js +90 -0
  59. package/dist/sync/area-ledger.test.js.map +1 -1
  60. package/dist/types.d.ts +23 -5
  61. package/dist/types.d.ts.map +1 -1
  62. package/package.json +1 -1
package/dist/cli/sync.js CHANGED
@@ -27,8 +27,8 @@ import { listRemoteForScope, POST_FILTER_THRESHOLD } from "../remote-pull.js";
27
27
  import { createIgnoreFilter } from "../ignore.js";
28
28
  import { hasRemoteChanged, isAccessDenied, resolveActiveCompany, resolveTransferConcurrency, readHostLoad, } from "../sync-core.js";
29
29
  import { isEphemeralPath, isMalformedVaultKey } from "./share.js";
30
- import { resolveConflict } from "./conflict.js";
31
- import { buildConflictId, buildConflictPath, readShortMachineId, } from "../lib/conflict-file.js";
30
+ import { pickWinner, resolveConflict, usesVersionAwareWinner } from "./conflict.js";
31
+ import { buildConflictBackupPath, buildConflictId, buildConflictProbePath, readShortMachineId, } from "../lib/conflict-file.js";
32
32
  import { appendConflictEntry } from "../lib/conflict-index.js";
33
33
  import { isCloudAuthoritative } from "../lib/cloud-authoritative.js";
34
34
  import { reindex } from "./reindex.js";
@@ -876,342 +876,381 @@ async function executeConflictItem(run, plan, scopeRun, counters, downloadItems,
876
876
  const detectedAt = new Date().toISOString();
877
877
  const machineId = readShortMachineId(run.hqRoot);
878
878
  const originalRelative = vaultKeyForLocalPath(run.hqRoot, localPath);
879
- const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
880
- const conflictAbs = localPathForVaultKey(run.hqRoot, conflictRelative);
881
- const conflictKey = vaultKeyForLocalPath(run.companyRoot, conflictAbs);
882
- if (!isDownloadWritePathStillContained(run.companyRoot, conflictKey, conflictAbs)) {
879
+ // The live path itself must still be contained in the sync root. The
880
+ // convergence probe lands in a scratch path under `.hq/tmp/` (never beside
881
+ // the live file), but every outcome below reads, renames or re-downloads at
882
+ // `localPath`, so a parent that was swapped for a link out of the root since
883
+ // planning must stop the whole item here.
884
+ if (!isDownloadWritePathStillContained(run.companyRoot, vaultKeyForLocalPath(run.companyRoot, localPath), localPath)) {
883
885
  counters.filesSkipped++;
884
886
  run.emit({
885
887
  type: "error",
886
888
  path: remoteFile.key,
887
- message: "conflict mirror skipped: local parent escaped the sync root",
889
+ message: "conflict probe skipped: local parent escaped the sync root",
888
890
  });
889
891
  return null;
890
892
  }
891
- let remoteFetched = false;
892
- let converged = false;
893
- let executionLocal = null;
893
+ // Scratch path for the remote body. It is ALWAYS removed before this
894
+ // function returns (the `finally` below) unless it was parked as the losing
895
+ // side's backup under `.hq/conflict-backups/` — no sibling twin is ever
896
+ // written next to the live file any more.
897
+ const probeAbs = buildConflictProbePath(run.hqRoot);
898
+ let probeParked = false;
899
+ const discardProbe = () => {
900
+ try {
901
+ fs.rmSync(probeAbs, { force: true });
902
+ }
903
+ catch {
904
+ /* best-effort cleanup; a stray scratch file under .hq/tmp is harmless */
905
+ }
906
+ };
907
+ /**
908
+ * Move the probe (the remote body) out of scratch into the backup dir and
909
+ * return its hq-root-relative key, or undefined when that failed. Used when
910
+ * the LOCAL body stays live so the remote bytes remain inspectable offline.
911
+ */
912
+ const parkProbeAsBackup = () => {
913
+ const backupKey = buildConflictBackupPath(originalRelative, detectedAt, machineId);
914
+ const backupAbs = localPathForVaultKey(run.hqRoot, backupKey);
915
+ try {
916
+ fs.mkdirSync(path.dirname(backupAbs), { recursive: true });
917
+ fs.renameSync(probeAbs, backupAbs);
918
+ probeParked = true;
919
+ return backupKey;
920
+ }
921
+ catch (parkErr) {
922
+ run.emit({
923
+ type: "error",
924
+ path: remoteFile.key,
925
+ message: `conflict backup of the cloud body failed: ${describeError(parkErr)}`,
926
+ });
927
+ return undefined;
928
+ }
929
+ };
894
930
  try {
895
- const downloaded = await downloadFile(run.ctx, remoteFile.key, conflictAbs);
896
- remoteFetched = true;
897
- executionLocal = readCurrentLocalFileState(localPath);
898
- if (executionLocal === null) {
899
- // The path changed kind, disappeared, or kept moving while the remote
900
- // probe was in flight. Leave both sides untouched and let the next
901
- // per-file pass classify that new state; a stale conflict is not useful.
902
- try {
903
- fs.rmSync(conflictAbs, { force: true });
931
+ fs.mkdirSync(path.dirname(probeAbs), { recursive: true });
932
+ }
933
+ catch (mkErr) {
934
+ counters.filesSkipped++;
935
+ run.emit({
936
+ type: "error",
937
+ path: remoteFile.key,
938
+ message: `conflict probe scratch dir unavailable: ${describeError(mkErr)}`,
939
+ });
940
+ return null;
941
+ }
942
+ try {
943
+ let remoteFetched = false;
944
+ let converged = false;
945
+ let probeIsSymlink = false;
946
+ let executionLocal = null;
947
+ try {
948
+ const downloaded = await downloadFile(run.ctx, remoteFile.key, probeAbs);
949
+ remoteFetched = true;
950
+ executionLocal = readCurrentLocalFileState(localPath);
951
+ if (executionLocal === null) {
952
+ // The path changed kind, disappeared, or kept moving while the remote
953
+ // probe was in flight. Leave both sides untouched and let the next
954
+ // per-file pass classify that new state; a stale conflict is not useful.
955
+ counters.filesSkipped++;
956
+ return null;
904
957
  }
905
- catch {
906
- /* best-effort cleanup */
958
+ if (fs.lstatSync(probeAbs).isSymbolicLink()) {
959
+ probeIsSymlink = true;
960
+ const target = readlinkOrNull(probeAbs);
961
+ if (target === null) {
962
+ counters.filesSkipped++;
963
+ run.emit({
964
+ type: "not-shipped",
965
+ reason: "unreadable-link",
966
+ count: 1,
967
+ samplePaths: [remoteFile.key],
968
+ });
969
+ return null;
970
+ }
971
+ else {
972
+ converged = hashSymlinkTarget(target) === executionLocal.hash;
973
+ }
974
+ }
975
+ else {
976
+ converged =
977
+ (downloaded.contentHash ?? hashFile(probeAbs)) === executionLocal.hash;
907
978
  }
908
- counters.filesSkipped++;
909
- return null;
910
979
  }
911
- if (fs.lstatSync(conflictAbs).isSymbolicLink()) {
912
- const target = readlinkOrNull(conflictAbs);
913
- if (target === null) {
980
+ catch (probeErr) {
981
+ // A session-level auth refusal is a run-level fact, not a per-file probe
982
+ // failure — propagate it so the pass aborts once.
983
+ if (probeErr instanceof VaultAuthError ||
984
+ isTerminalIdentityRefusal(probeErr) ||
985
+ isRetryableIdentityRefusal(probeErr)) {
986
+ throw probeErr;
987
+ }
988
+ if (probeErr instanceof WindowsSymlinkPrivilegeError) {
989
+ // Same deliberate skip as downloadOne: the remote symlink record cannot
990
+ // be materialized on this unprivileged Windows host. Skip it (never
991
+ // type:"error") so the company stays complete and the runner exits 0,
992
+ // and leave it unjournaled so a later privileged pass converges
993
+ // (Sentry HQ-DESKTOP-54).
914
994
  counters.filesSkipped++;
915
995
  run.emit({
916
- type: "not-shipped",
917
- reason: "unreadable-link",
918
- count: 1,
919
- samplePaths: [remoteFile.key],
996
+ type: "skip-symlink-privilege",
997
+ path: remoteFile.key,
998
+ target: probeErr.target,
999
+ remedy: WINDOWS_SYMLINK_PRIVILEGE_REMEDY,
920
1000
  });
921
1001
  return null;
922
1002
  }
923
- else {
924
- converged = hashSymlinkTarget(target) === executionLocal.hash;
1003
+ if (probeErr instanceof WindowsRenameBlockedError) {
1004
+ // Same deliberate skip as downloadOne: the remote body could not be
1005
+ // materialized because a program is holding the destination open. Skip
1006
+ // it (never type:"error") so the company stays complete and the runner
1007
+ // exits 0, and leave it unjournaled so a later pass converges once the
1008
+ // file is released (Sentry HQ-DESKTOP-54).
1009
+ counters.filesSkipped++;
1010
+ run.emit({
1011
+ type: "skip-rename-blocked",
1012
+ path: remoteFile.key,
1013
+ remedy: WINDOWS_RENAME_BLOCKED_REMEDY,
1014
+ });
1015
+ return null;
925
1016
  }
926
- }
927
- else {
928
- converged =
929
- (downloaded.contentHash ?? hashFile(conflictAbs)) === executionLocal.hash;
930
- }
931
- }
932
- catch (probeErr) {
933
- // A session-level auth refusal is a run-level fact, not a per-file probe
934
- // failure — propagate it so the pass aborts once.
935
- if (probeErr instanceof VaultAuthError ||
936
- isTerminalIdentityRefusal(probeErr) ||
937
- isRetryableIdentityRefusal(probeErr)) {
938
- throw probeErr;
939
- }
940
- if (probeErr instanceof WindowsSymlinkPrivilegeError) {
941
- // Same deliberate skip as downloadOne: the remote symlink record cannot
942
- // be materialized to a conflict mirror on this unprivileged Windows host.
943
- // Skip it (never type:"error") so the company stays complete and the
944
- // runner exits 0, and leave it unjournaled so a later privileged pass
945
- // converges (Sentry HQ-DESKTOP-54).
946
- counters.filesSkipped++;
947
1017
  run.emit({
948
- type: "skip-symlink-privilege",
1018
+ type: "error",
949
1019
  path: remoteFile.key,
950
- target: probeErr.target,
951
- remedy: WINDOWS_SYMLINK_PRIVILEGE_REMEDY,
1020
+ // describeError surfaces the error name and any code=/cause=/syscall=
1021
+ // tokens the desktop's cause axis parses, so a future recurrence carries
1022
+ // an attributable identity instead of `cause: unknown` (HQ-DESKTOP-54
1023
+ // instrumentation). The literal prefix is unchanged so the desktop's
1024
+ // fixed shape vocabulary keeps matching.
1025
+ message: `conflict convergence probe failed: ${describeError(probeErr)}`,
952
1026
  });
953
- return null;
954
1027
  }
955
- if (probeErr instanceof WindowsRenameBlockedError) {
956
- // Same deliberate skip as downloadOne: the remote body could not be
957
- // materialized to the conflict mirror because a program is holding the
958
- // destination open. Skip it (never type:"error") so the company stays
959
- // complete and the runner exits 0, and leave it unjournaled so a later
960
- // pass converges once the file is released (Sentry HQ-DESKTOP-54).
961
- counters.filesSkipped++;
962
- run.emit({
963
- type: "skip-rename-blocked",
964
- path: remoteFile.key,
965
- remedy: WINDOWS_RENAME_BLOCKED_REMEDY,
1028
+ if (converged) {
1029
+ if (executionLocal === null) {
1030
+ counters.filesSkipped++;
1031
+ return null;
1032
+ }
1033
+ updateEntry(run.journal, remoteFile.key, executionLocal.hash, executionLocal.size, "down", localPath, {
1034
+ remoteEtag: remoteFile.etag,
1035
+ mtimeMs: executionLocal.mtimeMs,
1036
+ ctimeMs: executionLocal.ctimeMs,
1037
+ kind: executionLocal.kind,
966
1038
  });
967
- return null;
968
- }
969
- run.emit({
970
- type: "error",
971
- path: remoteFile.key,
972
- // describeError surfaces the error name and any code=/cause=/syscall=
973
- // tokens the desktop's cause axis parses, so a future recurrence carries
974
- // an attributable identity instead of `cause: unknown` (HQ-DESKTOP-54
975
- // instrumentation). The literal prefix is unchanged so the desktop's
976
- // fixed shape vocabulary keeps matching.
977
- message: `conflict convergence probe failed: ${describeError(probeErr)}`,
978
- });
979
- }
980
- if (converged) {
981
- if (executionLocal === null) {
1039
+ run.emit({ type: "reconciled", path: remoteFile.key, direction: "pull" });
982
1040
  counters.filesSkipped++;
983
1041
  return null;
984
1042
  }
985
- if (remoteFetched) {
986
- try {
987
- fs.rmSync(conflictAbs, { force: true });
988
- }
989
- catch {
990
- /* best-effort cleanup; a stray identical mirror is harmless */
1043
+ counters.conflicts++;
1044
+ counters.conflictPaths.push(remoteFile.key);
1045
+ // A successful probe always decides from the local bytes captured after the
1046
+ // GET. Only a failed probe falls back to the preview snapshot so the existing
1047
+ // error-path behavior remains conservative.
1048
+ const localHash = executionLocal?.hash ?? item.localHash;
1049
+ const localSize = executionLocal?.size ?? item.localSize;
1050
+ const localMtime = executionLocal?.mtime ?? item.localMtime;
1051
+ const localSnapshot = executionLocal?.snapshot ?? item.localSnapshot;
1052
+ const localKind = executionLocal?.kind ??
1053
+ (item.localSnapshot.kind === "symlink" ? "symlink" : "file");
1054
+ // Version-aware winner (strategy unset or `keep`): compare the two bodies
1055
+ // instead of letting the flag name a side. Only regular files on both
1056
+ // sides have comparable bodies; a symlink on either side falls back to the
1057
+ // historical `keep` outcome (adopt the cloud record).
1058
+ let resolution;
1059
+ let decision;
1060
+ if (usesVersionAwareWinner(run.options.onConflict)) {
1061
+ resolution = "keep";
1062
+ if (remoteFetched && executionLocal?.kind === "file" && !probeIsSymlink) {
1063
+ try {
1064
+ decision = pickWinner({
1065
+ localBytes: fs.readFileSync(localPath),
1066
+ remoteBytes: fs.readFileSync(probeAbs),
1067
+ localMtime,
1068
+ remoteMtime: remoteFile.lastModified,
1069
+ });
1070
+ }
1071
+ catch (readErr) {
1072
+ run.emit({
1073
+ type: "error",
1074
+ path: remoteFile.key,
1075
+ message: `conflict winner comparison failed: ${describeError(readErr)}`,
1076
+ });
1077
+ }
991
1078
  }
992
1079
  }
993
- updateEntry(run.journal, remoteFile.key, executionLocal.hash, executionLocal.size, "down", localPath, {
994
- remoteEtag: remoteFile.etag,
995
- mtimeMs: executionLocal.mtimeMs,
996
- ctimeMs: executionLocal.ctimeMs,
997
- kind: executionLocal.kind,
1080
+ else {
1081
+ resolution = await resolveConflict({
1082
+ path: remoteFile.key,
1083
+ localHash,
1084
+ remoteModified: remoteFile.lastModified,
1085
+ localModified: localMtime,
1086
+ direction: "pull",
1087
+ }, run.options.onConflict);
1088
+ }
1089
+ run.emit({
1090
+ type: "conflict",
1091
+ path: remoteFile.key,
1092
+ direction: "pull",
1093
+ resolution,
1094
+ ...(decision ? { decision } : {}),
998
1095
  });
999
- run.emit({ type: "reconciled", path: remoteFile.key, direction: "pull" });
1000
- counters.filesSkipped++;
1001
- return null;
1002
- }
1003
- counters.conflicts++;
1004
- counters.conflictPaths.push(remoteFile.key);
1005
- // A successful probe always decides from the local bytes captured after the
1006
- // GET. Only a failed probe falls back to the preview snapshot so the existing
1007
- // error-path behavior remains conservative.
1008
- const localHash = executionLocal?.hash ?? item.localHash;
1009
- const localSize = executionLocal?.size ?? item.localSize;
1010
- const localMtime = executionLocal?.mtime ?? item.localMtime;
1011
- const localSnapshot = executionLocal?.snapshot ?? item.localSnapshot;
1012
- const localKind = executionLocal?.kind ??
1013
- (item.localSnapshot.kind === "symlink" ? "symlink" : "file");
1014
- const resolution = await resolveConflict({
1015
- path: remoteFile.key,
1016
- localHash,
1017
- remoteModified: remoteFile.lastModified,
1018
- localModified: localMtime,
1019
- direction: "pull",
1020
- }, run.options.onConflict);
1021
- run.emit({
1022
- type: "conflict",
1023
- path: remoteFile.key,
1024
- direction: "pull",
1025
- resolution,
1026
- });
1027
- if (resolution !== "abort" &&
1028
- resolution !== "overwrite" &&
1029
- resolution !== "keep") {
1030
- if (remoteFetched) {
1096
+ const recordConflict = (conflictPath, preserved) => {
1031
1097
  try {
1032
1098
  appendConflictEntry(run.hqRoot, {
1033
1099
  id: buildConflictId(originalRelative, detectedAt),
1034
1100
  originalPath: originalRelative,
1035
- conflictPath: conflictRelative,
1101
+ ...(conflictPath ? { conflictPath } : {}),
1036
1102
  detectedAt,
1037
1103
  side: "pull",
1038
1104
  machineId,
1039
1105
  localHash,
1040
1106
  remoteHash: remoteFile.etag ? normalizeEtag(remoteFile.etag) : "",
1041
- // The holding resolutions leave local alone and this sidecar keeps
1042
- // the cloud copy. `keep` is indexed only after its local rename
1043
- // succeeds below, so this row can never describe the wrong side.
1044
- preserved: "remote",
1107
+ preserved,
1108
+ ...(decision ? { decision } : {}),
1045
1109
  });
1046
1110
  }
1047
- catch (mirrorErr) {
1111
+ catch (indexErr) {
1048
1112
  run.emit({
1049
1113
  type: "error",
1050
1114
  path: remoteFile.key,
1051
- message: `conflict mirror index write failed: ${describeError(mirrorErr)}`,
1115
+ message: `conflict index write failed: ${describeError(indexErr)}`,
1052
1116
  });
1053
1117
  }
1118
+ };
1119
+ if (resolution === "abort") {
1120
+ run.emit({ type: "new-files", files: [] });
1121
+ persistPullJournal(run);
1122
+ return {
1123
+ filesDownloaded: counters.filesDownloaded,
1124
+ bytesDownloaded: counters.bytesDownloaded,
1125
+ filesSkipped: counters.filesSkipped,
1126
+ conflicts: counters.conflicts,
1127
+ conflictPaths: counters.conflictPaths,
1128
+ aborted: true,
1129
+ newFiles: plan.newFiles,
1130
+ newFilesCount: plan.newFilesCount,
1131
+ filesExcludedByPolicy: plan.filesExcludedByPolicy,
1132
+ filesTombstoned: 0,
1133
+ filesOutOfScope: counters.filesOutOfScope,
1134
+ scopeOrphansRemoved: scopeRun.scopeOrphansRemoved,
1135
+ scopeOrphansBlocked: scopeRun.shrinkResult.dirtyTombstoned,
1136
+ changedPaths: [...counters.changedPaths, ...scopeRun.changedPaths],
1137
+ appliedUpserts: counters.appliedUpserts,
1138
+ };
1054
1139
  }
1055
- }
1056
- else if (resolution !== "keep" && remoteFetched) {
1057
- try {
1058
- fs.rmSync(conflictAbs, { force: true });
1059
- }
1060
- catch {
1061
- /* best-effort; a leftover mirror is cosmetic, not corrupting */
1062
- }
1063
- }
1064
- if (resolution === "abort") {
1065
- run.emit({ type: "new-files", files: [] });
1066
- persistPullJournal(run);
1067
- return {
1068
- filesDownloaded: counters.filesDownloaded,
1069
- bytesDownloaded: counters.bytesDownloaded,
1070
- filesSkipped: counters.filesSkipped,
1071
- conflicts: counters.conflicts,
1072
- conflictPaths: counters.conflictPaths,
1073
- aborted: true,
1074
- newFiles: plan.newFiles,
1075
- newFilesCount: plan.newFilesCount,
1076
- filesExcludedByPolicy: plan.filesExcludedByPolicy,
1077
- filesTombstoned: 0,
1078
- filesOutOfScope: counters.filesOutOfScope,
1079
- scopeOrphansRemoved: scopeRun.scopeOrphansRemoved,
1080
- scopeOrphansBlocked: scopeRun.shrinkResult.dirtyTombstoned,
1081
- changedPaths: [...counters.changedPaths, ...scopeRun.changedPaths],
1082
- appliedUpserts: counters.appliedUpserts,
1140
+ // Hold the local body where it is, recording the remote etag so the conflict
1141
+ // cannot re-fire (#137) and arming the journal-honesty flag because the held
1142
+ // copy never matched that etag. The flag stops the currency-gated delete
1143
+ // planner propagating a delete whose currency would falsely match on HEAD,
1144
+ // and routes the next PUSH pass through the conflict path, where the same
1145
+ // version-aware comparison publishes the local body under an If-Match fence.
1146
+ // Any genuine future download clears it by replacing the entry.
1147
+ const holdLocal = () => {
1148
+ counters.filesSkipped++;
1149
+ updateEntry(run.journal, remoteFile.key, localHash, localSize, "down", localPath, {
1150
+ remoteEtag: remoteFile.etag,
1151
+ mtimeMs: localMtime.getTime(),
1152
+ kind: localKind,
1153
+ });
1154
+ const heldEntry = getEntry(run.journal, remoteFile.key);
1155
+ if (heldEntry)
1156
+ heldEntry.localDiverges = true;
1157
+ return null;
1083
1158
  };
1084
- }
1085
- // Hold the local body where it is, recording the remote etag so the conflict
1086
- // cannot re-fire (#137) and arming the journal-honesty flag because the held
1087
- // copy never matched that etag. The flag stops the currency-gated delete
1088
- // planner propagating a delete whose currency would falsely match on HEAD.
1089
- // Any genuine future download clears it by replacing the entry.
1090
- const holdLocal = () => {
1091
- counters.filesSkipped++;
1092
- updateEntry(run.journal, remoteFile.key, localHash, localSize, "down", localPath, {
1093
- remoteEtag: remoteFile.etag,
1094
- mtimeMs: localMtime.getTime(),
1095
- kind: localKind,
1096
- });
1097
- const heldEntry = getEntry(run.journal, remoteFile.key);
1098
- if (heldEntry)
1099
- heldEntry.localDiverges = true;
1100
- return null;
1101
- };
1102
- // `publish-local` is a PUSH-leg strategy: it means "send my body up". On the
1103
- // pull leg there is nothing to publish, so it holds the local body and arms
1104
- // the honesty flag, which is what the push leg then promotes under an
1105
- // If-Match fence. Falling through to the download branch instead would
1106
- // overwrite the very local copy the operator elected, which is the data loss
1107
- // this strategy exists to prevent.
1108
- //
1109
- // `skip` is the interactive "leave this one, I will deal with it later". A
1110
- // resolution that says leave it alone may not rename the operator's file, so
1111
- // it holds too — it is deliberately NOT bundled with `keep` any more.
1112
- if (resolution === "skip" || resolution === "publish-local") {
1113
- return holdLocal();
1114
- }
1115
- // `keep` ADOPTS the cloud body as the working copy and preserves the local
1116
- // one beside it under the `.conflict-` name.
1117
- //
1118
- // It used to mean the opposite — hold local, stamp the remote etag, arm
1119
- // `localDiverges` — and that combination was terminal. The push leg refuses
1120
- // to send a body the journal calls divergent; the pull leg sees a remote
1121
- // whose etag already matches and leaves it alone; and every later `keep`
1122
- // re-armed the flag. The file converged in neither direction, and because the
1123
- // desktop app hardcodes `--on-conflict keep` that was the default outcome for
1124
- // every real conflict. Adopting the remote clears the divergence by
1125
- // construction: the entry then describes the body that is actually on disk.
1126
- // The local bytes are not destroyed, only renamed.
1127
- if (resolution === "keep") {
1128
- if (!remoteFetched) {
1129
- // The probe never produced a body (its failure is already emitted above).
1130
- // Hold rather than move aside a file we have nothing to replace it with.
1159
+ // `publish-local` is a PUSH-leg strategy: it means "send my body up". On the
1160
+ // pull leg there is nothing to publish, so it holds the local body and arms
1161
+ // the honesty flag, which is what the push leg then promotes under an
1162
+ // If-Match fence. `skip` is the interactive "leave this one, I will deal
1163
+ // with it later" — a resolution that says leave it alone may not touch the
1164
+ // operator's file, so it holds too. Both keep the cloud body inspectable
1165
+ // by parking the probe as a backup and indexing it.
1166
+ if (resolution === "skip" || resolution === "publish-local") {
1167
+ if (remoteFetched)
1168
+ recordConflict(parkProbeAsBackup(), "remote");
1131
1169
  return holdLocal();
1132
1170
  }
1133
- try {
1134
- // The sidecar currently holds the fetched probe copy of the remote.
1135
- // Remove it explicitly before renaming: POSIX rename replaces a file at
1136
- // the destination, but Windows rename rejects an occupied destination.
1137
- // The download queued below re-fetches it. One extra GET buys the entire
1138
- // tested download path —
1139
- // symlink materialization, path codec, mtime and etag journalling —
1140
- // instead of a hand-rolled three-way swap with its own crash window.
1141
- //
1142
- // A transient Windows sharing violation on the preserve rename surfaces as
1143
- // WindowsRenameBlockedError (renameOrRaiseWindowsBlocked); the sidecar
1144
- // itself is a freshly-minted conflict path, so a plain rmSync is enough.
1145
- fs.rmSync(conflictAbs, { force: true });
1146
- renameOrRaiseWindowsBlocked(localPath, conflictAbs);
1147
- }
1148
- catch (preserveErr) {
1149
- if (preserveErr instanceof WindowsRenameBlockedError) {
1150
- // A program is holding the local file open, so it could not be moved
1151
- // aside. Downgrade to a deliberate skip and return WITHOUT holdLocal():
1152
- // the journal entry is left untouched (no remoteEtag stamp, no
1153
- // `localDiverges` arming), so the conflict simply re-fires next pass
1154
- // instead of stranding the operator's elected file as divergent (never
1155
- // type:"error"; company stays complete and the one-shot runner exits 0
1156
- // — Sentry HQ-DESKTOP-54, second path).
1157
- counters.filesSkipped++;
1171
+ if (resolution === "keep") {
1172
+ if (!remoteFetched) {
1173
+ // The probe never produced a body (its failure is already emitted above).
1174
+ // Hold rather than move aside a file we have nothing to replace it with.
1175
+ return holdLocal();
1176
+ }
1177
+ if (decision?.winner === "local") {
1178
+ // The local body is the newer version (higher frontmatter `version:`
1179
+ // or newer mtime). Keep it live; park the cloud body as the backup so
1180
+ // the decision stays auditable; hold with the honesty flag so the push
1181
+ // leg publishes it under a fence on the very etag observed here.
1182
+ recordConflict(parkProbeAsBackup(), "remote");
1183
+ return holdLocal();
1184
+ }
1185
+ // The cloud body wins (higher version / newer mtime, or no comparable
1186
+ // bodies — the historical `keep` outcome). Adopt it at the live path and
1187
+ // preserve the displaced local body OUT of the tree under
1188
+ // `.hq/conflict-backups/`, never as a sibling twin. Rename first, then
1189
+ // reuse the ordinary tested download path for the replacement (symlink
1190
+ // materialization, path codec, mtime and etag journalling) instead of a
1191
+ // hand-rolled swap from the probe.
1192
+ const backupKey = buildConflictBackupPath(originalRelative, detectedAt, machineId);
1193
+ const backupAbs = localPathForVaultKey(run.hqRoot, backupKey);
1194
+ try {
1195
+ fs.mkdirSync(path.dirname(backupAbs), { recursive: true });
1196
+ // A transient Windows sharing violation on the preserve rename surfaces
1197
+ // as WindowsRenameBlockedError (renameOrRaiseWindowsBlocked).
1198
+ renameOrRaiseWindowsBlocked(localPath, backupAbs);
1199
+ }
1200
+ catch (preserveErr) {
1201
+ if (preserveErr instanceof WindowsRenameBlockedError) {
1202
+ // A program is holding the local file open, so it could not be moved
1203
+ // aside. Downgrade to a deliberate skip and return WITHOUT holdLocal():
1204
+ // the journal entry is left untouched (no remoteEtag stamp, no
1205
+ // `localDiverges` arming), so the conflict simply re-fires next pass
1206
+ // instead of stranding the operator's elected file as divergent (never
1207
+ // type:"error"; company stays complete and the one-shot runner exits 0
1208
+ // — Sentry HQ-DESKTOP-54, second path).
1209
+ counters.filesSkipped++;
1210
+ run.emit({
1211
+ type: "skip-rename-blocked",
1212
+ path: remoteFile.key,
1213
+ remedy: WINDOWS_RENAME_BLOCKED_REMEDY,
1214
+ });
1215
+ return null;
1216
+ }
1158
1217
  run.emit({
1159
- type: "skip-rename-blocked",
1218
+ type: "error",
1160
1219
  path: remoteFile.key,
1161
- remedy: WINDOWS_RENAME_BLOCKED_REMEDY,
1220
+ // describeError carries the error name / code= / syscall= tokens for a
1221
+ // non-downgradable failure (e.g. EACCES) so the next occurrence is
1222
+ // attributable; the literal prefix is unchanged (HQ-DESKTOP-54).
1223
+ message: `conflict keep could not preserve the local copy: ${describeError(preserveErr)}`,
1162
1224
  });
1163
- return null;
1225
+ return holdLocal();
1164
1226
  }
1165
- run.emit({
1166
- type: "error",
1167
- path: remoteFile.key,
1168
- // describeError carries the error name / code= / syscall= tokens for a
1169
- // non-downgradable failure (e.g. EACCES) so the next occurrence is
1170
- // attributable; the literal prefix is unchanged (HQ-DESKTOP-54).
1171
- message: `conflict keep could not preserve the local copy: ${describeError(preserveErr)}`,
1172
- });
1173
- return holdLocal();
1174
- }
1175
- try {
1176
- appendConflictEntry(run.hqRoot, {
1177
- id: buildConflictId(originalRelative, detectedAt),
1178
- originalPath: originalRelative,
1179
- conflictPath: conflictRelative,
1180
- detectedAt,
1181
- side: "pull",
1182
- machineId,
1183
- localHash,
1184
- remoteHash: remoteFile.etag ? normalizeEtag(remoteFile.etag) : "",
1185
- preserved: "local",
1186
- });
1187
- }
1188
- catch (mirrorErr) {
1189
- run.emit({
1190
- type: "error",
1191
- path: remoteFile.key,
1192
- message: `conflict mirror index write failed: ${mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)}`,
1227
+ recordConflict(backupKey, "local");
1228
+ downloadItems.push({
1229
+ action: "download",
1230
+ remoteFile,
1231
+ localPath,
1232
+ isNew: false,
1233
+ // The local body was just moved aside, so the pre-replace guard must
1234
+ // expect absence. Passing the original snapshot would make that guard
1235
+ // abort the very download it exists to protect.
1236
+ localSnapshot: { kind: "absent" },
1193
1237
  });
1238
+ return null;
1194
1239
  }
1240
+ // `overwrite`: the cloud body replaces local unconditionally.
1195
1241
  downloadItems.push({
1196
1242
  action: "download",
1197
1243
  remoteFile,
1198
1244
  localPath,
1199
1245
  isNew: false,
1200
- // The local body was just moved aside, so the pre-replace guard must
1201
- // expect absence. Passing the original snapshot would make that guard
1202
- // abort the very download it exists to protect.
1203
- localSnapshot: { kind: "absent" },
1246
+ localSnapshot,
1204
1247
  });
1205
1248
  return null;
1206
1249
  }
1207
- downloadItems.push({
1208
- action: "download",
1209
- remoteFile,
1210
- localPath,
1211
- isNew: false,
1212
- localSnapshot,
1213
- });
1214
- return null;
1250
+ finally {
1251
+ if (!probeParked)
1252
+ discardProbe();
1253
+ }
1215
1254
  }
1216
1255
  async function executeDownloadExecutor(run, downloadItems, transferConcurrency, counters) {
1217
1256
  if (downloadItems.length === 0)