@indigoai-us/hq-cloud 6.11.12 → 6.11.14

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 (123) hide show
  1. package/.github/workflows/ci.yml +17 -26
  2. package/dist/bin/sync-runner-company.d.ts +35 -0
  3. package/dist/bin/sync-runner-company.d.ts.map +1 -0
  4. package/dist/bin/sync-runner-company.js +290 -0
  5. package/dist/bin/sync-runner-company.js.map +1 -0
  6. package/dist/bin/sync-runner-events.d.ts +12 -0
  7. package/dist/bin/sync-runner-events.d.ts.map +1 -0
  8. package/dist/bin/sync-runner-events.js +12 -0
  9. package/dist/bin/sync-runner-events.js.map +1 -0
  10. package/dist/bin/sync-runner-planning.d.ts +53 -0
  11. package/dist/bin/sync-runner-planning.d.ts.map +1 -0
  12. package/dist/bin/sync-runner-planning.js +59 -0
  13. package/dist/bin/sync-runner-planning.js.map +1 -0
  14. package/dist/bin/sync-runner-rollup.d.ts +24 -0
  15. package/dist/bin/sync-runner-rollup.d.ts.map +1 -0
  16. package/dist/bin/sync-runner-rollup.js +46 -0
  17. package/dist/bin/sync-runner-rollup.js.map +1 -0
  18. package/dist/bin/sync-runner-telemetry.d.ts +5 -0
  19. package/dist/bin/sync-runner-telemetry.d.ts.map +1 -0
  20. package/dist/bin/sync-runner-telemetry.js +5 -0
  21. package/dist/bin/sync-runner-telemetry.js.map +1 -0
  22. package/dist/bin/sync-runner-watch-loop.d.ts +17 -0
  23. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -0
  24. package/dist/bin/sync-runner-watch-loop.js +372 -0
  25. package/dist/bin/sync-runner-watch-loop.js.map +1 -0
  26. package/dist/bin/sync-runner-watch-routes.d.ts +25 -0
  27. package/dist/bin/sync-runner-watch-routes.d.ts.map +1 -0
  28. package/dist/bin/sync-runner-watch-routes.js +74 -0
  29. package/dist/bin/sync-runner-watch-routes.js.map +1 -0
  30. package/dist/bin/sync-runner.d.ts +3 -54
  31. package/dist/bin/sync-runner.d.ts.map +1 -1
  32. package/dist/bin/sync-runner.js +73 -1154
  33. package/dist/bin/sync-runner.js.map +1 -1
  34. package/dist/cli/reindex.d.ts.map +1 -1
  35. package/dist/cli/reindex.js +34 -17
  36. package/dist/cli/reindex.js.map +1 -1
  37. package/dist/cli/reindex.test.js +39 -5
  38. package/dist/cli/reindex.test.js.map +1 -1
  39. package/dist/cli/rescue-classify-ordering.test.js +17 -0
  40. package/dist/cli/rescue-classify-ordering.test.js.map +1 -1
  41. package/dist/cli/rescue-core.d.ts +45 -0
  42. package/dist/cli/rescue-core.d.ts.map +1 -1
  43. package/dist/cli/rescue-core.js +197 -170
  44. package/dist/cli/rescue-core.js.map +1 -1
  45. package/dist/cli/share.d.ts.map +1 -1
  46. package/dist/cli/share.js +235 -677
  47. package/dist/cli/share.js.map +1 -1
  48. package/dist/cli/sync.d.ts.map +1 -1
  49. package/dist/cli/sync.js +412 -727
  50. package/dist/cli/sync.js.map +1 -1
  51. package/dist/cli/sync.test.js +20 -0
  52. package/dist/cli/sync.test.js.map +1 -1
  53. package/dist/daemon-worker.d.ts +2 -2
  54. package/dist/daemon-worker.js +3 -3
  55. package/dist/daemon-worker.js.map +1 -1
  56. package/dist/index.d.ts +2 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +3 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/object-io.js +1 -1
  61. package/dist/object-io.js.map +1 -1
  62. package/dist/remote-pull.d.ts +2 -2
  63. package/dist/remote-pull.d.ts.map +1 -1
  64. package/dist/remote-pull.js +23 -3
  65. package/dist/remote-pull.js.map +1 -1
  66. package/dist/remote-pull.test.js +24 -2
  67. package/dist/remote-pull.test.js.map +1 -1
  68. package/dist/sync/push-receiver.d.ts +6 -0
  69. package/dist/sync/push-receiver.d.ts.map +1 -1
  70. package/dist/sync/push-receiver.js +32 -2
  71. package/dist/sync/push-receiver.js.map +1 -1
  72. package/dist/sync/push-receiver.test.js +31 -0
  73. package/dist/sync/push-receiver.test.js.map +1 -1
  74. package/dist/sync-core.d.ts +27 -0
  75. package/dist/sync-core.d.ts.map +1 -0
  76. package/dist/sync-core.js +54 -0
  77. package/dist/sync-core.js.map +1 -0
  78. package/dist/sync-progress.d.ts +37 -0
  79. package/dist/sync-progress.d.ts.map +1 -0
  80. package/dist/sync-progress.js +104 -0
  81. package/dist/sync-progress.js.map +1 -0
  82. package/dist/sync-progress.test.d.ts +2 -0
  83. package/dist/sync-progress.test.d.ts.map +1 -0
  84. package/dist/sync-progress.test.js +70 -0
  85. package/dist/sync-progress.test.js.map +1 -0
  86. package/dist/vault-client.d.ts.map +1 -1
  87. package/dist/vault-client.js +284 -36
  88. package/dist/vault-client.js.map +1 -1
  89. package/dist/vault-client.test.js +59 -0
  90. package/dist/vault-client.test.js.map +1 -1
  91. package/dist/watcher.d.ts +2 -20
  92. package/dist/watcher.d.ts.map +1 -1
  93. package/dist/watcher.js +3 -113
  94. package/dist/watcher.js.map +1 -1
  95. package/package.json +1 -1
  96. package/src/bin/sync-runner-company.ts +350 -0
  97. package/src/bin/sync-runner-events.ts +25 -0
  98. package/src/bin/sync-runner-planning.ts +121 -0
  99. package/src/bin/sync-runner-rollup.ts +72 -0
  100. package/src/bin/sync-runner-telemetry.ts +8 -0
  101. package/src/bin/sync-runner-watch-loop.ts +443 -0
  102. package/src/bin/sync-runner-watch-routes.ts +86 -0
  103. package/src/bin/sync-runner.ts +96 -1253
  104. package/src/cli/reindex.test.ts +41 -3
  105. package/src/cli/reindex.ts +35 -19
  106. package/src/cli/rescue-classify-ordering.test.ts +20 -0
  107. package/src/cli/rescue-core.ts +252 -176
  108. package/src/cli/share.ts +374 -706
  109. package/src/cli/sync.test.ts +25 -0
  110. package/src/cli/sync.ts +625 -803
  111. package/src/daemon-worker.ts +3 -3
  112. package/src/index.ts +9 -0
  113. package/src/object-io.ts +1 -1
  114. package/src/remote-pull.test.ts +30 -1
  115. package/src/remote-pull.ts +29 -4
  116. package/src/sync/push-receiver.test.ts +35 -0
  117. package/src/sync/push-receiver.ts +41 -2
  118. package/src/sync-core.ts +58 -0
  119. package/src/sync-progress.test.ts +81 -0
  120. package/src/sync-progress.ts +133 -0
  121. package/src/vault-client.test.ts +74 -0
  122. package/src/vault-client.ts +395 -43
  123. package/src/watcher.ts +6 -141
