@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/dist/cli/share.js CHANGED
@@ -16,6 +16,7 @@ import { wrapFilterWithPersonalVaultDefaults, } from "../personal-vault-exclusio
16
16
  import { resolveConflict } from "./conflict.js";
17
17
  import { fetchCompanyTombstones, } from "./tombstones.js";
18
18
  import { isCoveredByAny, isDirInScope, } from "../prefix-coalesce.js";
19
+ import { hasRemoteChanged, isAccessDenied, resolveActiveCompany, resolveTransferConcurrency, } from "../sync-core.js";
19
20
  import { buildConflictId, buildConflictPath, readShortMachineId, } from "../lib/conflict-file.js";
20
21
  import { appendConflictEntry } from "../lib/conflict-index.js";
21
22
  /**
@@ -334,20 +335,6 @@ function computePushPlan(filesToShare, journal, skipUnchanged) {
334
335
  }
335
336
  return { items, filesToUpload, bytesToUpload, filesToSkip };
336
337
  }
337
- /**
338
- * Is this error the S3/STS "access denied" class? Expected when a scoped
339
- * member/guest credential touches a key outside its granted ACL prefixes
340
- * (the server's `SCOPE_EXCEEDS_PARENT` surfaces as a 403 AccessDenied /
341
- * Forbidden). Mirrors the pull-side `isAccessDenied` in sync.ts so the push
342
- * leg can treat a stray out-of-scope key as a skip rather than a fatal throw.
343
- */
344
- function isAccessDenied(err) {
345
- if (err && typeof err === "object" && "name" in err) {
346
- const name = err.name;
347
- return name === "AccessDenied" || name === "Forbidden";
348
- }
349
- return false;
350
- }
351
338
  /**
352
339
  * A conditional-write fence rejection — the SDK's 412 (`name:
353
340
  * "PreconditionFailed"`) or the presigned transport's mirror of it. Means
@@ -398,21 +385,25 @@ function wrapFilterWithScope(underlying, syncRoot, prefixSet, onScopeExcluded) {
398
385
  * Share local file(s) to the entity vault.
399
386
  */
