@indigoai-us/hq-cloud 6.11.12 → 6.11.13

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 (107) hide show
  1. package/dist/bin/sync-runner-company.d.ts +35 -0
  2. package/dist/bin/sync-runner-company.d.ts.map +1 -0
  3. package/dist/bin/sync-runner-company.js +290 -0
  4. package/dist/bin/sync-runner-company.js.map +1 -0
  5. package/dist/bin/sync-runner-events.d.ts +12 -0
  6. package/dist/bin/sync-runner-events.d.ts.map +1 -0
  7. package/dist/bin/sync-runner-events.js +12 -0
  8. package/dist/bin/sync-runner-events.js.map +1 -0
  9. package/dist/bin/sync-runner-planning.d.ts +53 -0
  10. package/dist/bin/sync-runner-planning.d.ts.map +1 -0
  11. package/dist/bin/sync-runner-planning.js +59 -0
  12. package/dist/bin/sync-runner-planning.js.map +1 -0
  13. package/dist/bin/sync-runner-rollup.d.ts +24 -0
  14. package/dist/bin/sync-runner-rollup.d.ts.map +1 -0
  15. package/dist/bin/sync-runner-rollup.js +46 -0
  16. package/dist/bin/sync-runner-rollup.js.map +1 -0
  17. package/dist/bin/sync-runner-telemetry.d.ts +5 -0
  18. package/dist/bin/sync-runner-telemetry.d.ts.map +1 -0
  19. package/dist/bin/sync-runner-telemetry.js +5 -0
  20. package/dist/bin/sync-runner-telemetry.js.map +1 -0
  21. package/dist/bin/sync-runner-watch-loop.d.ts +17 -0
  22. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -0
  23. package/dist/bin/sync-runner-watch-loop.js +372 -0
  24. package/dist/bin/sync-runner-watch-loop.js.map +1 -0
  25. package/dist/bin/sync-runner-watch-routes.d.ts +25 -0
  26. package/dist/bin/sync-runner-watch-routes.d.ts.map +1 -0
  27. package/dist/bin/sync-runner-watch-routes.js +74 -0
  28. package/dist/bin/sync-runner-watch-routes.js.map +1 -0
  29. package/dist/bin/sync-runner.d.ts +3 -54
  30. package/dist/bin/sync-runner.d.ts.map +1 -1
  31. package/dist/bin/sync-runner.js +73 -1154
  32. package/dist/bin/sync-runner.js.map +1 -1
  33. package/dist/cli/reindex.d.ts.map +1 -1
  34. package/dist/cli/reindex.js +34 -17
  35. package/dist/cli/reindex.js.map +1 -1
  36. package/dist/cli/reindex.test.js +39 -5
  37. package/dist/cli/reindex.test.js.map +1 -1
  38. package/dist/cli/rescue-classify-ordering.test.js +17 -0
  39. package/dist/cli/rescue-classify-ordering.test.js.map +1 -1
  40. package/dist/cli/rescue-core.d.ts +45 -0
  41. package/dist/cli/rescue-core.d.ts.map +1 -1
  42. package/dist/cli/rescue-core.js +197 -170
  43. package/dist/cli/rescue-core.js.map +1 -1
  44. package/dist/cli/share.d.ts.map +1 -1
  45. package/dist/cli/share.js +224 -676
  46. package/dist/cli/share.js.map +1 -1
  47. package/dist/cli/sync.d.ts.map +1 -1
  48. package/dist/cli/sync.js +399 -726
  49. package/dist/cli/sync.js.map +1 -1
  50. package/dist/cli/sync.test.js +20 -0
  51. package/dist/cli/sync.test.js.map +1 -1
  52. package/dist/daemon-worker.d.ts +2 -2
  53. package/dist/daemon-worker.js +3 -3
  54. package/dist/daemon-worker.js.map +1 -1
  55. package/dist/object-io.js +1 -1
  56. package/dist/object-io.js.map +1 -1
  57. package/dist/remote-pull.d.ts +2 -2
  58. package/dist/remote-pull.d.ts.map +1 -1
  59. package/dist/remote-pull.js +23 -3
  60. package/dist/remote-pull.js.map +1 -1
  61. package/dist/remote-pull.test.js +24 -2
  62. package/dist/remote-pull.test.js.map +1 -1
  63. package/dist/sync/push-receiver.d.ts +6 -0
  64. package/dist/sync/push-receiver.d.ts.map +1 -1
  65. package/dist/sync/push-receiver.js +32 -2
  66. package/dist/sync/push-receiver.js.map +1 -1
  67. package/dist/sync/push-receiver.test.js +31 -0
  68. package/dist/sync/push-receiver.test.js.map +1 -1
  69. package/dist/sync-core.d.ts +27 -0
  70. package/dist/sync-core.d.ts.map +1 -0
  71. package/dist/sync-core.js +54 -0
  72. package/dist/sync-core.js.map +1 -0
  73. package/dist/vault-client.d.ts.map +1 -1
  74. package/dist/vault-client.js +284 -36
  75. package/dist/vault-client.js.map +1 -1
  76. package/dist/vault-client.test.js +59 -0
  77. package/dist/vault-client.test.js.map +1 -1
  78. package/dist/watcher.d.ts +2 -20
  79. package/dist/watcher.d.ts.map +1 -1
  80. package/dist/watcher.js +3 -113
  81. package/dist/watcher.js.map +1 -1
  82. package/package.json +1 -1
  83. package/src/bin/sync-runner-company.ts +350 -0
  84. package/src/bin/sync-runner-events.ts +25 -0
  85. package/src/bin/sync-runner-planning.ts +121 -0
  86. package/src/bin/sync-runner-rollup.ts +72 -0
  87. package/src/bin/sync-runner-telemetry.ts +8 -0
  88. package/src/bin/sync-runner-watch-loop.ts +443 -0
  89. package/src/bin/sync-runner-watch-routes.ts +86 -0
  90. package/src/bin/sync-runner.ts +96 -1253
  91. package/src/cli/reindex.test.ts +41 -3
  92. package/src/cli/reindex.ts +35 -19
  93. package/src/cli/rescue-classify-ordering.test.ts +20 -0
  94. package/src/cli/rescue-core.ts +252 -176
  95. package/src/cli/share.ts +363 -705
  96. package/src/cli/sync.test.ts +25 -0
  97. package/src/cli/sync.ts +612 -802
  98. package/src/daemon-worker.ts +3 -3
  99. package/src/object-io.ts +1 -1
  100. package/src/remote-pull.test.ts +30 -1
  101. package/src/remote-pull.ts +29 -4
  102. package/src/sync/push-receiver.test.ts +35 -0
  103. package/src/sync/push-receiver.ts +41 -2
  104. package/src/sync-core.ts +58 -0
  105. package/src/vault-client.test.ts +74 -0
  106. package/src/vault-client.ts +395 -43
  107. package/src/watcher.ts +6 -141
package/src/cli/share.ts CHANGED
@@ -51,6 +51,12 @@ import {
51
51
  isDirInScope,
52
52
  type ScopePrefixInput,
53
53
  } from "../prefix-coalesce.js";
