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
fix([issue-877]): address claude+codex review
Adam Eivy01545fcdfc5d
diff --git a/server/services/apps.js b/server/services/apps.jsindex b94dd0906b..d58c695ef1 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -193,7 +193,7 @@ export async function getActiveApps() {* 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 }>>}+ * @returns {Promise<Array<{ id, name, type, repoPath, overallStatus, managed: boolean }>>}*/export async function getAppStatuses() {const apps = await getAllApps({ includeArchived: false });@@ -214,8 +214,12 @@ export async function getAppStatuses() {return apps.map(app => {const managed = usesPm2(app.type);+ // repoPath is carried so callers can map an agent's workspacePath back to its+ // app (the CyberCity snapshot's agent-assignment mapping, mirroring the+ // client's agentMap) without a second apps read.+ const base = { id: app.id, name: app.name, type: app.type, repoPath: app.repoPath };if (!managed) {- return { id: app.id, name: app.name, type: app.type, overallStatus: 'n/a', managed: false };+ return { ...base, overallStatus: 'n/a', managed: false };}const procMap = procMaps.get(app.pm2Home || null) || new Map();const names = app.pm2ProcessNames || [];@@ -226,7 +230,7 @@ export async function getAppStatuses() {else if (statuses.some(s => s === 'stopped')) overallStatus = 'stopped';else overallStatus = 'not_started';}- return { id: app.id, name: app.name, type: app.type, overallStatus, managed: true };+ return { ...base, overallStatus, managed: true };});}diff --git a/server/services/citysnapshots.js b/server/services/citysnapshots.jsindex 6f04e4112a..88760396ea 100644--- a/server/services/citysnapshots.js+++ b/server/services/citysnapshots.js@@ -29,6 +29,9 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { getSettings } from './settings.js';import * as apps from './apps.js';import * as cos from './cos.js';+import { getAgents } from './cosAgents.js';+import { getCosTasks } from './cosTaskStore.js';+import { getPendingCounts } from './review.js';import { getSelf, getPeers } from './instances.js';import * as backup from './backup.js';import { getCountsByType } from './notifications.js';@@ -39,6 +42,12 @@ import os from 'os';const DATA_DIR = PATHS.data;const SNAPSHOTS_FILE = join(DATA_DIR, 'city-snapshots.jsonl');+// Sentinel a getter falls back to when it throws — distinct from a successful+// empty read. `null` for object/array sources means "source unavailable at+// capture time" (CLAUDE.md's absent-vs-empty rule), so a transient failure+// never reads as a legitimate "zero apps / zero peers" in the history.+const FAILED = null;+// 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;@@ -87,70 +96,105 @@ async function loadSnapshots() {return snapshotCache;}+// Map a CoS agent to the app it's working in by matching its workspacePath+// against each app's repoPath — the same rule the client's `agentMap` uses.+// workspacePath may sit on the agent or in its metadata depending on spawn path.+function resolveAgentApp(agent, appStatuses) {+ const workspacePath = agent?.workspacePath || agent?.metadata?.workspacePath;+ if (!workspacePath || !Array.isArray(appStatuses)) return null;+ const match = appStatuses.find(a => a.repoPath && workspacePath.startsWith(a.repoPath));+ return match?.id ?? null;+}+/*** 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."+ * Each source is wrapped so one failing getter degrades to the `FAILED` (null)+ * sentinel rather than dropping the whole frame — a partial snapshot is more+ * useful to a scrubber than a missing one. Crucially, a thrown getter records+ * `null` (source unavailable), NOT an empty array / zero count, so a transient+ * failure can't masquerade as a legitimate "zero apps / zero peers" in the+ * history (CLAUDE.md's absent-vs-empty rule). Counts derived from a FAILED+ * source are likewise `null`, distinct from a real `0` on a successful read.*/async function buildSnapshot() {- const [appStatuses, cosStatus, self, peers, backupState, notifCounts, character, memStats] =+ const [appStatuses, cosStatus, agents, taskState, reviewCounts, 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),+ apps.getAppStatuses().catch(() => FAILED),+ cos.getStatus().catch(() => FAILED),+ getAgents().catch(() => FAILED),+ getCosTasks().catch(() => FAILED),+ getPendingCounts().catch(() => FAILED),+ getSelf().catch(() => FAILED),+ getPeers().catch(() => FAILED),+ backup.getState().catch(() => FAILED),+ getCountsByType().catch(() => FAILED),+ getCharacter().catch(() => FAILED),+ getMemoryStats().catch(() => FAILED),]);- const onlineApps = appStatuses.filter(a => a.overallStatus === 'online').length;- const onlinePeers = (peers || []).filter(p => p?.status === 'online').length;+ // Per-app state + agent→app assignments — the minimum a scrubber needs to+ // re-render buildings and diff adjacent frames for construction/teardown.+ // `null` (not `[]`) when the source failed, so the scrubber can skip vs. clear.+ const appsFrame = Array.isArray(appStatuses)+ ? appStatuses.map(a => ({ id: a.id, name: a.name, status: a.overallStatus }))+ : null;+ const assignmentsFrame = Array.isArray(agents)+ ? agents+ .filter(a => a?.status === 'running')+ .map(a => ({ agentId: a.id, appId: resolveAgentApp(a, appStatuses), status: a.status }))+ : null;++ const tasks = Array.isArray(taskState?.tasks) ? taskState.tasks : null;+ const taskCount = (status) => tasks === null ? null : tasks.filter(t => t?.status === status).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);+ // os.loadavg() returns [0,0,0] on Windows (no load average) — record null+ // there rather than a misleading 0% so it reads as "unavailable," not "idle."+ const cpuPercent = process.platform === 'win32'+ ? null+ : Math.min(100, Math.round((os.loadavg()[0] / (os.cpus().length || 1)) * 100));++ // Successful-empty reads yield real 0s; FAILED sources yield null.+ const onlineApps = appsFrame === null ? null : appsFrame.filter(a => a.status === 'online').length;+ const onlinePeers = peers === null ? null : peers.filter(p => p?.status === 'online').length;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 })),+ apps: appsFrame,+ assignments: assignmentsFrame,counts: {appsOnline: onlineApps,- appsTotal: appStatuses.length,- agentsActive: cosStatus?.activeAgents ?? 0,- agentsPaused: cosStatus?.pausedAgents ?? 0,- tasksCompleted: cosStatus?.stats?.tasksCompleted ?? 0,+ appsTotal: appsFrame === null ? null : appsFrame.length,+ agentsActive: cosStatus === null ? null : (cosStatus.activeAgents ?? 0),+ agentsPaused: cosStatus === null ? null : (cosStatus.pausedAgents ?? 0),+ tasksCompleted: cosStatus === null ? null : (cosStatus.stats?.tasksCompleted ?? 0),+ tasksPending: taskCount('pending'),+ tasksInProgress: taskCount('in_progress'),peersOnline: onlinePeers,- peersTotal: (peers || []).length,- notificationsUnread: notifCounts?.unread ?? 0,+ peersTotal: peers === null ? null : peers.length,+ notificationsUnread: notifCounts === null ? null : (notifCounts.unread ?? 0),+ reviewTotal: reviewCounts === null ? null : (reviewCounts.total ?? 0),},- cos: {- running: cosStatus?.running ?? false,- paused: cosStatus?.paused ?? false,+ cos: cosStatus === null ? null : {+ running: cosStatus.running ?? false,+ paused: cosStatus.paused ?? false,},- backup: {- status: backupState?.status ?? null,- lastRun: backupState?.lastRun ?? null,+ backup: backupState === null ? null : {+ status: backupState.status ?? null,+ lastRun: backupState.lastRun ?? null,},health: {- cpuPercent: Number.isFinite(cpuUsagePercent) ? cpuUsagePercent : null,+ cpuPercent,memPercent: memUsagePercent,},- character: {- level: character?.level ?? null,- },- instance: {- id: self?.instanceId ?? null,- name: self?.name ?? null,+ character: { level: character === null ? null : (character.level ?? null) },+ instance: self === null ? null : {+ id: self.instanceId ?? null,+ name: self.name ?? null,},};}@@ -164,9 +208,12 @@ async function buildSnapshot() {*/export async function captureSnapshot() {const frame = await buildSnapshot();- const { maxSnapshots } = await getSnapshotConfig();return queueSnapshotWrite(async () => {+ // Resolve the cap inside the queued turn so the trim reads the freshest+ // config alongside the persisted series (mirrors history.js keeping MAX in+ // its write path).+ const { maxSnapshots } = await getSnapshotConfig();const existing = await loadSnapshots();const next = [...existing, frame];diff --git a/server/services/citysnapshots.test.js b/server/services/citysnapshots.test.jsindex ad1612e6f8..c3d381da54 100644--- a/server/services/citysnapshots.test.js+++ b/server/services/citysnapshots.test.js@@ -21,6 +21,9 @@ describe('citysnapshots service', () => {vi.doUnmock('./settings.js');vi.doUnmock('./apps.js');vi.doUnmock('./cos.js');+ vi.doUnmock('./cosAgents.js');+ vi.doUnmock('./cosTaskStore.js');+ vi.doUnmock('./review.js');vi.doUnmock('./instances.js');vi.doUnmock('./backup.js');vi.doUnmock('./notifications.js');@@ -30,10 +33,15 @@ describe('citysnapshots service', () => {// 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 = {} } = {}) {+ async function loadService({ settings = {}, sources = {}, reject = [], 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);+ // A getter named in `reject` rejects (simulating a failed source) so the+ // service's .catch(() => FAILED) sentinel path is exercised.+ const mock = (key, value) => reject.includes(key)+ ? vi.fn().mockRejectedValue(new Error(`${key} unavailable`))+ : vi.fn().mockResolvedValue(value);vi.doMock('../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, PATHS: { ...actual.PATHS, data: dataDir }, ...fileOverrides };@@ -42,31 +50,45 @@ describe('citysnapshots service', () => {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 },+ getAppStatuses: mock('appStatuses', src('appStatuses', [+ { id: 'a1', name: 'App One', type: 'express', repoPath: '/repos/a1', overallStatus: 'online', managed: true },+ { id: 'a2', name: 'App Two', type: 'express', repoPath: '/repos/a2', overallStatus: 'stopped', managed: true },])),}));vi.doMock('./cos.js', () => ({- getStatus: vi.fn().mockResolvedValue(src('cosStatus', {+ getStatus: mock('cosStatus', src('cosStatus', {running: true, paused: false, activeAgents: 2, pausedAgents: 0,stats: { tasksCompleted: 7 },})),}));+ vi.doMock('./cosAgents.js', () => ({+ getAgents: mock('agents', src('agents', [+ { id: 'agent-1', status: 'running', workspacePath: '/repos/a1/sub' },+ { id: 'agent-2', status: 'completed', workspacePath: '/repos/a2' },+ ])),+ }));+ vi.doMock('./cosTaskStore.js', () => ({+ getCosTasks: mock('taskState', src('taskState', {+ tasks: [{ status: 'pending' }, { status: 'pending' }, { status: 'in_progress' }],+ })),+ }));+ vi.doMock('./review.js', () => ({+ getPendingCounts: mock('reviewCounts', src('reviewCounts', { total: 4, alert: 1, todo: 3 })),+ }));vi.doMock('./instances.js', () => ({- getSelf: vi.fn().mockResolvedValue(src('self', { instanceId: 'inst-1', name: 'void' })),- getPeers: vi.fn().mockResolvedValue(src('peers', [+ getSelf: mock('self', src('self', { instanceId: 'inst-1', name: 'void' })),+ getPeers: mock('peers', 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' })),+ getState: mock('backupState', 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: {} })),+ getCountsByType: mock('notifCounts', src('notifCounts', { total: 5, unread: 3, byType: {} })),}));vi.doMock('./character.js', () => ({- getCharacter: vi.fn().mockResolvedValue(src('character', { level: 4 })),+ getCharacter: mock('character', src('character', { level: 4 })),}));return import('./citysnapshots.js');}@@ -81,9 +103,14 @@ describe('citysnapshots service', () => {{ id: 'a1', name: 'App One', status: 'online' },{ id: 'a2', name: 'App Two', status: 'stopped' },]);+ // Only the running agent is captured, mapped to its app via repoPath prefix.+ expect(frame.assignments).toEqual([+ { agentId: 'agent-1', appId: 'a1', status: 'running' },+ ]);expect(frame.counts).toMatchObject({appsOnline: 1, appsTotal: 2, agentsActive: 2, tasksCompleted: 7,- peersOnline: 1, peersTotal: 2, notificationsUnread: 3,+ tasksPending: 2, tasksInProgress: 1,+ peersOnline: 1, peersTotal: 2, notificationsUnread: 3, reviewTotal: 4,});expect(frame.cos).toEqual({ running: true, paused: false });expect(frame.backup).toEqual({ status: 'success', lastRun: '2026-06-05T00:00:00.000Z' });@@ -132,18 +159,46 @@ describe('citysnapshots service', () => {}});- it('degrades a missing data source to a sentinel rather than dropping the frame', async () => {+ it('degrades a null 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 });+ expect(frame.backup).toBeNull();+ expect(frame.instance).toBeNull();// Frame still recorded despite missing sources.expect(readLines(snapshotsFile)).toHaveLength(1);});+ it('records null (not zero/empty) when a source throws, distinguishing failure from a real empty read', async () => {+ const svc = await loadService({ reject: ['appStatuses', 'peers', 'reviewCounts'] });+ const frame = await svc.captureSnapshot();++ // Failed array sources → null, NOT [] — so the scrubber can skip the frame+ // rather than rendering a transient outage as "all buildings demolished."+ expect(frame.apps).toBeNull();+ // Counts derived from a failed source are null, not a misleading 0.+ expect(frame.counts.appsOnline).toBeNull();+ expect(frame.counts.appsTotal).toBeNull();+ expect(frame.counts.peersOnline).toBeNull();+ expect(frame.counts.peersTotal).toBeNull();+ expect(frame.counts.reviewTotal).toBeNull();+ // Frame is still captured (partial > missing).+ expect(readLines(snapshotsFile)).toHaveLength(1);+ });++ it('distinguishes a real empty read (0) from a failed one (null)', async () => {+ const svc = await loadService({ sources: { appStatuses: [], peers: [], reviewCounts: { total: 0 } } });+ const frame = await svc.captureSnapshot();+ // Successful but empty → real zeros, not null.+ expect(frame.apps).toEqual([]);+ expect(frame.counts.appsOnline).toBe(0);+ expect(frame.counts.appsTotal).toBe(0);+ expect(frame.counts.peersOnline).toBe(0);+ expect(frame.counts.reviewTotal).toBe(0);+ });+it('getSnapshots honors limit (most-recent N) and since filters', async () => {const svc = await loadService();const frames = [];