package/dist/cli/share.js CHANGED
@@ -8,6 +8,7 @@ import * as fs from "fs";
8
8
  import * as os from "os";
9
9
  import * as path from "path";
10
10
  import { resolveEntityContext, isExpiringSoon, refreshEntityContext } from "../context.js";
11
+ import { createSyncProgressRecorder } from "../sync-progress.js";
11
12
  import { uploadFile, uploadSymlink, toPosixKey, headRemoteFile, deleteRemoteFile, downloadFile, primeObjectTransport, primeUploads, } from "../s3.js";
12
13
  import * as crypto from "crypto";
13
14
  import { readJournal, writeJournal, hashFile, hashSymlinkTarget, updateEntry, removeEntry, normalizeEtag, PERSONAL_VAULT_JOURNAL_SLUG, migratePersonalVaultJournal, } from "../journal.js";
@@ -16,6 +17,7 @@ import { wrapFilterWithPersonalVaultDefaults, } from "../personal-vault-exclusio
16
17
  import { resolveConflict } from "./conflict.js";
17
18
  import { fetchCompanyTombstones, } from "./tombstones.js";
18
19
  import { isCoveredByAny, isDirInScope, } from "../prefix-coalesce.js";
20
+ import { hasRemoteChanged, isAccessDenied, resolveActiveCompany, resolveTransferConcurrency, } from "../sync-core.js";
19
21
  import { buildConflictId, buildConflictPath, readShortMachineId, } from "../lib/conflict-file.js";
20
22
  import { appendConflictEntry } from "../lib/conflict-index.js";