54
+ import {
55
+ hasRemoteChanged,
56
+ isAccessDenied,
57
+ resolveActiveCompany,
58
+ resolveTransferConcurrency,
59
+ } from "../sync-core.js";
54
60
  import {
55
61
  buildConflictId,
56
62
  buildConflictPath,
@@ -736,21 +742,6 @@ export interface ShareResult {
736
742
  aborted: boolean;
737
743
  }
738
744
 
739
- /**
740
- * Is this error the S3/STS "access denied" class? Expected when a scoped
741
- * member/guest credential touches a key outside its granted ACL prefixes
742
- * (the server's `SCOPE_EXCEEDS_PARENT` surfaces as a 403 AccessDenied /
743
- * Forbidden). Mirrors the pull-side `isAccessDenied` in sync.ts so the push
744
- * leg can treat a stray out-of-scope key as a skip rather than a fatal throw.
745
- */
746
- function isAccessDenied(err: unknown): boolean {
747
- if (err && typeof err === "object" && "name" in err) {
748
- const name = (err as { name?: unknown }).name;
749
- return name === "AccessDenied" || name === "Forbidden";
750
- }
751
- return false;
752
- }
753
-
754
745
  /**
755
746
  * A conditional-write fence rejection — the SDK's 412 (`name:
756
747
  * "PreconditionFailed"`) or the presigned transport's mirror of it. Means
@@ -804,23 +795,99 @@ function wrapFilterWithScope(
804
795
  * Share local file(s) to the entity vault.
805
796
  */
806
797
  export async function share(options: ShareOptions): Promise<ShareResult> {
798
+ const run = await createPushRunContext(options);
799
+ const counters = createShareCounters();
800
+ const filesRefusedStalePaths: string[] = [];
801
+ const conflictPaths: string[] = [];
802
+
803
+ const plans = await buildSharePlans(run);
804
+ const uploadResult = await executeUploads(
805
+ run,
806
+ plans.pushPlan,
807
+ counters,
808
+ conflictPaths,
809
+ );
810
+ if (uploadResult.aborted) {
811
+ return buildShareResult(
812
+ run,
813
+ counters,
814
+ filesRefusedStalePaths,
815
+ uploadResult.abortFlightConflictPaths,
816
+ true,
817
+ );
818
+ }
819
+
820
+ await executeDeletes(
821
+ run,
822
+ plans.deletePlan,
823
+ plans.decommissionPlan,
824
+ counters,
825
+ filesRefusedStalePaths,
826
+ );
827
+ finalizeShareJournal(run);
828
+ throwUploadWorkerErrors(uploadResult.workerErrors);
829
+
830
+ return buildShareResult(run, counters, filesRefusedStalePaths, conflictPaths, false);
831
+ }
832
+
833
+ type DeletePolicy = NonNullable<ShareOptions["propagateDeletePolicy"]>;
834
+ type ShareEmit = (event: SyncProgressEvent) => void;
835
+ type UploadPlanItem = Extract<PushPlanItem, { action: "upload" }>;
836
+ type JournalFileEntry = SyncJournal["files"][string];
837
+
838
+ interface PushRunContext {
839
+ options: ShareOptions;
840
+ paths: string[];
841
+ message?: string;
842
+ onConflict?: ConflictStrategy;
843
+ vaultConfig?: VaultServiceConfig;
844
+ entityContext?: EntityContext;
845
+ hqRoot: string;
846
+ skipUnchanged?: boolean;
847
+ propagateDeletes?: boolean;
848
+ propagateDeletePolicy: DeletePolicy;
849
+ emit: ShareEmit;
850
+ companyRef: string;
851
+ ctx: EntityContext;
852
+ syncRoot: string;
853
+ shouldSync: (filePath: string, isDir?: boolean) => boolean;
854
+ journalSlug: string;
855
+ journal: SyncJournal;
856
+ excludedSet: Set<string>;
857
+ excludedById: Record<string, number>;
858
+ scopeExcludedSet: Set<string>;
859
+ }
860
+
861
+ interface ShareCounters {
862
+ filesUploaded: number;
863
+ bytesUploaded: number;
864
+ filesSkipped: number;
865
+ filesDeleted: number;
866
+ filesTombstoned: number;
867
+ filesRefusedStale: number;
868
+ filesSuppressedByTombstone: number;
869
+ }
870
+
871
+ interface SharePlans {
872
+ pushPlan: PushPlan;
873
+ deletePlan: DeletePlan;
874
+ decommissionPlan: string[];
875
+ }
876
+
877
+ interface UploadExecutionResult {
878
+ aborted: boolean;
879
+ abortFlightConflictPaths: string[];
880
+ workerErrors: Error[];
881
+ }
882
+
883
+ const REFUSED_STALE_PATH_CAP = 50;
884
+
885
+ async function createPushRunContext(options: ShareOptions): Promise<PushRunContext> {
807
886
  const { paths, company, message, onConflict, vaultConfig, entityContext, hqRoot, skipUnchanged, propagateDeletes } = options;
808
- // Default to "owned-only" — the pre-5.24 behavior — when delete-propagation
809
- // is on but the caller hasn't pinned a policy. Staged-default rollout
810
- // (see CHANGELOG / PR for hq-cloud 5.24.0): 5.24 ships the currency-gated
811
- // CODE PATH plus the conflict-mirror exclusion (which is policy-
812
- // independent and immediately stops new litter), but holds the default
813
- // flip to a later release after soak. Opt into the safer policy now via
814
- // `propagateDeletePolicy: "currency-gated"` (explicit) or
815
- // `HQ_SYNC_DELETE_POLICY=currency-gated` (env, honored by sync-runner).
816
- // The default flip to `"currency-gated"` is scheduled for 5.25.0.
817
- let propagateDeletePolicy: "currency-gated" | "owned-only" | "all" =
887
+ let propagateDeletePolicy: DeletePolicy =
818
888
  options.propagateDeletePolicy ?? "owned-only";
819
889
  const emit = options.onEvent ?? defaultConsoleLogger;
820
890
 
821
- // Exactly-one-of contract: either we vend (vaultConfig) or the caller did
822
- // (entityContext). Both supplied is ambiguous (which credentials win?), and
823
- // neither leaves us with no way to talk to S3.
824
891
  if (vaultConfig && entityContext) {
825
892
  throw new Error(
826
893
  "share() requires exactly one of `vaultConfig` or `entityContext`, not both. " +
@@ -834,9 +901,6 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
834
901
  );
835
902
  }
836
903
 
837
- // Resolve company — slug, UID, or from active config. When the caller
838
- // provided a pre-resolved entityContext, prefer its slug as the canonical
839
- // ref (the caller already knows what entity these creds are for).
840
904
  const companyRef =
841
905
  company ?? entityContext?.slug ?? resolveActiveCompany(hqRoot);
842
906
  if (!companyRef) {
@@ -846,67 +910,18 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
846
910
  );
847
911
  }
848
912
 
849
- // Resolve entity context. Two paths:
850
- // 1. vaultConfig provided → resolveEntityContext does the lookup + STS vend
851
- // (cached + auto-refreshable mid-run).
852
- // 2. entityContext provided → use it directly. No lookup, no vending,
853
- // no auto-refresh (we have no Cognito token to re-vend with).
854
- // Caller is responsible for vending credentials with enough TTL to
855
- // cover the run; if they under-vend, the AWS SDK surfaces ExpiredToken
856
- // naturally on the first failing PUT.
857
- let ctx: EntityContext = entityContext
913
+ const ctx: EntityContext = entityContext
858
914
  ? entityContext
859
915
  : await resolveEntityContext(companyRef, vaultConfig!);
860
916
 
861
- // Personal-vault policy correction (6.0.1). The `owned-only` rule encodes a
862
- // multi-user curation premise — "don't tombstone peer-uploaded content even
863
- // if my journal says I pulled it" — which is meaningful when several humans
864
- // share a company bucket (a behind machine's first sync must not erase
865
- // recent uploads from peers). On a personal vault that premise collapses:
866
- // every file is the same human's content, just routed through different
867
- // machines, and `direction: "down"` only means "uploaded from my laptop,
868
- // pulled by my EC2" — it never means "uploaded by someone else." With
869
- // `owned-only` in effect, `rm <file>` followed by `hq sync` silently fails
870
- // to propagate the delete, leaving permanent vault litter (the May-27
871
- // `personal/.obsidian/*.drift-*` files were diagnosed exactly this way).
872
- // The etag-based `currency-gated` policy already captures the only safety
873
- // intent that survives the single-user case ("don't tombstone if remote
874
- // drifted since I last synced"); coerce to it here so the policy is right
875
- // regardless of which caller's default landed. Explicit `"all"` is
876
- // preserved — it's the emergency-reconcile opt-out and the caller has
877
- // already asserted intent.
878
917
  if (ctx.uid.startsWith("prs_") && propagateDeletePolicy === "owned-only") {
879
918
  propagateDeletePolicy = "currency-gated";
880
919
  }
881
920
 
882
- // Remote keys are company-relative; the on-disk scoping prefix is
883
- // companies/{slug}/. Anything outside this folder gets skipped to avoid
884
- // leaking cross-company state into the vault.
885
- //
886
- // In personalMode the syncRoot is `hqRoot` itself — remote keys are
887
- // hq-root-relative to match the Rust personal first-push (which uploads
888
- // every non-excluded top-level dir under ~/HQ). The exclusion list is
889
- // enforced upstream by the runner; share() just trusts `paths`.
890
921
  const syncRoot = options.personalMode === true
891
922
  ? hqRoot
892
923
  : path.join(hqRoot, "companies", ctx.slug);
893
924
 
894
- // Personal-vault default exclusions (introduced in 5.25): wrap the base
895
- // ignore filter so paths matching `PERSONAL_VAULT_DEFAULT_EXCLUSIONS` are
896
- // rejected before they upload OR enter the delete plan. Refuses & warns —
897
- // an already-leaked remote object stays put as an orphan; a separate one-
898
- // shot purge handles legacy litter.
899
- //
900
- // Out-of-policy hits are deduplicated in `excludedSet` so the same path
901
- // hitting the filter from both the upload walk and the delete-plan walk
902
- // counts once. `excludedById` powers the per-rule breakdown on the
903
- // `personal-vault-out-of-policy` event so UI can render which class
904
- // (secret / machine-local / scratch / …) did the work.
905
- //
906
- // Company-mode syncs skip this wrap entirely — company vaults have their
907
- // own first-push protection (settings/, data/, workers/, .git/) defined
908
- // in hq-sync's Rust util/ignore.rs, and a company may legitimately ship
909
- // `output/` or `.env*` paths inside its `companies/{slug}/data/` folder.
910
925
  const ignoreFilter = createIgnoreFilter(hqRoot);
911
926
  const excludedSet = new Set<string>();
912
927
  const excludedById: Record<string, number> = {};
@@ -915,12 +930,6 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
915
930
  excludedSet.add(rel);
916
931
  excludedById[match.id] = (excludedById[match.id] ?? 0) + 1;
917
932
  };
918
- // ACL scope filter (member/guest scoped push). The vended child credential
919
- // is scoped to `options.prefixSet`; any candidate outside those prefixes
920
- // would draw the server's correct 403 SCOPE_EXCEEDS_PARENT on PUT and abort
921
- // the whole company. Pre-filter the plan to the granted subset instead —
922
- // the push-side analogue of the pull leg's `skip-out-of-scope` (US-005).
923
- // `undefined` = owner/`all` → no scope filter (full access).
924
933
  const scopeExcludedSet = new Set<string>();
