farseer-cli 1.7.3 → 1.8.0

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/syncService.ts"],
4
- "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SCRIPT_EXTENSIONS } from './farseerFactory';\nimport { getSyncIncludes } from './configService';\nimport {\n calculateHash,\n getTenantFilesDir,\n getSyncFilePath,\n ensureDirectoryExists,\n getAllFilesInDir,\n fetchWithConcurrency,\n isHiddenFile,\n isOsMetadataFile,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { ValidationFailure, partitionForUpload, isLikelyTextFile } from '../utils/fileValidation';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { IGNORED_LOCAL_CAP } from '../utils/syncReporting';\n\n// Re-export so existing test imports (`from '../../src/services/syncService'`)\n// keep working \u2014 `isOsMetadataFile` moved to utils/helpers.ts so the file\n// listing helper can apply it as the default filter.\nexport { isOsMetadataFile, isHiddenFile } from '../utils/helpers';\n\nexport interface SyncOptions {\n all?: boolean;\n force?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n conflictResolutions?: ConflictResolutions;\n /**\n * Whitelist of file paths (relative to the tenant files dir).\n * When set, only listed paths participate in the sync \u2014 everything\n * else is treated as out-of-scope (not modified, not deleted, not\n * compared). Used by `farseer push --only` to push a single file\n * without touching unrelated drift in the working tree.\n */\n onlyFiles?: string[];\n}\n\n/**\n * Tooling-output folder names used to classify ignored files in the\n * warning. We DON'T use this list to widen `shouldIncludeFile`'s exclusion\n * rules \u2014 that gate stays narrow on purpose (the current default scope is\n * `.ts`/`.js`/`.mjs`/`.cjs` so a `node_modules/foo.ts` would be in-scope\n * and that's a deliberate choice we don't reverse here). Instead, the\n * blocklist tells the warning consumer \"this ignored file is in a folder\n * users almost never want to sync\" so the hint can say \"opting in is\n * unusual\" instead of generic \"include with --include-ext\".\n *\n * Match against ANY path segment: a file under `Scripts/node_modules/`\n * still flags as blocklisted-folder for the purposes of the warning copy.\n */\nconst IGNORED_FOLDER_BLOCKLIST = ['node_modules', 'dist', 'build', 'bower_components', 'coverage', '__pycache__'];\n\n/**\n * Reason a file was excluded from the active sync scope. Surfaced through\n * `SyncStatus.ignoredLocal` (and `push().ignoredLocal`) so the warning can\n * give a category-specific hint instead of a single generic line that\n * sometimes nudges users toward including `node_modules/`.\n *\n * Hidden files are NOT modelled here: they're excluded upstream from the\n * warning entirely (the warning suggests opt-in flags, and any opt-in\n * pointed at `.env` / `.git/` is a credential-leak vector). Add a category\n * here only when the consumer is allowed to advertise it.\n */\nexport type IgnoredReason = 'unsupportedExtension' | 'blocklistedFolder';\n\nexport interface IgnoredLocalEntry {\n path: string;\n reason: IgnoredReason;\n}\n\n/**\n * Classify why a non-hidden, non-OS-junk local file was rejected by\n * `shouldIncludeFile`. The two categories are mutually exclusive (we\n * pick the most specific reason \u2014 `blocklistedFolder` wins over\n * `unsupportedExtension` because a `node_modules/foo.json` is \"tooling\n * output\" first, \"wrong extension\" second).\n *\n * Caller must have already filtered hidden files and OS metadata. We\n * assert nothing about that here \u2014 it's the caller's job and folding\n * the check in would mask the security-sensitive exclusion behind a\n * generic classifier.\n */\nexport function classifyIgnoredFile(filePath: string): IgnoredReason {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (IGNORED_FOLDER_BLOCKLIST.includes(seg)) return 'blocklistedFolder';\n }\n return 'unsupportedExtension';\n}\n\n/**\n * Build a `shouldSkipDir` predicate for `getAllFilesInDir` that prunes\n * hidden subtrees the caller could not include anyway. This is the part\n * that actually bounds memory \u2014 without it a `.git/` or `.cache/` next\n * to the tenant `files/` folder still materialises every filename in\n * the walker before any filter runs.\n *\n * Returns true (skip) when the dir is hidden AND no include-folder\n * (from the per-command options or persistent config) nor `--only`\n * file path overlaps it. We keep the walk for any user-listed hidden\n * folder so `farseer config include --folder .vscode` continues to\n * work, and for hidden paths under `--only` so `farseer push --only\n * .vscode/settings.json` doesn't get pruned before the only-check\n * runs in `shouldIncludeFile`.\n */\nexport function buildHiddenDirSkipper(\n options: Pick<SyncOptions, 'includeFolders' | 'onlyFiles'> | undefined,\n configFolders: string[],\n): (relPath: string) => boolean {\n const normalize = (f: string) =>\n f\n .split(path.sep)\n .join('/')\n .replace(/^\\/+|\\/+$/g, '');\n const includeFolders = [...(options?.includeFolders ?? []), ...configFolders].map((f) =>\n f.split(path.sep).join('/').replace(/\\/+$/, ''),\n );\n const onlyFilesPosix = (options?.onlyFiles ?? []).map(normalize);\n return (relPath: string) => {\n const posix = relPath.split(path.sep).join('/');\n if (!isHiddenFile(posix)) return false;\n for (const include of includeFolders) {\n if (posix === include) return false;\n if (posix.startsWith(include + '/')) return false;\n if (include.startsWith(posix + '/')) return false;\n }\n for (const only of onlyFilesPosix) {\n if (only === posix) return false;\n if (only.startsWith(posix + '/')) return false;\n if (posix.startsWith(only + '/')) return false;\n }\n return true;\n };\n}\n\n/**\n * Determines if a file should be included in sync operations.\n *\n * Exclusion rules (run before any include rule):\n * - OS metadata (.DS_Store, Thumbs.db, ._foo, \u2026) \u2014 never synced.\n * - Hidden files / folders (any path segment starting with `.` \u2014 e.g.\n * .env, .git/, .vscode/) \u2014 synced only when explicitly opted in via\n * an `--include-folder` (or persistent folder include) whose prefix\n * covers the hidden path. Extension-based includes (`--include-ext\n * .json` / persistent extension includes) and `--all` do NOT pull\n * hidden files into scope \u2014 that would let a generic \".json\"\n * broadening leak `.vscode/settings.json`, `.aws/credentials.json`,\n * etc. The folder-based opt-in is the single way to consent to\n * syncing a hidden directory.\n *\n * Inclusion rules (file must satisfy at least one):\n * 1. `--all` flag is passed (only for non-hidden files).\n * 2. Has a default script extension (.ts, .js).\n * 3. Has an extension from inline includeExtensions option.\n * 4. Lives under a folder from inline includeFolders option.\n * 5. Has an extension from persistent syncIncludes config.\n * 6. Lives under a folder from persistent syncIncludes config.\n */\nexport function shouldIncludeFile(\n filePath: string,\n tenant: string,\n options?: Pick<SyncOptions, 'all' | 'includeExtensions' | 'includeFolders' | 'onlyFiles'>,\n): boolean {\n // OS metadata is always excluded \u2014 `--all` should sync the user's work,\n // not their filesystem's bookkeeping.\n if (isOsMetadataFile(filePath)) return false;\n\n // `--only` is a hard whitelist: when set, anything not listed is\n // out of scope regardless of other include rules. We compare on\n // exact relative path; the caller normalises before passing.\n if (options?.onlyFiles && options.onlyFiles.length > 0) {\n return options.onlyFiles.includes(filePath);\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const persistent = getSyncIncludes(tenant);\n\n const folderMatches =\n (options?.includeFolders?.some((f) => filePath.startsWith(f + '/') || filePath === f) ?? false) ||\n (persistent?.folders?.some((f) => filePath.startsWith(f + '/') || filePath === f) ?? false);\n\n // Hidden files (.env, .git/, .vscode/, \u2026) require a FOLDER-level\n // opt-in. Extension-based includes (`--include-ext .json`) are too\n // broad \u2014 following a \"include .json files\" hint would silently\n // pull `.vscode/settings.json` or `.aws/credentials.json` into the\n // push set. To sync a hidden file, the user names the hidden\n // directory explicitly: `--include-folder .vscode`. `--all` also\n // does not cover hidden paths for the same reason.\n if (isHiddenFile(filePath)) return folderMatches;\n\n const extensionMatches =\n (options?.includeExtensions?.includes(ext) ?? false) || (persistent?.extensions?.includes(ext) ?? false);\n const matchesIncludes = folderMatches || extensionMatches;\n\n if (options?.all) return true;\n if (DEFAULT_SCRIPT_EXTENSIONS.includes(ext)) return true;\n return matchesIncludes;\n}\n\nexport interface SyncFileInfo {\n localHash: string;\n remoteHash: string;\n metadata?: {\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n lastFetched?: string;\n };\n}\n\nexport interface SyncState {\n lastSync: string;\n files: Record<string, SyncFileInfo>;\n}\n\n/**\n * A single status snapshot produced by `getStatus()`. Both `farseer status`\n * (preview) and `farseer push` (preflight) use this shape so the user sees\n * the same buckets in both commands.\n *\n * The legacy two-bucket layout (`modifiedLocally` / `modifiedRemotely`)\n * silently lumped deletions in with edits, which was the single biggest\n * source of \"why does status say M for a file that's actually deleted?\"\n * confusion. This shape splits the six combinatoric outcomes into their\n * own buckets and keeps `modifiedLocally` / `modifiedRemotely` as\n * derived aliases for back-compat with code that still reads them.\n */\nexport interface SyncStatus {\n addedLocally: string[];\n modifiedLocally: string[];\n deletedLocally: string[];\n addedRemotely: string[];\n modifiedRemotely: string[];\n deletedRemotely: string[];\n inSync: string[];\n conflicts: SyncConflict[];\n /**\n * True when the status was computed without fetching remote file\n * content. In `deep: false` mode the comparator can detect adds /\n * deletes / *local* modifications, but cannot distinguish a\n * remote-modified file from an in-sync one because that requires\n * downloading and hashing the remote content. Treat this flag as\n * \"remote-edit detection skipped\" rather than \"everything checked\".\n */\n deepCompare: boolean;\n /**\n * Real remote-content hashes keyed by file path. Only populated when\n * `deep: true` ran (the listing-only fast mode never downloads bytes).\n * Exposed so a follow-up `push({ precomputedRemoteHashes })` can skip\n * its own re-download for files already covered here \u2014 under\n * `push --force --mirror` these two operations would otherwise both\n * fetch the same set of remote contents back-to-back.\n */\n remoteHashes?: Map<string, string>;\n /**\n * Local files we walked but excluded from comparison because\n * `shouldIncludeFile` rejected them under the current options. Used\n * by the CLI to warn the user when their work-in-progress files are\n * being silently skipped \u2014 the previous behaviour reported \"in sync\"\n * even when local edits lived in files outside the default\n * .ts/.js whitelist.\n *\n * Each entry carries a `reason` so the warning can group files by\n * cause and give a category-specific opt-in hint:\n * - `unsupportedExtension` \u2192 suggest `--include-ext <ext>`.\n * - `blocklistedFolder` \u2192 warn that opting in is unusual; the\n * folder is one users rarely want synced (node_modules/, dist/).\n *\n * Hidden files (`.env`, `.git/`, `.vscode/`) are NOT included here:\n * the consumer's job is to suggest opt-in flags, and pointing the\n * user at `--all` / `--include-ext` for `.env` is a credential\n * leak vector.\n *\n * Capped at `IGNORED_LOCAL_CAP` entries \u2014 a user that drops a sibling\n * repo into the synced folder shouldn't blow up memory or produce a\n * console wall. `ignoredLocalTotal` records the uncapped count so\n * UIs can still show the true number.\n */\n ignoredLocal: IgnoredLocalEntry[];\n /**\n * Uncapped count corresponding to `ignoredLocal`. When this exceeds\n * `ignoredLocal.length`, the slice was truncated to keep memory and\n * log output bounded.\n */\n ignoredLocalTotal: number;\n /**\n * Uncapped per-reason breakdown of `ignoredLocalTotal`. Tracked\n * during the same walk that builds `ignoredLocal`, so a consumer\n * rendering a category summary (\"250 outside scope: 230 with\n * unsupported extension, 20 in blocklisted folders\") gets honest\n * numbers even when the cap truncated the path slice. Counting the\n * stored slice would understate the breakdown whenever the cap\n * fires; that disagreement is what callers cannot reproduce from\n * `ignoredLocal` alone.\n */\n ignoredLocalTotalByReason: {\n unsupportedExtension: number;\n blocklistedFolder: number;\n };\n}\n\nexport interface GetStatusOptions extends SyncOptions {\n /**\n * When true, fetch and hash every remote file's content so we can\n * detect remote-side content edits made by other users. Slow on big\n * tenants. Default: false (list-only).\n */\n deep?: boolean;\n}\n\nfunction emptyStatus(deepCompare: boolean): SyncStatus {\n return {\n addedLocally: [],\n modifiedLocally: [],\n deletedLocally: [],\n addedRemotely: [],\n modifiedRemotely: [],\n deletedRemotely: [],\n inSync: [],\n conflicts: [],\n deepCompare,\n ignoredLocal: [],\n ignoredLocalTotal: 0,\n ignoredLocalTotalByReason: { unsupportedExtension: 0, blocklistedFolder: 0 },\n };\n}\n\n// Three-way comparison types\n\nexport type FileChangeType =\n | 'unchanged'\n | 'local_modified'\n | 'remote_modified'\n | 'remote_deleted'\n | 'local_deleted'\n | 'local_new'\n | 'remote_new'\n | 'conflict_both_modified'\n | 'conflict_local_modified_remote_deleted'\n | 'conflict_local_deleted_remote_modified'\n | 'conflict_both_new';\n\nexport interface FileCompareResult {\n filePath: string;\n changeType: FileChangeType;\n currentLocalHash: string | null;\n currentRemoteHash: string | null;\n baselineLocalHash: string | null;\n baselineRemoteHash: string | null;\n}\n\nexport interface SyncConflict {\n filePath: string;\n type: 'both_modified' | 'local_modified_remote_deleted' | 'local_deleted_remote_modified' | 'both_new';\n description: string;\n}\n\nexport interface PushFailure {\n filePath: string;\n operation: 'create' | 'update' | 'delete';\n reason: string;\n}\n\nexport type ConflictResolution = 'keep_local' | 'keep_remote' | 'keep_both' | 'merge_markers';\nexport type ConflictResolutions = Record<string, ConflictResolution>;\n\n/**\n * Markers we wrap a conflicted file with under the `merge_markers`\n * resolution \u2014 same convention as git so any IDE / editor picks them\n * up automatically and lets the user choose visually.\n *\n * The push pre-flight (utils/fileValidation.ts) refuses files that\n * still contain these markers \u2014 pushing an unresolved file would\n * upload broken syntax to the backend.\n */\nexport const MERGE_MARKER_LOCAL_START = '<<<<<<< LOCAL (your version)';\nexport const MERGE_MARKER_SEPARATOR = '=======';\nexport const MERGE_MARKER_REMOTE_END = '>>>>>>> REMOTE';\n\nexport class SyncService {\n private tenant: string;\n private farseerClient: IFarseerClient;\n\n constructor(tenant: string, farseerClient: IFarseerClient) {\n this.tenant = tenant;\n this.farseerClient = farseerClient;\n }\n\n loadSyncState(): SyncState {\n const syncFilePath = getSyncFilePath(this.tenant);\n\n if (!fs.existsSync(syncFilePath)) {\n return {\n lastSync: '',\n files: {},\n };\n }\n\n try {\n const content = fs.readFileSync(syncFilePath, 'utf-8');\n return JSON.parse(content) as SyncState;\n } catch {\n return {\n lastSync: '',\n files: {},\n };\n }\n }\n\n saveSyncState(state: SyncState): void {\n const syncFilePath = getSyncFilePath(this.tenant);\n ensureDirectoryExists(path.dirname(syncFilePath));\n fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), 'utf-8');\n }\n\n /**\n * Single status engine used by both `farseer status` and the push\n * preflight. By default (deep=false) we list remote files but don't\n * download their content \u2014 fast on big tenants and accurate for adds,\n * deletes, and *local* edits. Pass deep=true (or `farseer status --deep`)\n * to also detect remote-side edits, which requires hashing every remote\n * file.\n *\n * Output buckets are explicit (added/modified/deleted on each side) so\n * the user never sees \"M file.ts\" for a file that's actually deleted on\n * one side \u2014 a regular failure mode of the previous two-bucket layout.\n */\n async getStatus(options?: GetStatusOptions): Promise<SyncStatus> {\n const deep = options?.deep === true;\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // shouldIncludeFile must run on every entry, even under --all: it\n // gates hidden paths (`.env`, `.vscode/`, `.git/`) which only get\n // synced when the user explicitly lists them via --include-ext or\n // --include-folder. Without the call here, --all would pick up a\n // local `.env` and either unlink it on pull --force or upload it.\n //\n // Track entries we rejected so the CLI can warn the user; the\n // previous behaviour silently dropped non-whitelisted files and\n // reported \"in sync\" even when the user had pending work on disk.\n //\n // Hidden files (`.env`, `.git/*`, `.vscode/*`) are NEVER surfaced\n // here: the warning suggests `--all` / `--include-ext` as the fix,\n // and pointing the user at those flags for a credential file is a\n // credential-leak path. Hidden files stay invisible \u2014 users who\n // genuinely want to sync one do it via the explicit `farseer\n // config include` path, which has its own affordances.\n // Skip hidden directories at recursion time when the user hasn't\n // include-listed them. This is the memory-bound the cap on\n // `ignoredLocal` advertises \u2014 without it we still materialise every\n // path under `.git/` / `.cache/` / `.svelte-kit/` before any filter\n // runs. The skip is safe because:\n // - hidden files never appear in `ignoredLocal` anyway (security),\n // - the only way a hidden file enters scope is `--include-folder`\n // against the hidden prefix, in which case we keep walking.\n const includeFoldersFromConfig = getSyncIncludes(this.tenant)?.folders ?? [];\n const skipHiddenDir = buildHiddenDirSkipper(options, includeFoldersFromConfig);\n const allLocalFiles = getAllFilesInDir(filesDir, { shouldSkipDir: skipHiddenDir });\n const localFiles: string[] = [];\n const ignoredLocal: IgnoredLocalEntry[] = [];\n let ignoredLocalTotal = 0;\n const ignoredLocalTotalByReason = { unsupportedExtension: 0, blocklistedFolder: 0 };\n // `--only` is an intentional hard narrowing \u2014 the user explicitly\n // listed the file(s) they care about. Everything else on disk is\n // \"out of scope\" by construction, not \"accidentally skipped\", so\n // surfacing it as a warning is noise that suggests broadening\n // scope the user just rejected. Skip the bucket entirely under\n // --only and keep the totals at zero.\n const suppressIgnoredLocal = (options?.onlyFiles?.length ?? 0) > 0;\n for (const f of allLocalFiles) {\n if (shouldIncludeFile(f, this.tenant, options)) {\n localFiles.push(f);\n continue;\n }\n // OS junk and hidden files are excluded silently. Hidden files\n // in particular MUST NOT be advertised in the warning \u2014 that\n // would tell users to widen scope to include `.env`.\n if (isOsMetadataFile(f) || isHiddenFile(f)) continue;\n if (suppressIgnoredLocal) continue;\n ignoredLocalTotal++;\n const reason = classifyIgnoredFile(f);\n // Track per-reason totals over the FULL walk, not just the\n // capped slice. The MCP summary renders \"X with unsupported\n // extension, Y in blocklisted folders\" \u2014 counting the stored\n // paths would understate both buckets whenever the cap fires\n // (e.g. 250 ignored files \u2192 summary reads `100 with \u2026` and\n // the user thinks they're looking at the real number).\n ignoredLocalTotalByReason[reason]++;\n // Cap the in-memory preview list. The totals above remain\n // exact; this only bounds how many paths we KEEP for the\n // warning render. Combined with the hidden-dir pruning in\n // `shouldSkipDir` above, this gives the walker a memory\n // ceiling for the common large-tree shapes (`.git/`,\n // `.cache/`, `.svelte-kit/`). A `node_modules/` planted in\n // the tenant files dir is NOT pruned at recursion time \u2014\n // that would change the semantics of the current default\n // scope \u2014 so the cap is the last line of defence there.\n if (ignoredLocal.length < IGNORED_LOCAL_CAP) {\n ignoredLocal.push({ path: f, reason });\n }\n }\n\n const localHashes = new Map<string, string>();\n for (const file of localFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localHashes.set(file, calculateHash(content));\n }\n\n const remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n const remoteHashes = new Map<string, string>();\n if (deep) {\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { path: file.path, hash: calculateHash(content) };\n },\n 15,\n );\n for (const { path: filePath, hash } of fileContents) {\n remoteHashes.set(filePath, hash);\n }\n } else {\n // Fast mode: we never download remote content. The comparator\n // needs *some* hash, so we pick the value that makes its three-\n // way logic produce the \"trust syncState\" answer:\n //\n // \u2022 If we have a baseline remote hash, reuse it. This makes\n // `remoteChanged` always false in fast mode \u2014 the explicit\n // trade-off (we miss someone else's edits between pull and\n // push), surfaced via `status.deepCompare = false`.\n // \u2022 If there is no baseline but the file exists locally, use\n // the local hash. Without this, \"first-time both-sides\n // exist\" (fresh clone, no .farseer-sync.json) flips to\n // `conflict_both_new` even though the most likely truth is\n // \"this file is fine, we just lost the baseline\". `pull`\n // and `push` correctly re-validate before doing anything\n // destructive, so an over-optimistic preview here is safe.\n // \u2022 Otherwise emit a path-unique sentinel so the comparator\n // classifies this as `remote_new` (added remotely).\n for (const file of remoteFiles) {\n const baseline = syncState.files[file.path]?.remoteHash;\n if (baseline) {\n remoteHashes.set(file.path, baseline);\n continue;\n }\n const localHash = localHashes.get(file.path);\n if (localHash) {\n remoteHashes.set(file.path, localHash);\n continue;\n }\n remoteHashes.set(file.path, `__remote_present__:${file.path}`);\n }\n }\n\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n onlyFiles: options?.onlyFiles,\n });\n\n const status = emptyStatus(deep);\n status.ignoredLocal = ignoredLocal;\n status.ignoredLocalTotal = ignoredLocalTotal;\n status.ignoredLocalTotalByReason = ignoredLocalTotalByReason;\n if (deep) {\n // Hand back the just-computed deep map so callers (e.g. push.ts\n // running a deep status before a mirror push) can pass it into\n // service.push() and avoid re-downloading every file body.\n status.remoteHashes = remoteHashes;\n }\n\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'unchanged':\n status.inSync.push(c.filePath);\n break;\n case 'local_modified':\n status.modifiedLocally.push(c.filePath);\n break;\n case 'remote_modified':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_new':\n status.addedLocally.push(c.filePath);\n break;\n case 'remote_new':\n status.addedRemotely.push(c.filePath);\n break;\n case 'remote_deleted':\n status.deletedRemotely.push(c.filePath);\n break;\n case 'local_deleted':\n status.deletedLocally.push(c.filePath);\n break;\n default:\n status.conflicts.push(SyncService.buildConflicts([c])[0]);\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: SyncOptions): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n conflictFilesWritten: string[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n ensureDirectoryExists(filesDir);\n\n const syncState = this.loadSyncState();\n // shouldIncludeFile must run even under --all so the hidden-file\n // gate (`.env`, `.vscode/`, `.git/`) stays in effect \u2014 these only\n // sync when explicitly listed in --include-ext / --include-folder.\n let remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // Batch fetch metadata for all files\n remoteFiles = await this.fetchMetadataForFiles(remoteFiles);\n\n const result = {\n downloaded: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n conflictFilesWritten: [] as string[],\n };\n\n // Download file contents in parallel with concurrency limit\n logger.dim(`Fetching ${remoteFiles.length} files in parallel...`);\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file, index) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n // Show progress every 10 files\n if ((index + 1) % 10 === 0 || index === remoteFiles.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteFiles.length} files`);\n }\n return { file, content };\n },\n 15,\n );\n // Clear progress line\n if (remoteFiles.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n // Build remote content map with hashes\n const remoteContentMap = new Map<string, { file: RemoteFile; content: Buffer; hash: string }>();\n const remoteHashes = new Map<string, string>();\n for (const { file, content } of fileContents) {\n const hash = calculateHash(content);\n remoteContentMap.set(file.path, { file, content, hash });\n remoteHashes.set(file.path, hash);\n }\n\n // Build local hashes. shouldIncludeFile runs on every entry so the\n // hidden-file gate stays in effect even under --all.\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n if (!shouldIncludeFile(localFile, this.tenant, options)) {\n continue;\n }\n const localPath = safeResolveWithinBase(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n onlyFiles: options?.onlyFiles,\n });\n const resolutions = options?.conflictResolutions ?? {};\n\n for (const comparison of comparisons) {\n const { filePath, changeType } = comparison;\n const localPath = safeResolveWithinBase(filesDir, filePath);\n const remoteInfo = remoteContentMap.get(filePath);\n\n switch (changeType) {\n case 'unchanged':\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_modified':\n case 'local_new':\n if (options?.force && remoteInfo) {\n // --force on pull means \"make local match remote\".\n // Without this branch, local_modified silently went\n // into `unchanged` and the user's edit survived a\n // hard-reset \u2014 the opposite of what --force promises.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_deleted':\n if (options?.force && remoteInfo) {\n // Force: restore the file the user removed locally.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n break;\n\n case 'remote_modified':\n case 'remote_new':\n // Safe to write\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo!.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo!.hash,\n remoteHash: remoteInfo!.hash,\n metadata: this.buildMetadata(remoteInfo!.file),\n };\n break;\n\n case 'remote_deleted':\n // Safe to delete (local is unchanged)\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n }\n result.deleted.push(filePath);\n delete syncState.files[filePath];\n break;\n\n case 'conflict_both_modified':\n case 'conflict_local_modified_remote_deleted':\n case 'conflict_local_deleted_remote_modified':\n case 'conflict_both_new': {\n if (options?.force) {\n // Force: apply remote state\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted, force means delete local\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n }\n\n const resolution = resolutions[filePath];\n if (!resolution) {\n // No resolution provided - report conflict, skip file\n result.conflicts.push(SyncService.buildConflicts([comparison])[0]);\n break;\n }\n\n switch (resolution) {\n case 'keep_local':\n // Keep local as-is, update sync state to mark conflict resolved\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n } else {\n // Local was deleted, user wants to keep that decision\n delete syncState.files[filePath];\n }\n result.unchanged.push(filePath);\n break;\n\n case 'keep_remote':\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n\n case 'keep_both':\n if (remoteInfo) {\n // Write remote version as .remote file alongside local\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteInfo.content);\n result.conflictFilesWritten.push(conflictFileName);\n }\n // Keep local, update sync state\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n }\n result.unchanged.push(filePath);\n break;\n\n case 'merge_markers':\n // git-style inline merge. Wrap LOCAL and REMOTE\n // versions with markers so any editor / IDE\n // highlights them. After the user resolves the\n // file (manually picks the version they want and\n // strips the markers), a regular `farseer push`\n // uploads the cleaned-up content. The push\n // pre-flight refuses any file that still has\n // markers in it, so an accidentally-unfinished\n // resolve never reaches the backend as broken\n // syntax.\n if (remoteInfo && fs.existsSync(localPath)) {\n const localBuf = fs.readFileSync(localPath);\n const remoteBuf = remoteInfo.content;\n\n // Binary safety gate. Splicing UTF-8 markers\n // into a .png/.xlsx/.zip would corrupt it\n // (the toString('utf-8') round-trip flips\n // bytes). Fall back to keep_both \u2014 write\n // remote alongside local as <name>.remote.<ext>\n // and let the user diff with their tool of\n // choice. Without this gate the user's binary\n // got silently overwritten with garbage.\n if (!isLikelyTextFile(filePath, localBuf) || !isLikelyTextFile(filePath, remoteBuf)) {\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteBuf);\n const localHash = calculateHash(localBuf);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(\n `${conflictFileName} (binary \u2014 merge markers not safe; wrote .remote alongside)`,\n );\n result.unchanged.push(filePath);\n break;\n }\n\n const localContent = localBuf.toString('utf-8');\n const remoteContent = remoteBuf.toString('utf-8');\n const merged =\n `${MERGE_MARKER_LOCAL_START}\\n${localContent}` +\n `${localContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_SEPARATOR}\\n${remoteContent}` +\n `${remoteContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_REMOTE_END}\\n`;\n fs.writeFileSync(localPath, merged);\n // Update syncState so push sees this as\n // \"locally modified\" (localHash differs from\n // remoteHash). User pushes cleaned-up file\n // after manually resolving.\n const newHash = calculateHash(Buffer.from(merged));\n syncState.files[filePath] = {\n localHash: newHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(`${filePath} (merge markers)`);\n } else if (!remoteInfo && fs.existsSync(localPath)) {\n // Remote is gone \u2014 fall back to keep_local.\n // No useful merge for \"your version vs nothing\".\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = { localHash, remoteHash: '' };\n }\n result.unchanged.push(filePath);\n break;\n }\n break;\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n private buildMetadata(file: RemoteFile): SyncFileInfo['metadata'] {\n if (!file.metadata) return undefined;\n return {\n uploadTime: file.metadata.uploadTime,\n uploaderEmail: file.metadata.uploader?.email,\n uploaderName: file.metadata.uploader\n ? `${file.metadata.uploader.firstName} ${file.metadata.uploader.lastName}`.trim()\n : undefined,\n lastFetched: new Date().toISOString(),\n };\n }\n\n async push(options?: {\n force?: boolean;\n mirror?: boolean;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n /**\n * Hard whitelist (relative paths). When set, only these files are\n * considered for upload / delete. Mirrors the CLI's `--only` flag.\n * Forwarded from push.ts so the surgical-push path stays scoped\n * inside service.push too \u2014 without this, push() would walk every\n * eligible file and the `--only` semantic only applied at the\n * preview stage.\n */\n onlyFiles?: string[];\n /**\n * Pre-fetched remote-content hashes keyed by file path. Optional\n * optimisation for callers (push.ts) that already ran a deep\n * status \u2014 that pass already downloaded every remote file's body,\n * so we can skip the second remote fetch here when the entries\n * cover everything we'd otherwise refetch. Missing keys still\n * trigger a fetch as before, so it's safe to pass a partial map.\n */\n precomputedRemoteHashes?: Map<string, string>;\n }): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n rejected: ValidationFailure[];\n failed: PushFailure[];\n /**\n * Same shape as `SyncStatus.ignoredLocal` \u2014 non-hidden, non-OS-junk\n * local files that didn't survive `shouldIncludeFile` under the\n * current options. Surfaced from push() so callers without a\n * separate status preflight (notably the MCP push handler) can\n * still warn the user that work-in-progress files were silently\n * outside the active scope. Hidden files are NEVER included here:\n * advertising `--all` / `--include-ext` for a credential file is a\n * leak vector.\n *\n * Each entry carries a `reason` (unsupportedExtension /\n * blocklistedFolder) so the consumer can give category-specific\n * advice \u2014 broaden by extension vs warn about opting in to a\n * tooling folder.\n *\n * Suppressed when `onlyFiles` is set \u2014 under `--only` the user\n * intentionally narrowed scope, so \"the other files exist but\n * weren't touched\" isn't a warning.\n */\n ignoredLocal: IgnoredLocalEntry[];\n /** Uncapped count for `ignoredLocal`; matches the `SyncStatus` shape. */\n ignoredLocalTotal: number;\n /**\n * Uncapped per-reason breakdown of `ignoredLocalTotal`. Same\n * rationale as `SyncStatus.ignoredLocalTotalByReason` \u2014 the\n * MCP push summary renders these so consumers see honest\n * category counts when the cap truncated the path slice.\n */\n ignoredLocalTotalByReason: {\n unsupportedExtension: number;\n blocklistedFolder: number;\n };\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const syncState = this.loadSyncState();\n\n const result = {\n uploaded: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n rejected: [] as ValidationFailure[],\n // Per-file failures from create/update/delete API calls. We don't\n // abort the whole push on the first failure \u2014 each item is its\n // own atomic operation, and `syncState` is saved in `finally` so\n // already-successful items aren't re-uploaded next run. The\n // caller surfaces this list and exits non-zero on non-empty.\n failed: [] as PushFailure[],\n ignoredLocal: [] as IgnoredLocalEntry[],\n ignoredLocalTotal: 0,\n ignoredLocalTotalByReason: { unsupportedExtension: 0, blocklistedFolder: 0 },\n };\n\n // Get current remote files (just the list, not content). Filter out\n // OS metadata defensively in case anyone ever pushed one before.\n const remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !isOsMetadataFile(f.path));\n const remoteFileMap = new Map<string, RemoteFile>();\n for (const file of remoteFiles) {\n remoteFileMap.set(file.path, file);\n }\n\n // OS metadata is stripped at the helper level (getAllFilesInDir),\n // so we never try to upload the user's filesystem bookkeeping \u2014\n // backend rejects those filenames and the user can't reasonably\n // remove them from the working tree.\n //\n // Mirror the hidden-dir pruning from getStatus: prune hidden\n // subtrees at recursion time when the user hasn't include-listed\n // them. CLI push covers this via the status preflight, but MCP\n // `farseer_push` calls service.push() directly \u2014 without the\n // skipper here, the walk materialises every path under `.git/`\n // / `.cache/` / `.svelte-kit/` before any filter runs.\n const includeFoldersFromConfig = getSyncIncludes(this.tenant)?.folders ?? [];\n const skipHiddenDir = buildHiddenDirSkipper(options, includeFoldersFromConfig);\n const allLocalFiles = getAllFilesInDir(filesDir, { shouldSkipDir: skipHiddenDir });\n\n // Apply the user's declared sync scope BEFORE we treat anything as\n // an upload candidate. Without this filter, push iterates every\n // file the disk listing returned and any whitelisted-extension\n // bystander gets shipped to remote \u2014 e.g. a `.vscode/settings.json`\n // sitting next to scripts passes pre-flight (`.json` is on the\n // backend whitelist) and is silently uploaded under a default\n // `farseer push`. The status preview already filters by\n // `shouldIncludeFile`, so the user wouldn't even see it coming.\n // Pin the same scope here.\n //\n // `localPresenceSet` keeps the FULL on-disk listing, separately,\n // so the delete loop's \"is this file actually missing locally?\"\n // protection still works for any file the user has \u2014 including\n // out-of-scope ones we won't touch.\n const localPresenceSet = new Set(allLocalFiles);\n // Always route through shouldIncludeFile \u2014 under --all the function\n // returns true for non-hidden files under --all but still gates\n // hidden ones (.env, .vscode/, .git/) so they require explicit\n // --include-folder opt-in.\n const inScopeFiles: string[] = [];\n // Same out-of-scope bookkeeping as getStatus \u2014 collected here so\n // MCP push (which calls service.push() directly, without a\n // separate getStatus preflight) can still surface the silent-skip\n // signal to its agent caller. Hidden files / OS metadata stay\n // invisible for the same security reason as getStatus.\n //\n // Under `--only` the user intentionally narrowed scope, so\n // everything outside that whitelist is \"explicitly excluded\",\n // not \"accidentally outside scope\" \u2014 suppress the bucket.\n const suppressIgnoredLocal = (options?.onlyFiles?.length ?? 0) > 0;\n for (const f of allLocalFiles) {\n if (shouldIncludeFile(f, this.tenant, options)) {\n inScopeFiles.push(f);\n continue;\n }\n if (suppressIgnoredLocal) continue;\n if (isOsMetadataFile(f) || isHiddenFile(f)) continue;\n result.ignoredLocalTotal++;\n const reason = classifyIgnoredFile(f);\n // Track per-reason totals over the FULL walk so the MCP\n // push summary's category breakdown stays honest when the\n // cap truncates the path slice (same rationale as the\n // getStatus walk above).\n result.ignoredLocalTotalByReason[reason]++;\n if (result.ignoredLocal.length < IGNORED_LOCAL_CAP) {\n result.ignoredLocal.push({ path: f, reason });\n }\n }\n\n const localContents = new Map<string, Buffer>();\n for (const file of inScopeFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n localContents.set(file, fs.readFileSync(fullPath));\n }\n\n // Pre-flight: refuse files the backend will refuse anyway. We do\n // this before any network call so the user sees a single grouped\n // verdict (\"3 file(s) skipped: extension not allowed, \u2026\") rather\n // than a half-finished push that errors mid-stream with an opaque\n // 400. Files that fail validation never reach the upload loop, but\n // they still count toward `result.rejected` so the caller can show\n // them to the user and exit non-zero.\n const validationInputs = inScopeFiles.map((filePath) => {\n const content = localContents.get(filePath)!;\n return {\n filePath,\n size: content.length,\n content,\n };\n });\n const { valid: pushableValidatedFiles, rejected } = partitionForUpload(validationInputs);\n result.rejected = rejected;\n // `localFiles` = files we'll consider for upload (in-scope, validated).\n const localFiles = pushableValidatedFiles.map((f) => f.filePath);\n\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n localHashes.set(localFile, calculateHash(localContents.get(localFile)!));\n }\n\n // Identify candidates that need remote content check for conflict detection.\n // Compare against syncInfo.remoteHash (not .localHash): a file is a\n // candidate whenever local diverges from what we last knew about remote,\n // which also covers keep_local / keep_both resolutions where localHash\n // matches baseline local but remoteHash points at the conflicting remote.\n //\n // Mirror exception: under `mirror: true` we treat EVERY locally-\n // present file that also exists on remote as a candidate, so we can\n // re-fetch the actual remote hash and detect content drift even on\n // files our baseline marks as \"in sync\". Without this, a user who\n // ran `push --force --mirror` after someone else edited a remote\n // file (with our recorded baseline still stale) would skip the\n // upload entirely and remote stays diverged.\n const candidateFiles: string[] = [];\n for (const localFile of localFiles) {\n const syncInfo = syncState.files[localFile];\n const localHash = localHashes.get(localFile)!;\n const baselineDiverged = !syncInfo || localHash !== syncInfo.remoteHash;\n if (!remoteFileMap.has(localFile)) continue;\n if (baselineDiverged || options?.mirror) {\n candidateFiles.push(localFile);\n }\n }\n // Also check files in sync state that no longer exist locally (local deletions).\n // Use `localPresenceSet` (not `localFiles`): rejected files DO exist\n // locally \u2014 they just can't be uploaded \u2014 so they must NOT count as\n // \"locally deleted\" and must NOT trigger remote deletion. Scope-filter\n // too: a `Data/foo.csv` previously synced under `--include-ext .csv`\n // shouldn't get deleted on a default push without the same flag \u2014\n // out-of-scope files are invisible this run. shouldIncludeFile\n // handles the --all gate plus the hidden-file gate together.\n const inScope = (f: string) => shouldIncludeFile(f, this.tenant, options);\n const locallyDeletedFiles = Object.keys(syncState.files).filter(\n (f) => !localPresenceSet.has(f) && remoteFileMap.has(f) && inScope(f),\n );\n const filesToFetchRemote = [...new Set([...candidateFiles, ...locallyDeletedFiles])];\n\n // Fetch remote content for conflict detection. We skip the fetch\n // under plain `force: true` (the user said 'overwrite, don't ask\n // questions') \u2014 but under `mirror: true` we DO need it: mirror\n // semantics rest on knowing the actual remote hash so we can decide\n // 'do we re-upload because remote drifted?'.\n //\n // Caller can pass `precomputedRemoteHashes` to skip the network\n // round-trip for entries already in hand (e.g. push.ts ran a deep\n // getStatus right before this and already paid for every fetch).\n // Files NOT in the map still get fetched here, so the fast-path\n // is safe with partial coverage.\n const remoteHashes = new Map<string, string>(options?.precomputedRemoteHashes ?? []);\n if (filesToFetchRemote.length > 0 && (!options?.force || options?.mirror)) {\n const toFetch = filesToFetchRemote\n .filter((f) => remoteFileMap.has(f) && !remoteHashes.has(f))\n .map((f) => remoteFileMap.get(f)!);\n\n if (toFetch.length > 0) {\n const fetched = await fetchWithConcurrency(\n toFetch,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n },\n 15,\n );\n\n for (const { file, hash } of fetched) {\n remoteHashes.set(file.path, hash);\n }\n }\n }\n\n // Three-way comparison for conflict detection\n const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });\n const conflictPaths = new Set<string>();\n\n if (!options?.force) {\n for (const c of comparisons) {\n if (c.changeType.startsWith('conflict_')) {\n const conflict = SyncService.buildConflicts([c])[0];\n result.conflicts.push(conflict);\n conflictPaths.add(c.filePath);\n }\n }\n }\n\n // Per-file try/catch around every backend call. A single 5xx (or\n // any other transient error) on file N must not lose progress on\n // files 1..N-1: we log into result.failed[], save syncState in the\n // outer `finally`, and let the user re-run. Without this, an\n // interrupted run would re-upload everything and risk creating\n // dupes for items the backend silently committed before failing.\n try {\n // Process non-conflicting files\n for (const localFile of localFiles) {\n if (conflictPaths.has(localFile)) continue;\n\n const content = localContents.get(localFile)!;\n const localHash = localHashes.get(localFile)!;\n\n const remoteFile = remoteFileMap.get(localFile);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFile) {\n // File exists on remote. Push when local diverges from what we\n // last recorded as the remote hash. Using remoteHash (not\n // localHash) means keep_local / keep_both conflict resolutions \u2014\n // where localHash gets updated to current local but remoteHash\n // still carries the conflicting remote hash \u2014 correctly trigger\n // an upload instead of being silently marked as unchanged.\n //\n // Mirror exception: under `mirror: true` the user explicitly\n // asked for \"remote == local\". Trusting our recorded\n // remoteHash here can mark the file unchanged even though\n // the real remote content drifted. Re-fetched currentRemoteHash\n // (when available \u2014 drift fetch step above runs even under\n // force/mirror for non-conflict candidates) lets us tell.\n // If we have a real remote hash and it matches local, skip\n // the upload (saves a roundtrip); otherwise overwrite.\n const currentRemoteHash = remoteHashes.get(localFile);\n const mirrorWantsRecreate =\n options?.mirror && currentRemoteHash !== undefined && currentRemoteHash !== localHash;\n if (syncInfo && localHash === syncInfo.remoteHash && !mirrorWantsRecreate) {\n result.unchanged.push(localFile);\n } else {\n // Drift check: before overwriting remote, make sure remote\n // still has the version we last recorded. If someone else\n // (or a still-pending background job) moved remote forward\n // since our baseline, and this isn't a forced push, refuse\n // to silently overwrite it. Without this, the keep_local\n // path can clobber a newer remote edit because the file's\n // changeType comes back as 'remote_modified' (not\n // conflict_*) and would otherwise sail through.\n // (currentRemoteHash already declared above for the\n // mirror-recreate check; reuse it here.)\n if (\n !options?.force &&\n syncInfo &&\n currentRemoteHash !== undefined &&\n currentRemoteHash !== syncInfo.remoteHash\n ) {\n result.conflicts.push({\n filePath: localFile,\n type: 'both_modified',\n description: 'Remote changed since last sync \u2014 pull first or use --force to overwrite',\n });\n continue;\n }\n try {\n await this.farseerClient.updateFile(\n remoteFile.reference,\n content,\n path.basename(localFile),\n );\n result.updated.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'update',\n reason: await formatClientError(err),\n });\n }\n }\n } else {\n // File doesn't exist on remote.\n //\n // Default push: respect the remote deletion (someone deleted\n // it via UI, we shouldn't undo their action just because\n // we still have the file locally and our baseline says it\n // used to be on remote). Mark unchanged.\n //\n // Mirror push (`mirror: true`): the user explicitly asked\n // for \"remote == local\". A local copy that's no longer on\n // remote means we need to RECREATE it on remote \u2014 falling\n // through to the upload branch below does that.\n if (syncInfo && localHash === syncInfo.remoteHash && !options?.mirror) {\n result.unchanged.push(localFile);\n } else {\n // New or modified local file - upload\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n try {\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'create',\n reason: await formatClientError(err),\n });\n }\n }\n }\n }\n\n // Delete files on remote that were deleted locally.\n //\n // Default: only delete files we previously pulled (`syncInfo` exists)\n // \u2014 that's how you express \"I just `rm`'d this file, please match\".\n // Mirror mode (`push --force` from the CLI surface): also delete\n // remote files that have no local counterpart at all, even if we\n // never pulled them. This is the \"make remote = local\" semantics\n // the CLI promises with --force, but it's destructive enough that\n // the command layer must confirm with the user before passing\n // `mirror: true`.\n // Honour the same `--include-ext` / `--include-folder` scope the\n // command layer used for the preview. Out-of-scope files are\n // invisible this run \u2014 even when syncState remembers them. Without\n // the gate on the syncInfo branch, a default `farseer push`\n // (no `--include-ext .csv`) after a previous `farseer push\n // --include-ext .csv` plus a local rm would silently nuke\n // Data/foo.csv on remote. Cross-scope side effects are exactly\n // what users don't expect from a default-flag run.\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (localPresenceSet.has(remotePath) || conflictPaths.has(remotePath)) continue;\n if (!inScope(remotePath)) continue;\n const syncInfo = syncState.files[remotePath];\n const shouldDelete = syncInfo ? true : Boolean(options?.mirror);\n if (!shouldDelete) continue;\n try {\n await this.farseerClient.deleteFile(remoteFile.reference);\n result.deleted.push(remotePath);\n delete syncState.files[remotePath];\n } catch (err) {\n result.failed.push({\n filePath: remotePath,\n operation: 'delete',\n reason: await formatClientError(err),\n });\n }\n }\n } finally {\n // Always persist progress, even on partial failure or if the\n // outer flow is cancelled with Ctrl-C between files. The next\n // run reads this state and skips items we already finished.\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n }\n\n return result;\n }\n\n /**\n * Detect whether the remote has files we haven't seen yet (or recorded\n * files no longer present on remote) within the current sync scope.\n *\n * Returns the set of paths that are causing drift so the command layer\n * can show the user exactly what's blocking the push and suggest a\n * matching `farseer pull` command. The previous boolean-only return\n * gave the user just \"Remote has changes\" with no clue WHICH file \u2014\n * and `farseer pull` (without the same `--include-ext`/`--include-folder`)\n * silently said \"Already up to date\" because it ran in a different\n * scope, leaving the user stuck in an infinite \"pull says clean, push\n * says drift\" loop.\n */\n async checkRemoteChanges(options?: SyncOptions): Promise<{\n drift: boolean;\n addedRemotely: string[];\n deletedRemotely: string[];\n }> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes to avoid false positives\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // We need local presence too: a syncState entry for a file that's\n // gone from BOTH local and remote is just stale baseline \u2014 neither\n // side can act on it, and flagging it as drift sends the user to a\n // pull that does nothing. Only count \"remote-deleted\" when local\n // still has the file (so the upcoming pull would clean it up).\n const filesDir = getTenantFilesDir(this.tenant);\n const localPresenceSet = new Set(getAllFilesInDir(filesDir));\n\n const addedRemotely: string[] = [];\n const deletedRemotely: string[] = [];\n\n // New files on remote that we don't have in sync state.\n for (const file of remoteFiles) {\n if (!syncState.files[file.path]) {\n addedRemotely.push(file.path);\n }\n }\n\n // Files deleted on remote that we have in sync state. Skip if local\n // is also missing (stale baseline \u2014 treat as already cleaned, the\n // next pull will drop it from syncState without any drift signal\n // confusing the user).\n const remotePaths = new Set(remoteFiles.map((f) => f.path));\n for (const filePath of Object.keys(syncState.files)) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) continue;\n if (remotePaths.has(filePath)) continue;\n if (!syncState.files[filePath].remoteHash) continue;\n if (!localPresenceSet.has(filePath)) continue;\n deletedRemotely.push(filePath);\n }\n\n // Note: we don't check for content changes here for performance.\n // After a pull, sync state is accurate. Content changes by others\n // between pull and push are surfaced through the per-file drift\n // check inside push() instead.\n return {\n drift: addedRemotely.length > 0 || deletedRemotely.length > 0,\n addedRemotely,\n deletedRemotely,\n };\n }\n\n async getFileDiff(filePath: string): Promise<{\n localContent: string | null;\n remoteContent: string | null;\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const localPath = safeResolveWithinBase(filesDir, filePath);\n\n let localContent: string | null = null;\n let remoteContent: string | null = null;\n\n if (fs.existsSync(localPath)) {\n // For diff, read as text (diff only makes sense for text files)\n localContent = fs.readFileSync(localPath, 'utf-8');\n }\n\n const remoteFile = await this.farseerClient.getFileByPath(filePath);\n if (remoteFile) {\n remoteContent = await this.farseerClient.getFileContent(remoteFile.reference);\n }\n\n return { localContent, remoteContent };\n }\n\n /**\n * Three-way comparison of all files.\n * Compares current local state, current remote state, and baseline from sync state.\n */\n compareFiles(options: {\n localHashes: Map<string, string>;\n remoteHashes: Map<string, string>;\n syncState: SyncState;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n // Pass-through for `--only`: shouldIncludeFile honours it ahead of\n // ext/folder rules, but only if it's actually in `options`. Without\n // this, push --only would build a status that ignores the whitelist\n // (compareFiles re-runs shouldIncludeFile with only the ext/folder\n // fields above) and a non-.ts/.js whitelisted path would be filtered\n // out as out-of-scope.\n onlyFiles?: string[];\n }): FileCompareResult[] {\n const { localHashes, remoteHashes, syncState } = options;\n\n // Union of all known file paths\n const allPaths = new Set<string>([\n ...localHashes.keys(),\n ...remoteHashes.keys(),\n ...Object.keys(syncState.files),\n ]);\n\n const results: FileCompareResult[] = [];\n\n for (const filePath of allPaths) {\n // Filter files based on includes\n if (!options.all) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) {\n continue;\n }\n }\n\n const currentLocalHash = localHashes.get(filePath) ?? null;\n const currentRemoteHash = remoteHashes.get(filePath) ?? null;\n const baseline = syncState.files[filePath];\n const baselineLocalHash = baseline?.localHash ?? null;\n const baselineRemoteHash = baseline?.remoteHash ?? null;\n\n const localExists = currentLocalHash !== null;\n const remoteExists = currentRemoteHash !== null;\n const hadBaseline = baseline != null;\n\n let changeType: FileChangeType;\n\n if (localExists && remoteExists) {\n // Both exist\n if (currentLocalHash === currentRemoteHash) {\n changeType = 'unchanged';\n } else if (!hadBaseline) {\n changeType = 'conflict_both_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n const baselineDivergent = baselineLocalHash !== baselineRemoteHash;\n\n if (localChanged && remoteChanged) {\n changeType = 'conflict_both_modified';\n } else if (localChanged) {\n changeType = 'local_modified';\n } else if (remoteChanged) {\n changeType = 'remote_modified';\n } else if (baselineDivergent) {\n // Post `keep_local` / `keep_both` resolution: nothing\n // changed since baseline, but baseline already recorded\n // local diverged from remote on purpose. The user\n // chose local; we still need to push so remote\n // catches up. Without this branch, status & push\n // would both fall through to \"unchanged\" and the\n // local edit would silently never reach remote.\n changeType = 'local_modified';\n } else {\n changeType = 'unchanged';\n }\n }\n } else if (localExists && !remoteExists) {\n // Only local exists\n if (!hadBaseline) {\n changeType = 'local_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n if (localChanged) {\n changeType = 'conflict_local_modified_remote_deleted';\n } else {\n changeType = 'remote_deleted';\n }\n }\n } else if (!localExists && remoteExists) {\n // Only remote exists\n if (!hadBaseline) {\n changeType = 'remote_new';\n } else {\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n if (remoteChanged) {\n changeType = 'conflict_local_deleted_remote_modified';\n } else {\n changeType = 'local_deleted';\n }\n }\n } else {\n // Neither exists - both deleted since baseline, clean up\n continue;\n }\n\n results.push({\n filePath,\n changeType,\n currentLocalHash,\n currentRemoteHash,\n baselineLocalHash,\n baselineRemoteHash,\n });\n }\n\n return results;\n }\n\n /**\n * Extract SyncConflict[] from FileCompareResult[].\n */\n static buildConflicts(comparisons: FileCompareResult[]): SyncConflict[] {\n const conflicts: SyncConflict[] = [];\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'conflict_both_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_modified',\n description: 'Both local and remote versions modified since last sync',\n });\n break;\n case 'conflict_local_modified_remote_deleted':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n break;\n case 'conflict_local_deleted_remote_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_deleted_remote_modified',\n description: 'File deleted locally but modified on remote',\n });\n break;\n case 'conflict_both_new':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_new',\n description: 'File exists both locally and remotely with different content (no sync baseline)',\n });\n break;\n }\n }\n return conflicts;\n }\n\n /**\n * Batch fetch metadata for multiple files in parallel.\n * Fetches metadata in batches of 10 to avoid overwhelming the API.\n * Non-critical operation - failures are silently ignored.\n */\n private async fetchMetadataForFiles(files: RemoteFile[]): Promise<RemoteFile[]> {\n const batchSize = 10;\n\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const metadata = await this.farseerClient.getFileMetadata(file.reference);\n if (metadata) {\n file.metadata = metadata;\n }\n } catch {\n // Silently ignore metadata fetch errors - non-critical\n }\n }),\n );\n }\n\n return files;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,4BAAsE;AACtE,2BAAgC;AAChC,qBAUO;AACP,oBAAuB;AACvB,4BAAwE;AACxE,4BAAkC;AAClC,2BAAkC;AAKlC,IAAAA,kBAA+C;AA+B/C,MAAM,2BAA2B,CAAC,gBAAgB,QAAQ,SAAS,oBAAoB,YAAY,aAAa;AAgCzG,SAAS,oBAAoB,UAAiC;AACjE,QAAM,WAAW,SAAS,MAAM,GAAG;AACnC,aAAW,OAAO,UAAU;AACxB,QAAI,yBAAyB,SAAS,GAAG,EAAG,QAAO;AAAA,EACvD;AACA,SAAO;AACX;AAiBO,SAAS,sBACZ,SACA,eAC4B;AAC5B,QAAM,YAAY,CAAC,MACf,EACK,MAAM,KAAK,GAAG,EACd,KAAK,GAAG,EACR,QAAQ,cAAc,EAAE;AACjC,QAAM,iBAAiB,CAAC,GAAI,SAAS,kBAAkB,CAAC,GAAI,GAAG,aAAa,EAAE;AAAA,IAAI,CAAC,MAC/E,EAAE,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG,EAAE,QAAQ,QAAQ,EAAE;AAAA,EAClD;AACA,QAAM,kBAAkB,SAAS,aAAa,CAAC,GAAG,IAAI,SAAS;AAC/D,SAAO,CAAC,YAAoB;AACxB,UAAM,QAAQ,QAAQ,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;AAC9C,QAAI,KAAC,6BAAa,KAAK,EAAG,QAAO;AACjC,eAAW,WAAW,gBA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YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,QACJ,KAAK;AACD,oBAAU,KAAK;AAAA,YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,MACR;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,sBAAsB,OAA4C;AAC5E,UAAM,YAAY;AAElB,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAC9C,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAE1C,YAAM,QAAQ;AAAA,QACV,MAAM,IAAI,OAAO,SAAS;AACtB,cAAI;AACA,kBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,gBAAI,UAAU;AACV,mBAAK,WAAW;AAAA,YACpB;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SYNC_EXTENSIONS } from './farseerFactory';\nimport { getSyncIncludes } from './configService';\nimport {\n calculateHash,\n getTenantFilesDir,\n getSyncFilePath,\n ensureDirectoryExists,\n getAllFilesInDir,\n fetchWithConcurrency,\n isHiddenFile,\n isOsMetadataFile,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { ValidationFailure, partitionForUpload, isLikelyTextFile } from '../utils/fileValidation';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { IGNORED_LOCAL_CAP } from '../utils/syncReporting';\n\n// Re-export so existing test imports (`from '../../src/services/syncService'`)\n// keep working \u2014 `isOsMetadataFile` moved to utils/helpers.ts so the file\n// listing helper can apply it as the default filter.\nexport { isOsMetadataFile, isHiddenFile } from '../utils/helpers';\n\nexport interface SyncOptions {\n all?: boolean;\n force?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n conflictResolutions?: ConflictResolutions;\n /**\n * Whitelist of file paths (relative to the tenant files dir).\n * When set, only listed paths participate in the sync \u2014 everything\n * else is treated as out-of-scope (not modified, not deleted, not\n * compared). Used by `farseer push --only` to push a single file\n * without touching unrelated drift in the working tree.\n */\n onlyFiles?: string[];\n}\n\n/**\n * Tooling-output folder names used to classify ignored files in the\n * warning. Match against ANY path segment: a file under\n * `Scripts/node_modules/` still flags as blocklisted-folder for the\n * purposes of the warning copy. This is a SUBSET of ANY_DEPTH_BLOCKLIST\n * below (the exclusion list) \u2014 the warning needs short, human-readable\n * names for the hint message.\n */\nconst IGNORED_FOLDER_BLOCKLIST = ['node_modules', 'dist', 'build', 'bower_components', 'coverage', '__pycache__'];\n\n/**\n * Reason a file was excluded from the active sync scope. Surfaced through\n * `SyncStatus.ignoredLocal` (and `push().ignoredLocal`) so the warning can\n * give a category-specific hint instead of a single generic line that\n * sometimes nudges users toward including `node_modules/`.\n *\n * Hidden files are NOT modelled here: they're excluded upstream from the\n * warning entirely (the warning suggests opt-in flags, and any opt-in\n * pointed at `.env` / `.git/` is a credential-leak vector). Add a category\n * here only when the consumer is allowed to advertise it.\n */\nexport type IgnoredReason = 'unsupportedExtension' | 'blocklistedFolder';\n\nexport interface IgnoredLocalEntry {\n path: string;\n reason: IgnoredReason;\n}\n\n/**\n * Classify why a non-hidden, non-OS-junk local file was rejected by\n * `shouldIncludeFile`. The two categories are mutually exclusive (we\n * pick the most specific reason \u2014 `blocklistedFolder` wins over\n * `unsupportedExtension` because a `node_modules/foo.json` is \"tooling\n * output\" first, \"wrong extension\" second).\n *\n * Caller must have already filtered hidden files and OS metadata. We\n * assert nothing about that here \u2014 it's the caller's job and folding\n * the check in would mask the security-sensitive exclusion behind a\n * generic classifier.\n */\nexport function classifyIgnoredFile(filePath: string): IgnoredReason {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (IGNORED_FOLDER_BLOCKLIST.includes(seg)) return 'blocklistedFolder';\n }\n return 'unsupportedExtension';\n}\n\n/**\n * Build a `shouldSkipDir` predicate for `getAllFilesInDir` that prunes\n * hidden subtrees the caller could not include anyway. This is the part\n * that actually bounds memory \u2014 without it a `.git/` or `.cache/` next\n * to the tenant `files/` folder still materialises every filename in\n * the walker before any filter runs.\n *\n * Returns true (skip) when the dir is hidden AND no include-folder\n * (from the per-command options or persistent config) nor `--only`\n * file path overlaps it. We keep the walk for any user-listed hidden\n * folder so `farseer config include --folder .vscode` continues to\n * work, and for hidden paths under `--only` so `farseer push --only\n * .vscode/settings.json` doesn't get pruned before the only-check\n * runs in `shouldIncludeFile`.\n */\nexport function buildHiddenDirSkipper(\n options: Pick<SyncOptions, 'includeFolders' | 'onlyFiles'> | undefined,\n configFolders: string[],\n): (relPath: string) => boolean {\n const normalize = (f: string) =>\n f\n .split(path.sep)\n .join('/')\n .replace(/^\\/+|\\/+$/g, '');\n const includeFolders = [...(options?.includeFolders ?? []), ...configFolders].map((f) =>\n f.split(path.sep).join('/').replace(/\\/+$/, ''),\n );\n const onlyFilesPosix = (options?.onlyFiles ?? []).map(normalize);\n return (relPath: string) => {\n const posix = relPath.split(path.sep).join('/');\n if (!isHiddenFile(posix)) return false;\n for (const include of includeFolders) {\n if (posix === include) return false;\n if (posix.startsWith(include + '/')) return false;\n if (include.startsWith(posix + '/')) return false;\n }\n for (const only of onlyFilesPosix) {\n if (only === posix) return false;\n if (only.startsWith(posix + '/')) return false;\n if (posix.startsWith(only + '/')) return false;\n }\n return true;\n };\n}\n\n/**\n * Folder names that are NEVER user-named \u2014 pure tooling output. We\n * blocklist them at ANY depth in the relative path because there is no\n * legitimate scenario where a user authors a folder called\n * `node_modules/` under a tenant. Even when nested under business\n * folders (`Scripts/node_modules/lodash.js`), these stay out by default.\n *\n * Keep this list tight: every entry here must be a name that universally\n * means \"package manager / build tool output\" \u2014 never a domain word the\n * user might reasonably pick (Reports/, Data/, etc.). The ambiguous\n * names (build/, vendor/, target/, \u2026) live in `ROOT_ONLY_BLOCKLIST`\n * instead so they only fire when the user has explicitly turned the\n * tenant into a dev workspace at the root.\n */\nconst ANY_DEPTH_BLOCKLIST = ['node_modules/', 'bower_components/', '__snapshots__/', '__pycache__/'];\n\n/**\n * Folder names that we skip ONLY when they appear as the TOP-LEVEL\n * segment of the relative path. These are conventionally tooling\n * output at the project root (`dist/`, `coverage/`, `build/`, \u2026) but\n * are also plausible business words the user might choose deeper in\n * the tree (`Data/vendor/contracts.csv`, `Reports/build/summary.md`,\n * `Exports/temp/output.csv`). Matching them as any-segment used to\n * silently drop legitimate user files \u2014 the exact UX bug expanding the\n * default scope set out to fix.\n *\n * The dotted variants (`.venv/`, `.terraform/`, \u2026) are also caught by\n * the hidden-file rule, but listed explicitly so the blocklist stays\n * the authoritative answer to \"which ecosystem dirs are skipped\"\n * instead of relying on the dotfile-incidence accident. Hidden-dir\n * paths short-circuit through `isHiddenFile` first, so these entries\n * are belt-and-braces.\n */\nconst ROOT_ONLY_BLOCKLIST = [\n // JS / Node \u2014 build output at project root\n 'dist/',\n 'build/',\n 'out/', // Next.js static export\n '.next/',\n '.cache/',\n '.turbo/',\n '.parcel-cache/',\n '.svelte-kit/',\n // Test coverage\n 'coverage/',\n // Python \u2014 venv, tool caches at project root\n 'venv/',\n '.venv/',\n '.pytest_cache/',\n '.mypy_cache/',\n '.tox/',\n // Go / Rust / JVM \u2014 vendored deps and build artefacts at project root\n 'vendor/',\n 'target/',\n '.gradle/',\n // IaC / cloud SDK caches\n '.terraform/',\n '.serverless/',\n '.aws-sam/',\n // IDE state\n '.idea/',\n // Scratch\n 'tmp/',\n 'temp/',\n];\n\nfunction isBlocklistedPath(filePath: string): boolean {\n // Any-depth match: `node_modules/` anywhere in the tree.\n if (ANY_DEPTH_BLOCKLIST.some((prefix) => filePath.startsWith(prefix) || filePath.includes('/' + prefix))) {\n return true;\n }\n // Root-only match: prefix must be the FIRST path segment. Nested\n // occurrences (`Data/vendor/x.csv`) pass through to the regular\n // include rules.\n return ROOT_ONLY_BLOCKLIST.some((prefix) => filePath.startsWith(prefix));\n}\n\n/**\n * Normalise a relative file path to POSIX form so segment matching\n * (`/` boundary anchors, top-level prefix checks, include-folder\n * prefixes) works on Windows. `path.relative` returns backslash\n * separators on Windows, which means a path like\n * `Scripts\\node_modules\\pkg\\index.js` would slip past every check\n * that anchors on `/`. Centralised here so every comparator\n * (`isBlocklistedPath`, include-folder/onlyFiles matching) sees the\n * same shape.\n */\nfunction toPosix(filePath: string): string {\n return filePath.replace(/\\\\/g, '/');\n}\n\n/**\n * Determines if a file should be included in sync operations.\n *\n * Exclusion rules (run before any include rule):\n * - OS metadata (.DS_Store, Thumbs.db, ._foo, \u2026) \u2014 never synced.\n * - Hidden files / folders (any path segment starting with `.` \u2014 e.g.\n * .env, .git/, .vscode/) \u2014 synced only when explicitly opted in via\n * an `--include-folder` (or persistent folder include) whose prefix\n * covers the hidden path. Extension-based includes (`--include-ext\n * .json` / persistent extension includes) and `--all` do NOT pull\n * hidden files into scope \u2014 that would let a generic \".json\"\n * broadening leak `.vscode/settings.json`, `.aws/credentials.json`,\n * etc. The folder-based opt-in is the single way to consent to\n * syncing a hidden directory.\n * - Blocklisted folders (node_modules/, dist/, \u2026) \u2014 opt-in via\n * `--include-folder` if you really want them.\n *\n * Inclusion rules (file must satisfy at least one):\n * 1. `--all` flag is passed (only for non-hidden, non-blocklisted files).\n * 2. Has an extension in DEFAULT_SYNC_EXTENSIONS \u2014 the backend's accepted\n * extension whitelist (everyday data / config / docs / images / etc.).\n * 3. Has an extension from inline includeExtensions option.\n * 4. Lives under a folder from inline includeFolders option.\n * 5. Has an extension from persistent syncIncludes config.\n * 6. Lives under a folder from persistent syncIncludes config.\n */\nexport function shouldIncludeFile(\n filePath: string,\n tenant: string,\n options?: Pick<SyncOptions, 'all' | 'includeExtensions' | 'includeFolders' | 'onlyFiles'>,\n): boolean {\n // Normalise path separators so the blocklist / include-folder / hidden-\n // file checks see the same shape on Windows (where `path.relative`\n // produces `\\`-separated paths) as on POSIX. Without this a path like\n // `Scripts\\node_modules\\pkg\\index.js` would slip past `node_modules/`.\n filePath = toPosix(filePath);\n\n // OS metadata is always excluded \u2014 `--all` should sync the user's work,\n // not their filesystem's bookkeeping.\n if (isOsMetadataFile(filePath)) return false;\n\n // `--only` is a hard whitelist: when set, anything not listed is\n // out of scope regardless of other include rules. We compare on\n // exact relative path; the caller normalises before passing.\n if (options?.onlyFiles && options.onlyFiles.length > 0) {\n return options.onlyFiles.includes(filePath);\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const persistent = getSyncIncludes(tenant);\n\n const folderMatches =\n (options?.includeFolders?.some((f) => filePath.startsWith(toPosix(f) + '/') || filePath === toPosix(f)) ??\n false) ||\n (persistent?.folders?.some((f) => filePath.startsWith(toPosix(f) + '/') || filePath === toPosix(f)) ?? false);\n\n // Hidden files (.env, .git/, .vscode/, \u2026) require a FOLDER-level\n // opt-in. Extension-based includes (`--include-ext .json`) are too\n // broad \u2014 following a \"include .json files\" hint would silently\n // pull `.vscode/settings.json` or `.aws/credentials.json` into the\n // push set. To sync a hidden file, the user names the hidden\n // directory explicitly: `--include-folder .vscode`. `--all` also\n // does not cover hidden paths for the same reason.\n if (isHiddenFile(filePath)) return folderMatches;\n\n const extensionMatches =\n (options?.includeExtensions?.includes(ext) ?? false) || (persistent?.extensions?.includes(ext) ?? false);\n const matchesIncludes = folderMatches || extensionMatches;\n\n // Build artefacts and package caches behave the same as hidden files:\n // opt-in only. A user with `node_modules/` under their workspace\n // almost certainly doesn't want it uploaded.\n if (isBlocklistedPath(filePath)) return matchesIncludes;\n\n if (options?.all) return true;\n if (DEFAULT_SYNC_EXTENSIONS.includes(ext)) return true;\n return matchesIncludes;\n}\n\nexport interface SyncFileInfo {\n localHash: string;\n remoteHash: string;\n metadata?: {\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n lastFetched?: string;\n };\n}\n\nexport interface SyncState {\n lastSync: string;\n files: Record<string, SyncFileInfo>;\n}\n\n/**\n * A single status snapshot produced by `getStatus()`. Both `farseer status`\n * (preview) and `farseer push` (preflight) use this shape so the user sees\n * the same buckets in both commands.\n *\n * The legacy two-bucket layout (`modifiedLocally` / `modifiedRemotely`)\n * silently lumped deletions in with edits, which was the single biggest\n * source of \"why does status say M for a file that's actually deleted?\"\n * confusion. This shape splits the six combinatoric outcomes into their\n * own buckets and keeps `modifiedLocally` / `modifiedRemotely` as\n * derived aliases for back-compat with code that still reads them.\n */\nexport interface SyncStatus {\n addedLocally: string[];\n modifiedLocally: string[];\n deletedLocally: string[];\n addedRemotely: string[];\n modifiedRemotely: string[];\n deletedRemotely: string[];\n inSync: string[];\n conflicts: SyncConflict[];\n /**\n * True when the status was computed without fetching remote file\n * content. In `deep: false` mode the comparator can detect adds /\n * deletes / *local* modifications, but cannot distinguish a\n * remote-modified file from an in-sync one because that requires\n * downloading and hashing the remote content. Treat this flag as\n * \"remote-edit detection skipped\" rather than \"everything checked\".\n */\n deepCompare: boolean;\n /**\n * Real remote-content hashes keyed by file path. Only populated when\n * `deep: true` ran (the listing-only fast mode never downloads bytes).\n * Exposed so a follow-up `push({ precomputedRemoteHashes })` can skip\n * its own re-download for files already covered here \u2014 under\n * `push --force --mirror` these two operations would otherwise both\n * fetch the same set of remote contents back-to-back.\n */\n remoteHashes?: Map<string, string>;\n /**\n * Local files we walked but excluded from comparison because\n * `shouldIncludeFile` rejected them under the current options. Used\n * by the CLI to warn the user when their work-in-progress files are\n * being silently skipped \u2014 the previous behaviour reported \"in sync\"\n * even when local edits lived in files outside the default\n * .ts/.js whitelist.\n *\n * Each entry carries a `reason` so the warning can group files by\n * cause and give a category-specific opt-in hint:\n * - `unsupportedExtension` \u2192 suggest `--include-ext <ext>`.\n * - `blocklistedFolder` \u2192 warn that opting in is unusual; the\n * folder is one users rarely want synced (node_modules/, dist/).\n *\n * Hidden files (`.env`, `.git/`, `.vscode/`) are NOT included here:\n * the consumer's job is to suggest opt-in flags, and pointing the\n * user at `--all` / `--include-ext` for `.env` is a credential\n * leak vector.\n *\n * Capped at `IGNORED_LOCAL_CAP` entries \u2014 a user that drops a sibling\n * repo into the synced folder shouldn't blow up memory or produce a\n * console wall. `ignoredLocalTotal` records the uncapped count so\n * UIs can still show the true number.\n */\n ignoredLocal: IgnoredLocalEntry[];\n /**\n * Uncapped count corresponding to `ignoredLocal`. When this exceeds\n * `ignoredLocal.length`, the slice was truncated to keep memory and\n * log output bounded.\n */\n ignoredLocalTotal: number;\n /**\n * Uncapped per-reason breakdown of `ignoredLocalTotal`. Tracked\n * during the same walk that builds `ignoredLocal`, so a consumer\n * rendering a category summary (\"250 outside scope: 230 with\n * unsupported extension, 20 in blocklisted folders\") gets honest\n * numbers even when the cap truncated the path slice. Counting the\n * stored slice would understate the breakdown whenever the cap\n * fires; that disagreement is what callers cannot reproduce from\n * `ignoredLocal` alone.\n */\n ignoredLocalTotalByReason: {\n unsupportedExtension: number;\n blocklistedFolder: number;\n };\n}\n\nexport interface GetStatusOptions extends SyncOptions {\n /**\n * When true, fetch and hash every remote file's content so we can\n * detect remote-side content edits made by other users. Slow on big\n * tenants. Default: false (list-only).\n */\n deep?: boolean;\n}\n\nfunction emptyStatus(deepCompare: boolean): SyncStatus {\n return {\n addedLocally: [],\n modifiedLocally: [],\n deletedLocally: [],\n addedRemotely: [],\n modifiedRemotely: [],\n deletedRemotely: [],\n inSync: [],\n conflicts: [],\n deepCompare,\n ignoredLocal: [],\n ignoredLocalTotal: 0,\n ignoredLocalTotalByReason: { unsupportedExtension: 0, blocklistedFolder: 0 },\n };\n}\n\n// Three-way comparison types\n\nexport type FileChangeType =\n | 'unchanged'\n | 'local_modified'\n | 'remote_modified'\n | 'remote_deleted'\n | 'local_deleted'\n | 'local_new'\n | 'remote_new'\n | 'conflict_both_modified'\n | 'conflict_local_modified_remote_deleted'\n | 'conflict_local_deleted_remote_modified'\n | 'conflict_both_new';\n\nexport interface FileCompareResult {\n filePath: string;\n changeType: FileChangeType;\n currentLocalHash: string | null;\n currentRemoteHash: string | null;\n baselineLocalHash: string | null;\n baselineRemoteHash: string | null;\n}\n\nexport interface SyncConflict {\n filePath: string;\n type: 'both_modified' | 'local_modified_remote_deleted' | 'local_deleted_remote_modified' | 'both_new';\n description: string;\n}\n\nexport interface PushFailure {\n filePath: string;\n operation: 'create' | 'update' | 'delete';\n reason: string;\n}\n\nexport type ConflictResolution = 'keep_local' | 'keep_remote' | 'keep_both' | 'merge_markers';\nexport type ConflictResolutions = Record<string, ConflictResolution>;\n\n/**\n * Markers we wrap a conflicted file with under the `merge_markers`\n * resolution \u2014 same convention as git so any IDE / editor picks them\n * up automatically and lets the user choose visually.\n *\n * The push pre-flight (utils/fileValidation.ts) refuses files that\n * still contain these markers \u2014 pushing an unresolved file would\n * upload broken syntax to the backend.\n */\nexport const MERGE_MARKER_LOCAL_START = '<<<<<<< LOCAL (your version)';\nexport const MERGE_MARKER_SEPARATOR = '=======';\nexport const MERGE_MARKER_REMOTE_END = '>>>>>>> REMOTE';\n\nexport class SyncService {\n private tenant: string;\n private farseerClient: IFarseerClient;\n\n constructor(tenant: string, farseerClient: IFarseerClient) {\n this.tenant = tenant;\n this.farseerClient = farseerClient;\n }\n\n loadSyncState(): SyncState {\n const syncFilePath = getSyncFilePath(this.tenant);\n\n if (!fs.existsSync(syncFilePath)) {\n return {\n lastSync: '',\n files: {},\n };\n }\n\n try {\n const content = fs.readFileSync(syncFilePath, 'utf-8');\n return JSON.parse(content) as SyncState;\n } catch {\n return {\n lastSync: '',\n files: {},\n };\n }\n }\n\n saveSyncState(state: SyncState): void {\n const syncFilePath = getSyncFilePath(this.tenant);\n ensureDirectoryExists(path.dirname(syncFilePath));\n fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), 'utf-8');\n }\n\n /**\n * Single status engine used by both `farseer status` and the push\n * preflight. By default (deep=false) we list remote files but don't\n * download their content \u2014 fast on big tenants and accurate for adds,\n * deletes, and *local* edits. Pass deep=true (or `farseer status --deep`)\n * to also detect remote-side edits, which requires hashing every remote\n * file.\n *\n * Output buckets are explicit (added/modified/deleted on each side) so\n * the user never sees \"M file.ts\" for a file that's actually deleted on\n * one side \u2014 a regular failure mode of the previous two-bucket layout.\n */\n async getStatus(options?: GetStatusOptions): Promise<SyncStatus> {\n const deep = options?.deep === true;\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // shouldIncludeFile must run on every entry, even under --all: it\n // gates hidden paths (`.env`, `.vscode/`, `.git/`) which only get\n // synced when the user explicitly lists them via --include-ext or\n // --include-folder. Without the call here, --all would pick up a\n // local `.env` and either unlink it on pull --force or upload it.\n //\n // Track entries we rejected so the CLI can warn the user; the\n // previous behaviour silently dropped non-whitelisted files and\n // reported \"in sync\" even when the user had pending work on disk.\n //\n // Hidden files (`.env`, `.git/*`, `.vscode/*`) are NEVER surfaced\n // here: the warning suggests `--all` / `--include-ext` as the fix,\n // and pointing the user at those flags for a credential file is a\n // credential-leak path. Hidden files stay invisible \u2014 users who\n // genuinely want to sync one do it via the explicit `farseer\n // config include` path, which has its own affordances.\n // Skip hidden directories at recursion time when the user hasn't\n // include-listed them. This is the memory-bound the cap on\n // `ignoredLocal` advertises \u2014 without it we still materialise every\n // path under `.git/` / `.cache/` / `.svelte-kit/` before any filter\n // runs. The skip is safe because:\n // - hidden files never appear in `ignoredLocal` anyway (security),\n // - the only way a hidden file enters scope is `--include-folder`\n // against the hidden prefix, in which case we keep walking.\n const includeFoldersFromConfig = getSyncIncludes(this.tenant)?.folders ?? [];\n const skipHiddenDir = buildHiddenDirSkipper(options, includeFoldersFromConfig);\n const allLocalFiles = getAllFilesInDir(filesDir, { shouldSkipDir: skipHiddenDir });\n const localFiles: string[] = [];\n const ignoredLocal: IgnoredLocalEntry[] = [];\n let ignoredLocalTotal = 0;\n const ignoredLocalTotalByReason = { unsupportedExtension: 0, blocklistedFolder: 0 };\n // `--only` is an intentional hard narrowing \u2014 the user explicitly\n // listed the file(s) they care about. Everything else on disk is\n // \"out of scope\" by construction, not \"accidentally skipped\", so\n // surfacing it as a warning is noise that suggests broadening\n // scope the user just rejected. Skip the bucket entirely under\n // --only and keep the totals at zero.\n const suppressIgnoredLocal = (options?.onlyFiles?.length ?? 0) > 0;\n for (const f of allLocalFiles) {\n if (shouldIncludeFile(f, this.tenant, options)) {\n localFiles.push(f);\n continue;\n }\n // OS junk and hidden files are excluded silently. Hidden files\n // in particular MUST NOT be advertised in the warning \u2014 that\n // would tell users to widen scope to include `.env`.\n if (isOsMetadataFile(f) || isHiddenFile(f)) continue;\n if (suppressIgnoredLocal) continue;\n ignoredLocalTotal++;\n const reason = classifyIgnoredFile(f);\n // Track per-reason totals over the FULL walk, not just the\n // capped slice. The MCP summary renders \"X with unsupported\n // extension, Y in blocklisted folders\" \u2014 counting the stored\n // paths would understate both buckets whenever the cap fires\n // (e.g. 250 ignored files \u2192 summary reads `100 with \u2026` and\n // the user thinks they're looking at the real number).\n ignoredLocalTotalByReason[reason]++;\n // Cap the in-memory preview list. The totals above remain\n // exact; this only bounds how many paths we KEEP for the\n // warning render. Combined with the hidden-dir pruning in\n // `shouldSkipDir` above, this gives the walker a memory\n // ceiling for the common large-tree shapes (`.git/`,\n // `.cache/`, `.svelte-kit/`). A `node_modules/` planted in\n // the tenant files dir is NOT pruned at recursion time \u2014\n // that would change the semantics of the current default\n // scope \u2014 so the cap is the last line of defence there.\n if (ignoredLocal.length < IGNORED_LOCAL_CAP) {\n ignoredLocal.push({ path: f, reason });\n }\n }\n\n const localHashes = new Map<string, string>();\n for (const file of localFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localHashes.set(file, calculateHash(content));\n }\n\n const remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n const remoteHashes = new Map<string, string>();\n if (deep) {\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { path: file.path, hash: calculateHash(content) };\n },\n 15,\n );\n for (const { path: filePath, hash } of fileContents) {\n remoteHashes.set(filePath, hash);\n }\n } else {\n // Fast mode: we never download remote content. The comparator\n // needs *some* hash, so we pick the value that makes its three-\n // way logic produce the \"trust syncState\" answer:\n //\n // \u2022 If we have a baseline remote hash, reuse it. This makes\n // `remoteChanged` always false in fast mode \u2014 the explicit\n // trade-off (we miss someone else's edits between pull and\n // push), surfaced via `status.deepCompare = false`.\n // \u2022 If there is no baseline but the file exists locally, use\n // the local hash. Without this, \"first-time both-sides\n // exist\" (fresh clone, no .farseer-sync.json) flips to\n // `conflict_both_new` even though the most likely truth is\n // \"this file is fine, we just lost the baseline\". `pull`\n // and `push` correctly re-validate before doing anything\n // destructive, so an over-optimistic preview here is safe.\n // \u2022 Otherwise emit a path-unique sentinel so the comparator\n // classifies this as `remote_new` (added remotely).\n for (const file of remoteFiles) {\n const baseline = syncState.files[file.path]?.remoteHash;\n if (baseline) {\n remoteHashes.set(file.path, baseline);\n continue;\n }\n const localHash = localHashes.get(file.path);\n if (localHash) {\n remoteHashes.set(file.path, localHash);\n continue;\n }\n remoteHashes.set(file.path, `__remote_present__:${file.path}`);\n }\n }\n\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n onlyFiles: options?.onlyFiles,\n });\n\n const status = emptyStatus(deep);\n status.ignoredLocal = ignoredLocal;\n status.ignoredLocalTotal = ignoredLocalTotal;\n status.ignoredLocalTotalByReason = ignoredLocalTotalByReason;\n if (deep) {\n // Hand back the just-computed deep map so callers (e.g. push.ts\n // running a deep status before a mirror push) can pass it into\n // service.push() and avoid re-downloading every file body.\n status.remoteHashes = remoteHashes;\n }\n\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'unchanged':\n status.inSync.push(c.filePath);\n break;\n case 'local_modified':\n status.modifiedLocally.push(c.filePath);\n break;\n case 'remote_modified':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_new':\n status.addedLocally.push(c.filePath);\n break;\n case 'remote_new':\n status.addedRemotely.push(c.filePath);\n break;\n case 'remote_deleted':\n status.deletedRemotely.push(c.filePath);\n break;\n case 'local_deleted':\n status.deletedLocally.push(c.filePath);\n break;\n default:\n status.conflicts.push(SyncService.buildConflicts([c])[0]);\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: SyncOptions): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n conflictFilesWritten: string[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n ensureDirectoryExists(filesDir);\n\n const syncState = this.loadSyncState();\n // shouldIncludeFile must run even under --all so the hidden-file\n // gate (`.env`, `.vscode/`, `.git/`) stays in effect \u2014 these only\n // sync when explicitly listed in --include-ext / --include-folder.\n let remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // Batch fetch metadata for all files\n remoteFiles = await this.fetchMetadataForFiles(remoteFiles);\n\n const result = {\n downloaded: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n conflictFilesWritten: [] as string[],\n };\n\n // Download file contents in parallel with concurrency limit\n logger.dim(`Fetching ${remoteFiles.length} files in parallel...`);\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file, index) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n // Show progress every 10 files\n if ((index + 1) % 10 === 0 || index === remoteFiles.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteFiles.length} files`);\n }\n return { file, content };\n },\n 15,\n );\n // Clear progress line\n if (remoteFiles.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n // Build remote content map with hashes\n const remoteContentMap = new Map<string, { file: RemoteFile; content: Buffer; hash: string }>();\n const remoteHashes = new Map<string, string>();\n for (const { file, content } of fileContents) {\n const hash = calculateHash(content);\n remoteContentMap.set(file.path, { file, content, hash });\n remoteHashes.set(file.path, hash);\n }\n\n // Build local hashes. shouldIncludeFile runs on every entry so the\n // hidden-file gate stays in effect even under --all.\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n if (!shouldIncludeFile(localFile, this.tenant, options)) {\n continue;\n }\n const localPath = safeResolveWithinBase(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n onlyFiles: options?.onlyFiles,\n });\n const resolutions = options?.conflictResolutions ?? {};\n\n for (const comparison of comparisons) {\n const { filePath, changeType } = comparison;\n const localPath = safeResolveWithinBase(filesDir, filePath);\n const remoteInfo = remoteContentMap.get(filePath);\n\n switch (changeType) {\n case 'unchanged':\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_modified':\n case 'local_new':\n if (options?.force && remoteInfo) {\n // --force on pull means \"make local match remote\".\n // Without this branch, local_modified silently went\n // into `unchanged` and the user's edit survived a\n // hard-reset \u2014 the opposite of what --force promises.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_deleted':\n if (options?.force && remoteInfo) {\n // Force: restore the file the user removed locally.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n break;\n\n case 'remote_modified':\n case 'remote_new':\n // Safe to write\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo!.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo!.hash,\n remoteHash: remoteInfo!.hash,\n metadata: this.buildMetadata(remoteInfo!.file),\n };\n break;\n\n case 'remote_deleted':\n // Safe to delete (local is unchanged)\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n }\n result.deleted.push(filePath);\n delete syncState.files[filePath];\n break;\n\n case 'conflict_both_modified':\n case 'conflict_local_modified_remote_deleted':\n case 'conflict_local_deleted_remote_modified':\n case 'conflict_both_new': {\n if (options?.force) {\n // Force: apply remote state\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted, force means delete local\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n }\n\n const resolution = resolutions[filePath];\n if (!resolution) {\n // No resolution provided - report conflict, skip file\n result.conflicts.push(SyncService.buildConflicts([comparison])[0]);\n break;\n }\n\n switch (resolution) {\n case 'keep_local':\n // Keep local as-is, update sync state to mark conflict resolved\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n } else {\n // Local was deleted, user wants to keep that decision\n delete syncState.files[filePath];\n }\n result.unchanged.push(filePath);\n break;\n\n case 'keep_remote':\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n\n case 'keep_both':\n if (remoteInfo) {\n // Write remote version as .remote file alongside local\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteInfo.content);\n result.conflictFilesWritten.push(conflictFileName);\n }\n // Keep local, update sync state\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n }\n result.unchanged.push(filePath);\n break;\n\n case 'merge_markers':\n // git-style inline merge. Wrap LOCAL and REMOTE\n // versions with markers so any editor / IDE\n // highlights them. After the user resolves the\n // file (manually picks the version they want and\n // strips the markers), a regular `farseer push`\n // uploads the cleaned-up content. The push\n // pre-flight refuses any file that still has\n // markers in it, so an accidentally-unfinished\n // resolve never reaches the backend as broken\n // syntax.\n if (remoteInfo && fs.existsSync(localPath)) {\n const localBuf = fs.readFileSync(localPath);\n const remoteBuf = remoteInfo.content;\n\n // Binary safety gate. Splicing UTF-8 markers\n // into a .png/.xlsx/.zip would corrupt it\n // (the toString('utf-8') round-trip flips\n // bytes). Fall back to keep_both \u2014 write\n // remote alongside local as <name>.remote.<ext>\n // and let the user diff with their tool of\n // choice. Without this gate the user's binary\n // got silently overwritten with garbage.\n if (!isLikelyTextFile(filePath, localBuf) || !isLikelyTextFile(filePath, remoteBuf)) {\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteBuf);\n const localHash = calculateHash(localBuf);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(\n `${conflictFileName} (binary \u2014 merge markers not safe; wrote .remote alongside)`,\n );\n result.unchanged.push(filePath);\n break;\n }\n\n const localContent = localBuf.toString('utf-8');\n const remoteContent = remoteBuf.toString('utf-8');\n const merged =\n `${MERGE_MARKER_LOCAL_START}\\n${localContent}` +\n `${localContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_SEPARATOR}\\n${remoteContent}` +\n `${remoteContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_REMOTE_END}\\n`;\n fs.writeFileSync(localPath, merged);\n // Update syncState so push sees this as\n // \"locally modified\" (localHash differs from\n // remoteHash). User pushes cleaned-up file\n // after manually resolving.\n const newHash = calculateHash(Buffer.from(merged));\n syncState.files[filePath] = {\n localHash: newHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(`${filePath} (merge markers)`);\n } else if (!remoteInfo && fs.existsSync(localPath)) {\n // Remote is gone \u2014 fall back to keep_local.\n // No useful merge for \"your version vs nothing\".\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = { localHash, remoteHash: '' };\n }\n result.unchanged.push(filePath);\n break;\n }\n break;\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n private buildMetadata(file: RemoteFile): SyncFileInfo['metadata'] {\n if (!file.metadata) return undefined;\n return {\n uploadTime: file.metadata.uploadTime,\n uploaderEmail: file.metadata.uploader?.email,\n uploaderName: file.metadata.uploader\n ? `${file.metadata.uploader.firstName} ${file.metadata.uploader.lastName}`.trim()\n : undefined,\n lastFetched: new Date().toISOString(),\n };\n }\n\n async push(options?: {\n force?: boolean;\n mirror?: boolean;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n /**\n * Hard whitelist (relative paths). When set, only these files are\n * considered for upload / delete. Mirrors the CLI's `--only` flag.\n * Forwarded from push.ts so the surgical-push path stays scoped\n * inside service.push too \u2014 without this, push() would walk every\n * eligible file and the `--only` semantic only applied at the\n * preview stage.\n */\n onlyFiles?: string[];\n /**\n * Pre-fetched remote-content hashes keyed by file path. Optional\n * optimisation for callers (push.ts) that already ran a deep\n * status \u2014 that pass already downloaded every remote file's body,\n * so we can skip the second remote fetch here when the entries\n * cover everything we'd otherwise refetch. Missing keys still\n * trigger a fetch as before, so it's safe to pass a partial map.\n */\n precomputedRemoteHashes?: Map<string, string>;\n }): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n rejected: ValidationFailure[];\n failed: PushFailure[];\n /**\n * Same shape as `SyncStatus.ignoredLocal` \u2014 non-hidden, non-OS-junk\n * local files that didn't survive `shouldIncludeFile` under the\n * current options. Surfaced from push() so callers without a\n * separate status preflight (notably the MCP push handler) can\n * still warn the user that work-in-progress files were silently\n * outside the active scope. Hidden files are NEVER included here:\n * advertising `--all` / `--include-ext` for a credential file is a\n * leak vector.\n *\n * Each entry carries a `reason` (unsupportedExtension /\n * blocklistedFolder) so the consumer can give category-specific\n * advice \u2014 broaden by extension vs warn about opting in to a\n * tooling folder.\n *\n * Suppressed when `onlyFiles` is set \u2014 under `--only` the user\n * intentionally narrowed scope, so \"the other files exist but\n * weren't touched\" isn't a warning.\n */\n ignoredLocal: IgnoredLocalEntry[];\n /** Uncapped count for `ignoredLocal`; matches the `SyncStatus` shape. */\n ignoredLocalTotal: number;\n /**\n * Uncapped per-reason breakdown of `ignoredLocalTotal`. Same\n * rationale as `SyncStatus.ignoredLocalTotalByReason` \u2014 the\n * MCP push summary renders these so consumers see honest\n * category counts when the cap truncated the path slice.\n */\n ignoredLocalTotalByReason: {\n unsupportedExtension: number;\n blocklistedFolder: number;\n };\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const syncState = this.loadSyncState();\n\n const result = {\n uploaded: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n rejected: [] as ValidationFailure[],\n // Per-file failures from create/update/delete API calls. We don't\n // abort the whole push on the first failure \u2014 each item is its\n // own atomic operation, and `syncState` is saved in `finally` so\n // already-successful items aren't re-uploaded next run. The\n // caller surfaces this list and exits non-zero on non-empty.\n failed: [] as PushFailure[],\n ignoredLocal: [] as IgnoredLocalEntry[],\n ignoredLocalTotal: 0,\n ignoredLocalTotalByReason: { unsupportedExtension: 0, blocklistedFolder: 0 },\n };\n\n // Get current remote files (just the list, not content). Filter out\n // OS metadata defensively in case anyone ever pushed one before.\n const remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !isOsMetadataFile(f.path));\n const remoteFileMap = new Map<string, RemoteFile>();\n for (const file of remoteFiles) {\n remoteFileMap.set(file.path, file);\n }\n\n // OS metadata is stripped at the helper level (getAllFilesInDir),\n // so we never try to upload the user's filesystem bookkeeping \u2014\n // backend rejects those filenames and the user can't reasonably\n // remove them from the working tree.\n //\n // Mirror the hidden-dir pruning from getStatus: prune hidden\n // subtrees at recursion time when the user hasn't include-listed\n // them. CLI push covers this via the status preflight, but MCP\n // `farseer_push` calls service.push() directly \u2014 without the\n // skipper here, the walk materialises every path under `.git/`\n // / `.cache/` / `.svelte-kit/` before any filter runs.\n const includeFoldersFromConfig = getSyncIncludes(this.tenant)?.folders ?? [];\n const skipHiddenDir = buildHiddenDirSkipper(options, includeFoldersFromConfig);\n const allLocalFiles = getAllFilesInDir(filesDir, { shouldSkipDir: skipHiddenDir });\n\n // Apply the user's declared sync scope BEFORE we treat anything as\n // an upload candidate. Without this filter, push iterates every\n // file the disk listing returned and any whitelisted-extension\n // bystander gets shipped to remote \u2014 e.g. a `.vscode/settings.json`\n // sitting next to scripts passes pre-flight (`.json` is on the\n // backend whitelist) and is silently uploaded under a default\n // `farseer push`. The status preview already filters by\n // `shouldIncludeFile`, so the user wouldn't even see it coming.\n // Pin the same scope here.\n //\n // `localPresenceSet` keeps the FULL on-disk listing, separately,\n // so the delete loop's \"is this file actually missing locally?\"\n // protection still works for any file the user has \u2014 including\n // out-of-scope ones we won't touch.\n const localPresenceSet = new Set(allLocalFiles);\n // Always route through shouldIncludeFile \u2014 under --all the function\n // returns true for non-hidden files under --all but still gates\n // hidden ones (.env, .vscode/, .git/) so they require explicit\n // --include-folder opt-in.\n const inScopeFiles: string[] = [];\n // Same out-of-scope bookkeeping as getStatus \u2014 collected here so\n // MCP push (which calls service.push() directly, without a\n // separate getStatus preflight) can still surface the silent-skip\n // signal to its agent caller. Hidden files / OS metadata stay\n // invisible for the same security reason as getStatus.\n //\n // Under `--only` the user intentionally narrowed scope, so\n // everything outside that whitelist is \"explicitly excluded\",\n // not \"accidentally outside scope\" \u2014 suppress the bucket.\n const suppressIgnoredLocal = (options?.onlyFiles?.length ?? 0) > 0;\n for (const f of allLocalFiles) {\n if (shouldIncludeFile(f, this.tenant, options)) {\n inScopeFiles.push(f);\n continue;\n }\n if (suppressIgnoredLocal) continue;\n if (isOsMetadataFile(f) || isHiddenFile(f)) continue;\n result.ignoredLocalTotal++;\n const reason = classifyIgnoredFile(f);\n // Track per-reason totals over the FULL walk so the MCP\n // push summary's category breakdown stays honest when the\n // cap truncates the path slice (same rationale as the\n // getStatus walk above).\n result.ignoredLocalTotalByReason[reason]++;\n if (result.ignoredLocal.length < IGNORED_LOCAL_CAP) {\n result.ignoredLocal.push({ path: f, reason });\n }\n }\n\n const localContents = new Map<string, Buffer>();\n for (const file of inScopeFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n localContents.set(file, fs.readFileSync(fullPath));\n }\n\n // Pre-flight: refuse files the backend will refuse anyway. We do\n // this before any network call so the user sees a single grouped\n // verdict (\"3 file(s) skipped: extension not allowed, \u2026\") rather\n // than a half-finished push that errors mid-stream with an opaque\n // 400. Files that fail validation never reach the upload loop, but\n // they still count toward `result.rejected` so the caller can show\n // them to the user and exit non-zero.\n const validationInputs = inScopeFiles.map((filePath) => {\n const content = localContents.get(filePath)!;\n return {\n filePath,\n size: content.length,\n content,\n };\n });\n const { valid: pushableValidatedFiles, rejected } = partitionForUpload(validationInputs);\n result.rejected = rejected;\n // `localFiles` = files we'll consider for upload (in-scope, validated).\n const localFiles = pushableValidatedFiles.map((f) => f.filePath);\n\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n localHashes.set(localFile, calculateHash(localContents.get(localFile)!));\n }\n\n // Identify candidates that need remote content check for conflict detection.\n // Compare against syncInfo.remoteHash (not .localHash): a file is a\n // candidate whenever local diverges from what we last knew about remote,\n // which also covers keep_local / keep_both resolutions where localHash\n // matches baseline local but remoteHash points at the conflicting remote.\n //\n // Mirror exception: under `mirror: true` we treat EVERY locally-\n // present file that also exists on remote as a candidate, so we can\n // re-fetch the actual remote hash and detect content drift even on\n // files our baseline marks as \"in sync\". Without this, a user who\n // ran `push --force --mirror` after someone else edited a remote\n // file (with our recorded baseline still stale) would skip the\n // upload entirely and remote stays diverged.\n const candidateFiles: string[] = [];\n for (const localFile of localFiles) {\n const syncInfo = syncState.files[localFile];\n const localHash = localHashes.get(localFile)!;\n const baselineDiverged = !syncInfo || localHash !== syncInfo.remoteHash;\n if (!remoteFileMap.has(localFile)) continue;\n if (baselineDiverged || options?.mirror) {\n candidateFiles.push(localFile);\n }\n }\n // Also check files in sync state that no longer exist locally (local deletions).\n // Use `localPresenceSet` (not `localFiles`): rejected files DO exist\n // locally \u2014 they just can't be uploaded \u2014 so they must NOT count as\n // \"locally deleted\" and must NOT trigger remote deletion. Scope-filter\n // too: a `Data/foo.csv` previously synced under `--include-ext .csv`\n // shouldn't get deleted on a default push without the same flag \u2014\n // out-of-scope files are invisible this run. shouldIncludeFile\n // handles the --all gate plus the hidden-file gate together.\n const inScope = (f: string) => shouldIncludeFile(f, this.tenant, options);\n const locallyDeletedFiles = Object.keys(syncState.files).filter(\n (f) => !localPresenceSet.has(f) && remoteFileMap.has(f) && inScope(f),\n );\n const filesToFetchRemote = [...new Set([...candidateFiles, ...locallyDeletedFiles])];\n\n // Fetch remote content for conflict detection. We skip the fetch\n // under plain `force: true` (the user said 'overwrite, don't ask\n // questions') \u2014 but under `mirror: true` we DO need it: mirror\n // semantics rest on knowing the actual remote hash so we can decide\n // 'do we re-upload because remote drifted?'.\n //\n // Caller can pass `precomputedRemoteHashes` to skip the network\n // round-trip for entries already in hand (e.g. push.ts ran a deep\n // getStatus right before this and already paid for every fetch).\n // Files NOT in the map still get fetched here, so the fast-path\n // is safe with partial coverage.\n const remoteHashes = new Map<string, string>(options?.precomputedRemoteHashes ?? []);\n if (filesToFetchRemote.length > 0 && (!options?.force || options?.mirror)) {\n const toFetch = filesToFetchRemote\n .filter((f) => remoteFileMap.has(f) && !remoteHashes.has(f))\n .map((f) => remoteFileMap.get(f)!);\n\n if (toFetch.length > 0) {\n const fetched = await fetchWithConcurrency(\n toFetch,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n },\n 15,\n );\n\n for (const { file, hash } of fetched) {\n remoteHashes.set(file.path, hash);\n }\n }\n }\n\n // Three-way comparison for conflict detection\n const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });\n const conflictPaths = new Set<string>();\n\n if (!options?.force) {\n for (const c of comparisons) {\n if (c.changeType.startsWith('conflict_')) {\n const conflict = SyncService.buildConflicts([c])[0];\n result.conflicts.push(conflict);\n conflictPaths.add(c.filePath);\n }\n }\n }\n\n // Per-file try/catch around every backend call. A single 5xx (or\n // any other transient error) on file N must not lose progress on\n // files 1..N-1: we log into result.failed[], save syncState in the\n // outer `finally`, and let the user re-run. Without this, an\n // interrupted run would re-upload everything and risk creating\n // dupes for items the backend silently committed before failing.\n try {\n // Process non-conflicting files\n for (const localFile of localFiles) {\n if (conflictPaths.has(localFile)) continue;\n\n const content = localContents.get(localFile)!;\n const localHash = localHashes.get(localFile)!;\n\n const remoteFile = remoteFileMap.get(localFile);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFile) {\n // File exists on remote. Push when local diverges from what we\n // last recorded as the remote hash. Using remoteHash (not\n // localHash) means keep_local / keep_both conflict resolutions \u2014\n // where localHash gets updated to current local but remoteHash\n // still carries the conflicting remote hash \u2014 correctly trigger\n // an upload instead of being silently marked as unchanged.\n //\n // Mirror exception: under `mirror: true` the user explicitly\n // asked for \"remote == local\". Trusting our recorded\n // remoteHash here can mark the file unchanged even though\n // the real remote content drifted. Re-fetched currentRemoteHash\n // (when available \u2014 drift fetch step above runs even under\n // force/mirror for non-conflict candidates) lets us tell.\n // If we have a real remote hash and it matches local, skip\n // the upload (saves a roundtrip); otherwise overwrite.\n const currentRemoteHash = remoteHashes.get(localFile);\n const mirrorWantsRecreate =\n options?.mirror && currentRemoteHash !== undefined && currentRemoteHash !== localHash;\n if (syncInfo && localHash === syncInfo.remoteHash && !mirrorWantsRecreate) {\n result.unchanged.push(localFile);\n } else {\n // Drift check: before overwriting remote, make sure remote\n // still has the version we last recorded. If someone else\n // (or a still-pending background job) moved remote forward\n // since our baseline, and this isn't a forced push, refuse\n // to silently overwrite it. Without this, the keep_local\n // path can clobber a newer remote edit because the file's\n // changeType comes back as 'remote_modified' (not\n // conflict_*) and would otherwise sail through.\n // (currentRemoteHash already declared above for the\n // mirror-recreate check; reuse it here.)\n if (\n !options?.force &&\n syncInfo &&\n currentRemoteHash !== undefined &&\n currentRemoteHash !== syncInfo.remoteHash\n ) {\n result.conflicts.push({\n filePath: localFile,\n type: 'both_modified',\n description: 'Remote changed since last sync \u2014 pull first or use --force to overwrite',\n });\n continue;\n }\n try {\n await this.farseerClient.updateFile(\n remoteFile.reference,\n content,\n path.basename(localFile),\n );\n result.updated.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'update',\n reason: await formatClientError(err),\n });\n }\n }\n } else {\n // File doesn't exist on remote.\n //\n // Default push: respect the remote deletion (someone deleted\n // it via UI, we shouldn't undo their action just because\n // we still have the file locally and our baseline says it\n // used to be on remote). Mark unchanged.\n //\n // Mirror push (`mirror: true`): the user explicitly asked\n // for \"remote == local\". A local copy that's no longer on\n // remote means we need to RECREATE it on remote \u2014 falling\n // through to the upload branch below does that.\n if (syncInfo && localHash === syncInfo.remoteHash && !options?.mirror) {\n result.unchanged.push(localFile);\n } else {\n // New or modified local file - upload\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n try {\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'create',\n reason: await formatClientError(err),\n });\n }\n }\n }\n }\n\n // Delete files on remote that were deleted locally.\n //\n // Default: only delete files we previously pulled (`syncInfo` exists)\n // \u2014 that's how you express \"I just `rm`'d this file, please match\".\n // Mirror mode (`push --force` from the CLI surface): also delete\n // remote files that have no local counterpart at all, even if we\n // never pulled them. This is the \"make remote = local\" semantics\n // the CLI promises with --force, but it's destructive enough that\n // the command layer must confirm with the user before passing\n // `mirror: true`.\n // Honour the same `--include-ext` / `--include-folder` scope the\n // command layer used for the preview. Out-of-scope files are\n // invisible this run \u2014 even when syncState remembers them. Without\n // the gate on the syncInfo branch, a default `farseer push`\n // (no `--include-ext .csv`) after a previous `farseer push\n // --include-ext .csv` plus a local rm would silently nuke\n // Data/foo.csv on remote. Cross-scope side effects are exactly\n // what users don't expect from a default-flag run.\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (localPresenceSet.has(remotePath) || conflictPaths.has(remotePath)) continue;\n if (!inScope(remotePath)) continue;\n const syncInfo = syncState.files[remotePath];\n const shouldDelete = syncInfo ? true : Boolean(options?.mirror);\n if (!shouldDelete) continue;\n try {\n await this.farseerClient.deleteFile(remoteFile.reference);\n result.deleted.push(remotePath);\n delete syncState.files[remotePath];\n } catch (err) {\n result.failed.push({\n filePath: remotePath,\n operation: 'delete',\n reason: await formatClientError(err),\n });\n }\n }\n } finally {\n // Always persist progress, even on partial failure or if the\n // outer flow is cancelled with Ctrl-C between files. The next\n // run reads this state and skips items we already finished.\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n }\n\n return result;\n }\n\n /**\n * Detect whether the remote has files we haven't seen yet (or recorded\n * files no longer present on remote) within the current sync scope.\n *\n * Returns the set of paths that are causing drift so the command layer\n * can show the user exactly what's blocking the push and suggest a\n * matching `farseer pull` command. The previous boolean-only return\n * gave the user just \"Remote has changes\" with no clue WHICH file \u2014\n * and `farseer pull` (without the same `--include-ext`/`--include-folder`)\n * silently said \"Already up to date\" because it ran in a different\n * scope, leaving the user stuck in an infinite \"pull says clean, push\n * says drift\" loop.\n */\n async checkRemoteChanges(options?: SyncOptions): Promise<{\n drift: boolean;\n addedRemotely: string[];\n deletedRemotely: string[];\n }> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes to avoid false positives\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // We need local presence too: a syncState entry for a file that's\n // gone from BOTH local and remote is just stale baseline \u2014 neither\n // side can act on it, and flagging it as drift sends the user to a\n // pull that does nothing. Only count \"remote-deleted\" when local\n // still has the file (so the upcoming pull would clean it up).\n const filesDir = getTenantFilesDir(this.tenant);\n const localPresenceSet = new Set(getAllFilesInDir(filesDir));\n\n const addedRemotely: string[] = [];\n const deletedRemotely: string[] = [];\n\n // New files on remote that we don't have in sync state.\n for (const file of remoteFiles) {\n if (!syncState.files[file.path]) {\n addedRemotely.push(file.path);\n }\n }\n\n // Files deleted on remote that we have in sync state. Skip if local\n // is also missing (stale baseline \u2014 treat as already cleaned, the\n // next pull will drop it from syncState without any drift signal\n // confusing the user).\n const remotePaths = new Set(remoteFiles.map((f) => f.path));\n for (const filePath of Object.keys(syncState.files)) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) continue;\n if (remotePaths.has(filePath)) continue;\n if (!syncState.files[filePath].remoteHash) continue;\n if (!localPresenceSet.has(filePath)) continue;\n deletedRemotely.push(filePath);\n }\n\n // Note: we don't check for content changes here for performance.\n // After a pull, sync state is accurate. Content changes by others\n // between pull and push are surfaced through the per-file drift\n // check inside push() instead.\n return {\n drift: addedRemotely.length > 0 || deletedRemotely.length > 0,\n addedRemotely,\n deletedRemotely,\n };\n }\n\n async getFileDiff(filePath: string): Promise<{\n localContent: string | null;\n remoteContent: string | null;\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const localPath = safeResolveWithinBase(filesDir, filePath);\n\n let localContent: string | null = null;\n let remoteContent: string | null = null;\n\n if (fs.existsSync(localPath)) {\n // For diff, read as text (diff only makes sense for text files)\n localContent = fs.readFileSync(localPath, 'utf-8');\n }\n\n const remoteFile = await this.farseerClient.getFileByPath(filePath);\n if (remoteFile) {\n remoteContent = await this.farseerClient.getFileContent(remoteFile.reference);\n }\n\n return { localContent, remoteContent };\n }\n\n /**\n * Three-way comparison of all files.\n * Compares current local state, current remote state, and baseline from sync state.\n */\n compareFiles(options: {\n localHashes: Map<string, string>;\n remoteHashes: Map<string, string>;\n syncState: SyncState;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n // Pass-through for `--only`: shouldIncludeFile honours it ahead of\n // ext/folder rules, but only if it's actually in `options`. Without\n // this, push --only would build a status that ignores the whitelist\n // (compareFiles re-runs shouldIncludeFile with only the ext/folder\n // fields above) and a non-.ts/.js whitelisted path would be filtered\n // out as out-of-scope.\n onlyFiles?: string[];\n }): FileCompareResult[] {\n const { localHashes, remoteHashes, syncState } = options;\n\n // Union of all known file paths\n const allPaths = new Set<string>([\n ...localHashes.keys(),\n ...remoteHashes.keys(),\n ...Object.keys(syncState.files),\n ]);\n\n const results: FileCompareResult[] = [];\n\n for (const filePath of allPaths) {\n // Filter files based on includes\n if (!options.all) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) {\n continue;\n }\n }\n\n const currentLocalHash = localHashes.get(filePath) ?? null;\n const currentRemoteHash = remoteHashes.get(filePath) ?? null;\n const baseline = syncState.files[filePath];\n const baselineLocalHash = baseline?.localHash ?? null;\n const baselineRemoteHash = baseline?.remoteHash ?? null;\n\n const localExists = currentLocalHash !== null;\n const remoteExists = currentRemoteHash !== null;\n const hadBaseline = baseline != null;\n\n let changeType: FileChangeType;\n\n if (localExists && remoteExists) {\n // Both exist\n if (currentLocalHash === currentRemoteHash) {\n changeType = 'unchanged';\n } else if (!hadBaseline) {\n changeType = 'conflict_both_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n const baselineDivergent = baselineLocalHash !== baselineRemoteHash;\n\n if (localChanged && remoteChanged) {\n changeType = 'conflict_both_modified';\n } else if (localChanged) {\n changeType = 'local_modified';\n } else if (remoteChanged) {\n changeType = 'remote_modified';\n } else if (baselineDivergent) {\n // Post `keep_local` / `keep_both` resolution: nothing\n // changed since baseline, but baseline already recorded\n // local diverged from remote on purpose. The user\n // chose local; we still need to push so remote\n // catches up. Without this branch, status & push\n // would both fall through to \"unchanged\" and the\n // local edit would silently never reach remote.\n changeType = 'local_modified';\n } else {\n changeType = 'unchanged';\n }\n }\n } else if (localExists && !remoteExists) {\n // Only local exists\n if (!hadBaseline) {\n changeType = 'local_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n if (localChanged) {\n changeType = 'conflict_local_modified_remote_deleted';\n } else {\n changeType = 'remote_deleted';\n }\n }\n } else if (!localExists && remoteExists) {\n // Only remote exists\n if (!hadBaseline) {\n changeType = 'remote_new';\n } else {\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n if (remoteChanged) {\n changeType = 'conflict_local_deleted_remote_modified';\n } else {\n changeType = 'local_deleted';\n }\n }\n } else {\n // Neither exists - both deleted since baseline, clean up\n continue;\n }\n\n results.push({\n filePath,\n changeType,\n currentLocalHash,\n currentRemoteHash,\n baselineLocalHash,\n baselineRemoteHash,\n });\n }\n\n return results;\n }\n\n /**\n * Extract SyncConflict[] from FileCompareResult[].\n */\n static buildConflicts(comparisons: FileCompareResult[]): SyncConflict[] {\n const conflicts: SyncConflict[] = [];\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'conflict_both_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_modified',\n description: 'Both local and remote versions modified since last sync',\n });\n break;\n case 'conflict_local_modified_remote_deleted':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n break;\n case 'conflict_local_deleted_remote_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_deleted_remote_modified',\n description: 'File deleted locally but modified on remote',\n });\n break;\n case 'conflict_both_new':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_new',\n description: 'File exists both locally and remotely with different content (no sync baseline)',\n });\n break;\n }\n }\n return conflicts;\n }\n\n /**\n * Batch fetch metadata for multiple files in parallel.\n * Fetches metadata in batches of 10 to avoid overwhelming the API.\n * Non-critical operation - failures are silently ignored.\n */\n private async fetchMetadataForFiles(files: RemoteFile[]): Promise<RemoteFile[]> {\n const batchSize = 10;\n\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const metadata = await this.farseerClient.getFileMetadata(file.reference);\n if (metadata) {\n file.metadata = metadata;\n }\n } catch {\n // Silently ignore metadata fetch errors - non-critical\n }\n }),\n );\n }\n\n return files;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,4BAAoE;AACpE,2BAAgC;AAChC,qBAUO;AACP,oBAAuB;AACvB,4BAAwE;AACxE,4BAAkC;AAClC,2BAAkC;AAKlC,IAAAA,kBAA+C;AA0B/C,MAAM,2BAA2B,CAAC,gBAAgB,QAAQ,SAAS,oBAAoB,YAAY,aAAa;AAgCzG,SAAS,oBAAoB,UAAiC;AACjE,QAAM,WAAW,SAAS,MAAM,GAAG;AACnC,aAAW,OAAO,UAAU;AACxB,QAAI,yBAAyB,SAAS,GAAG,EAAG,QAAO;AAAA,EACvD;AACA,SAAO;AACX;AAiBO,SAAS,sBACZ,SACA,eAC4B;AAC5B,QAAM,YAAY,CAAC,MACf,EACK,MAAM,KAAK,GAAG,EACd,KAAK,GAAG,EACR,QAAQ,cAAc,EAAE;AACjC,QAAM,iBAAiB,CAAC,GAAI,SAAS,kBAAkB,CAAC,GAAI,GAAG,aAAa,EAAE;AAAA,IAAI,CAAC,MAC/E,EAAE,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG,EAAE,QAAQ,QAAQ,EAAE;AAAA,EAClD;AACA,QAAM,kBAAkB,SAAS,aAAa,CAAC,GAAG,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AA;AAAA,EAOA,MAAc,sBAAsB,OAA4C;AAC5E,UAAM,YAAY;AAElB,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAC9C,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAE1C,YAAM,QAAQ;AAAA,QACV,MAAM,IAAI,OAAO,SAAS;AACtB,cAAI;AACA,kBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,gBAAI,UAAU;AACV,mBAAK,WAAW;AAAA,YACpB;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
6
6
  "names": ["import_helpers"]
