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
refactor([issue-875]): extract shared CyberCity district layout helpers
[._.]/ Adam Eivycc2db316a4e6
diff --git a/client/src/components/city/cityLayout.js b/client/src/components/city/cityLayout.jsindex bf834b2fc0..2195673643 100644--- a/client/src/components/city/cityLayout.js+++ b/client/src/components/city/cityLayout.js@@ -1,4 +1,5 @@import { BUILDING_PARAMS, DISTRICT_PARAMS } from './cityConstants';+import { autoColumns, gridIndexToPosition } from '../../utils/cityDistrictLayout';const STATUS_ORDER = { online: 0, stopped: 1, not_started: 2, not_found: 3 };@@ -20,36 +21,27 @@ export const computeCityLayout = (apps) => {const positions = new Map();const { spacing } = BUILDING_PARAMS;- // Downtown district (active apps) centered at origin- const activeCols = Math.max(1, Math.ceil(Math.sqrt(active.length)));+ // Downtown district (active apps): a roughly-square grid centered on the origin (both axes).+ const activeCols = autoColumns(active.length);const activeRows = Math.ceil(active.length / activeCols);- const activeOffsetX = ((activeCols - 1) * spacing) / 2;- const activeOffsetZ = ((activeRows - 1) * spacing) / 2;active.forEach((app, i) => {- const col = i % activeCols;- const row = Math.floor(i / activeCols);- positions.set(app.id, {- x: col * spacing - activeOffsetX,- z: row * spacing - activeOffsetZ,- district: 'downtown',- });+ const [x, , z] = gridIndexToPosition(i, { columns: activeCols, spacing, rowCount: activeRows });+ positions.set(app.id, { x, z, district: 'downtown' });});- // Warehouse district (archived apps) offset along +Z+ // Warehouse district (archived apps): X-centered grid offset along +Z from downtown.if (archived.length > 0) {- const archiveCols = Math.max(1, Math.ceil(Math.sqrt(archived.length)));- const archiveOffsetX = ((archiveCols - 1) * spacing) / 2;+ const archiveCols = autoColumns(archived.length);const warehouseZ = activeRows * spacing / 2 + DISTRICT_PARAMS.gap;archived.forEach((app, i) => {- const col = i % archiveCols;- const row = Math.floor(i / archiveCols);- positions.set(app.id, {- x: col * spacing - archiveOffsetX,- z: warehouseZ + row * spacing,- district: 'warehouse',+ const [x, , z] = gridIndexToPosition(i, {+ columns: archiveCols,+ spacing,+ base: [0, 0, warehouseZ],});+ positions.set(app.id, { x, z, district: 'warehouse' });});}diff --git a/client/src/components/city/cityLayout.test.js b/client/src/components/city/cityLayout.test.jsnew file mode 100644index 0000000000..fd55d4ba81--- /dev/null+++ b/client/src/components/city/cityLayout.test.js@@ -0,0 +1,43 @@+import { describe, it, expect } from 'vitest';+import { computeCityLayout } from './cityLayout';++// spacing = BUILDING_PARAMS.spacing = 12, DISTRICT_PARAMS.gap = 4 (see cityConstants.js)+const online = (id) => ({ id, overallStatus: 'online', archived: false });++describe('computeCityLayout', () => {+ it('lays active apps in a square grid centered on the origin', () => {+ const pos = computeCityLayout([online('a'), online('b'), online('c'), online('d')]);+ // 4 apps → 2 cols, 2 rows; X & Z both centered at offset (2-1)*12/2 = 6+ expect(pos.get('a')).toEqual({ x: -6, z: -6, district: 'downtown' });+ expect(pos.get('b')).toEqual({ x: 6, z: -6, district: 'downtown' });+ expect(pos.get('c')).toEqual({ x: -6, z: 6, district: 'downtown' });+ expect(pos.get('d')).toEqual({ x: 6, z: 6, district: 'downtown' });+ });++ it('places a single active app at the origin', () => {+ const pos = computeCityLayout([online('solo')]);+ expect(pos.get('solo')).toEqual({ x: 0, z: 0, district: 'downtown' });+ });++ it('offsets archived apps into a warehouse grid along +Z', () => {+ const pos = computeCityLayout([+ online('a'),+ { id: 'x', overallStatus: 'online', archived: true },+ { id: 'y', overallStatus: 'online', archived: true },+ ]);+ // 1 active → activeRows 1 → warehouseZ = 1*12/2 + 4 = 10; 2 archived → 2 cols, X offset 6+ expect(pos.get('a')).toEqual({ x: 0, z: 0, district: 'downtown' });+ expect(pos.get('x')).toEqual({ x: -6, z: 10, district: 'warehouse' });+ expect(pos.get('y')).toEqual({ x: 6, z: 10, district: 'warehouse' });+ });++ it('sorts active apps online-first so status drives grid order', () => {+ const pos = computeCityLayout([+ { id: 'stopped', overallStatus: 'stopped', archived: false },+ { id: 'live', overallStatus: 'online', archived: false },+ ]);+ // online sorts to index 0 (col 0), stopped to index 1 (col 1); 2 cols, 1 row, X offset 6+ expect(pos.get('live')).toEqual({ x: -6, z: 0, district: 'downtown' });+ expect(pos.get('stopped')).toEqual({ x: 6, z: 0, district: 'downtown' });+ });+});diff --git a/client/src/utils/cityDistrictLayout.js b/client/src/utils/cityDistrictLayout.jsnew file mode 100644index 0000000000..0a5fc42d7b--- /dev/null+++ b/client/src/utils/cityDistrictLayout.js@@ -0,0 +1,89 @@+// Shared, pure layout primitives for CyberCity districts. Several district modules had+// converged on the same three computations — column-wrapped grid placement, count-into-buckets+// tallies, and log-scaled clamped heights — each rolling its own copy. These helpers are the+// single source of truth they now delegate to. No three.js / React imports so every district+// stays headless-testable (mirrors cityJiraDistrict.js / cityMemoryDistrict.js / cityTaskQueue.js).++// ---------------------------------------------------------------------------+// Grid placement: index → world position, wrapping into columns and X-centered.+// ---------------------------------------------------------------------------++// Auto-pick a roughly-square column count for `count` items (downtown/warehouse grow both ways+// as apps are added). Floors at 1 so an empty or single-item grid still has a valid column.+export function autoColumns(count) {+ const n = Number.isFinite(count) ? count : 0;+ return Math.max(1, Math.ceil(Math.sqrt(Math.max(0, n))));+}++// Column-wrapped grid position for the `index`-th cell, returned as `[x, y, z]`.+// - columns: cells per row before wrapping (use autoColumns(n) for the sqrt-auto mode).+// - spacing: distance between adjacent cells (applied on both axes).+// - base: [x, y, z] origin of the grid (default origin).+// - rowDir: +1 lays successive rows toward +Z, -1 toward -Z.+// - rowCount: when provided, rows are *centered* on Z (offset by half the grid depth) — the+// downtown behavior; omit it to have rows extend outward from the base (jira yard,+// warehouse). Columns are always X-centered regardless.+export function gridIndexToPosition(index, opts = {}) {+ const { columns = 1, spacing = 1, base = [0, 0, 0], rowDir = 1, rowCount = null } = opts;+ const cols = Math.max(1, columns);+ const col = index % cols;+ const row = Math.floor(index / cols);+ const offsetX = ((cols - 1) * spacing) / 2;+ const offsetZ = rowCount != null ? ((Math.max(1, rowCount) - 1) * spacing) / 2 : 0;+ return [+ base[0] + col * spacing - offsetX,+ base[1],+ base[2] + rowDir * (row * spacing - offsetZ),+ ];+}++// ---------------------------------------------------------------------------+// Bucketing: count (and optionally weight) items by a categorical field.+// ---------------------------------------------------------------------------++// Count items into buckets keyed by `keyFn(item)`, returned as a plain `{ key: count }` object.+// `seed` pre-creates zeroed buckets so a caller that depends on a fixed set of keys (e.g. a status+// breakdown where `other` must always be present) always gets them; unknown keys are added on+// demand. Tolerates a non-array input (returns just the seeded zeros).+export function tallyByKey(items, keyFn, seed = []) {+ const counts = {};+ for (const key of seed) counts[key] = 0;+ for (const item of Array.isArray(items) ? items : []) {+ const key = keyFn(item);+ counts[key] = (counts[key] || 0) + 1;+ }+ return counts;+}++// Group items into buckets keyed by `keyFn`, each carrying a `count` and a summed `weight`+// (`weightFn` defaults to 1 per item — i.e. weight == count). Returns an array of+// `{ key, count, weight }` sorted by count desc, then key asc — the stable order districts render+// in. Use when a district needs both a population and an accumulated magnitude per bucket.+export function groupByFieldValue(items, keyFn, { weightFn = () => 1, seed = [] } = {}) {+ const buckets = new Map();+ for (const key of seed) buckets.set(key, { key, count: 0, weight: 0 });+ for (const item of Array.isArray(items) ? items : []) {+ const key = keyFn(item);+ const entry = buckets.get(key) || { key, count: 0, weight: 0 };+ const w = weightFn(item);+ entry.count += 1;+ entry.weight += Number.isFinite(w) ? w : 0;+ buckets.set(key, entry);+ }+ return [...buckets.values()].sort(+ (a, b) => b.count - a.count || String(a.key).localeCompare(String(b.key)),+ );+}++// ---------------------------------------------------------------------------+// Height: log-scale a metric into a clamped band so big values don't dwarf the skyline.+// ---------------------------------------------------------------------------++// height = base + log2(1 + value) * k, clamped to [min, max]. `value` is floored at 0 (a zero or+// missing metric yields exactly `base`). Districts use this so a chunky ticket / heavy memory+// cluster reads as taller while staying within a legible band.+export function scaleMetricToHeight(value, { min = 0, max = Infinity, k = 1, base = 0 } = {}) {+ const v = Math.max(0, Number.isFinite(value) ? value : 0);+ const scaled = base + Math.log2(1 + v) * k;+ return Math.min(max, Math.max(min, scaled));+}diff --git a/client/src/utils/cityDistrictLayout.test.js b/client/src/utils/cityDistrictLayout.test.jsnew file mode 100644index 0000000000..73b7f5206b--- /dev/null+++ b/client/src/utils/cityDistrictLayout.test.js@@ -0,0 +1,130 @@+import { describe, it, expect } from 'vitest';+import {+ autoColumns,+ gridIndexToPosition,+ tallyByKey,+ groupByFieldValue,+ scaleMetricToHeight,+} from './cityDistrictLayout';++describe('autoColumns', () => {+ it('returns a roughly-square column count', () => {+ expect(autoColumns(0)).toBe(1); // empty grid still has a valid column+ expect(autoColumns(1)).toBe(1);+ expect(autoColumns(4)).toBe(2);+ expect(autoColumns(5)).toBe(3); // ceil(sqrt(5)) = 3+ expect(autoColumns(9)).toBe(3);+ expect(autoColumns(10)).toBe(4);+ });++ it('floors at 1 for negative / NaN input', () => {+ expect(autoColumns(-3)).toBe(1);+ expect(autoColumns(NaN)).toBe(1);+ });+});++describe('gridIndexToPosition', () => {+ it('wraps into columns and centers X', () => {+ const opts = { columns: 3, spacing: 2, base: [0, 0, 0] };+ // 3 columns, spacing 2 → X offset = (3-1)*2/2 = 2, so cols sit at -2, 0, +2+ expect(gridIndexToPosition(0, opts)).toEqual([-2, 0, 0]);+ expect(gridIndexToPosition(1, opts)).toEqual([0, 0, 0]);+ expect(gridIndexToPosition(2, opts)).toEqual([2, 0, 0]);+ // index 3 wraps to row 1, col 0 → rows extend toward +Z by default+ expect(gridIndexToPosition(3, opts)).toEqual([-2, 0, 2]);+ });++ it('carries base x/y/z through', () => {+ const p = gridIndexToPosition(0, { columns: 1, spacing: 1, base: [5, 7, 9] });+ expect(p).toEqual([5, 7, 9]); // single column → no X offset+ });++ it('lays rows toward -Z when rowDir is -1 (jira yard)', () => {+ const opts = { columns: 2, spacing: 3, base: [0, 0, 0], rowDir: -1 };+ expect(gridIndexToPosition(2, opts)).toEqual([-1.5, 0, -3]); // row 1 recedes to -Z+ });++ it('centers rows on Z when rowCount is given (downtown)', () => {+ // 4 items, 2 cols → 2 rows, spacing 2 → Z offset = (2-1)*2/2 = 1, rows at -1 and +1+ const opts = { columns: 2, spacing: 2, base: [0, 0, 0], rowCount: 2 };+ expect(gridIndexToPosition(0, opts)).toEqual([-1, 0, -1]);+ expect(gridIndexToPosition(2, opts)).toEqual([-1, 0, 1]);+ });+});++describe('tallyByKey', () => {+ it('counts items into buckets by key', () => {+ const items = [{ s: 'a' }, { s: 'b' }, { s: 'a' }];+ expect(tallyByKey(items, (i) => i.s)).toEqual({ a: 2, b: 1 });+ });++ it('seeds fixed buckets to zero so absent keys are present', () => {+ expect(tallyByKey([], (i) => i.s, ['a', 'b'])).toEqual({ a: 0, b: 0 });+ const items = [{ s: 'a' }];+ expect(tallyByKey(items, (i) => i.s, ['a', 'b', 'c'])).toEqual({ a: 1, b: 0, c: 0 });+ });++ it('tolerates a non-array input', () => {+ expect(tallyByKey(null, (i) => i.s, ['a'])).toEqual({ a: 0 });+ expect(tallyByKey(undefined, (i) => i.s)).toEqual({});+ });+});++describe('groupByFieldValue', () => {+ it('groups, counts, and sums weight, sorted by count desc then key asc', () => {+ const items = [+ { c: 'work', w: 2 },+ { c: 'home', w: 5 },+ { c: 'work', w: 3 },+ ];+ const out = groupByFieldValue(items, (i) => i.c, { weightFn: (i) => i.w });+ expect(out).toEqual([+ { key: 'work', count: 2, weight: 5 },+ { key: 'home', count: 1, weight: 5 },+ ]);+ });++ it('defaults weight to 1 per item when no weightFn', () => {+ const items = [{ c: 'x' }, { c: 'x' }, { c: 'y' }];+ expect(groupByFieldValue(items, (i) => i.c)).toEqual([+ { key: 'x', count: 2, weight: 2 },+ { key: 'y', count: 1, weight: 1 },+ ]);+ });++ it('treats a non-finite weight as 0 contribution', () => {+ const items = [{ c: 'x', w: NaN }, { c: 'x', w: 4 }];+ const out = groupByFieldValue(items, (i) => i.c, { weightFn: (i) => i.w });+ expect(out).toEqual([{ key: 'x', count: 2, weight: 4 }]);+ });++ it('breaks count ties by key ascending', () => {+ const items = [{ c: 'b' }, { c: 'a' }];+ expect(groupByFieldValue(items, (i) => i.c).map((b) => b.key)).toEqual(['a', 'b']);+ });++ it('seeds buckets so an empty group still appears', () => {+ expect(groupByFieldValue([], (i) => i.c, { seed: ['a'] })).toEqual([+ { key: 'a', count: 0, weight: 0 },+ ]);+ });+});++describe('scaleMetricToHeight', () => {+ it('log-scales and clamps to the band', () => {+ // base 0.9 + log2(1+1)*1.1 = 0.9 + 1.1 = 2.0+ expect(scaleMetricToHeight(1, { max: 4.5, k: 1.1, base: 0.9 })).toBeCloseTo(2.0);+ // clamps at max+ expect(scaleMetricToHeight(1000, { max: 4.5, k: 1.1, base: 0.9 })).toBe(4.5);+ });++ it('floors value at 0 → yields exactly base', () => {+ expect(scaleMetricToHeight(0, { min: 1.2, max: 4.5, k: 0.7, base: 1.2 })).toBe(1.2);+ expect(scaleMetricToHeight(-9, { min: 1.2, max: 4.5, k: 0.7, base: 1.2 })).toBe(1.2);+ expect(scaleMetricToHeight(NaN, { base: 3 })).toBe(3);+ });++ it('respects the min clamp', () => {+ expect(scaleMetricToHeight(0, { min: 2, base: 0 })).toBe(2);+ });+});diff --git a/client/src/utils/cityJiraDistrict.js b/client/src/utils/cityJiraDistrict.jsindex b442be911c..edc0612176 100644--- a/client/src/utils/cityJiraDistrict.js+++ b/client/src/utils/cityJiraDistrict.js@@ -5,6 +5,8 @@// finished, lit buildings. Tickets are gathered across every JIRA-enabled app, deduped by key.// No three.js / React imports so the topology is unit-testable (mirrors cityTaskQueue.js etc.).+import { gridIndexToPosition, tallyByKey, scaleMetricToHeight } from './cityDistrictLayout';+export const JIRA_DISTRICT = {// North-east-of-north: a yard between the goal monuments (NE, +30,-40) and downtown, on the// -X side so it doesn't collide with the artifact hall (+44,-28) or memory district (-44,-30).@@ -37,7 +39,7 @@ export function ticketState(ticket) {// floor when the ticket carries no estimate so every ticket is at least a visible crate.export function structureHeight(storyPoints) {const pts = Number.isFinite(storyPoints) && storyPoints > 0 ? storyPoints : 1;- return Math.min(JIRA_DISTRICT.maxHeight, 0.9 + Math.log2(1 + pts) * 1.1);+ return scaleMetricToHeight(pts, { max: JIRA_DISTRICT.maxHeight, k: 1.1, base: 0.9 });}// Dedupe tickets across apps by key (the same JIRA ticket can surface under two apps that share a@@ -59,20 +61,17 @@ export function dedupeAndSort(tickets) {// Grid position for the i-th structure in the yard: rows wrap toward -Z, centered on the base X.export function structurePosition(index, opts = {}) {- const base = opts.base || JIRA_DISTRICT.base;- const columns = opts.columns ?? JIRA_DISTRICT.columns;- const spacing = opts.spacing ?? JIRA_DISTRICT.spacing;- const col = index % columns;- const row = Math.floor(index / columns);- const offsetX = ((columns - 1) * spacing) / 2;- return [base[0] + col * spacing - offsetX, base[1], base[2] - row * spacing];+ return gridIndexToPosition(index, {+ base: opts.base || JIRA_DISTRICT.base,+ columns: opts.columns ?? JIRA_DISTRICT.columns,+ spacing: opts.spacing ?? JIRA_DISTRICT.spacing,+ rowDir: -1, // rows pile toward -Z so the yard reads receding from the viewer+ });}// Tally tickets by bucket — drives the district label ("3/8 DONE") and per-state counts.export function tallyStates(tickets) {- const counts = { todo: 0, inProgress: 0, done: 0 };- for (const t of Array.isArray(tickets) ? tickets : []) counts[ticketState(t)] += 1;- return counts;+ return tallyByKey(tickets, ticketState, ['todo', 'inProgress', 'done']);}// Full derived view-model for the component: positioned structures (capped, overflow summarized)diff --git a/client/src/utils/cityMemoryDistrict.js b/client/src/utils/cityMemoryDistrict.jsindex 91c5ee3cab..6b53399262 100644--- a/client/src/utils/cityMemoryDistrict.js+++ b/client/src/utils/cityMemoryDistrict.js@@ -7,6 +7,7 @@// unit-testable (mirrors cityFederation.js / cityBackupVault.js).import { hashString } from './hashString';+import { groupByFieldValue, scaleMetricToHeight } from './cityDistrictLayout';export const MEMORY_DISTRICT = {// Northwest quadrant — mirrors the artifact cluster at NE (+44,-28), clear of the@@ -56,15 +57,10 @@ export function categoryKey(node) {// importance (importance defaults to 1 when absent so every memory contributes some mass).// Returns buckets sorted by count desc, then category asc for a stable order.export function groupByCategory(nodes) {- const buckets = new Map();- for (const node of Array.isArray(nodes) ? nodes : []) {- const key = categoryKey(node);- const entry = buckets.get(key) || { category: key, count: 0, importance: 0 };- entry.count += 1;- entry.importance += Number.isFinite(node?.importance) ? node.importance : 1;- buckets.set(key, entry);- }- return [...buckets.values()].sort((a, b) => b.count - a.count || a.category.localeCompare(b.category));+ const nodeImportance = (node) => (Number.isFinite(node?.importance) ? node.importance : 1);+ return groupByFieldValue(nodes, categoryKey, { weightFn: nodeImportance }).map(+ ({ key, count, weight }) => ({ category: key, count, importance: weight }),+ );}// Place a cluster on the district ring. Angle is seeded by the category name (not the index)@@ -88,8 +84,12 @@ export function placeCluster(category, index, total, opts = {}) {// a huge category doesn't dwarf the skyline and a tiny one is still visible.export function clusterHeight(importance) {const { minCrystalHeight, maxCrystalHeight } = MEMORY_DISTRICT;- const scaled = minCrystalHeight + Math.log2(1 + Math.max(0, importance)) * 0.7;- return Math.min(maxCrystalHeight, Math.max(minCrystalHeight, scaled));+ return scaleMetricToHeight(importance, {+ min: minCrystalHeight,+ max: maxCrystalHeight,+ k: 0.7,+ base: minCrystalHeight,+ });}// Build the bridges between category clusters from the graph's cross-category edges. Each edgediff --git a/client/src/utils/cityTaskQueue.js b/client/src/utils/cityTaskQueue.jsindex 2ff381de3f..6e1165d906 100644--- a/client/src/utils/cityTaskQueue.js+++ b/client/src/utils/cityTaskQueue.js@@ -4,6 +4,8 @@// in-progress task lights the warehouse, a blocked task tints it amber. No three.js /// React imports so the topology is unit-testable (mirrors cityBackupVault.js).+import { tallyByKey } from './cityDistrictLayout';+export const TASK_QUEUE = {position: [34, 0, -10], // east of the building grid, mirroring the backup vault to the westmaxCrates: 8, // visible-crate cap; beyond this the warehouse reads as "overflow"@@ -24,18 +26,10 @@ const STATE_COLORS = {// Tally CoS tasks by status. Tolerates a missing/non-array input (returns all-zero) and// buckets unrecognized statuses under `other` so the counts always sum to the input length.+const KNOWN_TASK_STATUSES = ['pending', 'in_progress', 'blocked', 'completed'];+const taskStatusKey = (t) => (KNOWN_TASK_STATUSES.includes(t?.status) ? t.status : 'other');export function countByStatus(tasks) {- const counts = { pending: 0, in_progress: 0, blocked: 0, completed: 0, other: 0 };- const list = Array.isArray(tasks) ? tasks : [];- for (const t of list) {- const s = t?.status;- if (s === 'pending') counts.pending++;- else if (s === 'in_progress') counts.in_progress++;- else if (s === 'blocked') counts.blocked++;- else if (s === 'completed') counts.completed++;- else counts.other++;- }- return counts;+ return tallyByKey(tasks, taskStatusKey, [...KNOWN_TASK_STATUSES, 'other']);}// Overall queue mood for the warehouse lighting, in priority order: a blocked task is the