925
934
  const onScopeExcluded = (rel: string) => {
926
935
  scopeExcludedSet.add(rel);
@@ -932,124 +941,93 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
932
941
  ? wrapFilterWithScope(baseFilter, syncRoot, options.prefixSet, onScopeExcluded)
933
942
  : baseFilter;
934
943
  const journalSlug = options.journalSlug ?? ctx.slug;
935
- // Seed the canonical personal-vault journal from the legacy `personal` file
936
- // exactly once — engine-side so every consumer (sync-runner, hq-cli) gets
937
- // it; see the matching guard in sync.ts.
938
944
  if (journalSlug === PERSONAL_VAULT_JOURNAL_SLUG) migratePersonalVaultJournal();
939
945
  const journal = readJournal(journalSlug);
940
946
 
941
- let filesUploaded = 0;
942
- let bytesUploaded = 0;
943
- let filesSkipped = 0;
944
- let filesDeleted = 0;
945
- // Tombstone and refused-stale counts mirror the deletePlan buckets so the
946
- // ShareResult can report them without the caller having to count events.
947
- // Populated only after Stage 3 runs (deletePlan is computed first, then
948
- // mutated through the execution loop) — initial zero handles the
949
- // propagateDeletes=false path.
950
- let filesTombstoned = 0;
951
- let filesRefusedStale = 0;
952
- // Count of uploads suppressed by the push-side FILE_TOMBSTONE consult (a
953
- // behind peer's stale copy of an authoritatively-deleted key). Always 0 when
954
- // there are no tombstones for in-scope keys.
955
- let filesSuppressedByTombstone = 0;
956
- // Capped at 50 to bound event payload size — `newFiles` uses the same cap.
957
- const REFUSED_STALE_PATH_CAP = 50;
958
- const filesRefusedStalePaths: string[] = [];
959
- const conflictPaths: string[] = [];
947
+ return {
948
+ options,
949
+ paths,
950
+ message,
951
+ onConflict,
952
+ vaultConfig,
953
+ entityContext,
954
+ hqRoot,
955
+ skipUnchanged,
956
+ propagateDeletes,
957
+ propagateDeletePolicy,
958
+ emit,
959
+ companyRef,
960
+ ctx,
961
+ syncRoot,
962
+ shouldSync,
963
+ journalSlug,
964
+ journal,
965
+ excludedSet,
966
+ excludedById,
967
+ scopeExcludedSet,
968
+ };
969
+ }
960
970
 