21
23
  /**
@@ -334,20 +336,6 @@ function computePushPlan(filesToShare, journal, skipUnchanged) {
334
336
  }
335
337
  return { items, filesToUpload, bytesToUpload, filesToSkip };
336
338
  }
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
339
  /**
352
340
  * A conditional-write fence rejection — the SDK's 412 (`name:
353
341
  * "PreconditionFailed"`) or the presigned transport's mirror of it. Means
@@ -398,21 +386,34 @@ function wrapFilterWithScope(underlying, syncRoot, prefixSet, onScopeExcluded) {
398
386
  * Share local file(s) to the entity vault.
399
387
  */
400
388
  export async function share(options) {
389
+ const run = await createPushRunContext(options);
390
+ const counters = createShareCounters();
391
+ const filesRefusedStalePaths = [];
392
+ const conflictPaths = [];
393
+ const plans = await buildSharePlans(run);
394
+ const uploadResult = await executeUploads(run, plans.pushPlan, counters, conflictPaths);
395
+ if (uploadResult.aborted) {
396
+ return buildShareResult(run, counters, filesRefusedStalePaths, uploadResult.abortFlightConflictPaths, true);
397
+ }
398
+ await executeDeletes(run, plans.deletePlan, plans.decommissionPlan, counters, filesRefusedStalePaths);
399
+ finalizeShareJournal(run);
400
+ throwUploadWorkerErrors(uploadResult.workerErrors);
401
+ return buildShareResult(run, counters, filesRefusedStalePaths, conflictPaths, false);
402
+ }
403
+ const REFUSED_STALE_PATH_CAP = 50;
404
+ async function createPushRunContext(options) {
401
405
  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
406
  let propagateDeletePolicy = options.propagateDeletePolicy ?? "owned-only";
412
- 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.
407
+ const baseEmit = options.onEvent ?? defaultConsoleLogger;
408
+ // Mirror push progress into the shared cross-process snapshot (see sync.ts).
409
+ const recordProgress = createSyncProgressRecorder({
410
+ company: company ?? null,
411
+ phase: "push",
412
+ });
413
+ const emit = (event) => {
414
+ baseEmit(event);
415
+ recordProgress(event);
416
+ };
416
417
  if (vaultConfig && entityContext) {
417
418
  throw new Error("share() requires exactly one of `vaultConfig` or `entityContext`, not both. " +
418
419
  "Pass `vaultConfig` to vend credentials internally, or `entityContext` to use pre-vended ones.");
@@ -421,72 +422,20 @@ export async function share(options) {
421
422
  throw new Error("share() requires either `vaultConfig` (for internal STS vending) " +
422
423
  "or `entityContext` (pre-vended credentials).");
423
424
  }
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
425
  const companyRef = company ?? entityContext?.slug ?? resolveActiveCompany(hqRoot);
428
426
  if (!companyRef) {
429
427
  throw new Error("No company specified and no active company found. " +
430
428
  "Use --company <slug> or set up .hq/config.json.");
431
429
  }
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
430
+ const ctx = entityContext
441
431
  ? entityContext
442
432
  : 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
433
  if (ctx.uid.startsWith("prs_") && propagateDeletePolicy === "owned-only") {
461
434
  propagateDeletePolicy = "currency-gated";
462
435
  }
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
436
  const syncRoot = options.personalMode === true
472
437
  ? hqRoot
473
438
  : 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
439
  const ignoreFilter = createIgnoreFilter(hqRoot);
491
440
  const excludedSet = new Set();
492
441
  const excludedById = {};
@@ -496,12 +445,6 @@ export async function share(options) {
496
445
  excludedSet.add(rel);
497
446
  excludedById[match.id] = (excludedById[match.id] ?? 0) + 1;
498
447
  };
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
448
  const scopeExcludedSet = new Set();
506
449
  const onScopeExcluded = (rel) => {
507
450
  scopeExcludedSet.add(rel);
@@ -513,106 +456,67 @@ export async function share(options) {
513
456
  ? wrapFilterWithScope(baseFilter, syncRoot, options.prefixSet, onScopeExcluded)
514
457
  : baseFilter;
515
458
  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
459
  if (journalSlug === PERSONAL_VAULT_JOURNAL_SLUG)
520
460
  migratePersonalVaultJournal();
521
461
  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)
462
+ return {
463
+ options,
464
+ paths,
465
+ message,
466
+ onConflict,
467
+ vaultConfig,
468
+ entityContext,
469
+ hqRoot,
470
+ skipUnchanged,
471
+ propagateDeletes,
472
+ propagateDeletePolicy,
473
+ emit,
474
+ companyRef,
475
+ ctx,
476
+ syncRoot,
477
+ shouldSync,
478
+ journalSlug,
479
+ journal,
480
+ excludedSet,
481
+ excludedById,
482
+ scopeExcludedSet,
483
+ };
484
+ }
485
+ function createShareCounters() {
486
+ return {
487
+ filesUploaded: 0,
488
+ bytesUploaded: 0,
489
+ filesSkipped: 0,
490
+ filesDeleted: 0,
491
+ filesTombstoned: 0,
492
+ filesRefusedStale: 0,
493
+ filesSuppressedByTombstone: 0,
494
+ };
495
+ }
496
+ async function buildSharePlans(run) {
497
+ const filesToShare = collectFiles(run.paths, run.hqRoot, run.syncRoot, run.shouldSync);
498
+ const pushPlan = computePushPlan(filesToShare, run.journal, run.skipUnchanged === true);
499
+ const deleteScopeRoots = run.propagateDeletes === true
500
+ ? resolveDeleteScopeRoots(run.paths, run.hqRoot, run.syncRoot)
555
501
  : [];
556
- const deletePlan = propagateDeletes === true
557
- ? await computeDeletePlan(journal, syncRoot, deleteScopeRoots, shouldSync, propagateDeletePolicy, ctx)
502
+ const deletePlan = run.propagateDeletes === true
503
+ ? await computeDeletePlan(run.journal, run.syncRoot, deleteScopeRoots, run.shouldSync, run.propagateDeletePolicy, run.ctx)
558
504
  : { 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]))
505
+ const decommissionPlan = (run.options.decommissionPrefixes ?? []).length > 0
506
+ ? computeDecommissionPlan(run.journal, run.options.decommissionPrefixes ?? [], run.propagateDeletePolicy, new Set([...deletePlan.toDelete, ...deletePlan.toTombstone]))
589
507
  : [];
590
- emit({
508
+ run.emit({
591
509
  type: "plan",
592
- // share() is push-only; pull counts are sourced from sync()'s plan event.
593
510
  filesToDownload: 0,
594
511
  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.
512
+ filesToUpload: pushPlan.filesToUpload,
513
+ bytesToUpload: pushPlan.bytesToUpload,
514
+ filesToSkip: pushPlan.filesToSkip,
600
515
  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
516
  filesToDelete: deletePlan.toDelete.length + decommissionPlan.length,
609
517
  });
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
518
  if (deletePlan.bulkAsymmetry) {
615
- emit({
519
+ run.emit({
616
520
  type: "delete-refused-bulk-asymmetry",
617
521
  candidates: deletePlan.bulkAsymmetry.candidates,
618
522
  inScope: deletePlan.bulkAsymmetry.inScope,
@@ -620,197 +524,85 @@ export async function share(options) {
620
524
  samplePaths: deletePlan.bulkAsymmetry.samplePaths,
621
525
  });
622
526
  }
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.
527
+ return { pushPlan, deletePlan, decommissionPlan };
528
+ }
529
+ async function executeUploads(run, pushPlan, counters, conflictPaths) {
530
+ const TRANSFER_CONCURRENCY = resolveTransferConcurrency();
662
531
  let conflictPromptChain = Promise.resolve();
663
532
  const resolveConflictSerialized = (info) => {
664
- const run = conflictPromptChain.then(() => resolveConflict(info, onConflict));
665
- conflictPromptChain = run.then(() => undefined, () => undefined);
666
- return run;
533
+ const resolution = conflictPromptChain.then(() => resolveConflict(info, run.onConflict));
534
+ conflictPromptChain = resolution.then(() => undefined, () => undefined);
535
+ return resolution;
667
536
  };
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)
537
+ const fileTombstones = run.options.fileTombstones ??
538
+ (!run.ctx.uid.startsWith("prs_") && run.vaultConfig
539
+ ? await fetchCompanyTombstones(run.vaultConfig, run.ctx.uid)
688
540
  : new Map());
689
- // Phase A: serial classification pass — handle skips inline, collect
690
- // upload candidates for the parallel pool.
691
541
  const uploadItems = [];
692
- for (const item of plan.items) {
542
+ for (const item of pushPlan.items) {
693
543
  if (item.action === "skip-size-limit") {
694
- emit({
544
+ run.emit({
695
545
  type: "error",
696
546
  path: item.relativePath,
697
547
  message: "file exceeds size limit",
698
548
  });
699
- filesSkipped++;
549
+ counters.filesSkipped++;
700
550
  continue;
701
551
  }
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;
552
+ if (item.action === "upload") {
553
+ if (fileTombstones.size > 0) {
554
+ const ts = fileTombstones.get(toPosixKey(item.relativePath));
555
+ if (ts !== undefined) {
556
+ const entry = run.journal.files[item.relativePath];
557
+ if (entry && entry.hash === item.localHash) {
558
+ counters.filesSuppressedByTombstone++;
559
+ run.emit({
560
+ type: "upload-suppressed-tombstone",
561
+ path: item.relativePath,
562
+ deletedAt: ts.deletedAt,
563
+ });
564
+ continue;
565
+ }
723
566
  }
724
567
  }
568
+ uploadItems.push(item);
569
+ continue;
725
570
  }
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
- }
571
+ if (item.restamp) {
572
+ const existing = run.journal.files[item.relativePath];
573
+ if (existing && existing.hash) {
574
+ existing.mtimeMs = item.restamp.mtimeMs;
575
+ existing.size = item.restamp.size;
740
576
  }
741
- filesSkipped++;
742
- continue;
743
577
  }
744
- uploadItems.push(item);
578
+ counters.filesSkipped++;
745
579
  }
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) => ({
580
+ await primeUploads(run.ctx, uploadItems.map((it) => ({
752
581
  key: it.relativePath,
753
582
  localPath: it.absolutePath,
754
583
  isSymlink: it.kind === "symlink",
755
- author: options.author,
584
+ author: run.options.author,
756
585
  })));
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.
586
+ // Warm the GET presigns the per-item conflict HEAD (remoteMeta) reuses, so a
587
+ // large upload set doesn't mint one presign per HEAD and burst/trip the
588
+ // presign breaker. Mirrors the new-files + tombstone pre-primes on the pull.
589
+ await primeObjectTransport(run.ctx, "get", uploadItems.map((it) => it.relativePath));
761
590
  let aborted = false;
762
591
  let abortFlightConflictPaths = [];
763
592
  const processUploadItem = async (item) => {
764
593
  if (aborted)
765
594
  return;
766
595
  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);
596
+ if (run.vaultConfig && isExpiringSoon(run.ctx.expiresAt)) {
597
+ run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
773
598
  }
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
599
  let remoteMeta;
808
600
  try {
809
- remoteMeta = await headRemoteFile(ctx, relativePath);
601
+ remoteMeta = await headRemoteFile(run.ctx, relativePath);
810
602
  }
811
603
  catch (headErr) {
812
604
  if (isAccessDenied(headErr)) {
813
- emit({
605
+ run.emit({
814
606
  type: "error",
815
607
  path: relativePath,
816
608
  message: "skipped: outside granted ACL scope (server returned 403 " +
@@ -822,21 +614,15 @@ export async function share(options) {
822
614
  throw headErr;
823
615
  }
824
616
  if (remoteMeta) {
825
- const journalEntry = journal.files[relativePath];
617
+ const journalEntry = run.journal.files[relativePath];
826
618
  const localChanged = !!journalEntry && journalEntry.hash !== localHash;
827
619
  const remoteChanged = !!journalEntry && hasRemoteChanged(remoteMeta, journalEntry);
828
620
  let isFreshCollision = false;
829
621
  let multipartConverged = false;
830
622
  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
623
  isFreshCollision = true;
835
624
  }
836
625
  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
626
  const remoteEtagNormalized = normalizeEtag(remoteMeta.etag);
841
627
  const isMultipart = /-\d+$/.test(remoteEtagNormalized);
842
628
  if (!isMultipart) {
@@ -845,44 +631,22 @@ export async function share(options) {
845
631
  if (localMd5 !== remoteEtagNormalized) {
846
632
  isFreshCollision = true;
847
633
  }
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
634
  }
852
635
  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);
636
+ const remoteDiffers = await remoteContentDiffers(run.ctx, relativePath, localHash, run.hqRoot);
868
637
  if (remoteDiffers) {
869
638
  isFreshCollision = true;
870
639
  }
871
640
  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
641
  multipartConverged = true;
878
642
  }
879
643
  }
880
644
  }
881
645
  if (multipartConverged) {
882
646
  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++;
647
+ updateEntry(run.journal, relativePath, localHash, lstat.size, "up", remoteMeta.etag, lstat.mtimeMs);
648
+ run.emit({ type: "reconciled", path: relativePath, direction: "push" });
649
+ counters.filesSkipped++;
886
650
  return;
887
651
  }
888
652
  if ((localChanged && remoteChanged) || isFreshCollision) {
@@ -893,130 +657,53 @@ export async function share(options) {
893
657
  remoteModified: remoteMeta.lastModified,
894
658
  direction: "push",
895
659
  });
896
- emit({
660
+ run.emit({
897
661
  type: "conflict",
898
662
  path: relativePath,
899
663
  direction: "push",
900
664
  resolution,
901
665
  });
902
666
  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
667
  aborted = true;
908
668
  abortFlightConflictPaths = [...conflictPaths];
909
669
  return;
910
670
  }
911
671
  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
672
  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
- }
673
+ await writePushConflictMirror(run, item, normalizeEtag(remoteMeta.etag));
954
674
  }
955
- filesSkipped++;
675
+ counters.filesSkipped++;
956
676
  return;
957
677
  }
958
- // "overwrite" falls through to upload
959
678
  }
960
679
  }
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
680
  if (aborted)
967
681
  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
682
  const precondition = remoteMeta
981
683
  ? { ifMatch: remoteMeta.etag }
982
684
  : { 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
685
  const performUpload = async (pc) => {
990
686
  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
687
  const lstat = fs.lstatSync(absolutePath);
997
688
  const size = isSymlinkUpload ? 0 : lstat.size;
998
689
  const mtimeMs = lstat.mtimeMs;
999
690
  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,
691
+ ? await uploadSymlink(run.ctx, item.target, relativePath, run.options.author, pc)
692
+ : await uploadFile(run.ctx, absolutePath, relativePath, run.options.author, pc);
693
+ updateEntry(run.journal, relativePath, localHash, size, "up", etag, mtimeMs);
694
+ if (run.message) {
695
+ run.journal.files[relativePath] = {
696
+ ...run.journal.files[relativePath],
697
+ message: run.message,
1011
698
  };
1012
699
  }
1013
- filesUploaded++;
1014
- bytesUploaded += size;
1015
- emit({
700
+ counters.filesUploaded++;
701
+ counters.bytesUploaded += size;
702
+ run.emit({
1016
703
  type: "progress",
1017
704
  path: relativePath,
1018
705
  bytes: size,
1019
- ...(message ? { message } : {}),
706
+ ...(run.message ? { message: run.message } : {}),
1020
707
  });
1021
708
  };
1022
709
  try {
@@ -1024,17 +711,13 @@ export async function share(options) {
1024
711
  }
1025
712
  catch (err) {
1026
713
  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
714
  conflictPaths.push(relativePath);
1032
715
  const resolution = await resolveConflictSerialized({
1033
716
  path: relativePath,
1034
717
  localHash,
1035
718
  direction: "push",
1036
719
  });
1037
- emit({
720
+ run.emit({
1038
721
  type: "conflict",
1039
722
  path: relativePath,
1040
723
  direction: "push",
@@ -1046,13 +729,11 @@ export async function share(options) {
1046
729
  return;
1047
730
  }
1048
731
  if (resolution === "overwrite") {
1049
- // Explicit clobber consent — retry once without the fence. A
1050
- // second failure falls through to the generic error emit.
1051
732
  try {
1052
733
  await performUpload(undefined);
1053
734
  }
1054
735
  catch (retryErr) {
1055
- emit({
736
+ run.emit({
1056
737
  type: "error",
1057
738
  path: relativePath,
1058
739
  message: retryErr instanceof Error ? retryErr.message : String(retryErr),
@@ -1060,50 +741,11 @@ export async function share(options) {
1060
741
  }
1061
742
  return;
1062
743
  }
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++;
744
+ await writePushConflictMirror(run, item, remoteMeta ? normalizeEtag(remoteMeta.etag) : "");
745
+ counters.filesSkipped++;
1104
746
  return;
1105
747
  }
1106
- emit({
748
+ run.emit({
1107
749
  type: "error",
1108
750
  path: relativePath,
1109
751
  message: isAccessDenied(err)
@@ -1116,25 +758,6 @@ export async function share(options) {
1116
758
  });
1117
759
  }
1118
760
  };
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
761
  const workerErrors = [];
1139
762
  {
1140
763
  const queue = [...uploadItems];
@@ -1155,87 +778,63 @@ export async function share(options) {
1155
778
  await Promise.race(Array.from(inFlight));
1156
779
  }
1157
780
  else {
1158
- // Aborted with nothing in flight → exit the drain loop.
1159
781
  break;
1160
782
  }
1161
783
  }
1162
784
  }
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
- };
785
+ return { aborted, abortFlightConflictPaths, workerErrors };
786
+ }
787
+ async function writePushConflictMirror(run, item, remoteHash) {
788
+ try {
789
+ const detectedAt = new Date().toISOString();
790
+ const machineId = readShortMachineId(run.hqRoot);
791
+ const originalRelative = path.relative(run.hqRoot, item.absolutePath);
792
+ const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
793
+ const conflictAbs = path.join(run.hqRoot, conflictRelative);
794
+ if (!isMaterializationPathStillContained(run.syncRoot, conflictAbs)) {
795
+ run.emit({
796
+ type: "error",
797
+ path: item.relativePath,
798
+ message: "conflict mirror skipped: local parent escaped the sync root",
799
+ });
800
+ }
801
+ else {
802
+ await downloadFile(run.ctx, item.relativePath, conflictAbs);
803
+ appendConflictEntry(run.hqRoot, {
804
+ id: buildConflictId(originalRelative, detectedAt),
805
+ originalPath: originalRelative,
806
+ conflictPath: conflictRelative,
807
+ detectedAt,
808
+ side: "push",
809
+ machineId,
810
+ localHash: item.localHash,
811
+ remoteHash,
812
+ });
813
+ }
1197
814
  }
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.
815
+ catch (mirrorErr) {
816
+ run.emit({
817
+ type: "error",
818
+ path: item.relativePath,
819
+ message: "conflict mirror write failed: " +
820
+ (mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)),
821
+ });
822
+ }
823
+ }
824
+ async function executeDeletes(run, deletePlan, decommissionPlan, counters, filesRefusedStalePaths) {
1226
825
  const deleteKeys = [...deletePlan.toDelete, ...decommissionPlan];
1227
- await primeObjectTransport(ctx, "delete", deleteKeys);
826
+ await primeObjectTransport(run.ctx, "delete", deleteKeys);
1228
827
  for (const relativePath of deleteKeys) {
1229
- if (vaultConfig && isExpiringSoon(ctx.expiresAt)) {
1230
- ctx = await refreshEntityContext(companyRef, vaultConfig);
828
+ if (run.vaultConfig && isExpiringSoon(run.ctx.expiresAt)) {
829
+ run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
1231
830
  }
1232
831
  try {
1233
- const entry = journal.files[relativePath];
832
+ const entry = run.journal.files[relativePath];
1234
833
  const size = entry?.size ?? 0;
1235
- await deleteRemoteFile(ctx, relativePath);
1236
- removeEntry(journal, relativePath);
1237
- filesDeleted++;
1238
- emit({
834
+ await deleteRemoteFile(run.ctx, relativePath);
835
+ removeEntry(run.journal, relativePath);
836
+ counters.filesDeleted++;
837
+ run.emit({
1239
838
  type: "progress",
1240
839
  path: relativePath,
1241
840
  bytes: size,
@@ -1243,7 +842,7 @@ export async function share(options) {
1243
842
  });
1244
843
  }
1245
844
  catch (err) {
1246
- emit({
845
+ run.emit({
1247
846
  type: "error",
1248
847
  path: relativePath,
1249
848
  message: err instanceof Error ? err.message : String(err),
@@ -1251,9 +850,9 @@ export async function share(options) {
1251
850
  }
1252
851
  }
1253
852
  for (const relativePath of deletePlan.toTombstone) {
1254
- removeEntry(journal, relativePath);
1255
- filesTombstoned++;
1256
- emit({
853
+ removeEntry(run.journal, relativePath);
854
+ counters.filesTombstoned++;
855
+ run.emit({
1257
856
  type: "progress",
1258
857
  path: relativePath,
1259
858
  bytes: 0,
@@ -1261,20 +860,15 @@ export async function share(options) {
1261
860
  message: "tombstone (remote already 404)",
1262
861
  });
1263
862
  }
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
863
  const decommissionedSet = decommissionPlan.length > 0 ? new Set(decommissionPlan) : null;
1270
864
  for (const refused of deletePlan.refusedStale) {
1271
865
  if (decommissionedSet && decommissionedSet.has(refused.key))
1272
866
  continue;
1273
- filesRefusedStale++;
867
+ counters.filesRefusedStale++;
1274
868
  if (filesRefusedStalePaths.length < REFUSED_STALE_PATH_CAP) {
1275
869
  filesRefusedStalePaths.push(refused.key);
1276
870
  }
1277
- emit({
871
+ run.emit({
1278
872
  type: "delete-refused-stale-etag",
1279
873
  path: refused.key,
1280
874
  journalEtag: refused.journalEtag,
@@ -1282,75 +876,65 @@ export async function share(options) {
1282
876
  reason: refused.reason,
1283
877
  });
1284
878
  }
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) {
879
+ }
880
+ function finalizeShareJournal(run) {
881
+ run.journal.lastSync = new Date().toISOString();
882
+ writeJournal(run.journalSlug, run.journal);
883
+ if (run.excludedSet.size > 0) {
1294
884
  const samplePaths = [];
1295
- for (const p of excludedSet) {
885
+ for (const p of run.excludedSet) {
1296
886
  samplePaths.push(p);
1297
887
  if (samplePaths.length >= 10)
1298
888
  break;
1299
889
  }
1300
- emit({
890
+ run.emit({
1301
891
  type: "personal-vault-out-of-policy",
1302
- count: excludedSet.size,
892
+ count: run.excludedSet.size,
1303
893
  samplePaths,
1304
- byId: { ...excludedById },
894
+ byId: { ...run.excludedById },
1305
895
  });
1306
896
  }
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) {
897
+ if (run.scopeExcludedSet.size > 0) {
1313
898
  const samplePaths = [];
1314
- for (const p of scopeExcludedSet) {
899
+ for (const p of run.scopeExcludedSet) {
1315
900
  samplePaths.push(p);
1316
901
  if (samplePaths.length >= 10)
1317
902
  break;
1318
903
  }
1319
- emit({
904
+ run.emit({
1320
905
  type: "scope-excluded",
1321
- count: scopeExcludedSet.size,
906
+ count: run.scopeExcludedSet.size,
1322
907
  samplePaths,
1323
908
  });
1324
909
  }
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.
910
+ }
911
+ function throwUploadWorkerErrors(workerErrors) {
1334
912
  if (workerErrors.length > 0) {
1335
913
  const first = workerErrors[0];
1336
914
  if (workerErrors.length > 1) {
1337
- first.message = `${first.message} (and ${workerErrors.length - 1} more upload-worker errors)`;
915
+ first.message =
916
+ first.message +
917
+ " (and " +
918
+ (workerErrors.length - 1) +
919
+ " more upload-worker errors)";
1338
920
  }
1339
921
  throw first;
1340
922
  }
923
+ }
924
+ function buildShareResult(run, counters, filesRefusedStalePaths, conflictPaths, aborted) {
1341
925
  return {
1342
- filesUploaded,
1343
- bytesUploaded,
1344
- filesSkipped,
1345
- filesDeleted,
1346
- filesTombstoned,
1347
- filesRefusedStale,
926
+ filesUploaded: counters.filesUploaded,
927
+ bytesUploaded: counters.bytesUploaded,
928
+ filesSkipped: counters.filesSkipped,
929
+ filesDeleted: counters.filesDeleted,
930
+ filesTombstoned: counters.filesTombstoned,
931
+ filesRefusedStale: counters.filesRefusedStale,
1348
932
  filesRefusedStalePaths,
1349
- filesSuppressedByTombstone,
1350
- filesExcludedByPolicy: excludedSet.size,
1351
- filesExcludedByScope: scopeExcludedSet.size,
933
+ filesSuppressedByTombstone: counters.filesSuppressedByTombstone,
934
+ filesExcludedByPolicy: run.excludedSet.size,
935
+ filesExcludedByScope: run.scopeExcludedSet.size,
1352
936
  conflictPaths,
1353
- aborted: false,
937
+ aborted,
1354
938
  };
1355
939
  }
1356
940
  /**
@@ -1410,22 +994,6 @@ function defaultConsoleLogger(event) {
1410
994
  ` To proceed anyway: re-run with HQ_SYNC_DELETE_BULK_OVERRIDE=1 (or propagateDeletePolicy:"all").`);
1411
995
  }
1412
996
  }
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
997
  /**
1430
998
  * Collect files from paths (expanding directories recursively).
1431
999
  *
@@ -1661,20 +1229,6 @@ function isWithinForLink(parent, linkPath) {
1661
1229
  const rel = path.relative(parentReal, candidate);
1662
1230
  return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
1663
1231
  }
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
1232
  /**
1679
1233
  * Resolve each user-supplied share path to a directory under `syncRoot`,
1680
1234
  * returning the company-relative prefix that constrains delete propagation.
@@ -1983,6 +1537,10 @@ async function computeDeletePlan(journal, syncRoot, scopeRoots, shouldSync, poli
1983
1537
  // independently — one failed HEAD doesn't poison the others (errors
1984
1538
  // propagate from the chunk's Promise.all and are surfaced by share()'s
1985
1539
  // outer try/catch, mirroring the existing pre-share error handling).
1540
+ // Warm the GET presigns the HEAD pass reuses so a large candidate set doesn't
1541
+ // mint one presign per HEAD and trip the presign breaker. Mirrors the
1542
+ // new-files + tombstone HEAD-pass pre-primes.
1543
+ await primeObjectTransport(ctx, "get", headCandidates.map((c) => c.key));
1986
1544
  for (let i = 0; i < headCandidates.length; i += DELETE_PLAN_HEAD_CONCURRENCY) {
1987
1545
  const chunk = headCandidates.slice(i, i + DELETE_PLAN_HEAD_CONCURRENCY);
1988
1546
  const results = await Promise.all(chunk.map(async (c) => ({