Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-5855]): sweep abandoned resumable-download leftovers (#5868)
atomanticagent989ea4b7b1f7
diff --git a/server/lib/README.md b/server/lib/README.mdindex c668164115..68911cfb33 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -221,7 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting `pruneTombstoned*` loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |-| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. |+| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. || `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. || `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. || `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |diff --git a/server/lib/downloadPreflight.js b/server/lib/downloadPreflight.jsindex 1ae2cf26ac..7ca7091c14 100644--- a/server/lib/downloadPreflight.js+++ b/server/lib/downloadPreflight.js@@ -14,8 +14,8 @@*/import { createWriteStream } from 'fs';-import { readFile, rm, stat, statfs, rename, writeFile } from 'fs/promises';-import { dirname } from 'path';+import { readFile, readdir, rm, stat, statfs, rename, writeFile } from 'fs/promises';+import { dirname, join } from 'path';import { Readable, Transform } from 'stream';import { pipeline } from 'stream/promises';import { ServerError } from './errorHandler.js';@@ -42,6 +42,93 @@ export const partialPathFor = (destPath) => `${destPath}${PARTIAL_SUFFIX}`;// object instead of silently splicing its bytes onto our stale prefix.export const etagPathFor = (destPath) => `${partialPathFor(destPath)}.etag`;+/** Age after which a leftover `.partial` is treated as abandoned rather than resumable. */+export const ORPHANED_PARTIAL_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;++const destPathForPartial = (partialPath) => (+ String(partialPath).endsWith(PARTIAL_SUFFIX)+ ? partialPath.slice(0, -PARTIAL_SUFFIX.length)+ : partialPath+);++const MAX_SWEEP_DEPTH = 8;++/**+ * Recursively collect `${name}.partial` files under `dir`. A missing or+ * non-directory path returns `null` so the caller can treat it as a no-op.+ */+async function collectPartialFiles(dir, { recursive = true, depth = 0 } = {}) {+ const entries = await readdir(dir, { withFileTypes: true }).catch((err) => {+ if (err?.code === 'ENOENT' || err?.code === 'ENOTDIR') return null;+ throw err;+ });+ if (!entries) return null;+ const files = [];+ for (const entry of entries) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!recursive || depth >= MAX_SWEEP_DEPTH) continue;+ const nested = await collectPartialFiles(full, { recursive, depth: depth + 1 });+ if (nested) files.push(...nested);+ continue;+ }+ if (entry.isFile() && entry.name.endsWith(PARTIAL_SUFFIX)) files.push(full);+ }+ return files;+}++/**+ * Age-based sweep of leftover `${dest}.partial` files (and their+ * `.partial.etag` sidecars) in one or more download destination directories.+ *+ * A missing directory is a no-op. Recent files (mtime within `maxAgeMs`) and+ * any path `isProtected` returns true for — an in-flight download's dest, or+ * its `.partial` — are never unlinked. An active transfer's mtime keeps+ * advancing as bytes land, but the protected-path check is the belt against a+ * sweep tick racing a live write.+ *+ * @param {string|string[]} dirs+ * @param {{ maxAgeMs?: number, now?: number, isProtected?: (path: string) => boolean, recursive?: boolean }} [opts]+ * @returns {Promise<{ deleted: number, keptYoung: number, keptProtected: number }>}+ */+export async function sweepOrphanedPartials(dirs, {+ maxAgeMs = ORPHANED_PARTIAL_MAX_AGE_MS,+ now = Date.now(),+ isProtected = () => false,+ recursive = true,+} = {}) {+ const dirList = (Array.isArray(dirs) ? dirs : [dirs])+ .filter((d) => typeof d === 'string' && d);+ let deleted = 0;+ let keptYoung = 0;+ let keptProtected = 0;+ for (const dir of dirList) {+ const files = await collectPartialFiles(dir, { recursive }).catch(() => null);+ if (!files) continue;+ for (const partial of files) {+ const destPath = destPathForPartial(partial);+ if (isProtected(destPath) || isProtected(partial)) {+ keptProtected += 1;+ continue;+ }+ const info = await stat(partial).catch(() => null);+ if (!info) continue;+ if (now - info.mtimeMs < maxAgeMs) {+ keptYoung += 1;+ continue;+ }+ const removed = await rm(partial, { force: true }).then(() => true).catch(() => false);+ // Only drop the sidecar after the partial itself is gone — an EACCES+ // (or any other unlink failure) must not strand a `.partial` without+ // the etag a later resume uses for If-Range.+ if (!removed) continue;+ await rm(etagPathFor(destPath), { force: true }).catch(() => {});+ deleted += 1;+ }+ }+ return { deleted, keptYoung, keptProtected };+}+export function normalizeSha256(value) {if (typeof value !== 'string') return null;const hex = value.trim().toLowerCase().replace(/^sha256:/, '').replace(/['"]/g, '');diff --git a/server/lib/downloadPreflight.test.js b/server/lib/downloadPreflight.test.jsindex abd6a32896..2eecfd4346 100644--- a/server/lib/downloadPreflight.test.js+++ b/server/lib/downloadPreflight.test.js@@ -1,5 +1,5 @@import { createHash } from 'crypto';-import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';import { Readable } from 'stream';@@ -15,6 +15,8 @@ import {verifyDownloadHash,partialPathFor,probeRemoteSize,+ sweepOrphanedPartials,+ ORPHANED_PARTIAL_MAX_AGE_MS,} from './downloadPreflight.js';const GiB = 1024 ** 3;@@ -560,3 +562,77 @@ describe('verifyDownloadHash', () => {await expect(verifyDownloadHash(path, digest)).resolves.toMatchObject({ ok: true });});});++describe('sweepOrphanedPartials', () => {+ let dir;+ afterEach(async () => {+ if (dir) await rm(dir, { recursive: true, force: true });+ });++ const writeAged = async (name, ageMs, contents = 'x') => {+ const p = join(dir, name);+ await writeFile(p, contents);+ if (ageMs > 0) {+ const when = new Date(Date.now() - ageMs);+ await utimes(p, when, when);+ }+ return p;+ };++ it('all-zero on a missing dir (does not throw)', async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-partial-sweep-'));+ const res = await sweepOrphanedPartials(join(dir, 'nope'));+ expect(res).toEqual({ deleted: 0, keptYoung: 0, keptProtected: 0 });+ });++ it('removes a .partial older than the cutoff and its .etag sidecar', async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-partial-sweep-'));+ const age = ORPHANED_PARTIAL_MAX_AGE_MS + 60_000;+ const partial = await writeAged('model.gguf.partial', age);+ const etag = await writeAged('model.gguf.partial.etag', age, '"abc"');+ await writeAged('keep.gguf', age, 'done');+ const res = await sweepOrphanedPartials(dir);+ expect(res.deleted).toBe(1);+ expect(await readFile(partial).catch(() => null)).toBeNull();+ expect(await readFile(etag).catch(() => null)).toBeNull();+ expect(await readFile(join(dir, 'keep.gguf'), 'utf8')).toBe('done');+ });++ it('keeps a recent .partial (in-flight / still-resumable)', async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-partial-sweep-'));+ const fresh = await writeAged('model.gguf.partial', 0);+ const res = await sweepOrphanedPartials(dir);+ expect(res.deleted).toBe(0);+ expect(res.keptYoung).toBe(1);+ expect(await readFile(fresh).catch(() => null)).not.toBeNull();+ });++ it('never deletes an isProtected dest even when the .partial is old', async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-partial-sweep-'));+ const age = ORPHANED_PARTIAL_MAX_AGE_MS + 60_000;+ const pinned = await writeAged('live.gguf.partial', age);+ const stray = await writeAged('stale.gguf.partial', age);+ const dest = join(dir, 'live.gguf');+ const res = await sweepOrphanedPartials(dir, {+ isProtected: (path) => path === dest,+ });+ expect(res.deleted).toBe(1);+ expect(res.keptProtected).toBe(1);+ expect(await readFile(pinned).catch(() => null)).not.toBeNull();+ expect(await readFile(stray).catch(() => null)).toBeNull();+ });++ it('walks nested download dirs (ollama/lmstudio-style trees)', async () => {+ dir = await mkdtemp(join(tmpdir(), 'portos-partial-sweep-'));+ const nested = join(dir, 'blobs');+ await mkdir(nested);+ const age = ORPHANED_PARTIAL_MAX_AGE_MS + 60_000;+ const nestedPartial = join(nested, 'sha.partial');+ await writeFile(nestedPartial, 'x');+ const when = new Date(Date.now() - age);+ await utimes(nestedPartial, when, when);+ const res = await sweepOrphanedPartials(dir);+ expect(res.deleted).toBe(1);+ expect(await readFile(nestedPartial).catch(() => null)).toBeNull();+ });+});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 221896ad3b..6e1fa4f05a 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -98,6 +98,7 @@ import { restoreLoops } from './loops.js';import { startOrphanShellGc } from './importerOrphanGc.js';import { startImageRefsGc } from './imageRefsGc.js';import { startImageCleanTmpGc } from './imageCleanTmpGc.js';+import { startOrphanedPartialGc } from './orphanedPartialGc.js';import { initBridge as initBrainMemoryBridge } from './brainMemoryBridge.js';import { initDrillCache } from './meatspacePostDrillCache.js';import { registerPostReminderSchedule } from './meatspacePostReminder.js';@@ -455,6 +456,12 @@ const startBackgroundServices = ({ spawnerReady, io }) => {// mask/original) that land in data/image-clean-tmp and are never long-lived// (issue #2264). Age-gate only — nothing here is referenced after the fetch.startImageCleanTmpGc();+ // Periodically GC leftover `${dest}.partial` files from resumable weight+ // downloads (issue #5855). Age-gated (7 days) so an overnight pause-and-resume+ // is not punished; in-flight spec-decode dests are also pinned. Fire-and-forget+ // like the other GCs — not part of the awaited warmStores pruneLegacyFiles+ // chain, so a large sweep cannot stall listen().+ startOrphanedPartialGc();// Warm the catalog user-type registry from the user-type store (Postgres as of// #1001; the settings.json slice under the escape hatch) before any catalog// request can land, so user-defined types validate + mint ids immediately ondiff --git a/server/services/orphanedPartialGc.js b/server/services/orphanedPartialGc.jsnew file mode 100644index 0000000000..0c46530a6e--- /dev/null+++ b/server/services/orphanedPartialGc.js@@ -0,0 +1,81 @@+/**+ * Orphaned resumable-download `.partial` GC (issue #5855).+ *+ * `streamResumableDownload` keeps `${dest}.partial` (+ a `.partial.etag`+ * sidecar) after a transport failure so a retry can Range-resume. If the user+ * never retries, those files sit invisible in LoRA / spec-decode / local-LLM+ * model dirs and eat the disk the preflight exists to protect.+ *+ * This is the same shape as imageCleanTmpGc / imageRefsGc: a delayed boot pass+ * plus a daily tick through eventScheduler. The age-gate lives in+ * `sweepOrphanedPartials`; this module only names the destinations and the+ * in-flight dests that must not be touched.+ */++import { dirname } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { sweepOrphanedPartials, ORPHANED_PARTIAL_MAX_AGE_MS } from '../lib/downloadPreflight.js';+import { SPEC_DECODE_PRESETS, SPEC_MODEL_ROLES } from '../lib/specDecodePresets.js';+import {+ resolveSpecModelPath,+ isSpecDecodeDownloadInFlight,+} from './specDecodeModels.js';+import { getModelsDir as getOllamaModelsDir } from './ollamaManager.js';+import { getModelsDir as getLmStudioModelsDir } from './lmStudioManager.js';+import { createSweepScheduler } from './sweepScheduler.js';++export { ORPHANED_PARTIAL_MAX_AGE_MS };++const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours++/**+ * Directories the four #5817 download entry points can leave a `.partial` in.+ * Spec-decode dests are per-file; we sweep each file's parent so a custom+ * `~/models/...` path is covered without walking the whole home directory.+ */+export async function collectPartialSweepDirs() {+ const dirs = new Set();+ dirs.add(PATHS.loras);+ for (const preset of SPEC_DECODE_PRESETS) {+ for (const role of SPEC_MODEL_ROLES) {+ const path = preset[role]?.path;+ if (path) dirs.add(dirname(resolveSpecModelPath(path)));+ }+ }+ dirs.add(getOllamaModelsDir());+ dirs.add(await getLmStudioModelsDir());+ return [...dirs];+}++/**+ * One GC pass. `dirs` is injectable so tests can point at a temp tree without+ * touching the live install's model directories.+ */+export async function sweepOrphanedDownloadPartials({+ now = Date.now(),+ maxAgeMs = ORPHANED_PARTIAL_MAX_AGE_MS,+ dirs = null,+} = {}) {+ const targets = dirs || await collectPartialSweepDirs();+ return sweepOrphanedPartials(targets, {+ now,+ maxAgeMs,+ isProtected: (path) => isSpecDecodeDownloadInFlight(path),+ });+}++const runSweep = async () => {+ const { deleted } = await sweepOrphanedDownloadPartials();+ if (deleted > 0) console.log(`🧹 Orphaned download partial GC: removed ${deleted} stale file(s)`);+};++export const {+ start: startOrphanedPartialGc,+ stop: stopOrphanedPartialGc,+} = createSweepScheduler({+ id: 'orphaned-partial-gc',+ intervalMs: SWEEP_INTERVAL_MS,+ initialDelayMs: 5 * 60 * 1000,+ handler: runSweep,+ source: 'orphanedPartialGc',+});diff --git a/server/services/specDecodeModels.js b/server/services/specDecodeModels.jsindex 3474609afa..8666e23046 100644--- a/server/services/specDecodeModels.js+++ b/server/services/specDecodeModels.js@@ -377,6 +377,16 @@ export function cancelSpecDecodeModelDownload({ presetId, role }) {return true;}+/** True while a curated GGUF download is writing `destPath` (or its `.partial`). */+export function isSpecDecodeDownloadInFlight(destPath) {+ if (!destPath) return false;+ if (inFlight.has(destPath)) return true;+ if (String(destPath).endsWith('.partial')) {+ return inFlight.has(destPath.slice(0, -'.partial'.length));+ }+ return false;+}+/** Clears in-flight download bookkeeping (used by test suites). */export function _resetSpecDecodeDownloadsForTests() {inFlight.clear();