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
extract `~/`-expanding `expandHome` to fileUtils + add HF download `--local-dir` / `--ignore` flags
[._.]/ Adam Eivy5ab315a4bf01
diff --git a/scripts/hf_download_repo.py b/scripts/hf_download_repo.pyindex 7ecf7922ce..764b3d96b6 100755--- a/scripts/hf_download_repo.py+++ b/scripts/hf_download_repo.py@@ -46,6 +46,8 @@ def main() -> int:parser.add_argument("--repo", required=True, help="HF repo id, e.g. 'org/name'.")parser.add_argument("--revision", default=None, help="Optional revision (branch / tag / sha).")parser.add_argument("--token-env", default=None, help="Env var name to read the HF token from (e.g. HF_TOKEN).")+ parser.add_argument("--local-dir", default=None, help="If set, materialize the repo as a flat copy at this dir instead of relying on the standard HF cache symlinks (used by BYOV installers like HiDream-O1 that need a real on-disk repo).")+ parser.add_argument("--ignore", action="append", default=[], help="Glob pattern (fnmatch) to skip from the file list. Repeat for multiple patterns. e.g. --ignore 'scripts/**' --ignore 'docs/**' to skip non-weight subdirs.")args = parser.parse_args()token = None@@ -81,6 +83,9 @@ def main() -> int:# as part of a snapshot (`.gitattributes` is, but `LICENSE` and similar# are — we keep them; the only true skip is the `.huggingface` folder).files = [f for f in files if not f.startswith(".huggingface/")]+ if args.ignore:+ import fnmatch+ files = [f for f in files if not any(fnmatch.fnmatch(f, pat) for pat in args.ignore)]total = len(files)if total == 0:print(f"USER_ERROR:repo_empty:{args.repo}", file=sys.stderr, flush=True)@@ -100,6 +105,7 @@ def main() -> int:filename=filename,revision=args.revision,token=token,+ local_dir=args.local_dir,)except GatedRepoError:print(f"USER_ERROR:gated_repo:{args.repo}", file=sys.stderr, flush=True)diff --git a/server/lib/README.md b/server/lib/README.mdindex 761958a301..b732f093a8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -90,7 +90,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. || `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. `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from `pruneTombstonedUniverses`/`pruneTombstonedSeries`) so the side store doesn't grow without bound. `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. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. || `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. || `multipart.js` | Streaming multipart/form-data parser. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 5778be2c47..b5e26afade 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -182,6 +182,15 @@ export function dataPath(...segments) {return join(PATHS.data, ...segments);}+// `path.join(homedir(), '/.foo')` discards the homedir prefix because of+// the leading slash, so strip the `~/` (or bare `~`) before joining.+export function expandHome(p) {+ if (typeof p !== 'string' || !p) return p;+ if (p === '~') return homedir();+ if (p.startsWith('~/')) return join(homedir(), p.slice(2));+ return p;+}+/*** Check if a string is potentially valid JSON.* Performs quick structural validation before parsing.diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 81b0aca385..f6de660a88 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -16,9 +16,8 @@*/import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';-import { homedir } from 'os';import { join, dirname } from 'path';-import { PATHS } from './fileUtils.js';+import { PATHS, expandHome } from './fileUtils.js';import { isPlainObject } from './objects.js';import { RUNNER_FAMILIES } from './runners.js';// fileUtils.ensureDir is async/Promise-returning; this module needs a@@ -276,15 +275,6 @@ const DEFAULT_REGISTRY = {selectedTextEncoder: 'gemma-bf16',};-// `path.join(homedir(), '/.foo')` discards the homedir because of the-// leading slash, so we have to strip the `~/` prefix (or `~`) before joining.-const expandHome = (p) => {- if (!p || !p.startsWith('~')) return p;- if (p === '~') return homedir();- if (p.startsWith('~/')) return join(homedir(), p.slice(2));- return p;-};-let cached = null;const ensureDir = (file) => {diff --git a/server/lib/runners.test.js b/server/lib/runners.test.jsindex 36e4a34314..2b5c9f60b0 100644--- a/server/lib/runners.test.js+++ b/server/lib/runners.test.js@@ -3,17 +3,19 @@ import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { RUNNER_FAMILIES, isMflux, isFlux2, isZImage, isErnie } from './runners.js';+import { RUNNER_FAMILIES, isMflux, isFlux2, isZImage, isErnie, isHiDream } from './runners.js';const __dirname_self = dirname(fileURLToPath(import.meta.url));const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');describe('RUNNER_FAMILIES', () => {- it('exports the four canonical runner ids', () => {+ it('exports the canonical runner ids', () => {expect(RUNNER_FAMILIES.MFLUX).toBe('mflux');expect(RUNNER_FAMILIES.FLUX2).toBe('flux2');expect(RUNNER_FAMILIES.Z_IMAGE).toBe('z-image');expect(RUNNER_FAMILIES.ERNIE).toBe('ernie');+ expect(RUNNER_FAMILIES.HIDREAM).toBe('hidream');+ expect(RUNNER_FAMILIES.QWEN).toBe('qwen');});it('is frozen so callers can\'t mutate the canonical strings at runtime', () => {@@ -30,6 +32,8 @@ describe('RUNNER_FAMILIES', () => {expect(text).toMatch(/FLUX2:\s*'flux2'/);expect(text).toMatch(/Z_IMAGE:\s*'z-image'/);expect(text).toMatch(/ERNIE:\s*'ernie'/);+ expect(text).toMatch(/HIDREAM:\s*'hidream'/);+ expect(text).toMatch(/QWEN:\s*'qwen'/);});it('predicate helpers match on the canonical runner ids', () => {@@ -37,6 +41,7 @@ describe('RUNNER_FAMILIES', () => {expect(isFlux2({ runner: 'flux2' })).toBe(true);expect(isZImage({ runner: 'z-image' })).toBe(true);expect(isErnie({ runner: 'ernie' })).toBe(true);+ expect(isHiDream({ runner: 'hidream' })).toBe(true);expect(isFlux2({ runner: 'mflux' })).toBe(false);expect(isFlux2(null)).toBe(false);expect(isFlux2(undefined)).toBe(false);diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex 50c55c22b8..890fe58cb2 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -20,10 +20,9 @@*/import { existsSync, statSync } from 'fs';-import { homedir } from 'os';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';-import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { ensureDir, expandHome, PATHS } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { execGit } from '../lib/execGit.js';import {@@ -32,17 +31,6 @@ import {} from './apps.js';import { DEFAULT_REVIEWER } from '../lib/validation.js';-// `path.join(homedir(), '/.foo')` discards the homedir because of the leading-// slash, so we strip the `~/` prefix (or `~`) before joining. Same shape as-// the helper in lib/mediaModels.js — kept inline here to avoid pulling in the-// rest of that module just for one helper.-const expandHome = (p) => {- if (!p || typeof p !== 'string' || !p.startsWith('~')) return p;- if (p === '~') return homedir();- if (p.startsWith('~/')) return join(homedir(), p.slice(2));- return p;-};-const REFERENCE_REPOS_ROOT = join(PATHS.data, 'cos', 'reference-repos');// 40-char hex SHA the same way git outputs it. Used by every callsite thatdiff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.jsindex b2e6e2f6f8..98352db7ef 100644--- a/server/services/referenceRepos.test.js+++ b/server/services/referenceRepos.test.js@@ -3,8 +3,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// ─── mocks (must precede the import under test) ──────────────────────────────vi.mock('../lib/fileUtils.js', () => ({-tryReadFile: vi.fn().mockResolvedValue(null),+ tryReadFile: vi.fn().mockResolvedValue(null),ensureDir: vi.fn(async () => {}),+ expandHome: vi.fn((p) => p),PATHS: { data: '/mock/data', root: '/mock/root' },readJSONFile: vi.fn(async () => ({ apps: {} })),}));