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-877]): city-state snapshot capture pipeline
Adam Eivy284519c59ab0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5be479378b..e9779a9668 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,6 +15,7 @@- **[issue-715] "Why am I seeing this?" chips across Chief of Staff, Goals, and the dashboard** — The same provenance chip now appears wherever PortOS shows you something it derived rather than something you set. The Chief of Staff's actionable-insights banner explains how its top item was derived — a live count of your records (pending approvals, blocked tasks) reads as data-backed, while a success-rate-driven suggestion reads as inferred. A goal's detail panel marks its urgency and activity-budget readings as modeled from your health timeline and linked activities — not numbers you entered — so a derived reading never reads as a fact you stated. On the dashboard, the Proactive Alerts card declares its alerts are inferred from trends in your goals, costs, and system metrics, while the Decision Log card declares its entries are read straight from the ledger of choices the Chief of Staff actually made. Tap any chip for how it was derived and what would change it.- **[issue-952] Cinematic depth-of-field in City photo mode** — Photo mode now blurs the background for a cinematic look: whatever the current framing points at stays sharp while the rest of the city falls off softly, and each preset focuses on its own subject (the low-angle shot uses a shallower, more dramatic focus). It's on by default; toggle it with the "Depth" button in the photo bar or the D key, and your captured postcard matches what you see. Depth-of-field only runs while you're in photo mode, so the live dashboard is unaffected.- **[issue-912] Regenerate gallery images to defeat SynthID watermarks** — Generated images gain a "Regenerate" action in the lightbox, next to "Clean", whenever a local FLUX image generator is installed. The existing Clean only strips embedded provenance metadata and can't touch SynthID — Google's invisible per-pixel watermark — which survives by design. Regenerate is the honest defeat path: it round-trips the picture through a local FLUX model at low denoise so composition holds but the watermark signal is overwritten by fresh sampling. It runs entirely on-device, is never applied automatically, and saves the result as a new variant beside the original (which is kept); the lightbox's variant switch lets you toggle between the original and the regenerated copy.+- **[issue-877] City records its history for a future timeline scrubber** — The City now quietly snapshots its own state on a schedule (every 5 minutes by default), capturing which apps are online, how many agents are working, system health, and the other landmark readouts. These frames accumulate locally — never synced to peers — so an upcoming timeline view can let you scrub back and watch the city change over time. There's nothing to interact with yet; this is the recording groundwork. You can tune the capture interval, set how many frames to keep, or turn it off in settings.## Changeddiff --git a/data.reference/settings.json b/data.reference/settings.jsonindex 886b4de05a..40836dadb3 100644--- a/data.reference/settings.json+++ b/data.reference/settings.json@@ -45,5 +45,10 @@}},"vad": { "endOfSpeechMs": 700, "minUtteranceMs": 250 }+ },+ "citySnapshots": {+ "enabled": true,+ "intervalMinutes": 5,+ "maxSnapshots": 1000}}\ No newline at end of filediff --git a/docs/plans/2026-06-05-issue-877.md b/docs/plans/2026-06-05-issue-877.mdnew file mode 100644index 0000000000..062d5900d8--- /dev/null+++ b/docs/plans/2026-06-05-issue-877.md@@ -0,0 +1,136 @@+# Plan — CyberCity snapshot-capture pipeline (issue #877, prereq slice)++## Context++Issue #877 ("CyberCity 3.6 — historical timeline scrubber") asks for the ability to scrub+back through past city states, with buildings/landmarks animating in and out as you drag a+timeline. The issue is **explicitly blocked** on infrastructure that doesn't exist: the city+derives everything live (apps, agents, landmarks, counts) with **no persistence of past+state**, so there's nothing to replay.++Per the issue's own "Suggested approach," this is two slices:+1. **Prerequisite — snapshot capture** (this PR): periodically persist a compact city-state+ snapshot to a rolling, capped store, with enough resolution to later animate transitions.+2. **Scrubber UI** (deferred to a follow-up issue): the 3D HUD timeline control that loads the+ series and drives the scene from a past frame.++**Scope decided with the user:** ship slice 1 only — capture pipeline + rolling capped store ++read API — and file slice 2 as a new `plan`-labelled GitHub issue. Capture on a **fixed+interval (~5min) with a capped frame count** (mirrors the proven `history.jsonl` pattern).+Snapshots are **local-only** (each install's own derived state; no peer sync).++This unblocks #877 without a giant change and lets the scrubber get its own review cycle.++## Approach++A small, self-contained server feature that assembles a compact snapshot from existing+**server-side service getters** (no HTTP round-trip), appends it to a rolling capped JSONL+store, and exposes a read API. An interval scheduler drives periodic capture; the interval and+cap are user-configurable via the existing settings store. No migration is needed (brand-new+gitignored runtime file that self-caps); no peer-sync wiring.++### New files++- **`server/services/citysnapshots.js`** — the store + capture logic. Mirrors+ `server/services/history.js` (rolling JSONL, `MAX` cap, 2s cache, `createFileWriteQueue`).+ Exports:+ - `captureSnapshot()` — assemble a compact frame from server getters, append, trim to cap, return it.+ - `getSnapshots({ from, limit, since })` — read the series (for the future scrubber + API).+ - `getSnapshotConfig()` — resolve `{ enabled, intervalMinutes, maxSnapshots }` from settings with defaults.+ - File: `data/city-snapshots.jsonl` (via `PATHS.data`). Cache + write-queue exactly like `history.js`.+ - **Snapshot shape** (`{ ts, schemaVersion, ... }`) — compact, only what a frame needs to+ re-render: per-app `{ id, name, overallStatus, archived }`; agent assignments+ (`agentMap`-equivalent: `{ appId, agentId, status }[]`); landmark/counts+ (`apps: {online,total}`, `agents.active`, `peers.online`, `review` counts,+ `backup.status`, `health.overallHealth` + cpu/mem/disk %, `notifications.unread`,+ `character.level`, `tasks` counts). Carry an internal `schemaVersion: 1` so the future+ scrubber can gate on frame shape.+ - Assembled via `Promise.all` over: `apps.getAllApps`, `cos.getStatus` (agents + running),+ `cosTaskStore.getCosTasks`/`getAllTasks`, `instances.getSelf`/`getPeers`,+ `backup.getState`, `notifications.getUnreadCount`/`getCountsByType`, `character.getCharacter`,+ and the system-health helper. Each getter wrapped `.catch(() => fallback)` so one failing+ source degrades that field to a sentinel rather than dropping the whole frame+ (per CLAUDE.md "distinguish absent vs empty").++- **`server/services/citySnapshotScheduler.js`** — `startCitySnapshotScheduler()` /+ `stopCitySnapshotScheduler()`. Mirrors `backupScheduler.js` but uses+ `eventScheduler.schedule({ id: 'city-snapshot', type: 'interval', intervalMs, handler })`+ (eventScheduler supports `type:'interval'`, confirmed). Handler **re-reads settings each run**+ (so an `enabled:false` toggle takes effect without restart, like backupScheduler). No-op when+ disabled. Note in a code comment that, like backup's cron, the *interval value* is locked at+ registration — changing it needs a restart (acceptable; documented).++- **`server/routes/cityRoutes.js`** — `GET /api/city/snapshots` (list; Zod-validated query+ `{ limit?, since? }`), `POST /api/city/snapshots/capture` (capture-now, for manual/testing),+ `GET /api/city/snapshots/config`. Registered in `server/index.js` (`app.use('/api/city', …)`).+ No try/catch (errors bubble to middleware).++- **Tests** next to source: `server/services/citysnapshots.test.js` (capture shape, cap+ enforcement, config defaults, sentinel-on-failed-getter) and `server/routes/cityRoutes.test.js`+ (list/capture/config + query validation). Use `mockPathsDataRoot` for an isolated data dir.+ Mock the service getters; **does not** call `createUniverse`/`createSeries`, so no peer-sync+ mocking needed.++### Modified files++- **`server/index.js`** — import + register `cityRoutes`; import + call+ `startCitySnapshotScheduler()` at boot, right after `startBackupScheduler()`.+- **`server/lib/validation.js`** — add `citySnapshotConfigSchema`+ (`{ enabled?: bool, intervalMinutes?: int≥1, maxSnapshots?: int≥10 }`) and wire it into the+ `PUT /api/settings` slice validation (`.partial()` when the `citySnapshots` key is present,+ per the `backupConfigSchema.partial()` pattern in `server/routes/settings.js`).+- **`server/services/settings.js` / `data.reference/settings.json`** — seed default+ `citySnapshots: { enabled: true, intervalMinutes: 5, maxSnapshots: 1000 }` if the repo's+ settings seed is a structured JSON merged by `scripts/setup-data.js`. (Confirm during impl+ whether defaults live in code or the seed file; follow whichever the repo uses — no new+ migration since this is additive config with code-side defaults via `getSnapshotConfig()`.)++### Reuse (do not re-implement)++- `appendJSONLine` / `readJSONLines` / `writeJSONLines` / `atomicWrite` / `PATHS` — `server/lib/fileUtils.js`+- `createFileWriteQueue` — `server/lib/fileWriteQueue.js`+- `schedule` / `cancel` — `server/services/eventScheduler.js`+- `getSettings` — `server/services/settings.js`+- The whole rolling-store shape — copy `server/services/history.js` structure (cap + cache + queue).+- `validateRequest` + Zod schemas — `server/lib/validation.js`++### Explicitly NOT in this PR (deferred → new `plan` issue)++- The 3D scrubber HUD: timeline drag control, frame loading into the scene, diff-driven+ construction/teardown animations between adjacent frames, wiring snapshots into+ `useCityData` / `CityScene`. This is slice 2 and gets its own issue + review cycle.+- Client `apiCity.js` wrapper + `services/api.js` export — only add now if a test needs it;+ otherwise it lands with the scrubber PR that consumes it. (Lean: build the read API server-side+ now, consume it in the scrubber PR.)++## Migration / compat / changelog obligations++- **No migration** — `data/city-snapshots.jsonl` is brand-new gitignored runtime state that+ self-caps; nothing on disk changes shape.+- **Settings** — additive only; `getSnapshotConfig()` supplies defaults so older installs with+ no `citySnapshots` key work unchanged. Schema accepts absence.+- **No NAV_COMMANDS entry** — no new navigable page in this slice (the scrubber, when built,+ lives inside the existing `/cybercity` route, so still none).+- **Changelog** — add a one-line user-facing entry to `.changelog/NEXT.md` under the+ `[issue-877]` slug (e.g. "CyberCity now records periodic snapshots of city state so a future+ timeline view can replay history").++## Verification++1. **Unit tests:** `cd server && npm test -- citysnapshots` and `… -- cityRoutes` — assert+ capture shape, cap trimming (write `maxSnapshots+N`, expect last `maxSnapshots`), config+ defaults, and a failed-getter degrading to a sentinel field (not a dropped frame).+2. **Full server suite:** `cd server && npm test` — confirm no regressions and the+ barrel/README enforcement tests pass (new public modules wired into any required index/README).+3. **Manual end-to-end:** start the server, `curl -s :5553/api/city/snapshots/config` (loopback+ HTTP mirror) shows defaults; `curl -X POST :5553/api/city/snapshots/capture` returns a frame;+ `curl :5553/api/city/snapshots?limit=5` lists it; confirm `data/city-snapshots.jsonl` grew by+ one line. Optionally lower `intervalMinutes` and confirm the scheduler appends a frame on tick.++## Follow-up issue to file (Phase 4/6)++`gh issue create --label plan` — "CyberCity 3.6 (scrubber slice) — timeline HUD that replays+city-state snapshots" — referencing #877, describing: load the snapshot series from+`GET /api/city/snapshots`, a HUD timeline drag control, and diff-adjacent-frames to animate+buildings/landmarks in/out (construction/teardown). Note the capture pipeline (this PR) is the+unblocking prerequisite.diff --git a/server/index.js b/server/index.jsindex a4916ee143..b9281b5627 100644--- a/server/index.js+++ b/server/index.js@@ -69,6 +69,7 @@ import dataManagerRoutes from './routes/dataManager.js';import jiraRoutes from './routes/jira.js';import autobiographyRoutes from './routes/autobiography.js';import backupRoutes from './routes/backup.js';+import cityRoutes from './routes/cityRoutes.js';import databaseRoutes from './routes/database.js';import localLlmRoutes from './routes/localLlm.js';import codeReviewRoutes from './routes/codeReview.js';@@ -137,6 +138,7 @@ import * as automationScheduler from './services/automationScheduler.js';import * as agentActionExecutor from './services/agentActionExecutor.js';import * as cos from './services/cos.js';import { startBackupScheduler } from './services/backupScheduler.js';+import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';import * as telegram from './services/telegram.js';import * as telegramBridge from './services/telegramBridge.js';import { getSettings as getInitSettings, settingsEvents } from './services/settings.js';@@ -424,6 +426,7 @@ app.use('/api/media/annotations', mediaAnnotationsRoutes);app.use('/api/attachments', attachmentsRoutes);app.use('/api/client-errors', clientErrorsRoutes);app.use('/api/backup', backupRoutes);+app.use('/api/city', cityRoutes);app.use('/api/database', databaseRoutes);app.use('/api/uploads', uploadsRoutes);app.use('/api/image-clean', imageCleanRoutes);@@ -534,6 +537,9 @@ initBrainMemoryBridge();initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: ${err.message}`));// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));+// Initialize CyberCity snapshot scheduler — records periodic city-state frames+// for the historical timeline scrubber (issue #877).+startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot scheduler init failed: ${err.message}`));// Periodically GC orphan zero-issue/zero-canon importer shells left by an// abandoned analyze (issue #727).startOrphanShellGc();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1646335f46..96c05a1603 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -795,6 +795,23 @@ export const restoreRequestSchema = z.object({dryRun: z.boolean().optional().default(true)});+// CyberCity snapshot pipeline (issue #877): how often to capture a city-state+// frame and how many to retain. Validated as a settings slice on PUT /api/settings;+// service-side defaults (DEFAULT_SNAPSHOT_CONFIG) fill any absent field so an+// install with no `citySnapshots` key still captures.+export const citySnapshotConfigSchema = z.object({+ enabled: z.boolean().optional(),+ intervalMinutes: z.number().int().min(1).max(1440).optional(),+ maxSnapshots: z.number().int().min(10).max(100000).optional()+});++// Query for GET /api/city/snapshots — `since` (ISO timestamp) and `limit`+// (most-recent N) both arrive as strings on the query string.+export const citySnapshotsQuerySchema = z.object({+ since: z.string().datetime().optional(),+ limit: z.coerce.number().int().min(1).max(100000).optional()+});+// Per-feature AI provider assignment: which configured CLI provider/model a// feature runs through (e.g. `settings.autofixer`, `settings.calendarSync`).// Empty string (UI "unset" sentinel) is coerced to undefined so it round-tripsdiff --git a/server/routes/cityRoutes.js b/server/routes/cityRoutes.jsnew file mode 100644index 0000000000..0a203a49f8--- /dev/null+++ b/server/routes/cityRoutes.js@@ -0,0 +1,32 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest, citySnapshotsQuerySchema } from '../lib/validation.js';+import {+ captureSnapshot,+ getSnapshots,+ getSnapshotConfig,+} from '../services/citysnapshots.js';+import { getNextSnapshotTime } from '../services/citySnapshotScheduler.js';++const router = Router();++// GET /api/city/snapshots — the recorded city-state series, oldest-first.+// A future timeline scrubber loads this and drives the 3D scene from a frame.+router.get('/snapshots', asyncHandler(async (req, res) => {+ const { since, limit } = validateRequest(citySnapshotsQuerySchema, req.query);+ res.json(await getSnapshots({ since, limit }));+}));++// POST /api/city/snapshots/capture — capture a frame on demand (manual /+// testing trigger; the scheduler drives the periodic captures).+router.post('/snapshots/capture', asyncHandler(async (req, res) => {+ res.json(await captureSnapshot());+}));++// GET /api/city/snapshots/config — effective capture config + next run time.+router.get('/snapshots/config', asyncHandler(async (req, res) => {+ const config = await getSnapshotConfig();+ res.json({ ...config, nextRun: getNextSnapshotTime() });+}));++export default router;diff --git a/server/routes/cityRoutes.test.js b/server/routes/cityRoutes.test.jsnew file mode 100644index 0000000000..887f5cee88--- /dev/null+++ b/server/routes/cityRoutes.test.js@@ -0,0 +1,88 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Mock the service layer — these route tests verify routing + query validation,+// not the capture/store logic (covered in citysnapshots.test.js).+const captureSnapshot = vi.fn();+const getSnapshots = vi.fn();+const getSnapshotConfig = vi.fn();+const getNextSnapshotTime = vi.fn();++vi.mock('../services/citysnapshots.js', () => ({+ captureSnapshot: (...a) => captureSnapshot(...a),+ getSnapshots: (...a) => getSnapshots(...a),+ getSnapshotConfig: (...a) => getSnapshotConfig(...a),+}));+vi.mock('../services/citySnapshotScheduler.js', () => ({+ getNextSnapshotTime: (...a) => getNextSnapshotTime(...a),+}));++const { default: cityRoutes } = await import('./cityRoutes.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/city', cityRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('city snapshot routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getSnapshots.mockResolvedValue({ total: 0, snapshots: [] });+ getSnapshotConfig.mockResolvedValue({ enabled: true, intervalMinutes: 5, maxSnapshots: 1000 });+ getNextSnapshotTime.mockReturnValue('2026-06-05T12:00:00.000Z');+ captureSnapshot.mockResolvedValue({ ts: '2026-06-05T11:55:00.000Z', schemaVersion: 1, counts: {} });+ });++ describe('GET /api/city/snapshots', () => {+ it('returns the series with no query params', async () => {+ getSnapshots.mockResolvedValue({ total: 2, snapshots: [{ ts: 'a' }, { ts: 'b' }] });+ const res = await request(makeApp()).get('/api/city/snapshots');+ expect(res.status).toBe(200);+ expect(res.body.total).toBe(2);+ expect(getSnapshots).toHaveBeenCalledWith({ since: undefined, limit: undefined });+ });++ it('coerces limit and passes a valid since through', async () => {+ const res = await request(makeApp()).get('/api/city/snapshots?limit=10&since=2026-06-01T00:00:00.000Z');+ expect(res.status).toBe(200);+ expect(getSnapshots).toHaveBeenCalledWith({ since: '2026-06-01T00:00:00.000Z', limit: 10 });+ });++ it('rejects a non-numeric limit', async () => {+ const res = await request(makeApp()).get('/api/city/snapshots?limit=abc');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('rejects a malformed since timestamp', async () => {+ const res = await request(makeApp()).get('/api/city/snapshots?since=not-a-date');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });+ });++ describe('POST /api/city/snapshots/capture', () => {+ it('captures a frame on demand', async () => {+ const res = await request(makeApp()).post('/api/city/snapshots/capture');+ expect(res.status).toBe(200);+ expect(res.body.schemaVersion).toBe(1);+ expect(captureSnapshot).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');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({+ enabled: true, intervalMinutes: 5, maxSnapshots: 1000,+ nextRun: '2026-06-05T12:00:00.000Z',+ });+ });+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 5a1df554a0..1b019889ae 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -9,7 +9,7 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, validateRequest } from '../lib/validation.js';import { catalogUserTypesSettingsSchema } from '../lib/catalogValidation.js';const router = Router();@@ -92,6 +92,11 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.embeddings !== undefined) {validateRequest(settingsEmbeddingsSchema.partial(), req.body.embeddings);}+ // CyberCity snapshot capture config — validate the slice when present so a+ // malformed interval/cap can't reach disk and break the scheduler.+ if (req.body?.citySnapshots !== undefined) {+ validateRequest(citySnapshotConfigSchema.partial(), req.body.citySnapshots);+ }// User-defined catalog types — validate the whole slice (unique-id +// system-collision refinements) when the key is present, mirroring the// backup/embeddings slice guards above. The catalog `/types` routes are thediff --git a/server/services/apps.js b/server/services/apps.jsindex e53aabdb36..b94dd0906b 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -183,18 +183,27 @@ export async function getActiveApps() {* are reported separately under `unmanaged` so callers can show context* without inflating the running denominator.*/-export async function getAppStatusSummary() {+/**+ * Resolve each active app's overall PM2 status in one pass.+ *+ * Returns one entry per active app — PM2-runnable apps carry a derived+ * `overallStatus` of `online` / `stopped` / `not_started`; native projects+ * (Xcode, iOS, macOS) report `n/a` since they have no detectable runtime.+ * Each unique PM2_HOME is queried at most once. This is the shared primitive+ * behind both `getAppStatusSummary()` (counts) and the CyberCity snapshot+ * pipeline (per-building status), so the two never drift.+ *+ * @returns {Promise<Array<{ id, name, type, overallStatus, managed: boolean }>>}+ */+export async function getAppStatuses() {const apps = await getAllApps({ includeArchived: false });- const pm2Apps = apps.filter(a => usesPm2(a.type));- const unmanaged = apps.length - pm2Apps.length;-- // Group by pm2Home so each unique home is queried at most once+ // Group PM2 apps by pm2Home so each unique home is queried at most once.const homeGroups = new Map();- for (const app of pm2Apps) {+ for (const app of apps) {+ if (!usesPm2(app.type)) continue;const home = app.pm2Home || null;- if (!homeGroups.has(home)) homeGroups.set(home, []);- homeGroups.get(home).push(app);+ if (!homeGroups.has(home)) homeGroups.set(home, true);}const procMaps = new Map();@@ -203,28 +212,34 @@ export async function getAppStatusSummary() {procMaps.set(home, new Map(procs.map(p => [p.name, p])));}- let online = 0;- let stopped = 0;- let notStarted = 0;- for (const app of pm2Apps) {+ return apps.map(app => {+ const managed = usesPm2(app.type);+ if (!managed) {+ return { id: app.id, name: app.name, type: app.type, overallStatus: 'n/a', managed: false };+ }const procMap = procMaps.get(app.pm2Home || null) || new Map();const names = app.pm2ProcessNames || [];- if (names.length === 0) {- notStarted++;- continue;+ let overallStatus = 'not_started';+ if (names.length > 0) {+ const statuses = names.map(n => procMap.get(n)?.status || 'not_found');+ if (statuses.some(s => s === 'online')) overallStatus = 'online';+ else if (statuses.some(s => s === 'stopped')) overallStatus = 'stopped';+ else overallStatus = 'not_started';}- const statuses = names.map(n => procMap.get(n)?.status || 'not_found');- if (statuses.some(s => s === 'online')) online++;- else if (statuses.some(s => s === 'stopped')) stopped++;- else notStarted++;- }+ return { id: app.id, name: app.name, type: app.type, overallStatus, managed: true };+ });+}++export async function getAppStatusSummary() {+ const statuses = await getAppStatuses();+ const managed = statuses.filter(s => s.managed);return {- total: pm2Apps.length,- online,- stopped,- notStarted,- unmanaged+ total: managed.length,+ online: managed.filter(s => s.overallStatus === 'online').length,+ stopped: managed.filter(s => s.overallStatus === 'stopped').length,+ notStarted: managed.filter(s => s.overallStatus === 'not_started').length,+ unmanaged: statuses.length - managed.length};}diff --git a/server/services/citySnapshotScheduler.js b/server/services/citySnapshotScheduler.jsnew file mode 100644index 0000000000..db56e07734--- /dev/null+++ b/server/services/citySnapshotScheduler.js@@ -0,0 +1,66 @@+/**+ * CyberCity Snapshot Scheduler+ *+ * Registers an interval job that periodically captures a CyberCity state+ * snapshot (see citysnapshots.js). Mirrors the backupScheduler.js pattern.+ *+ * Like the backup scheduler's cron expression, the *interval value* is locked+ * in at registration — changing `intervalMinutes` requires a restart. But the+ * `enabled` toggle is re-read inside the handler on every run, so disabling+ * capture from settings takes effect on the next tick without a restart.+ */++import { schedule, cancel, getEvent } from './eventScheduler.js';+import { captureSnapshot, getSnapshotConfig } from './citysnapshots.js';++const EVENT_ID = 'city-snapshot';++/**+ * Start the snapshot scheduler. No-ops if disabled in settings.+ */+export async function startCitySnapshotScheduler() {+ const { enabled, intervalMinutes } = await getSnapshotConfig();++ if (!enabled) {+ console.log('🏙️ City snapshot scheduler: disabled in settings — skipping');+ return;+ }++ const intervalMs = intervalMinutes * 60 * 1000;++ schedule({+ id: EVENT_ID,+ type: 'interval',+ intervalMs,+ handler: async () => {+ // Re-read settings each run so an `enabled: false` toggle takes effect+ // without a restart (the interval value itself is locked at registration).+ const current = await getSnapshotConfig();+ if (!current.enabled) {+ console.log('🏙️ City snapshot scheduler: disabled since registration — skipping run');+ return;+ }+ const frame = await captureSnapshot();+ console.log(`🏙️ City snapshot captured: ${frame.counts.appsOnline}/${frame.counts.appsTotal} apps online, ${frame.counts.agentsActive} agents active`);+ },+ metadata: { source: 'citySnapshotScheduler' },+ });++ console.log(`🏙️ City snapshot scheduler: registered every ${intervalMinutes}min`);+}++/**+ * Stop the snapshot scheduler.+ */+export function stopCitySnapshotScheduler() {+ cancel(EVENT_ID);+ console.log('🏙️ City snapshot scheduler: stopped');+}++/**+ * ISO timestamp of the next scheduled capture, or null if not scheduled.+ */+export function getNextSnapshotTime() {+ const event = getEvent(EVENT_ID);+ return event?.nextRunAt ? new Date(event.nextRunAt).toISOString() : null;+}diff --git a/server/services/citysnapshots.js b/server/services/citysnapshots.jsnew file mode 100644index 0000000000..6f04e4112a--- /dev/null+++ b/server/services/citysnapshots.js@@ -0,0 +1,214 @@+/**+ * CyberCity Snapshot Store+ *+ * Periodically captures a compact snapshot of the CyberCity's derived state+ * (per-app status, agent activity, landmark counts, system health) to a+ * rolling, capped JSONL store. This is the prerequisite slice for the roadmap+ * 3.6 "historical timeline scrubber" (issue #877): the city derives everything+ * live with no persistence of past state, so there is nothing to scrub to until+ * snapshots accumulate. A future scrubber UI loads this series and drives the+ * 3D scene from a past frame.+ *+ * Snapshots are local-only — each install records its own derived state and+ * never syncs to federated peers.+ *+ * Storage mirrors the proven rolling-JSONL pattern in `history.js`: append on+ * the hot path, compact (rewrite) only when the cap is exceeded, 2s read cache,+ * and a single write-queue tail so concurrent captures can't interleave.+ */++import { join } from 'path';+import {+ appendJSONLine,+ ensureDir,+ PATHS,+ readJSONLines,+ writeJSONLines,+} from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { getSettings } from './settings.js';+import * as apps from './apps.js';+import * as cos from './cos.js';+import { getSelf, getPeers } from './instances.js';+import * as backup from './backup.js';+import { getCountsByType } from './notifications.js';+import { getCharacter } from './character.js';+import { getMemoryStats } from '../lib/memoryStats.js';+import os from 'os';++const DATA_DIR = PATHS.data;+const SNAPSHOTS_FILE = join(DATA_DIR, 'city-snapshots.jsonl');++// Bump when the snapshot shape changes incompatibly so a future scrubber can+// gate on frame shape and skip / migrate older frames rather than mis-render.+export const SNAPSHOT_SCHEMA_VERSION = 1;++// Config defaults — surfaced via getSnapshotConfig() so installs with no+// `citySnapshots` settings key behave sanely without a migration.+export const DEFAULT_SNAPSHOT_CONFIG = {+ enabled: true,+ intervalMinutes: 5,+ maxSnapshots: 1000, // ~3.5 days at the 5-minute default+};++// In-memory cache with TTL (mirrors history.js).+let snapshotCache = null;+let cacheTimestamp = 0;+const CACHE_TTL_MS = 2000;+const queueSnapshotWrite = createFileWriteQueue();++/**+ * Resolve the effective snapshot config, layering the user's settings slice+ * over the defaults. Hand-edited / partial settings degrade to defaults+ * field-by-field rather than disabling capture wholesale.+ */+export async function getSnapshotConfig() {+ const settings = await getSettings().catch(() => ({}));+ const c = settings?.citySnapshots || {};+ return {+ enabled: typeof c.enabled === 'boolean' ? c.enabled : DEFAULT_SNAPSHOT_CONFIG.enabled,+ intervalMinutes: Number.isFinite(c.intervalMinutes) && c.intervalMinutes >= 1+ ? Math.floor(c.intervalMinutes)+ : DEFAULT_SNAPSHOT_CONFIG.intervalMinutes,+ maxSnapshots: Number.isFinite(c.maxSnapshots) && c.maxSnapshots >= 10+ ? Math.floor(c.maxSnapshots)+ : DEFAULT_SNAPSHOT_CONFIG.maxSnapshots,+ };+}++async function loadSnapshots() {+ const now = Date.now();+ if (snapshotCache && (now - cacheTimestamp) < CACHE_TTL_MS) {+ return snapshotCache;+ }+ await ensureDir(DATA_DIR);+ snapshotCache = await readJSONLines(SNAPSHOTS_FILE, { logErrors: true });+ cacheTimestamp = now;+ return snapshotCache;+}++/**+ * Assemble a compact city-state frame from server-side service getters.+ *+ * Each source is wrapped so one failing getter degrades that field to a+ * sentinel (null / empty) rather than dropping the whole frame — a partial+ * snapshot is more useful to a scrubber than a missing one, and a captured+ * `null` distinguishes "source unavailable at capture time" from "absent."+ */+async function buildSnapshot() {+ const [appStatuses, cosStatus, self, peers, backupState, notifCounts, character, memStats] =+ await Promise.all([+ apps.getAppStatuses().catch(() => []),+ cos.getStatus().catch(() => null),+ getSelf().catch(() => null),+ getPeers().catch(() => []),+ backup.getState().catch(() => null),+ getCountsByType().catch(() => null),+ getCharacter().catch(() => null),+ getMemoryStats().catch(() => null),+ ]);++ const onlineApps = appStatuses.filter(a => a.overallStatus === 'online').length;+ const onlinePeers = (peers || []).filter(p => p?.status === 'online').length;++ const memUsagePercent = memStats && memStats.total > 0+ ? Math.round((memStats.used / memStats.total) * 100)+ : null;+ const cpuCount = os.cpus().length || 1;+ const cpuUsagePercent = Math.round((os.loadavg()[0] / cpuCount) * 100);++ return {+ ts: new Date().toISOString(),+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,+ // Per-building state — the minimum a scrubber needs to re-render and+ // diff adjacent frames for construction/teardown animations.+ apps: appStatuses.map(a => ({ id: a.id, name: a.name, status: a.overallStatus })),+ counts: {+ appsOnline: onlineApps,+ appsTotal: appStatuses.length,+ agentsActive: cosStatus?.activeAgents ?? 0,+ agentsPaused: cosStatus?.pausedAgents ?? 0,+ tasksCompleted: cosStatus?.stats?.tasksCompleted ?? 0,+ peersOnline: onlinePeers,+ peersTotal: (peers || []).length,+ notificationsUnread: notifCounts?.unread ?? 0,+ },+ cos: {+ running: cosStatus?.running ?? false,+ paused: cosStatus?.paused ?? false,+ },+ backup: {+ status: backupState?.status ?? null,+ lastRun: backupState?.lastRun ?? null,+ },+ health: {+ cpuPercent: Number.isFinite(cpuUsagePercent) ? cpuUsagePercent : null,+ memPercent: memUsagePercent,+ },+ character: {+ level: character?.level ?? null,+ },+ instance: {+ id: self?.instanceId ?? null,+ name: self?.name ?? null,+ },+ };+}++/**+ * Capture a snapshot now: build the frame, append it, and enforce the cap.+ * Serialized on the write queue so a scheduled capture and a manual+ * `POST /capture` can't interleave their read-modify-write.+ *+ * @returns {Promise<object>} the captured snapshot frame+ */+export async function captureSnapshot() {+ const frame = await buildSnapshot();+ const { maxSnapshots } = await getSnapshotConfig();++ return queueSnapshotWrite(async () => {+ const existing = await loadSnapshots();+ const next = [...existing, frame];++ if (next.length > maxSnapshots) {+ // Over cap: rewrite the file with the trailing window (drops oldest).+ const trimmed = next.slice(-maxSnapshots);+ await ensureDir(DATA_DIR);+ await writeJSONLines(SNAPSHOTS_FILE, trimmed);+ snapshotCache = trimmed;+ } else {+ await appendJSONLine(SNAPSHOTS_FILE, frame);+ snapshotCache = next;+ }+ cacheTimestamp = Date.now();+ return frame;+ });+}++/**+ * Read the snapshot series, oldest-first (chronological — a scrubber drags+ * left→right through time).+ *+ * @param {object} [options]+ * @param {number} [options.limit] - return only the most recent N frames+ * @param {string} [options.since] - ISO timestamp; return only frames at/after it+ * @returns {Promise<{ total: number, snapshots: Array }>}+ */+export async function getSnapshots({ limit, since } = {}) {+ const all = await loadSnapshots();+ let frames = all;++ if (since) {+ const sinceMs = Date.parse(since);+ if (Number.isFinite(sinceMs)) {+ frames = frames.filter(f => Date.parse(f.ts) >= sinceMs);+ }+ }++ const total = frames.length;+ if (Number.isFinite(limit) && limit >= 0 && limit < frames.length) {+ frames = frames.slice(-limit); // most-recent N, still chronological+ }++ return { total, snapshots: frames };+}diff --git a/server/services/citysnapshots.test.js b/server/services/citysnapshots.test.jsnew file mode 100644index 0000000000..ad1612e6f8--- /dev/null+++ b/server/services/citysnapshots.test.js@@ -0,0 +1,167 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';++const readLines = (path) =>+ readFileSync(path, 'utf-8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line));++describe('citysnapshots service', () => {+ let dataDir;+ let snapshotsFile;++ beforeEach(() => {+ vi.resetModules();+ dataDir = mkdtempSync(join(tmpdir(), 'portos-citysnap-'));+ snapshotsFile = join(dataDir, 'city-snapshots.jsonl');+ });++ afterEach(() => {+ vi.doUnmock('../lib/fileUtils.js');+ vi.doUnmock('./settings.js');+ vi.doUnmock('./apps.js');+ vi.doUnmock('./cos.js');+ vi.doUnmock('./instances.js');+ vi.doUnmock('./backup.js');+ vi.doUnmock('./notifications.js');+ vi.doUnmock('./character.js');+ rmSync(dataDir, { recursive: true, force: true });+ });++ // Load the service with the data dir redirected and all data-source services+ // mocked. `sources`/`settings` overrides let individual tests vary inputs.+ async function loadService({ settings = {}, sources = {}, fileOverrides = {} } = {}) {+ // Honor an explicitly-provided override (including `null`) over the default;+ // `key in sources` distinguishes "not provided" from "provided as null".+ const src = (key, fallback) => (key in sources ? sources[key] : fallback);+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: dataDir }, ...fileOverrides };+ });+ vi.doMock('./settings.js', () => ({+ getSettings: vi.fn().mockResolvedValue(settings),+ }));+ vi.doMock('./apps.js', () => ({+ getAppStatuses: vi.fn().mockResolvedValue(src('appStatuses', [+ { id: 'a1', name: 'App One', type: 'express', overallStatus: 'online', managed: true },+ { id: 'a2', name: 'App Two', type: 'express', overallStatus: 'stopped', managed: true },+ ])),+ }));+ vi.doMock('./cos.js', () => ({+ getStatus: vi.fn().mockResolvedValue(src('cosStatus', {+ running: true, paused: false, activeAgents: 2, pausedAgents: 0,+ stats: { tasksCompleted: 7 },+ })),+ }));+ vi.doMock('./instances.js', () => ({+ getSelf: vi.fn().mockResolvedValue(src('self', { instanceId: 'inst-1', name: 'void' })),+ getPeers: vi.fn().mockResolvedValue(src('peers', [+ { status: 'online' }, { status: 'offline' },+ ])),+ }));+ vi.doMock('./backup.js', () => ({+ getState: vi.fn().mockResolvedValue(src('backupState', { status: 'success', lastRun: '2026-06-05T00:00:00.000Z' })),+ }));+ vi.doMock('./notifications.js', () => ({+ getCountsByType: vi.fn().mockResolvedValue(src('notifCounts', { total: 5, unread: 3, byType: {} })),+ }));+ vi.doMock('./character.js', () => ({+ getCharacter: vi.fn().mockResolvedValue(src('character', { level: 4 })),+ }));+ return import('./citysnapshots.js');+ }++ it('captures a compact frame and appends it as JSONL', async () => {+ const svc = await loadService();+ const frame = await svc.captureSnapshot();++ expect(frame.schemaVersion).toBe(svc.SNAPSHOT_SCHEMA_VERSION);+ expect(typeof frame.ts).toBe('string');+ expect(frame.apps).toEqual([+ { id: 'a1', name: 'App One', status: 'online' },+ { id: 'a2', name: 'App Two', status: 'stopped' },+ ]);+ expect(frame.counts).toMatchObject({+ appsOnline: 1, appsTotal: 2, agentsActive: 2, tasksCompleted: 7,+ peersOnline: 1, peersTotal: 2, notificationsUnread: 3,+ });+ expect(frame.cos).toEqual({ running: true, paused: false });+ expect(frame.backup).toEqual({ status: 'success', lastRun: '2026-06-05T00:00:00.000Z' });+ expect(frame.character).toEqual({ level: 4 });+ expect(frame.instance).toEqual({ id: 'inst-1', name: 'void' });++ expect(existsSync(snapshotsFile)).toBe(true);+ expect(readLines(snapshotsFile)).toHaveLength(1);+ });++ it('resolves config defaults when settings absent, and overrides when present', async () => {+ const svcDefault = await loadService();+ expect(await svcDefault.getSnapshotConfig()).toEqual(svcDefault.DEFAULT_SNAPSHOT_CONFIG);++ vi.resetModules();+ const svcCustom = await loadService({+ settings: { citySnapshots: { enabled: false, intervalMinutes: 15, maxSnapshots: 50 } },+ });+ expect(await svcCustom.getSnapshotConfig()).toEqual({ enabled: false, intervalMinutes: 15, maxSnapshots: 50 });+ });++ it('falls back to defaults field-by-field for invalid settings values', async () => {+ const svc = await loadService({+ settings: { citySnapshots: { enabled: 'yes', intervalMinutes: 0, maxSnapshots: 5 } },+ });+ // enabled non-boolean → default true; intervalMinutes <1 → default; maxSnapshots <10 → default+ expect(await svc.getSnapshotConfig()).toEqual(svc.DEFAULT_SNAPSHOT_CONFIG);+ });++ it('enforces the maxSnapshots cap by dropping the oldest frames', async () => {+ const svc = await loadService({ settings: { citySnapshots: { maxSnapshots: 10 } } });++ for (let i = 0; i < 13; i += 1) {+ await svc.captureSnapshot();+ }++ const lines = readLines(snapshotsFile);+ expect(lines).toHaveLength(10);++ const { total, snapshots } = await svc.getSnapshots();+ expect(total).toBe(10);+ expect(snapshots).toHaveLength(10);+ // Chronological (oldest-first) and timestamps non-decreasing.+ for (let i = 1; i < snapshots.length; i += 1) {+ expect(Date.parse(snapshots[i].ts)).toBeGreaterThanOrEqual(Date.parse(snapshots[i - 1].ts));+ }+ });++ it('degrades a missing data source to a sentinel rather than dropping the frame', async () => {+ const svc = await loadService({+ sources: { character: null, backupState: null, self: null },+ });+ const frame = await svc.captureSnapshot();+ expect(frame.character).toEqual({ level: null });+ expect(frame.backup).toEqual({ status: null, lastRun: null });+ expect(frame.instance).toEqual({ id: null, name: null });+ // Frame still recorded despite missing sources.+ expect(readLines(snapshotsFile)).toHaveLength(1);+ });++ it('getSnapshots honors limit (most-recent N) and since filters', async () => {+ const svc = await loadService();+ const frames = [];+ for (let i = 0; i < 5; i += 1) frames.push(await svc.captureSnapshot());++ const limited = await svc.getSnapshots({ limit: 2 });+ expect(limited.total).toBe(5);+ expect(limited.snapshots).toHaveLength(2);+ expect(limited.snapshots[1].ts).toBe(frames[4].ts);++ const since = frames[3].ts;+ const sinceResult = await svc.getSnapshots({ since });+ expect(sinceResult.snapshots.every(f => Date.parse(f.ts) >= Date.parse(since))).toBe(true);+ });++ it('serializes concurrent captures so none are lost', async () => {+ const svc = await loadService();+ await Promise.all(Array.from({ length: 12 }, () => svc.captureSnapshot()));+ expect(readLines(snapshotsFile)).toHaveLength(12);+ });+});