Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

audit and fix documentation drift across README, docs/, and feature docs

[._.]/ Adam Eivy1c263264be19
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b340c38e53..7e972a95bc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,7 @@
+## Documentation
+
+- **Full documentation audit — accuracy, organization, and a master index.** Six parallel audits verified every doc against the current code and the drift is now fixed. Highlights: `docs/API.md` corrected (the four `/api/agents/*` sections and the scaffold/templates section had wrong base paths, the stale CoS scheduled-scripts section is replaced by the real `/cos/jobs` surface, dead Socket.IO events — `detect:stream`, `errors:subscribe`, `cos:status`/`cos:log`/`script:*`/`cos:memory:*` — replaced with the real ones, and a complete route-domain index of every mounted `/api/*` prefix added, pointing at the OpenAPI spec on `/api-access`); the PostgreSQL-primary reality (June ADR) now reflected everywhere it was missing (`README.md` tech stack + contributing notes, `GOALS.md` non-goals, `docs/ARCHITECTURE.md` diagram/storage tier, `docs/CONTRIBUTING.md` prerequisites, `docs/TROUBLESHOOTING.md` database section, `docs/features/memory-system.md` storage story); `docs/DEPS.md` tables resynced to the real dependency lists (`sax` removed via #1824, `portos-ai-toolkit` vendored in-tree, `googleapis` → scoped `@googleapis/*`, missing `pdf-lib`/`sharp`/`undici` + client test deps + full override-pin list added); `docs/GITHUB_ACTIONS.md` now describes the actual CI jobs (Postgres service container, `test:ci`/`test:db:ci`, client tests, smoke boot, client lint); stale service/page paths fixed across the feature docs (`digital-twin.js`, `promptService.js`, `PromptManager.jsx`, `/api/detect/port`, JIRA sprint manager's move to the Schedule system, unbuilt M35 Phase-5 services marked "(not built)", shipped-status notes on the OpenClaw spec/audit); `ecosystem.config.cjs` docs (`docs/PM2.md`, `docs/PORTS.md`, `docs/ARCHITECTURE.md`) updated to the top-level `PORTS` convention and the real `portos-ui` process name. Organization: new `docs/README.md` master index (linked from the root README), convention READMEs for `docs/decisions/`, `docs/research/`, and `docs/superpowers/`, the brain build-plan artifacts moved from `docs/features/brain/` to `docs/plans/`, the undated research review date-prefixed, and `docs/SECURITY_AUDIT.md` labeled as the historical 2026-02 snapshot it is (title year typo fixed). README also gained the missing feature bullets (Music Studio, Music Video, Mood Boards, Catalog, Tribe, Morse/CW trainer) and the previously unlinked docs (`DEPS.md`, `GOALS_OPERATIONAL.md`, `claude-ollama.md`).
+
## AI Providers
- **MeatSpace POST wordplay drills no longer cold-bootstrap LLM calls on server boot.** `initDrillCache()` fired at every server start and, on a fresh install (empty on-disk cache), silently kicked off a sequential 40-call backfill (4 drill types × up to 10 batches each) — visibly slow and surprising when the active provider was a TUI-driven CLI, since each call pastes into a real `claude`/`codex` session and waits. Boot now only loads the existing on-disk cache into memory (zero LLM calls); the bulk cache-fill only runs from a new explicit `POST /api/meatspace/post/drill-cache/fill` endpoint, gated behind a client-side consent modal (`CacheFillConsentModal` in `WordplayTrainer.jsx`) that names the provider about to be used and lets the user pick a different provider/model or skip straight to a single on-demand drill. Incremental top-ups after a cache has already been primed still run silently (`triggerReplenish` now no-ops on a cold/empty cache). See the new "AI Provider Usage Policy" section in `CLAUDE.md` — no PortOS feature should queue AI provider calls a user hasn't knowingly triggered, outside of automations the user explicitly scheduled.
diff --git a/GOALS.md b/GOALS.md
index a3ec2bb8d6..efc6b48ec6 100644
--- a/GOALS.md
+++ b/GOALS.md
@@ -74,8 +74,8 @@ Sharpen the mind alongside everything else. **POST** delivers a daily 5-minute s
## Non-Goals
- **Multi-user support**: PortOS is a personal tool built for one person. Adding auth, roles, or multi-tenancy would add complexity with no benefit.
-- **Public internet deployment**: Runs on a private Tailscale network. No HTTPS, CORS, rate limiting, or public-facing hardening needed.
-- **Database-backed persistence (general)**: JSON files are the primary persistence layer — human-readable, git-friendly, and sufficient for single-user scale. PostgreSQL + pgvector is used only for the memory system (vector search requires it). Do not migrate other data stores to a database.
+- **Public internet deployment**: Runs on a private Tailscale network. No CORS, rate limiting, or public-facing hardening needed. (HTTPS is supported via `npm run setup:cert` for browser-API and cert-trust convenience — not as public-exposure hardening.)
+- **ORM / heavyweight database tooling**: PostgreSQL + pgvector is the primary datastore for app-native relational records (see the [storage contract](./docs/STORAGE.md) and the [Postgres ADR](./docs/decisions/2026-06-07-postgres-as-primary-datastore.md)), but PortOS deliberately uses plain SQL — no ORM, no query builder. Binary assets and externally-synced/ephemeral state stay as files under `data/`.
- **Authentication / Authorization**: Single-user on a private network. Auth would be security theater here.
- **Cloud hosting**: Runs on your local machine. Your data stays on your hardware.
diff --git a/README.md b/README.md
index 2ccf12c821..a57fe1586d 100644
--- a/README.md
+++ b/README.md
@@ -81,8 +81,12 @@ A full creative studio for taking an idea from blank page to finished media. Eac
- **Image** — FLUX.1, FLUX.2 (klein), Z-Image via MFLUX/diffusers locally; A1111 / external endpoints; OpenAI Codex `gpt-image` mode
- **Video** — LTX models via `mlx_video` on macOS, diffusers on Windows. Modes: text-to-video, image-to-video, first/last-frame, extend, audio-to-video
- **Creative Director** — Treatment → scene plan → render orchestration for short films, with a media job queue serializing local GPU work
+ - **Music Video** — Track-driven storyboard and render pipeline for music videos
- **Timeline Editor** — Stitch clips, scenes, and audio into longer videos
- **Collections / History / Models / LoRAs** — Browse generated assets, install Civitai LoRAs by URL, and manage installed model weights
+- **Music Studio** — Artists, albums, and tracks with AI music generation, plus Rounds (musical rounds / quodlibets)
+- **Mood Boards** — Collect reference imagery into shareable boards that feed generation work
+- **Catalog** — The creative-ingredients graph (characters, places, objects, lore) shared across every Create surface
- **Importer** — Drop in an external manuscript (short story, novel, screenplay, comic script). The importer analyzes the text, suggests an arc shape, classifies characters/locations/scenes, and commits the result as either a new Writers Room work or a Pipeline series with a pre-filled bible
- **Sharing** — Cross-network share buckets via cloud-synced folders (Dropbox / iCloud / etc.). Register a bucket, pick `auto-merge` or `inbox` mode, and outgoing PortOS records (universes, series, characters, media) propagate to friends running their own PortOS instance. Live subscription indicators surface when the sender is actively editing
- **Image Cleaner** — Strip backgrounds, remove unwanted elements, and prep stills for downstream renders
@@ -121,6 +125,7 @@ A thought capture and knowledge management system — your offline-first externa
- **Insights** — Cross-domain narratives (genome↔health correlations, taste↔identity themes) generated from captured data
- **Daily/Weekly Digest** — AI-curated summaries of captured knowledge (< 150 / 250 words)
- **Trust Scoring** — Rate data source reliability for better knowledge hygiene
+- **Tribe** — Relationship graph of the people in your life, connected to Brain people records
- **Import** — Pull in data from external sources into the Brain pipeline
- **JSONL Audit Trail** — Full provenance tracking for every classified item
@@ -156,6 +161,7 @@ A gamified daily cognitive self-test in ~5 minutes across 5 domains. ([Full docs
- **Wordplay** — Language analysis and verbal reasoning exercises
- **Verbal Agility** — Communication skill challenges
- **Imagination** — Creative thinking exercises scored by LLM
+- **Morse Code (CW)** — Adaptive Morse sending/receiving trainer
- **Progress Tracking** — Streaks, rolling averages, and performance history
### Developer Tools
@@ -275,8 +281,8 @@ PortOS binds to `0.0.0.0` so you can access it from any device on your Tailscale
|-------|-------------|
| **Frontend** | React 18, Vite, Tailwind CSS, Three.js, xterm.js |
| **Backend** | Express.js, Socket.IO, PM2, Zod validation |
-| **Data** | PostgreSQL, JSON file persistence, vector embeddings |
-| **AI** | Claude Code, Codex, Antigravity CLI, Ollama, LM Studio (via [portos-ai-toolkit](https://www.npmjs.com/package/portos-ai-toolkit)) |
+| **Data** | PostgreSQL + pgvector (primary datastore — mandatory), JSON files for binary assets and synced/ephemeral state ([storage contract](./docs/STORAGE.md)) |
+| **AI** | Claude Code, Codex, Antigravity CLI, Ollama, LM Studio (via the in-tree AI toolkit, `server/lib/aiToolkit/`) |
## Project Structure
@@ -321,9 +327,11 @@ Configure AI providers for the runner and Chief of Staff:
## Documentation
+Full catalog (including design plans, ADRs, and research notes): [docs/README.md](./docs/README.md)
+
### Architecture & Operations
- [Architecture Overview](./docs/ARCHITECTURE.md) — System design, data flow, and service diagram
-- [API Reference](./docs/API.md) — 50+ REST endpoints and WebSocket events
+- [API Reference](./docs/API.md) — REST endpoints, full route-domain index, and WebSocket events
- [Storage Classification Contract](./docs/STORAGE.md) — when data belongs in PostgreSQL vs the filesystem, plus the new-data-store checklist
- [Backup & Restore](./docs/BACKUP.md) — filesystem snapshots + mandatory PostgreSQL dumps and how to restore them
- [Port Allocation](./docs/PORTS.md) — Port conventions (5553-5561) and allocation guide
@@ -333,14 +341,17 @@ Configure AI providers for the runner and Chief of Staff:
- [Contributing Guide](./docs/CONTRIBUTING.md) — Development setup and code conventions
- [GitHub Actions](./docs/GITHUB_ACTIONS.md) — CI/CD workflow patterns
- [Versioning & Releases](./docs/VERSIONING.md) — Semantic versioning and release process
-- [Security Audit](./docs/SECURITY_AUDIT.md) — Hardening audit (10/10 items resolved)
+- [Dependency Audit](./docs/DEPS.md) — Every third-party dependency and why it stays
+- [Security Audit](./docs/SECURITY_AUDIT.md) — Historical hardening audit (2026-02, 10/10 items resolved)
- [Troubleshooting](./docs/TROUBLESHOOTING.md) — Common issues and solutions
### Feature Deep Dives
- [Voice Mode](./docs/features/voice.md) — local STT/TTS/LLM voice assistant setup
- [Chief of Staff](./docs/features/chief-of-staff.md) — Autonomous agent orchestrator
+- [Operational Goals](./docs/GOALS_OPERATIONAL.md) — Runtime priorities the CoS reads when generating work
- [Agent Skills](./docs/features/agent-skills.md) — Task-type-specific agent prompts
+- [Claude on Ollama](./docs/features/claude-ollama.md) — Run agent tasks on a local model
- [CoS Agent Runner](./docs/features/cos-agent-runner.md) — Isolated agent process architecture
- [CoS Enhancement](./docs/features/cos-enhancement.md) — Hybrid search, proactive execution, error recovery
- [Memory System](./docs/features/memory-system.md) — Semantic memory with vector search and importance decay
@@ -365,7 +376,7 @@ Pull requests are welcome. This is a personal project, so:
- **Breakage happens.** Major version bumps (e.g. v2.0.0) may rename pages, reorganize data directories, or change schemas in ways that require a migration pass on your local data. Check the relevant `.changelog/vX.Y.Z.md` for what changed.
- **Data migration.** If something stops working after an update, the fastest fix is to point your coding agent at the changelog: `"Read .changelog/vX.Y.Z.md and fix any migration issues in my PortOS data/ directory."` Most data issues are trivially auto-fixable this way.
-- **Opinionated by design.** Architecture decisions (single-user, no auth, JSON files over a full ORM, Tailscale-only networking) are intentional and will not change. PRs that add multi-user support, HTTPS-by-default, or general-purpose hardening will not be merged.
+- **Opinionated by design.** Architecture decisions (single-user, no auth, PostgreSQL + flat files over a heavy ORM, Tailscale-only networking) are intentional and will not change. PRs that add multi-user support or general-purpose hardening will not be merged.
- **Style.** Match the existing conventions in [CLAUDE.md](./CLAUDE.md) before opening a PR — especially the no-try/catch route convention, emoji-prefixed logging, and Zod validation on all inputs.
## License
diff --git a/docs/API.md b/docs/API.md
index 29fde3e243..cfaf63163b 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -8,6 +8,10 @@ PortOS exposes a REST API on port 5555 and WebSocket events via Socket.IO.
http://localhost:5555/api
```
+When a TLS cert is provisioned (`npm run setup:cert`), `:5555` serves HTTPS instead and a loopback-only HTTP mirror runs on `http://127.0.0.1:5553` for local scripts. See [PORTS.md](./PORTS.md).
+
+This document covers the most commonly used endpoints plus a [complete route-domain index](#route-domain-index). A machine-readable OpenAPI 3.1 spec for the public API surface is served at `GET /api/api-docs/openapi.json` and rendered in the UI at `/api-access`.
+
## Security Model
PortOS is designed for personal/developer use on trusted networks. It implements the following security measures:
@@ -99,18 +103,19 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| Method | Endpoint | Description |
|--------|----------|-------------|
-| POST | `/detect/ports` | Detect process on port |
+| POST | `/detect/port` | Detect process on port |
| POST | `/detect/repo` | Validate repo path |
+| POST | `/detect/pm2` | Detect PM2 processes for a repo |
| POST | `/detect/ai` | AI-powered app detection |
-### Templates
+### Scaffold (App Templates)
| Method | Endpoint | Description |
|--------|----------|-------------|
-| GET | `/templates` | List available templates |
-| POST | `/templates` | Add custom template |
-| POST | `/templates/create` | Create app from template |
-| DELETE | `/templates/:id` | Delete custom template |
+| GET | `/scaffold/directories` | List candidate parent directories |
+| GET | `/scaffold/templates` | List available templates |
+| POST | `/scaffold/templates/create` | Create app from template |
+| POST | `/scaffold` | Scaffold a new app |
### Prompts
@@ -150,20 +155,24 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| GET | `/cos/learning/durations` | Get task duration estimates by type |
| POST | `/cos/learning/backfill` | Backfill learning data from history |
-### CoS Scheduled Scripts
+### CoS Jobs (Autonomous Jobs)
| Method | Endpoint | Description |
|--------|----------|-------------|
-| GET | `/cos/scripts` | List all scheduled scripts |
-| POST | `/cos/scripts` | Create a new script |
-| GET | `/cos/scripts/presets` | Get available schedule presets |
-| GET | `/cos/scripts/allowed-commands` | Get allowed commands for scripts |
-| GET | `/cos/scripts/jobs` | Get scheduled job info |
-| GET | `/cos/scripts/:id` | Get a specific script |
-| PUT | `/cos/scripts/:id` | Update a script |
-| DELETE | `/cos/scripts/:id` | Delete a script |
-| POST | `/cos/scripts/:id/run` | Execute a script immediately |
-| GET | `/cos/scripts/:id/runs` | Get script run history |
+| GET | `/cos/jobs` | List all jobs |
+| GET | `/cos/jobs/due` | List jobs due to run |
+| GET | `/cos/jobs/intervals` | Get available interval options |
+| GET | `/cos/jobs/allowed-commands` | Get allowed commands for shell jobs |
+| GET | `/cos/jobs/gates` | Get job gate status |
+| GET | `/cos/jobs/:id` | Get a specific job |
+| POST | `/cos/jobs` | Create a new job |
+| PUT | `/cos/jobs/:id` | Update a job |
+| DELETE | `/cos/jobs/:id` | Delete a job |
+| POST | `/cos/jobs/:id/toggle` | Toggle job on/off |
+| POST | `/cos/jobs/:id/trigger` | Run a job immediately |
+| POST | `/cos/jobs/:id/gate-check` | Evaluate a job's gates |
+
+(`GET /cos/scripts` still exists but now lists generated scripts only; scheduling lives in `/cos/jobs` and `/cos/schedule`.)
### CoS Weekly Digest
@@ -321,46 +330,47 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| Method | Endpoint | Description |
|--------|----------|-------------|
-| GET | `/agent-personalities` | List all agent personalities |
-| GET | `/agent-personalities/:id` | Get personality details |
-| POST | `/agent-personalities` | Create personality |
-| PUT | `/agent-personalities/:id` | Update personality |
-| DELETE | `/agent-personalities/:id` | Delete personality |
-| POST | `/agent-personalities/generate` | AI-generate personality |
-| POST | `/agent-personalities/:id/toggle` | Toggle personality active state |
+| GET | `/agents/personalities` | List all agent personalities |
+| GET | `/agents/personalities/:id` | Get personality details |
+| POST | `/agents/personalities` | Create personality |
+| PUT | `/agents/personalities/:id` | Update personality |
+| DELETE | `/agents/personalities/:id` | Delete personality |
+| POST | `/agents/personalities/generate` | AI-generate personality |
+| POST | `/agents/personalities/:id/toggle` | Toggle personality active state |
### Platform Accounts
| Method | Endpoint | Description |
|--------|----------|-------------|
-| GET | `/platform-accounts` | List linked platform accounts |
-| POST | `/platform-accounts` | Link new account |
-| PUT | `/platform-accounts/:id` | Update account |
-| DELETE | `/platform-accounts/:id` | Unlink account |
-| POST | `/platform-accounts/:id/test` | Test account connection |
+| GET | `/agents/accounts` | List linked platform accounts |
+| GET | `/agents/accounts/:id` | Get account details |
+| POST | `/agents/accounts` | Link new account |
+| DELETE | `/agents/accounts/:id` | Unlink account |
+| POST | `/agents/accounts/:id/test` | Test account connection |
+| POST | `/agents/accounts/:id/claim` | Claim account for an agent |
### Automation Schedules
| Method | Endpoint | Description |
|--------|----------|-------------|
-| GET | `/automation-schedules` | List all schedules |
-| GET | `/automation-schedules/stats` | Get schedule statistics |
-| GET | `/automation-schedules/:id` | Get schedule details |
-| POST | `/automation-schedules` | Create schedule |
-| PUT | `/automation-schedules/:id` | Update schedule |
-| DELETE | `/automation-schedules/:id` | Delete schedule |
-| POST | `/automation-schedules/:id/toggle` | Toggle schedule on/off |
-| POST | `/automation-schedules/:id/run` | Run schedule immediately |
+| GET | `/agents/schedules` | List all schedules |
+| GET | `/agents/schedules/stats` | Get schedule statistics |
+| GET | `/agents/schedules/:id` | Get schedule details |
+| POST | `/agents/schedules` | Create schedule |
+| PUT | `/agents/schedules/:id` | Update schedule |
+| DELETE | `/agents/schedules/:id` | Delete schedule |
+| POST | `/agents/schedules/:id/toggle` | Toggle schedule on/off |
+| POST | `/agents/schedules/:id/run` | Run schedule immediately |
### Agent Activity
| Method | Endpoint | Description |
|--------|----------|-------------|
-| GET | `/agent-activity` | List activity logs |
-| GET | `/agent-activity/timeline` | Get activity timeline |
-| GET | `/agent-activity/agent/:agentId` | Get agent's activity |
-| GET | `/agent-activity/agent/:agentId/stats` | Get agent statistics |
-| POST | `/agent-activity/cleanup` | Clean up old activity logs |
+| GET | `/agents/activity` | List activity logs |
+| GET | `/agents/activity/timeline` | Get activity timeline |
+| GET | `/agents/activity/agent/:agentId` | Get agent's activity |
+| GET | `/agents/activity/agent/:agentId/stats` | Get agent statistics |
+| POST | `/agents/activity/cleanup` | Clean up old activity logs |
### Notifications
@@ -434,6 +444,77 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| POST | `/agents/tools/moltworld/say` | Send chat message |
| GET | `/agents/tools/moltworld/status` | Get world status |
+## Route Domain Index
+
+Every mounted API prefix (see `server/index.js` for the authoritative list). Domains documented in detail above are omitted. Each prefix corresponds to a router in `server/routes/`.
+
+| Prefix | Domain |
+|--------|--------|
+| `/api/auth` | Optional password gate |
+| `/api/alerts` | System alerts |
+| `/api/avatar` | Avatar rendering/config |
+| `/api/system` | System health metrics |
+| `/api/capabilities` | Feature capability flags |
+| `/api/workspace-contexts` | Workspace context management |
+| `/api/apps/:appId/reference-repos` | Per-app reference repos |
+| `/api/network-exposure` | Network exposure checks |
+| `/api/git` | Git operations for managed apps |
+| `/api/screenshots` | Screenshot capture |
+| `/api/search` | Global search |
+| `/api/palette` | ⌘K command palette manifest + actions |
+| `/api/dashboard/layouts` | Dashboard widget layouts |
+| `/api/media/collections`, `/api/media/annotations` | Media library collections/annotations |
+| `/api/client-errors` | Client-side error reporting |
+| `/api/backup` | Backup snapshots + restore |
+| `/api/legacy-export` | Legacy data export |
+| `/api/database` | Postgres introspection |
+| `/api/image-clean` | Image metadata cleaning |
+| `/api/city` | CyberCity snapshots/introspection |
+| `/api/cos/gsd` | CoS GSD workflow |
+| `/api/feature-agents` | Feature agent runs |
+| `/api/feeds` | RSS/content feeds |
+| `/api/catalog` | Creative ingredients catalog |
+| `/api/tribe` | Tribe relationship graph |
+| `/api/notes` | Notes |
+| `/api/calendar` | Calendar integration |
+| `/api/messages` | Messages (email) integration |
+| `/api/digital-twin/social-accounts`, `/identity`, `/autobiography` | Digital-twin sub-domains |
+| `/api/meatspace` | MeatSpace (health, POST, genome) |
+| `/api/lmstudio`, `/api/local-llm` | Local LLM backends |
+| `/api/code-review` | Code review runs |
+| `/api/voice`, `/api/voice/public` | Voice assistant |
+| `/api/api-docs` | OpenAPI 3.1 spec |
+| `/api/data` | Data manager/sync |
+| `/api/datadog`, `/api/jira`, `/api/github`, `/api/telegram` | External integrations |
+| `/api/health` | Health check |
+| `/api/insights` | Cross-domain insights |
+| `/api/instances`, `/api/sync`, `/api/peer-sync`, `/api/sharing` | Federation / peer sync |
+| `/api/mortalloom` | MortalLoom |
+| `/api/review` | Review queue |
+| `/api/settings` | App settings |
+| `/api/update` | Self-update flow |
+| `/api/loops` | Loops |
+| `/api/character` | Character management |
+| `/api/tools` | Agent tool registry |
+| `/api/image-gen`, `/api/video-gen`, `/api/image-video/models` | Image/video generation |
+| `/api/devtools/video-download` | Video download |
+| `/api/video-timeline` | Video timeline editor |
+| `/api/media-jobs` | Async media job queue |
+| `/api/creative-director` | Creative Director projects |
+| `/api/music-video` | Music video projects |
+| `/api/mood-boards` | Mood boards |
+| `/api/writers-room` | Writers Room |
+| `/api/universe-builder` | Universe Builder |
+| `/api/authors`, `/api/artists`, `/api/albums`, `/api/tracks`, `/api/music` | Music/creator catalogs |
+| `/api/pipeline` | Series/comic pipeline |
+| `/api/conflict-journal` | Sync conflict journal |
+| `/api/importer` | Story importer |
+| `/api/story-builder` | Story Builder |
+| `/api/loras`, `/api/lora-datasets`, `/api/lora-training` | LoRA management/training |
+| `/api/openclaw` | OpenClaw operator chat |
+| `/api/rounds` | Rounds (music + Morse training) |
+| `/api/ask` | Ask (LLM Q&A) |
+
## WebSocket Events
Connect to Socket.IO at `http://localhost:5555`.
@@ -455,76 +536,51 @@ socket.emit('logs:unsubscribe', { processName: 'portos-server' });
### Error Notifications
-```javascript
-// Subscribe to errors
-socket.emit('errors:subscribe');
+Server errors are broadcast to all connected sockets — no subscription handshake is needed.
+```javascript
// Receive error events
socket.on('error:occurred', (error) => {
console.error('Server error:', error.message, error.code);
});
-
-// Unsubscribe
-socket.emit('errors:unsubscribe');
```
### Chief of Staff Events
```javascript
-// CoS status updates
-socket.on('cos:status', (status) => {
- console.log('CoS running:', status.running);
+// Join the CoS room to receive agent lifecycle events
+socket.emit('cos:subscribe');
+
+socket.on('cos:agent:spawned', (agent) => {
+ console.log('Agent spawned:', agent.id, agent.task);
});
-// Agent activity
-socket.on('cos:agent:started', (agent) => {
- console.log('Agent started:', agent.id, agent.task);
+socket.on('cos:agent:updated', (agent) => {
+ console.log('Agent updated:', agent.id, agent.status);
});
socket.on('cos:agent:completed', (agent) => {
console.log('Agent completed:', agent.id, agent.success);
});
-// Task updates
-socket.on('cos:task:updated', (task) => {
- console.log('Task updated:', task.id, task.status);
-});
-
-// Logs from CoS
-socket.on('cos:log', (entry) => {
- console.log(`[CoS] ${entry.level}: ${entry.message}`);
+socket.on('cos:agent:output', ({ agentId, lines }) => {
+ console.log('Agent output:', agentId, lines);
});
```
### Memory Events
```javascript
-socket.on('cos:memory:created', (memory) => {
+socket.on('memory:created', (memory) => {
console.log('Memory created:', memory.id);
});
-socket.on('cos:memory:updated', (memory) => {
+socket.on('memory:updated', (memory) => {
console.log('Memory updated:', memory.id);
});
-```
-
-### Script Events
-
-```javascript
-socket.on('script:created', (script) => {
- console.log('Script created:', script.id, script.name);
-});
-
-socket.on('script:started', ({ scriptId, name }) => {
- console.log('Script started:', scriptId);
-});
-
-socket.on('script:completed', ({ scriptId, exitCode, duration }) => {
- console.log('Script completed:', scriptId, exitCode);
-});
-socket.on('script:error', ({ scriptId, error }) => {
- console.error('Script error:', scriptId, error);
+socket.on('memory:deleted', ({ id }) => {
+ console.log('Memory deleted:', id);
});
```
@@ -532,7 +588,7 @@ socket.on('script:error', ({ scriptId, error }) => {
```javascript
// Start streaming detection
-socket.emit('detect:stream', { path: '/path/to/repo' });
+socket.emit('detect:start', { path: '/path/to/repo' });
// Receive discovery steps
socket.on('detect:step', (step) => {
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 3ce1fd6e86..102b923ca4 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -22,8 +22,8 @@ PortOS is a monorepo application with a React frontend and Express.js backend, m
│ │ └──────────────┘ │ │ | └──────────────┘ │ │
│ │ | │ │ | | │ │
│ │ ┌──────────────┐ │ │ | ┌────v─────────┐ │ │
-│ │ │ api.js │ │ │ | │ JSON Files │ │ │
-│ │ │ socket.js │ │ │ | │ (data/) │ │ │
+│ │ │ api.js │ │ │ | │ Postgres + │ │ │
+│ │ │ socket.js │ │ │ | │ data/ files │ │ │
│ │ └──────────────┘ │ │ | └──────────────┘ │ │
│ └────────────────────┘ └──────────────────────────────────────┘ │
│ │
@@ -47,6 +47,7 @@ PortOS is a monorepo application with a React frontend and Express.js backend, m
Communication paths:
Client <--HTTP/Socket.IO--> Server --PM2 API--> all satellite processes
+ Server --pg--> PostgreSQL + pgvector (system :5432 or Docker :5561) — mandatory primary datastore
Server --browserService--> portos-browser (CDP :5556, health :5557)
Server --apps.json--> portos-autofixer reads registered apps to monitor
CoS agents --CDP WebSocket--> portos-browser for web automation tasks
@@ -93,7 +94,7 @@ PortOS/
│ ├── server.js # Crash detection daemon (polls PM2 every 15min)
│ └── ui.js # Standalone Express UI with SSE log streaming
│
-├── data/ # Runtime data (gitignored)
+├── data/ # Runtime file data (gitignored) — relational records live in PostgreSQL (see docs/STORAGE.md)
│ ├── apps.json # Registered apps (read by autofixer)
│ ├── providers.json # AI provider configs
│ ├── history.jsonl # Action history (JSON Lines)
@@ -103,20 +104,19 @@ PortOS/
│ ├── COS-GOALS.md # Mission and goals
│ ├── cos/ # CoS state and agents
│ │ ├── state.json # Daemon state
-│ │ ├── agents/ # Agent outputs
-│ │ └── memory/ # Memory storage
+│ │ └── agents/ # Agent outputs
│ ├── autofixer/ # Autofixer session history
│ │ ├── index.json # Fix session index (max 100 entries)
│ │ └── sessions/ # Per-session prompt, output, metadata
-│ ├── brain/ # Brain second-brain data
+│ ├── brain/ # Brain second-brain data (file-primary)
│ │ ├── meta.json # Settings
-│ │ ├── inbox_log.jsonl # Captured thoughts
-│ │ ├── people.jsonl # People records
-│ │ ├── projects.jsonl # Project records
-│ │ ├── ideas.jsonl # Ideas
-│ │ ├── admin.jsonl # Admin tasks
-│ │ ├── links.json # Saved links
-│ │ └── digests.jsonl # Daily/weekly digests
+│ │ ├── inbox.json # Captured thoughts
+│ │ ├── people.json # People records
+│ │ ├── projects.json # Project records
+│ │ ├── ideas.json # Ideas
+│ │ ├── admin.json # Admin tasks
+│ │ ├── links.json # Saved links (+ buckets.json, journals.json, memories.json)
+│ │ └── digests.jsonl # Daily/weekly digests (+ reviews.jsonl)
│ ├── digital-twin/ # Digital twin identity documents
│ │ ├── meta.json # Settings and state
│ │ └── documents/ # Markdown identity documents
@@ -138,7 +138,7 @@ Browser → React Page → api.js → Express Route → Service → Response
│
├── Zod Validation
├── Service Logic
- └── JSON File / PM2 API
+ └── PostgreSQL / data/ file / PM2 API
```
### WebSocket Event Flow
@@ -220,9 +220,9 @@ Server Event → Socket.IO → socket.js → React Component State Update
- MCP server integration
- Usage tracking
-### Memory Service (`server/services/memory.js`)
-- Semantic memory storage
-- Vector embeddings via LM Studio
+### Memory Service (`server/services/memoryBackend.js`)
+- Backend switcher: PostgreSQL + pgvector (`memoryDB.js`) for real installs; the file backend (`memory.js`) is a test-only escape hatch
+- Semantic memory storage with vector embeddings via LM Studio
- Memory retrieval for context injection
### Task Learning Service (`server/services/taskLearning.js`)
@@ -231,11 +231,10 @@ Server Event → Socket.IO → socket.js → React Component State Update
- Model tier effectiveness analysis
- Actionable recommendations
-### Script Runner Service (`server/services/scriptRunner.js`)
-- Cron-based script scheduling
-- Command allowlist enforcement
-- Agent trigger integration
-- Run history tracking
+### Task Schedule Service (`server/services/taskSchedule.js`)
+- Interval/cron scheduling for CoS self-improvement and app tasks
+- Autonomous jobs (`/api/cos/jobs`) with command allowlist enforcement for shell jobs
+- Prompt-template versioning with auto-upgrade of unchanged defaults
### Brain Service (`server/services/brain.js`)
- Thought capture and AI classification
@@ -305,13 +304,15 @@ Error severity levels:
| Process | Port | Script | Purpose |
|---------|------|--------|---------|
-| portos-client | 5554 | `client/` (Vite) | React frontend dev server |
+| portos-ui | 5554 | `client/node_modules/vite/bin/vite.js` | React frontend dev server (dev only) |
| portos-server | 5555 | `server/index.js` | Main Express API server |
| portos-browser | 5556 (CDP), 5557 (health) | `browser/server.js` | Persistent Chromium with CDP for web automation |
| portos-cos | 5558 | `server/cos-runner/index.js` | Isolated CoS agent runner |
| portos-autofixer | 5559 | `autofixer/server.js` | Autonomous crash detection and Claude CLI repair |
| portos-autofixer-ui | 5560 | `autofixer/ui.js` | Standalone fix history dashboard with SSE logs |
+PostgreSQL itself is not PM2-managed — it runs as the system service (`:5432`) or the `docker-compose.yml` container (`:5561`), provisioned by `npm run setup:db`.
+
## Extension Points
### Adding a New Page
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 2f0287577c..bcc43cd06a 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -67,6 +67,7 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER
| `{ status: 'ok', dryRun, sizeBytes, tableCount }` | Dry-run report, or a successful real restore |
| `{ status: 'skipped', reason: 'no_dump' }` | No `portos-db.sql` in the snapshot (or 0 bytes) |
| `{ status: 'skipped', reason: 'not_configured' }` | Real restore requested but Postgres is unreachable — refuses to half-restore |
+| `{ status: 'failed', reason: 'manifest_mismatch' }` | Snapshot's `portos-db.sql` hash disagrees with `manifest.json` — dump considered untrustworthy |
| `{ status: 'failed', reason: 'restore_error', error }` | `psql` replay failed (stderr captured) |
A non-dry-run restore requires a reachable DB first (`checkHealth()`), so a restore never half-applies against a down database.
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index ea68e5dce9..935ed7a34b 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -15,6 +15,10 @@ npm run dev
pm2 start ecosystem.config.cjs
```
+**PostgreSQL is a mandatory dependency** — the server fails fast at boot without a healthy database. `npm run install:all` runs `npm run setup:db`, which provisions either the system PostgreSQL (`:5432`) or a Docker container (`:5561`, via `docker-compose.yml`). See [STORAGE.md](./STORAGE.md) and the [Postgres ADR](./decisions/2026-06-07-postgres-as-primary-datastore.md).
+
+For DB-backed tests, provision the separate test database first (`npm run setup:db:test`) and run them via `npm run test:db` — never against the real `portos` database.
+
## Code Guidelines
### General
diff --git a/docs/DEPS.md b/docs/DEPS.md
index 35800fbdfd..adff6df556 100644
--- a/docs/DEPS.md
+++ b/docs/DEPS.md
@@ -2,8 +2,8 @@
Living reference of every third-party dependency in PortOS, why it's kept, and what the current verdict is. Updated by `/do:depfree` runs.
-**Last audited:** 2026-04-28 (default mode)
-**Verdict:** All dependencies justified. 0 removals.
+**Last audited:** 2026-04-28 (default mode); tables corrected 2026-07-01 during a docs audit.
+**Verdict:** All dependencies justified. Since the last full audit: `sax` was removed (replaced with an owned parser, issue #1824), `portos-ai-toolkit` was vendored in-tree (`server/lib/aiToolkit/`), and monolithic `googleapis` was replaced with scoped `@googleapis/*` packages.
## Audit Methodology
@@ -22,17 +22,19 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).
| **Root devDeps** | | | | |
| `pm2` | 1 | KEEP | top-level scripts | Process manager, foundational |
| **Server deps** | | | | |
+| `@googleapis/calendar` | 1 | KEEP | Calendar integration | Scoped official Google SDK (replaced monolithic `googleapis`) |
+| `@googleapis/gmail` | 1 | KEEP | Messages/Gmail integration | Scoped official Google SDK |
| `express` | 1 | KEEP | `server/index.js` + routes | Framework |
-| `googleapis` | 1 | KEEP | Google integrations | Official Google SDK |
+| `google-auth-library` | 1 | KEEP | Google OAuth | Pairs with `@googleapis/*` |
| `kokoro-js` | 2 | KEEP | `server/services/voice/tts-kokoro.js` | Only pure-JS in-process TTS; replacement = Python subprocess + pooling |
| `node-pty` | 1 | KEEP | shell/terminal services | Native PTY binding (N-API) |
+| `pdf-lib` | 1 | KEEP | PDF generation/manipulation | |
| `pg` | 1 | KEEP | Postgres access | Official `pg` driver |
| `pm2` | 1 | KEEP | app lifecycle | Process manager |
-| `portos-ai-toolkit` | 1 | KEEP | provider mgmt, prompts | Owned by author (separate repo) |
-| `sax` | 3 → KEEP (transitive) | KEEP | `claudeChangelog.js`, `appleHealthXml.js` | Pulled by `pm2 → [email protected] → [email protected]` (deduped) — direct removal saves nothing |
+| `sharp` | 1 | KEEP | image processing | Native, widely-audited |
| `socket.io` | 1 | KEEP | realtime | Foundational |
| `socket.io-client` | 1 | KEEP | server-to-client | Paired with socket.io |
-| `ws` | 1 | KEEP | raw WebSocket | Widely-audited |
+| `undici` | 1 | KEEP | HTTP client | Node core team project |
| `zod` | 1 | KEEP | input validation | Widely-audited |
| **Server devDeps** | | | | |
| `vitest` | 1 | KEEP | test runner | |
@@ -62,41 +64,36 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).
| `tailwindcss` | 1 | KEEP | styling | |
| `@vitejs/plugin-react` | 1 | KEEP | build | |
| `vite` | 1 | KEEP | build | |
+| `vitest` | 1 | KEEP | client test runner | jsdom environment |
+| `jsdom` | 1 | KEEP | test DOM | Paired with vitest |
+| `@testing-library/jest-dom` | 1 | KEEP | test matchers | |
+| `@testing-library/react` | 1 | KEEP | component tests | |
+| `@testing-library/user-event` | 1 | KEEP | interaction tests | |
+| `rollup-plugin-visualizer` | 2 | KEEP | bundle-size analysis | Dev-only, opt-in |
## Detailed Findings — Tier 2/3 Audits
### `kokoro-js` — KEEP (Tier 2)
- **Usage**: 1 dynamic import in `server/services/voice/tts-kokoro.js` (~80 LOC module). 3 call sites: `KokoroTTS.from_pretrained()`, `tts.generate(text, {voice, speed})`, `audio.toWav()`.
-- **Maintenance**: 1.2.1 published 2025-05-03. Active.
+- **Maintenance**: pinned at 1.2.0. Active upstream.
- **Vulns**: None (npm audit clean).
- **Replacement complexity**: Moderate (~50–80 LOC) but requires Python subprocess + JSON IPC + process pooling + lifecycle management. Operational overhead exceeds the supply-chain risk.
- **Decision**: KEEP. The only pure-JS in-process TTS option; Web Speech API is cloud-dependent and Piper requires CLI install.
- **Re-audit trigger**: if maintenance lapses (no publish for >12 months) or a CVE is reported, revisit and migrate to Piper subprocess.
-### `sax` — KEEP (Transitive)
-
-- **Direct usage**: 2 files — `server/services/claudeChangelog.js` (Atom feed parsing, ~5 events) and `server/services/appleHealthXml.js` (streaming Apple Health export, 3 event types on shallow `<record>` elements).
-- **Initial verdict**: REMOVE. ~100 LOC of owned regex+state-machine parser would suffice for both use cases.
-- **Transitive check**: `npm ls sax` →
- ```
- ├─┬ [email protected]
- │ └─┬ [email protected]
- │ └── [email protected] deduped
- └── [email protected]
- ```
-- **Reversal reason**: same major version (1.4.4) deduped via pm2→needle. Removing the direct dep leaves the package in `node_modules` with identical attack surface. No consolidation target (no other XML parser kept).
-- **Decision**: KEEP (transitive).
-- **Re-audit trigger**: if `pm2`/`needle` drops sax (check on each pm2 major bump), revisit and replace with owned code.
+### `sax` — REMOVED (issue #1824)
+
+- **History**: was used by `server/services/claudeChangelog.js` and the Apple Health XML import; originally kept as "transitive via pm2→needle" (the 2026-04 audit above).
+- **Resolution**: replaced with an owned streaming parser (`server/services/appleHealthXmlParser.js`) in issue #1824, and pm2 7.x no longer pulls it. No longer in `server/package.json`.
## Heavy-Mode Notes
If `/do:depfree --heavy` is run, the following Tier 1 entries would drop to Tier 2/3 and become replacement candidates regardless of popularity:
-- `googleapis` — narrow surface used; could be replaced with direct REST calls + owned auth.
+- `@googleapis/calendar` / `@googleapis/gmail` — narrow surface used; could be replaced with direct REST calls + owned auth.
- Many of the `@dnd-kit/*`, `@xterm/*`, `lucide-react`, `recharts` deps would be re-evaluated.
-- `pm2` would NOT be replaced (foundational process manager) but its transitive `needle`/`sax` chain would still be considered "out of scope" since pm2 itself is kept.
+- `pm2` would NOT be replaced (foundational process manager).
This is intentionally NOT done in default mode — current dependency footprint is reasonable for the project's deployment context (single-user, Tailscale-private).
@@ -106,10 +103,19 @@ Defined in `package.json` (root + server + client) — kept current to dodge kno
+- `[email protected]` (root/client; server pins `5.0.6`)
+- `[email protected]` (server only)
-- `minimatch@3 → [email protected]` (client only, scoped)
+- `minimatch@3 → [email protected]` (client only, scoped)
+- `[email protected]` (client only, keeps drei/fiber on one three copy)
These exist purely to force-bump transitive deps; revisit if `npm audit` flags new advisories.
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index ea66d1cd02..d5f2492a11 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -15,14 +15,17 @@ Triggers on PRs to `main`/`release` and pushes to `main`. Runs two parallel jobs
### Test Job
+- Starts a PostgreSQL service container (`pgvector/pgvector:pg17`) and provisions the test database (`npm run setup:db:test`)
- Installs root, server, and client dependencies
-- Runs server tests (`npm test --prefix server`)
-- Builds client (`npm run build --prefix client`)
+- Runs server tests (`npm run test:ci --prefix server`) and DB-backed tests (`npm run test:db:ci --prefix server`)
+- Runs client tests (`npm test --prefix client`)
+- Builds client (`npm run build --prefix client`) and smoke-boots the server (`npm run smoke`)
- Skips on `[skip ci]` commits (push events only; PR CI always runs)
### Lint Job
- Checks server entry point for syntax errors (`node --check server/index.js`)
+- Runs client lint (`npm run lint --prefix client`)
## Release Workflow (`release.yml`)
diff --git a/docs/GOALS_OPERATIONAL.md b/docs/GOALS_OPERATIONAL.md
index 6bfceba6ee..b07b0e6ae6 100644
--- a/docs/GOALS_OPERATIONAL.md
+++ b/docs/GOALS_OPERATIONAL.md
@@ -52,7 +52,7 @@ The CoS autonomous agent system reads these goals to guide its behavior and task
When idle, generate tasks in this priority order:
1. **Critical Fixes**: Security vulnerabilities, crashes, data loss risks
-2. **User Tasks**: Any pending tasks from TASKS.md
+2. **User Tasks**: Any pending user-submitted CoS tasks
3. **Health Issues**: PM2 errors, failed processes, high memory
4. **Self-Improvement**: UI bugs, mobile issues, code quality
5. **Documentation**: Update docs, generate reports
diff --git a/docs/PM2.md b/docs/PM2.md
index e3d4152fff..deb5846b20 100644
--- a/docs/PM2.md
+++ b/docs/PM2.md
@@ -28,7 +28,6 @@ module.exports = {
script: 'server/index.js',
cwd: __dirname,
interpreter: 'node',
- ports: { api: 5570 },
env: {
NODE_ENV: 'development',
PORT: 5570,
@@ -56,7 +55,6 @@ module.exports = {
| Field | Description | Default |
|-------|-------------|---------|
| `interpreter` | Node interpreter path | `'node'` |
-| `ports` | Port allocation object (PortOS convention) | - |
| `env` | Environment variables | `{}` |
| `watch` | Enable file watching | `false` |
| `max_memory_restart` | Restart if memory exceeds threshold | - |
@@ -83,18 +81,26 @@ For services that should auto-recover from failures:
## Port Allocation Convention
-Define all ports in a `ports` object for documentation and PortOS integration:
+Define all ports once in a top-level `PORTS` constant and reference it from each app's `env` — a single source of truth instead of magic numbers scattered through the config (this is the pattern PortOS's own `ecosystem.config.cjs` uses):
```javascript
-{
- name: 'my-app',
- // PortOS convention: define all ports used by this process
- ports: { api: 5570, health: 5571 },
- env: {
- PORT: 5570,
- HEALTH_PORT: 5571
- }
-}
+const PORTS = {
+ API: 5570, // REST API server
+ HEALTH: 5571, // Health check endpoint
+};
+
+module.exports = {
+ PORTS, // exported so other configs/scripts can reference it
+ apps: [
+ {
+ name: 'my-app',
+ env: {
+ PORT: PORTS.API,
+ HEALTH_PORT: PORTS.HEALTH
+ }
+ }
+ ]
+};
```
### Common Port Labels
@@ -117,7 +123,6 @@ See `PORTS.md` for the full port allocation guide.
script: 'server/index.js',
cwd: __dirname,
interpreter: 'node',
- ports: { api: 5570 },
env: {
NODE_ENV: 'development',
PORT: 5570,
@@ -136,7 +141,6 @@ See `PORTS.md` for the full port allocation guide.
script: 'node_modules/.bin/vite',
cwd: `${__dirname}/client`,
args: '--host 0.0.0.0 --port 5571',
- ports: { ui: 5571 },
env: {
NODE_ENV: 'development'
},
@@ -152,7 +156,6 @@ See `PORTS.md` for the full port allocation guide.
script: 'worker/index.js',
cwd: __dirname,
interpreter: 'node',
- ports: {}, // No ports if internal-only
env: {
NODE_ENV: 'development'
},
@@ -172,7 +175,6 @@ See `PORTS.md` for the full port allocation guide.
script: '.browser/server.js',
cwd: __dirname,
interpreter: 'node',
- ports: { cdp: 5572, health: 5573 },
env: {
NODE_ENV: 'development',
CDP_PORT: 5572,
@@ -242,7 +244,6 @@ module.exports = {
script: 'server/index.js',
cwd: __dirname,
interpreter: 'node',
- ports: { api: 5570 },
env: {
NODE_ENV: 'development',
PORT: 5570,
@@ -256,7 +257,6 @@ module.exports = {
script: 'node_modules/.bin/vite',
cwd: `${__dirname}/client`,
args: '--host 0.0.0.0 --port 5571',
- ports: { ui: 5571 },
env: {
NODE_ENV: 'development'
},
@@ -267,7 +267,6 @@ module.exports = {
script: 'worker/index.js',
cwd: __dirname,
interpreter: 'node',
- ports: {},
env: {
NODE_ENV: 'development'
},
diff --git a/docs/PORTS.md b/docs/PORTS.md
index 65a091c0dc..282e98f4f7 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -7,7 +7,7 @@ PortOS uses a contiguous port allocation scheme to make it easy to understand wh
### Convention
1. **Contiguous Ranges**: Each app should use a contiguous block of ports
-2. **Labeled Ports**: Use the `ports` object in `ecosystem.config.cjs` to define all ports with descriptive labels
+2. **Labeled Ports**: Define all ports in the top-level `PORTS` object in `ecosystem.config.cjs` (re-exported at `server/lib/ports.js`); the per-process label map lives in `server/services/apps.js`
3. **No Gaps**: Avoid leaving gaps between port allocations within an app
### Port Labels
@@ -24,7 +24,7 @@ Common port labels:
| Port | Process | Label | Description |
|------|---------|-------|-------------|
| 5553 | portos-server | api-local | Loopback-only HTTP mirror of the API (only listens when HTTPS is active on 5555). Lets `http://localhost:5553` work without cert warnings. Override with `PORTOS_HTTP_PORT`. |
-| 5554 | portos-client | ui | Vite dev server (React UI) — only present in `npm run dev`; `npm start` serves the built client from :5555 directly. |
+| 5554 | portos-ui | ui | Vite dev server (React UI) — only present in `npm run dev`; `npm start` serves the built client from :5555 directly. |
| 5555 | portos-server | api | Main API server — **always the user-facing port**. Switches between HTTP and HTTPS based on whether `data/certs/{cert,key}.pem` exists. |
| 5556 | portos-browser | cdp | Chrome DevTools Protocol |
| 5557 | portos-browser | health | Browser health check API |
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000000..2fb48c07aa
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,48 @@
+# PortOS Documentation
+
+Index of everything under `docs/`. Start with the [root README](../README.md) for the product overview and quick start.
+
+## Guides (living documents)
+
+| Doc | Covers |
+|-----|--------|
+| [ARCHITECTURE.md](./ARCHITECTURE.md) | System design: React client, Express server, PM2 satellites, PostgreSQL + `data/` files |
+| [API.md](./API.md) | REST endpoints, complete route-domain index, Socket.IO events |
+| [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 |
+| [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects |
+| [CONTRIBUTING.md](./CONTRIBUTING.md) | Dev setup (PostgreSQL required), code conventions |
+| [GITHUB_ACTIONS.md](./GITHUB_ACTIONS.md) | CI and release workflows |
+| [VERSIONING.md](./VERSIONING.md) | SemVer + release process (`/do:release`) |
+| [DEPS.md](./DEPS.md) | Dependency audit — every third-party package and its verdict |
+| [TROUBLESHOOTING.md](./TROUBLESHOOTING.md) | Common runtime issues, known issues |
+| [GOALS_OPERATIONAL.md](./GOALS_OPERATIONAL.md) | Runtime operating principles the CoS agent reads (parsed by `goalProgress.js`) |
+| [SECURITY_AUDIT.md](./SECURITY_AUDIT.md) | Historical hardening audit (2026-02, all items resolved) |
+
+## Feature deep dives (`features/`)
+
+App management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)
+
+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [prompt-manager](./features/prompt-manager.md)
+
+Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [cross-domain-insights-engine](./features/cross-domain-insights-engine.md) · [post](./features/post.md)
+
+Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)
+
+Create: [writers-room](./features/writers-room.md) · [cybercity-v2](./features/cybercity-v2.md)
+
+Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./features/openclaw-operator-chat-audit.md)) · [voice](./features/voice.md)
+
+## Point-in-time records
+
+- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs.
+- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md).
+- **research/** — dated investigation and incident write-ups (e.g. the [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md)).
+- **superpowers/** — plan/spec pairs from superpowers-driven builds: `specs/<date>-<slug>-design.md` (design) + `plans/<date>-<slug>.md` (implementation plan).
+
+## Other
+
+- **[themes/](./themes/README.md)** — UI theme specs and the theme integration contract.
+- **[examples/](./examples/README.md)** — copy-ready config examples (e.g. Claude Code → Ollama settings).
+- **media/** — screenshots and logo used by the root README.
diff --git a/docs/SECURITY_AUDIT.md b/docs/SECURITY_AUDIT.md
index 9aed10495a..86a057b929 100644
--- a/docs/SECURITY_AUDIT.md
+++ b/docs/SECURITY_AUDIT.md
@@ -1,4 +1,6 @@
-# Security Hardening Audit (2025-02-19)
+# Security Hardening Audit (2026-02-19)
+
+> **Historical record.** This is a point-in-time audit from February 2026 (v1.14 era, before the PostgreSQL migration). It is kept as a record of the hardening pass, not maintained as a living document.
PortOS is an internal/VPN app so auth, CORS, rate limiting, and HTTPS are out of scope. These items address real bugs, crash risks, and secret leaks that matter regardless of network posture.
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 84d9255714..af70271082 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -201,12 +201,34 @@ pm2 restart ecosystem.config.cjs
## Database/Data Issues
+### Server Won't Boot: Database Unreachable
+
+**Symptom**: Server fails fast at startup with a database health error.
+
+PostgreSQL is a **mandatory** dependency (see [STORAGE.md](./STORAGE.md)) — there is no silent file fallback.
+
+**Solution**:
+```bash
+# Re-run DB provisioning (system pg on :5432 or Docker on :5561)
+npm run setup:db
+
+# Docker mode: make sure the container is up
+docker compose up -d
+
+# Check what's answering
+pg_isready -h localhost -p 5432 || pg_isready -h localhost -p 5561
+```
+
+### Missing/Corrupted Relational Data
+
+Universes, series, catalog ingredients, memories, and other relational records live in PostgreSQL, not `data/` files. Inspect them via the Database settings tab or `psql`. To recover, restore a snapshot's `portos-db.sql` from the Backup tab (see [BACKUP.md](./BACKUP.md)).
+
### Lost App Registrations
**Symptom**: Apps disappear after restart.
**Causes**:
-- `data/apps.json` was deleted or corrupted
+- `data/apps.json` was deleted or corrupted (app registry is file-backed)
- File permissions prevent writing
**Solution**:
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
new file mode 100644
index 0000000000..e4be4753bd
--- /dev/null
+++ b/docs/decisions/README.md
@@ -0,0 +1,5 @@
+# Architecture Decision Records
+
+One file per accepted decision, named `YYYY-MM-DD-<slug>.md` (date of acceptance), starting with `# ADR: <title>` and a `**Date:**` line.
+
+ADRs record *why* a structural choice was made and what the alternatives were. They are point-in-time records — when a decision is superseded, add a new ADR that references the old one rather than editing history.
diff --git a/docs/features/app-wizard.md b/docs/features/app-wizard.md
index a638f15271..f156ee8876 100644
--- a/docs/features/app-wizard.md
+++ b/docs/features/app-wizard.md
@@ -57,7 +57,7 @@ Scaffold a new project from template:
| POST /api/apps | Register existing app |
| POST /api/scaffold | Create new app from template |
| GET /api/scaffold/templates | List available templates |
-| POST /api/detect/ports | Detect process on port |
+| POST /api/detect/port | Detect process on port |
| POST /api/detect/repo | Validate repo path, detect type |
## Related Features
diff --git a/docs/features/brain-system.md b/docs/features/brain-system.md
index f51685f453..15d88bdb83 100644
--- a/docs/features/brain-system.md
+++ b/docs/features/brain-system.md
@@ -63,14 +63,21 @@ Track administrative tasks:
```
./data/brain/
-├── meta.json # Settings and scheduler state
-├── inbox_log.jsonl # All captured thoughts with classifications
-├── people.jsonl # People records
-├── projects.jsonl # Projects with status tracking
-├── ideas.jsonl # Ideas and concepts
-├── admin.jsonl # Administrative tasks
-├── digests.jsonl # Daily digest history
-└── reviews.jsonl # Weekly review history
+├── meta.json # Settings and scheduler state
+├── inbox.json # All captured thoughts with classifications
+├── people.json # People records
+├── projects.json # Projects with status tracking
+├── ideas.json # Ideas and concepts
+├── admin.json # Administrative tasks
+├── buckets.json # Custom bucket definitions
+├── links.json # Cross-record links
+├── memories.json # Brain memories
+├── journals.json # Daily Log entries
+├── memory-bridge-map.json # Brain↔CoS memory bridge mapping
+├── obsidian-vaults.json # Obsidian vault sync config
+├── sync_log.jsonl # Obsidian sync history
+├── digests.jsonl # Daily digest history
+└── reviews.jsonl # Weekly review history
```
## AI Classification
@@ -151,7 +158,7 @@ Generated weekly (GTD-style):
| `server/services/brain.js` | Core business logic |
| `server/services/brainStorage.js` | JSONL/JSON file operations |
| `server/services/brainScheduler.js` | Daily/weekly job scheduler |
-| `server/routes/brain.js` | API endpoints |
+| `server/routes/brain.js` | Aggregator router mounting brainCapture, brainCrud, brainDigest, brainSettings, brainLinks, brainGraph, brainSync, and brainDailyLog |
| `client/src/pages/Brain.jsx` | Main page with tabs |
| `client/src/components/brain/tabs/*.jsx` | Tab components |
| `data/prompts/stages/brain-*.md` | Prompt templates |
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 02e89d78df..c38ed2f6b9 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -114,7 +114,7 @@ The `selectModelForTask` function routes tasks to appropriate model tiers:
## Related Features
- [Memory System](./memory-system.md)
-- [Task Learning](./task-learning.md)
-- [Self-Improvement](./self-improvement.md)
+- Task Learning — see `server/services/taskLearning/` and the `/api/cos/learning` endpoints
+- [Self-Improvement](./cos-enhancement.md)
- [Error Handling](./error-handling.md)
-- [Scheduled Scripts](./scheduled-scripts.md)
+- Scheduled Scripts — see the Schedule system (`server/services/taskSchedule.js`, `/api/cos/jobs`)
diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.md
index 9018dd55cb..38aabf8db4 100644
--- a/docs/features/cos-enhancement.md
+++ b/docs/features/cos-enhancement.md
@@ -1,5 +1,7 @@
# Chief of Staff Enhancement (M35)
+> **Status:** This M35 milestone spec shipped, except the Phase 5 agent-architecture services (`agentGateway.js`, `errorRecovery.js`, `agentRunCache.js`, `contextUpgrader.js`) and `sessionDelta.js`, which were never built under those names. Their rows below are marked "(not built)" and kept for historical legibility.
+
Comprehensive upgrade from reactive task executor to proactive autonomous agent with hybrid memory, missions, local model integration, and dynamic thinking levels.
## Architecture
@@ -10,18 +12,18 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
|---------|---------|
| `server/lib/bm25.js` | BM25 algorithm with IDF weighting |
| `server/services/memoryBM25.js` | BM25 index manager for memory search |
-| `server/services/sessionDelta.js` | Session delta tracking for pending bytes/messages |
+| `server/services/sessionDelta.js` | Session delta tracking for pending bytes/messages (not built) |
| `server/services/toolStateMachine.js` | Tool execution state machine |
-| `server/services/agentGateway.js` | Request deduplication and caching |
-| `server/services/errorRecovery.js` | Error analysis and recovery strategies |
-| `server/services/agentRunCache.js` | Agent output caching with TTL |
+| `server/services/agentGateway.js` | Request deduplication and caching (not built) |
+| `server/services/errorRecovery.js` | Error analysis and recovery strategies (not built) |
+| `server/services/agentRunCache.js` | Agent output caching with TTL (not built) |
| `server/services/eventScheduler.js` | Cron-based event scheduling |
| `server/services/executionLanes.js` | Concurrent execution lane management |
| `server/services/missions.js` | Long-term goal and mission management |
| `server/services/lmStudioManager.js` | LM Studio model discovery and health |
| `server/services/localThinking.js` | Local model completions |
| `server/services/thinkingLevels.js` | Dynamic model selection |
-| `server/services/contextUpgrader.js` | Complexity analysis for model upgrade |
+| `server/services/contextUpgrader.js` | Complexity analysis for model upgrade (not built) |
## Features
@@ -114,8 +116,8 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
| `server/services/toolStateMachine.test.js` | Tool State Machine |
| `server/services/thinkingLevels.test.js` | Thinking Levels |
| `server/services/executionLanes.test.js` | Execution Lanes |
-| `server/services/errorRecovery.test.js` | Error Recovery |
-| `server/services/agentRunCache.test.js` | Agent Run Cache |
+| `server/services/errorRecovery.test.js` | Error Recovery (not built) |
+| `server/services/agentRunCache.test.js` | Agent Run Cache (not built) |
| `server/services/missions.test.js` | Missions Service |
## Related Features
diff --git a/docs/features/digital-twin.md b/docs/features/digital-twin.md
index 34a6d378a2..c69ae916d8 100644
--- a/docs/features/digital-twin.md
+++ b/docs/features/digital-twin.md
@@ -8,7 +8,7 @@ Transform the Digital Twin from a document capture system into a quantitative pe
## Architecture
-- **Digital Twin Service** (`server/services/digitalTwin.js`): Trait analysis, confidence scoring, gap recommendations
+- **Digital Twin Service** (`server/services/digital-twin.js`, with logic split across ~25 `digital-twin-*.js` modules): Trait analysis, confidence scoring, gap recommendations
- **Digital Twin Routes** (`server/routes/digital-twin.js`): REST API endpoints
- **Digital Twin Validation** (`server/lib/digitalTwinValidation.js`): Zod schemas for trait data
@@ -82,7 +82,6 @@ traits: {
- `PersonalityMap.jsx` - Radar chart of Big Five with confidence coloring
- `ConfidenceGauge.jsx` - Per-dimension confidence indicator
- `GapRecommendations.jsx` - Prioritized enrichment suggestions
-- `TraitEditor.jsx` - Manual trait override interface
## API Endpoints
@@ -90,7 +89,7 @@ traits: {
|-------|-------------|
| GET /api/digital-twin/traits | Get all trait scores |
| POST /api/digital-twin/traits/analyze | Analyze documents to extract traits |
-| PUT /api/digital-twin/traits/:category | Manual override trait scores |
+| PUT /api/digital-twin/traits | Manual override trait scores |
| GET /api/digital-twin/confidence | Get confidence scores |
| POST /api/digital-twin/confidence/calculate | Recalculate confidence |
| GET /api/digital-twin/gaps | Get gap recommendations |
diff --git a/docs/features/identity-system.md b/docs/features/identity-system.md
index 1e45fe8ed3..7c7951d38e 100644
--- a/docs/features/identity-system.md
+++ b/docs/features/identity-system.md
@@ -1,5 +1,7 @@
# Unified Digital Twin Identity System (M42)
+> **Status:** design plan, since largely implemented (`server/services/identity.js`, `server/routes/identity.js`, `data/digital-twin/{identity,chronotype,goals}.json`). Kept here as the identity-architecture reference; phase/roadmap sections below are the original plan, and a few items (e.g. `aesthetics.json`) remain unbuilt. For current behavior, trust the code paths named in each section.
+
Connects Genome (117 markers, 32 categories), Chronotype (5 sleep markers + behavioral), Aesthetic Taste (P2 complete, P2.5 adds twin-aware prompting), and Mortality-Aware Goals into a single coherent Identity architecture with cross-insights engine.
## Motivation
diff --git a/docs/features/jira-sprint-manager.md b/docs/features/jira-sprint-manager.md
index fe35696b78..66940db635 100644
--- a/docs/features/jira-sprint-manager.md
+++ b/docs/features/jira-sprint-manager.md
@@ -1,10 +1,10 @@
# JIRA Sprint Manager Job
-Autonomous job that triages and implements JIRA tickets for apps with JIRA integration enabled. Combines triage (reviewing, commenting, prioritizing) with implementation (worktree, PR, JIRA transition) in a single daily run.
+Scheduled task that triages and implements JIRA tickets for apps with JIRA integration enabled. Combines triage (reviewing, commenting, prioritizing) with implementation (worktree, PR, JIRA transition) in a single daily run.
## Overview
-The JIRA Sprint Manager runs Monday-Friday at 9 AM. It first triages all sprint tickets across JIRA-enabled apps, then implements the highest-priority ready ticket.
+The JIRA Sprint Manager is a daily task in the Schedule system (defined in `server/services/taskSchedule.js`), disabled by default. When enabled, it first triages all sprint tickets across JIRA-enabled apps, then implements the highest-priority ready ticket.
## How It Works
@@ -41,7 +41,7 @@ The JIRA Sprint Manager runs Monday-Friday at 9 AM. It first triages all sprint
| Interval | Daily at 09:00 | Weekdays only |
| Priority | HIGH | Job priority |
| Autonomy Level | yolo | Fully autonomous |
-| Enabled | true | Active by default |
+| Enabled | false | Disabled by default |
### App-Level JIRA Configuration
@@ -72,5 +72,3 @@ Customizable at: `data/prompts/skills/jobs/jira-sprint-manager.md`
## Related Features
- [Chief of Staff](./chief-of-staff.md) — Core autonomous agent system
-- [Autonomous Jobs](./autonomous-jobs.md) — Recurring job scheduler
-- [JIRA Integration](./jira-integration.md) — JIRA API setup
diff --git a/docs/features/memory-system.md b/docs/features/memory-system.md
index 0172ce5308..0236be74b7 100644
--- a/docs/features/memory-system.md
+++ b/docs/features/memory-system.md
@@ -4,7 +4,8 @@ Semantic memory system for the Chief of Staff that stores facts, learnings, obse
## Architecture
-- **Memory Service** (`server/services/memory.js`): Core CRUD, search, and lifecycle operations
+- **Memory Backend** (`server/services/memoryBackend.js`): Selects the storage backend — `memoryDB.js` (PostgreSQL + pgvector) for real installs; `memory.js` (JSON files) is a test-only escape hatch (`MEMORY_BACKEND=file` / `NODE_ENV=test`), not a supported deployment mode
+- **Memory DB Service** (`server/services/memoryDB.js`): Primary CRUD, search, and lifecycle operations against PostgreSQL
- **Embeddings Service** (`server/services/memoryEmbeddings.js`): LM Studio integration for vector generation
- **Memory Extractor** (`server/services/memoryExtractor.js`): Extract memories from agent output
- **Memory Classifier** (`server/services/memoryClassifier.js`): LLM-based quality filtering
@@ -49,6 +50,10 @@ Semantic memory system for the Chief of Staff that stores facts, learnings, obse
## Data Storage
+Memories and links live in PostgreSQL — the `memories` and `memory_links` tables, with pgvector columns for embeddings (see [docs/STORAGE.md](../STORAGE.md)).
+
+The test-only file backend (`MEMORY_BACKEND=file` / `NODE_ENV=test`) uses this JSON layout instead:
+
```
./data/cos/memory/
├── index.json # Lightweight metadata for listing/filtering
@@ -130,6 +135,11 @@ Before agent task execution:
| POST /api/memory/decay | Apply importance decay |
| DELETE /api/memory/expired | Clear expired memories |
| GET /api/memory/embeddings/status | LM Studio connection status |
+| GET /api/memory/backend/status | Active storage backend status |
+| GET /api/memory/sync | File↔DB sync status |
+| POST /api/memory/sync | Trigger file↔DB sync |
+| POST /api/memory/:id/approve | Approve a pending memory |
+| POST /api/memory/:id/reject | Reject a pending memory |
## WebSocket Events
@@ -172,7 +182,9 @@ memory: {
|------|---------|
| `server/lib/memoryValidation.js` | Zod schemas for memory operations |
| `server/lib/vectorMath.js` | Cosine similarity, clustering helpers |
-| `server/services/memory.js` | Core CRUD, search, lifecycle |
+| `server/services/memoryBackend.js` | Backend switcher (Postgres primary, file test-only) |
+| `server/services/memoryDB.js` | Core CRUD, search, lifecycle (PostgreSQL + pgvector) |
+| `server/services/memory.js` | File-backed CRUD (test-only backend) |
| `server/services/memoryEmbeddings.js` | LM Studio embedding generation |
| `server/services/memoryExtractor.js` | Extract memories from agent output |
| `server/services/memoryClassifier.js` | LLM-based classification service |
diff --git a/docs/features/openclaw-operator-chat-audit.md b/docs/features/openclaw-operator-chat-audit.md
index 5d5b76b165..483cb12c79 100644
--- a/docs/features/openclaw-operator-chat-audit.md
+++ b/docs/features/openclaw-operator-chat-audit.md
@@ -1,5 +1,7 @@
# OpenClaw Operator Chat — Extension Point Audit
+> **Note:** Historical pre-implementation extension-point audit (2026-04/05). The feature has since shipped largely along these lines; kept as a design record, not maintained.
+
This audit maps the real PortOS insertion points for a generic OpenClaw/operator chat feature.
It is a companion to:
diff --git a/docs/features/openclaw-operator-chat.md b/docs/features/openclaw-operator-chat.md
index d3b96734ba..2c0fac9ce5 100644
--- a/docs/features/openclaw-operator-chat.md
+++ b/docs/features/openclaw-operator-chat.md
@@ -1,5 +1,7 @@
# OpenClaw Operator Chat
+> **Status: implemented.** See `server/routes/openclaw.js`, `server/integrations/openclaw/api.js`, `client/src/pages/OpenClaw.jsx`, and the client service `client/src/services/apiOpenclaw.js` (not the proposed `openclaw.js`). The shipped endpoint surface differs from this proposal: `GET /api/openclaw/status`, `GET /api/openclaw/sessions`, `GET/POST /api/openclaw/sessions/:id/messages`, and streaming `POST /api/openclaw/sessions/:id/messages/stream`. The proposed `POST /sessions`, `GET /jobs`, `GET /subagents`, and `POST /context/compose` were not built.
+
A generic, first-party operator chat surface inside PortOS that allows a user to communicate with a local or privately reachable OpenClaw runtime without relying on third-party messaging providers like Telegram.
## Why this exists
diff --git a/docs/features/post.md b/docs/features/post.md
index 096ac4eac6..d2f104532f 100644
--- a/docs/features/post.md
+++ b/docs/features/post.md
@@ -167,7 +167,8 @@ Users can add their own items via the Config page:
- `GET/POST/PUT/DELETE /api/meatspace/post/memory-items` — memory item CRUD
- `POST /api/meatspace/post/memory-items/:id/practice` — submit practice result, update mastery
- `GET /api/meatspace/post/memory-items/:id/mastery` — get mastery breakdown
-- `POST /api/meatspace/post/drill` — extended to support `imagination` and `memory` drill types
+- `POST /api/meatspace/post/drill` — extended to support the `imagination` drill type
+- `POST /api/meatspace/post/memory-drill` — generate memory drills (separate endpoint)
## UI Components
diff --git a/docs/features/prompt-manager.md b/docs/features/prompt-manager.md
index cfb7c3c85c..396fd39eb1 100644
--- a/docs/features/prompt-manager.md
+++ b/docs/features/prompt-manager.md
@@ -4,9 +4,9 @@ Customizable AI prompts for all backend AI operations with file-based storage an
## Architecture
-- **Prompt Service** (`server/services/prompts.js`): Template loading, variable substitution, stage configuration
+- **Prompt Service** (`server/services/promptService.js`): Template loading, variable substitution, stage configuration
- **Prompt Routes** (`server/routes/prompts.js`): REST API endpoints
-- **Prompt Page** (`client/src/pages/Prompts.jsx`): Stages, Variables, Elements tabs with live preview
+- **Prompt Page** (`client/src/pages/PromptManager.jsx`): Stages, Variables, Elements tabs with live preview
## Features
diff --git a/docs/features/soul-system.md b/docs/features/soul-system.md
index a409b9fb91..54747d969e 100644
--- a/docs/features/soul-system.md
+++ b/docs/features/soul-system.md
@@ -8,7 +8,7 @@ LLMs can embody specific personas, but creating comprehensive identity documents
## Architecture
-- **Digital Twin Service** (`server/services/digitalTwin.js`): Document management, testing, enrichment
+- **Digital Twin Service** (`server/services/digital-twin.js` plus the `digital-twin-*.js` module family): Document management, testing, enrichment
- **Digital Twin Routes** (`server/routes/digital-twin.js`): REST API endpoints mounted under `/api/digital-twin/*`
- **Digital Twin Page** (`client/src/pages/DigitalTwin.jsx`): Overview, Documents, Test, Enrich, Export tabs
diff --git a/docs/features/brain/prompt.md b/docs/plans/2026-01-10-brain-build-prompt.md
similarity index 100%
rename from docs/features/brain/prompt.md
rename to docs/plans/2026-01-10-brain-build-prompt.md
diff --git a/docs/features/brain/plan.md b/docs/plans/2026-01-10-brain-feature-plan.md
similarity index 100%
rename from docs/features/brain/plan.md
rename to docs/plans/2026-01-10-brain-feature-plan.md
diff --git a/docs/research/posthuman-web-feature-review.md b/docs/research/2026-03-06-posthuman-web-feature-review.md
similarity index 100%
rename from docs/research/posthuman-web-feature-review.md
rename to docs/research/2026-03-06-posthuman-web-feature-review.md
diff --git a/docs/research/README.md b/docs/research/README.md
new file mode 100644
index 0000000000..844892c206
--- /dev/null
+++ b/docs/research/README.md
@@ -0,0 +1,5 @@
+# Research & Incident Write-ups
+
+Dated investigation notes, incident analyses, and external-feature reviews, named `YYYY-MM-DD-<slug>.md` (date the investigation happened).
+
+These are point-in-time records: they capture what was known/true at the time (hardware, versions, upstream bugs) and are not maintained afterward. Cross-link them from the relevant living doc (e.g. `docs/TROUBLESHOOTING.md` Known Issues) instead of updating them.
diff --git a/docs/superpowers/README.md b/docs/superpowers/README.md
new file mode 100644
index 0000000000..15b65e6cc4
--- /dev/null
+++ b/docs/superpowers/README.md
@@ -0,0 +1,10 @@
+# Superpowers Plan/Spec Records
+
+Artifacts from builds driven by the superpowers workflow, kept as point-in-time records:
+
+- `specs/YYYY-MM-DD-<slug>-design.md` — the approved design document.
+- `plans/YYYY-MM-DD-<slug>.md` — the matching implementation plan (headed with the subagent-driven-development skill requirement).
+
+A spec pairs with the plan sharing its slug; some early specs (`2026-04-20-rigged-3d-avatar-stage-design`, `2026-05-10-cd-pipeline-polish-design`) have no plan file because implementation was driven directly from the spec.
+
+New design records outside the superpowers workflow go in [`docs/plans/`](../plans/README.md) instead.