400
387
  export async function share(options) {
388
+ const run = await createPushRunContext(options);
389
+ const counters = createShareCounters();
390
+ const filesRefusedStalePaths = [];
391
+ const conflictPaths = [];
392
+ const plans = await buildSharePlans(run);
393
+ const uploadResult = await executeUploads(run, plans.pushPlan, counters, conflictPaths);
394
+ if (uploadResult.aborted) {
395
+ return buildShareResult(run, counters, filesRefusedStalePaths, uploadResult.abortFlightConflictPaths, true);
396
+ }
397
+ await executeDeletes(run, plans.deletePlan, plans.decommissionPlan, counters, filesRefusedStalePaths);
398
+ finalizeShareJournal(run);
399
+ throwUploadWorkerErrors(uploadResult.workerErrors);
400
+ return buildShareResult(run, counters, filesRefusedStalePaths, conflictPaths, false);
401
+ }
402
+ const REFUSED_STALE_PATH_CAP = 50;
403
+ async function createPushRunContext(options) {
401
404
  const { paths, company, message, onConflict, vaultConfig, entityContext, hqRoot, skipUnchanged, propagateDeletes } = options;
402
- // Default to "owned-only" — the pre-5.24 behavior — when delete-propagation
403
- // is on but the caller hasn't pinned a policy. Staged-default rollout
404
- // (see CHANGELOG / PR for hq-cloud 5.24.0): 5.24 ships the currency-gated
405
- // CODE PATH plus the conflict-mirror exclusion (which is policy-
406
- // independent and immediately stops new litter), but holds the default
407
- // flip to a later release after soak. Opt into the safer policy now via
408
- // `propagateDeletePolicy: "currency-gated"` (explicit) or
409
- // `HQ_SYNC_DELETE_POLICY=currency-gated` (env, honored by sync-runner).
410
- // The default flip to `"currency-gated"` is scheduled for 5.25.0.
411
405
  let propagateDeletePolicy = options.propagateDeletePolicy ?? "owned-only";
412
406
  const emit = options.onEvent ?? defaultConsoleLogger;
413
- // Exactly-one-of contract: either we vend (vaultConfig) or the caller did
414
- // (entityContext). Both supplied is ambiguous (which credentials win?), and
415
- // neither leaves us with no way to talk to S3.
416
407
  if (vaultConfig && entityContext) {
417
408
  throw new Error("share() requires exactly one of `vaultConfig` or `entityContext`, not both. " +
418
409
  "Pass `vaultConfig` to vend credentials internally, or `entityContext` to use pre-vended ones.");
@@ -421,72 +412,20 @@ export async function share(options) {
421
412
  throw new Error("share() requires either `vaultConfig` (for internal STS vending) " +
422
413
  "or `entityContext` (pre-vended credentials).");
423
414
  }
424
- // Resolve company — slug, UID, or from active config. When the caller
425
- // provided a pre-resolved entityContext, prefer its slug as the canonical
426
- // ref (the caller already knows what entity these creds are for).
427
415
  const companyRef = company ?? entityContext?.slug ?? resolveActiveCompany(hqRoot);
428
416
  if (!companyRef) {
429
417
  throw new Error("No company specified and no active company found. " +
430
418
  "Use --company <slug> or set up .hq/config.json.");
431
419
  }
432
- // Resolve entity context. Two paths:
433
- // 1. vaultConfig provided → resolveEntityContext does the lookup + STS vend
434
- // (cached + auto-refreshable mid-run).
435
- // 2. entityContext provided → use it directly. No lookup, no vending,
436
- // no auto-refresh (we have no Cognito token to re-vend with).
437
- // Caller is responsible for vending credentials with enough TTL to
438
- // cover the run; if they under-vend, the AWS SDK surfaces ExpiredToken
439
- // naturally on the first failing PUT.
440
- let ctx = entityContext
420
+ const ctx = entityContext
441
421
  ? entityContext
442
422
  : await resolveEntityContext(companyRef, vaultConfig);
443
- // Personal-vault policy correction (6.0.1). The `owned-only` rule encodes a
444
- // multi-user curation premise — "don't tombstone peer-uploaded content even
445
- // if my journal says I pulled it" — which is meaningful when several humans
446
- // share a company bucket (a behind machine's first sync must not erase
447
- // recent uploads from peers). On a personal vault that premise collapses:
448
- // every file is the same human's content, just routed through different
449
- // machines, and `direction: "down"` only means "uploaded from my laptop,
450
- // pulled by my EC2" — it never means "uploaded by someone else." With
451
- // `owned-only` in effect, `rm <file>` followed by `hq sync` silently fails
452
- // to propagate the delete, leaving permanent vault litter (the May-27
453
- // `personal/.obsidian/*.drift-*` files were diagnosed exactly this way).
454
- // The etag-based `currency-gated` policy already captures the only safety
455
- // intent that survives the single-user case ("don't tombstone if remote
456
- // drifted since I last synced"); coerce to it here so the policy is right
457
- // regardless of which caller's default landed. Explicit `"all"` is
458
- // preserved — it's the emergency-reconcile opt-out and the caller has
459
- // already asserted intent.
460
423
  if (ctx.uid.startsWith("prs_") && propagateDeletePolicy === "owned-only") {
461
424
  propagateDeletePolicy = "currency-gated";
462
425
  }
463
- // Remote keys are company-relative; the on-disk scoping prefix is
464
- // companies/{slug}/. Anything outside this folder gets skipped to avoid
465
- // leaking cross-company state into the vault.
466
- //
467
- // In personalMode the syncRoot is `hqRoot` itself — remote keys are
468
- // hq-root-relative to match the Rust personal first-push (which uploads
469
- // every non-excluded top-level dir under ~/HQ). The exclusion list is
470
- // enforced upstream by the runner; share() just trusts `paths`.
471
426
  const syncRoot = options.personalMode === true
472
427
  ? hqRoot
473
428
  : path.join(hqRoot, "companies", ctx.slug);
474
- // Personal-vault default exclusions (introduced in 5.25): wrap the base
475
- // ignore filter so paths matching `PERSONAL_VAULT_DEFAULT_EXCLUSIONS` are
476
- // rejected before they upload OR enter the delete plan. Refuses & warns —
477
- // an already-leaked remote object stays put as an orphan; a separate one-
478
- // shot purge handles legacy litter.
479
- //
480
- // Out-of-policy hits are deduplicated in `excludedSet` so the same path
481
- // hitting the filter from both the upload walk and the delete-plan walk
482
- // counts once. `excludedById` powers the per-rule breakdown on the
483
- // `personal-vault-out-of-policy` event so UI can render which class
484
- // (secret / machine-local / scratch / …) did the work.
485
- //
486
- // Company-mode syncs skip this wrap entirely — company vaults have their
487
- // own first-push protection (settings/, data/, workers/, .git/) defined
488
- // in hq-sync's Rust util/ignore.rs, and a company may legitimately ship
489
- // `output/` or `.env*` paths inside its `companies/{slug}/data/` folder.
490
429
  const ignoreFilter = createIgnoreFilter(hqRoot);
491
430
  const excludedSet = new Set();
492
431
  const excludedById = {};
@@ -496,12 +435,6 @@ export async function share(options) {
496
435
  excludedSet.add(rel);
497
436
  excludedById[match.id] = (excludedById[match.id] ?? 0) + 1;
498
437
  };
499
- // ACL scope filter (member/guest scoped push). The vended child credential
500
- // is scoped to `options.prefixSet`; any candidate outside those prefixes
501
- // would draw the server's correct 403 SCOPE_EXCEEDS_PARENT on PUT and abort
502
- // the whole company. Pre-filter the plan to the granted subset instead —
503
- // the push-side analogue of the pull leg's `skip-out-of-scope` (US-005).
504
- // `undefined` = owner/`all` → no scope filter (full access).
505
438
  const scopeExcludedSet = new Set();
506
439
  const onScopeExcluded = (rel) => {
507
440
  scopeExcludedSet.add(rel);
@@ -513,106 +446,67 @@ export async function share(options) {
513
446
  ? wrapFilterWithScope(baseFilter, syncRoot, options.prefixSet, onScopeExcluded)
514
447
  : baseFilter;
515
448
  const journalSlug = options.journalSlug ?? ctx.slug;
516
- // Seed the canonical personal-vault journal from the legacy `personal` file
517
- // exactly once — engine-side so every consumer (sync-runner, hq-cli) gets
518
- // it; see the matching guard in sync.ts.
519
449
  if (journalSlug === PERSONAL_VAULT_JOURNAL_SLUG)
520
450
  migratePersonalVaultJournal();
521
451
  const journal = readJournal(journalSlug);
522
- let filesUploaded = 0;
523
- let bytesUploaded = 0;
524
- let filesSkipped = 0;
525
- let filesDeleted = 0;
526
- // Tombstone and refused-stale counts mirror the deletePlan buckets so the
527
- // ShareResult can report them without the caller having to count events.
528
- // Populated only after Stage 3 runs (deletePlan is computed first, then
529
- // mutated through the execution loop) — initial zero handles the
530
- // propagateDeletes=false path.
531
- let filesTombstoned = 0;
532
- let filesRefusedStale = 0;
533
- // Count of uploads suppressed by the push-side FILE_TOMBSTONE consult (a
534
- // behind peer's stale copy of an authoritatively-deleted key). Always 0 when
535
- // there are no tombstones for in-scope keys.
536
- let filesSuppressedByTombstone = 0;
537
- // Capped at 50 to bound event payload size — `newFiles` uses the same cap.
538
- const REFUSED_STALE_PATH_CAP = 50;
539
- const filesRefusedStalePaths = [];
540
- const conflictPaths = [];
541
- // Collect all files to share
542
- const filesToShare = collectFiles(paths, hqRoot, syncRoot, shouldSync);
543
- // Stage 1: classify each file. Pre-HEAD — only inputs we can evaluate
544
- // locally (size limit, journal hash, optional skip-unchanged) are
545
- // considered. The plan event below carries an upper-bound `filesToUpload`
546
- // (true conflicts emerge from the per-file HEAD in Stage 2 and aren't
547
- // knowable here). The final `complete` event reports authoritative counts.
548
- const plan = computePushPlan(filesToShare, journal, skipUnchanged === true);
549
- // Delete-propagation plan: walk journal entries whose key falls under the
550
- // requested scope; any whose local file is gone is a candidate for a
551
- // remote DeleteObject. Only computed when the caller opts in — `hq share
552
- // <file>` must never sweep deletes outside the explicit path list.
553
- const deleteScopeRoots = propagateDeletes === true
554
- ? resolveDeleteScopeRoots(paths, hqRoot, syncRoot)
452
+ return {
453
+ options,
454
+ paths,
455
+ message,
456
+ onConflict,
457
+ vaultConfig,
458
+ entityContext,
459
+ hqRoot,
460
+ skipUnchanged,
461
+ propagateDeletes,
462
+ propagateDeletePolicy,
463
+ emit,
464
+ companyRef,
465
+ ctx,
466
+ syncRoot,
467
+ shouldSync,
468
+ journalSlug,
469
+ journal,
470
+ excludedSet,
471
+ excludedById,
472
+ scopeExcludedSet,
473
+ };
474
+ }
475
+ function createShareCounters() {
476
+ return {
477
+ filesUploaded: 0,
478
+ bytesUploaded: 0,
479
+ filesSkipped: 0,
480
+ filesDeleted: 0,
481
+ filesTombstoned: 0,
482
+ filesRefusedStale: 0,
483
+ filesSuppressedByTombstone: 0,
484
+ };
485
+ }
486
+ async function buildSharePlans(run) {
487
+ const filesToShare = collectFiles(run.paths, run.hqRoot, run.syncRoot, run.shouldSync);
488
+ const pushPlan = computePushPlan(filesToShare, run.journal, run.skipUnchanged === true);
489
+ const deleteScopeRoots = run.propagateDeletes === true
490
+ ? resolveDeleteScopeRoots(run.paths, run.hqRoot, run.syncRoot)
555
491
  : [];
556
- const deletePlan = propagateDeletes === true
557
- ? await computeDeletePlan(journal, syncRoot, deleteScopeRoots, shouldSync, propagateDeletePolicy, ctx)
492
+ const deletePlan = run.propagateDeletes === true
493
+ ? await computeDeletePlan(run.journal, run.syncRoot, deleteScopeRoots, run.shouldSync, run.propagateDeletePolicy, run.ctx)
558
494
  : { toDelete: [], toTombstone: [], refusedStale: [] };
559
- // Decommission plan: journal entries under explicit prefixes the caller
560
- // has asserted no longer belong in this bucket (typically a promoted
561
- // company's `companies/{slug}/` keys in the personal bucket). Independent
562
- // of `propagateDeletes` and DOES NOT require the local file to be missing
563
- // — the caller is making a stronger claim than "local says delete this".
564
- // Honors the same owned-only safety policy so a misconfigured caller
565
- // can never erase content the journal records as pulled from elsewhere.
566
- // Dedupes against `deletePlan` so a key in both plans is only processed
567
- // once (DeleteObject is idempotent on S3 but the journal-write would
568
- // race a no-op pass through the loop body).
569
- const decommissionPlan = (options.decommissionPrefixes ?? []).length > 0
570
- ? computeDecommissionPlan(journal, options.decommissionPrefixes ?? [], propagateDeletePolicy,
571
- // Dedup against `toDelete` (decommission and propagate-delete
572
- // would both issue DeleteObject — single call wins) and against
573
- // `toTombstone` (the remote is already 404; the tombstone loop
574
- // drops the journal entry without a network call — decommission
575
- // yields, both for efficiency and to avoid emitting two
576
- // "deleted" events for the same key).
577
- //
578
- // We do NOT dedup against `refusedStale`. A key whose remote
579
- // ETag drifted (peer wrote a newer version) but which decommission
580
- // claims should still be removed — the caller has asserted this
581
- // key doesn't belong in this bucket regardless of peer activity.
582
- // Under owned-only (default) `computeDecommissionPlan`'s
583
- // direction:'up' filter already excludes peer-written entries;
584
- // under policy:'all' the caller has opted out of that safety
585
- // anyway. The refusedStale loop below filters out keys we're
586
- // about to decommission to avoid emitting a spurious "kept on
587
- // remote" event for content we're deleting.
588
- new Set([...deletePlan.toDelete, ...deletePlan.toTombstone]))
495
+ const decommissionPlan = (run.options.decommissionPrefixes ?? []).length > 0
496
+ ? computeDecommissionPlan(run.journal, run.options.decommissionPrefixes ?? [], run.propagateDeletePolicy, new Set([...deletePlan.toDelete, ...deletePlan.toTombstone]))
589
497
  : [];
590
- emit({
498
+ run.emit({
591
499
  type: "plan",
592
- // share() is push-only; pull counts are sourced from sync()'s plan event.
593
500
  filesToDownload: 0,
594
501
  bytesToDownload: 0,
595
- filesToUpload: plan.filesToUpload,
596
- bytesToUpload: plan.bytesToUpload,
597
- filesToSkip: plan.filesToSkip,
598
- // Push conflicts require a remote HEAD; we don't yet do that in Stage 1,
599
- // so this stays 0. V1.5 (single LIST) will let us classify them up-front.
502
+ filesToUpload: pushPlan.filesToUpload,
503
+ bytesToUpload: pushPlan.bytesToUpload,
504
+ filesToSkip: pushPlan.filesToSkip,
600
505
  filesToConflict: 0,
601
- // Reported count is the deletes we're actually going to issue — does NOT
602
- // include tombstones (no S3 call) or refused-stale (no journal change).
603
- // Refusals surface as their own event stream so consumers that care can
604
- // render a "kept on remote: N" line separately. `decommissionPlan` adds
605
- // to this count because every decommission entry IS an issued
606
- // DeleteObject (different intent than propagate-deletes, same network
607
- // effect).
608
506
  filesToDelete: deletePlan.toDelete.length + decommissionPlan.length,
609
507
  });
610
- // Bulk-asymmetry summary event. Emitted once if the circuit-breaker
611
- // tripped inside `computeDeletePlan` — see DeletePlan.bulkAsymmetry doc.
612
- // Per-key refusal events fire later in the refusedStale loop with
613
- // reason: "bulk-asymmetry" so the UI can also show the affected paths.
614
508
  if (deletePlan.bulkAsymmetry) {
615
- emit({
509
+ run.emit({
616
510
  type: "delete-refused-bulk-asymmetry",
617
511
  candidates: deletePlan.bulkAsymmetry.candidates,
618
512
  inScope: deletePlan.bulkAsymmetry.inScope,
@@ -620,197 +514,85 @@ export async function share(options) {
620
514
  samplePaths: deletePlan.bulkAsymmetry.samplePaths,
621
515
  });
622
516
  }
623
- // Stage 2: execute. Skip items pre-classified as no-ops, then for each
624
- // upload candidate run the HEAD + 3-way conflict check + actual PUT.
625
- //
626
- // 5.36.0: upload candidates go through a bounded-concurrent pool
627
- // (`TRANSFER_CONCURRENCY`, default 16, tunable via
628
- // `HQ_SYNC_TRANSFER_CONCURRENCY`) for 4-8x speedup on transfer-heavy
629
- // syncs. Skip-size-limit and skip-unchanged are handled inline first
630
- // (pure local-state mutation). Upload candidates are collected into
631
- // `uploadItems[]` and processed in parallel via the pool below.
632
- //
633
- // Abort handling: when any item's conflict resolution is "abort", we
634
- // set `aborted = true` so the pool stops queueing new items, drain
635
- // in-flight cleanly, and short-circuit to the abort return. In-flight
636
- // PUTs that already issued will complete (S3 doesn't have client-side
637
- // cancellation in this code path); their results are still recorded on
638
- // the journal so the next sync's planner doesn't re-fire them.
639
- // Interactive-mode prompts: when `onConflict` is unset the per-item conflict
640
- // path calls resolveConflict()'s readline prompt on process.stdin, and two
641
- // pool workers prompting at once would race for the terminal and interleave
642
- // answers. The 5.36.x guard solved this by forcing the WHOLE pool to
643
- // concurrency=1 — which made an interactive `hq sync now` crawl even when
644
- // zero conflicts existed (every transfer serialized just in case one might
645
- // prompt). Instead, keep full env-tunable concurrency and serialize ONLY the
646
- // prompt (see `resolveConflictSerialized` below): at most one prompt awaits
647
- // input at a time while transfers stay parallel.
648
- const TRANSFER_CONCURRENCY = (() => {
649
- const raw = process.env.HQ_SYNC_TRANSFER_CONCURRENCY;
650
- if (raw === undefined || raw === "")
651
- return 16;
652
- const parsed = Number.parseInt(raw, 10);
653
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 16;
654
- })();
655
- // Chained lock around the (possibly interactive) conflict prompt. Each
656
- // resolveConflict() runs only after the previous one settles, so concurrent
657
- // pool workers never prompt over each other on stdin — without dropping the
658
- // transfer pool's parallelism. A rejected prompt must not wedge the chain,
659
- // so the link swallows errors (the original promise still rejects to its
660
- // awaiter). In non-interactive mode resolveConflict applies the configured
661
- // strategy without reading stdin, so the lock adds no real serialization.
517
+ return { pushPlan, deletePlan, decommissionPlan };
518
+ }
519
+ async function executeUploads(run, pushPlan, counters, conflictPaths) {
520
+ const TRANSFER_CONCURRENCY = resolveTransferConcurrency();
662
521
  let conflictPromptChain = Promise.resolve();
663
522
  const resolveConflictSerialized = (info) => {
664
- const run = conflictPromptChain.then(() => resolveConflict(info, onConflict));
665
- conflictPromptChain = run.then(() => undefined, () => undefined);
666
- return run;
523
+ const resolution = conflictPromptChain.then(() => resolveConflict(info, run.onConflict));
524
+ conflictPromptChain = resolution.then(() => undefined, () => undefined);
525
+ return resolution;
667
526
  };
668
- // Push-side FILE_TOMBSTONE consult (delete-resync) — symmetric to the pull
669
- // planner's suppression in sync.ts. An authoritative delete
670
- // (`hq files delete <prefix>`) writes a FILE_TOMBSTONE and removes the S3
671
- // object; the pull side already honors it. But the PUSH side did not: a behind
672
- // peer who still holds the deleted file locally would re-upload it here, and
673
- // because the re-uploaded object post-dates the tombstone, the pull planner's
674
- // timestamp-only re-create heuristic (`isRemoteRecreateAfterTombstone`) treats
675
- // it as a genuine re-create and resurrects the key for EVERYONE — defeating the
676
- // authoritative delete. Consult the tombstones so a stale-baseline upload is
677
- // skipped at the source.
678
- //
679
- // Source: an injected `fileTombstones` (a sync run can hand the push leg the
680
- // map it already fetched for the pull leg), else a self-fetch for COMPANY
681
- // vaults that have a `vaultConfig`. Personal vaults have no company tombstones
682
- // (the pull side skips them too), and `entityContext`-only callers have no
683
- // auth to fetch with — both degrade to an empty map (no suppression), the
684
- // safe/legacy direction.
685
- const fileTombstones = options.fileTombstones ??
686
- (!ctx.uid.startsWith("prs_") && vaultConfig
687
- ? await fetchCompanyTombstones(vaultConfig, ctx.uid)
527
+ const fileTombstones = run.options.fileTombstones ??
528
+ (!run.ctx.uid.startsWith("prs_") && run.vaultConfig
529
+ ? await fetchCompanyTombstones(run.vaultConfig, run.ctx.uid)
688
530
  : new Map());
689
- // Phase A: serial classification pass — handle skips inline, collect
690
- // upload candidates for the parallel pool.
691
531
  const uploadItems = [];
692
- for (const item of plan.items) {
532
+ for (const item of pushPlan.items) {
693
533
  if (item.action === "skip-size-limit") {
694
- emit({
534
+ run.emit({
695
535
  type: "error",
696
536
  path: item.relativePath,
697
537
  message: "file exceeds size limit",
698
538
  });
699
- filesSkipped++;
539
+ counters.filesSkipped++;
700
540
  continue;
701
541
  }
702
- // Suppress the re-upload of an authoritatively-deleted key when the local
703
- // copy is still the deleted baseline. Discrimination mirrors the pull side's
704
- // `localChanged || !journalEntry` test: a journal entry whose hash matches
705
- // the upload's localHash means the file is byte-identical to what was last
706
- // synced i.e. the deleted version a behind peer never pulled away — so
707
- // SKIP it. A locally-changed file (hash differs) or one with no journal
708
- // entry is genuine new content (a real re-create or a post-delete edit) and
709
- // uploads normally. The deleter's own stale local copy is removed by the
710
- // pull leg's `tombstone-delete`; this guard only stops the resurrection.
711
- if (item.action === "upload" && fileTombstones.size > 0) {
712
- const ts = fileTombstones.get(toPosixKey(item.relativePath));
713
- if (ts !== undefined) {
714
- const entry = journal.files[item.relativePath];
715
- if (entry && entry.hash === item.localHash) {
716
- filesSuppressedByTombstone++;
717
- emit({
718
- type: "upload-suppressed-tombstone",
719
- path: item.relativePath,
720
- deletedAt: ts.deletedAt,
721
- });
722
- continue;
542
+ if (item.action === "upload") {
543
+ if (fileTombstones.size > 0) {
544
+ const ts = fileTombstones.get(toPosixKey(item.relativePath));
545
+ if (ts !== undefined) {
546
+ const entry = run.journal.files[item.relativePath];
547
+ if (entry && entry.hash === item.localHash) {
548
+ counters.filesSuppressedByTombstone++;
549
+ run.emit({
550
+ type: "upload-suppressed-tombstone",
551
+ path: item.relativePath,
552
+ deletedAt: ts.deletedAt,
553
+ });
554
+ continue;
555
+ }
723
556
  }
724
557
  }
558
+ uploadItems.push(item);
559
+ continue;
725
560
  }
726
- if (item.action === "skip-unchanged") {
727
- // Refresh the journal's (mtimeMs, size) for a touched-but-identical file
728
- // so the next sync's lstat fast-path matches and skips without re-hashing.
729
- // Guarded on item.restamp (only set when the fast-path missed AND the
730
- // stored stat actually differs) and on the entry still carrying a hash —
731
- // never alters the content hash, so this stays a pure no-op skip. The
732
- // journal is persisted unconditionally by writeJournal at the end of the
733
- // run, so this survives even when nothing uploads.
734
- if (item.restamp) {
735
- const existing = journal.files[item.relativePath];
736
- if (existing && existing.hash) {
737
- existing.mtimeMs = item.restamp.mtimeMs;
738
- existing.size = item.restamp.size;
739
- }
561
+ if (item.restamp) {
562
+ const existing = run.journal.files[item.relativePath];
563
+ if (existing && existing.hash) {
564
+ existing.mtimeMs = item.restamp.mtimeMs;
565
+ existing.size = item.restamp.size;
740
566
  }
741
- filesSkipped++;
742
- continue;
743
567
  }
744
- uploadItems.push(item);
568
+ counters.filesSkipped++;
745
569
  }
746
- // Batch pre-mint PUT URLs (+ the created-at HEADs) for the whole upload set,
747
- // signing the SAME metadata the pool below computes so each task replays the
748
- // cached headers and skips its own presign. Turns an N-file push from ~N
749
- // presign calls into ceil(N/1000) GET + ceil(N/1000) PUT — keeping a bulk
750
- // push under the 100/hr limit. No-op on the S3 SDK transport; best-effort.
751
- await primeUploads(ctx, uploadItems.map((it) => ({
570
+ await primeUploads(run.ctx, uploadItems.map((it) => ({
752
571
  key: it.relativePath,
753
572
  localPath: it.absolutePath,
754
573
  isSymlink: it.kind === "symlink",
755
- author: options.author,
574
+ author: run.options.author,
756
575
  })));
757
- // Phase B: parallel upload pool. Each task runs the full per-item flow
758
- // (HEAD + conflict + PUT + journal stamp + emit). Aborts flip the
759
- // shared `aborted` flag and the pool stops draining the queue; tasks
760
- // already in flight complete normally.
576
+ // Warm the GET presigns the per-item conflict HEAD (remoteMeta) reuses, so a
577
+ // large upload set doesn't mint one presign per HEAD and burst/trip the
578
+ // presign breaker. Mirrors the new-files + tombstone pre-primes on the pull.
579
+ await primeObjectTransport(run.ctx, "get", uploadItems.map((it) => it.relativePath));
761
580
  let aborted = false;
762
581
  let abortFlightConflictPaths = [];
763
582
  const processUploadItem = async (item) => {
764
583
  if (aborted)
765
584
  return;
766
585
  const { absolutePath, relativePath, localHash } = item;
767
- // Auto-refresh context if credentials expiring. Only available on the
768
- // vaultConfig path pre-vended contexts have no source to re-vend
769
- // from, so we let the AWS SDK surface ExpiredToken naturally on the
770
- // PUT below if the caller under-vended.
771
- if (vaultConfig && isExpiringSoon(ctx.expiresAt)) {
772
- ctx = await refreshEntityContext(companyRef, vaultConfig);
586
+ if (run.vaultConfig && isExpiringSoon(run.ctx.expiresAt)) {
587
+ run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
773
588
  }
774
- // Check for remote conflict — refuse to overwrite newer remote version.
775
- //
776
- // A real conflict requires BOTH sides to have moved since the last sync.
777
- // The previous predicate only checked `journalEntry.hash !== localHash`,
778
- // which mislabelled every local edit as a conflict and (combined with
779
- // `--on-conflict keep`) silently dropped the user's edit. We now compare
780
- // the current remote ETag against the one captured at last sync; when
781
- // missing (legacy entries), we fall back to the same `lastModified >
782
- // syncedAt` heuristic the pull side uses.
783
- //
784
- // Bug #7 (data-loss class — see workspace/reports/hq-cloud-5.33.0-
785
- // deep-test.md): for a path with NO prior journal entry (first push
786
- // from this machine), the localChanged/remoteChanged predicates above
787
- // both evaluate FALSE (their guards require `!!journalEntry`). Push
788
- // fell through to an unconditional PUT, silently clobbering any
789
- // peer's content already at that key. The verification report's V7
790
- // isolated this — the bug is independent of \`--on-conflict\` mode;
791
- // it's keyed on "do I have a prior journal entry?" not on the flag.
792
- //
793
- // Fresh-collision branch: when remoteMeta exists and there's no
794
- // journal entry, hash the local body (MD5 for parity with S3's
795
- // single-part etag) and compare. Match → no conflict, silently skip
796
- // the PUT (the bytes are already there). Mismatch → treat as a
797
- // conflict in the same shared branch below.
798
- // Defense-in-depth for the scoped-push 403: the `prefixSet` filter above
799
- // should already have dropped any out-of-scope key from the plan, but a
800
- // grant that changed mid-run, a pinned prefix outside the grant, or
801
- // prefix-coalesce imprecision can still leave an out-of-scope key here.
802
- // This HEAD sits OUTSIDE the per-file PUT try/catch below, so a thrown
803
- // 403 used to bubble to `workerErrors` and abort the ENTIRE company with
804
- // a generic message and exit 2. Catch the access-denied class, surface
805
- // the offending PATH clearly, and skip just this key — the rest of the
806
- // company still syncs. Non-access-denied errors re-throw unchanged.
807
589
  let remoteMeta;
808
590
  try {
809
- remoteMeta = await headRemoteFile(ctx, relativePath);
591
+ remoteMeta = await headRemoteFile(run.ctx, relativePath);
810
592
  }
811
593
  catch (headErr) {
812
594
  if (isAccessDenied(headErr)) {
813
- emit({
595
+ run.emit({
814
596
  type: "error",
815
597
  path: relativePath,
816
598
  message: "skipped: outside granted ACL scope (server returned 403 " +
@@ -822,21 +604,15 @@ export async function share(options) {
822
604
  throw headErr;
823
605
  }
824
606
  if (remoteMeta) {
825
- const journalEntry = journal.files[relativePath];
607
+ const journalEntry = run.journal.files[relativePath];
826
608
  const localChanged = !!journalEntry && journalEntry.hash !== localHash;
827
609
  const remoteChanged = !!journalEntry && hasRemoteChanged(remoteMeta, journalEntry);
828
610
  let isFreshCollision = false;
829
611
  let multipartConverged = false;
830
612
  if (!journalEntry && item.kind === "symlink") {
831
- // A HEAD on an existing object does not expose the symlink target.
832
- // On a first sync, treat the existing remote as a fresh collision
833
- // instead of replacing it with the local link record.
834
613
  isFreshCollision = true;
835
614
  }
836
615
  else if (!journalEntry && item.kind === "file") {
837
- // Single-part S3 PUT etag is MD5 of the body. Multipart uploads
838
- // produce `<md5>-<partCount>`. Symlink records cannot be classified
839
- // from HEAD alone, so the branch above fails closed.
840
616
  const remoteEtagNormalized = normalizeEtag(remoteMeta.etag);
841
617
  const isMultipart = /-\d+$/.test(remoteEtagNormalized);
842
618
  if (!isMultipart) {
@@ -845,44 +621,22 @@ export async function share(options) {
845
621
  if (localMd5 !== remoteEtagNormalized) {
846
622
  isFreshCollision = true;
847
623
  }
848
- // Match → bytes are already there; fall through to upload
849
- // path which is idempotent (S3 will overwrite with identical
850
- // content + carry our metadata). Cheap, no behavior change.
851
624
  }
852
625
  else {
853
- // Multipart remote etag is \`<md5>-<partCount>\`, NOT a usable
854
- // content hash, so — unlike the single-part branch — we cannot
855
- // decide collision-vs-identical from the etag alone. The old
856
- // behavior assumed a collision here, which minted a FALSE
857
- // conflict for the most common fresh-install case: re-pushing a
858
- // byte-identical \`core/\` scaffold file whose remote copy happened
859
- // to be multipart-uploaded. Every fresh install that hit an
860
- // already-populated bucket therefore came up "with conflicts".
861
- //
862
- // Instead, fetch the remote bytes once and compare content
863
- // hashes directly — the same convergence guard the pull side
864
- // uses (sync.ts). Identical content is NOT a conflict. On any
865
- // fetch/hash failure we fail safe to "conflict" (false positives
866
- // prompt the operator; false negatives risk clobbering a peer).
867
- const remoteDiffers = await remoteContentDiffers(ctx, relativePath, localHash, hqRoot);
626
+ const remoteDiffers = await remoteContentDiffers(run.ctx, relativePath, localHash, run.hqRoot);
868
627
  if (remoteDiffers) {
869
628
  isFreshCollision = true;
870
629
  }
871
630
  else {
872
- // Byte-identical multipart object already present. Seed the
873
- // journal baseline from the remote so the next sync sees no
874
- // change on either side, and skip the redundant PUT —
875
- // re-uploading would needlessly rewrite remote and churn its
876
- // etag from multipart to single-part.
877
631
  multipartConverged = true;
878
632
  }
879
633
  }
880
634
  }
881
635
  if (multipartConverged) {
882
636
  const lstat = fs.lstatSync(absolutePath);
883
- updateEntry(journal, relativePath, localHash, lstat.size, "up", remoteMeta.etag, lstat.mtimeMs);
884
- emit({ type: "reconciled", path: relativePath, direction: "push" });
885
- filesSkipped++;
637
+ updateEntry(run.journal, relativePath, localHash, lstat.size, "up", remoteMeta.etag, lstat.mtimeMs);
638
+ run.emit({ type: "reconciled", path: relativePath, direction: "push" });
639
+ counters.filesSkipped++;
886
640
  return;
887
641
  }
888
642
  if ((localChanged && remoteChanged) || isFreshCollision) {
@@ -893,130 +647,53 @@ export async function share(options) {
893
647
  remoteModified: remoteMeta.lastModified,
894
648
  direction: "push",
895
649
  });
896
- emit({
650
+ run.emit({
897
651
  type: "conflict",
898
652
  path: relativePath,
899
653
  direction: "push",
900
654
  resolution,
901
655
  });
902
656
  if (resolution === "abort") {
903
- // Flip the shared aborted flag — the pool drainer below sees this
904
- // and stops queueing new items. In-flight tasks complete normally
905
- // (S3 PUTs have no client-side cancel here). The outer abort
906
- // return is built after the pool drains.
907
657
  aborted = true;
908
658
  abortFlightConflictPaths = [...conflictPaths];
909
659
  return;
910
660
  }
911
661
  if (resolution === "keep" || resolution === "skip") {
912
- // Bug #7 mirror branch: when the resolution is keep/skip on a
913
- // FRESH collision (no prior journal entry), download the
914
- // remote bytes to \`<orig>.conflict-<ts>-<short>\` so both
915
- // versions survive on disk. Mirrors the pull-side mirror-write
916
- // routine in sync.ts exactly. Skipped for stale-journal
917
- // conflicts (the pre-Bug-#7 codepath) — those already produce
918
- // a pull-side mirror on the next sync cycle.
919
662
  if (isFreshCollision) {
920
- try {
921
- const detectedAt = new Date().toISOString();
922
- const machineId = readShortMachineId(hqRoot);
923
- const originalRelative = path.relative(hqRoot, absolutePath);
924
- const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
925
- const conflictAbs = path.join(hqRoot, conflictRelative);
926
- if (!isMaterializationPathStillContained(syncRoot, conflictAbs)) {
927
- emit({
928
- type: "error",
929
- path: relativePath,
930
- message: "conflict mirror skipped: local parent escaped the sync root",
931
- });
932
- }
933
- else {
934
- await downloadFile(ctx, relativePath, conflictAbs);
935
- appendConflictEntry(hqRoot, {
936
- id: buildConflictId(originalRelative, detectedAt),
937
- originalPath: originalRelative,
938
- conflictPath: conflictRelative,
939
- detectedAt,
940
- side: "push",
941
- machineId,
942
- localHash,
943
- remoteHash: normalizeEtag(remoteMeta.etag),
944
- });
945
- }
946
- }
947
- catch (mirrorErr) {
948
- emit({
949
- type: "error",
950
- path: relativePath,
951
- message: `conflict mirror write failed: ${mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)}`,
952
- });
953
- }
663
+ await writePushConflictMirror(run, item, normalizeEtag(remoteMeta.etag));
954
664
  }
955
- filesSkipped++;
665
+ counters.filesSkipped++;
956
666
  return;
957
667
  }
958
- // "overwrite" falls through to upload
959
668
  }
960
669
  }
961
- // Re-check abort flag right before the PUT — if a peer task aborted
962
- // while we were waiting on HEAD, skip the PUT entirely. This is
963
- // belt-and-suspenders alongside the queue-drain check; without it,
964
- // up to TRANSFER_CONCURRENCY in-flight uploads could still issue PUTs
965
- // after the user signaled abort.
966
670
  if (aborted)
967
671
  return;
968
- // Conditional-write fence (storage-level backstop for the entire
969
- // stale-clobber class). Every PUT asserts the remote state this pass
970
- // just inspected:
971
- // - remote exists → If-Match on the observed etag ("replace exactly
972
- // what I HEAD'd"). Closes the HEAD→PUT TOCTOU: a peer's write
973
- // landing in the window makes S3 itself reject with 412 instead of
974
- // this machine silently regressing the object.
975
- // - remote absent → If-None-Match:* ("create only"). If the HEAD was
976
- // wrong about absence (any transport/state bug — the 2026-06-10..12
977
- // regression storm's shape), the PUT 412s instead of clobbering.
978
- // Enforced natively on the SDK transport; on the presigned transport it
979
- // activates when files-presign signs the headers (see object-io.ts).
980
672
  const precondition = remoteMeta
981
673
  ? { ifMatch: remoteMeta.etag }
982
674
  : { ifNoneMatch: "*" };
983
- // Upload — symlinks go through uploadSymlink (zero-byte body + target
984
- // metadata), regular files through uploadFile (file contents). The
985
- // discriminator is item.kind set by computePushPlan; both branches
986
- // converge on the same journal/event update path below. Factored into a
987
- // closure so the 412 "overwrite" resolution below can re-run it without
988
- // the fence after explicit user consent.
989
675
  const performUpload = async (pc) => {
990
676
  const isSymlinkUpload = item.kind === "symlink";
991
- // Capture lstat post-upload so size + mtimeMs stamped into the
992
- // journal reflect the bytes we actually shipped. lstat (not stat)
993
- // so a symlink stamps the link's own mtime, not the target's —
994
- // matches the fast-path's lstat comparison so the next sync can
995
- // skip without dereferencing.
996
677
  const lstat = fs.lstatSync(absolutePath);
997
678
  const size = isSymlinkUpload ? 0 : lstat.size;
998
679
  const mtimeMs = lstat.mtimeMs;
999
680
  const { etag } = isSymlinkUpload
1000
- ? await uploadSymlink(ctx, item.target, relativePath, options.author, pc)
1001
- : await uploadFile(ctx, absolutePath, relativePath, options.author, pc);
1002
- // Update journal with optional message; capture the post-upload ETag
1003
- // so the next sync can distinguish "remote moved since we last wrote"
1004
- // from "user edited locally" without conflating the two. mtimeMs
1005
- // feeds the 5.36.0 lstat fast-path on the next push.
1006
- updateEntry(journal, relativePath, localHash, size, "up", etag, mtimeMs);
1007
- if (message) {
1008
- journal.files[relativePath] = {
1009
- ...journal.files[relativePath],
1010
- message,
681
+ ? await uploadSymlink(run.ctx, item.target, relativePath, run.options.author, pc)
682
+ : await uploadFile(run.ctx, absolutePath, relativePath, run.options.author, pc);
683
+ updateEntry(run.journal, relativePath, localHash, size, "up", etag, mtimeMs);
684
+ if (run.message) {
685
+ run.journal.files[relativePath] = {
686
+ ...run.journal.files[relativePath],
687
+ message: run.message,
1011
688
  };
1012
689
  }
1013
- filesUploaded++;
1014
- bytesUploaded += size;
1015
- emit({
690
+ counters.filesUploaded++;
691
+ counters.bytesUploaded += size;
692
+ run.emit({
1016
693
  type: "progress",
1017
694
  path: relativePath,
1018
695
  bytes: size,
1019
- ...(message ? { message } : {}),
696
+ ...(run.message ? { message: run.message } : {}),
1020
697
  });
1021
698
  };
1022
699
  try {
@@ -1024,17 +701,13 @@ export async function share(options) {
1024
701
  }
1025
702
  catch (err) {
1026
703
  if (isPreconditionFailed(err)) {
1027
- // The fence fired: the remote moved past (If-Match) or appeared at
1028
- // (If-None-Match) this key between our HEAD and the PUT — exactly
1029
- // the race the fence exists to catch. Surface as a push conflict;
1030
- // never silently overwrite.
1031
704
  conflictPaths.push(relativePath);
1032
705
  const resolution = await resolveConflictSerialized({
1033
706
  path: relativePath,
1034
707
  localHash,
1035
708
  direction: "push",
1036
709
  });
1037
- emit({
710
+ run.emit({
1038
711
  type: "conflict",
1039
712
  path: relativePath,
1040
713
  direction: "push",
@@ -1046,13 +719,11 @@ export async function share(options) {
1046
719
  return;
1047
720
  }
1048
721
  if (resolution === "overwrite") {
1049
- // Explicit clobber consent — retry once without the fence. A
1050
- // second failure falls through to the generic error emit.
1051
722
  try {
1052
723
  await performUpload(undefined);
1053
724
  }
1054
725
  catch (retryErr) {
1055
- emit({
726
+ run.emit({
1056
727
  type: "error",
1057
728
  path: relativePath,
1058
729
  message: retryErr instanceof Error ? retryErr.message : String(retryErr),
@@ -1060,50 +731,11 @@ export async function share(options) {
1060
731
  }
1061
732
  return;
1062
733
  }
1063
- // keep/skip: preserve the racing remote next to the local copy so
1064
- // both versions survive — same mirror routine as the fresh-collision
1065
- // branch above.
1066
- try {
1067
- const detectedAt = new Date().toISOString();
1068
- const machineId = readShortMachineId(hqRoot);
1069
- const originalRelative = path.relative(hqRoot, absolutePath);
1070
- const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
1071
- const conflictAbs = path.join(hqRoot, conflictRelative);
1072
- if (!isMaterializationPathStillContained(syncRoot, conflictAbs)) {
1073
- emit({
1074
- type: "error",
1075
- path: relativePath,
1076
- message: "conflict mirror skipped: local parent escaped the sync root",
1077
- });
1078
- }
1079
- else {
1080
- await downloadFile(ctx, relativePath, conflictAbs);
1081
- appendConflictEntry(hqRoot, {
1082
- id: buildConflictId(originalRelative, detectedAt),
1083
- originalPath: originalRelative,
1084
- conflictPath: conflictRelative,
1085
- detectedAt,
1086
- side: "push",
1087
- machineId,
1088
- localHash,
1089
- // remoteMeta (if any) predates the racing write that fired the
1090
- // fence — record what we knew ("" when the key was believed
1091
- // absent); the mirror file carries the authoritative remote bytes.
1092
- remoteHash: remoteMeta ? normalizeEtag(remoteMeta.etag) : "",
1093
- });
1094
- }
1095
- }
1096
- catch (mirrorErr) {
1097
- emit({
1098
- type: "error",
1099
- path: relativePath,
1100
- message: `conflict mirror write failed: ${mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)}`,
1101
- });
1102
- }
1103
- filesSkipped++;
734
+ await writePushConflictMirror(run, item, remoteMeta ? normalizeEtag(remoteMeta.etag) : "");
735
+ counters.filesSkipped++;
1104
736
  return;
1105
737
  }
1106
- emit({
738
+ run.emit({
1107
739
  type: "error",
1108
740
  path: relativePath,
1109
741
  message: isAccessDenied(err)
@@ -1116,25 +748,6 @@ export async function share(options) {
1116
748
  });
1117
749
  }
1118
750
  };
1119
- // Drain the upload queue with bounded concurrency. Per-file progress
1120
- // events fire from inside processUploadItem at file-settle time, so
1121
- // cross-file event ordering is settle-order, not plan-walk-order — the
1122
- // menubar's stream parser already tolerates per-company interleave so
1123
- // this is shape-compatible. allSettled-style waiting (via Promise.race
1124
- // on the in-flight set) keeps the pool topped up without idling on slow
1125
- // members.
1126
- //
1127
- // Codex P1 (5.36.x): each worker promise is wrapped in a .catch that
1128
- // records the error to `workerErrors` and resolves normally — so
1129
- // `Promise.race(inFlight)` can never reject and unwind the drain loop
1130
- // mid-flight. Without the wrap, an unhandled rejection inside
1131
- // processUploadItem (e.g. headRemoteFile or refreshEntityContext, both
1132
- // of which sit outside the per-item PUT try/catch) bubbled out of the
1133
- // race, abandoned still-in-flight uploads that kept mutating remote
1134
- // state, and skipped writeJournal — leaving remote and journal
1135
- // permanently out of sync for the next run. After the pool fully
1136
- // drains we throw an aggregated error so the caller still surfaces the
1137
- // failure (and the journal reflects the writes that actually landed).
1138
751
  const workerErrors = [];
1139
752
  {
1140
753
  const queue = [...uploadItems];
@@ -1155,87 +768,63 @@ export async function share(options) {
1155
768
  await Promise.race(Array.from(inFlight));
1156
769
  }
1157
770
  else {
1158
- // Aborted with nothing in flight → exit the drain loop.
1159
771
  break;
1160
772
  }
1161
773
  }
1162
774
  }
1163
- if (aborted) {
1164
- return {
1165
- filesUploaded,
1166
- bytesUploaded,
1167
- filesSkipped,
1168
- filesDeleted,
1169
- // Abort path: delete stage never runs, so tombstone + refused-
1170
- // stale counts are necessarily zero. Explicit fields keep the
1171
- // ShareResult shape stable for consumers that destructure.
1172
- filesTombstoned,
1173
- filesRefusedStale,
1174
- // Always present so consumers can destructure without a
1175
- // defaulting fallback. Empty on the abort path because the
1176
- // delete-plan execution loop is short-circuited.
1177
- filesRefusedStalePaths,
1178
- // Tombstone-suppressed uploads are classified in Phase A, which runs
1179
- // before the upload pool can abort, so the count is meaningful here.
1180
- filesSuppressedByTombstone,
1181
- // Exclusions are computed during the upload walk which has
1182
- // already completed by the time we hit a per-file conflict-
1183
- // abort, so the count is meaningful here. No event emit on
1184
- // abort (matches the existing convention: abort short-circuits
1185
- // before the end-of-run telemetry emits).
1186
- filesExcludedByPolicy: excludedSet.size,
1187
- // Scope exclusions are likewise computed during the upload walk, so the
1188
- // count is meaningful on the abort path too.
1189
- filesExcludedByScope: scopeExcludedSet.size,
1190
- // Use the snapshot of conflictPaths taken at the moment the abort
1191
- // fired — additional in-flight items may have appended to the
1192
- // shared array after the abort signal, and those should not show
1193
- // up in the abort result.
1194
- conflictPaths: abortFlightConflictPaths,
1195
- aborted: true,
1196
- };
775
+ return { aborted, abortFlightConflictPaths, workerErrors };
776
+ }
777
+ async function writePushConflictMirror(run, item, remoteHash) {
778
+ try {
779
+ const detectedAt = new Date().toISOString();
780
+ const machineId = readShortMachineId(run.hqRoot);
781
+ const originalRelative = path.relative(run.hqRoot, item.absolutePath);
782
+ const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
783
+ const conflictAbs = path.join(run.hqRoot, conflictRelative);
784
+ if (!isMaterializationPathStillContained(run.syncRoot, conflictAbs)) {
785
+ run.emit({
786
+ type: "error",
787
+ path: item.relativePath,
788
+ message: "conflict mirror skipped: local parent escaped the sync root",
789
+ });
790
+ }
791
+ else {
792
+ await downloadFile(run.ctx, item.relativePath, conflictAbs);
793
+ appendConflictEntry(run.hqRoot, {
794
+ id: buildConflictId(originalRelative, detectedAt),
795
+ originalPath: originalRelative,
796
+ conflictPath: conflictRelative,
797
+ detectedAt,
798
+ side: "push",
799
+ machineId,
800
+ localHash: item.localHash,
801
+ remoteHash,
802
+ });
803
+ }
804
+ }
805
+ catch (mirrorErr) {
806
+ run.emit({
807
+ type: "error",
808
+ path: item.relativePath,
809
+ message: "conflict mirror write failed: " +
810
+ (mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)),
811
+ });
1197
812
  }
1198
- // Stage 3: propagate deletes. Three buckets, three actions:
1199
- //
1200
- // 1. `toDelete` (PLUS `decommissionPlan` concatenated in) — write a
1201
- // delete-marker (versioning is enabled on the bucket so the delete
1202
- // is soft and prior versions remain recoverable) and remove the
1203
- // journal entry so the next sync sees the key as truly gone on
1204
- // this machine. A failed DeleteObject leaves both the journal
1205
- // entry and remote object intact — the next run retries.
1206
- // Decommission keys join this bucket because their effect is
1207
- // identical (DeleteObject + journal removal); the difference is
1208
- // intent only, and the dedupe at plan-computation time ensures we
1209
- // don't double-issue for a key both plans matched.
1210
- //
1211
- // 2. `toTombstone` — the remote was 404 at HEAD time (cleaned up out
1212
- // of band, e.g. someone hand-deleted via console). No DeleteObject
1213
- // needed; just drop the journal entry so the journal converges with
1214
- // reality. Emit a synthetic `progress` event with `deleted: true`
1215
- // and bytes=0 so consumers see the convergence.
1216
- //
1217
- // 3. `refusedStale` — under `currency-gated`, the remote's current
1218
- // ETag no longer matches the journal's recorded one. Some other
1219
- // device modified the file since this device last synced it. Keep
1220
- // the remote intact; keep the journal entry intact. The next pull
1221
- // leg of `sync now` re-pulls naturally via the existing
1222
- // `hasRemoteChanged` path. Emit a dedicated event so UIs can
1223
- // surface the refusal without inferring it from absence.
1224
- // Batch pre-mint DELETE URLs so a large delete set is ~ceil(N/1000) presign
1225
- // calls, not N. No-op on the S3 SDK transport; best-effort.
813
+ }
814
+ async function executeDeletes(run, deletePlan, decommissionPlan, counters, filesRefusedStalePaths) {
1226
815
  const deleteKeys = [...deletePlan.toDelete, ...decommissionPlan];
1227
- await primeObjectTransport(ctx, "delete", deleteKeys);
816
+ await primeObjectTransport(run.ctx, "delete", deleteKeys);
1228
817
  for (const relativePath of deleteKeys) {
1229
- if (vaultConfig && isExpiringSoon(ctx.expiresAt)) {
1230
- ctx = await refreshEntityContext(companyRef, vaultConfig);
818
+ if (run.vaultConfig && isExpiringSoon(run.ctx.expiresAt)) {
819
+ run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
1231
820
  }
1232
821
  try {
1233
- const entry = journal.files[relativePath];
822
+ const entry = run.journal.files[relativePath];
1234
823
  const size = entry?.size ?? 0;
1235
- await deleteRemoteFile(ctx, relativePath);
1236
- removeEntry(journal, relativePath);
1237
- filesDeleted++;
1238
- emit({
824
+ await deleteRemoteFile(run.ctx, relativePath);
825
+ removeEntry(run.journal, relativePath);
826
+ counters.filesDeleted++;
827
+ run.emit({
1239
828
  type: "progress",
1240
829
  path: relativePath,
1241
830
  bytes: size,
@@ -1243,7 +832,7 @@ export async function share(options) {
1243
832
  });
1244
833
  }
1245
834
  catch (err) {
1246
- emit({
835
+ run.emit({
1247
836
  type: "error",
1248
837
  path: relativePath,
1249
838
  message: err instanceof Error ? err.message : String(err),
@@ -1251,9 +840,9 @@ export async function share(options) {
1251
840
  }
1252
841
  }
1253
842
  for (const relativePath of deletePlan.toTombstone) {
1254
- removeEntry(journal, relativePath);
1255
- filesTombstoned++;
1256
- emit({
843
+ removeEntry(run.journal, relativePath);
844
+ counters.filesTombstoned++;
845
+ run.emit({
1257
846
  type: "progress",
1258
847
  path: relativePath,
1259
848
  bytes: 0,
@@ -1261,20 +850,15 @@ export async function share(options) {
1261
850
  message: "tombstone (remote already 404)",
1262
851
  });
1263
852
  }
1264
- // Decommission overrides refusedStale: a key whose peer drifted but
1265
- // which the caller has claimed via `decommissionPrefixes` is processed
1266
- // by the DeleteObject loop above; skip the refusal event here so the
1267
- // event stream doesn't simultaneously claim "we deleted it" and "we
1268
- // kept it on remote" for the same key.
1269
853
  const decommissionedSet = decommissionPlan.length > 0 ? new Set(decommissionPlan) : null;
1270
854
  for (const refused of deletePlan.refusedStale) {
1271
855
  if (decommissionedSet && decommissionedSet.has(refused.key))
1272
856
  continue;
1273
- filesRefusedStale++;
857
+ counters.filesRefusedStale++;
1274
858
  if (filesRefusedStalePaths.length < REFUSED_STALE_PATH_CAP) {
1275
859
  filesRefusedStalePaths.push(refused.key);
1276
860
  }
1277
- emit({
861
+ run.emit({
1278
862
  type: "delete-refused-stale-etag",
1279
863
  path: refused.key,
1280
864
  journalEtag: refused.journalEtag,
@@ -1282,75 +866,65 @@ export async function share(options) {
1282
866
  reason: refused.reason,
1283
867
  });
1284
868
  }
1285
- // See cli/sync.ts: stamp lastSync on completion so a no-op share still
1286
- // ticks the "Last sync" indicator.
1287
- journal.lastSync = new Date().toISOString();
1288
- writeJournal(journalSlug, journal);
1289
- // Personal-vault out-of-policy summary. Emit at most once, only when at
1290
- // least one path was excluded. Sample is capped at 10 to keep the event
1291
- // small (Set iteration order = insertion order, so samples are the first
1292
- // ten paths encountered during the walk — deterministic, not random).
1293
- if (excludedSet.size > 0) {
869
+ }
870
+ function finalizeShareJournal(run) {
871
+ run.journal.lastSync = new Date().toISOString();
872
+ writeJournal(run.journalSlug, run.journal);
873
+ if (run.excludedSet.size > 0) {
1294
874
  const samplePaths = [];
1295
- for (const p of excludedSet) {
875
+ for (const p of run.excludedSet) {
1296
876
  samplePaths.push(p);
1297
877
  if (samplePaths.length >= 10)
1298
878
  break;
1299
879
  }
1300
- emit({
880
+ run.emit({
1301
881
  type: "personal-vault-out-of-policy",
1302
- count: excludedSet.size,
882
+ count: run.excludedSet.size,
1303
883
  samplePaths,
1304
- byId: { ...excludedById },
884
+ byId: { ...run.excludedById },
1305
885
  });
1306
886
  }
1307
- // ACL scope-exclusion summary. Emit at most once when one or more candidate
1308
- // paths fell outside the run's granted `prefixSet` and were skipped from the
1309
- // upload/delete plan. Informational (NOT an error): the company still syncs
1310
- // its in-scope subset and the run exits 0. Sample capped at 10 (insertion
1311
- // order = walk order, deterministic).
1312
- if (scopeExcludedSet.size > 0) {
887
+ if (run.scopeExcludedSet.size > 0) {
1313
888
  const samplePaths = [];
1314
- for (const p of scopeExcludedSet) {
889
+ for (const p of run.scopeExcludedSet) {
1315
890
  samplePaths.push(p);
1316
891
  if (samplePaths.length >= 10)
1317
892
  break;
1318
893
  }
1319
- emit({
894
+ run.emit({
1320
895
  type: "scope-excluded",
1321
- count: scopeExcludedSet.size,
896
+ count: run.scopeExcludedSet.size,
1322
897
  samplePaths,
1323
898
  });
1324
899
  }
1325
- // Codex P1 (5.36.x): if any worker rejected (unhandled error in
1326
- // headRemoteFile / refreshEntityContext / resolveConflict — paths
1327
- // outside the per-item PUT try/catch), we deliberately let the pool
1328
- // drain AND let post-pool stages (deletes, tombstones, journal write,
1329
- // personal-vault summary) run to completion so journal + remote stay
1330
- // converged on what actually landed. NOW surface the failure to the
1331
- // caller — preserving the first error's stack so debugging works.
1332
- // Aggregate count is reported in the message for visibility when
1333
- // multiple workers failed.
900
+ }
901
+ function throwUploadWorkerErrors(workerErrors) {
1334
902
  if (workerErrors.length > 0) {
1335
903
  const first = workerErrors[0];
1336
904
  if (workerErrors.length > 1) {
1337
- first.message = `${first.message} (and ${workerErrors.length - 1} more upload-worker errors)`;
905
+ first.message =
906
+ first.message +
907
+ " (and " +
908
+ (workerErrors.length - 1) +
909
+ " more upload-worker errors)";
1338
910
  }
1339
911
  throw first;
1340
912
  }
913
+ }
914
+ function buildShareResult(run, counters, filesRefusedStalePaths, conflictPaths, aborted) {
1341
915
  return {
1342
- filesUploaded,
1343
- bytesUploaded,
1344
- filesSkipped,
1345
- filesDeleted,
1346
- filesTombstoned,
1347
- filesRefusedStale,
916
+ filesUploaded: counters.filesUploaded,
917
+ bytesUploaded: counters.bytesUploaded,
918
+ filesSkipped: counters.filesSkipped,
919
+ filesDeleted: counters.filesDeleted,
920
+ filesTombstoned: counters.filesTombstoned,
921
+ filesRefusedStale: counters.filesRefusedStale,
1348
922
  filesRefusedStalePaths,
1349
- filesSuppressedByTombstone,
1350
- filesExcludedByPolicy: excludedSet.size,
1351
- filesExcludedByScope: scopeExcludedSet.size,
923
+ filesSuppressedByTombstone: counters.filesSuppressedByTombstone,
924
+ filesExcludedByPolicy: run.excludedSet.size,
925
+ filesExcludedByScope: run.scopeExcludedSet.size,
1352
926
  conflictPaths,
1353
- aborted: false,
927
+ aborted,
1354
928
  };
1355
929
  }
1356
930
  /**
@@ -1410,22 +984,6 @@ function defaultConsoleLogger(event) {
1410
984
  ` To proceed anyway: re-run with HQ_SYNC_DELETE_BULK_OVERRIDE=1 (or propagateDeletePolicy:"all").`);
1411
985
  }
1412
986
  }
1413
- /**
1414
- * Resolve active company from .hq/config.json or parent directory chain.
1415
- */
1416
- function resolveActiveCompany(hqRoot) {
1417
- const configPath = path.join(hqRoot, ".hq", "config.json");
1418
- if (fs.existsSync(configPath)) {
1419
- try {
1420
- const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
1421
- return config.activeCompany ?? config.companySlug;
1422
- }
1423
- catch {
1424
- // Ignore parse errors
1425
- }
1426
- }
1427
- return undefined;
1428
- }
1429
987
  /**
1430
988
  * Collect files from paths (expanding directories recursively).
1431
989
  *
@@ -1661,20 +1219,6 @@ function isWithinForLink(parent, linkPath) {
1661
1219
  const rel = path.relative(parentReal, candidate);
1662
1220
  return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
1663
1221
  }
1664
- /**
1665
- * Returns true when the remote object appears to have moved since the
1666
- * journal entry's last-recorded sync. Prefers ETag equality; falls back to
1667
- * `lastModified > syncedAt` for legacy entries written before remoteEtag
1668
- * was tracked. Conservative on tie (`<=` skews "remote unchanged") so an
1669
- * S3-side mtime that exactly equals our syncedAt is not treated as drift.
1670
- */
1671
- function hasRemoteChanged(remote, entry) {
1672
- if (entry.remoteEtag) {
1673
- return normalizeEtag(remote.etag) !== entry.remoteEtag;
1674
- }
1675
- const syncedAt = new Date(entry.syncedAt).getTime();
1676
- return remote.lastModified.getTime() > syncedAt;
1677
- }
1678
1222
  /**
1679
1223
  * Resolve each user-supplied share path to a directory under `syncRoot`,
1680
1224
  * returning the company-relative prefix that constrains delete propagation.
@@ -1983,6 +1527,10 @@ async function computeDeletePlan(journal, syncRoot, scopeRoots, shouldSync, poli
1983
1527
  // independently — one failed HEAD doesn't poison the others (errors
1984
1528
  // propagate from the chunk's Promise.all and are surfaced by share()'s
1985
1529
  // outer try/catch, mirroring the existing pre-share error handling).
1530
+ // Warm the GET presigns the HEAD pass reuses so a large candidate set doesn't
1531
+ // mint one presign per HEAD and trip the presign breaker. Mirrors the
1532
+ // new-files + tombstone HEAD-pass pre-primes.
1533
+ await primeObjectTransport(ctx, "get", headCandidates.map((c) => c.key));
1986
1534
  for (let i = 0; i < headCandidates.length; i += DELETE_PLAN_HEAD_CONCURRENCY) {
1987
1535
  const chunk = headCandidates.slice(i, i + DELETE_PLAN_HEAD_CONCURRENCY);
1988
1536
  const results = await Promise.all(chunk.map(async (c) => ({