7
7
  }
@@ -19,7 +19,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var cliOptions_exports = {};
20
20
  __export(cliOptions_exports, {
21
21
  collectValues: () => collectValues,
22
- normalizeExtensions: () => normalizeExtensions
22
+ normalizeExtensions: () => normalizeExtensions,
23
+ normalizeRelativePath: () => normalizeRelativePath
23
24
  });
24
25
  module.exports = __toCommonJS(cliOptions_exports);
25
26
  function collectValues(value, previous) {
@@ -28,9 +29,13 @@ function collectValues(value, previous) {
28
29
  function normalizeExtensions(exts) {
29
30
  return exts.map((ext) => ext.startsWith(".") ? ext.toLowerCase() : `.${ext.toLowerCase()}`);
30
31
  }
32
+ function normalizeRelativePath(value) {
33
+ return value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
34
+ }
31
35
  // Annotate the CommonJS export names for ESM import in node:
32
36
  0 && (module.exports = {
33
37
  collectValues,
34
- normalizeExtensions
38
+ normalizeExtensions,
39
+ normalizeRelativePath
35
40
  });
36
41
  //# sourceMappingURL=cliOptions.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/cliOptions.ts"],
4
- "sourcesContent": ["/**\n * Shared Commander option parsers for the sync verbs (push, pull, status,\n * checkout). All four commands take the same `--include-ext` /\n * `--include-folder` flag pair, so the parser + normalizer live in one place.\n */\n\n/**\n * Commander custom-parse callback for repeatable string options. Each\n * occurrence of the flag appends to the same string[] accumulator.\n *\n * Used as: `.option('--include-ext <ext>', '\u2026', collectValues, [])`.\n */\nexport function collectValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\n/**\n * Normalize the `--include-ext` array: prepend a leading dot if missing\n * and lowercase. Backend extension matching is case-sensitive on the\n * server side (BACKEND_EXTENSION_WHITELIST), and the rest of the CLI\n * compares with `path.extname(...).toLowerCase()`, so we lower here too.\n */\nexport function normalizeExtensions(exts: string[]): string[] {\n return exts.map((ext) => (ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`));\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYO,SAAS,cAAc,OAAe,UAA8B;AACvE,SAAO,SAAS,OAAO,CAAC,KAAK,CAAC;AAClC;AAQO,SAAS,oBAAoB,MAA0B;AAC1D,SAAO,KAAK,IAAI,CAAC,QAAS,IAAI,WAAW,GAAG,IAAI,IAAI,YAAY,IAAI,IAAI,IAAI,YAAY,CAAC,EAAG;AAChG;",
4
+ "sourcesContent": ["/**\n * Shared Commander option parsers for the sync verbs (push, pull, status,\n * checkout). All four commands take the same `--include-ext` /\n * `--include-folder` flag pair, so the parser + normalizer live in one place.\n */\n\n/**\n * Commander custom-parse callback for repeatable string options. Each\n * occurrence of the flag appends to the same string[] accumulator.\n *\n * Used as: `.option('--include-ext <ext>', '\u2026', collectValues, [])`.\n */\nexport function collectValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\n/**\n * Normalize the `--include-ext` array: prepend a leading dot if missing\n * and lowercase. Backend extension matching is case-sensitive on the\n * server side (BACKEND_EXTENSION_WHITELIST), and the rest of the CLI\n * compares with `path.extname(...).toLowerCase()`, so we lower here too.\n */\nexport function normalizeExtensions(exts: string[]): string[] {\n return exts.map((ext) => (ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`));\n}\n\n/**\n * Normalize a relative file path to POSIX form for comparison against the\n * sync engine's internal representation. The engine canonicalises every\n * candidate to forward slashes (via `toPosix` in syncService) before any\n * include / blocklist / onlyFiles check, so user-supplied paths must match\n * that shape. On Windows, `--only Scripts\\foo.ts` would otherwise be\n * compared byte-for-byte against the POSIX `Scripts/foo.ts` and silently\n * fall out of scope (file validates, then never makes it into the upload\n * set). Trims redundant leading/trailing slashes for the same reason.\n *\n * Replaces backslashes unconditionally (not `path.sep`) \u2014 POSIX hosts\n * receiving a Windows-style argument over SSH / a cross-platform script\n * must still normalise.\n */\nexport function normalizeRelativePath(value: string): string {\n return value.replace(/\\\\/g, '/').replace(/^\\/+|\\/+$/g, '');\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYO,SAAS,cAAc,OAAe,UAA8B;AACvE,SAAO,SAAS,OAAO,CAAC,KAAK,CAAC;AAClC;AAQO,SAAS,oBAAoB,MAA0B;AAC1D,SAAO,KAAK,IAAI,CAAC,QAAS,IAAI,WAAW,GAAG,IAAI,IAAI,YAAY,IAAI,IAAI,IAAI,YAAY,CAAC,EAAG;AAChG;AAgBO,SAAS,sBAAsB,OAAuB;AACzD,SAAO,MAAM,QAAQ,OAAO,GAAG,EAAE,QAAQ,cAAc,EAAE;AAC7D;",
6
6
  "names": []
7
7
  }
@@ -68,8 +68,9 @@ const BACKEND_EXTENSION_WHITELIST = /* @__PURE__ */ new Set([
68
68
  "png",
69
69
  "gif",
70
70
  "webp",
71
- // Archives
72
- "zip"
71
+ // Archives / columnar data
72
+ "zip",
73
+ "parquet"
73
74
  ]);
74
75
  const MAX_FILE_NAME_LENGTH = 256;
75
76
  const CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \(your version\)$/m;