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

8.6 KB
Raw Blame

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.