Skip to content

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

feat(server): city introspection service + GET /api/city/introspection

[._.]/ Adam Eivydd052fdeb58d
diff --git a/docs/API.md b/docs/API.md
index 84a33825f1..29fde3e243 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -215,6 +215,15 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| GET | `/usage/daily` | Get daily activity |
| GET | `/usage/hourly` | Get hourly activity |
+### CyberCity
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/city/snapshots` | Recorded city-state series, oldest-first (`since`, `limit` query params) |
+| POST | `/city/snapshots/capture` | Capture a city snapshot frame on demand |
+| GET | `/city/snapshots/config` | Effective snapshot capture config + next run time |
+| GET | `/city/introspection` | DB tables (rows/size/pgvector) + `data/` domain sizes for the Data Harbor district. Cached server-side; `db: null` means the database is unreachable (distinct from reachable-but-empty) |
+
### Brain (Second Brain)
| Method | Endpoint | Description |
diff --git a/server/routes/cityRoutes.js b/server/routes/cityRoutes.js
index 0a203a49f8..22f0473ed9 100644
--- a/server/routes/cityRoutes.js
+++ b/server/routes/cityRoutes.js
@@ -7,6 +7,7 @@ import {
getSnapshotConfig,
} from '../services/citysnapshots.js';
import { getNextSnapshotTime } from '../services/citySnapshotScheduler.js';
+import { getCityIntrospection } from '../services/cityIntrospection.js';
const router = Router();
@@ -23,6 +24,13 @@ router.post('/snapshots/capture', asyncHandler(async (req, res) => {
res.json(await captureSnapshot());
}));
+// GET /api/city/introspection — DB tables + data/ domain sizes for the Data
+// Harbor district. Cached server-side (stale-while-revalidate); `db: null`
+// means the database is unreachable, distinct from a reachable-but-empty one.
+router.get('/introspection', asyncHandler(async (req, res) => {
+ res.json(await getCityIntrospection());
+}));
+
// GET /api/city/snapshots/config — effective capture config + next run time.
router.get('/snapshots/config', asyncHandler(async (req, res) => {
const config = await getSnapshotConfig();
diff --git a/server/routes/cityRoutes.test.js b/server/routes/cityRoutes.test.js
index 887f5cee88..750cede4ee 100644
--- a/server/routes/cityRoutes.test.js
+++ b/server/routes/cityRoutes.test.js
@@ -9,6 +9,7 @@ const captureSnapshot = vi.fn();
const getSnapshots = vi.fn();
const getSnapshotConfig = vi.fn();
const getNextSnapshotTime = vi.fn();
+const getCityIntrospection = vi.fn();
vi.mock('../services/citysnapshots.js', () => ({
captureSnapshot: (...a) => captureSnapshot(...a),
@@ -18,6 +19,9 @@ vi.mock('../services/citysnapshots.js', () => ({
vi.mock('../services/citySnapshotScheduler.js', () => ({
getNextSnapshotTime: (...a) => getNextSnapshotTime(...a),
}));
+vi.mock('../services/cityIntrospection.js', () => ({
+ getCityIntrospection: (...a) => getCityIntrospection(...a),
+}));
const { default: cityRoutes } = await import('./cityRoutes.js');
@@ -75,6 +79,17 @@ describe('city snapshot routes', () => {
});
});
+ describe('GET /api/city/introspection', () => {
+ it('passes the introspection payload through, including db: null', async () => {
+ const payload = { ts: '2026-06-09T00:00:00.000Z', db: null, fs: { domains: [], totalBytes: 0, totalFiles: 0 } };
+ getCityIntrospection.mockResolvedValue(payload);
+ const res = await request(makeApp()).get('/api/city/introspection');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(payload);
+ expect(getCityIntrospection).toHaveBeenCalledOnce();
+ });
+ });
+
describe('GET /api/city/snapshots/config', () => {
it('returns effective config plus the next run time', async () => {
const res = await request(makeApp()).get('/api/city/snapshots/config');
diff --git a/server/services/cityIntrospection.js b/server/services/cityIntrospection.js
new file mode 100644
index 0000000000..88cdceee3b
--- /dev/null
+++ b/server/services/cityIntrospection.js
@@ -0,0 +1,183 @@
+/**
+ * City Introspection
+ *
+ * Read-only diagnostics backing CyberCity's Data Harbor district: the PostgreSQL
+ * datastore (one silo per table) and the `data/` filesystem (one archive rack per
+ * domain directory). Purely derived state — nothing is stored, synced, or backed
+ * up (see docs/STORAGE.md: transient query results need no classification).
+ *
+ * Caching: the data/ walk can take whole seconds on a media-heavy install
+ * (data/images alone holds thousands of files), so results are cached with a TTL
+ * and served stale-while-revalidate — once a payload exists, callers always get
+ * an immediate answer while an expired cache refreshes in the background.
+ * Concurrent first calls share one in-flight build.
+ */
+
+import { readdir, stat } from 'fs/promises';
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
+import { query } from '../lib/db.js';
+
+export const INTROSPECTION_TTL_MS = 45_000;
+
+// Domain directories walked concurrently (each walk is itself sequential —
+// bounded I/O pressure either way).
+const WALK_CONCURRENCY = 4;
+
+let cache = null;
+let cacheBuiltAt = 0;
+let inFlight = null;
+
+// Test hook — clears the module-level cache between suites.
+export function resetIntrospectionCache() {
+ cache = null;
+ cacheBuiltAt = 0;
+ inFlight = null;
+}
+
+// Postgres returns bigint columns as strings; coerce defensively.
+const toNumber = (v) => {
+ const n = Number(v);
+ return Number.isFinite(n) ? n : 0;
+};
+
+// The database section. A down/unreachable DB yields `null` (absent), never a
+// hollow `{ tables: [] }` — the harbor renders "DB OFFLINE" instead of an empty
+// quay (CLAUDE.md's absent-vs-empty rule).
+async function buildDbSection() {
+ const tables = await query(
+ `SELECT relname AS name,
+ n_live_tup AS row_estimate,
+ pg_total_relation_size(relid) AS total_bytes
+ FROM pg_stat_user_tables
+ WHERE schemaname = 'public'
+ ORDER BY pg_total_relation_size(relid) DESC, relname ASC`,
+ ).then((r) => r.rows, () => null);
+ if (!tables) return null;
+
+ // Independent enrichments — each degrades to absent without sinking the section.
+ const [vectorRows, sizeRow, migrationRow] = await Promise.all([
+ query(
+ `SELECT DISTINCT table_name
+ FROM information_schema.columns
+ WHERE table_schema = 'public' AND udt_name = 'vector'`,
+ ).then((r) => r.rows, () => []),
+ query('SELECT pg_database_size(current_database()) AS bytes')
+ .then((r) => r.rows[0], () => null),
+ query('SELECT count(*)::int AS applied, max(applied_at) AS last_applied FROM schema_migrations')
+ .then((r) => r.rows[0], () => null),
+ ]);
+
+ const vectorTables = new Set(vectorRows.map((r) => r.table_name));
+
+ return {
+ sizeBytes: sizeRow ? toNumber(sizeRow.bytes) : null,
+ tables: tables.map((t) => ({
+ name: t.name,
+ rowEstimate: toNumber(t.row_estimate),
+ totalBytes: toNumber(t.total_bytes),
+ hasEmbedding: vectorTables.has(t.name),
+ })),
+ migrations: migrationRow
+ ? { applied: toNumber(migrationRow.applied), lastApplied: migrationRow.last_applied ?? null }
+ : null,
+ };
+}
+
+// Recursive size/count of a directory tree. Symlinks are skipped (a link into a
+// media library shouldn't count as local data); unreadable entries are tolerated
+// per-entry so one bad file can't sink a domain.
+async function walkDir(path) {
+ let bytes = 0;
+ let files = 0;
+ const entries = await readdir(path, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) continue;
+ const childPath = join(path, entry.name);
+ if (entry.isDirectory()) {
+ const sub = await walkDir(childPath);
+ bytes += sub.bytes;
+ files += sub.files;
+ } else if (entry.isFile()) {
+ const s = await stat(childPath).catch(() => null);
+ if (s) {
+ bytes += s.size;
+ files += 1;
+ }
+ }
+ }
+ return { bytes, files };
+}
+
+// The filesystem section: each depth-1 directory under data/ becomes a domain;
+// loose top-level files roll into a "(root)" pseudo-domain. Domains sorted by
+// size so the harbor's biggest racks come first.
+async function buildFsSection() {
+ const entries = await readdir(PATHS.data, { withFileTypes: true }).catch(() => null);
+ if (!entries) return null;
+
+ const dirs = [];
+ let rootBytes = 0;
+ let rootFiles = 0;
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) continue;
+ if (entry.isDirectory()) {
+ dirs.push(entry.name);
+ } else if (entry.isFile()) {
+ const s = await stat(join(PATHS.data, entry.name)).catch(() => null);
+ if (s) {
+ rootBytes += s.size;
+ rootFiles += 1;
+ }
+ }
+ }
+
+ const domains = [];
+ for (let i = 0; i < dirs.length; i += WALK_CONCURRENCY) {
+ const batch = dirs.slice(i, i + WALK_CONCURRENCY);
+ const results = await Promise.all(batch.map((name) => walkDir(join(PATHS.data, name))));
+ batch.forEach((name, j) => domains.push({ name, ...results[j] }));
+ }
+ if (rootFiles > 0) domains.push({ name: '(root)', bytes: rootBytes, files: rootFiles });
+
+ domains.sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));
+ return {
+ domains,
+ totalBytes: domains.reduce((sum, d) => sum + d.bytes, 0),
+ totalFiles: domains.reduce((sum, d) => sum + d.files, 0),
+ };
+}
+
+async function build() {
+ const [db, fs] = await Promise.all([buildDbSection(), buildFsSection()]);
+ return { ts: new Date().toISOString(), db, fs };
+}
+
+export async function getCityIntrospection() {
+ const now = Date.now();
+ if (cache && now - cacheBuiltAt < INTROSPECTION_TTL_MS) return cache;
+
+ if (!inFlight) {
+ inFlight = build().then(
+ (result) => {
+ cache = result;
+ cacheBuiltAt = Date.now();
+ inFlight = null;
+ return result;
+ },
+ (err) => {
+ // When stale cache is being served nobody awaits this promise, so a
+ // rethrow would be an unhandled rejection — resolve to the stale
+ // payload instead and only propagate when there's nothing to serve.
+ inFlight = null;
+ console.error(`❌ City introspection rebuild failed: ${err.message}`);
+ if (cache) return cache;
+ throw err;
+ },
+ );
+ }
+
+ // Stale-while-revalidate: an expired-but-present cache answers immediately
+ // while the rebuild completes in the background.
+ return cache ?? inFlight;
+}
diff --git a/server/services/cityIntrospection.test.js b/server/services/cityIntrospection.test.js
new file mode 100644
index 0000000000..98c4720af1
--- /dev/null
+++ b/server/services/cityIntrospection.test.js
@@ -0,0 +1,157 @@
+/**
+ * Tests for the Data Harbor introspection service: DB section shape (including
+ * the down-DB → `db: null` absent-vs-empty contract), the data/ domain walk
+ * (sizes, file counts, symlink skip, "(root)" pseudo-domain), and the
+ * TTL + stale-while-revalidate cache discipline.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, symlinkSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'city-introspection-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+
+const { queryMock } = vi.hoisted(() => ({ queryMock: vi.fn() }));
+vi.mock('../lib/db.js', () => ({ query: queryMock }));
+
+const {
+ getCityIntrospection,
+ resetIntrospectionCache,
+ INTROSPECTION_TTL_MS,
+} = await import('./cityIntrospection.js');
+
+const TABLE_ROWS = [
+ { name: 'memories', row_estimate: '1200', total_bytes: '900000' },
+ { name: 'catalog_scraps', row_estimate: '40', total_bytes: '50000' },
+ { name: 'schema_migrations', row_estimate: '12', total_bytes: '8000' },
+];
+
+// Default happy-path query dispatcher, keyed on SQL shape.
+const happyQueries = (sql) => {
+ if (sql.includes('pg_stat_user_tables')) return { rows: TABLE_ROWS };
+ if (sql.includes('information_schema.columns')) {
+ return { rows: [{ table_name: 'memories' }, { table_name: 'catalog_scraps' }] };
+ }
+ if (sql.includes('pg_database_size')) return { rows: [{ bytes: '5000000' }] };
+ if (sql.includes('schema_migrations')) {
+ return { rows: [{ applied: 12, last_applied: '2026-06-01T00:00:00.000Z' }] };
+ }
+ throw new Error(`unexpected query: ${sql}`);
+};
+
+const writeFixtureTree = () => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(join(TEST_DATA_ROOT, 'images', 'sub'), { recursive: true });
+ mkdirSync(join(TEST_DATA_ROOT, 'brain'), { recursive: true });
+ writeFileSync(join(TEST_DATA_ROOT, 'images', 'a.png'), 'aaaaa'); // 5 bytes
+ writeFileSync(join(TEST_DATA_ROOT, 'images', 'sub', 'b.png'), 'bbb'); // 3 bytes
+ writeFileSync(join(TEST_DATA_ROOT, 'brain', 'x.json'), 'ccccccc'); // 7 bytes
+ writeFileSync(join(TEST_DATA_ROOT, 'loose.json'), 'dd'); // 2 bytes
+ // A symlinked directory must not be walked (or counted).
+ symlinkSync(join(TEST_DATA_ROOT, 'images'), join(TEST_DATA_ROOT, 'linked'));
+};
+
+beforeEach(() => {
+ resetIntrospectionCache();
+ vi.restoreAllMocks();
+ queryMock.mockReset();
+ queryMock.mockImplementation(async (sql) => happyQueries(sql));
+ writeFixtureTree();
+});
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('getCityIntrospection — db section', () => {
+ it('maps tables with coerced numbers, embedding flags, size, and migrations', async () => {
+ const result = await getCityIntrospection();
+ expect(result.ts).toBeTruthy();
+ expect(result.db.sizeBytes).toBe(5000000);
+ expect(result.db.tables).toHaveLength(3);
+ const memories = result.db.tables.find((t) => t.name === 'memories');
+ expect(memories).toEqual({
+ name: 'memories', rowEstimate: 1200, totalBytes: 900000, hasEmbedding: true,
+ });
+ const migrationsTable = result.db.tables.find((t) => t.name === 'schema_migrations');
+ expect(migrationsTable.hasEmbedding).toBe(false);
+ expect(result.db.migrations).toEqual({ applied: 12, lastApplied: '2026-06-01T00:00:00.000Z' });
+ });
+
+ it('returns db: null (absent, not empty) when the table query fails', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (sql.includes('pg_stat_user_tables')) throw new Error('connection refused');
+ return happyQueries(sql);
+ });
+ const result = await getCityIntrospection();
+ expect(result.db).toBeNull();
+ // The filesystem section is independent of DB health.
+ expect(result.fs.domains.length).toBeGreaterThan(0);
+ });
+
+ it('tolerates enrichment failures without sinking the section', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (sql.includes('schema_migrations')) throw new Error('relation does not exist');
+ if (sql.includes('pg_database_size')) throw new Error('nope');
+ if (sql.includes('information_schema.columns')) throw new Error('nope');
+ return happyQueries(sql);
+ });
+ const result = await getCityIntrospection();
+ expect(result.db.tables).toHaveLength(3);
+ expect(result.db.migrations).toBeNull();
+ expect(result.db.sizeBytes).toBeNull();
+ expect(result.db.tables.every((t) => t.hasEmbedding === false)).toBe(true);
+ });
+});
+
+describe('getCityIntrospection — fs section', () => {
+ it('walks domains recursively, rolls loose files into (root), sorts by size', async () => {
+ const { fs } = await getCityIntrospection();
+ expect(fs.domains.map((d) => d.name)).toEqual(['images', 'brain', '(root)']);
+ expect(fs.domains[0]).toEqual({ name: 'images', bytes: 8, files: 2 });
+ expect(fs.domains[1]).toEqual({ name: 'brain', bytes: 7, files: 1 });
+ expect(fs.domains[2]).toEqual({ name: '(root)', bytes: 2, files: 1 });
+ expect(fs.totalBytes).toBe(17);
+ expect(fs.totalFiles).toBe(4);
+ });
+
+ it('skips symlinked directories entirely', async () => {
+ const { fs } = await getCityIntrospection();
+ expect(fs.domains.find((d) => d.name === 'linked')).toBeUndefined();
+ });
+});
+
+describe('getCityIntrospection — cache discipline', () => {
+ it('serves the cached payload within the TTL without re-querying', async () => {
+ const first = await getCityIntrospection();
+ const callsAfterFirst = queryMock.mock.calls.length;
+ const second = await getCityIntrospection();
+ expect(second).toBe(first);
+ expect(queryMock.mock.calls.length).toBe(callsAfterFirst);
+ });
+
+ it('serves stale immediately past the TTL while revalidating in the background', async () => {
+ const first = await getCityIntrospection();
+ // Jump past the TTL without fake timers — the background rebuild does real
+ // (mocked-fs) I/O that fake timers can't flush.
+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + INTROSPECTION_TTL_MS + 1000);
+
+ // Make the rebuild distinguishable.
+ queryMock.mockImplementation(async (sql) => {
+ if (sql.includes('pg_database_size')) return { rows: [{ bytes: '777' }] };
+ return happyQueries(sql);
+ });
+
+ const stale = await getCityIntrospection();
+ expect(stale).toBe(first); // immediate stale answer, no blocking on the walk
+
+ // Once the background rebuild settles, the fresh payload is served.
+ await vi.waitFor(async () => {
+ expect((await getCityIntrospection()).db.sizeBytes).toBe(777);
+ });
+ vi.restoreAllMocks();
+ });
+});