@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/dist/cli/sync.js
CHANGED
|
@@ -7,12 +7,14 @@
|
|
|
7
7
|
import * as fs from "fs";
|
|
8
8
|
import * as path from "path";
|
|
9
9
|
import { resolveEntityContext, isExpiringSoon, refreshEntityContext } from "../context.js";
|
|
10
|
+
import { createSyncProgressRecorder } from "../sync-progress.js";
|
|
10
11
|
import { downloadFile, listRemoteFiles, headRemoteFile, primeObjectTransport, toPosixKey, } from "../s3.js";
|
|
11
12
|
import { readJournal, writeJournal, hashFile, hashSymlinkTarget, updateEntry, removeEntry, getEntry, normalizeEtag, migrateToV2, gcTombstones, lastPullRecord, appendPullRecord, generatePullId, PERSONAL_VAULT_JOURNAL_SLUG, migratePersonalVaultJournal, } from "../journal.js";
|
|
12
13
|
import { PERSONAL_VAULT_MANIFEST_KEY } from "../personal-vault.js";
|
|
13
14
|
import { buildScopeShrinkPlan, applyScopeShrink, ScopeShrinkBlockedError, ScopeShrinkLargePruneError, } from "../scope-shrink.js";
|
|
14
15
|
import { coalescePrefixes, isCoveredByAny, } from "../prefix-coalesce.js";
|
|
15
16
|
import { createIgnoreFilter } from "../ignore.js";
|
|
17
|
+
import { hasRemoteChanged, isAccessDenied, resolveActiveCompany, resolveTransferConcurrency, } from "../sync-core.js";
|
|
16
18
|
import { isEphemeralPath, isMalformedVaultKey } from "./share.js";
|
|
17
19
|
import { resolveConflict } from "./conflict.js";
|
|
18
20
|
import { buildConflictId, buildConflictPath, readShortMachineId, } from "../lib/conflict-file.js";
|
|
@@ -129,193 +131,151 @@ export async function sync(options) {
|
|
|
129
131
|
return withOperationLock(options.hqRoot, "sync", () => syncWithOperationLockHeld(options));
|
|
130
132
|
}
|
|
131
133
|
async function syncWithOperationLockHeld(options) {
|
|
132
|
-
const
|
|
133
|
-
const
|
|
134
|
-
|
|
134
|
+
const run = await buildPullContext(options);
|
|
135
|
+
const plan = planPull(run);
|
|
136
|
+
emitPullPlan(run.emit, plan);
|
|
137
|
+
const scopePlan = planScopeShrink(run);
|
|
138
|
+
const scopeRun = executeScopeShrink(run, scopePlan);
|
|
139
|
+
const counters = createPullCounters();
|
|
140
|
+
const transferConcurrency = resolveTransferConcurrency();
|
|
141
|
+
const conflictRun = await executeConflictExecutor(run, plan, scopeRun, counters);
|
|
142
|
+
if (conflictRun.abortResult) {
|
|
143
|
+
return conflictRun.abortResult;
|
|
144
|
+
}
|
|
145
|
+
await executeDownloadExecutor(run, conflictRun.downloadItems, transferConcurrency, counters);
|
|
146
|
+
await emitAndReportNewFiles(run, plan);
|
|
147
|
+
await verifyPlannedJournalTombstones(run, plan);
|
|
148
|
+
executeJournalTombstoneDeletes(run, plan, counters);
|
|
149
|
+
return finalizePullRun(run, plan, scopeRun, counters);
|
|
150
|
+
}
|
|
151
|
+
async function buildPullContext(options) {
|
|
152
|
+
const { company, vaultConfig, hqRoot } = options;
|
|
153
|
+
const baseEmit = options.onEvent ?? defaultConsoleLogger;
|
|
154
|
+
// Mirror every progress event into the shared cross-process snapshot so the
|
|
155
|
+
// menubar shows live progress for THIS sync regardless of who launched it
|
|
156
|
+
// (auto-sync / Sync Now / CLI). Best-effort; never affects the sync.
|
|
157
|
+
const recordProgress = createSyncProgressRecorder({
|
|
158
|
+
company: company ?? null,
|
|
159
|
+
phase: "pull",
|
|
160
|
+
});
|
|
161
|
+
const emit = (event) => {
|
|
162
|
+
baseEmit(event);
|
|
163
|
+
recordProgress(event);
|
|
164
|
+
};
|
|
135
165
|
const companyRef = company ?? resolveActiveCompany(hqRoot);
|
|
136
166
|
if (!companyRef) {
|
|
137
167
|
throw new Error("No company specified and no active company found. " +
|
|
138
168
|
"Use --company <slug> or set up .hq/config.json.");
|
|
139
169
|
}
|
|
140
|
-
|
|
141
|
-
let ctx = await resolveEntityContext(companyRef, vaultConfig);
|
|
142
|
-
// Every company's files land under companies/{slug}/ so fanning out multiple
|
|
143
|
-
// companies into the same hqRoot doesn't cross-clobber files with overlapping
|
|
144
|
-
// S3 keys (e.g. every company has a .hq/manifest.json). Remote keys stay
|
|
145
|
-
// company-relative; the prefix lives only on disk.
|
|
146
|
-
// In personalMode the journal slug + S3 keys are person-relative (e.g. "docs/foo.md");
|
|
147
|
-
// the local target is `hqRoot` directly, NOT `<hqRoot>/companies/<personSlug>/`. This
|
|
148
|
-
// keeps round-trip parity with the Rust personal first-push (Step 7) which sources
|
|
149
|
-
// `<hqRoot>/docs/foo.md`.
|
|
170
|
+
const ctx = await resolveEntityContext(companyRef, vaultConfig);
|
|
150
171
|
const companyRoot = options.personalMode === true
|
|
151
172
|
? hqRoot
|
|
152
173
|
: path.join(hqRoot, "companies", ctx.slug);
|
|
153
174
|
const shouldSync = createIgnoreFilter(hqRoot);
|
|
154
175
|
const journalSlug = options.journalSlug ?? ctx.slug;
|
|
155
176
|
const startedAt = new Date().toISOString();
|
|
156
|
-
// Personal-vault callers must never start from an empty journal when only
|
|
157
|
-
// the legacy `personal` file exists (mass re-download/etag churn). Seeding
|
|
158
|
-
// here — inside the engine — covers every consumer (sync-runner already
|
|
159
|
-
// seeds; hq-cli historically didn't, which split the vault's bookkeeping
|
|
160
|
-
// across two journal files and re-flagged synced files as conflicts).
|
|
161
177
|
if (journalSlug === PERSONAL_VAULT_JOURNAL_SLUG)
|
|
162
178
|
migratePersonalVaultJournal();
|
|
163
|
-
// Migrate v1 → v2 in place so the scope-shrink / pull-record machinery has
|
|
164
|
-
// its fields, and GC any tombstones past the 30-day retention window before
|
|
165
|
-
// we re-evaluate orphans (so a long-pruned path can re-download cleanly).
|
|
166
179
|
const journal = migrateToV2(readJournal(journalSlug));
|
|
167
180
|
gcTombstones(journal, Date.now());
|
|
168
|
-
// ── Effective download scope (US-005) ─────────────────────────────────────
|
|
169
|
-
// `all` → prefixSet `[""]`, which `isCoveredByAny` treats as "covers
|
|
170
|
-
// everything" — so the download filter and the scope-shrink
|
|
171
|
-
// comparison both become no-ops, preserving legacy full-bucket
|
|
172
|
-
// behavior bit-for-bit.
|
|
173
|
-
// `shared`/`custom` → the coalesced, company-relative prefix set the runner
|
|
174
|
-
// resolved. An empty set means "nothing in scope" → download
|
|
175
|
-
// nothing (the runner falls back to `all` on resolution errors, so
|
|
176
|
-
// empty here is an intentional "nothing shared", never a failure).
|
|
177
181
|
const syncMode = options.syncMode ?? "all";
|
|
178
182
|
const currentPrefixSet = syncMode === "all" ? [""] : coalescePrefixes(options.prefixSet ?? []);
|
|
179
|
-
// Authorship guard input (scope-shrink): the caller's own Cognito sub,
|
|
180
|
-
// injected by the entry point (the runner sources it from its decoded
|
|
181
|
-
// idToken claims — the same sub stamped onto uploads as `created-by-sub`).
|
|
182
|
-
// Undefined degrades safely: own-author files lose their special shield, but
|
|
183
|
-
// the `protectUnknownAuthors` conservative path below still prevents a
|
|
184
|
-
// routine sync from deleting anything it can't prove is foreign.
|
|
185
|
-
const callerSub = options.callerSub;
|
|
186
|
-
let filesDownloaded = 0;
|
|
187
|
-
let bytesDownloaded = 0;
|
|
188
|
-
let filesSkipped = 0;
|
|
189
|
-
let conflicts = 0;
|
|
190
|
-
let filesTombstoned = 0;
|
|
191
|
-
let filesOutOfScope = 0;
|
|
192
|
-
const conflictPaths = [];
|
|
193
|
-
// List all remote files (IAM session policy filters at the AWS layer)
|
|
194
183
|
const remoteFiles = await listRemoteFiles(ctx);
|
|
195
|
-
|
|
196
|
-
// resurrection of an intentionally-deleted object (delete-resync). Done in
|
|
197
|
-
// parallel intent with the LIST above conceptually, but kept serial here for
|
|
198
|
-
// a clean read of `ctx`; best-effort — a failed read degrades to an empty map
|
|
199
|
-
// (no suppression), preserving the pre-fix behavior. ctx.uid is the verified
|
|
200
|
-
// companyUid the tombstone rows are keyed under.
|
|
201
|
-
//
|
|
202
|
-
// SKIP for the personal vault: its `ctx.uid` is a personUid (`prs_…`), but
|
|
203
|
-
// `GET /v1/files/tombstones?company=…` is COMPANY-scoped server-side
|
|
204
|
-
// (findCallerWithMembership), so a personal-vault request resolves
|
|
205
|
-
// `company=prs_…` to no membership and is correctly rejected with
|
|
206
|
-
// `403 "No active membership for caller in company prs_…"`. That 403 is
|
|
207
|
-
// benign for the pull (it already degrades to the empty map below), but
|
|
208
|
-
// hq-pro captures EVERY one as a Sentry warning — the per-personal-vault
|
|
209
|
-
// no-membership cluster (one Sentry issue per signed-in user). Personal-vault
|
|
210
|
-
// delete-resync was never a committed feature and there is no person-scoped
|
|
211
|
-
// tombstone path, so for the personal target we skip the fetch and use an
|
|
212
|
-
// empty map — byte-for-byte the current degraded behavior, minus the 403 spam.
|
|
213
|
-
// FUTURE FOLLOW-UP (not built here): if personal-vault delete-resync is
|
|
214
|
-
// wanted, it needs a real person-scoped tombstone endpoint + client read.
|
|
215
|
-
const tombstones = options.personalMode === true
|
|
184
|
+
const fileTombstones = options.personalMode === true
|
|
216
185
|
? new Map()
|
|
217
186
|
: await fetchCompanyTombstones(vaultConfig, ctx.uid);
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
187
|
+
return {
|
|
188
|
+
options,
|
|
189
|
+
companyRef,
|
|
190
|
+
vaultConfig,
|
|
191
|
+
hqRoot,
|
|
192
|
+
emit,
|
|
193
|
+
ctx,
|
|
194
|
+
companyRoot,
|
|
195
|
+
shouldSync,
|
|
196
|
+
journalSlug,
|
|
197
|
+
startedAt,
|
|
198
|
+
journal,
|
|
199
|
+
remoteFiles,
|
|
200
|
+
syncMode,
|
|
201
|
+
currentPrefixSet,
|
|
202
|
+
fileTombstones,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
function planPull(run) {
|
|
206
|
+
return computePullPlan(run.remoteFiles, run.journal, run.companyRoot, run.shouldSync, run.options.personalMode === true, run.options.includeLocalCompanies === true, run.options.teamSyncedSlugs ?? null, run.currentPrefixSet, run.fileTombstones);
|
|
207
|
+
}
|
|
208
|
+
function emitPullPlan(emit, plan) {
|
|
222
209
|
emit({
|
|
223
210
|
type: "plan",
|
|
224
211
|
filesToDownload: plan.filesToDownload,
|
|
225
212
|
bytesToDownload: plan.bytesToDownload,
|
|
226
|
-
// sync() is pull-only; push counts are sourced from share()'s plan event.
|
|
227
213
|
filesToUpload: 0,
|
|
228
214
|
bytesToUpload: 0,
|
|
229
215
|
filesToSkip: plan.filesToSkip,
|
|
230
216
|
filesToConflict: plan.filesToConflict,
|
|
231
|
-
// Authoritative FILE_TOMBSTONE suppressions (delete-resync) are the only
|
|
232
|
-
// deletes known at plan time; the journal-vs-LIST tombstones are
|
|
233
|
-
// HEAD-verified later and surfaced via the final filesTombstoned count.
|
|
234
217
|
filesToDelete: plan.filesToTombstoneDelete,
|
|
235
218
|
});
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
// AWS layer never narrows the pull. This client-side shrink is what makes
|
|
251
|
-
// `hq sync mode shared` actually stick across re-syncs for an owner.
|
|
252
|
-
const lastRecord = lastPullRecord(journal, ctx.uid);
|
|
253
|
-
// A missing record, or a v1-migrated record with an empty prefixSet, means
|
|
254
|
-
// "no recorded scope" → treat the last scope as full-bucket `all` (`[""]`),
|
|
255
|
-
// per the PullRecord.prefixSet contract in types.ts.
|
|
219
|
+
}
|
|
220
|
+
function createPullCounters() {
|
|
221
|
+
return {
|
|
222
|
+
filesDownloaded: 0,
|
|
223
|
+
bytesDownloaded: 0,
|
|
224
|
+
filesSkipped: 0,
|
|
225
|
+
conflicts: 0,
|
|
226
|
+
filesTombstoned: 0,
|
|
227
|
+
filesOutOfScope: 0,
|
|
228
|
+
conflictPaths: [],
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
function planScopeShrink(run) {
|
|
232
|
+
const lastRecord = lastPullRecord(run.journal, run.ctx.uid);
|
|
256
233
|
const lastPrefixSet = lastRecord && lastRecord.prefixSet.length > 0
|
|
257
234
|
? lastRecord.prefixSet
|
|
258
235
|
: [""];
|
|
259
236
|
const shrinkPlan = buildScopeShrinkPlan({
|
|
260
|
-
journal,
|
|
261
|
-
hqRoot: companyRoot,
|
|
237
|
+
journal: run.journal,
|
|
238
|
+
hqRoot: run.companyRoot,
|
|
262
239
|
lastPrefixSet,
|
|
263
|
-
currentPrefixSet,
|
|
264
|
-
callerSub,
|
|
265
|
-
// Automatic pull: never auto-prune content the caller authored, and never
|
|
266
|
-
// make a destructive guess about unknown-author (legacy) orphans. The
|
|
267
|
-
// explicit `hq sync narrow` ritual opts out of the unknown-author shield.
|
|
240
|
+
currentPrefixSet: run.currentPrefixSet,
|
|
241
|
+
callerSub: run.options.callerSub,
|
|
268
242
|
protectUnknownAuthors: true,
|
|
269
243
|
});
|
|
270
|
-
|
|
271
|
-
// interactive flag, so it must never throw on a shrink — it self-heals
|
|
272
|
-
// non-destructively (dirty kept on disk + un-tracked, clean quarantined).
|
|
273
|
-
// A foreground `hq sync` ("block", the default) keeps the protective gate
|
|
274
|
-
// but renders FOLLOWABLE advice. `autoRecover` implies force (proceed) and
|
|
275
|
-
// bypasses the bulk-prune cap (quarantine is non-destructive, so a large
|
|
276
|
-
// recovery move is safe). DEV-1768.
|
|
277
|
-
const scopeShrinkPolicy = options.scopeShrinkPolicy ?? "block";
|
|
244
|
+
const scopeShrinkPolicy = run.options.scopeShrinkPolicy ?? "block";
|
|
278
245
|
const autoRecover = scopeShrinkPolicy === "auto-recover";
|
|
279
246
|
const adviceContext = autoRecover ? "runner" : "cli";
|
|
280
|
-
const effectiveForce = options.forceScopeShrink === true || autoRecover;
|
|
247
|
+
const effectiveForce = run.options.forceScopeShrink === true || autoRecover;
|
|
248
|
+
return {
|
|
249
|
+
lastRecord,
|
|
250
|
+
shrinkPlan,
|
|
251
|
+
autoRecover,
|
|
252
|
+
adviceContext,
|
|
253
|
+
effectiveForce,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function executeScopeShrink(run, scopePlan) {
|
|
257
|
+
const { lastRecord, shrinkPlan, adviceContext, effectiveForce } = scopePlan;
|
|
281
258
|
if (shrinkPlan.dirty.length > 0 && !effectiveForce) {
|
|
282
|
-
throw new ScopeShrinkBlockedError(ctx.uid, lastRecord?.syncMode ?? "unknown", syncMode, shrinkPlan.dirty, shrinkPlan.clean, adviceContext);
|
|
259
|
+
throw new ScopeShrinkBlockedError(run.ctx.uid, lastRecord?.syncMode ?? "unknown", run.syncMode, shrinkPlan.dirty, shrinkPlan.clean, adviceContext);
|
|
283
260
|
}
|
|
284
|
-
// Bulk guard: refuse to auto-move more than the safety cap of CLEAN files in
|
|
285
|
-
// a single foreground sync. A deliberate large narrow goes through
|
|
286
|
-
// `hq sync narrow --apply` (its own confirmation); `--force-scope-shrink` (or
|
|
287
|
-
// raising HQ_SYNC_MAX_AUTO_PRUNE) overrides. Cap of 0 = unlimited. Skipped
|
|
288
|
-
// under auto-recover — quarantine is non-destructive so a big recovery is
|
|
289
|
-
// safe, and the runner has no way to act on a thrown cap. The engine moves
|
|
290
|
-
// nothing when it throws here.
|
|
291
261
|
const autoPruneCap = resolveAutoPruneCap();
|
|
292
262
|
if (!effectiveForce &&
|
|
293
263
|
autoPruneCap > 0 &&
|
|
294
264
|
shrinkPlan.clean.length > autoPruneCap) {
|
|
295
|
-
throw new ScopeShrinkLargePruneError(ctx.uid, syncMode, shrinkPlan.clean.length, autoPruneCap, adviceContext);
|
|
265
|
+
throw new ScopeShrinkLargePruneError(run.ctx.uid, run.syncMode, shrinkPlan.clean.length, autoPruneCap, adviceContext);
|
|
296
266
|
}
|
|
297
|
-
|
|
298
|
-
// recoverable), never silently deleted — a background sync purging local
|
|
299
|
-
// files unannounced was DEV-1768 fix #3. The quarantine root lives under the
|
|
300
|
-
// real HQ root's `.hq/` (outside `companyRoot` and never pushed), so moved
|
|
301
|
-
// files don't round-trip back through S3.
|
|
302
|
-
const scopeQuarantineRoot = path.join(hqRoot, ".hq", "scope-quarantine", journalSlug);
|
|
267
|
+
const scopeQuarantineRoot = path.join(run.hqRoot, ".hq", "scope-quarantine", run.journalSlug);
|
|
303
268
|
const shrinkResult = applyScopeShrink({
|
|
304
|
-
journal,
|
|
269
|
+
journal: run.journal,
|
|
305
270
|
plan: shrinkPlan,
|
|
306
|
-
hqRoot: companyRoot,
|
|
271
|
+
hqRoot: run.companyRoot,
|
|
307
272
|
forceScopeShrink: effectiveForce,
|
|
308
273
|
reason: "scope_shrink",
|
|
309
274
|
cleanDisposition: "quarantine",
|
|
310
275
|
quarantineRoot: scopeQuarantineRoot,
|
|
311
276
|
});
|
|
312
|
-
// Surface each affected orphan explicitly (named path) so the prune is never
|
|
313
|
-
// silent. Quarantined clean files render as `deleted: true` (removed from the
|
|
314
|
-
// working tree, recoverable in quarantine); dirty files KEPT on disk render
|
|
315
|
-
// as a non-deletion notice so the operator knows they were un-tracked, not
|
|
316
|
-
// removed. The Rust menubar parser already handles `deleted: true`.
|
|
317
277
|
for (const relPath of shrinkResult.quarantinedPaths) {
|
|
318
|
-
emit({
|
|
278
|
+
run.emit({
|
|
319
279
|
type: "progress",
|
|
320
280
|
path: relPath,
|
|
321
281
|
bytes: 0,
|
|
@@ -324,7 +284,7 @@ async function syncWithOperationLockHeld(options) {
|
|
|
324
284
|
});
|
|
325
285
|
}
|
|
326
286
|
for (const relPath of shrinkResult.removedPaths) {
|
|
327
|
-
emit({
|
|
287
|
+
run.emit({
|
|
328
288
|
type: "progress",
|
|
329
289
|
path: relPath,
|
|
330
290
|
bytes: 0,
|
|
@@ -333,498 +293,314 @@ async function syncWithOperationLockHeld(options) {
|
|
|
333
293
|
});
|
|
334
294
|
}
|
|
335
295
|
for (const relPath of shrinkResult.dirtyKeptPaths) {
|
|
336
|
-
emit({
|
|
296
|
+
run.emit({
|
|
337
297
|
type: "progress",
|
|
338
298
|
path: relPath,
|
|
339
299
|
bytes: 0,
|
|
340
300
|
message: "scope-narrowed: locally-modified file KEPT on disk, un-tracked from sync (outside scope)",
|
|
341
301
|
});
|
|
342
302
|
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
// partition the plan items into "conflict (serial)" and "download
|
|
356
|
-
// (parallel)" buckets and run the serial pass first; the parallel pass
|
|
357
|
-
// only runs if no conflict aborted.
|
|
358
|
-
//
|
|
359
|
-
// Per-file `progress` events fire at the moment each individual download
|
|
360
|
-
// settles (inside the pool wrapper), NOT in plan-walk order. The cross-
|
|
361
|
-
// file interleave is acceptable: the menubar stream parser already
|
|
362
|
-
// handles per-company interleave, and the same shape applies within a
|
|
363
|
-
// single company's pool. Per-file event-count correctness is preserved
|
|
364
|
-
// (one progress per download, one error per failure).
|
|
365
|
-
const TRANSFER_CONCURRENCY = (() => {
|
|
366
|
-
const raw = process.env.HQ_SYNC_TRANSFER_CONCURRENCY;
|
|
367
|
-
if (raw === undefined || raw === "")
|
|
368
|
-
return 16;
|
|
369
|
-
const parsed = Number.parseInt(raw, 10);
|
|
370
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : 16;
|
|
371
|
-
})();
|
|
372
|
-
// First pass: serial walk for non-download outcomes (skips + conflicts).
|
|
373
|
-
// Conflicts may set `aborted = true` and short-circuit the whole pull;
|
|
374
|
-
// we detect that and skip the parallel pass. Download items are
|
|
375
|
-
// collected into `downloadItems[]` for the pool pass below.
|
|
303
|
+
return {
|
|
304
|
+
shrinkPlan,
|
|
305
|
+
shrinkResult,
|
|
306
|
+
scopeOrphansRemoved: shrinkResult.cleanRemoved + shrinkResult.cleanQuarantined,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
async function refreshRunContextIfExpiring(run) {
|
|
310
|
+
if (isExpiringSoon(run.ctx.expiresAt)) {
|
|
311
|
+
run.ctx = await refreshEntityContext(run.companyRef, run.vaultConfig);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
async function executeConflictExecutor(run, plan, scopeRun, counters) {
|
|
376
315
|
const downloadItems = [];
|
|
377
|
-
let aborted = false;
|
|
378
|
-
let abortResult = null;
|
|
379
316
|
for (const item of plan.items) {
|
|
380
|
-
if (aborted)
|
|
381
|
-
break;
|
|
382
317
|
if (item.action === "skip-ignored" ||
|
|
383
318
|
item.action === "skip-personal-mode" ||
|
|
384
319
|
item.action === "skip-unchanged" ||
|
|
385
320
|
item.action === "skip-local-only") {
|
|
386
|
-
filesSkipped++;
|
|
321
|
+
counters.filesSkipped++;
|
|
387
322
|
continue;
|
|
388
323
|
}
|
|
389
324
|
if (item.action === "skip-excluded-policy") {
|
|
390
|
-
// Policy-excluded items count separately from `filesSkipped` so the
|
|
391
|
-
// pull result mirrors the push side's `filesExcludedByPolicy`
|
|
392
|
-
// counter — `filesSkipped` stays a measure of "unchanged on this
|
|
393
|
-
// run", not a catch-all for everything we didn't download.
|
|
394
325
|
continue;
|
|
395
326
|
}
|
|
396
327
|
if (item.action === "skip-out-of-scope") {
|
|
397
|
-
|
|
398
|
-
// axis so `filesSkipped` keeps meaning "unchanged on this run" — these
|
|
399
|
-
// are "deliberately not downloaded because of your sync scope".
|
|
400
|
-
filesOutOfScope++;
|
|
328
|
+
counters.filesOutOfScope++;
|
|
401
329
|
continue;
|
|
402
330
|
}
|
|
403
331
|
if (item.action === "tombstone-delete") {
|
|
404
|
-
|
|
405
|
-
// is present but a tombstone marks the key intentionally deleted and it is
|
|
406
|
-
// not a newer re-create. Delete any local copy and drop the journal entry
|
|
407
|
-
// so it stays gone — the mirror of the journal-vs-LIST tombstone executor
|
|
408
|
-
// below, but WITHOUT the HEAD-verify (the remote object is present by
|
|
409
|
-
// definition; the FILE_TOMBSTONE is the deletion authority). The planner
|
|
410
|
-
// already routed any divergent local copy to `conflict`, so a local file
|
|
411
|
-
// reaching here matches the deleted baseline and is safe to remove.
|
|
412
|
-
const tombstoneKey = item.remoteFile.key;
|
|
413
|
-
// Same Windows-backslash landmine guard as the journal-tombstone executor:
|
|
414
|
-
// a malformed key must never reach fs.unlinkSync (path.join collapses the
|
|
415
|
-
// backslashes onto a REAL POSIX file). Traversal keys are likewise
|
|
416
|
-
// refused before any local filesystem or journal mutation.
|
|
417
|
-
const tombstonePath = resolveContainedVaultPath(companyRoot, tombstoneKey);
|
|
418
|
-
if (tombstonePath === null)
|
|
419
|
-
continue;
|
|
420
|
-
try {
|
|
421
|
-
const lstat = fs.lstatSync(tombstonePath);
|
|
422
|
-
if (tombstoneTargetDiverged(journal, tombstoneKey, tombstonePath, lstat)) {
|
|
423
|
-
continue;
|
|
424
|
-
}
|
|
425
|
-
if (lstat.isSymbolicLink() || lstat.isFile()) {
|
|
426
|
-
fs.unlinkSync(tombstonePath);
|
|
427
|
-
}
|
|
428
|
-
// A directory at the key: don't recursively rm-rf the operator's dir;
|
|
429
|
-
// just drop the journal entry (safe-by-default, same as the other path).
|
|
430
|
-
}
|
|
431
|
-
catch (err) {
|
|
432
|
-
const code = err && typeof err === "object" && "code" in err
|
|
433
|
-
? err.code
|
|
434
|
-
: undefined;
|
|
435
|
-
// ENOENT → local already absent (the common case: a fresh machine that
|
|
436
|
-
// never held the file, or a prior pull already removed it) → drop the
|
|
437
|
-
// journal entry and converge. Other errors (EACCES/EPERM/…) leave the
|
|
438
|
-
// file in place; surface and KEEP the journal entry so the next sync
|
|
439
|
-
// retries rather than forgetting the delete.
|
|
440
|
-
if (code !== "ENOENT") {
|
|
441
|
-
emit({
|
|
442
|
-
type: "error",
|
|
443
|
-
path: tombstoneKey,
|
|
444
|
-
message: `tombstone-suppress unlink failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
445
|
-
});
|
|
446
|
-
continue;
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
removeEntry(journal, tombstoneKey);
|
|
450
|
-
filesTombstoned++;
|
|
451
|
-
emit({ type: "progress", path: tombstoneKey, bytes: 0 });
|
|
332
|
+
executeFileTombstoneDelete(run, item, counters);
|
|
452
333
|
continue;
|
|
453
334
|
}
|
|
454
335
|
if (item.action === "download") {
|
|
455
336
|
downloadItems.push(item);
|
|
456
337
|
continue;
|
|
457
338
|
}
|
|
458
|
-
const
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
if (isExpiringSoon(ctx.expiresAt)) {
|
|
462
|
-
ctx = await refreshEntityContext(companyRef, vaultConfig);
|
|
339
|
+
const abortResult = await executeConflictItem(run, plan, scopeRun, counters, downloadItems, item);
|
|
340
|
+
if (abortResult) {
|
|
341
|
+
return { downloadItems, abortResult };
|
|
463
342
|
}
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
const machineId = readShortMachineId(hqRoot);
|
|
491
|
-
const originalRelative = path.relative(hqRoot, localPath);
|
|
492
|
-
const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
|
|
493
|
-
const conflictAbs = path.join(hqRoot, conflictRelative);
|
|
494
|
-
const conflictKey = toPosixKey(path.relative(companyRoot, conflictAbs));
|
|
495
|
-
if (!isDownloadWritePathStillContained(companyRoot, conflictKey, conflictAbs)) {
|
|
496
|
-
filesSkipped++;
|
|
497
|
-
emit({
|
|
498
|
-
type: "error",
|
|
499
|
-
path: remoteFile.key,
|
|
500
|
-
message: "conflict mirror skipped: local parent escaped the sync root",
|
|
501
|
-
});
|
|
502
|
-
continue;
|
|
503
|
-
}
|
|
504
|
-
let remoteFetched = false;
|
|
505
|
-
let converged = false;
|
|
506
|
-
try {
|
|
507
|
-
const downloaded = await downloadFile(ctx, remoteFile.key, conflictAbs);
|
|
508
|
-
remoteFetched = true;
|
|
509
|
-
// Hash the fetched remote exactly the way the planner hashed local
|
|
510
|
-
// (symlink-aware) so the two hashes are directly comparable. A
|
|
511
|
-
// symlink record round-trips to a symlink on disk; hashing its
|
|
512
|
-
// target string matches `hashSymlinkTarget(localPath)`.
|
|
513
|
-
const remoteHash = fs.lstatSync(conflictAbs).isSymbolicLink()
|
|
514
|
-
? hashSymlinkTarget(fs.readlinkSync(conflictAbs))
|
|
515
|
-
: (downloaded.contentHash ?? hashFile(conflictAbs));
|
|
516
|
-
converged = remoteHash === item.localHash;
|
|
517
|
-
}
|
|
518
|
-
catch (probeErr) {
|
|
519
|
-
// Couldn't fetch or hash the remote — fail safe by falling through to
|
|
520
|
-
// the conventional conflict path (converged stays false). No mirror
|
|
521
|
-
// is on disk in this case.
|
|
522
|
-
emit({
|
|
523
|
-
type: "error",
|
|
524
|
-
path: remoteFile.key,
|
|
525
|
-
message: `conflict convergence probe failed: ${probeErr instanceof Error ? probeErr.message : String(probeErr)}`,
|
|
526
|
-
});
|
|
527
|
-
}
|
|
528
|
-
if (converged) {
|
|
529
|
-
// False positive: remote == local. Drop the byte-identical mirror and
|
|
530
|
-
// re-stamp the baseline (current localHash + current remoteEtag) so
|
|
531
|
-
// the next sync sees "no change on either side". Counts as a skip.
|
|
532
|
-
if (remoteFetched) {
|
|
533
|
-
try {
|
|
534
|
-
fs.rmSync(conflictAbs, { force: true });
|
|
535
|
-
}
|
|
536
|
-
catch {
|
|
537
|
-
/* best-effort cleanup; a stray identical mirror is harmless */
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
updateEntry(journal, remoteFile.key, item.localHash, item.localSize, "down", remoteFile.etag, item.localMtime.getTime());
|
|
541
|
-
emit({ type: "reconciled", path: remoteFile.key, direction: "pull" });
|
|
542
|
-
filesSkipped++;
|
|
543
|
-
continue;
|
|
544
|
-
}
|
|
545
|
-
// ── Genuine divergence ───────────────────────────────────────────
|
|
546
|
-
conflicts++;
|
|
547
|
-
conflictPaths.push(remoteFile.key);
|
|
548
|
-
const resolution = await resolveConflict({
|
|
549
|
-
path: remoteFile.key,
|
|
550
|
-
localHash: item.localHash,
|
|
551
|
-
remoteModified: remoteFile.lastModified,
|
|
552
|
-
// Use the lstat-mtime captured by the planner — statSync
|
|
553
|
-
// here would follow a dangling symlink and throw ENOENT,
|
|
554
|
-
// aborting the pull before resolveConflict could prompt.
|
|
555
|
-
localModified: item.localMtime,
|
|
556
|
-
direction: "pull",
|
|
557
|
-
}, onConflict);
|
|
558
|
-
emit({
|
|
559
|
-
type: "conflict",
|
|
560
|
-
path: remoteFile.key,
|
|
561
|
-
direction: "pull",
|
|
562
|
-
resolution,
|
|
563
|
-
});
|
|
564
|
-
// The remote bytes were already fetched to `conflictAbs` by the
|
|
565
|
-
// convergence probe. For "keep"/"skip" they become the
|
|
566
|
-
// `<original>.conflict-<ts>-<machine>.<ext>` inspection mirror — just
|
|
567
|
-
// index it (no second download). For "abort" (user gave up) and
|
|
568
|
-
// "overwrite" (cloud bytes are about to replace local) the mirror is
|
|
569
|
-
// redundant, so discard it. Best-effort: failure here only emits an
|
|
570
|
-
// error, doesn't break the sync.
|
|
571
|
-
if (resolution !== "abort" && resolution !== "overwrite") {
|
|
572
|
-
if (remoteFetched) {
|
|
573
|
-
try {
|
|
574
|
-
appendConflictEntry(hqRoot, {
|
|
575
|
-
id: buildConflictId(originalRelative, detectedAt),
|
|
576
|
-
originalPath: originalRelative,
|
|
577
|
-
conflictPath: conflictRelative,
|
|
578
|
-
detectedAt,
|
|
579
|
-
side: "pull",
|
|
580
|
-
machineId,
|
|
581
|
-
localHash: item.localHash,
|
|
582
|
-
remoteHash: remoteFile.etag ? normalizeEtag(remoteFile.etag) : "",
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
catch (mirrorErr) {
|
|
586
|
-
emit({
|
|
587
|
-
type: "error",
|
|
588
|
-
path: remoteFile.key,
|
|
589
|
-
message: `conflict mirror index write failed: ${mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)}`,
|
|
590
|
-
});
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
// If the probe download failed (!remoteFetched) there is no mirror on
|
|
594
|
-
// disk; the probe already emitted the error. The conflict is still
|
|
595
|
-
// surfaced and journal-stamped below so it doesn't re-fire silently.
|
|
596
|
-
}
|
|
597
|
-
else if (remoteFetched) {
|
|
598
|
-
try {
|
|
599
|
-
fs.rmSync(conflictAbs, { force: true });
|
|
600
|
-
}
|
|
601
|
-
catch {
|
|
602
|
-
/* best-effort; a leftover mirror is cosmetic, not corrupting */
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
if (resolution === "abort") {
|
|
606
|
-
emit({ type: "new-files", files: [] });
|
|
607
|
-
writeJournal(journalSlug, journal);
|
|
608
|
-
aborted = true;
|
|
609
|
-
abortResult = {
|
|
610
|
-
filesDownloaded,
|
|
611
|
-
bytesDownloaded,
|
|
612
|
-
filesSkipped,
|
|
613
|
-
conflicts,
|
|
614
|
-
conflictPaths,
|
|
615
|
-
aborted: true,
|
|
616
|
-
newFiles: plan.newFiles,
|
|
617
|
-
newFilesCount: plan.newFilesCount,
|
|
618
|
-
filesExcludedByPolicy: plan.filesExcludedByPolicy,
|
|
619
|
-
// Abort short-circuits before the tombstone loop runs; report
|
|
620
|
-
// 0 so the field shape stays stable for consumers that
|
|
621
|
-
// destructure it.
|
|
622
|
-
filesTombstoned: 0,
|
|
623
|
-
// Scope-shrink ran before execution, so its counts are real even on
|
|
624
|
-
// a conflict abort. `filesOutOfScope` reflects how far the serial
|
|
625
|
-
// pass got before the abort; that's acceptable for an abort result.
|
|
626
|
-
filesOutOfScope,
|
|
627
|
-
scopeOrphansRemoved,
|
|
628
|
-
scopeOrphansBlocked: shrinkResult.dirtyTombstoned,
|
|
629
|
-
};
|
|
630
|
-
break;
|
|
631
|
-
}
|
|
632
|
-
if (resolution === "keep" || resolution === "skip") {
|
|
633
|
-
filesSkipped++;
|
|
634
|
-
// Stamp the journal with the new baseline so the same conflict
|
|
635
|
-
// doesn't re-fire on every subsequent sync. After "keep", local
|
|
636
|
-
// wins — the user has accepted that the cloud version we just
|
|
637
|
-
// mirrored is what cloud is at this etag, and they don't want
|
|
638
|
-
// it. Recording (current localHash + current remoteEtag) tells
|
|
639
|
-
// the next sync "no change on either side" until something new
|
|
640
|
-
// diverges. Without this, both `localChanged` and `remoteChanged`
|
|
641
|
-
// stay true forever and the conflict is sticky.
|
|
642
|
-
// Stamp from planner-captured size (symlink-aware), NOT
|
|
643
|
-
// statSync — which would follow a dangling symlink and
|
|
644
|
-
// throw ENOENT, get swallowed, and leave the journal
|
|
645
|
-
// stale so this conflict would re-fire on every sync
|
|
646
|
-
// forever. localSize is sourced from the same lstat that
|
|
647
|
-
// computed localMtime + localHash above.
|
|
648
|
-
updateEntry(journal, remoteFile.key, item.localHash, item.localSize, "down", remoteFile.etag, item.localMtime.getTime());
|
|
649
|
-
continue;
|
|
650
|
-
}
|
|
651
|
-
// "overwrite" falls through to download — re-route through the pool
|
|
652
|
-
// so it benefits from parallelism too. Synthesize a download item
|
|
653
|
-
// pointing at the same remoteFile/localPath; isNew=false because
|
|
654
|
-
// there was a conflict-eligible local file present.
|
|
655
|
-
downloadItems.push({
|
|
656
|
-
action: "download",
|
|
657
|
-
remoteFile,
|
|
658
|
-
localPath,
|
|
659
|
-
isNew: false,
|
|
343
|
+
}
|
|
344
|
+
return { downloadItems, abortResult: null };
|
|
345
|
+
}
|
|
346
|
+
function executeFileTombstoneDelete(run, item, counters) {
|
|
347
|
+
const tombstoneKey = item.remoteFile.key;
|
|
348
|
+
const tombstonePath = resolveContainedVaultPath(run.companyRoot, tombstoneKey);
|
|
349
|
+
if (tombstonePath === null)
|
|
350
|
+
return;
|
|
351
|
+
try {
|
|
352
|
+
const lstat = fs.lstatSync(tombstonePath);
|
|
353
|
+
if (tombstoneTargetDiverged(run.journal, tombstoneKey, tombstonePath, lstat)) {
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (lstat.isSymbolicLink() || lstat.isFile()) {
|
|
357
|
+
fs.unlinkSync(tombstonePath);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
const code = err && typeof err === "object" && "code" in err
|
|
362
|
+
? err.code
|
|
363
|
+
: undefined;
|
|
364
|
+
if (code !== "ENOENT") {
|
|
365
|
+
run.emit({
|
|
366
|
+
type: "error",
|
|
367
|
+
path: tombstoneKey,
|
|
368
|
+
message: `tombstone-suppress unlink failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
660
369
|
});
|
|
661
|
-
|
|
370
|
+
return;
|
|
662
371
|
}
|
|
663
372
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
373
|
+
removeEntry(run.journal, tombstoneKey);
|
|
374
|
+
counters.filesTombstoned++;
|
|
375
|
+
run.emit({ type: "progress", path: tombstoneKey, bytes: 0 });
|
|
376
|
+
}
|
|
377
|
+
async function executeConflictItem(run, plan, scopeRun, counters, downloadItems, item) {
|
|
378
|
+
const { remoteFile, localPath } = item;
|
|
379
|
+
await refreshRunContextIfExpiring(run);
|
|
380
|
+
const detectedAt = new Date().toISOString();
|
|
381
|
+
const machineId = readShortMachineId(run.hqRoot);
|
|
382
|
+
const originalRelative = path.relative(run.hqRoot, localPath);
|
|
383
|
+
const conflictRelative = buildConflictPath(originalRelative, detectedAt, machineId);
|
|
384
|
+
const conflictAbs = path.join(run.hqRoot, conflictRelative);
|
|
385
|
+
const conflictKey = toPosixKey(path.relative(run.companyRoot, conflictAbs));
|
|
386
|
+
if (!isDownloadWritePathStillContained(run.companyRoot, conflictKey, conflictAbs)) {
|
|
387
|
+
counters.filesSkipped++;
|
|
388
|
+
run.emit({
|
|
389
|
+
type: "error",
|
|
390
|
+
path: remoteFile.key,
|
|
391
|
+
message: "conflict mirror skipped: local parent escaped the sync root",
|
|
392
|
+
});
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
let remoteFetched = false;
|
|
396
|
+
let converged = false;
|
|
397
|
+
try {
|
|
398
|
+
const downloaded = await downloadFile(run.ctx, remoteFile.key, conflictAbs);
|
|
399
|
+
remoteFetched = true;
|
|
400
|
+
const remoteHash = fs.lstatSync(conflictAbs).isSymbolicLink()
|
|
401
|
+
? hashSymlinkTarget(fs.readlinkSync(conflictAbs))
|
|
402
|
+
: (downloaded.contentHash ?? hashFile(conflictAbs));
|
|
403
|
+
converged = remoteHash === item.localHash;
|
|
404
|
+
}
|
|
405
|
+
catch (probeErr) {
|
|
406
|
+
run.emit({
|
|
407
|
+
type: "error",
|
|
408
|
+
path: remoteFile.key,
|
|
409
|
+
message: `conflict convergence probe failed: ${probeErr instanceof Error ? probeErr.message : String(probeErr)}`,
|
|
410
|
+
});
|
|
670
411
|
}
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
// (inside the wrapper), so cross-file interleave is expected and the
|
|
676
|
-
// menubar's stream parser already handles it.
|
|
677
|
-
if (downloadItems.length > 0) {
|
|
678
|
-
// Batch pre-mint GET URLs for every download in one shot (chunked server-
|
|
679
|
-
// side) so the pool below — and the new-files HEAD enrichment that follows,
|
|
680
|
-
// which re-reads the same keys — reuse them instead of presigning per file.
|
|
681
|
-
// On a large initial pull this is the difference between ~ceil(N/100)
|
|
682
|
-
// presign calls and N (which would 429 past the 100-req/hr limit). No-op
|
|
683
|
-
// on the S3 SDK transport; best-effort (failure falls back to per-file).
|
|
684
|
-
await primeObjectTransport(ctx, "get", downloadItems.map((d) => d.remoteFile.key));
|
|
685
|
-
const queue = [...downloadItems];
|
|
686
|
-
const inFlight = new Set();
|
|
687
|
-
const downloadOne = async (downloadItem) => {
|
|
688
|
-
const { remoteFile, localPath } = downloadItem;
|
|
689
|
-
// Auto-refresh context if credentials expiring. Each task checks
|
|
690
|
-
// independently — refresh is idempotent on the same context object.
|
|
691
|
-
if (isExpiringSoon(ctx.expiresAt)) {
|
|
692
|
-
ctx = await refreshEntityContext(companyRef, vaultConfig);
|
|
412
|
+
if (converged) {
|
|
413
|
+
if (remoteFetched) {
|
|
414
|
+
try {
|
|
415
|
+
fs.rmSync(conflictAbs, { force: true });
|
|
693
416
|
}
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
emit({
|
|
697
|
-
type: "error",
|
|
698
|
-
path: remoteFile.key,
|
|
699
|
-
message: "download skipped: local parent escaped the sync root",
|
|
700
|
-
});
|
|
701
|
-
return;
|
|
417
|
+
catch {
|
|
418
|
+
/* best-effort cleanup; a stray identical mirror is harmless */
|
|
702
419
|
}
|
|
420
|
+
}
|
|
421
|
+
updateEntry(run.journal, remoteFile.key, item.localHash, item.localSize, "down", remoteFile.etag, item.localMtime.getTime());
|
|
422
|
+
run.emit({ type: "reconciled", path: remoteFile.key, direction: "pull" });
|
|
423
|
+
counters.filesSkipped++;
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
counters.conflicts++;
|
|
427
|
+
counters.conflictPaths.push(remoteFile.key);
|
|
428
|
+
const resolution = await resolveConflict({
|
|
429
|
+
path: remoteFile.key,
|
|
430
|
+
localHash: item.localHash,
|
|
431
|
+
remoteModified: remoteFile.lastModified,
|
|
432
|
+
localModified: item.localMtime,
|
|
433
|
+
direction: "pull",
|
|
434
|
+
}, run.options.onConflict);
|
|
435
|
+
run.emit({
|
|
436
|
+
type: "conflict",
|
|
437
|
+
path: remoteFile.key,
|
|
438
|
+
direction: "pull",
|
|
439
|
+
resolution,
|
|
440
|
+
});
|
|
441
|
+
if (resolution !== "abort" && resolution !== "overwrite") {
|
|
442
|
+
if (remoteFetched) {
|
|
703
443
|
try {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
// size = 0
|
|
714
|
-
// Without this check, hashFile would follow the link and stamp the
|
|
715
|
-
// target file's contents — a value the next push would never
|
|
716
|
-
// produce — which makes skipUnchanged perpetually re-upload every
|
|
717
|
-
// symlink, defeating the point of the gate.
|
|
718
|
-
const localLstat = fs.lstatSync(localPath);
|
|
719
|
-
const isLocalSymlink = localLstat.isSymbolicLink();
|
|
720
|
-
const hash = isLocalSymlink
|
|
721
|
-
? hashSymlinkTarget(fs.readlinkSync(localPath))
|
|
722
|
-
: (contentHash ?? hashFile(localPath));
|
|
723
|
-
const size = isLocalSymlink ? 0 : (contentSize ?? fs.statSync(localPath).size);
|
|
724
|
-
// Capture the listing's ETag so subsequent syncs can detect remote
|
|
725
|
-
// drift independently of mtime drift. Stamp mtimeMs from localLstat
|
|
726
|
-
// (5.36.0) so the next push planner's lstat fast-path can skip the
|
|
727
|
-
// SHA256 for this file without reading its bytes.
|
|
728
|
-
//
|
|
729
|
-
// 5.37.0 ordering invariant: downloadFile applies hq-mtime via
|
|
730
|
-
// utimesSync AFTER its byte write but BEFORE returning, and this
|
|
731
|
-
// lstat runs AFTER downloadFile resolves — so localLstat.mtimeMs
|
|
732
|
-
// already reflects the source-stamped mtime, not the wall-clock
|
|
733
|
-
// write-time. The journal therefore matches what the next push's
|
|
734
|
-
// lstat fast-path will see, and the file is correctly skipped on
|
|
735
|
-
// re-sync instead of being hashed every tick. Do not move this
|
|
736
|
-
// lstat earlier; do not stamp the journal from any pre-download
|
|
737
|
-
// mtime.
|
|
738
|
-
updateEntry(journal, remoteFile.key, hash, size, "down", remoteFile.etag, localLstat.mtimeMs, createdBySub);
|
|
739
|
-
// Attach message from the prior journal entry if present (set by a
|
|
740
|
-
// previous `share` operation that included a --message).
|
|
741
|
-
const priorEntry = getEntry(journal, remoteFile.key);
|
|
742
|
-
const remoteJournalMessage = priorEntry?.message;
|
|
743
|
-
emit({
|
|
744
|
-
type: "progress",
|
|
745
|
-
path: remoteFile.key,
|
|
746
|
-
bytes: size,
|
|
747
|
-
...(remoteJournalMessage ? { message: remoteJournalMessage } : {}),
|
|
748
|
-
...(author ? { author } : {}),
|
|
444
|
+
appendConflictEntry(run.hqRoot, {
|
|
445
|
+
id: buildConflictId(originalRelative, detectedAt),
|
|
446
|
+
originalPath: originalRelative,
|
|
447
|
+
conflictPath: conflictRelative,
|
|
448
|
+
detectedAt,
|
|
449
|
+
side: "pull",
|
|
450
|
+
machineId,
|
|
451
|
+
localHash: item.localHash,
|
|
452
|
+
remoteHash: remoteFile.etag ? normalizeEtag(remoteFile.etag) : "",
|
|
749
453
|
});
|
|
750
|
-
filesDownloaded++;
|
|
751
|
-
bytesDownloaded += size;
|
|
752
454
|
}
|
|
753
|
-
catch (
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
}
|
|
759
|
-
else {
|
|
760
|
-
emit({
|
|
761
|
-
type: "error",
|
|
762
|
-
path: remoteFile.key,
|
|
763
|
-
message: err instanceof Error ? err.message : String(err),
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
};
|
|
768
|
-
// Codex P1 (5.36.x): worker promises wrapped in .catch so an
|
|
769
|
-
// unhandled rejection inside downloadOne (e.g. refreshEntityContext
|
|
770
|
-
// before the per-item try/catch, or lstatSync after the download
|
|
771
|
-
// succeeded but before journal stamping) cannot escape
|
|
772
|
-
// `Promise.race(inFlight)` and unwind the drain mid-flight. Without
|
|
773
|
-
// this wrap, sibling downloads kept running after share()/sync()
|
|
774
|
-
// had already failed, their files materialized on disk without
|
|
775
|
-
// matching journal entries, and the next sync re-downloaded
|
|
776
|
-
// everything. Errors are collected and surfaced after the pool
|
|
777
|
-
// fully drains — see workerErrors throw below.
|
|
778
|
-
const workerErrors = [];
|
|
779
|
-
while (queue.length > 0 || inFlight.size > 0) {
|
|
780
|
-
while (inFlight.size < TRANSFER_CONCURRENCY && queue.length > 0) {
|
|
781
|
-
const downloadItem = queue.shift();
|
|
782
|
-
const p = downloadOne(downloadItem)
|
|
783
|
-
.catch((err) => {
|
|
784
|
-
workerErrors.push(err instanceof Error ? err : new Error(String(err)));
|
|
785
|
-
})
|
|
786
|
-
.finally(() => {
|
|
787
|
-
inFlight.delete(p);
|
|
455
|
+
catch (mirrorErr) {
|
|
456
|
+
run.emit({
|
|
457
|
+
type: "error",
|
|
458
|
+
path: remoteFile.key,
|
|
459
|
+
message: `conflict mirror index write failed: ${mirrorErr instanceof Error ? mirrorErr.message : String(mirrorErr)}`,
|
|
788
460
|
});
|
|
789
|
-
inFlight.add(p);
|
|
790
|
-
}
|
|
791
|
-
if (inFlight.size > 0) {
|
|
792
|
-
// Wait for at least one in-flight task to settle before topping up
|
|
793
|
-
// the pool. allSettled-style semantics via Promise.race — the
|
|
794
|
-
// .catch wrap above guarantees no worker promise can reject.
|
|
795
|
-
await Promise.race(Array.from(inFlight));
|
|
796
461
|
}
|
|
797
462
|
}
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
463
|
+
}
|
|
464
|
+
else if (remoteFetched) {
|
|
465
|
+
try {
|
|
466
|
+
fs.rmSync(conflictAbs, { force: true });
|
|
467
|
+
}
|
|
468
|
+
catch {
|
|
469
|
+
/* best-effort; a leftover mirror is cosmetic, not corrupting */
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (resolution === "abort") {
|
|
473
|
+
run.emit({ type: "new-files", files: [] });
|
|
474
|
+
writeJournal(run.journalSlug, run.journal);
|
|
475
|
+
return {
|
|
476
|
+
filesDownloaded: counters.filesDownloaded,
|
|
477
|
+
bytesDownloaded: counters.bytesDownloaded,
|
|
478
|
+
filesSkipped: counters.filesSkipped,
|
|
479
|
+
conflicts: counters.conflicts,
|
|
480
|
+
conflictPaths: counters.conflictPaths,
|
|
481
|
+
aborted: true,
|
|
482
|
+
newFiles: plan.newFiles,
|
|
483
|
+
newFilesCount: plan.newFilesCount,
|
|
484
|
+
filesExcludedByPolicy: plan.filesExcludedByPolicy,
|
|
485
|
+
filesTombstoned: 0,
|
|
486
|
+
filesOutOfScope: counters.filesOutOfScope,
|
|
487
|
+
scopeOrphansRemoved: scopeRun.scopeOrphansRemoved,
|
|
488
|
+
scopeOrphansBlocked: scopeRun.shrinkResult.dirtyTombstoned,
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
if (resolution === "keep" || resolution === "skip") {
|
|
492
|
+
counters.filesSkipped++;
|
|
493
|
+
updateEntry(run.journal, remoteFile.key, item.localHash, item.localSize, "down", remoteFile.etag, item.localMtime.getTime());
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
downloadItems.push({
|
|
497
|
+
action: "download",
|
|
498
|
+
remoteFile,
|
|
499
|
+
localPath,
|
|
500
|
+
isNew: false,
|
|
501
|
+
});
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
async function executeDownloadExecutor(run, downloadItems, transferConcurrency, counters) {
|
|
505
|
+
if (downloadItems.length === 0)
|
|
506
|
+
return;
|
|
507
|
+
await primeObjectTransport(run.ctx, "get", downloadItems.map((d) => d.remoteFile.key));
|
|
508
|
+
const queue = [...downloadItems];
|
|
509
|
+
const inFlight = new Set();
|
|
510
|
+
const workerErrors = [];
|
|
511
|
+
while (queue.length > 0 || inFlight.size > 0) {
|
|
512
|
+
while (inFlight.size < transferConcurrency && queue.length > 0) {
|
|
513
|
+
const downloadItem = queue.shift();
|
|
514
|
+
const p = downloadOne(run, downloadItem, counters)
|
|
515
|
+
.catch((err) => {
|
|
516
|
+
workerErrors.push(err instanceof Error ? err : new Error(String(err)));
|
|
517
|
+
})
|
|
518
|
+
.finally(() => {
|
|
519
|
+
inFlight.delete(p);
|
|
520
|
+
});
|
|
521
|
+
inFlight.add(p);
|
|
522
|
+
}
|
|
523
|
+
if (inFlight.size > 0) {
|
|
524
|
+
await Promise.race(Array.from(inFlight));
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (workerErrors.length > 0) {
|
|
528
|
+
writeJournal(run.journalSlug, run.journal);
|
|
529
|
+
const first = workerErrors[0];
|
|
530
|
+
if (workerErrors.length > 1) {
|
|
531
|
+
first.message = `${first.message} (and ${workerErrors.length - 1} more download-worker errors)`;
|
|
532
|
+
}
|
|
533
|
+
throw first;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
async function downloadOne(run, downloadItem, counters) {
|
|
537
|
+
const { remoteFile, localPath } = downloadItem;
|
|
538
|
+
await refreshRunContextIfExpiring(run);
|
|
539
|
+
if (!isDownloadWritePathStillContained(run.companyRoot, remoteFile.key, localPath)) {
|
|
540
|
+
counters.filesSkipped++;
|
|
541
|
+
run.emit({
|
|
542
|
+
type: "error",
|
|
543
|
+
path: remoteFile.key,
|
|
544
|
+
message: "download skipped: local parent escaped the sync root",
|
|
545
|
+
});
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
try {
|
|
549
|
+
const { metadata, contentHash, contentSize } = await downloadFile(run.ctx, remoteFile.key, localPath);
|
|
550
|
+
const author = metadata?.["created-by"] ?? null;
|
|
551
|
+
const createdBySub = metadata?.["created-by-sub"];
|
|
552
|
+
const localLstat = fs.lstatSync(localPath);
|
|
553
|
+
const isLocalSymlink = localLstat.isSymbolicLink();
|
|
554
|
+
const hash = isLocalSymlink
|
|
555
|
+
? hashSymlinkTarget(fs.readlinkSync(localPath))
|
|
556
|
+
: (contentHash ?? hashFile(localPath));
|
|
557
|
+
const size = isLocalSymlink ? 0 : (contentSize ?? fs.statSync(localPath).size);
|
|
558
|
+
updateEntry(run.journal, remoteFile.key, hash, size, "down", remoteFile.etag, localLstat.mtimeMs, createdBySub);
|
|
559
|
+
const priorEntry = getEntry(run.journal, remoteFile.key);
|
|
560
|
+
const remoteJournalMessage = priorEntry?.message;
|
|
561
|
+
run.emit({
|
|
562
|
+
type: "progress",
|
|
563
|
+
path: remoteFile.key,
|
|
564
|
+
bytes: size,
|
|
565
|
+
...(remoteJournalMessage ? { message: remoteJournalMessage } : {}),
|
|
566
|
+
...(author ? { author } : {}),
|
|
567
|
+
});
|
|
568
|
+
counters.filesDownloaded++;
|
|
569
|
+
counters.bytesDownloaded += size;
|
|
570
|
+
}
|
|
571
|
+
catch (err) {
|
|
572
|
+
if (isAccessDenied(err)) {
|
|
573
|
+
counters.filesSkipped++;
|
|
574
|
+
}
|
|
575
|
+
else {
|
|
576
|
+
run.emit({
|
|
577
|
+
type: "error",
|
|
578
|
+
path: remoteFile.key,
|
|
579
|
+
message: err instanceof Error ? err.message : String(err),
|
|
580
|
+
});
|
|
808
581
|
}
|
|
809
582
|
}
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
// calls are best-effort and capped at 5 concurrent to avoid hammering S3.
|
|
583
|
+
}
|
|
584
|
+
async function emitAndReportNewFiles(run, plan) {
|
|
813
585
|
const enrichedNewFiles = [];
|
|
586
|
+
// Batch-mint the GET presigns once (chunked, breaker-aware) so the per-file
|
|
587
|
+
// created-by HEADs below reuse the cache instead of each minting its own
|
|
588
|
+
// presign. Without this, a big catch-up pull (hundreds of new files) bursts
|
|
589
|
+
// the presign endpoint, trips the circuit breaker, and every enrichment HEAD
|
|
590
|
+
// then fails. Mirrors the tombstone HEAD-verify pre-prime.
|
|
591
|
+
await primeObjectTransport(run.ctx, "get", plan.newFiles.map((nf) => nf.path));
|
|
814
592
|
const HEAD_CONCURRENCY = 5;
|
|
815
593
|
for (let i = 0; i < plan.newFiles.length; i += HEAD_CONCURRENCY) {
|
|
816
594
|
const batch = plan.newFiles.slice(i, i + HEAD_CONCURRENCY);
|
|
817
595
|
const results = await Promise.all(batch.map(async (nf) => {
|
|
818
596
|
let addedBy = null;
|
|
819
597
|
try {
|
|
820
|
-
const head = await headRemoteFile(ctx, nf.path);
|
|
598
|
+
const head = await headRemoteFile(run.ctx, nf.path);
|
|
821
599
|
if (head?.metadata?.["created-by"]) {
|
|
822
600
|
addedBy = head.metadata["created-by"];
|
|
823
601
|
}
|
|
824
602
|
}
|
|
825
603
|
catch (headErr) {
|
|
826
|
-
// Best-effort: log to console (Sentry captures via global handler)
|
|
827
|
-
// and fall through with addedBy = null.
|
|
828
604
|
try {
|
|
829
605
|
console.error(`[hq-sync] HeadObject failed for ${nf.path}: ${headErr instanceof Error ? headErr.message : String(headErr)}`);
|
|
830
606
|
}
|
|
@@ -836,75 +612,49 @@ async function syncWithOperationLockHeld(options) {
|
|
|
836
612
|
}));
|
|
837
613
|
enrichedNewFiles.push(...results);
|
|
838
614
|
}
|
|
839
|
-
emit({ type: "new-files", files: enrichedNewFiles });
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
// - HEAD throws AccessDenied → can't tell → defensive skip; journal
|
|
858
|
-
// stays so next sync (with broader scope) can re-evaluate.
|
|
859
|
-
// - HEAD throws transient → defensive skip + emit error.
|
|
860
|
-
// Bounded concurrency mirrors the new-files attribution pass above.
|
|
861
|
-
if (plan.tombstones.length > 0) {
|
|
862
|
-
// Pre-mint GET URLs for the tombstone HEAD-verify probes below (headRemote
|
|
863
|
-
// File presigns a GET), so a large delete set doesn't add N presign calls.
|
|
864
|
-
await primeObjectTransport(ctx, "get", plan.tombstones);
|
|
865
|
-
const HEAD_VERIFY_CONCURRENCY = 5;
|
|
866
|
-
const verified = [];
|
|
867
|
-
for (let i = 0; i < plan.tombstones.length; i += HEAD_VERIFY_CONCURRENCY) {
|
|
868
|
-
const batch = plan.tombstones.slice(i, i + HEAD_VERIFY_CONCURRENCY);
|
|
869
|
-
const results = await Promise.all(batch.map(async (key) => {
|
|
870
|
-
try {
|
|
871
|
-
const head = await headRemoteFile(ctx, key);
|
|
872
|
-
return head === null ? key : null;
|
|
873
|
-
}
|
|
874
|
-
catch (err) {
|
|
875
|
-
if (isAccessDenied(err))
|
|
876
|
-
return null;
|
|
877
|
-
emit({
|
|
878
|
-
type: "error",
|
|
879
|
-
path: key,
|
|
880
|
-
message: `tombstone HEAD verify failed (deferring): ${err instanceof Error ? err.message : String(err)}`,
|
|
881
|
-
});
|
|
615
|
+
run.emit({ type: "new-files", files: enrichedNewFiles });
|
|
616
|
+
await reportNewFilesToNotify(run.vaultConfig, run.ctx.uid, run.ctx.slug, enrichedNewFiles);
|
|
617
|
+
}
|
|
618
|
+
async function verifyPlannedJournalTombstones(run, plan) {
|
|
619
|
+
if (plan.tombstones.length === 0)
|
|
620
|
+
return;
|
|
621
|
+
await primeObjectTransport(run.ctx, "get", plan.tombstones);
|
|
622
|
+
const HEAD_VERIFY_CONCURRENCY = 5;
|
|
623
|
+
const verified = [];
|
|
624
|
+
for (let i = 0; i < plan.tombstones.length; i += HEAD_VERIFY_CONCURRENCY) {
|
|
625
|
+
const batch = plan.tombstones.slice(i, i + HEAD_VERIFY_CONCURRENCY);
|
|
626
|
+
const results = await Promise.all(batch.map(async (key) => {
|
|
627
|
+
try {
|
|
628
|
+
const head = await headRemoteFile(run.ctx, key);
|
|
629
|
+
return head === null ? key : null;
|
|
630
|
+
}
|
|
631
|
+
catch (err) {
|
|
632
|
+
if (isAccessDenied(err))
|
|
882
633
|
return null;
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
634
|
+
run.emit({
|
|
635
|
+
type: "error",
|
|
636
|
+
path: key,
|
|
637
|
+
message: `tombstone HEAD verify failed (deferring): ${err instanceof Error ? err.message : String(err)}`,
|
|
638
|
+
});
|
|
639
|
+
return null;
|
|
888
640
|
}
|
|
641
|
+
}));
|
|
642
|
+
for (const k of results) {
|
|
643
|
+
if (k !== null)
|
|
644
|
+
verified.push(k);
|
|
889
645
|
}
|
|
890
|
-
plan.tombstones = verified;
|
|
891
646
|
}
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
// remnant) and drop the journal entry so the next sync's planner stays
|
|
896
|
-
// converged. Failures are reported but non-fatal — the entry stays in
|
|
897
|
-
// the journal and the next run retries.
|
|
647
|
+
plan.tombstones = verified;
|
|
648
|
+
}
|
|
649
|
+
function executeJournalTombstoneDeletes(run, plan, counters) {
|
|
898
650
|
for (const key of plan.tombstones) {
|
|
899
|
-
|
|
900
|
-
// fs.unlinkSync or journal mutation for a path outside the sync root.
|
|
901
|
-
const localPath = resolveContainedVaultPath(companyRoot, key);
|
|
651
|
+
const localPath = resolveContainedVaultPath(run.companyRoot, key);
|
|
902
652
|
if (localPath === null)
|
|
903
653
|
continue;
|
|
904
654
|
let removedSomething = false;
|
|
905
655
|
try {
|
|
906
656
|
const lstat = fs.lstatSync(localPath);
|
|
907
|
-
if (tombstoneTargetDiverged(journal, key, localPath, lstat)) {
|
|
657
|
+
if (tombstoneTargetDiverged(run.journal, key, localPath, lstat)) {
|
|
908
658
|
continue;
|
|
909
659
|
}
|
|
910
660
|
if (lstat.isSymbolicLink() || lstat.isFile()) {
|
|
@@ -912,130 +662,74 @@ async function syncWithOperationLockHeld(options) {
|
|
|
912
662
|
removedSomething = true;
|
|
913
663
|
}
|
|
914
664
|
else if (lstat.isDirectory()) {
|
|
915
|
-
// A dir at a key
|
|
916
|
-
// state. Don't recursively rm-rf the operator's dir; just drop
|
|
917
|
-
// the journal entry so we converge with reality.
|
|
665
|
+
// A dir at a key is converged by dropping only the journal entry.
|
|
918
666
|
}
|
|
919
667
|
}
|
|
920
668
|
catch (err) {
|
|
921
669
|
const code = err && typeof err === "object" && "code" in err
|
|
922
670
|
? err.code
|
|
923
671
|
: undefined;
|
|
924
|
-
// ENOENT → local already gone; safe to drop the journal entry.
|
|
925
|
-
// Other errors (EACCES/EPERM/EBUSY/etc.) leave the local file in
|
|
926
|
-
// place — if we dropped the journal entry anyway, the pull side
|
|
927
|
-
// would forget the peer's delete and a later push could re-upload
|
|
928
|
-
// the still-present local file, silently undoing the peer's delete.
|
|
929
|
-
// Surface the error and KEEP the journal entry so the next sync
|
|
930
|
-
// retries the unlink after the operator fixes the permission.
|
|
931
672
|
if (code !== "ENOENT") {
|
|
932
|
-
emit({
|
|
673
|
+
run.emit({
|
|
933
674
|
type: "error",
|
|
934
675
|
path: key,
|
|
935
676
|
message: `tombstone unlink failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
936
677
|
});
|
|
937
|
-
// Skip removeEntry / filesTombstoned / progress event — the
|
|
938
|
-
// tombstone hasn't actually been honored. Next sync retries.
|
|
939
678
|
continue;
|
|
940
679
|
}
|
|
941
680
|
}
|
|
942
|
-
removeEntry(journal, key);
|
|
943
|
-
filesTombstoned++;
|
|
944
|
-
emit({
|
|
681
|
+
removeEntry(run.journal, key);
|
|
682
|
+
counters.filesTombstoned++;
|
|
683
|
+
run.emit({
|
|
945
684
|
type: "progress",
|
|
946
685
|
path: key,
|
|
947
686
|
bytes: 0,
|
|
948
687
|
deleted: true,
|
|
949
|
-
// Suffix differentiates a tombstone from a normal delete in the
|
|
950
|
-
// tty stream — matches the push-side `defaultConsoleLogger`
|
|
951
|
-
// tombstone surface in share.ts.
|
|
952
688
|
message: removedSomething ? "tombstone (cross-machine delete)" : "tombstone (already absent locally)",
|
|
953
689
|
});
|
|
954
690
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
// the journal keys; `all` mode records `[""]` (covers everything).
|
|
959
|
-
appendPullRecord(journal, {
|
|
691
|
+
}
|
|
692
|
+
function finalizePullRun(run, plan, scopeRun, counters) {
|
|
693
|
+
appendPullRecord(run.journal, {
|
|
960
694
|
pullId: generatePullId(),
|
|
961
|
-
companyUid: ctx.uid,
|
|
962
|
-
startedAt,
|
|
695
|
+
companyUid: run.ctx.uid,
|
|
696
|
+
startedAt: run.startedAt,
|
|
963
697
|
completedAt: new Date().toISOString(),
|
|
964
|
-
syncMode,
|
|
965
|
-
prefixSet: currentPrefixSet,
|
|
966
|
-
scopeChangeDetected: shrinkPlan.scopeChangeDetected,
|
|
967
|
-
orphansRemoved: scopeOrphansRemoved,
|
|
968
|
-
orphansBlocked: shrinkResult.dirtyTombstoned,
|
|
698
|
+
syncMode: run.syncMode,
|
|
699
|
+
prefixSet: run.currentPrefixSet,
|
|
700
|
+
scopeChangeDetected: scopeRun.shrinkPlan.scopeChangeDetected,
|
|
701
|
+
orphansRemoved: scopeRun.scopeOrphansRemoved,
|
|
702
|
+
orphansBlocked: scopeRun.shrinkResult.dirtyTombstoned,
|
|
969
703
|
});
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
// When the pull actually changed on-disk sources (new files, tombstoned
|
|
977
|
-
// removals, or scope-orphan cleanups), refresh the generated skill wrappers,
|
|
978
|
-
// personal-overlay mirrors, and workers registry. reindex is idempotent and
|
|
979
|
-
// best-effort — it must never fail a sync, and is skipped on no-op syncs
|
|
980
|
-
// (the common daemon case) and when the caller opts out via skipReindex.
|
|
981
|
-
const changedOnDisk = filesDownloaded > 0 ||
|
|
982
|
-
filesTombstoned > 0 ||
|
|
983
|
-
scopeOrphansRemoved > 0;
|
|
984
|
-
if (!options.skipReindex && changedOnDisk) {
|
|
704
|
+
run.journal.lastSync = new Date().toISOString();
|
|
705
|
+
writeJournal(run.journalSlug, run.journal);
|
|
706
|
+
const changedOnDisk = counters.filesDownloaded > 0 ||
|
|
707
|
+
counters.filesTombstoned > 0 ||
|
|
708
|
+
scopeRun.scopeOrphansRemoved > 0;
|
|
709
|
+
if (!run.options.skipReindex && changedOnDisk) {
|
|
985
710
|
try {
|
|
986
|
-
|
|
987
|
-
// lock; reindex re-acquiring would refuse against our own live PID.
|
|
988
|
-
reindex({ repoRoot: hqRoot, skipLock: true });
|
|
711
|
+
reindex({ repoRoot: run.hqRoot, skipLock: true });
|
|
989
712
|
}
|
|
990
713
|
catch {
|
|
991
714
|
// best-effort: a post-sync refresh failure never fails the sync
|
|
992
715
|
}
|
|
993
716
|
}
|
|
994
717
|
return {
|
|
995
|
-
filesDownloaded,
|
|
996
|
-
bytesDownloaded,
|
|
997
|
-
filesSkipped,
|
|
998
|
-
conflicts,
|
|
999
|
-
conflictPaths,
|
|
718
|
+
filesDownloaded: counters.filesDownloaded,
|
|
719
|
+
bytesDownloaded: counters.bytesDownloaded,
|
|
720
|
+
filesSkipped: counters.filesSkipped,
|
|
721
|
+
conflicts: counters.conflicts,
|
|
722
|
+
conflictPaths: counters.conflictPaths,
|
|
1000
723
|
aborted: false,
|
|
1001
724
|
newFiles: plan.newFiles,
|
|
1002
725
|
newFilesCount: plan.newFilesCount,
|
|
1003
726
|
filesExcludedByPolicy: plan.filesExcludedByPolicy,
|
|
1004
|
-
filesTombstoned,
|
|
1005
|
-
filesOutOfScope,
|
|
1006
|
-
scopeOrphansRemoved,
|
|
1007
|
-
scopeOrphansBlocked: shrinkResult.dirtyTombstoned,
|
|
727
|
+
filesTombstoned: counters.filesTombstoned,
|
|
728
|
+
filesOutOfScope: counters.filesOutOfScope,
|
|
729
|
+
scopeOrphansRemoved: scopeRun.scopeOrphansRemoved,
|
|
730
|
+
scopeOrphansBlocked: scopeRun.shrinkResult.dirtyTombstoned,
|
|
1008
731
|
};
|
|
1009
732
|
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Resolve active company from .hq/config.json.
|
|
1012
|
-
*/
|
|
1013
|
-
function resolveActiveCompany(hqRoot) {
|
|
1014
|
-
const configPath = path.join(hqRoot, ".hq", "config.json");
|
|
1015
|
-
if (fs.existsSync(configPath)) {
|
|
1016
|
-
try {
|
|
1017
|
-
const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
1018
|
-
return config.activeCompany ?? config.companySlug;
|
|
1019
|
-
}
|
|
1020
|
-
catch {
|
|
1021
|
-
// Ignore parse errors
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
return undefined;
|
|
1025
|
-
}
|
|
1026
|
-
/**
|
|
1027
|
-
* Returns true when the remote object appears to have moved since the
|
|
1028
|
-
* journal entry's last-recorded sync. Prefers ETag equality; falls back to
|
|
1029
|
-
* `lastModified > syncedAt` for legacy entries written before remoteEtag
|
|
1030
|
-
* was tracked. Conservative on tie (`<=` skews "remote unchanged").
|
|
1031
|
-
*/
|
|
1032
|
-
function hasRemoteChanged(remote, entry) {
|
|
1033
|
-
if (entry.remoteEtag) {
|
|
1034
|
-
return normalizeEtag(remote.etag) !== entry.remoteEtag;
|
|
1035
|
-
}
|
|
1036
|
-
const syncedAt = new Date(entry.syncedAt).getTime();
|
|
1037
|
-
return remote.lastModified.getTime() > syncedAt;
|
|
1038
|
-
}
|
|
1039
733
|
/**
|
|
1040
734
|
* Decide whether a remote object present in the LIST is a GENUINE RE-CREATE
|
|
1041
735
|
* written AFTER a FILE_TOMBSTONE — in which case the tombstone is stale and the
|
|
@@ -1617,15 +1311,6 @@ fileTombstones = new Map()) {
|
|
|
1617
1311
|
tombstones,
|
|
1618
1312
|
};
|
|
1619
1313
|
}
|
|
1620
|
-
/**
|
|
1621
|
-
* Check if an error is an S3 access denied (expected for filtered guests).
|
|
1622
|
-
*/
|
|
1623
|
-
function isAccessDenied(err) {
|
|
1624
|
-
if (err && typeof err === "object" && "name" in err) {
|
|
1625
|
-
return err.name === "AccessDenied" || err.name === "Forbidden";
|
|
1626
|
-
}
|
|
1627
|
-
return false;
|
|
1628
|
-
}
|
|
1629
1314
|
/**
|
|
1630
1315
|
* Default human-readable event rendering. Preserves the exact output format
|
|
1631
1316
|
* that `hq sync` emitted before SyncProgressEvent was introduced, so callers
|