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
compress four AGENTS.md sections onto their linked docs and move the number-formatting rule to the client tree
[._.]/ Adam Eivy2717cd421249
diff --git a/AGENTS.md b/AGENTS.mdindex 02030122cd..a5610071f8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -23,13 +23,11 @@ npm run test:db # DB-backed suites → portos_test ONLY (see Se## Test Strategy: Value Over Assertion Count-The default new test is the highest practical public boundary: an Express route, service workflow, persisted-store adapter, socket exchange, or rendered user interaction. Cover the success path plus the materially different failure/compatibility paths; do not enumerate every internal branch because it exists.--Do not add or keep a unit test that only raises coverage for a deterministic helper already exercised through a stable caller. When a helper's signature and every caller would change together, prefer the caller's integration contract and delete redundant helper-level examples. Table-driven permutations that all prove the same product outcome are duplication.--Focused unit tests remain valuable where a higher-level test cannot pin behavior precisely or cheaply: parsers and algorithms with a real input matrix; security, privacy, data-isolation, and destructive-action guards; migrations and cross-version compatibility; serialization/schema boundaries; retry, timeout, and process-lifecycle state machines; pure edge cases whose failure would be ambiguous through an integration test. Real timeout behavior gets one contract test with injected/fake time — never repeated production sleeps.--Before adding a test, name the regression it uniquely catches. In review, remove tests that duplicate a stronger boundary assertion, mirror implementation details, only verify mocks called other mocks, or cover impossible states. Test count and line coverage are diagnostics; CI time, determinism, and regression-detection value are the goals.+- **Default to the highest practical public boundary** — an Express route, service workflow, persisted-store adapter, socket exchange, or rendered user interaction. Cover the success path plus the materially different failure/compatibility paths; do not enumerate every internal branch because it exists.+- **Don't unit-test a helper a stable caller already exercises.** No test that only raises coverage for a deterministic helper. When a helper's signature and every caller would change together, prefer the caller's integration contract and delete redundant helper-level examples. Table-driven permutations that all prove the same product outcome are duplication.+- **Focused unit tests stay valuable where a higher-level test cannot pin behavior precisely or cheaply:** parsers and algorithms with a real input matrix; security, privacy, data-isolation, and destructive-action guards; migrations and cross-version compatibility; serialization/schema boundaries; retry, timeout, and process-lifecycle state machines; pure edge cases whose failure would be ambiguous through an integration test. Real timeout behavior gets one contract test with injected/fake time — never repeated production sleeps.+- **Name the regression a new test uniquely catches** before adding it. In review, remove tests that duplicate a stronger boundary assertion, mirror implementation details, only verify mocks called other mocks, or cover impossible states.+- Test count and line coverage are diagnostics; CI time, determinism, and regression-detection value are the goals.## Security Model@@ -92,7 +90,7 @@ Client- and server-specific conventions live in nested memory files that load wh`server/lib/navManifest.js` is the single source of truth for navigation: `NAV_COMMANDS` + `resolveNavCommand()`, consumed by both the `⌘K` palette and the voice agent's `ui_navigate` tool. **Adding a `<Route>` without a `NAV_COMMANDS` entry leaves the page unreachable from `⌘K` and un-navigable by voice.** Invoke the `portos-add-page` skill for the entry shape, palette-action wiring, and the fail-fast guards.-**Optional features gate navigation, not routes.** `server/lib/instanceFeatureRegistry.js` declares the optional per-install features (**Settings > Features**); a nav entry tagged `feature: '<id>'` (or in a `SECTION_FEATURE` section) drops out of `⌘K` and the sidebar while the feature is off, but its `<Route>` keeps working. The gate is applied CLIENT-side (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), never by filtering the HTTP-cached manifest response, and a sidebar row still needs its own `NAV_PRESENTATION` entry in `client/src/lib/navPresentation.js`. Feature groups (`INSTANCE_FEATURE_GROUPS`) bucket features under one toggle additively — per-feature override → group flag → detector → default, with an unstored group defaulting to `true` so registering one is never a silent hide. **A feature toggle that arms background work must reconcile that work at toggle time, not only at boot** — one idempotent `reconcile…()` called from every path that moves the gate (`server/services/beeperArming.js` is the worked example). Full contract: `docs/INSTANCE_FEATURES.md`.+**Optional features gate navigation, not routes.** `server/lib/instanceFeatureRegistry.js` declares the optional per-install features (**Settings > Features**); a nav entry tagged `feature: '<id>'` (or in a `SECTION_FEATURE` section) drops out of `⌘K` and the sidebar while the feature is off, but its `<Route>` keeps working. The gate is applied CLIENT-side (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), never by filtering the HTTP-cached manifest response, and a sidebar row still needs its own `NAV_PRESENTATION` entry in `client/src/lib/navPresentation.js`. **A feature toggle that arms background work must reconcile that work at toggle time, not only at boot** — one idempotent `reconcile…()` called from every path that moves the gate (`server/services/beeperArming.js` is the worked example). Feature groups, the resolution order, and the full contract: `docs/INSTANCE_FEATURES.md`.### Slashdo Commands (`lib/slashdo`)@@ -129,14 +127,14 @@ If a close match exists, **extend it or use it**. Only add a new module when non- `tryReadFile` (`server/lib/fileUtils.js`) — collapses `readFile(path).catch(() => null)`.- `atomicWrite` (`server/lib/fileUtils.js`) — `ensureDir + writeFile + JSON.stringify` in one call.-- `createCollectionStore` (`server/lib/collectionStore.js`) — when a service outgrows its single-JSON-file shape (large per-record payload, frequent mutations), use this instead of another `readJSONFile` + `atomicWrite` + `createFileWriteQueue`. Lays out `data/{type}/{id}/index.json` with a type-level `data/{type}/index.json` stamping the storage-layout `schemaVersion`; includes a per-id write queue and a `verifySchemaVersion` hook used by the boot-time verifier in `server/index.js`. Worked example: `server/services/universeBuilder.js` (migration 034).+- `createCollectionStore` (`server/lib/collectionStore.js`) — when a service outgrows its single-JSON-file shape (large per-record payload, frequent mutations), use this instead of another `readJSONFile` + `atomicWrite` + `createFileWriteQueue`. Lays out `data/{type}/{id}/index.json` under a type-level index stamping the storage-layout `schemaVersion`, with a per-id write queue and a `verifySchemaVersion` hook for the boot-time verifier. Full API in `server/lib/README.md`; worked example `server/services/universeBuilder.js` (migration 034).- `optionalBooleanMap(keys)` (`server/lib/validation.js`) — collapses `z.object(Object.fromEntries(KEYS.map(k => [k, z.boolean().optional()])))`.- `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` (`server/lib/canonPrompt.js`, mirrored to client) — render `[{ prefix?, value }]` fragments to a sentence or array.- `copyToClipboard` / `writeClipboardSilently` / `readClipboard` (`client/src/lib/clipboard.js`) — safe on insecure-origin contexts. Never use `navigator.clipboard.writeText` inline.- `useLockToggle` (`client/src/hooks/useLockToggle.js`) — optimistic-PATCH lock toggle for any new lock button.- `useSseProgress` (`client/src/hooks/useSseProgress.js`) — generic JSON-frame EventSource subscriber; build new progress hooks on it.- `formatBytes` / `formatTimecode` / `formatDateShort` / `formatDurationMs` / `timeAgo` (`client/src/utils/formatters.js`) — never re-define formatters inside components.-- `formatCount` / `formatUsd` (`client/src/utils/formatters.js`) — thousands-grouped, en-US-pinned (`2,762`, `$4,610.09`). Reach for these rather than rendering a raw integer or a bare `.toLocaleString()` for a user-facing count or amount — an unseparated `4610` is read at the wrong order of magnitude, and the browser locale disagrees with the `$` beside it. A **measured** zero already renders `0`; `formatCount` gives `—` only for a value that is missing or unparseable, so pass `{ fallback: '0' }` just where an ABSENT count should still read as zero. `client/src/numberFormattingConventions.test.js` enforces this tree-wide — any new bare `.toLocaleString(` call under `client/src` fails CI.+- `formatCount` / `formatUsd` (`client/src/utils/formatters.js`) — thousands-grouped, en-US-pinned (`2,762`, `$4,610.09`) for every user-facing count or amount. Never a raw integer or a bare `.toLocaleString()`; `client/src/numberFormattingConventions.test.js` fails CI on one. Full rule (including when to pass `{ fallback: '0' }`) in `client/src/AGENTS.md`.### Maintenance rule (WHEN adding a public module)@@ -152,7 +150,7 @@ Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — theFirst ask whether the manifest needs to exist: a derivation that is deterministic, cheap, and reads only inputs every install ships belongs **in memory, derived on first use and cached for the process** (`server/lib/apiRouteGraph.js`, `server/lib/socketEventInventory.js`). A checked-in `*.generated.json` must change when — and *only* when — the thing it describes changes, so key each record by the declaring file plus the semantic identity of what it declares (stage key plus file paths in `scripts/generate-prompt-stage-call-sites.js`), never by line/column: a `foo.js:412` record makes every unrelated edit above it churn the file and every rebase conflict on it.-**A new generator proves this with `shiftSourceText` (`scripts/lib/positionInvariance.js`)** — shift every line in its inputs, regenerate, assert byte-identical output. `server/lib/generatedManifests.test.js` is the tree-wide backstop and also **fails when a `scripts/generate-*.js` has no sibling test importing `positionInvariance.js`**. The rule lives in root because the generators are in `scripts/`, which carries no nested file; rationale and the coverage-without-positions pattern are under "Generated manifests" in `server/AGENTS.md`.+**A new generator proves this with `shiftSourceText` (`scripts/lib/positionInvariance.js`)** — shift every line in its inputs, regenerate, assert byte-identical output. `server/lib/generatedManifests.test.js` is the tree-wide backstop and **fails when a `scripts/generate-*.js` has no sibling test importing `positionInvariance.js`**. This rule lives in root because the generators are in `scripts/`, which carries no nested file; the mechanism and the coverage-without-positions pattern are under "Generated manifests" in `server/AGENTS.md`.## Scope Boundary@@ -187,7 +185,7 @@ This complements the Security Model (the deployed product) — this section gove- **Command allowlist** — shell execution restricted to approved commands only.- **Every new page registers in the nav manifest** — a `<Route>` + sidebar link also means a `NAV_COMMANDS` entry in `server/lib/navManifest.js`. Invoke the `portos-add-page` skill.- **Selection lives in the URL, never in local state** — any view that opens/selects a specific record encodes it as a route param, so it's shareable, bookmarkable, and reachable from ⌘K and voice. Full contract in `client/src/AGENTS.md`.-- **Client UI conventions** (`client/src/AGENTS.md`) — no `alert`/`confirm`, `htmlFor`/`id` label pairing, mobile responsive, above the fold, no hardcoded localhost, alphabetical nav, reactive local-state updates after mutations, silent-vs-toasting API errors, save gating for "Run Now" actions, and the shared tabbed `Drawer` convention.+- **Client UI conventions** (`client/src/AGENTS.md`) — no `alert`/`confirm`, `htmlFor`/`id` label pairing, mobile responsive, above the fold, no hardcoded localhost, alphabetical nav, user-facing number formatting, reactive local-state updates after mutations, silent-vs-toasting API errors, save gating for "Run Now" actions, and the shared tabbed `Drawer` convention.- **Server conventions** (`server/AGENTS.md`) — schema parity when adding fields, serializing async PATCH races on shared records, batching high-frequency state writes, peer fan-out in record-creating tests, backup exclude anchoring, and stage-prompt template migrations.- **Socket-driven UI** — invoke the `portos-socket-ui` skill before wiring or debugging a socket-driven view.- **Single-line logging** — emoji prefixes and string interpolation; never log full JSON blobs or arrays.diff --git a/client/src/AGENTS.md b/client/src/AGENTS.mdindex 629a3cf22b..03db70f61d 100644--- a/client/src/AGENTS.md+++ b/client/src/AGENTS.md@@ -25,6 +25,7 @@ These apply to React/Vite client code. Universal constraints (functional program- **Interval polling goes through `useAutoRefetch`** - a view that re-fetches on a timer uses `useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })` (`hooks/useAutoRefetch.js`), never a hand-rolled `useEffect` + `setInterval`. The hook skips its tick while `document.visibilityState === 'hidden'` and re-fires once on the way back; a raw interval keeps hammering the server from a background tab, and PortOS is routinely left open on a second machine over the tailnet (#5697). Keep the site's existing gate as `enabled` rather than an early `return`, and pass `immediate: false` when another effect already owns the first fetch. Enforced tree-wide by `client/src/pollingConventions.test.js`, which allowlists the local timers that are not polls (clock ticks, frame advances, a bounded self-cancelling poll).- **No local binding shadows a timer or `fetch`** - a `useState` pair, `useCallback`, or `const` named `setInterval` / `setTimeout` / `clearInterval` / `clearTimeout` / `requestAnimationFrame` / `cancelAnimationFrame` / `fetch` shadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (`intervalPreset`, `timeoutMinutes`, `loadRefs`). Enforced tree-wide by `client/src/globalShadowConventions.test.js`, which has no allowlist; idiomatic React state like `[open, setOpen]` / `[status, setStatus]` is deliberately out of scope because nothing here calls those globals bare.- **An async effect keyed to a switchable identity drops a superseded response** - an effect that fetches on a dependency and writes the answer into state needs a disposal guard: `let active = true;` at the top, every `set*` gated on it, `return () => { active = false; };`. Without it, switching the record faster than the request resolves renders the previous record's data under the current one — and it does not self-correct where the value is passed down as a controlled prop, so `WorkEditor` enriched one work's persisted storyboard images with another's characters and places (#7242, after #6996–#7000 were each fixed as a single site). **`useMounted()` does not cover this** — the component never unmounted, only its subject changed. Where the response must be matched against the newest request rather than merely dropped — notably when the effect writes a state value that is itself in its own dependency array, so a lifetime-scoped flag would be flipped by its own cleanup — bump and compare a generation ref instead (`IngredientPicker.jsx`). Enforced tree-wide by `client/src/asyncEffectDisposalConventions.test.js`, which allowlists the few deps that cannot select a different record (a drawer `open` flag, a once-only latch).+- **User-facing counts and amounts go through `formatCount` / `formatUsd`** (`utils/formatters.js`) — thousands-grouped and en-US-pinned (`2,762`, `$4,610.09`). An unseparated `4610` is read at the wrong order of magnitude, and a bare `.toLocaleString()` follows the browser locale, which then disagrees with the `$` beside it. A **measured** zero already renders `0`; `formatCount` gives `—` only for a value that is missing or unparseable, so pass `{ fallback: '0' }` just where an ABSENT count should still read as zero. Enforced tree-wide by `client/src/numberFormattingConventions.test.js` — any new bare `.toLocaleString(` call under `client/src` fails CI. Other formatters (`formatBytes`, `timeAgo`, …) live beside them — see the helper catalog in the root `AGENTS.md`.- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback## API errors and save gating