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