961
- // Collect all files to share
962
- const filesToShare = collectFiles(paths, hqRoot, syncRoot, shouldSync);
963
-
964
- // Stage 1: classify each file. Pre-HEAD — only inputs we can evaluate
965
- // locally (size limit, journal hash, optional skip-unchanged) are
966
- // considered. The plan event below carries an upper-bound `filesToUpload`
967
- // (true conflicts emerge from the per-file HEAD in Stage 2 and aren't
968
- // knowable here). The final `complete` event reports authoritative counts.
969
- const plan = computePushPlan(filesToShare, journal, skipUnchanged === true);
970
-
971
- // Delete-propagation plan: walk journal entries whose key falls under the
972
- // requested scope; any whose local file is gone is a candidate for a
973
- // remote DeleteObject. Only computed when the caller opts in — `hq share
974
- // <file>` must never sweep deletes outside the explicit path list.
975
- const deleteScopeRoots = propagateDeletes === true
976
- ? resolveDeleteScopeRoots(paths, hqRoot, syncRoot)
971
+ function createShareCounters(): ShareCounters {
972
+ return {
973
+ filesUploaded: 0,
974
+ bytesUploaded: 0,
975
+ filesSkipped: 0,
976
+ filesDeleted: 0,
977
+ filesTombstoned: 0,
978
+ filesRefusedStale: 0,
979
+ filesSuppressedByTombstone: 0,
980
+ };
981
+ }
982
+
983
+ async function buildSharePlans(run: PushRunContext): Promise<SharePlans> {
984
+ const filesToShare = collectFiles(
985
+ run.paths,
986
+ run.hqRoot,
987
+ run.syncRoot,
988
+ run.shouldSync,
989
+ );
990
+ const pushPlan = computePushPlan(
991
+ filesToShare,
992
+ run.journal,
993
+ run.skipUnchanged === true,
994
+ );
995
+ const deleteScopeRoots = run.propagateDeletes === true
996
+ ? resolveDeleteScopeRoots(run.paths, run.hqRoot, run.syncRoot)
977
997
  : [];
978
- const deletePlan: DeletePlan = propagateDeletes === true
998
+ const deletePlan: DeletePlan = run.propagateDeletes === true
979
999
  ? await computeDeletePlan(
980
- journal,
981
- syncRoot,
1000
+ run.journal,
1001
+ run.syncRoot,
982
1002
  deleteScopeRoots,
983
- shouldSync,
984
- propagateDeletePolicy,
985
- ctx,
1003
+ run.shouldSync,
1004
+ run.propagateDeletePolicy,
1005
+ run.ctx,
986
1006
  )
987
1007
  : { toDelete: [], toTombstone: [], refusedStale: [] };
988
-
989
- // Decommission plan: journal entries under explicit prefixes the caller
990
- // has asserted no longer belong in this bucket (typically a promoted
991
- // company's `companies/{slug}/` keys in the personal bucket). Independent
992
- // of `propagateDeletes` and DOES NOT require the local file to be missing
993
- // — the caller is making a stronger claim than "local says delete this".
994
- // Honors the same owned-only safety policy so a misconfigured caller
995
- // can never erase content the journal records as pulled from elsewhere.
996
- // Dedupes against `deletePlan` so a key in both plans is only processed
997
- // once (DeleteObject is idempotent on S3 but the journal-write would
998
- // race a no-op pass through the loop body).
999
1008
  const decommissionPlan =
1000
- (options.decommissionPrefixes ?? []).length > 0
1009
+ (run.options.decommissionPrefixes ?? []).length > 0
1001
1010
  ? computeDecommissionPlan(
1002
- journal,
1003
- options.decommissionPrefixes ?? [],
1004
- propagateDeletePolicy,
1005
- // Dedup against `toDelete` (decommission and propagate-delete
1006
- // would both issue DeleteObject — single call wins) and against
1007
- // `toTombstone` (the remote is already 404; the tombstone loop
1008
- // drops the journal entry without a network call — decommission
1009
- // yields, both for efficiency and to avoid emitting two
1010
- // "deleted" events for the same key).
1011
- //
1012
- // We do NOT dedup against `refusedStale`. A key whose remote
1013
- // ETag drifted (peer wrote a newer version) but which decommission
1014
- // claims should still be removed — the caller has asserted this
1015
- // key doesn't belong in this bucket regardless of peer activity.
1016
- // Under owned-only (default) `computeDecommissionPlan`'s
1017
- // direction:'up' filter already excludes peer-written entries;
1018
- // under policy:'all' the caller has opted out of that safety
1019
- // anyway. The refusedStale loop below filters out keys we're
1020
- // about to decommission to avoid emitting a spurious "kept on
1021
- // remote" event for content we're deleting.
1011
+ run.journal,
1012
+ run.options.decommissionPrefixes ?? [],
1013
+ run.propagateDeletePolicy,
1022
1014
  new Set([...deletePlan.toDelete, ...deletePlan.toTombstone]),
1023
1015
  )
1024
1016
  : [];
1025
1017
 
1026
- emit({
1018
+ run.emit({
1027
1019
  type: "plan",
1028
- // share() is push-only; pull counts are sourced from sync()'s plan event.
1029
1020
  filesToDownload: 0,
1030
1021
  bytesToDownload: 0,
1031
- filesToUpload: plan.filesToUpload,
1032
- bytesToUpload: plan.bytesToUpload,
1033
- filesToSkip: plan.filesToSkip,
1034
- // Push conflicts require a remote HEAD; we don't yet do that in Stage 1,
1035
- // so this stays 0. V1.5 (single LIST) will let us classify them up-front.
1022
+ filesToUpload: pushPlan.filesToUpload,
1023
+ bytesToUpload: pushPlan.bytesToUpload,
1024
+ filesToSkip: pushPlan.filesToSkip,
1036
1025
  filesToConflict: 0,
1037
- // Reported count is the deletes we're actually going to issue — does NOT
1038
- // include tombstones (no S3 call) or refused-stale (no journal change).
1039
- // Refusals surface as their own event stream so consumers that care can
1040
- // render a "kept on remote: N" line separately. `decommissionPlan` adds
1041
- // to this count because every decommission entry IS an issued
1042
- // DeleteObject (different intent than propagate-deletes, same network
1043
- // effect).
1044
1026
  filesToDelete: deletePlan.toDelete.length + decommissionPlan.length,
1045
1027
  });
1046
1028
 
1047
- // Bulk-asymmetry summary event. Emitted once if the circuit-breaker
1048
- // tripped inside `computeDeletePlan` — see DeletePlan.bulkAsymmetry doc.
1049
- // Per-key refusal events fire later in the refusedStale loop with
1050
- // reason: "bulk-asymmetry" so the UI can also show the affected paths.
1051
1029
  if (deletePlan.bulkAsymmetry) {
1052
- emit({
1030
+ run.emit({
1053
1031
  type: "delete-refused-bulk-asymmetry",
1054
1032
  candidates: deletePlan.bulkAsymmetry.candidates,
1055
1033
  inScope: deletePlan.bulkAsymmetry.inScope,
@@ -1058,213 +1036,111 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1058
1036
  });
1059
1037
  }
1060
1038
 
1061
- // Stage 2: execute. Skip items pre-classified as no-ops, then for each
1062
- // upload candidate run the HEAD + 3-way conflict check + actual PUT.
1063
- //
1064
- // 5.36.0: upload candidates go through a bounded-concurrent pool
1065
- // (`TRANSFER_CONCURRENCY`, default 16, tunable via
1066
- // `HQ_SYNC_TRANSFER_CONCURRENCY`) for 4-8x speedup on transfer-heavy
1067
- // syncs. Skip-size-limit and skip-unchanged are handled inline first
1068
- // (pure local-state mutation). Upload candidates are collected into
1069
- // `uploadItems[]` and processed in parallel via the pool below.
1070
- //
1071
- // Abort handling: when any item's conflict resolution is "abort", we
1072
- // set `aborted = true` so the pool stops queueing new items, drain
1073
- // in-flight cleanly, and short-circuit to the abort return. In-flight
1074
- // PUTs that already issued will complete (S3 doesn't have client-side
1075
- // cancellation in this code path); their results are still recorded on
1076
- // the journal so the next sync's planner doesn't re-fire them.
1077
- // Interactive-mode prompts: when `onConflict` is unset the per-item conflict
1078
- // path calls resolveConflict()'s readline prompt on process.stdin, and two
1079
- // pool workers prompting at once would race for the terminal and interleave
1080
- // answers. The 5.36.x guard solved this by forcing the WHOLE pool to
1081
- // concurrency=1 — which made an interactive `hq sync now` crawl even when
1082
- // zero conflicts existed (every transfer serialized just in case one might
1083
- // prompt). Instead, keep full env-tunable concurrency and serialize ONLY the
1084
- // prompt (see `resolveConflictSerialized` below): at most one prompt awaits
1085
- // input at a time while transfers stay parallel.
1086
- const TRANSFER_CONCURRENCY = (() => {
1087
- const raw = process.env.HQ_SYNC_TRANSFER_CONCURRENCY;
1088
- if (raw === undefined || raw === "") return 16;
1089
- const parsed = Number.parseInt(raw, 10);
1090
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 16;
1091
- })();
1092
-
1093
- // Chained lock around the (possibly interactive) conflict prompt. Each
1094
- // resolveConflict() runs only after the previous one settles, so concurrent
1095
- // pool workers never prompt over each other on stdin — without dropping the
1096
- // transfer pool's parallelism. A rejected prompt must not wedge the chain,
1097
- // so the link swallows errors (the original promise still rejects to its
1098
- // awaiter). In non-interactive mode resolveConflict applies the configured
1099
- // strategy without reading stdin, so the lock adds no real serialization.
1039
+ return { pushPlan, deletePlan, decommissionPlan };
1040
+ }
1041
+
1042
+ async function executeUploads(
1043
+ run: PushRunContext,
1044
+ pushPlan: PushPlan,
1045
+ counters: ShareCounters,
1046
+ conflictPaths: string[],
1047
+ ): Promise<UploadExecutionResult> {
1048
+ const TRANSFER_CONCURRENCY = resolveTransferConcurrency();
1100
1049
  let conflictPromptChain: Promise<unknown> = Promise.resolve();
1101
1050
  const resolveConflictSerialized = (
1102
1051
  info: Parameters<typeof resolveConflict>[0],
1103
1052
  ): ReturnType<typeof resolveConflict> => {
1104
- const run = conflictPromptChain.then(() => resolveConflict(info, onConflict));
1105
- conflictPromptChain = run.then(
1053
+ const resolution = conflictPromptChain.then(() =>
1054
+ resolveConflict(info, run.onConflict),
1055
+ );
1056
+ conflictPromptChain = resolution.then(
1106
1057
  () => undefined,
1107
1058
  () => undefined,
1108
1059
  );
1109
- return run;
1060
+ return resolution;
1110
1061
  };
1111
1062
 
1112
- // Push-side FILE_TOMBSTONE consult (delete-resync) — symmetric to the pull
1113
- // planner's suppression in sync.ts. An authoritative delete
1114
- // (`hq files delete <prefix>`) writes a FILE_TOMBSTONE and removes the S3
1115
- // object; the pull side already honors it. But the PUSH side did not: a behind
1116
- // peer who still holds the deleted file locally would re-upload it here, and
1117
- // because the re-uploaded object post-dates the tombstone, the pull planner's
1118
- // timestamp-only re-create heuristic (`isRemoteRecreateAfterTombstone`) treats
1119
- // it as a genuine re-create and resurrects the key for EVERYONE — defeating the
1120
- // authoritative delete. Consult the tombstones so a stale-baseline upload is
1121
- // skipped at the source.
1122
- //
1123
- // Source: an injected `fileTombstones` (a sync run can hand the push leg the
1124
- // map it already fetched for the pull leg), else a self-fetch for COMPANY
1125
- // vaults that have a `vaultConfig`. Personal vaults have no company tombstones
1126
- // (the pull side skips them too), and `entityContext`-only callers have no
1127
- // auth to fetch with — both degrade to an empty map (no suppression), the
1128
- // safe/legacy direction.
1129
1063
  const fileTombstones: Map<string, CompanyTombstone> =
1130
- options.fileTombstones ??
1131
- (!ctx.uid.startsWith("prs_") && vaultConfig
1132
- ? await fetchCompanyTombstones(vaultConfig, ctx.uid)
1064
+ run.options.fileTombstones ??
1065
+ (!run.ctx.uid.startsWith("prs_") && run.vaultConfig
1066
+ ? await fetchCompanyTombstones(run.vaultConfig, run.ctx.uid)
1133
1067
  : new Map<string, CompanyTombstone>());
1134
1068
 
1135
- // Phase A: serial classification pass — handle skips inline, collect
1136
- // upload candidates for the parallel pool.
1137
- const uploadItems: Array<typeof plan.items[number] & { action: "upload" }> = [];
1138
- for (const item of plan.items) {
1069
+ const uploadItems: UploadPlanItem[] = [];
1070
+ for (const item of pushPlan.items) {
1139
1071
  if (item.action === "skip-size-limit") {
1140
- emit({
1072
+ run.emit({
1141
1073
  type: "error",
1142
1074
  path: item.relativePath,
1143
1075
  message: "file exceeds size limit",
1144
1076
  });
1145
- filesSkipped++;
1077
+ counters.filesSkipped++;
1146
1078
  continue;
1147
1079
  }
1148
- // Suppress the re-upload of an authoritatively-deleted key when the local
1149
- // copy is still the deleted baseline. Discrimination mirrors the pull side's
1150
- // `localChanged || !journalEntry` test: a journal entry whose hash matches
1151
- // the upload's localHash means the file is byte-identical to what was last
1152
- // synced i.e. the deleted version a behind peer never pulled away — so
1153
- // SKIP it. A locally-changed file (hash differs) or one with no journal
1154
- // entry is genuine new content (a real re-create or a post-delete edit) and
1155
- // uploads normally. The deleter's own stale local copy is removed by the
1156
- // pull leg's `tombstone-delete`; this guard only stops the resurrection.
1157
- if (item.action === "upload" && fileTombstones.size > 0) {
1158
- const ts = fileTombstones.get(toPosixKey(item.relativePath));
1159
- if (ts !== undefined) {
1160
- const entry = journal.files[item.relativePath];
1161
- if (entry && entry.hash === item.localHash) {
1162
- filesSuppressedByTombstone++;
1163
- emit({
1164
- type: "upload-suppressed-tombstone",
1165
- path: item.relativePath,
1166
- deletedAt: ts.deletedAt,
1167
- });
1168
- continue;
1080
+ if (item.action === "upload") {
1081
+ if (fileTombstones.size > 0) {
1082
+ const ts = fileTombstones.get(toPosixKey(item.relativePath));
1083
+ if (ts !== undefined) {
1084
+ const entry = run.journal.files[item.relativePath];
1085
+ if (entry && entry.hash === item.localHash) {
1086
+ counters.filesSuppressedByTombstone++;
1087
+ run.emit({
1088
+ type: "upload-suppressed-tombstone",
1089
+ path: item.relativePath,
1090
+ deletedAt: ts.deletedAt,
1091
+ });
1092
+ continue;
1093
+ }
1169
1094
  }
1170
1095
  }
1096
+ uploadItems.push(item);
1097
+ continue;
1171
1098
  }
1172
- if (item.action === "skip-unchanged") {
1173
- // Refresh the journal's (mtimeMs, size) for a touched-but-identical file
1174
- // so the next sync's lstat fast-path matches and skips without re-hashing.
1175
- // Guarded on item.restamp (only set when the fast-path missed AND the
1176
- // stored stat actually differs) and on the entry still carrying a hash —
1177
- // never alters the content hash, so this stays a pure no-op skip. The
1178
- // journal is persisted unconditionally by writeJournal at the end of the
1179
- // run, so this survives even when nothing uploads.
1180
- if (item.restamp) {
1181
- const existing = journal.files[item.relativePath];
1182
- if (existing && existing.hash) {
1183
- existing.mtimeMs = item.restamp.mtimeMs;
1184
- existing.size = item.restamp.size;
1185
- }
1099
+ if (item.restamp) {
1100
+ const existing = run.journal.files[item.relativePath];
1101
+ if (existing && existing.hash) {
1102
+ existing.mtimeMs = item.restamp.mtimeMs;
1103
+ existing.size = item.restamp.size;
1186
1104
  }
1187
- filesSkipped++;
1188
- continue;
1189
1105
  }
1190
- uploadItems.push(item);
1106
+ counters.filesSkipped++;
1191
1107
  }
1192
1108
 
1193
- // Batch pre-mint PUT URLs (+ the created-at HEADs) for the whole upload set,
1194
- // signing the SAME metadata the pool below computes so each task replays the
1195
- // cached headers and skips its own presign. Turns an N-file push from ~N
1196
- // presign calls into ceil(N/1000) GET + ceil(N/1000) PUT — keeping a bulk
1197
- // push under the 100/hr limit. No-op on the S3 SDK transport; best-effort.
1198
1109
  await primeUploads(
1199
- ctx,
1110
+ run.ctx,
1200
1111
  uploadItems.map((it) => ({
1201
1112
  key: it.relativePath,
1202
1113
  localPath: it.absolutePath,
1203
1114
  isSymlink: it.kind === "symlink",
1204
- author: options.author,
1115
+ author: run.options.author,
1205
1116
  })),
1206
1117
  );
1118
+ // Warm the GET presigns the per-item conflict HEAD (remoteMeta) reuses, so a
1119
+ // large upload set doesn't mint one presign per HEAD and burst/trip the
1120
+ // presign breaker. Mirrors the new-files + tombstone pre-primes on the pull.
1121
+ await primeObjectTransport(
1122
+ run.ctx,
1123
+ "get",
1124
+ uploadItems.map((it) => it.relativePath),
1125
+ );
1207
1126
 
1208
- // Phase B: parallel upload pool. Each task runs the full per-item flow
1209
- // (HEAD + conflict + PUT + journal stamp + emit). Aborts flip the
1210
- // shared `aborted` flag and the pool stops draining the queue; tasks
1211
- // already in flight complete normally.
1212
1127
  let aborted = false;
1213
1128
  let abortFlightConflictPaths: string[] = [];
1214
1129
 
1215
- const processUploadItem = async (
1216
- item: typeof uploadItems[number],
1217
- ): Promise<void> => {
1130
+ const processUploadItem = async (item: UploadPlanItem): Promise<void> => {
1218
1131
  if (aborted) return;
1219
1132
  const { absolutePath, relativePath, localHash } = item;
1220
1133
 
1221
- // Auto-refresh context if credentials expiring. Only available on the
1222
- // vaultConfig path pre-vended contexts have no source to re-vend
1223
- // from, so we let the AWS SDK surface ExpiredToken naturally on the
1224
- // PUT below if the caller under-vended.
1225
- if (vaultConfig && isExpiringSoon(ctx.expiresAt)) {
1226
- ctx = await refreshEntityContext(companyRef, vaultConfig);
1134
+ if (run.vaultConfig && isExpiringSoon(run.ctx.expiresAt)) {
1135
+ run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
1227
1136
  }
1228
1137
 
1229
- // Check for remote conflict — refuse to overwrite newer remote version.
1230
- //
1231
- // A real conflict requires BOTH sides to have moved since the last sync.
1232
- // The previous predicate only checked `journalEntry.hash !== localHash`,
1233
- // which mislabelled every local edit as a conflict and (combined with
1234
- // `--on-conflict keep`) silently dropped the user's edit. We now compare
1235
- // the current remote ETag against the one captured at last sync; when
1236
- // missing (legacy entries), we fall back to the same `lastModified >
1237
- // syncedAt` heuristic the pull side uses.
1238
- //
1239
- // Bug #7 (data-loss class — see workspace/reports/hq-cloud-5.33.0-
1240
- // deep-test.md): for a path with NO prior journal entry (first push
1241
- // from this machine), the localChanged/remoteChanged predicates above
1242
- // both evaluate FALSE (their guards require `!!journalEntry`). Push
1243
- // fell through to an unconditional PUT, silently clobbering any
1244
- // peer's content already at that key. The verification report's V7
1245
- // isolated this — the bug is independent of \`--on-conflict\` mode;
1246
- // it's keyed on "do I have a prior journal entry?" not on the flag.
1247
- //
1248
- // Fresh-collision branch: when remoteMeta exists and there's no
1249
- // journal entry, hash the local body (MD5 for parity with S3's
1250
- // single-part etag) and compare. Match → no conflict, silently skip
1251
- // the PUT (the bytes are already there). Mismatch → treat as a
1252
- // conflict in the same shared branch below.
1253
- // Defense-in-depth for the scoped-push 403: the `prefixSet` filter above
1254
- // should already have dropped any out-of-scope key from the plan, but a
1255
- // grant that changed mid-run, a pinned prefix outside the grant, or
1256
- // prefix-coalesce imprecision can still leave an out-of-scope key here.
1257
- // This HEAD sits OUTSIDE the per-file PUT try/catch below, so a thrown
1258
- // 403 used to bubble to `workerErrors` and abort the ENTIRE company with
1259
- // a generic message and exit 2. Catch the access-denied class, surface
1260
- // the offending PATH clearly, and skip just this key — the rest of the
1261
- // company still syncs. Non-access-denied errors re-throw unchanged.
1262
1138
  let remoteMeta: Awaited<ReturnType<typeof headRemoteFile>>;
1263
1139
  try {
1264
- remoteMeta = await headRemoteFile(ctx, relativePath);
1140
+ remoteMeta = await headRemoteFile(run.ctx, relativePath);
1265
1141
  } catch (headErr) {
1266
1142
  if (isAccessDenied(headErr)) {
1267
- emit({
1143
+ run.emit({
1268
1144
  type: "error",
1269
1145
  path: relativePath,
1270
1146
  message:
@@ -1277,21 +1153,15 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1277
1153
  throw headErr;
1278
1154
  }
1279
1155
  if (remoteMeta) {
1280
- const journalEntry = journal.files[relativePath];
1156
+ const journalEntry = run.journal.files[relativePath];
1281
1157
  const localChanged = !!journalEntry && journalEntry.hash !== localHash;
1282
1158
  const remoteChanged = !!journalEntry && hasRemoteChanged(remoteMeta, journalEntry);
1283
1159
 
1284
1160
  let isFreshCollision = false;
1285
1161
  let multipartConverged = false;
1286
1162
  if (!journalEntry && item.kind === "symlink") {
1287
- // A HEAD on an existing object does not expose the symlink target.
1288
- // On a first sync, treat the existing remote as a fresh collision
1289
- // instead of replacing it with the local link record.
1290
1163
  isFreshCollision = true;
1291
1164
  } else if (!journalEntry && item.kind === "file") {
1292
- // Single-part S3 PUT etag is MD5 of the body. Multipart uploads
1293
- // produce `<md5>-<partCount>`. Symlink records cannot be classified
1294
- // from HEAD alone, so the branch above fails closed.
1295
1165
  const remoteEtagNormalized = normalizeEtag(remoteMeta.etag);
1296
1166
  const isMultipart = /-\d+$/.test(remoteEtagNormalized);
1297
1167
  if (!isMultipart) {
@@ -1300,38 +1170,16 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1300
1170
  if (localMd5 !== remoteEtagNormalized) {
1301
1171
  isFreshCollision = true;
1302
1172
  }
1303
- // Match → bytes are already there; fall through to upload
1304
- // path which is idempotent (S3 will overwrite with identical
1305
- // content + carry our metadata). Cheap, no behavior change.
1306
1173
  } else {
1307
- // Multipart remote etag is \`<md5>-<partCount>\`, NOT a usable
1308
- // content hash, so — unlike the single-part branch — we cannot
1309
- // decide collision-vs-identical from the etag alone. The old
1310
- // behavior assumed a collision here, which minted a FALSE
1311
- // conflict for the most common fresh-install case: re-pushing a
1312
- // byte-identical \`core/\` scaffold file whose remote copy happened
1313
- // to be multipart-uploaded. Every fresh install that hit an
1314
- // already-populated bucket therefore came up "with conflicts".
1315
- //
1316
- // Instead, fetch the remote bytes once and compare content
1317
- // hashes directly — the same convergence guard the pull side
1318
- // uses (sync.ts). Identical content is NOT a conflict. On any
1319
- // fetch/hash failure we fail safe to "conflict" (false positives
1320
- // prompt the operator; false negatives risk clobbering a peer).
1321
1174
  const remoteDiffers = await remoteContentDiffers(
1322
- ctx,
1175
+ run.ctx,
1323
1176
  relativePath,
1324
1177
  localHash,
1325
- hqRoot,
1178
+ run.hqRoot,
1326
1179
  );
1327
1180
  if (remoteDiffers) {
1328
1181
  isFreshCollision = true;
1329
1182
  } else {
1330
- // Byte-identical multipart object already present. Seed the
1331
- // journal baseline from the remote so the next sync sees no
1332
- // change on either side, and skip the redundant PUT —
1333
- // re-uploading would needlessly rewrite remote and churn its
1334
- // etag from multipart to single-part.
1335
1183
  multipartConverged = true;
1336
1184
  }
1337
1185
  }
@@ -1340,7 +1188,7 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1340
1188
  if (multipartConverged) {
1341
1189
  const lstat = fs.lstatSync(absolutePath);
1342
1190
  updateEntry(
1343
- journal,
1191
+ run.journal,
1344
1192
  relativePath,
1345
1193
  localHash,
1346
1194
  lstat.size,
@@ -1348,8 +1196,8 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1348
1196
  remoteMeta.etag,
1349
1197
  lstat.mtimeMs,
1350
1198
  );
1351
- emit({ type: "reconciled", path: relativePath, direction: "push" });
1352
- filesSkipped++;
1199
+ run.emit({ type: "reconciled", path: relativePath, direction: "push" });
1200
+ counters.filesSkipped++;
1353
1201
  return;
1354
1202
  }
1355
1203
 
@@ -1363,7 +1211,7 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1363
1211
  direction: "push",
1364
1212
  });
1365
1213
 
1366
- emit({
1214
+ run.emit({
1367
1215
  type: "conflict",
1368
1216
  path: relativePath,
1369
1217
  direction: "push",
@@ -1371,132 +1219,51 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1371
1219
  });
1372
1220
 
1373
1221
  if (resolution === "abort") {
1374
- // Flip the shared aborted flag — the pool drainer below sees this
1375
- // and stops queueing new items. In-flight tasks complete normally
1376
- // (S3 PUTs have no client-side cancel here). The outer abort
1377
- // return is built after the pool drains.
1378
1222
  aborted = true;
1379
1223
  abortFlightConflictPaths = [...conflictPaths];
1380
1224
  return;
1381
1225
  }
1382
1226
  if (resolution === "keep" || resolution === "skip") {
1383
- // Bug #7 mirror branch: when the resolution is keep/skip on a
1384
- // FRESH collision (no prior journal entry), download the
1385
- // remote bytes to \`<orig>.conflict-<ts>-<short>\` so both
1386
- // versions survive on disk. Mirrors the pull-side mirror-write
1387
- // routine in sync.ts exactly. Skipped for stale-journal
1388
- // conflicts (the pre-Bug-#7 codepath) — those already produce
1389
- // a pull-side mirror on the next sync cycle.
1390
1227
  if (isFreshCollision) {
1391
- try {
1392
- const detectedAt = new Date().toISOString();
1393
- const machineId = readShortMachineId(hqRoot);
1394
- const originalRelative = path.relative(hqRoot, absolutePath);
1395
- const conflictRelative = buildConflictPath(
1396
- originalRelative,
1397
- detectedAt,
1398
- machineId,
1399
- );
1400
- const conflictAbs = path.join(hqRoot, conflictRelative);
1401
- if (!isMaterializationPathStillContained(syncRoot, conflictAbs)) {
1402
- emit({
1403
- type: "error",
1404
- path: relativePath,
1405
- message: "conflict mirror skipped: local parent escaped the sync root",
1406
- });
1407
- } else {
1408
- await downloadFile(ctx, relativePath, conflictAbs);
1409
- appendConflictEntry(hqRoot, {
1410
- id: buildConflictId(originalRelative, detectedAt),
1411
- originalPath: originalRelative,
1412
- conflictPath: conflictRelative,
1413
- detectedAt,
1414
- side: "push",
1415
- machineId,
1416
- localHash,
1417
- remoteHash: normalizeEtag(remoteMeta.etag),
1418
- });
1419
- }
1420
- } catch (mirrorErr) {
1421
- emit({
1422
- type: "error",
1423
- path: relativePath,
1424
- message: `conflict mirror write failed: ${
1425
- mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)
1426
- }`,
1427
- });
1428
- }
1228
+ await writePushConflictMirror(run, item, normalizeEtag(remoteMeta.etag));
1429
1229
  }
1430
- filesSkipped++;
1230
+ counters.filesSkipped++;
1431
1231
  return;
1432
1232
  }
1433
- // "overwrite" falls through to upload
1434
1233
  }
1435
1234
  }
1436
1235
 
1437
- // Re-check abort flag right before the PUT — if a peer task aborted
1438
- // while we were waiting on HEAD, skip the PUT entirely. This is
1439
- // belt-and-suspenders alongside the queue-drain check; without it,
1440
- // up to TRANSFER_CONCURRENCY in-flight uploads could still issue PUTs
1441
- // after the user signaled abort.
1442
1236
  if (aborted) return;
1443
1237
 
1444
- // Conditional-write fence (storage-level backstop for the entire
1445
- // stale-clobber class). Every PUT asserts the remote state this pass
1446
- // just inspected:
1447
- // - remote exists → If-Match on the observed etag ("replace exactly
1448
- // what I HEAD'd"). Closes the HEAD→PUT TOCTOU: a peer's write
1449
- // landing in the window makes S3 itself reject with 412 instead of
1450
- // this machine silently regressing the object.
1451
- // - remote absent → If-None-Match:* ("create only"). If the HEAD was
1452
- // wrong about absence (any transport/state bug — the 2026-06-10..12
1453
- // regression storm's shape), the PUT 412s instead of clobbering.
1454
- // Enforced natively on the SDK transport; on the presigned transport it
1455
- // activates when files-presign signs the headers (see object-io.ts).
1456
1238
  const precondition: PutPrecondition = remoteMeta
1457
1239
  ? { ifMatch: remoteMeta.etag }
1458
1240
  : { ifNoneMatch: "*" };
1459
1241
 
1460
- // Upload — symlinks go through uploadSymlink (zero-byte body + target
1461
- // metadata), regular files through uploadFile (file contents). The
1462
- // discriminator is item.kind set by computePushPlan; both branches
1463
- // converge on the same journal/event update path below. Factored into a
1464
- // closure so the 412 "overwrite" resolution below can re-run it without
1465
- // the fence after explicit user consent.
1466
1242
  const performUpload = async (pc: PutPrecondition | undefined): Promise<void> => {
1467
1243
  const isSymlinkUpload = item.kind === "symlink";
1468
- // Capture lstat post-upload so size + mtimeMs stamped into the
1469
- // journal reflect the bytes we actually shipped. lstat (not stat)
1470
- // so a symlink stamps the link's own mtime, not the target's —
1471
- // matches the fast-path's lstat comparison so the next sync can
1472
- // skip without dereferencing.
1473
1244
  const lstat = fs.lstatSync(absolutePath);
1474
1245
  const size = isSymlinkUpload ? 0 : lstat.size;
1475
1246
  const mtimeMs = lstat.mtimeMs;
1476
1247
 
1477
1248
  const { etag } = isSymlinkUpload
1478
- ? await uploadSymlink(ctx, item.target, relativePath, options.author, pc)
1479
- : await uploadFile(ctx, absolutePath, relativePath, options.author, pc);
1480
-
1481
- // Update journal with optional message; capture the post-upload ETag
1482
- // so the next sync can distinguish "remote moved since we last wrote"
1483
- // from "user edited locally" without conflating the two. mtimeMs
1484
- // feeds the 5.36.0 lstat fast-path on the next push.
1485
- updateEntry(journal, relativePath, localHash, size, "up", etag, mtimeMs);
1486
- if (message) {
1487
- journal.files[relativePath] = {
1488
- ...journal.files[relativePath],
1489
- message,
1490
- } as typeof journal.files[string] & { message: string };
1249
+ ? await uploadSymlink(run.ctx, item.target, relativePath, run.options.author, pc)
1250
+ : await uploadFile(run.ctx, absolutePath, relativePath, run.options.author, pc);
1251
+
1252
+ updateEntry(run.journal, relativePath, localHash, size, "up", etag, mtimeMs);
1253
+ if (run.message) {
1254
+ run.journal.files[relativePath] = {
1255
+ ...run.journal.files[relativePath],
1256
+ message: run.message,
1257
+ } as JournalFileEntry & { message: string };
1491
1258
  }
1492
1259
 
1493
- filesUploaded++;
1494
- bytesUploaded += size;
1495
- emit({
1260
+ counters.filesUploaded++;
1261
+ counters.bytesUploaded += size;
1262
+ run.emit({
1496
1263
  type: "progress",
1497
1264
  path: relativePath,
1498
1265
  bytes: size,
1499
- ...(message ? { message } : {}),
1266
+ ...(run.message ? { message: run.message } : {}),
1500
1267
  });
1501
1268
  };
1502
1269
 
@@ -1504,17 +1271,13 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1504
1271
  await performUpload(precondition);
1505
1272
  } catch (err) {
1506
1273
  if (isPreconditionFailed(err)) {
1507
- // The fence fired: the remote moved past (If-Match) or appeared at
1508
- // (If-None-Match) this key between our HEAD and the PUT — exactly
1509
- // the race the fence exists to catch. Surface as a push conflict;
1510
- // never silently overwrite.
1511
1274
  conflictPaths.push(relativePath);
1512
1275
  const resolution = await resolveConflictSerialized({
1513
1276
  path: relativePath,
1514
1277
  localHash,
1515
1278
  direction: "push",
1516
1279
  });
1517
- emit({
1280
+ run.emit({
1518
1281
  type: "conflict",
1519
1282
  path: relativePath,
1520
1283
  direction: "push",
@@ -1526,12 +1289,10 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1526
1289
  return;
1527
1290
  }
1528
1291
  if (resolution === "overwrite") {
1529
- // Explicit clobber consent — retry once without the fence. A
1530
- // second failure falls through to the generic error emit.
1531
1292
  try {
1532
1293
  await performUpload(undefined);
1533
1294
  } catch (retryErr) {
1534
- emit({
1295
+ run.emit({
1535
1296
  type: "error",
1536
1297
  path: relativePath,
1537
1298
  message:
@@ -1540,54 +1301,15 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1540
1301
  }
1541
1302
  return;
1542
1303
  }
1543
- // keep/skip: preserve the racing remote next to the local copy so
1544
- // both versions survive — same mirror routine as the fresh-collision
1545
- // branch above.
1546
- try {
1547
- const detectedAt = new Date().toISOString();
1548
- const machineId = readShortMachineId(hqRoot);
1549
- const originalRelative = path.relative(hqRoot, absolutePath);
1550
- const conflictRelative = buildConflictPath(
1551
- originalRelative,
1552
- detectedAt,
1553
- machineId,
1554
- );
1555
- const conflictAbs = path.join(hqRoot, conflictRelative);
1556
- if (!isMaterializationPathStillContained(syncRoot, conflictAbs)) {
1557
- emit({
1558
- type: "error",
1559
- path: relativePath,
1560
- message: "conflict mirror skipped: local parent escaped the sync root",
1561
- });
1562
- } else {
1563
- await downloadFile(ctx, relativePath, conflictAbs);
1564
- appendConflictEntry(hqRoot, {
1565
- id: buildConflictId(originalRelative, detectedAt),
1566
- originalPath: originalRelative,
1567
- conflictPath: conflictRelative,
1568
- detectedAt,
1569
- side: "push",
1570
- machineId,
1571
- localHash,
1572
- // remoteMeta (if any) predates the racing write that fired the
1573
- // fence — record what we knew ("" when the key was believed
1574
- // absent); the mirror file carries the authoritative remote bytes.
1575
- remoteHash: remoteMeta ? normalizeEtag(remoteMeta.etag) : "",
1576
- });
1577
- }
1578
- } catch (mirrorErr) {
1579
- emit({
1580
- type: "error",
1581
- path: relativePath,
1582
- message: `conflict mirror write failed: ${
1583
- mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)
1584
- }`,
1585
- });
1586
- }
1587
- filesSkipped++;
1304
+ await writePushConflictMirror(
1305
+ run,
1306
+ item,
1307
+ remoteMeta ? normalizeEtag(remoteMeta.etag) : "",
1308
+ );
1309
+ counters.filesSkipped++;
1588
1310
  return;
1589
1311
  }
1590
- emit({
1312
+ run.emit({
1591
1313
  type: "error",
1592
1314
  path: relativePath,
1593
1315
  message: isAccessDenied(err)
@@ -1601,25 +1323,6 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1601
1323
  }
1602
1324
  };
1603
1325
 
1604
- // Drain the upload queue with bounded concurrency. Per-file progress
1605
- // events fire from inside processUploadItem at file-settle time, so
1606
- // cross-file event ordering is settle-order, not plan-walk-order — the
1607
- // menubar's stream parser already tolerates per-company interleave so
1608
- // this is shape-compatible. allSettled-style waiting (via Promise.race
1609
- // on the in-flight set) keeps the pool topped up without idling on slow
1610
- // members.
1611
- //
1612
- // Codex P1 (5.36.x): each worker promise is wrapped in a .catch that
1613
- // records the error to `workerErrors` and resolves normally — so
1614
- // `Promise.race(inFlight)` can never reject and unwind the drain loop
1615
- // mid-flight. Without the wrap, an unhandled rejection inside
1616
- // processUploadItem (e.g. headRemoteFile or refreshEntityContext, both
1617
- // of which sit outside the per-item PUT try/catch) bubbled out of the
1618
- // race, abandoned still-in-flight uploads that kept mutating remote
1619
- // state, and skipped writeJournal — leaving remote and journal
1620
- // permanently out of sync for the next run. After the pool fully
1621
- // drains we throw an aggregated error so the caller still surfaces the
1622
- // failure (and the journal reflects the writes that actually landed).
1623
1326
  const workerErrors: Error[] = [];
1624
1327
  {
1625
1328
  const queue = [...uploadItems];
@@ -1639,96 +1342,86 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1639
1342
  if (inFlight.size > 0) {
1640
1343
  await Promise.race(Array.from(inFlight));
1641
1344
  } else {
1642
- // Aborted with nothing in flight → exit the drain loop.
1643
1345
  break;
1644
1346
  }
1645
1347
  }
1646
1348
  }
1647
1349
 
1648
- if (aborted) {
1649
- return {
1650
- filesUploaded,
1651
- bytesUploaded,
1652
- filesSkipped,
1653
- filesDeleted,
1654
- // Abort path: delete stage never runs, so tombstone + refused-
1655
- // stale counts are necessarily zero. Explicit fields keep the
1656
- // ShareResult shape stable for consumers that destructure.
1657
- filesTombstoned,
1658
- filesRefusedStale,
1659
- // Always present so consumers can destructure without a
1660
- // defaulting fallback. Empty on the abort path because the
1661
- // delete-plan execution loop is short-circuited.
1662
- filesRefusedStalePaths,
1663
- // Tombstone-suppressed uploads are classified in Phase A, which runs
1664
- // before the upload pool can abort, so the count is meaningful here.
1665
- filesSuppressedByTombstone,
1666
- // Exclusions are computed during the upload walk which has
1667
- // already completed by the time we hit a per-file conflict-
1668
- // abort, so the count is meaningful here. No event emit on
1669
- // abort (matches the existing convention: abort short-circuits
1670
- // before the end-of-run telemetry emits).
1671
- filesExcludedByPolicy: excludedSet.size,
1672
- // Scope exclusions are likewise computed during the upload walk, so the
1673
- // count is meaningful on the abort path too.
1674
- filesExcludedByScope: scopeExcludedSet.size,
1675
- // Use the snapshot of conflictPaths taken at the moment the abort
1676
- // fired — additional in-flight items may have appended to the
1677
- // shared array after the abort signal, and those should not show
1678
- // up in the abort result.
1679
- conflictPaths: abortFlightConflictPaths,
1680
- aborted: true,
1681
- };
1350
+ return { aborted, abortFlightConflictPaths, workerErrors };
1351
+ }
1352
+
1353
+ async function writePushConflictMirror(
1354
+ run: PushRunContext,
1355
+ item: UploadPlanItem,
1356
+ remoteHash: string,
1357
+ ): Promise<void> {
1358
+ try {
1359
+ const detectedAt = new Date().toISOString();
1360
+ const machineId = readShortMachineId(run.hqRoot);
1361
+ const originalRelative = path.relative(run.hqRoot, item.absolutePath);
1362
+ const conflictRelative = buildConflictPath(
1363
+ originalRelative,
1364
+ detectedAt,
1365
+ machineId,
1366
+ );
1367
+ const conflictAbs = path.join(run.hqRoot, conflictRelative);
1368
+ if (!isMaterializationPathStillContained(run.syncRoot, conflictAbs)) {
1369
+ run.emit({
1370
+ type: "error",
1371
+ path: item.relativePath,
1372
+ message: "conflict mirror skipped: local parent escaped the sync root",
1373
+ });
1374
+ } else {
1375
+ await downloadFile(run.ctx, item.relativePath, conflictAbs);
1376
+ appendConflictEntry(run.hqRoot, {
1377
+ id: buildConflictId(originalRelative, detectedAt),
1378
+ originalPath: originalRelative,
1379
+ conflictPath: conflictRelative,
1380
+ detectedAt,
1381
+ side: "push",
1382
+ machineId,
1383
+ localHash: item.localHash,
1384
+ remoteHash,
1385
+ });
1386
+ }
1387
+ } catch (mirrorErr) {
1388
+ run.emit({
1389
+ type: "error",
1390
+ path: item.relativePath,
1391
+ message:
1392
+ "conflict mirror write failed: " +
1393
+ (mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)),
1394
+ });
1682
1395
  }
1396
+ }
1683
1397
 
1684
- // Stage 3: propagate deletes. Three buckets, three actions:
1685
- //
1686
- // 1. `toDelete` (PLUS `decommissionPlan` concatenated in) — write a
1687
- // delete-marker (versioning is enabled on the bucket so the delete
1688
- // is soft and prior versions remain recoverable) and remove the
1689
- // journal entry so the next sync sees the key as truly gone on
1690
- // this machine. A failed DeleteObject leaves both the journal
1691
- // entry and remote object intact — the next run retries.
1692
- // Decommission keys join this bucket because their effect is
1693
- // identical (DeleteObject + journal removal); the difference is
1694
- // intent only, and the dedupe at plan-computation time ensures we
1695
- // don't double-issue for a key both plans matched.
1696
- //
1697
- // 2. `toTombstone` — the remote was 404 at HEAD time (cleaned up out
1698
- // of band, e.g. someone hand-deleted via console). No DeleteObject
1699
- // needed; just drop the journal entry so the journal converges with
1700
- // reality. Emit a synthetic `progress` event with `deleted: true`
1701
- // and bytes=0 so consumers see the convergence.
1702
- //
1703
- // 3. `refusedStale` — under `currency-gated`, the remote's current
1704
- // ETag no longer matches the journal's recorded one. Some other
1705
- // device modified the file since this device last synced it. Keep
1706
- // the remote intact; keep the journal entry intact. The next pull
1707
- // leg of `sync now` re-pulls naturally via the existing
1708
- // `hasRemoteChanged` path. Emit a dedicated event so UIs can
1709
- // surface the refusal without inferring it from absence.
1710
- // Batch pre-mint DELETE URLs so a large delete set is ~ceil(N/1000) presign
1711
- // calls, not N. No-op on the S3 SDK transport; best-effort.
1398
+ async function executeDeletes(
1399
+ run: PushRunContext,
1400
+ deletePlan: DeletePlan,
1401
+ decommissionPlan: string[],
1402
+ counters: ShareCounters,
1403
+ filesRefusedStalePaths: string[],
1404
+ ): Promise<void> {
1712
1405
  const deleteKeys = [...deletePlan.toDelete, ...decommissionPlan];
1713
- await primeObjectTransport(ctx, "delete", deleteKeys);
1406
+ await primeObjectTransport(run.ctx, "delete", deleteKeys);
1714
1407
  for (const relativePath of deleteKeys) {
1715
- if (vaultConfig && isExpiringSoon(ctx.expiresAt)) {
1716
- ctx = await refreshEntityContext(companyRef, vaultConfig);
1408
+ if (run.vaultConfig && isExpiringSoon(run.ctx.expiresAt)) {
1409
+ run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
1717
1410
  }
1718
1411
  try {
1719
- const entry = journal.files[relativePath];
1412
+ const entry = run.journal.files[relativePath];
1720
1413
  const size = entry?.size ?? 0;
1721
- await deleteRemoteFile(ctx, relativePath);
1722
- removeEntry(journal, relativePath);
1723
- filesDeleted++;
1724
- emit({
1414
+ await deleteRemoteFile(run.ctx, relativePath);
1415
+ removeEntry(run.journal, relativePath);
1416
+ counters.filesDeleted++;
1417
+ run.emit({
1725
1418
  type: "progress",
1726
1419
  path: relativePath,
1727
1420
  bytes: size,
1728
1421
  deleted: true,
1729
1422
  });
1730
1423
  } catch (err) {
1731
- emit({
1424
+ run.emit({
1732
1425
  type: "error",
1733
1426
  path: relativePath,
1734
1427
  message: err instanceof Error ? err.message : String(err),
@@ -1736,9 +1429,9 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1736
1429
  }
1737
1430
  }
1738
1431
  for (const relativePath of deletePlan.toTombstone) {
1739
- removeEntry(journal, relativePath);
1740
- filesTombstoned++;
1741
- emit({
1432
+ removeEntry(run.journal, relativePath);
1433
+ counters.filesTombstoned++;
1434
+ run.emit({
1742
1435
  type: "progress",
1743
1436
  path: relativePath,
1744
1437
  bytes: 0,
@@ -1746,20 +1439,15 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1746
1439
  message: "tombstone (remote already 404)",
1747
1440
  });
1748
1441
  }
1749
- // Decommission overrides refusedStale: a key whose peer drifted but
1750
- // which the caller has claimed via `decommissionPrefixes` is processed
1751
- // by the DeleteObject loop above; skip the refusal event here so the
1752
- // event stream doesn't simultaneously claim "we deleted it" and "we
1753
- // kept it on remote" for the same key.
1754
1442
  const decommissionedSet =
1755
1443
  decommissionPlan.length > 0 ? new Set(decommissionPlan) : null;
1756
1444
  for (const refused of deletePlan.refusedStale) {
1757
1445
  if (decommissionedSet && decommissionedSet.has(refused.key)) continue;
1758
- filesRefusedStale++;
1446
+ counters.filesRefusedStale++;
1759
1447
  if (filesRefusedStalePaths.length < REFUSED_STALE_PATH_CAP) {
1760
1448
  filesRefusedStalePaths.push(refused.key);
1761
1449
  }
1762
- emit({
1450
+ run.emit({
1763
1451
  type: "delete-refused-stale-etag",
1764
1452
  path: refused.key,
1765
1453
  journalEtag: refused.journalEtag,
@@ -1767,78 +1455,74 @@ export async function share(options: ShareOptions): Promise<ShareResult> {
1767
1455
  reason: refused.reason,
1768
1456
  });
1769
1457
  }
1458
+ }
1770
1459
 
1771
- // See cli/sync.ts: stamp lastSync on completion so a no-op share still
1772
- // ticks the "Last sync" indicator.
1773
- journal.lastSync = new Date().toISOString();
1774
- writeJournal(journalSlug, journal);
1460
+ function finalizeShareJournal(run: PushRunContext): void {
1461
+ run.journal.lastSync = new Date().toISOString();
1462
+ writeJournal(run.journalSlug, run.journal);
1775
1463
 
1776
- // Personal-vault out-of-policy summary. Emit at most once, only when at
1777
- // least one path was excluded. Sample is capped at 10 to keep the event
1778
- // small (Set iteration order = insertion order, so samples are the first
1779
- // ten paths encountered during the walk — deterministic, not random).
1780
- if (excludedSet.size > 0) {
1464
+ if (run.excludedSet.size > 0) {
1781
1465
  const samplePaths: string[] = [];
1782
- for (const p of excludedSet) {
1466
+ for (const p of run.excludedSet) {
1783
1467
  samplePaths.push(p);
1784
1468
  if (samplePaths.length >= 10) break;
1785
1469
  }
1786
- emit({
1470
+ run.emit({
1787
1471
  type: "personal-vault-out-of-policy",
1788
- count: excludedSet.size,
1472
+ count: run.excludedSet.size,
1789
1473
  samplePaths,
1790
- byId: { ...excludedById },
1474
+ byId: { ...run.excludedById },
1791
1475
  });
1792
1476
  }
1793
1477
 
1794
- // ACL scope-exclusion summary. Emit at most once when one or more candidate
1795
- // paths fell outside the run's granted `prefixSet` and were skipped from the
1796
- // upload/delete plan. Informational (NOT an error): the company still syncs
1797
- // its in-scope subset and the run exits 0. Sample capped at 10 (insertion
1798
- // order = walk order, deterministic).
1799
- if (scopeExcludedSet.size > 0) {
1478
+ if (run.scopeExcludedSet.size > 0) {
1800
1479
  const samplePaths: string[] = [];
1801
- for (const p of scopeExcludedSet) {
1480
+ for (const p of run.scopeExcludedSet) {
1802
1481
  samplePaths.push(p);
1803
1482
  if (samplePaths.length >= 10) break;
1804
1483
  }
1805
- emit({
1484
+ run.emit({
1806
1485
  type: "scope-excluded",
1807
- count: scopeExcludedSet.size,
1486
+ count: run.scopeExcludedSet.size,
1808
1487
  samplePaths,
1809
1488
  });
1810
1489
  }
1490
+ }
1811
1491
 
1812
- // Codex P1 (5.36.x): if any worker rejected (unhandled error in
1813
- // headRemoteFile / refreshEntityContext / resolveConflict — paths
1814
- // outside the per-item PUT try/catch), we deliberately let the pool
1815
- // drain AND let post-pool stages (deletes, tombstones, journal write,
1816
- // personal-vault summary) run to completion so journal + remote stay
1817
- // converged on what actually landed. NOW surface the failure to the
1818
- // caller — preserving the first error's stack so debugging works.
1819
- // Aggregate count is reported in the message for visibility when
1820
- // multiple workers failed.
1492
+ function throwUploadWorkerErrors(workerErrors: Error[]): void {
1821
1493
  if (workerErrors.length > 0) {
1822
1494
  const first = workerErrors[0]!;
1823
1495
  if (workerErrors.length > 1) {
1824
- first.message = `${first.message} (and ${workerErrors.length - 1} more upload-worker errors)`;
1496
+ first.message =
1497
+ first.message +
1498
+ " (and " +
1499
+ (workerErrors.length - 1) +
1500
+ " more upload-worker errors)";
1825
1501
  }
1826
1502
  throw first;
1827
1503
  }
1504
+ }
1828
1505
 
1506
+ function buildShareResult(
1507
+ run: PushRunContext,
1508
+ counters: ShareCounters,
1509
+ filesRefusedStalePaths: string[],
1510
+ conflictPaths: string[],
1511
+ aborted: boolean,
1512
+ ): ShareResult {
1829
1513
  return {
1830
- filesUploaded,
1831
- bytesUploaded,
1832
- filesSkipped,
1833
- filesDeleted,
1834
- filesTombstoned,
1835
- filesRefusedStale,
1514
+ filesUploaded: counters.filesUploaded,
1515
+ bytesUploaded: counters.bytesUploaded,
1516
+ filesSkipped: counters.filesSkipped,
1517
+ filesDeleted: counters.filesDeleted,
1518
+ filesTombstoned: counters.filesTombstoned,
1519
+ filesRefusedStale: counters.filesRefusedStale,
1836
1520
  filesRefusedStalePaths,
1837
- filesSuppressedByTombstone,
1838
- filesExcludedByPolicy: excludedSet.size,
1839
- filesExcludedByScope: scopeExcludedSet.size,
1521
+ filesSuppressedByTombstone: counters.filesSuppressedByTombstone,
1522
+ filesExcludedByPolicy: run.excludedSet.size,
1523
+ filesExcludedByScope: run.scopeExcludedSet.size,
1840
1524
  conflictPaths,
1841
- aborted: false,
1525
+ aborted,
1842
1526
  };
1843
1527
  }
1844
1528
 
@@ -1901,22 +1585,6 @@ function defaultConsoleLogger(event: SyncProgressEvent): void {
1901
1585
  }
1902
1586
  }
1903
1587
 
1904
- /**
1905
- * Resolve active company from .hq/config.json or parent directory chain.
1906
- */
1907
- function resolveActiveCompany(hqRoot: string): string | undefined {
1908
- const configPath = path.join(hqRoot, ".hq", "config.json");
1909
- if (fs.existsSync(configPath)) {
1910
- try {
1911
- const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
1912
- return config.activeCompany ?? config.companySlug;
1913
- } catch {
1914
- // Ignore parse errors
1915
- }
1916
- }
1917
- return undefined;
1918
- }
1919
-
1920
1588
  /**
1921
1589
  * One entry produced by collectFiles/walkDir. Files describe regular
1922
1590
  * payloads that get hashed + size-checked + uploaded via uploadFile;
@@ -2181,24 +1849,6 @@ function isWithinForLink(parent: string, linkPath: string): boolean {
2181
1849
  return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
2182
1850
  }
2183
1851
 
2184
- /**
2185
- * Returns true when the remote object appears to have moved since the
2186
- * journal entry's last-recorded sync. Prefers ETag equality; falls back to
2187
- * `lastModified > syncedAt` for legacy entries written before remoteEtag
2188
- * was tracked. Conservative on tie (`<=` skews "remote unchanged") so an
2189
- * S3-side mtime that exactly equals our syncedAt is not treated as drift.
2190
- */
2191
- function hasRemoteChanged(
2192
- remote: { lastModified: Date; etag: string },
2193
- entry: { syncedAt: string; remoteEtag?: string },
2194
- ): boolean {
2195
- if (entry.remoteEtag) {
2196
- return normalizeEtag(remote.etag) !== entry.remoteEtag;
2197
- }
2198
- const syncedAt = new Date(entry.syncedAt).getTime();
2199
- return remote.lastModified.getTime() > syncedAt;
2200
- }
2201
-
2202
1852
  /**
2203
1853
  * Resolve each user-supplied share path to a directory under `syncRoot`,
2204
1854
  * returning the company-relative prefix that constrains delete propagation.
@@ -2579,6 +2229,14 @@ async function computeDeletePlan(
2579
2229
  // independently — one failed HEAD doesn't poison the others (errors
2580
2230
  // propagate from the chunk's Promise.all and are surfaced by share()'s
2581
2231
  // outer try/catch, mirroring the existing pre-share error handling).
2232
+ // Warm the GET presigns the HEAD pass reuses so a large candidate set doesn't
2233
+ // mint one presign per HEAD and trip the presign breaker. Mirrors the
2234
+ // new-files + tombstone HEAD-pass pre-primes.
2235
+ await primeObjectTransport(
2236
+ ctx,
2237
+ "get",
2238
+ headCandidates.map((c) => c.key),
2239
+ );
2582
2240
  for (let i = 0; i < headCandidates.length; i += DELETE_PLAN_HEAD_CONCURRENCY) {
2583
2241
  const chunk = headCandidates.slice(i, i + DELETE_PLAN_HEAD_CONCURRENCY);
2584
2242
  const results = await Promise.all(