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

address review: fix Tribe edit-save 400, layout clip, and harden routes/tests

[._.]/ Adam Eivyb59ea27ff46d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a8f4c99cfa..b9406f82cc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Tribe — a relationship manager for rings, care cadence, focus lists, and touchpoints.** A new **Tribe** page (Brain → Tribe, also reachable via ⌘K / voice) lets you organize the people in your life into Dunbar-style rings (Support / Core / Tribe / Village), each with a default check-in cadence; log touchpoints (manual or sourced from a calendar event), track per-person energy/next-move/notes, and link people to Brain memories. People, touchpoints, and memory links live in Postgres (`tribe_people`, `tribe_touchpoints`, `tribe_memory_links`) so they can be joined to Brain memories and carry calendar event references for future scheduling work — provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` (with audit triggers on people/touchpoints), and exercised by route + service tests. The page reconciles live against a `tribe:changed` socket broadcast (covers other tabs/devices) and falls back to a one-shot import of any legacy `localStorage` contacts on first load. New `/api/tribe` routes + service; relationship data is currently machine-local (the tables carry no sync columns). (`server/routes/tribe.js`, `server/services/tribe.js`, `server/lib/db.js`, `server/scripts/init-db.sql`, `client/src/pages/Tribe.jsx`, `client/src/services/apiTribe.js`, #1436)
+
- **[issue-901] Legacy Export — download your whole identity as a portable bundle (server foundation).** A new `POST /api/legacy-export` endpoint gathers your identity across every PortOS domain — digital-twin prompt, autobiography, brain notes, memories, goals + milestones, key decisions, and a health summary — into a single self-contained `.zip` of human-readable Markdown plus machine-readable JSON and a SHA-256 `manifest.json`. The bundle is readable with **zero PortOS running** (plain files, no database), opens with a privacy banner, and degrades gracefully when a domain is empty. Secrets accidentally pasted into notes are redacted before anything leaves the box. `GET /api/legacy-export/preview` reports which sections are present and the estimated size without building the file. This is the server core of the Knowledge Legacy export; PDF rendering and a one-click UI are tracked as follow-ups. (#901)
- **[issue-902] Workspace Contexts — save and restore a project's full working context.** A new **Workspaces** view (Dev Tools → Workspaces) lists every active app/project and, for each, captures the *working context* you'd otherwise have to rebuild by hand: the repo's current **git branch** (plus dirty/clean state), the live **shell sessions** rooted in that repo, and the **CoS/user tasks** scoped to it (the PortOS project also collects its `_self`/unscoped tasks). **Save** snapshots that context; **Restore** reconciles the snapshot against what's live now — reporting which saved shell sessions are still alive (re-attachable, one click to open in the Shell page via its existing attach/claim contract) versus gone, and whether the saved branch is still checked out. It's deliberately **read-only with respect to your work**: it never stashes, switches branches, or kills/respawns shells, so an open editor or uncommitted changes are never clobbered (the #902 hard constraints). Deep-linkable (`/workspace-contexts` and `/workspace-contexts/:appId`), reachable via ⌘K / voice. Stored machine-local in `data/workspace-contexts.json` (shell sessions and repo paths are machine-specific — a context never federates). New endpoints under `/api/workspace-contexts`. (`server/services/workspaceContext.js`, `server/routes/workspaceContexts.js`, `client/src/pages/WorkspaceContexts.jsx`, `client/src/services/apiWorkspaceContexts.js`) (#902)
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 5ca1a49e21..bde2a1e6cf 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -1147,6 +1147,10 @@ export default function Layout() {
location.pathname === '/shell' ||
location.pathname.startsWith('/shell/') ||
location.pathname.startsWith('/city') ||
+ // Tribe is a full-bleed two-pane page that owns its own internal
+ // scroll (PageHeader + a `flex-1 overflow-auto` main); keep it out
+ // of the default padded+scrolling main or it double-pads and clips.
+ location.pathname === '/tribe' ||
// Only the App DETAIL editor (/apps/:id, /apps/:id/:tab) is
// full-width and owns its own scroll; the Add App form
// (/apps/create) is a plain scrolling page and must stay OUT of
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
index 5c22201089..d5cce09190 100644
--- a/client/src/pages/Tribe.jsx
+++ b/client/src/pages/Tribe.jsx
@@ -17,6 +17,7 @@ import {
} from 'lucide-react';
import * as api from '../services/api';
+import socket from '../services/socket';
import BrailleSpinner from '../components/BrailleSpinner';
import PageHeader from '../components/PageHeader';
import toast from '../components/ui/Toast';
@@ -631,16 +632,21 @@ export default function Tribe() {
const selectedId = draft.id;
- const loadContacts = async () => {
+ const loadContacts = async (isCancelled = () => false) => {
setLoading(true);
const result = await api.getTribePeople({ silent: true }).catch((err) => {
- toast.error(err.message || 'Failed to load Tribe');
- return { people: [] };
+ if (!isCancelled()) toast.error(err.message || 'Failed to load Tribe');
+ // null (not an empty list) so a failed fetch is distinguishable from a
+ // genuinely-empty server — otherwise a transient error would trigger the
+ // one-shot legacy localStorage import and duplicate data on recovery.
+ return null;
});
+ if (isCancelled()) return;
+ const fetchFailed = result === null;
let people = result?.people || [];
const legacy = getLegacyContacts();
- if (people.length === 0 && legacy.length > 0) {
+ if (!fetchFailed && people.length === 0 && legacy.length > 0) {
const imported = [];
for (const contact of legacy) {
const created = await api.createTribePerson({
@@ -664,12 +670,24 @@ export default function Tribe() {
}
}
+ if (isCancelled()) return;
setContacts(people);
setLoading(false);
};
useEffect(() => {
- loadContacts();
+ let cancelled = false;
+ const isCancelled = () => cancelled;
+ loadContacts(isCancelled);
+ // Mutations broadcast `tribe:changed` from the server; reconcile against
+ // server truth (covers other tabs/devices and the GREATEST last-contact
+ // merge that optimistic updates can't predict).
+ const handleChanged = () => loadContacts(isCancelled);
+ socket.on('tribe:changed', handleChanged);
+ return () => {
+ cancelled = true;
+ socket.off('tribe:changed', handleChanged);
+ };
}, []);
const filteredContacts = useMemo(() => {
@@ -701,24 +719,29 @@ export default function Tribe() {
});
const saveDraft = async () => {
- const normalized = {
- ...draft,
+ // Send only the editable fields the schema accepts. The PUT route rejects a
+ // body `id` (`z.never()`) — it comes from the URL — and `lastContact` must be
+ // null (not '') when empty, so a bare `{ ...draft }` would 400 on both counts.
+ const payload = {
name: draft.name.trim() || 'Unnamed person',
relationship: draft.relationship.trim(),
+ ring: draft.ring,
+ cadenceDays: Math.max(1, Number(draft.cadenceDays) || ringFor(draft.ring).cadenceDays),
+ lastContact: draft.lastContact || null,
channel: draft.channel.trim(),
+ energy: draft.energy,
tags: tagsToArray(draft.tags),
nextMove: draft.nextMove.trim(),
notes: draft.notes.trim(),
- cadenceDays: Math.max(1, Number(draft.cadenceDays) || ringFor(draft.ring).cadenceDays),
};
setSaving(true);
const saved = draft.id
- ? await api.updateTribePerson(draft.id, normalized).catch((err) => {
+ ? await api.updateTribePerson(draft.id, payload).catch((err) => {
toast.error(err.message || 'Failed to save relationship');
return null;
})
- : await api.createTribePerson(normalized).catch((err) => {
+ : await api.createTribePerson(payload).catch((err) => {
toast.error(err.message || 'Failed to save relationship');
return null;
});
diff --git a/server/routes/tribe.js b/server/routes/tribe.js
index 6b16f705cc..9d7cf0d9e9 100644
--- a/server/routes/tribe.js
+++ b/server/routes/tribe.js
@@ -50,10 +50,28 @@ const memoryLinkSchema = z.object({
note: z.string().max(1000).optional().default(''),
});
+const listQuerySchema = z.object({
+ search: z.string().max(200).optional(),
+ ring: ringSchema.or(z.literal('all')).optional(),
+});
+
+// Validate UUID path params before they hit the UUID-typed columns; otherwise a
+// non-UUID segment raises a raw Postgres "invalid input syntax for type uuid"
+// 500 (leaking the column type) instead of a clean 400.
+const guidParam = (label) => (req, res, next, value) => {
+ if (!z.string().guid().safeParse(value).success) {
+ return next(new ServerError(`Invalid ${label}`, { status: 400 }));
+ }
+ return next();
+};
+router.param('id', guidParam('person id'));
+router.param('memoryId', guidParam('memory id'));
+
router.get('/people', asyncHandler(async (req, res) => {
+ const { search, ring } = validateRequest(listQuerySchema, req.query);
const people = await tribe.listPeople({
- search: req.query.search || undefined,
- ring: req.query.ring || undefined,
+ search: search || undefined,
+ ring: ring || undefined,
});
res.json({ people });
}));
diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.js
index 126e1343dd..b88164a023 100644
--- a/server/routes/tribe.test.js
+++ b/server/routes/tribe.test.js
@@ -1,8 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
+import { errorEvents } from '../lib/errorHandler.js';
import tribeRoutes from './tribe.js';
+// asyncHandler emits to errorEvents on every route failure when `io` is set; an
+// EventEmitter with no 'error' listener would rethrow and hang the response, so
+// swallow it (matches routes/voice.test.js, routes/localLlm.test.js).
+errorEvents.on('error', () => {});
+
vi.mock('../services/tribe.js', () => ({
listPeople: vi.fn(),
getPerson: vi.fn(),
@@ -75,7 +81,7 @@ describe('Tribe Routes', () => {
expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });
});
- it('logs touchpoints with calendar-ready metadata', async () => {
+ it('forwards calendar fields on a manual touchpoint', async () => {
const touchpoint = {
id: 'touch-1',
personId: PERSON_ID,
@@ -145,16 +151,92 @@ describe('Tribe Routes', () => {
expect(tribe.unlinkMemory).toHaveBeenCalledWith(PERSON_ID, MEMORY_ID);
});
- it('rejects invalid person payloads before service calls', async () => {
- const validationApp = express();
- validationApp.use(express.json());
- validationApp.use('/api/tribe', tribeRoutes);
+ it('rejects an empty name before service calls', async () => {
+ const response = await request(app)
+ .post('/api/tribe/people')
+ .send({ name: '', ring: 'core' });
+
+ expect(response.status).toBe(400);
+ expect(tribe.createPerson).not.toHaveBeenCalled();
+ });
+
+ it('rejects an out-of-enum ring before service calls', async () => {
+ const response = await request(app)
+ .post('/api/tribe/people')
+ .send({ name: 'Ada', ring: 'outer-space' });
+
+ expect(response.status).toBe(400);
+ expect(tribe.createPerson).not.toHaveBeenCalled();
+ });
- const response = await request(validationApp)
+ it('rejects a blank lastContact (must be a date or null, not "")', async () => {
+ const response = await request(app)
.post('/api/tribe/people')
- .send({ name: '', ring: 'outer-space' });
+ .send({ name: 'Ada', ring: 'core', lastContact: '' });
expect(response.status).toBe(400);
expect(tribe.createPerson).not.toHaveBeenCalled();
});
+
+ it('accepts a create payload with lastContact: null', async () => {
+ tribe.createPerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada' });
+
+ const response = await request(app)
+ .post('/api/tribe/people')
+ .send({ name: 'Ada', ring: 'core', lastContact: null });
+
+ expect(response.status).toBe(201);
+ expect(tribe.createPerson).toHaveBeenCalledWith(expect.objectContaining({ lastContact: null }));
+ });
+
+ it('rejects a PUT body that carries an id (id comes from the URL)', async () => {
+ const response = await request(app)
+ .put(`/api/tribe/people/${PERSON_ID}`)
+ .send({ id: PERSON_ID, name: 'Ada' });
+
+ expect(response.status).toBe(400);
+ expect(tribe.updatePerson).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-UUID person id path param with 400', async () => {
+ const response = await request(app).get('/api/tribe/people/not-a-uuid');
+
+ expect(response.status).toBe(400);
+ expect(tribe.getPerson).not.toHaveBeenCalled();
+ });
+
+ it('rejects an out-of-enum ring query param with 400', async () => {
+ const response = await request(app).get('/api/tribe/people?ring=outer-space');
+
+ expect(response.status).toBe(400);
+ expect(tribe.listPeople).not.toHaveBeenCalled();
+ });
+
+ it('returns 404 when getting a missing person', async () => {
+ tribe.getPerson.mockResolvedValue(null);
+
+ const response = await request(app).get(`/api/tribe/people/${PERSON_ID}`);
+
+ expect(response.status).toBe(404);
+ });
+
+ it('returns 404 when updating a missing person', async () => {
+ tribe.updatePerson.mockResolvedValue(null);
+
+ const response = await request(app)
+ .put(`/api/tribe/people/${PERSON_ID}`)
+ .send({ nextMove: 'Coffee' });
+
+ expect(response.status).toBe(404);
+ expect(emit).not.toHaveBeenCalledWith('tribe:changed', expect.anything());
+ });
+
+ it('returns 404 when deleting a missing person', async () => {
+ tribe.deletePerson.mockResolvedValue(false);
+
+ const response = await request(app).delete(`/api/tribe/people/${PERSON_ID}`);
+
+ expect(response.status).toBe(404);
+ expect(emit).not.toHaveBeenCalledWith('tribe:changed', expect.anything());
+ });
});
diff --git a/server/services/tribe.js b/server/services/tribe.js
index 018ece741d..7f57fd49a9 100644
--- a/server/services/tribe.js
+++ b/server/services/tribe.js
@@ -3,38 +3,44 @@ import { ensureSchema, query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
import * as calendarSync from './calendarSync.js';
-const DEFAULT_RING_CADENCE = {
+// Default check-in cadence (days) per ring. Mirrored on the client in
+// `client/src/pages/Tribe.jsx` (the RINGS array's `cadenceDays`); the SQL column
+// default is a flat 45 (`cadence_days` in db.js / init-db.sql) because the
+// ring-aware default is resolved here before insert. Keep all three in sync.
+export const DEFAULT_RING_CADENCE = {
support: 7,
core: 21,
tribe: 45,
village: 90,
};
-function isoDate(value) {
+export function isoDate(value) {
if (!value) return null;
if (value instanceof Date) return value.toISOString().slice(0, 10);
return String(value).slice(0, 10);
}
-function isoDateTime(value) {
+export function isoDateTime(value) {
if (!value) return null;
if (value instanceof Date) return value.toISOString();
- return new Date(value).toISOString();
+ const parsed = new Date(value);
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
}
-function normalizeTags(tags) {
+export function normalizeTags(tags) {
if (!tags) return [];
if (Array.isArray(tags)) return tags.map((tag) => String(tag).trim()).filter(Boolean);
return String(tags).split(',').map((tag) => tag.trim()).filter(Boolean);
}
-function rowToPerson(row) {
+export function rowToPerson(row) {
return {
id: row.id,
name: row.name,
relationship: row.relationship || '',
ring: row.ring || 'tribe',
- cadenceDays: row.cadence_days ?? DEFAULT_RING_CADENCE[row.ring] ?? 45,
+ // cadence_days is NOT NULL DEFAULT 45, so it's always present on a real row.
+ cadenceDays: row.cadence_days,
lastContact: isoDate(row.last_contact_on),
channel: row.channel || '',
energy: row.energy || 'steady',
@@ -48,7 +54,7 @@ function rowToPerson(row) {
};
}
-function rowToTouchpoint(row) {
+export function rowToTouchpoint(row) {
return {
id: row.id,
personId: row.person_id,
@@ -63,7 +69,7 @@ function rowToTouchpoint(row) {
};
}
-function rowToMemoryLink(row) {
+export function rowToMemoryLink(row) {
return {
personId: row.person_id,
memoryId: row.memory_id,
diff --git a/server/services/tribe.test.js b/server/services/tribe.test.js
new file mode 100644
index 0000000000..dec61087dc
--- /dev/null
+++ b/server/services/tribe.test.js
@@ -0,0 +1,177 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the DB layer so the SQL builders and row mappers can be tested without a
+// live Postgres — the route test mocks the whole service away, so this is the
+// only coverage for the contract-dense SQL↔JS mapping code.
+vi.mock('../lib/db.js', () => ({
+ ensureSchema: vi.fn().mockResolvedValue(undefined),
+ query: vi.fn(),
+ withTransaction: vi.fn(),
+}));
+
+import { query } from '../lib/db.js';
+import {
+ listPeople,
+ createPerson,
+ normalizeTags,
+ isoDate,
+ isoDateTime,
+ rowToPerson,
+ rowToTouchpoint,
+ DEFAULT_RING_CADENCE,
+} from './tribe.js';
+
+describe('tribe service — pure helpers', () => {
+ describe('normalizeTags', () => {
+ it('splits a comma string, trimming and dropping empties', () => {
+ expect(normalizeTags('a, b , ,c')).toEqual(['a', 'b', 'c']);
+ });
+
+ it('maps and trims an array, dropping empties', () => {
+ expect(normalizeTags([' a ', '', 'b'])).toEqual(['a', 'b']);
+ });
+
+ it('returns [] for nullish input', () => {
+ expect(normalizeTags(null)).toEqual([]);
+ expect(normalizeTags(undefined)).toEqual([]);
+ });
+ });
+
+ describe('isoDate / isoDateTime', () => {
+ it('isoDate slices a Date to YYYY-MM-DD', () => {
+ expect(isoDate(new Date('2026-06-18T15:00:00.000Z'))).toBe('2026-06-18');
+ });
+
+ it('isoDate keeps the date head of a string', () => {
+ expect(isoDate('2026-06-18')).toBe('2026-06-18');
+ });
+
+ it('isoDate returns null for empty', () => {
+ expect(isoDate(null)).toBeNull();
+ });
+
+ it('isoDateTime returns null for an unparseable string instead of throwing', () => {
+ expect(isoDateTime('not-a-date')).toBeNull();
+ });
+
+ it('isoDateTime renders a valid Date', () => {
+ expect(isoDateTime(new Date('2026-06-18T15:00:00.000Z'))).toBe('2026-06-18T15:00:00.000Z');
+ });
+ });
+
+ describe('rowToPerson', () => {
+ it('maps a full DB row to the API shape and coerces counts to numbers', () => {
+ const row = {
+ id: 'p1',
+ name: 'Ada',
+ relationship: 'mentor',
+ ring: 'core',
+ cadence_days: 21,
+ last_contact_on: '2026-06-01',
+ channel: 'sms',
+ energy: 'steady',
+ tags: ['x'],
+ next_move: 'call',
+ notes: 'n',
+ touchpoint_count: '3',
+ linked_memory_count: '2',
+ created_at: '2026-05-01T00:00:00.000Z',
+ updated_at: '2026-05-02T00:00:00.000Z',
+ };
+ expect(rowToPerson(row)).toMatchObject({
+ id: 'p1',
+ name: 'Ada',
+ ring: 'core',
+ cadenceDays: 21,
+ lastContact: '2026-06-01',
+ tags: ['x'],
+ touchpointCount: 3,
+ linkedMemoryCount: 2,
+ });
+ });
+
+ it('defaults absent optional columns', () => {
+ const r = rowToPerson({ id: 'p2', name: 'B', ring: 'tribe', cadence_days: 45 });
+ expect(r.relationship).toBe('');
+ expect(r.tags).toEqual([]);
+ expect(r.touchpointCount).toBe(0);
+ expect(r.lastContact).toBeNull();
+ });
+ });
+
+ describe('rowToTouchpoint', () => {
+ it('maps a touchpoint row and defaults nullable calendar fields', () => {
+ const r = rowToTouchpoint({
+ id: 't1',
+ person_id: 'p1',
+ happened_at: new Date('2026-06-18T15:00:00.000Z'),
+ summary: 'Walk',
+ });
+ expect(r).toMatchObject({
+ id: 't1',
+ personId: 'p1',
+ happenedAt: '2026-06-18T15:00:00.000Z',
+ summary: 'Walk',
+ calendarAccountId: null,
+ calendarEventId: null,
+ metadata: {},
+ });
+ });
+ });
+});
+
+describe('tribe service — listPeople query builder', () => {
+ beforeEach(() => {
+ query.mockReset();
+ query.mockResolvedValue({ rows: [] });
+ });
+
+ it('filters by ring with a single $1 parameter', async () => {
+ await listPeople({ ring: 'core' });
+ const [sql, params] = query.mock.calls[0];
+ expect(sql).toContain('ring = $1');
+ expect(params).toEqual(['core']);
+ });
+
+ it('does not add a ring filter when ring is "all"', async () => {
+ await listPeople({ ring: 'all' });
+ const [sql, params] = query.mock.calls[0];
+ expect(sql).not.toContain('ring = $');
+ expect(params).toEqual([]);
+ });
+
+ it('reuses one parameter across every search column, wrapped in %%', async () => {
+ await listPeople({ search: 'ada' });
+ const [sql, params] = query.mock.calls[0];
+ expect(sql).toContain('ILIKE $1');
+ expect(params).toEqual(['%ada%']);
+ });
+
+ it('assigns sequential parameter indices for ring + search together', async () => {
+ await listPeople({ ring: 'core', search: 'ada' });
+ const [sql, params] = query.mock.calls[0];
+ expect(sql).toContain('ring = $1');
+ expect(sql).toContain('ILIKE $2');
+ expect(params).toEqual(['core', '%ada%']);
+ });
+});
+
+describe('tribe service — createPerson', () => {
+ beforeEach(() => {
+ query.mockReset();
+ });
+
+ it('resolves the ring-aware default cadence and normalizes a tag string', async () => {
+ query.mockResolvedValue({
+ rows: [{ id: 'p1', name: 'Ada', ring: 'core', cadence_days: 21, tags: ['a', 'b'] }],
+ });
+ await createPerson({ name: 'Ada', ring: 'core', tags: 'a, b' });
+
+ const [, params] = query.mock.calls[0];
+ // INSERT param order: id,name,relationship,ring,cadence_days,last_contact,
+ // channel,energy,tags,next_move,notes
+ expect(params[3]).toBe('core');
+ expect(params[4]).toBe(DEFAULT_RING_CADENCE.core); // 21, not the flat SQL default
+ expect(params[8]).toEqual(['a', 'b']);
+ });
+});