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
docs: trim root AGENTS.md by 10KB, moving long-form rationale into docs
[._.]/ Adam Eivy332a29cce64c
diff --git a/AGENTS.md b/AGENTS.mdindex 2ade38cd0c..b715041d75 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,8 +1,8 @@# AGENTS.md-This file provides guidance to every AI coding agent working in this repository — Claude Code, Codex, Antigravity (`agy`), grok, cursor-agent, OpenCode, and the local-model providers that front them.+Guidance for every AI coding agent working in this repository — Claude Code, Codex, Antigravity (`agy`), grok, cursor-agent, OpenCode, and the local-model providers that front them.-`AGENTS.md` is the canonical file. The `CLAUDE.md` beside it is a one-line `@AGENTS.md` import, because Claude Code's memory discovery hardcodes `CLAUDE.md` and has no configurable filename — an import rather than a symlink so it survives a Windows checkout without symlink support, and so a CLI that reads both names doesn't ingest the body twice. Both files exist at the root and at each nested location below. **Edit `AGENTS.md`; never put content in a `CLAUDE.md`.**+`AGENTS.md` is the canonical file. The `CLAUDE.md` beside it is a one-line `@AGENTS.md` import (Claude Code hardcodes that filename) — an import rather than a symlink so it survives a Windows checkout and a CLI that reads both names doesn't ingest the body twice. Both files exist at the root and at each nested location below. **Edit `AGENTS.md`; never put content in a `CLAUDE.md`.**## Commands@@ -15,127 +15,94 @@ npm run install:all # includes git submodule update --init --recursive# per workspace to scope to one — both are Vitest, with different environments:cd server && npm test # Vitest (node) — ALSO globs ../scripts, ../lib, ../autofixercd client && npm test # Vitest (happy-dom) — component/unit tests-# No NODE_ENV prefix needed: server/vitest.config.js FORCES NODE_ENV=test (#4554).-# Vitest only defaults it when unset, and PortOS runs under PM2 with-# NODE_ENV=development — a suite run that inherits that aims at the real Postgres.+# No NODE_ENV prefix needed: server/vitest.config.js FORCES NODE_ENV=test (#4554),+# because PortOS runs under PM2 with NODE_ENV=development and a suite that+# inherits it aims at the real Postgres.npm run test:db # DB-backed suites → portos_test ONLY (see Security Model)```## Test Strategy: Value Over Assertion Count-PortOS tests move **up the stack as behavior stabilizes**. The default new test-is the highest practical public boundary: an Express route, service workflow,-persisted-store adapter, socket exchange, or rendered user interaction. A-boundary test should cover the success path plus the materially different-failure/compatibility paths; it should not enumerate every internal branch just-because the branch exists.--Do not add or retain a unit test merely to raise coverage for a deterministic-helper whose behavior is already exercised through a stable caller. When a-helper's signature and every caller would have to change together, prefer the-caller's integration contract and delete redundant helper-level examples.-Table-driven permutations are still duplication when they all prove the same-product outcome.--Focused unit tests remain valuable for behavior that a higher-level test cannot-pin 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; and pure edge cases whose failure would be-ambiguous through an integration test. Real timeout behavior gets one focused-contract test with injected/fake time — never repeated production sleeps.--Before adding a test, name the regression it uniquely catches. During 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, not goals; CI time, determinism, and-regression-detection value are the goals.+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.## Security Model-**Trust model (within one install).** Each PortOS install serves exactly one human user, on a private network behind Tailscale VPN, never exposed to the public internet. Within an install there is one server process and one user — so concurrent *request* races, mutex locking on file I/O, and atomic write patterns are unnecessary as defenses against competing actors and should not be added or flagged as concerns. Simple re-entrancy guards (per-account sync locks preventing duplicate in-flight operations; serializing two write paths that mutate the same record) are fine and expected. PortOS intentionally omits CORS restrictions, rate limiting, and full concurrency controls by default — non-issues for a single-user private-network deployment. Do not add them or flag their absence. **"Single-user" means: do not defend against multiple competing humans inside one install. It does NOT mean "assume only one install exists."**+**Trust model (within one install).** Each install serves exactly one human, on a private network behind Tailscale VPN, never exposed to the public internet — one server process, one user. Concurrent *request* races, mutex locking on file I/O, and atomic-write patterns as defenses against competing actors are unnecessary; do not add or flag them. Simple re-entrancy guards (per-account sync locks against duplicate in-flight operations; serializing two write paths that mutate the same record) are fine and expected. PortOS intentionally omits CORS restrictions, rate limiting, and full concurrency controls — non-issues here. **"Single-user" means: do not defend against multiple competing humans inside one install. It does NOT mean "assume only one install exists."****Authentication and HTTPS exist, but are OPT-IN and OFF by default.** Do not assume they are absent:- **Auth** — an optional instance password (`server/services/auth.js`, enforced by `server/services/authGate.js`) gates all of `/api/*` and `/data/*` when set, with a small always-public set (`/api/auth/status`, `/api/system/health`). Peers reach a password-gated instance via a per-peer Basic credential on the peer record, attached to every outbound hop by `peerFetch` (`server/lib/peerHttpClient.js`).-- **HTTPS** — provisioned by `npm run setup:cert`; `:5555` flips to TLS with a loopback-only HTTP mirror on `:5553`. Peer hops set `rejectUnauthorized: false` ("Tailnet is the trust boundary") — between two tailnet nodes WireGuard already supplies mutual auth, but a non-tailnet peer (plain LAN IP / non-`.ts.net` host, see `peerRequiresTailscale()`) gets no server authentication.+- **HTTPS** — provisioned by `npm run setup:cert`; `:5555` flips to TLS with a loopback-only HTTP mirror on `:5553`. Peer hops set `rejectUnauthorized: false` ("Tailnet is the trust boundary"): between two tailnet nodes WireGuard supplies mutual auth, but a non-tailnet peer (plain LAN IP / non-`.ts.net` host, see `peerRequiresTailscale()`) gets no server authentication.-Because both are off by default, **never treat "the password is set" as an available guarantee** when designing a feature — gate on it explicitly, or design for the default posture. **PII must not ride the federation layer at all** — see ADR [privacy records machine-local](docs/decisions/2026-08-08-privacy-records-machine-local.md). That rule governs *records* and *status/capability payloads*; one scoped carve-out is a submitted job body carrying the conditioning an allowlisted peer is being asked to render — the prompt (ADR [federated visual prompts](docs/decisions/2026-08-20-federated-visual-prompts.md)), and, under the same gate, lyrics and conditioning images (ADR [conditioning crosses to an allowlisted peer](docs/decisions/2026-08-22-federated-media-input-assets.md), which also records what stays refused: model weights and multi-step chain state). Explicit Eidoverse guest conversations have a separate narrow carve-out: submitted world-chat messages and live replies may cross an enabled registered peer under guest admission and the independent default-off Mind travel grant (ADR [Eidoverse guest chat](docs/decisions/2026-09-05-eidoverse-guest-chat.md)). No private records, secrets, automatic conversation-history exports, or record-bearing status payloads are authorized by that exception.+Because both are off by default, **never treat "the password is set" as an available guarantee** — gate on it explicitly, or design for the default posture. **PII must not ride the federation layer at all** — ADR [privacy records machine-local](docs/decisions/2026-08-08-privacy-records-machine-local.md). That governs *records* and *status/capability payloads*. The only carve-outs are a submitted job body carrying the conditioning an allowlisted peer is asked to render — the prompt (ADR [federated visual prompts](docs/decisions/2026-08-20-federated-visual-prompts.md)) and, under the same gate, lyrics and conditioning images (ADR [conditioning crosses to an allowlisted peer](docs/decisions/2026-08-22-federated-media-input-assets.md), which also records what stays refused: model weights and multi-step chain state) — and explicit Eidoverse guest conversations, where submitted world-chat messages and live replies may cross an enabled registered peer under guest admission and the independent default-off Mind travel grant (ADR [Eidoverse guest chat](docs/decisions/2026-09-05-eidoverse-guest-chat.md)). No private records, secrets, automatic conversation-history exports, or record-bearing status payloads are authorized by those exceptions.-**Distribution model (across installs).** PortOS is distributed software: many independent people each run their own install, on their own machine(s), each upgrading on their own schedule — and a single user commonly runs **several machines federated as sync peers**. Backward/forward compatibility across installs and versions is first-class, NOT optional:+**Distribution model (across installs).** PortOS is distributed software: many independent people each run their own install, upgrading on their own schedule, and a single user commonly runs **several machines federated as sync peers**. Backward/forward compatibility across installs and versions is first-class:-- **Never delete or skip migration / compatibility code on the grounds that "there's only one install."** There isn't — other people and other machines run this code and update it independently.-- On-disk format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`). Seed files must ship in `data.reference/`.-- **A migration that DERIVES `data/<x>` from an install's existing records ships NO `data.reference/<x>` seed, and gates on the presence of its INPUT — never the absence of its output.** `setup-data.js` runs before `run-migrations.js` and copies every `data.reference/` file the install lacks, so a seed lands first; a migration that skips because its output already exists then silently leaves shipped defaults where the user's data was, and the next write destroys the original. Declare such a path in `scripts/lib/migrationOwnedPaths.js` (its test fails if a seed reappears). The applied-list already provides re-run safety, so gating on the input costs nothing. This is not hypothetical: it replaced CoS settings with shipped defaults on any install whose update crossed #6182 — see `scripts/migrations/340-cos-config-seed-repair.js`.-- Prompt-default changes are two steps: bump the prompt's `PROMPT_VERSIONS` entry, then run `node scripts/regen-prompt-integrity-snapshot.js`. The tool retires the outgoing default's hash into `server/services/taskPromptDefaults/integrity.snapshot.json`, which is how other installs recognize the stored prompt they hold as a shipped default and auto-upgrade it (`promptMatchesShippedDefault`), and it refuses a body change with no bump. The retired bodies themselves live only in git history — never paste one back into the tree as recognition data; the single literal that remains (`taskPromptDefaults/retiredPromptFixtures.js`) is a test fixture whose hash the recognition test pins.+- **Never delete or skip migration / compatibility code on the grounds that "there's only one install."** Other people and other machines run this code and update it independently.+- On-disk format changes need a migration in `scripts/migrations/` (applied-list tracked per install in `data/migrations.applied.json`). Seed files ship in `data.reference/`.+- **A migration that DERIVES `data/<x>` from an install's existing records ships NO `data.reference/<x>` seed, and gates on the presence of its INPUT — never the absence of its output.** `setup-data.js` runs before `run-migrations.js` and copies every `data.reference/` file the install lacks, so a seed lands first; a migration that skips because its output already exists then leaves shipped defaults where the user's data was, and the next write destroys the original. Declare such a path in `scripts/lib/migrationOwnedPaths.js` (its test fails if a seed reappears). The applied-list already provides re-run safety. This replaced CoS settings with shipped defaults on installs crossing #6182 — see `scripts/migrations/340-cos-config-seed-repair.js`.+- Prompt-default changes are two steps: bump the prompt's `PROMPT_VERSIONS` entry, then run `node scripts/regen-prompt-integrity-snapshot.js`. The tool retires the outgoing default's hash into `server/services/taskPromptDefaults/integrity.snapshot.json` — how other installs recognize a stored prompt as a shipped default and auto-upgrade it (`promptMatchesShippedDefault`) — and refuses a body change with no bump. Retired bodies live only in git history; never paste one back as recognition data (the one literal in `taskPromptDefaults/retiredPromptFixtures.js` is a test fixture).- Cross-machine sync payloads stay version-gated (`server/lib/schemaVersions.js`) so a newer peer can't corrupt an older one.-- The self-update path stays fork-aware — other users run forks, not just upstream. **Never add `--force` to the server-side `gh repo sync`** (it would discard a user's fork commits; the 409 `FORK_DIVERGED` message points them at running it themselves). Don't re-hardcode the upstream slug outside `server/lib/gitRemote.js`, and new UI claiming "you are running PortOS" must read `remoteInfo.isUpstream`, not just `currentVersion`, or it lies to fork users. Mechanism: [docs/SELF_UPDATE.md](docs/SELF_UPDATE.md).+- The self-update path stays fork-aware — other users run forks. **Never add `--force` to the server-side `gh repo sync`** (it would discard a user's fork commits; the 409 `FORK_DIVERGED` message points them at running it themselves). Don't re-hardcode the upstream slug outside `server/lib/gitRemote.js`, and new UI claiming "you are running PortOS" must read `remoteInfo.isUpstream`, not just `currentVersion`. Mechanism: [docs/SELF_UPDATE.md](docs/SELF_UPDATE.md).-**The default database password `portos`** (in `ecosystem.config.cjs`, `docker-compose.yml`, `.env.example`) is an intentional backward-compatible fallback for local development. Do not remove it or flag it as a security concern. Production overrides it via `PGPASSWORD`.+**The default database password `portos`** (in `ecosystem.config.cjs`, `docker-compose.yml`, `.env.example`) is an intentional backward-compatible fallback for local development. Do not remove it or flag it. Production overrides it via `PGPASSWORD`.-**Storage backend policy.** PostgreSQL (system `:5432` or Docker `:5561`) is a **mandatory** dependency for every install and every federated peer — provisioned by `npm run setup:db` (ADR `docs/decisions/2026-06-07-postgres-as-primary-datastore.md`, `docs/STORAGE.md`). **`MEMORY_BACKEND=file` is a development/test-only escape hatch, NOT a supported deployment mode** — the creative catalog/pgvector, federation, and backup all assume Postgres with no file-backed equivalent. When `MEMORY_BACKEND` is unset, `server/services/memoryBackend.js` requires a healthy DB and fails fast with no silent fallback. That is **intentional**: do not "fix" the no-fallback behavior, re-add a file menu choice in `scripts/setup-db.js`, or treat the file backend as a fallback for real installs. The file path stays runnable only because `NODE_ENV=test` selects it — guarded from bitrot by the suite, not promoted to a deployment option.+**Storage backend policy.** PostgreSQL (system `:5432` or Docker `:5561`) is a **mandatory** dependency for every install and every federated peer, provisioned by `npm run setup:db` (ADR `docs/decisions/2026-06-07-postgres-as-primary-datastore.md`, `docs/STORAGE.md`). **`MEMORY_BACKEND=file` is a development/test-only escape hatch, NOT a supported deployment mode** — the creative catalog/pgvector, federation, and backup all assume Postgres. When `MEMORY_BACKEND` is unset, `server/services/memoryBackend.js` requires a healthy DB and fails fast with no silent fallback. That is **intentional**: do not "fix" it, re-add a file choice to `scripts/setup-db.js`, or treat the file backend as a fallback. The file path stays runnable only because `NODE_ENV=test` selects it.-**Third-party API keys for free, non-monetary services are not security findings.** PortOS calls a few free external APIs (e.g. CivitAI model downloads) with an API key in a query parameter or header. Proposals to host-allowlist the download URL before attaching the key, strip the key across redirects, or similar are won't-fix: leaking that key **to an unintended host** has no monetary loss and no meaningful security consequence — worst case is quota abuse against a free service, borne by that service. (This exempts only that class of finding; the key is still a secret under Sensitive Data & Privacy below — never commit or log it.) This does NOT extend to paid/quota-billed providers (LLM API keys, payment gateways) or keys gating money-bearing or destructive actions, which retain full hardening requirements. Precedent: issue #2200, closed 2026-07-04 (`applyDownloadToken` in `server/services/loras.js#installFromCivitai`).+**Third-party API keys for free, non-monetary services are not security findings.** PortOS calls a few free external APIs (e.g. CivitAI model downloads) with an API key in a query parameter or header. Host-allowlisting the URL before attaching the key, stripping it across redirects, and similar are won't-fix: leaking that key to an unintended host costs nothing beyond quota abuse against a free service. (The key is still a secret under Sensitive Data & Privacy — never commit or log it.) This does NOT extend to paid/quota-billed providers or keys gating money-bearing or destructive actions. Precedent: issue #2200 (`applyDownloadToken` in `server/services/loras.js#installFromCivitai`).-**Never run DB-backed tests against the real `portos` database.** There is ONE Postgres per install, shared by every git worktree (including CoS-agent worktrees). The `*.db.test.js` suites `DELETE FROM`/`INSERT` whole tables, so running them against `portos` corrupts the user's real universes/series/writers-room/catalog. They are gated to skip on a non-test DB and run only via `npm run test:db` (→ `portos_test`, provisioned by `npm run setup:db:test`). The gate in `server/lib/db.js` keys on `isTestRunner()` (`NODE_ENV==='test'` **OR** `process.env.VITEST` — not bare `NODE_ENV`, so a wrapper that drops `NODE_ENV` can't disarm it), and the `query()` backstop refuses ALL row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`) to a non-test DB under the runner. Do not weaken either to "just `NODE_ENV`" or "DELETE-only" — that's exactly the hole that wiped real data on 2026-06-13/14. See `server/lib/db.guards.test.js`.+**Never run DB-backed tests against the real `portos` database.** There is ONE Postgres per install, shared by every git worktree (including CoS-agent worktrees). The `*.db.test.js` suites `DELETE FROM`/`INSERT` whole tables, so running them against `portos` corrupts the user's real data. They are gated to skip on a non-test DB and run only via `npm run test:db` (→ `portos_test`, provisioned by `npm run setup:db:test`). The gate in `server/lib/db.js` keys on `isTestRunner()` (`NODE_ENV==='test'` **OR** `process.env.VITEST`, so a wrapper that drops `NODE_ENV` can't disarm it), and the `query()` backstop refuses ALL row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`) to a non-test DB under the runner. Do not weaken either to "just `NODE_ENV`" or "DELETE-only" — that hole wiped real data on 2026-06-13/14. See `server/lib/db.guards.test.js`.## AI Provider Usage Policy-**No cold-bootstrap LLM calls.** PortOS must never queue up AI provider calls a user hasn't knowingly triggered. A new install (or a freshly merged feature) coming online should be silent on the LLM front until the user actually asks for AI-backed work. This rules out:--- Firing LLM calls from server boot / `server/index.js` init sequences (cache warm-ups, pre-generation, startup backfills).-- Any background job that silently expands from "generate the one thing the user asked for" into "generate a whole batch for later," without the user having opted into that batch.--**Scheduled automations are the one sanctioned exception** — a cron-style task, autopilot, or CoS agent the user explicitly configured (`taskSchedule.js`, `backupScheduler.js`, autopilot gates) is expected to call AI providers on its own schedule, because the user set it up and knows it's running. Anything else touching an AI provider needs either a direct user action in the same request, or an explicit consent/config step first.--**Pattern for background pre-generation (e.g. caches):**+**No cold-bootstrap LLM calls.** PortOS must never queue AI provider calls a user hasn't knowingly triggered. A new install (or freshly merged feature) coming online stays silent on the LLM front until the user asks for AI-backed work. This rules out LLM calls from server boot / `server/index.js` init (cache warm-ups, pre-generation, startup backfills), and any background job that silently expands from "generate the one thing the user asked for" into "generate a whole batch for later."-1. Boot-time init loads only what's already on disk — zero LLM calls.-2. The bulk/cold fill runs only from an explicit user-triggered endpoint, gated behind a UI prompt that names the provider/model about to be used and lets the user change it (or decline and get a single on-demand generation instead).-3. Incremental top-ups after the user has already engaged with the feature (replenishing one item after they consumed one from a primed cache) are fine to run silently — the user consented once, and a small top-up doesn't route through a slow provider unannounced the way a from-zero batch does.+**Scheduled automations are the one sanctioned exception** — a cron-style task, autopilot, or CoS agent the user explicitly configured (`taskSchedule.js`, `backupScheduler.js`, autopilot gates) may call providers on its own schedule. Anything else needs a direct user action in the same request, or an explicit consent/config step first.-Reference implementation: `server/services/meatspacePostDrillCache.js` (`initDrillCache` / `requestCacheFill` split) and `client/src/components/meatspace/post/WordplayTrainer.jsx` (`CacheFillConsentModal`) — added after a fresh MeatSpace POST install triggered an unannounced 40-call sequential TUI backfill on first boot.+**Pattern for background pre-generation (e.g. caches):** boot-time init loads only what's on disk (zero LLM calls); the bulk/cold fill runs only from an explicit user-triggered endpoint behind a UI prompt that names the provider/model and lets the user change it or decline; incremental top-ups after the user has engaged (replenishing one item they consumed) may run silently. Reference: `server/services/meatspacePostDrillCache.js` (`initDrillCache` / `requestCacheFill`) and `client/src/components/meatspace/post/WordplayTrainer.jsx` (`CacheFillConsentModal`).## Architecture-The server is always user-facing on `:5555` (HTTP or HTTPS). The client runs on the Vite dev server at `:5554` under `npm run dev`; under `npm start` the built client is served from `:5555` directly. PM2 manages app lifecycles. Where a given record persists (Postgres vs a `data/` file) is decided by the storage-classification contract in `docs/STORAGE.md`.+The server is always user-facing on `:5555` (HTTP or HTTPS). The client runs on the Vite dev server at `:5554` under `npm run dev`; under `npm start` the built client is served from `:5555`. PM2 manages app lifecycles. Where a record persists (Postgres vs a `data/` file) is decided by `docs/STORAGE.md`.-**Ports.** PortOS uses 5553–5561 (system PostgreSQL on 5432, Docker PostgreSQL on 5561). When HTTPS is on, the loopback-only HTTP mirror on `:5553` is what local curl/scripts should hit to skip the cert warning. Define ports in the top-level `PORTS` object in `ecosystem.config.cjs` (canonical re-export at `server/lib/ports.js`). Full guide and diagram: `docs/PORTS.md`.+**Ports.** PortOS uses 5553–5561 (system PostgreSQL on 5432, Docker PostgreSQL on 5561). When HTTPS is on, local curl/scripts hit the loopback-only HTTP mirror on `:5553` to skip the cert warning. Define ports in the top-level `PORTS` object in `ecosystem.config.cjs` (re-exported at `server/lib/ports.js`). Guide and diagram: `docs/PORTS.md`.-**Never run `npm ci` or `npm install` from inside a CoS worktree (`data/cos/worktrees/*`).** A fresh `git worktree` has no `node_modules`, so agents symlink the primary checkout's `node_modules`, `client/node_modules` and `server/node_modules` into the worktree to make `vitest` runnable. npm does not treat that symlink as a boundary: it empties the **target** — the primary checkout's real `node_modules` — then replaces the symlink with a fresh real directory in the worktree and installs there. The primary is left with an EMPTY `node_modules`, and removing the worktree does nothing to restore it. This is not a slow-burn annoyance, it takes the whole CoS fleet down at once: `portos-cos` keeps running on its already-loaded node-pty binding, but node-pty execs its `spawn-helper` binary from disk on EVERY spawn, so every agent spawn then fails with the opaque `posix_spawn failed: No such file or directory` until someone reinstalls. If a worktree is missing dependencies, symlink them from the primary checkout and call the workspace binaries directly (`server/node_modules/.bin/vitest run <files>`) — never install. Recovery is `npm install --prefix server` (and `client`) in the PRIMARY checkout, then `pm2 restart portos-cos`. The runner names this fault instead of retrying it — see `server/lib/ptySpawnDiagnostics.js`.+**Never run `npm ci` or `npm install` from inside a CoS worktree (`data/cos/worktrees/*`).** Worktrees get the primary checkout's `node_modules` (root, `client/`, `server/`) by symlink; npm follows the symlink and empties the PRIMARY checkout's real `node_modules`, which takes every agent spawn down with `posix_spawn failed: No such file or directory` until someone reinstalls. If a worktree is missing dependencies, symlink them from the primary checkout and call the workspace binaries directly (`server/node_modules/.bin/vitest run <files>`) — never install. Recovery and mechanism: `docs/TROUBLESHOOTING.md` ("Every Agent Spawn Fails…"); the runner names the fault in `server/lib/ptySpawnDiagnostics.js`.-**Backup excludes.** `DEFAULT_EXCLUDES` in `server/services/backup.js` is **rsync filter syntax — every path must be anchored with a leading `/`.** An unanchored pattern matches at any depth and silently drops unrelated user data; that is a data-loss bug, not a style nit. See `docs/BACKUP.md` for the failure mode, the `overridable` tiers, and `computeEffectiveExcludes()`.+**Backup excludes.** `DEFAULT_EXCLUDES` in `server/services/backup.js` is **rsync filter syntax — every path must be anchored with a leading `/`.** An unanchored pattern matches at any depth and silently drops unrelated user data; that is a data-loss bug. See `docs/BACKUP.md` for the `overridable` tiers and `computeEffectiveExcludes()`.### Per-directory conventions-Client- and server-specific conventions live in nested memory files that load when you work in those trees (each is an `AGENTS.md` with a bridge `CLAUDE.md` beside it):+Client- and server-specific conventions live in nested memory files that load when you work in those trees (each an `AGENTS.md` with a bridge `CLAUDE.md`):- `client/src/AGENTS.md` — UI conventions, routing/deep-linking, API error/save gating, the shared `Drawer` convention- `client/src/components/dashboard/AGENTS.md` — widget registration, grid/arrange mechanics, ⌘K layout wiring-- `server/AGENTS.md` — schema parity, write serialization, peer fan-out in tests, prompt-template migrations-- `server/lib/aiToolkit/AGENTS.md` — the override-consistency contract for the vendored provider/runner/prompt toolkit (self-contained: no imports out to other PortOS modules). PortOS overrides `executeCliRun`/`stopRun`/`isRunActive` and mirrors time-based provider-status recovery on read — read it before editing the runner or provider config.+- `server/AGENTS.md` — schema parity, write serialization, peer fan-out in tests, generated manifests, prompt-template migrations+- `server/lib/aiToolkit/AGENTS.md` — the override-consistency contract for the vendored provider/runner/prompt toolkit (self-contained: no imports out to other PortOS modules). Read it before editing the runner or provider config.-**Nested files reach API-provider agents too — but the walk is bounded.** Nested instruction files load on demand in the agent CLIs, and `getAgentInstructionsContext()` in `server/services/agentPromptBuilder.js` splices them into the prompts PortOS builds for its own API-provider agents as well (`~/.claude/CLAUDE.md` — Claude Code's user-level memory, which keeps that name — then the workspace-root file, then every nested one as its own labeled section). It matches `AGENTS.md` and `CLAUDE.md`, prefers `AGENTS.md`, contributes ONE entry per directory when both are present, and skips a bridge `CLAUDE.md` whose whole body is the `@AGENTS.md` import. The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and any subdirectory carrying its own `.git` (submodules and vendored checkouts, e.g. `lib/slashdo/`). Two consequences: **a rule that must reach every agent has to sit inside that budget** — if the repo ever exceeds 10 nested files, the overflow is silently dropped, so raise the cap in the same change rather than assuming coverage; and **the root file is the only guaranteed-first slot**, so a rule guarding data loss, a destructive action, privacy, or spend still belongs here when it must outrank a subtree convention (that is why the backup-exclude anchoring rule above sits in root rather than `server/AGENTS.md`).+**Nested files reach API-provider agents too — but the walk is bounded.** `getAgentInstructionsContext()` in `server/services/agentPromptBuilder.js` splices `~/.claude/CLAUDE.md`, the workspace-root file, then every nested one (`AGENTS.md` preferred, one entry per directory, bridge `CLAUDE.md`s skipped) into the prompts PortOS builds for its API-provider agents. The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and any subdirectory with its own `.git`. Consequences: **a rule that must reach every agent has to sit inside that budget** (raise the cap in the same change if the repo exceeds 10 nested files), and **the root file is the only guaranteed-first slot** — a rule guarding data loss, a destructive action, privacy, or spend belongs here when it must outrank a subtree convention.### Command Palette & Voice Nav — shared backbone`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 (`post`, `datadog`, `jira`) the user toggles in **Settings > Features**; `server/services/instanceFeatures.js` resolves each one as stored override → auto-detection of the integration it fronts → `defaultEnabled`. A nav entry tagged `feature: '<id>'` (or living in a section listed in navManifest's `SECTION_FEATURE` map) drops out of `⌘K` and the sidebar while that feature is off — **the `<Route>` keeps working, so bookmarks, direct links, and voice `ui_navigate` still resolve**. The gate is applied CLIENT-side (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), not by filtering the manifest response: `⌘K` and the voice widget each fetch `/api/palette/manifest` once per session and it is HTTP-cached, so a server-side filter would both defeat that cache and still show hidden pages until a reload. A sidebar row still needs its own `NAV_PRESENTATION` entry in `client/src/lib/navPresentation.js` (path → icon), which `Layout.jsx` iterates; `feature`, `section` and `label` are inherited from `NAV_COMMANDS`, so the path is the one thing declared twice — the icon lives only in `NAV_PRESENTATION` — and a manifest tag alone yields no sidebar row — `NAV_PRESENTATION`'s keys are the set the sidebar iterates. `Layout.test.jsx` pins that every Settings, Digital Twin and Messages sub-tab path has a `NAV_PRESENTATION` entry, and that each entry stays presentation-only (an icon, no `to`/`label`/`section`/`feature`) keyed to a live manifest path. `navManifest.test.js` fails when a tag names an unregistered feature, or when a `SECTION_FEATURE` key stops matching a live section.--**Feature groups bucket related features under one toggle, additively.** `INSTANCE_FEATURE_GROUPS` in `server/lib/instanceFeatureRegistry.js` declares the groups (today: `comms`, holding FaceTime Audio, iMessage, Signal, X, Stacker News and Beeper); a feature joins one by carrying `group: '<groupId>'` on its descriptor, which is the whole edit. `resolveOne` in `server/services/instanceFeatures.js` resolves a grouped feature as **its own stored override → the group flag → the detector → `defaultEnabled`**: an explicit per-feature override always wins, and only a feature left on "inherit" answers to its group (group off hides it, group on hands it straight back to its normal resolution). Setting an override back to inherit deletes the stored key rather than writing a third sentinel, so it reads exactly like a feature nobody ever touched. **A group's own `enabled` defaults to `true` when no group state is stored** — that default is the parity guarantee: an install with no `instanceFeatureGroups` in settings resolves every member exactly as it did before the group existed, so registering a group is never a silent hide and needs no settings migration. Malformed group settings fail toward `false`, matching the per-feature override's own posture. An ungrouped feature is completely unaffected.--**A feature toggle that arms background work must reconcile that work at toggle time, not only at boot.** A subsystem gated on "feature on AND credential present" and started once in `services/bootstrap.js` is silently wrong the moment either half of that gate moves at runtime: on a live install, storing a Beeper credential left the realtime transport down and no sweep registered for 48 minutes, until a restart — and the mirror-image gap left a socket relaying on a token a disconnect had just revoked. Give the subsystem one idempotent `reconcile…()` that reads the gate and moves everything to match it, and call it from every path that can move the gate (each credential write, the feature toggle, the group toggle, disconnect). Make repeat calls no-ops rather than re-registrations — re-`schedule()`ing an existing event resets `nextRunAt` a full interval out, so an unrelated toggle would keep pushing the next run away — serialize overlapping calls on one tail, and log transitions only, so an install that has never enabled the feature still narrates nothing. `server/services/beeperArming.js` is the worked example.+**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`.### Slashdo Commands (`lib/slashdo`)-PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing slash commands (`/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, …) without a separate global install. The `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents use the shared slashdo renderer: file-tool hosts receive a short entrypoint with supporting files read by phase; `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` remains the eager, self-contained form for other consumers.+PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`, providing `/do:next`, `/do:review`, `/do:pr`, `/do:push`, `/do:release`, … without a global install; `.claude/commands/do/` symlinks expose them as project-level slash commands. `/do:next` claims the next PLAN.md item (or GitHub issue with `--issues`) in an isolated worktree and ships a PR. CoS agents use the shared slashdo renderer: file-tool hosts receive a short entrypoint with supporting files read by phase; `loadSlashdoCommand(name)` from `server/services/subAgentSpawner.js` is the eager, self-contained form.-Project command symlinks expose slashdo source directly. In that source, `!read lib/<name>.md` means read `lib/slashdo/lib/<name>.md` when the named phase applies; resolve nested library references (including `~/.claude/lib/<name>.md` tokens) against that same bundled package root. These are required reads, not shell commands. Do not preload every phase or depend on a global slashdo installation. Staged CoS bundles instead resolve each reference relative to the file containing it.+In that source, `!read lib/<name>.md` means read `lib/slashdo/lib/<name>.md` when the named phase applies; resolve nested references (including `~/.claude/lib/<name>.md` tokens) against the same bundled package root. These are required reads, not shell commands. Do not preload every phase or depend on a global slashdo installation. Staged CoS bundles resolve each reference relative to the file containing it.## Module Organization-PortOS has reached the size where re-implementing a helper is cheaper to *start* than finding what already exists. To keep that pressure off, every directory holding reusable code carries a catalog `README.md` and an enumerable `index.js` barrel. **Before writing a helper, grep the catalog.**+PortOS is large enough that re-implementing a helper is cheaper to *start* than finding what exists. Every directory holding reusable code carries a catalog `README.md` and an enumerable `index.js` barrel. **Before writing a helper, grep the catalog.**### Where new code lives@@ -145,14 +112,12 @@ PortOS has reached the size where re-implementing a helper is cheaper to *start*- **HTTP / Socket / browser clients** → `client/src/services/`. API wrappers start with `api*`.- **Express handlers** → `server/routes/`. Use `validateRequest` + `lib/validation.js` schemas.- **Domain orchestration (multi-step business logic over models + services)** → `server/services/`-- **Persisted data (PostgreSQL vs a `data/` file)** → decide via the storage-classification contract in `docs/STORAGE.md` *before* defaulting to a new `data/*.json`. App-native relational records are `db-primary`; that doc's "Adding a new data store?" checklist is required in PR review.+- **Persisted data (PostgreSQL vs a `data/` file)** → decide via `docs/STORAGE.md` *before* defaulting to a new `data/*.json`. App-native relational records are `db-primary`; that doc's "Adding a new data store?" checklist is required in PR review.One concern per file. Tests live next to their source as `<name>.test.js`. Naming is camelCase with a domain prefix (`brainValidation.js`, `creativeDirectorPrompts.js`).### Discovery rule (BEFORE writing a helper)-Grep the catalog for the directory most likely to hold it:-```bashgrep -i "what you want to do" server/lib/README.mdgrep -i "what you want to do" client/src/lib/README.md@@ -160,48 +125,41 @@ grep -i "what you want to do" client/src/hooks/README.mdgrep -i "what you want to do" client/src/services/README.md```-If a close match exists, **extend it or use it**. Only add a new module when none fits. Pre-existing helpers that are easy to miss:+If a close match exists, **extend it or use it**. Only add a new module when none fits. Easy-to-miss helpers:- `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 monolithic single-JSON-file shape (large per-record payload, frequent mutations), use this instead of rolling another `readJSONFile` + `atomicWrite` + `createFileWriteQueue`. Lays out `data/{type}/{id}/index.json` with a type-level `data/{type}/index.json` stamping `schemaVersion` (the storage-layout version, distinct from any per-record-shape `schemaVersion` the sanitizer carries). 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 splits the legacy `universe-builder.json` into this shape).+- `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).- `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 top of it.+- `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.### Maintenance rule (WHEN adding a public module)-Any new file in `server/lib/`, `client/src/lib/`, `client/src/hooks/`, `client/src/utils/`, or a new `apiX.js` in `client/src/services/` **MUST**:+Any new file in `server/lib/`, `client/src/lib/`, `client/src/hooks/`, `client/src/utils/`, or a new `apiX.js` in `client/src/services/` **MUST** (1) be re-exported from the same-directory `index.js` barrel (or, for `services/`, from `api.js`) and (2) get a one-line row in the same-directory `README.md`. Enforced: `server/lib/index.test.js` and its client counterparts fail when a non-test `.js` file is missing from either.-1. Be re-exported from the same-directory `index.js` barrel (or, for `services/`, from `api.js`).-2. Get a one-line row in the same-directory `README.md`.+**Catalogs and barrels merge with git's `union` driver** (`.gitattributes`), because every branch inserts one sorted line and concurrent branches collide on the same hunk. Union keeps both sides — right for an insertion, wrong for an edit or deletion beside one — so after a rebase that touched a catalog, `scripts/catalog-merge-union.test.js` fails on a doubled or resurrected row; keep one and move on. Never give a file with real code paths the `union` attribute; the guard rejects a `.js` that is not a pure re-export barrel.-This is the one rule that keeps catalogs from rotting, and it is enforced: `server/lib/index.test.js` and its client counterparts fail when a non-test `.js` file is missing from either the barrel or the README.+**Name collisions.** When two modules in one directory export the same identifier (e.g. `settingsUpdateInputSchema` in both `brainValidation.js` and `digitalTwinValidation.js`), the barrel uses `export * as <name>` namespace exports so callers reach for `brainValidation.settingsUpdateInputSchema` explicitly. Catch-all modules like `validation.js` stay flat. The collision-detector test fails if two flat-`export *` modules share an identifier.-**These catalogs and barrels merge with git's `union` driver** (`.gitattributes`), because every branch inserts one sorted line into each and two concurrent branches routinely collide on the same hunk. Union keeps both sides, which is right for an insertion and wrong for an edit or deletion beside one — so after a rebase that touched a catalog, `scripts/catalog-merge-union.test.js` (always-run) fails on a doubled or resurrected row; keep one and move on. Never give a file with real code paths the `union` attribute; the guard rejects a `.js` that is not a pure re-export barrel.--**Name collisions.** When two modules in one directory export the same identifier (e.g. `settingsUpdateInputSchema` in both `brainValidation.js` and `digitalTwinValidation.js`), the barrel uses `export * as <name>` namespace exports so callers reach for `brainValidation.settingsUpdateInputSchema` explicitly. Catch-all modules like `validation.js` stay flat. The collision-detector test fails if two flat-`export *` modules ever share an identifier, forcing namespace resolution where the conflict is introduced.--Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the barrel exists for *discovery*, not to force a re-import. New code may use either form. The worked example for "barrel + documented exports" is `server/lib/aiToolkit/index.js`.+Existing deep imports (`import { x } from '../lib/foo.js'`) keep working — the barrel exists for *discovery*. The worked example for "barrel + documented exports" is `server/lib/aiToolkit/index.js`.### Generated manifests are addressed by content, never by position-First 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` and `server/lib/socketEventInventory.js` are the pattern; the rationale and the one justified exception are under "Generated manifests" in `server/AGENTS.md`.--A checked-in `*.generated.json` must then change when — and *only* when — the thing it describes changes. A record pointing at `foo.js:412` breaks the *only*: any edit inserting a line above 412 rewrites it, so its drift test fires on commits that change nothing, each parallel branch regenerates it differently, and **every rebase conflicts on it**. 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.+First 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. That tests the rule itself, so it catches a position under any key name. `server/lib/generatedManifests.test.js` is the tree-wide backstop for a manifest whose generator skipped it, and it also **fails when a `scripts/generate-*.js` has no sibling test importing `positionInvariance.js`** — so adoption is structural, not a convention you have to remember. This rule lives in root because the generators are in `scripts/`, which carries no nested file; rationale and the coverage-without-positions pattern are 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 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`.## Scope Boundary-When CoS agents or AI tools work on managed apps outside PortOS, all research, plans, docs, and code for those apps must be written to the target app's own repository/directory — never to this repo. PortOS stores only its own features, plans, and documentation. A PLAN.md, research doc, or feature spec generated for another app goes in that app's directory.+When CoS agents or AI tools work on managed apps outside PortOS, all research, plans, docs, and code for those apps go in the target app's own repository/directory — never here. PortOS stores only its own features, plans, and documentation.## Sensitive Data & Privacy (developing on a live instance)-**This code is written and reviewed on a live install holding one real user's data.** Machine identity, network topology, personal records, and app-specific names read out of the running instance are the user's private data — they must never leak into anything committed, pushed, or published. Treat every artifact an agent produces (source, comments, test fixtures, docs, changelog, commit messages, PR titles/descriptions/review comments, issue text) as world-readable the moment it lands on a branch.+**This code is written and reviewed on a live install holding one real user's data.** Machine identity, network topology, personal records, and app-specific names read out of the running instance are private — they must never leak into anything committed, pushed, or published. Treat every artifact an agent produces (source, comments, test fixtures, docs, changelog, commit messages, PR titles/descriptions/review comments, issue text) as world-readable the moment it lands on a branch.**Never commit, log to a shared file, or write into a PR/issue/commit any of:**@@ -212,52 +170,48 @@ When CoS agents or AI tools work on managed apps outside PortOS, all research, p**Rules for agents:**-- **Placeholders, not observations.** When code, a test, a comment, or a doc needs an example value, invent an obviously-fake one (`example.com`, `[email protected]`, `192.0.2.10` (TEST-NET-1), `Acme Corp`, `Example Universe`, `host-XXXX`). Never transcribe a value observed in the live instance or environment.-- **Reproduce with redaction.** When a bug repro, log excerpt, or stack trace legitimately needs real state, redact the sensitive fields (`<hostname>`, `<user-email>`, `<tailscale-ip>`, `<record-id>`) before it goes into a commit, PR, issue, or review comment. The point is the shape of the data, not its contents.-- **No environment scraping into artifacts.** Do not run `hostname`, `whoami`, `ifconfig`/`ip addr`, `tailscale status`, `env`, `git config user.*` and paste the output into anything committed or published. Read them only for transient in-session logic; never persist them.-- **Scrub before you ship.** Before `git add`/commit and before opening or commenting on a PR/issue, scan your own diff and prose for the categories above. If real data slipped in, replace it with a placeholder; if it was already committed, amend/rewrite the branch before pushing rather than layering a "redaction" commit on top (the history still leaks).+- **Placeholders, not observations.** When an example value is needed, invent an obviously-fake one (`example.com`, `[email protected]`, `192.0.2.10`, `Acme Corp`, `Example Universe`, `host-XXXX`). Never transcribe a value observed in the live instance or environment.+- **Reproduce with redaction.** When a repro, log excerpt, or stack trace needs real state, redact the sensitive fields (`<hostname>`, `<user-email>`, `<tailscale-ip>`, `<record-id>`) before it goes into a commit, PR, issue, or review comment.+- **No environment scraping into artifacts.** Do not run `hostname`, `whoami`, `ifconfig`/`ip addr`, `tailscale status`, `env`, `git config user.*` and paste the output into anything committed or published. Read them only for transient in-session logic.+- **Scrub before you ship.** Before `git add`/commit and before opening or commenting on a PR/issue, scan your own diff and prose for the categories above. If real data was already committed, amend/rewrite the branch before pushing rather than layering a "redaction" commit on top.- **Absolute paths.** Prefer repo-relative paths in committed text; when an absolute path is unavoidable, strip the user segment (`~/…` or `<repo-root>/…`).-This complements the Security Model (which governs the deployed product) — this section governs what agents may *write down* while working against real data.+This complements the Security Model (the deployed product) — this section governs what agents may *write down* while working against real data.## Code Conventions-- **No try/catch** — errors bubble to centralized middleware. **Exception:** PTY/child-process/`setTimeout`/`setInterval` callbacks and any code running *outside* the Express request lifecycle. An uncaught throw there crashes the Node process (there is no `next(err)` to bubble to). At those boundaries, wrap hook invocation in try/catch and log via the emoji-prefixed `console.error` style. Async event handlers that mutate shared module-level state (e.g. the TUI spawner's `handleData`) must also be serialized — chain them onto a per-session/per-actor `Promise.resolve()` queue rather than firing concurrently, or interleaved awaits race on shared buffers.+- **No try/catch** — errors bubble to centralized middleware. **Exception:** PTY/child-process/`setTimeout`/`setInterval` callbacks and any code running *outside* the Express request lifecycle, where an uncaught throw crashes the Node process. At those boundaries, wrap hook invocation in try/catch and log via the emoji-prefixed `console.error` style. Async event handlers that mutate shared module-level state (e.g. the TUI spawner's `handleData`) must also be serialized — chain them onto a per-session/per-actor `Promise.resolve()` queue rather than firing concurrently.- **Functional programming** — no classes; use hooks in React.- **Zod validation** — all route inputs validated via `lib/validation.js`.- **Command allowlist** — shell execution restricted to approved commands only.-- **Every new page registers in the nav manifest** — adding a `<Route>` + sidebar link also means a `NAV_COMMANDS` entry in `server/lib/navManifest.js`, which makes the page reachable via `⌘K` and voice (`ui_navigate`). Invoke the `portos-add-page` skill for the entry shape.+- **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.- **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 (event-driven state swaps, single-subscriber resources, pending-request tracking, deferred-work guards).+- **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.```jsconsole.log(`🚀 Server started on port ${PORT}`);- console.log(`📜 Processing ${items.length} items`);console.error(`❌ Failed to connect: ${err.message}`);```-- **LLM response merging — distinguish absent vs intentionally empty.** When merging an LLM response into existing state, "key absent" must preserve the original while "key present with empty value" must apply the intentional clear. Don't use `.length` truthiness as the signal — it conflates the two and silently restores values the user (or LLM) just cleared.- - Strings: `null`/`undefined` = absent, `""` = a clear. Server helpers like `universeBuilderExpand.trimField` return `null` for non-strings, not `""`.- - Arrays/objects: gate on `Array.isArray(parsed?.field)` / `typeof parsed?.field === 'object'` before falling back to the original.- - Keep server-side merges and the client's `pick` helpers mirrored — a one-sided change breaks the round-trip.-- **Sentinel + validate to distinguish "not set / failed" from "present-but-empty / valid".** The `.length`-truthiness footgun above is one instance of a broader rule: never let *absent*, *failed-to-fetch*, or *invalid* collapse into the same value as *fetched-and-legitimately-empty* or *valid*. Use an explicit sentinel and validate before falling through — not `x.length` or `x || fallback`-on-mere-presence. Canonical examples in the local-LLM backends: model-list caches use `null = not fetched` vs `[] = cached-empty`, so a zero-model backend still caches instead of re-hitting the API every call (`ollamaManager.js` `installedModels`, `lmStudioManager.js` `availableModels`); `getBackend()` validates the `.env` marker first and only then falls back to `process.env`, so a stale `.env` value can't mask a valid runtime env override (`server/services/localLlm.js`); and a reachable-but-list-failed backend surfaces an explicit `modelsError` rather than reporting `0 models` (`lmStudioManager.js` `getLastListError`).+- **LLM response merging — distinguish absent vs intentionally empty.** "Key absent" preserves the original; "key present with empty value" applies the clear. Don't use `.length` truthiness as the signal. Strings: `null`/`undefined` = absent, `""` = a clear (server helpers like `universeBuilderExpand.trimField` return `null` for non-strings). Arrays/objects: gate on `Array.isArray(parsed?.field)` / `typeof parsed?.field === 'object'` before falling back. Keep server-side merges and the client's `pick` helpers mirrored.+- **Sentinel + validate to distinguish "not set / failed" from "present-but-empty / valid".** Never let *absent*, *failed-to-fetch*, or *invalid* collapse into the same value as *fetched-and-legitimately-empty* or *valid*; use an explicit sentinel and validate before falling through, not `x.length` or `x || fallback`. Canonical examples in the local-LLM backends: model-list caches use `null = not fetched` vs `[] = cached-empty` (`ollamaManager.js` `installedModels`, `lmStudioManager.js` `availableModels`); `getBackend()` validates the `.env` marker before falling back to `process.env` (`server/services/localLlm.js`); a reachable-but-list-failed backend surfaces an explicit `modelsError` rather than `0 models` (`lmStudioManager.js` `getLastListError`).## Git Workflow- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.- **Push pattern**: `git pull --rebase --autostash && git push`-- **No per-branch changelog entries.** Individual PRs do not write a changelog file or fragment — commit messages are the record. `/do:release` synthesizes the release notes from the commit log since the last tag (grouped by feature/theme) when it runs, and writes the result to `.changelog/v{version}.md`. This replaced an earlier per-branch fragment workflow (`.changelog/next/*.md` + `npm run changelog:add`), which existed to avoid parallel branches conflicting on a shared `NEXT.md` — deriving notes from commits at release time sidesteps that problem entirely, since no branch writes to `.changelog/` anymore. Consequence: **write commit subjects/bodies for a human release-note reader**, not just for `git log` — see "Git commits and PRs" in the global instructions. Full rationale: `.changelog/README.md`.-- **Release quality snapshot**: Before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only — no provider calls, no private run prose — writing and committing the repo-root `.quality.json` through the same publisher every managed app uses. If no local evidence exists it commits nothing and reports that the existing snapshot was not refreshed.-- **Versioning**: the version in `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.+- **No per-branch changelog entries.** PRs do not write a changelog file or fragment — commit messages are the record, and `/do:release` synthesizes the release notes from the commit log since the last tag into `.changelog/v{version}.md`. **Write commit subjects/bodies for a human release-note reader** (see "Git commits and PRs" in the global instructions). Rationale: `.changelog/README.md`.+- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json`; with no local evidence it commits nothing and says so.+- **Versioning**: `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.- After each feature or bug fix, run `/simplify`, then commit and push.-- **Capture deferred work, and decide rather than park it.** Deferred refactors/cleanups go into a filed GitHub issue labeled `plan`, specific enough to pick up cold — never left only in chat. When the sole obstacle is an undecided design choice, **make the call yourself** and file it ready-to-work; `future` / `needs-input` are last resorts. Invoke the `portos-file-issue` skill for the full labeling contract. Add independent slashdo dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when the work you just inspected justifies them — omit an axis rather than guessing, never stamp `medium` on both, and never mark a wide mechanical sweep as a good first issue. Also stamp `planner:<model>` — a third, independent axis naming the model that WROTE the plan — taking the value verbatim from the "Planner Attribution" section of your own prompt (PortOS resolves it from the provider/model it dispatched you with); never guess it from what you believe you are, and omit it when your run was given none. Create missing labels lazily with slashdo/GitHub colors before `gh issue create`, use repeated `--label` flags, and keep category labels (`plan`, `ux`, `bug`, `tests`) intact.-- **Never link to AI conversation sessions.** Do not paste `claude.ai`, `chatgpt.com`/`chat.openai.com`, or any other AI chat/session share URL (or a "generated by / view this conversation" link) into a PR description, commit message, issue, or review comment. These leak session context, aren't durable references, and read as AI attribution — the PR must stand on its own with a Summary and a Test plan. Reference durable artifacts instead: issue/PR numbers, commit SHAs, file paths.+- **Capture deferred work, and decide rather than park it.** Deferred refactors/cleanups go into a filed GitHub issue labeled `plan`, specific enough to pick up cold — never left only in chat. When the sole obstacle is an undecided design choice, **make the call yourself** and file it ready-to-work; `future` / `needs-input` are last resorts. Invoke the `portos-file-issue` skill for the labeling contract: independent dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when the work you just inspected justifies them — omit an axis rather than guess, never stamp `medium` on both by reflex, never mark a wide mechanical sweep a good first issue — plus `planner:<model>` taken verbatim from the "Planner Attribution" section of your own prompt (omit it when your run was given none). Create missing labels lazily with slashdo/GitHub colors before `gh issue create`, use repeated `--label` flags, and keep category labels (`plan`, `ux`, `bug`, `tests`) intact.+- **Never link to AI conversation sessions.** No `claude.ai`, `chatgpt.com`, or other AI chat/session share URL (or "view this conversation" link) in a PR description, commit message, issue, or review comment. Reference durable artifacts instead: issue/PR numbers, commit SHAs, file paths.- If enough commits have accumulated to warrant a production release, pull the latest `main` and `release`, then run `/do:release` from `main`.-- **Archive approved design plans.** When a plan is approved out of plan mode, copy the finalized plan from `~/.claude/plans/` to `./docs/plans/YYYY-MM-DD-<slug>.md` (date of approval) as a design record before implementing. See `docs/plans/README.md`.+- **Archive approved design plans.** When a plan is approved out of plan mode, copy it from `~/.claude/plans/` to `./docs/plans/YYYY-MM-DD-<slug>.md` (date of approval) before implementing. See `docs/plans/README.md`.## Documentation-[ETHOS.md](ETHOS.md) states the project's ethos — why unsupervised agent operation is the design target, what the structural guards actually protect, and the testable commitments a change must not break. Read it before proposing supervision gates, per-action confirmations, external edits to a mind's own memories, or new data that crosses the federation layer.+[ETHOS.md](ETHOS.md) states the project's ethos — why unsupervised agent operation is the design target, what the structural guards protect, and the testable commitments a change must not break. Read it before proposing supervision gates, per-action confirmations, external edits to a mind's own memories, or new data that crosses the federation layer.-`docs/README.md` indexes everything under `docs/` — guides, feature deep dives, ADRs (`docs/decisions/`), and design records (`docs/plans/`). The contracts referenced most often from code review: `docs/STORAGE.md` (where a record lives), `docs/PORTS.md`, `docs/BACKUP.md`, `docs/SELF_UPDATE.md`, `docs/ARCHITECTURE.md`, `docs/API.md`.+`docs/README.md` indexes everything under `docs/` — guides, feature deep dives, ADRs (`docs/decisions/`), and design records (`docs/plans/`). Most-referenced contracts: `docs/STORAGE.md` (where a record lives), `docs/PORTS.md`, `docs/BACKUP.md`, `docs/SELF_UPDATE.md`, `docs/ARCHITECTURE.md`, `docs/API.md`.diff --git a/docs/INSTANCE_FEATURES.md b/docs/INSTANCE_FEATURES.mdnew file mode 100644index 0000000000..4033c6f631--- /dev/null+++ b/docs/INSTANCE_FEATURES.md@@ -0,0 +1,82 @@+# Optional instance features++How per-install optional features (`post`, `datadog`, `jira`, the `comms`+integrations, …) are declared, resolved, gated in navigation, grouped under one+toggle, and kept in sync with the background work they arm. The rules here are+the long form of the "Optional features gate navigation, not routes" paragraph+in the root `AGENTS.md`; the `portos-add-page` skill covers the nav-manifest+entry itself.++## Registry and resolution++`server/lib/instanceFeatureRegistry.js` declares every optional feature the user+toggles in **Settings > Features**. `server/services/instanceFeatures.js`+resolves each one as **stored override → auto-detection of the integration it+fronts → `defaultEnabled`**.++## Navigation gating (client-side, on purpose)++A nav entry tagged `feature: '<id>'` (or living in a section listed in+navManifest's `SECTION_FEATURE` map) drops out of `⌘K` and the sidebar while+that feature is off. **The `<Route>` keeps working**, so bookmarks, direct+links, and voice `ui_navigate` still resolve.++The gate is applied CLIENT-side (`useInstanceFeatures` ++`client/src/lib/navFeatures.js`), not by filtering the manifest response: `⌘K`+and the voice widget each fetch `/api/palette/manifest` once per session and it+is HTTP-cached, so a server-side filter would both defeat that cache and still+show hidden pages until a reload.++A sidebar row still needs its own `NAV_PRESENTATION` entry in+`client/src/lib/navPresentation.js` (path → icon), which `Layout.jsx` iterates.+`feature`, `section` and `label` are inherited from `NAV_COMMANDS`, so the path+is the one thing declared twice — the icon lives only in `NAV_PRESENTATION` —+and a manifest tag alone yields no sidebar row: `NAV_PRESENTATION`'s keys are+the set the sidebar iterates. `Layout.test.jsx` pins that every Settings,+Digital Twin and Messages sub-tab path has a `NAV_PRESENTATION` entry, and that+each entry stays presentation-only (an icon, no `to`/`label`/`section`/`feature`)+keyed to a live manifest path. `navManifest.test.js` fails when a tag names an+unregistered feature, or when a `SECTION_FEATURE` key stops matching a live+section.++## Feature groups (one toggle, additive)++`INSTANCE_FEATURE_GROUPS` in `server/lib/instanceFeatureRegistry.js` declares+the groups (today: `comms`, holding FaceTime Audio, iMessage, Signal, X,+Stacker News and Beeper). A feature joins one by carrying `group: '<groupId>'`+on its descriptor — that is the whole edit.++`resolveOne` in `server/services/instanceFeatures.js` resolves a grouped+feature as **its own stored override → the group flag → the detector →+`defaultEnabled`**: an explicit per-feature override always wins, and only a+feature left on "inherit" answers to its group (group off hides it, group on+hands it straight back to its normal resolution). Setting an override back to+inherit deletes the stored key rather than writing a third sentinel, so it+reads exactly like a feature nobody ever touched.++**A group's own `enabled` defaults to `true` when no group state is stored.**+That default is the parity guarantee: an install with no+`instanceFeatureGroups` in settings resolves every member exactly as it did+before the group existed, so registering a group is never a silent hide and+needs no settings migration. Malformed group settings fail toward `false`,+matching the per-feature override's own posture. An ungrouped feature is+completely unaffected.++## A toggle that arms background work reconciles at toggle time++A subsystem gated on "feature on AND credential present" and started once in+`services/bootstrap.js` is silently wrong the moment either half of that gate+moves at runtime. On a live install, storing a Beeper credential left the+realtime transport down and no sweep registered for 48 minutes, until a+restart — and the mirror-image gap left a socket relaying on a token a+disconnect had just revoked.++Give the subsystem one idempotent `reconcile…()` that reads the gate and moves+everything to match it, and call it from every path that can move the gate+(each credential write, the feature toggle, the group toggle, disconnect).+Make repeat calls no-ops rather than re-registrations — re-`schedule()`ing an+existing event resets `nextRunAt` a full interval out, so an unrelated toggle+would keep pushing the next run away — serialize overlapping calls on one+tail, and log transitions only, so an install that has never enabled the+feature still narrates nothing. `server/services/beeperArming.js` is the+worked example.diff --git a/docs/README.md b/docs/README.mdindex 44d9e1d2c0..3e0ed7e0d9 100644--- a/docs/README.md+++ b/docs/README.md@@ -18,6 +18,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [STORAGE.md](./STORAGE.md) | Storage classification contract — PostgreSQL vs filesystem, new-data-store checklist || [BACKUP.md](./BACKUP.md) | Filesystem snapshots + PostgreSQL dumps, restore semantics || [PORTS.md](./PORTS.md) | Port allocation (5553–5561) and how 5555/5553/5554 relate |+| [INSTANCE_FEATURES.md](./INSTANCE_FEATURES.md) | Optional per-install features — registry, client-side nav gating, feature groups, reconcile-at-toggle || [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects || [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry || [MODEL-COMPARISON.md](./MODEL-COMPARISON.md) | Sourced provider/model/effort comparisons, cost estimates and CoS research refresh |diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 475e74f0fb..d66e96b21b 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -196,6 +196,35 @@ pm2 logs portos-cos --lines 100which claude```+### Every Agent Spawn Fails with `posix_spawn failed: No such file or directory`++**Cause**: `npm ci` or `npm install` was run inside a CoS worktree+(`data/cos/worktrees/*`). A fresh `git worktree` has no `node_modules`, so agents+symlink the primary checkout's `node_modules`, `client/node_modules` and+`server/node_modules` into the worktree to make `vitest` runnable. npm does not+treat that symlink as a boundary: it empties the **target** — the primary+checkout's real `node_modules` — then replaces the symlink with a fresh real+directory in the worktree and installs there. The primary is left with an EMPTY+`node_modules`, and removing the worktree does nothing to restore it.++This takes the whole CoS fleet down at once: `portos-cos` keeps running on its+already-loaded node-pty binding, but node-pty execs its `spawn-helper` binary+from disk on EVERY spawn, so every agent spawn fails with the opaque error above+until someone reinstalls. The runner names this fault instead of retrying it —+see `server/lib/ptySpawnDiagnostics.js`.++**Recovery**:+```bash+# In the PRIMARY checkout, never in a worktree+npm install --prefix server+npm install --prefix client+pm2 restart portos-cos+```++**Prevention**: if a worktree is missing dependencies, symlink them from the+primary checkout and call the workspace binaries directly+(`server/node_modules/.bin/vitest run <files>`) — never install.+### Tasks Not Being Picked Up**Symptom**: Added tasks to TASKS.md but CoS ignores them.