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

docs: optimize markdown files — fix stale references, deduplicate, consolidate audits

Adam Eivy76fcaee9d8b8
diff --git a/.changelog/README.md b/.changelog/README.md
index f762f6396a..2bf1e13c4a 100644
--- a/.changelog/README.md
+++ b/.changelog/README.md
@@ -10,7 +10,7 @@ This directory contains detailed release notes for each version of PortOS.
During development, all changelog entries are appended to `NEXT.md`. This file accumulates changes across multiple commits until a release is created.
-- `/cam` (commit all my work) automatically adds entries to `NEXT.md`
+- During development, append changelog entries to `NEXT.md` under the appropriate section (Added, Changed, Fixed, Removed)
- `/release` renames `NEXT.md` to `v{version}.md` and finalizes it with the version number and release date
- Do NOT create versioned changelog files manually — `/release` handles that
@@ -68,7 +68,7 @@ The GitHub Actions release workflow (`.github/workflows/release.yml`) automatica
## Development Workflow
-1. **During Development**: Each `/cam` commit appends entries to `NEXT.md` under the appropriate section (Added, Changed, Fixed, Removed)
+1. **During Development**: Append entries to `NEXT.md` under the appropriate section (Added, Changed, Fixed, Removed)
2. **During Release** (`/release`):
- Determines the version bump from conventional commit prefixes
@@ -80,14 +80,14 @@ The GitHub Actions release workflow (`.github/workflows/release.yml`) automatica
## Best Practices
### Do:
-- Update the changelog **as you work** via `/cam`
+- Update the changelog **as you work**
- Use clear, descriptive entries
- Group related changes together
- Explain the "why" not just the "what"
### Don't:
- Create versioned changelog files manually (use `/release`)
-- Bump the version in `/cam` — only `/release` does that
+- Bump the version manually — only `/release` does that
- Use vague descriptions like "various improvements"
- Leave placeholder or TODO content
diff --git a/CLAUDE.md b/CLAUDE.md
index 704f3d1f98..32a259f431 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -107,7 +107,7 @@ port-error: #ef4444
- **main**: Active development
- **release**: Push `main` to `release` to trigger GitHub Release workflow
- **Push pattern**: `git pull --rebase --autostash && git push`
-- **Changelog**: `/cam` appends to `.changelog/NEXT.md`; `/release` finalizes it into a versioned file
+- **Changelog**: Append entries to `.changelog/NEXT.md` during development; `/release` finalizes it into a versioned file
- **Versioning**: Version in `package.json` reflects the last release. Do not bump during development — `/release` handles version bumps
- After each feature or bug fix, run `/simplify` and then commit and push code
- If we have created enough commits to wrap up a feature or issue to warrant a production release, pull the latest main and release branches and then run `/release` from main
diff --git a/GOALS.md b/GOALS.md
index fa93613b48..f090d5c472 100644
--- a/GOALS.md
+++ b/GOALS.md
@@ -62,7 +62,7 @@ Calendar integration, life goal tracking, and email management transform PortOS
- **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**: JSON files are intentional. They're human-readable, git-friendly, and sufficient for single-user scale. No Postgres, SQLite, or MongoDB.
+- **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.
- **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/PLAN.md b/PLAN.md
index 86129760fb..67740d26bc 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -2,29 +2,6 @@
See [GOALS.md](./GOALS.md) for project goals and direction.
-## Quick Reference
-
-### Tech Stack
-- Frontend: React + Tailwind CSS + Vite (port 5554)
-- Backend: Express.js (port 5555)
-- Process Manager: PM2
-- Data Storage: JSON files in `./data/`, PostgreSQL + pgvector (memory system)
-
-### Commands
-```bash
-# Install all dependencies
-npm run install:all
-
-# Start development (both client and server)
-npm run dev
-
-# Start with PM2
-pm2 start ecosystem.config.cjs
-
-# View PM2 logs
-pm2 logs
-```
-
---
## Milestones
@@ -99,51 +76,6 @@ pm2 logs
## Planned Feature Details
-### M55: POST Enhancement — Training + Memory Builder + Imagination
-
-Evolves POST from a test-only system into a cognitive training platform. Covers five domains: **Math** (existing), **Memory** (new), **Wordplay** (existing), **Verbal Agility** (existing), **Imagination** (new). Sessions take ~5 minutes with balanced time budgets across domains.
-
-**Phases:**
-
-- **P1: Memory Builder Engine + Elements Song** — Memory item data model (`data/meatspace/post-memory-items.json`), CRUD routes (`GET/POST/PUT/DELETE /api/meatspace/post/memory-items`), practice submission with mastery tracking (`POST /memory-items/:id/practice`), mastery retrieval. Built-in Elements Song: Tom Lehrer lyrics parsed into lines with element name → symbol/atomic number mapping, chunked into verses.
-- **P2: Memory Builder UI** — `MemoryItemList` (browse/add items), `MemoryPractice` with 5 training modes (learn, fill-in-the-blank, sequence recall, random prompt, speed run), `ElementsSong` component with periodic table grid colored by mastery (green/yellow/red), karaoke-style progressive reveal.
-- **P3: Imagination & Ideation Drills** — 5 new LLM drill types: `what-if` (absurd hypotheticals), `alternative-uses` (divergent thinking), `story-prompt` (connect 3 random words), `invention-pitch` (solve a problem creatively), `reframe` (positive reframing). LLM generation prompts + scoring prompts. `ImaginationDrillRunner` UI with textarea input and difficulty badges.
-- **P4: Training Mode** — Per-domain train/test toggle in `PostSessionLauncher`. Train mode: progressive difficulty, hints on wrong answers, immediate feedback, no final score. Practice log in `data/meatspace/post-training-log.json` tracks practice count, streaks, time spent. Train sessions don't appear in scored POST history.
-- **P5: 5-Minute Session Flow** — Session pulls 1 drill per enabled domain with time budgets (Math ~60s, Memory ~90s, Wordplay ~60s, Verbal ~60s, Imagination ~60s). Smooth transition UI between drills with domain label and progress. Session score = weighted average across domains.
-- **P6: Custom Memory Items** ✅ — Config UI for adding songs/poems/speeches/sequences with title, type picker, and content textarea. Auto-chunking splits by blank lines (verse boundaries) with 4-line fallback. Spaced repetition mode orders chunks by mastery (weakest first) with graduated hint levels (full first-letters → partial → word-count-only → none). Chunk mastery overview with expandable per-chunk accuracy bars. New `GET /memory-items/:id/chunk-mastery` endpoint.
-
-**Data:** `data/meatspace/post-memory-items.json` (content + mastery), `data/meatspace/post-training-log.json` (practice sessions), extended `post-config.json` (imagination + memory drill settings)
-
-**Routes:** Extend existing POST routes + new memory item CRUD + practice endpoints. See [POST feature doc](./docs/features/post.md).
-
-*Touches: server/services/meatspacePost.js, server/services/meatspacePostLlm.js, new server/services/meatspacePostMemory.js, server/routes/meatspace.js, server/lib/postValidation.js, client/src/components/meatspace/post/*, client/src/hooks/usePostSession.js, client/src/services/api.js*
-
-### M44 P7: Apple Health Integration
-
-Bring Apple Health data into MeatSpace via two complementary paths: live sync from the [Health Auto Export](https://apps.apple.com/us/app/health-auto-export-json-csv/id1115567069) iOS app (~$4) and bulk historical import from Apple Health XML exports.
-
-**Live Sync (Health Auto Export)**
-- `POST /api/health/ingest` — accepts Health Auto Export JSON payload (metrics, workouts, sleep, ECG, medications)
-- Validate payload with Zod, deduplicate by metric name + timestamp
-- Persist to `data/health/YYYY-MM-DD.json` (one file per day, append/merge)
-- Configure app to POST to `http://<tailscale-ip>:5554/api/health/ingest` on 15-60 min interval
-- Support custom auth header for basic request validation
-- 150+ metric types: steps, heart rate, HRV, VO2 max, sleep stages, blood pressure, workouts with GPS routes, etc.
-- Reference: [health-auto-export-server](https://github.com/HealthyApps/health-auto-export-server), [payload schema](https://github.com/Lybron/health-auto-export)
-
-**Bulk Historical Import (XML Export)**
-- `POST /api/health/import-xml` — accepts Apple Health export ZIP upload
-- Stream-parse `export.xml` using `xml-stream` (files can be 500MB+), extract records into same `data/health/YYYY-MM-DD.json` format
-- Progress reporting via WebSocket during import
-- Reference: [apple-health-parser](https://github.com/cvyl/apple-health-parser)
-
-**MeatSpace Dashboard Integration**
-- New dashboard cards for key Apple Health metrics (steps, heart rate, sleep, HRV trends)
-- Correlate with existing MeatSpace data (alcohol intake vs. HRV/sleep, blood work trends vs. activity)
-- Time-series charts with configurable date ranges
-
-*Touches: server/routes/health.js, server/services/healthIngest.js, MeatSpace UI, data/health/*
-
### M45: Data Backup & Recovery
All PortOS data lives in `./data/` as JSON files with no redundancy. A corrupted write, accidental deletion, or disk failure loses everything — brain captures, digital identity, health records, memory embeddings, agent state, and run history.
@@ -167,33 +99,6 @@ All PortOS data lives in `./data/` as JSON files with no redundancy. A corrupted
*Touches: new server/services/backup.js, server/routes/backup.js, Dashboard widget, settings.json, automation scheduler*
-### M46: Unified Search (Cmd+K)
-
-Global keyboard-driven search across all PortOS data sources from any page.
-
-**Search Sources**
-- Brain captures (ideas, projects, people, admin)
-- Semantic memory (vector + BM25 hybrid, already exists)
-- Command history and AI run history
-- Agent activity and task logs
-- Apps registry
-- Digital twin documents, autobiography, taste summaries
-- MeatSpace health entries
-
-**UI**
-- `Cmd+K` / `Ctrl+K` opens search overlay from any page
-- Type-ahead with categorized results (Brain, Memory, Apps, History, etc.)
-- Result cards with source icon, snippet, and timestamp
-- Click navigates to deep-linked location (e.g., specific brain capture, agent run, history entry)
-
-**Implementation**
-- Server-side `/api/search` endpoint that fans out to existing service search functions
-- Client-side `GlobalSearch` component mounted in Layout.jsx
-- Debounced input with 200ms delay
-- Results ranked by relevance with source-type boosting
-
-*Touches: new server/routes/search.js, new server/services/search.js, new client/src/components/GlobalSearch.jsx, Layout.jsx*
-
### M47: Push Notifications
External notification delivery for critical events when not actively viewing the dashboard.
@@ -263,23 +168,13 @@ Multi-provider email integration — Gmail via MCP, Outlook/Teams via CDP browse
Always review before send — AI-generated drafts go to an outbox queue. The user reviews, edits, and approves each response before it's sent. No auto-send.
-**Completed:**
+**Completed:** P1-P6.5 (Email sync, AI triage, reply generation, thread capture, config, per-action models, prompt injection hardening, per-message re-fetch). See git history for details.
-- [x] **P1: Email Read & Sync** — Outlook CDP browser scraping with `[role='listbox'] [role='option']` selectors, Gmail MCP integration, account CRUD, Sync Unread / Full Sync modes with scrolling for virtualized lists, message caching with dedup
-- [x] **P2: AI Triage & Inbox Actions** — AI evaluation endpoint (`POST /messages/evaluate`) classifies messages as reply/archive/delete/review with priority, inbox shows action badges + priority dots + pin/flag indicators, 1-click "Draft" button generates AI reply and navigates to Drafts
-- [x] **P3: AI Reply Generation** — Real AI reply using configured provider/model and customizable prompt templates (reply + forward), `{{variable}}` substitution, settings persisted in `settings.json`
-- [x] **P3.5: Full Body & Thread Capture** — Outlook sync clicks into each conversation to extract full email body (not just 300-char preview). Conversation threads linked by `threadId`. `GET /messages/thread/:accountId/:threadId` endpoint. MessageDetail shows full conversation chain with "Preview only" indicator for uncaptured messages. Dedup preserves full body upgrades on re-sync.
-- [x] **P4: Config Page** — Unified Config tab with AI Provider & Model selector, prompt template editor, and email account management
+**Remaining:**
-**Remaining TODO:**
-
-- [x] **P5: Per-action model selection** — Separate provider/model configs for triage vs reply generation (different cost/capability tiers). Expand `settings.messages` to `{ triage: { providerId, model }, reply: { providerId, model } }`. Update ConfigTab with two `ProviderModelSelector` sections.
-- [x] **P6: Prompt injection hardening** — XML-fence untrusted email content in AI prompts to prevent injection. Add content sanitization layer (`sanitize()` escapes `<>`), `<emails>` XML fencing on eval prompt.
-- [x] **P6.5: Per-message re-fetch & detail fetch fixes** — Refresh button in MessageDetail re-clicks conversation and re-extracts full body (bypasses cache). Inbox-level "Fetch Full Content" button runs detail fetch for all preview-only messages. Clear Cache button per account in Config. Note: Outlook marks messages as read when opened for detail fetch (native behavior, documented as known limitation).
- [ ] **P7: Digital Twin voice drafting** — Draft responses using Digital Twin voice/style (reads COMMUNICATION.md, PERSONALITY.md, VALUES.md + recent thread context)
- [ ] **P8: CoS Automation & Rules** — Automated classification on new emails via CoS job, rule-based pre-filtering, email-to-task pipeline, priority email notifications
- [ ] **P9: Auto-Send with AI Review Gate** — Remove human-in-the-loop for trusted accounts. Before auto-sending, a second LLM call reviews the draft against the original email for: prompt injection artifacts, off-topic content, tone/identity drift, leaked system instructions. Configurable per-account trust level (manual → review-assisted → auto-send). See [Messages Security](./docs/features/messages-security.md) for threat model.
-- [x] **Cleanup** — Delete unused `client/src/components/messages/AccountsTab.jsx` (replaced by ConfigTab)
**Data:** `data/messages/accounts.json`, `data/messages/cache/{accountId}.json`, `data/messages/selectors.json`, `settings.json` (messages key for AI config + templates)
@@ -317,8 +212,6 @@ Check for new PortOS releases on GitHub and notify the user when an update is av
- **Chronotype-Aware Scheduling** — Chronotype derivation exists (M42 P1) but isn't applied to task scheduling yet. Use peak-focus windows from genome sleep markers to schedule deep-work tasks during peak hours, routine tasks during low-energy. Display energy curve on Schedule tab. *Touches: taskSchedule.js, genome.js, CoS Schedule tab*
- **Identity Context Injection** — Identity context is used for taste questions (M42 P2.5) but not yet injected as a system preamble for general AI calls. Build identity brief from EXISTENTIAL.md, taste, personality, autobiography; inject via toolkit. Per-task-type toggle. *Touches: portos-ai-toolkit, runner.js, CoS Config*
-- ~~**Mortality-Aware Goal Widget**~~ ✅ Shipped as M42 P3
-- ~~**Behavioral Feedback Loop**~~ ✅ Shipped as M34 P3
### Tier 2: Deeper Autonomy
@@ -336,7 +229,6 @@ Check for new PortOS releases on GitHub and notify the user when an update is av
### Tier 4: Developer Experience
-- ~~**Unified Search (Cmd+K)**~~ → Promoted to M46
- **Dashboard Customization** — Drag-and-drop widget reordering, show/hide toggles, named layouts ("morning briefing", "deep work"). *Touches: Dashboard.jsx, settings.js, dnd-kit*
- **Workspace Contexts** — Active project context that syncs shell, git, tasks, and browser to current project. Persists across navigation. *Touches: Settings state, Layout context, Shell/Git/Browser*
- **Inline Code Review Annotations** — Surface self-improvement findings as inline annotations in a code viewer. One-click "fix this" spawns CoS task. *Touches: New code viewer, selfImprovement.js*
@@ -384,235 +276,69 @@ Check for new PortOS releases on GitHub and notify the user when an update is av
---
-## Security Hardening ✅
-
-All 10 audit items (S1–S10) from the 2025-02-19 security audit have been resolved. See [Security Audit](./docs/SECURITY_AUDIT.md) for details.
-
----
-
-## Better Audit - 2026-03-05
-
-Summary: 35 findings across 28 files. 0 shared utilities to extract (ensureDataDir removal is deletion, not extraction).
-
-### File Ownership Map
-
-| File | Primary Category | Reason |
-|------|-----------------|--------|
-| `server/lib/db.js` | Security | Hardcoded DB password |
-| `server/routes/cos.js` | Security | Mass assignment (HIGH) + string concat bug |
-| `server/services/backup.js` | Security | Hardcoded DB password in backup |
-| `server/lib/ports.js` | Code Quality | Hardcoded localhost |
-| `server/services/browserService.js` | Code Quality | Hardcoded 127.0.0.1 |
-| `server/services/instances.js` | Code Quality | Magic number + bare catch |
-| `server/services/worktreeManager.js` | Code Quality | Silent .catch blocks |
-| `client/src/pages/PromptManager.jsx` | Bugs & Perf | window.alert/confirm |
-| `server/lib/errorHandler.js` | Bugs & Perf | process.exit in library |
-| `server/services/socket.js` | Bugs & Perf | Socket cleanup for dropped clients |
-| `client/src/hooks/useCityData.js` | Stack-Specific | Incorrect socket.off() |
-| `client/src/pages/ChiefOfStaff.jsx` | Stack-Specific | Incorrect socket.off() |
-| `client/src/pages/Instances.jsx` | Stack-Specific | Incorrect socket.off() |
-| `client/src/pages/AIProviders.jsx` | Stack-Specific | Stale closure in useEffect |
-| `client/src/services/api.js` | Stack-Specific | Missing response.ok check |
-| `client/src/utils/fileUpload.js` | DRY | Duplicate formatFileSize |
-| `client/src/components/cos/TaskAddForm.jsx` | DRY | Import update for formatFileSize |
-| `server/services/cosEvolution.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/apps.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/missions.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/appActivity.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/productivity.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/autonomousJobs.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/history.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/memoryBM25.js` | DRY | ensureDataDir wrapper removal |
-| `server/services/autobiography.js` | DRY | ensureDataDir wrapper removal |
-
-### Security & Secrets
-- [x] **[HIGH]** `server/lib/db.js:18` - Hardcoded default DB password 'portos' as fallback. *(Fixed: PR #71)*
-- [x] **[HIGH]** `server/routes/cos.js:77` - Mass assignment: `req.body` spread directly into config without Zod validation. *(Already had Zod `.strict()` validation)*
-- [x] **[HIGH]** `server/routes/cos.js:991` - String concatenation with potentially undefined value. *(Fixed: PR #71)*
-- [x] **[MEDIUM]** `server/services/backup.js:173` - Same hardcoded 'portos' password fallback. *(Fixed: PR #71)*
-- [x] **[HIGH]** npm audit: multer DoS vulnerability (GHSA-5528-5vmv-3xc2). *(Already resolved)*
-- [ ] **[LOW]** npm audit: pm2 ReDoS (GHSA-x5gf-qvw8-r2rm). No upstream fix available. (Tracked only)
-
-### Code Quality & Style
-- [x] **[HIGH]** `server/lib/ports.js:4` - Hardcoded `localhost`. *(Fixed: PR #67)*
-- [x] **[HIGH]** `server/services/browserService.js:26,66` - Hardcoded `127.0.0.1` for CDP. *(Fixed: PR #67)*
-- [x] **[HIGH]** `server/services/instances.js:384` - Magic number `2000`. *(Fixed: PR #67)*
-- [x] **[MEDIUM]** `server/services/instances.js:190,316` - Bare catch blocks. *(Fixed: PR #67)*
-- [x] **[MEDIUM]** `server/services/worktreeManager.js` - Silent `.catch(() => {})` blocks. *(Fixed: PR #67)*
-
-### DRY & YAGNI
-- [x] **[MEDIUM]** `client/src/utils/fileUpload.js:247` - Duplicate `formatFileSize`. *(Fixed: PR #68)*
-- [x] **[HIGH]** 9 files with redundant `ensureDataDir()` wrappers. *(Fixed: PR #68)*
-
-### Architecture & SOLID (tracked, not auto-remediated)
-- [ ] **[CRITICAL]** `server/services/cos.js` (3827 lines) - God file with 40+ exports, mixed concerns. Needs decomposition into cosOrchestrator, cosStateManager, taskGenerator, agentRegistry. (Complexity: Very Complex)
-- [ ] **[CRITICAL]** `server/services/subAgentSpawner.js` (3284 lines) - Mega service spanning model selection, spawning, worktrees, JIRA, git, memory. (Complexity: Very Complex)
-- [ ] **[HIGH]** `server/services/digital-twin.js:280-375` - Mixed API/CLI provider abstraction in single function. (Complexity: Medium)
-- [ ] **[MEDIUM]** `client/src/pages/ChiefOfStaff.jsx:43-150` - 14+ useState hooks, should extract custom hooks. (Complexity: Medium)
-- [ ] **[MEDIUM]** Inconsistent pagination patterns across routes. (Complexity: Medium)
-- [ ] **[MEDIUM]** Error response envelope not fully consistent. (Complexity: Simple)
-
-### Bugs, Performance & Error Handling
-- [x] **[HIGH]** `client/src/pages/PromptManager.jsx` - Uses `alert()` and `confirm()`. *(Fixed: PR #69)*
-- [x] **[MEDIUM]** `server/lib/errorHandler.js:224` - `process.exit(1)` in library code. *(Fixed: PR #69)*
-- [x] **[MEDIUM]** `server/services/socket.js` - Socket event handlers not cleaned up for dropped clients. *(Fixed: PR #72)*
-
-### Stack-Specific (Node/React)
-- [x] **[HIGH]** `client/src/hooks/useCityData.js` - Incorrect `socket.off()`. *(Fixed: PR #70)*
-- [x] **[HIGH]** `client/src/pages/ChiefOfStaff.jsx` - Incorrect `socket.off()`. *(Fixed: PR #70)*
-- [x] **[HIGH]** `client/src/pages/Instances.jsx` - Incorrect `socket.off()`. *(Fixed: PR #70)*
-- [x] **[HIGH]** `client/src/pages/AIProviders.jsx` - Stale closure. *(Fixed: PR #70)*
-- [x] **[MEDIUM]** `client/src/services/api.js` - Missing `response.ok` check. *(Fixed: PR #69)*
-
-### Test Coverage (tracked, not auto-remediated)
-- [ ] **[CRITICAL]** `server/services/cos.js` - No service tests for core 3827-line business logic
-- [ ] **[CRITICAL]** `server/services/subAgentSpawner.js` - Partial tests (657 lines), most spawn logic untested
-- [ ] **[HIGH]** `server/services/instances.js` - No tests for federation logic
-- [ ] **[HIGH]** `server/services/digital-twin.js` - No tests for 2823-line service
-- [ ] **[HIGH]** `server/services/memory.js` - No tests for CRUD and search
-- [ ] **[HIGH]** `server/services/brain.js` - No service tests (route tests only)
-- [ ] **[HIGH]** `server/services/pm2.js` - No tests for process management
-- [ ] **[HIGH]** `server/services/shell.js` - No tests for PTY sessions
-- [ ] Overall: 29.4% service coverage (35/119), 12.0% route coverage (6/50)
-
-## Better Audit - 2026-03-05 (Pass 2)
-
-Summary: 18 new findings across 16 files. 2 shared utilities to extract.
-
-### Foundation — Shared Utilities
-1. **dateUtils** — `getDateString(date)` → `date.toISOString().split('T')[0]`. Replaces duplicates in agentActivity.js, productivity.js. Add to `server/lib/fileUtils.js`.
-2. **timeConstants** — `HOUR`, `DAY` constants. Replaces duplicates in autonomousJobs.js, taskSchedule.js. Add to `server/lib/fileUtils.js`.
-
-### File Ownership Map
-
-| File | Primary Category | Reason |
-|------|-----------------|--------|
-| `server/services/cos.js` | Bugs & Perf | CRITICAL TOCTOU race condition |
-| `server/services/cosRunnerClient.js` | Bugs & Perf | Missing fetch timeout |
-| `client/src/pages/PromptManager.jsx` | Bugs & Perf | Missing fetch error handling |
-| `server/services/mediaService.js` | Code Quality | Class-based → functional |
-| `client/src/hooks/useTheme.js` | Code Quality | Empty catch blocks |
-| `server/services/runner.js` | Code Quality | Silent JSON parse catch |
-| `server/lib/db.js` | Code Quality | Silent health check error |
-| `client/src/pages/Settings.jsx` | Code Quality | Empty catch handlers |
-| `server/services/agentActivity.js` | DRY | Duplicate getDateString |
-| `server/services/productivity.js` | DRY | Duplicate getDateString |
-| `server/services/autonomousJobs.js` | DRY | Duplicate time constants |
-| `server/services/taskSchedule.js` | DRY | Duplicate time constants |
-| `server/lib/logger.js` | DRY | Unused module — DELETE |
-| `server/lib/logger.test.js` | DRY | Unused test — DELETE |
-| `server/lib/fileUtils.js` | DRY | Add shared getDateString + time constants |
-| `server/integrations/moltworld/api.js` | Stack-Specific | Missing fetch timeout |
-| `server/integrations/moltbook/api.js` | Stack-Specific | Missing fetch timeout |
-
-### Bugs, Performance & Error Handling
-- [ ] **[CRITICAL]** `server/services/cos.js:3103,3394,3454,3486,3526` - TOCTOU race condition: addTask, updateTask, deleteTask, reorderTasks, approveTask lack withStateLock mutex. Concurrent calls lose data. Fix: Wrap read-modify-write in withStateLock(). Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/cosRunnerClient.js:237-268` - executeCliRunViaRunner() fetch has no timeout. Fix: Add AbortController with 60s timeout. Complexity: Simple
-- [ ] **[HIGH]** `client/src/pages/PromptManager.jsx:85-91,95-100,112-127` - Multiple fetch calls missing response.ok check. Fix: Add error handling with toast notifications. Complexity: Simple
-
-### Code Quality & Style
-- [ ] **[HIGH]** `server/services/mediaService.js:4-186` - Class-based implementation violates functional programming convention. Fix: Convert to functional module with closures. Complexity: Medium
-- [ ] **[MEDIUM]** `client/src/hooks/useTheme.js:123,136` - Empty .catch(() => {}) swallows errors. Fix: Add console.log with warning. Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/runner.js:140` - Silent try/catch on JSON parse without logging. Fix: Add warning log. Complexity: Simple
-- [ ] **[MEDIUM]** `server/lib/db.js:87-89` - Health check error swallowed without logging. Fix: Add error log. Complexity: Simple
-- [ ] **[MEDIUM]** `client/src/pages/Settings.jsx:23,30` - Empty .catch(() => {}) handlers. Fix: Add toast.error() feedback. Complexity: Simple
-
-### DRY & YAGNI
-- [ ] **[HIGH]** `server/services/agentActivity.js:42` + `server/services/productivity.js:28` - Duplicate getDateString. Fix: Extract to fileUtils.js. Complexity: Simple
-- [ ] **[HIGH]** `server/services/autonomousJobs.js:5-6` + `server/services/taskSchedule.js:9-10` - Duplicate HOUR/DAY constants. Fix: Extract to fileUtils.js. Complexity: Simple
-- [ ] **[HIGH]** `server/lib/logger.js` - Unused 84-line module (0 imports). Fix: Delete file and its test. Complexity: Simple
-
-### Stack-Specific (Node/React)
-- [ ] **[MEDIUM]** `server/integrations/moltworld/api.js:41` + `server/integrations/moltbook/api.js:84` - Fetch calls without timeout. Fix: Add AbortController with 10s timeout. Complexity: Simple
-
-### Architecture & SOLID (tracked, not auto-remediated)
-- [ ] **[CRITICAL]** `server/services/cos.js` ↔ `server/services/subAgentSpawner.js` - Circular dependency via dynamic imports. (Complexity: Complex)
-- [ ] **[HIGH]** `server/routes/apps.js:68-77,126-135` - Duplicated app status computation logic. (Complexity: Simple)
-- [ ] **[HIGH]** `server/routes/scaffold.js` (1270 lines) - God route file mixing navigation, templates, scaffolding, GitHub. (Complexity: Medium)
-
-### Test Coverage (tracked, not auto-remediated)
-- Same gaps as Pass 1 — see above section.
-
----
-
-## Better Audit - 2026-03-05 (Pass 3)
-
-Summary: 22 new actionable findings across 16 files. 1 shared utility to extract (fetchWithTimeout).
-
-### Foundation — Shared Utilities
-1. **fetchWithTimeout** — `fetchWithTimeout(url, options, timeoutMs)` wraps fetch with AbortController timeout. Replaces 8+ duplicate patterns in cosRunnerClient.js, memoryClassifier.js, visionTest.js, lmStudioManager.js, etc. Create as `server/lib/fetchWithTimeout.js`.
-
-### File Ownership Map
-
-| File | Primary Category | Reason |
-|------|-----------------|--------|
-| `server/services/cosRunnerClient.js` | Bugs & Perf | CRITICAL: 12 fetch calls missing timeouts + socket config |
-| `server/services/memory.js` | Bugs & Perf | HIGH: data race in getMemory + MEDIUM: sorting type safety |
-| `server/services/agentActionExecutor.js` | Bugs & Perf | HIGH: unsafe array fallback |
-| `server/services/cos.js` | Bugs & Perf | MEDIUM: migration error + lazy-load race |
-| `server/services/memorySync.js` | Code Quality | HIGH: unsafe rows[0] access |
-| `server/lib/db.js` | Code Quality | HIGH: unsafe rows[0] destructuring |
-| `server/services/lmStudioManager.js` | Code Quality | MEDIUM: hardcoded localhost |
-| `server/services/memoryClassifier.js` | Code Quality | MEDIUM: hardcoded localhost |
-| `client/src/pages/Browser.jsx` | Code Quality | MEDIUM: empty catch |
-| `client/src/pages/Shell.jsx` | Code Quality | MEDIUM: empty catch |
-| `client/src/components/cos/TaskAddForm.jsx` | Code Quality | MEDIUM: empty catch |
-| `client/src/hooks/useAgentFeedbackToast.jsx` | Code Quality | MEDIUM: empty catch |
-| `client/src/components/meatspace/HealthCategorySection.jsx` | Code Quality | MEDIUM: empty catch |
-| `client/src/pages/DevTools.jsx` | Code Quality | MEDIUM: stale closure |
-| `server/services/contextUpgrader.js` | Code Quality | MEDIUM: unused 350-line module (DELETE) |
-| `server/lib/fetchWithTimeout.js` | Foundation | NEW: shared utility |
-
-### Bugs, Performance & Error Handling
-- [ ] **[CRITICAL]** `server/services/cosRunnerClient.js:91-313` - 12 fetch calls missing AbortController/timeout (only spawnAgentViaRunner and executeCliRunViaRunner have timeouts). Fix: Use fetchWithTimeout for all calls. Complexity: Simple
-- [ ] **[HIGH]** `server/services/cosRunnerClient.js:19-26` - Socket.IO with `reconnectionAttempts: Infinity` and no error handler. Fix: Cap at 10, add error handler. Complexity: Simple
-- [ ] **[HIGH]** `server/services/memory.js:203-214` - Data race: loadMemory() called outside withMemoryLock, then accessCount incremented inside lock. Fix: Move loadMemory inside lock. Complexity: Simple
-- [ ] **[HIGH]** `server/services/agentActionExecutor.js:137` - Unsafe fallback: `commentsResponse.comments || commentsResponse || []` may yield non-array. Fix: Use Array.isArray check. Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/cos.js:211-221` - Migration rename fallback: copy failure silently swallowed. Fix: Add error propagation in fallback path. Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/memory.js:220-265` - Sort comparison not type-safe for dates (ISO strings compared as numbers via `|| 0`). Fix: Add type-aware comparison. Complexity: Medium
-- [ ] **[MEDIUM]** `server/services/cos.js:83-101` - Agent index lazy-load race: concurrent calls both trigger migration. Fix: Use promise-based singleton pattern. Complexity: Medium
-
-### Code Quality & Style
-- [ ] **[HIGH]** `server/services/memorySync.js:156` - `result.rows[0].max_seq` without checking rows length. Fix: Add bounds check. Complexity: Simple
-- [ ] **[HIGH]** `server/lib/db.js:85` - Destructuring `result.rows[0]` without row existence check. Fix: Add bounds check. Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/lmStudioManager.js:12` - Hardcoded `http://localhost:1234`. Fix: Use `process.env.LM_STUDIO_URL` with fallback. Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/memoryClassifier.js:24` - Hardcoded `http://localhost:1234/v1/chat/completions`. Fix: Use env var with fallback. Complexity: Simple
-- [ ] **[MEDIUM]** `client/src/pages/Browser.jsx:87`, `client/src/pages/Shell.jsx:81`, `client/src/components/cos/TaskAddForm.jsx:106`, `client/src/hooks/useAgentFeedbackToast.jsx:43`, `client/src/components/meatspace/HealthCategorySection.jsx:48` - Empty `.catch(() => {})` swallowing errors. Fix: Replace with `console.warn`. Complexity: Simple
-- [ ] **[MEDIUM]** `client/src/pages/DevTools.jsx:21-40` - Stale closure risk: `loadData` depends on `filter` but not wrapped in useCallback. Fix: Wrap in useCallback with [filter] dep. Complexity: Simple
-- [ ] **[MEDIUM]** `server/services/contextUpgrader.js` - Unused 350-line module with 0 imports. Fix: DELETE file. Complexity: Simple
-
-### Architecture & SOLID (tracked, not auto-remediated)
-- [ ] **[CRITICAL]** `server/services/cos.js` (3837 lines) - God file with 40+ exports. evaluateTasks() is 346 lines with 5-level nesting. (Complexity: Very Complex)
-- [ ] **[CRITICAL]** `server/services/subAgentSpawner.js` (3284 lines) - 10 imports from cos.js, spawnDirectly/spawnViaRunner have 11/10 parameters. (Complexity: Very Complex)
-- [ ] **[HIGH]** `client/src/services/api.js` (1627 lines) - Monolithic API client mixing 20+ domains. (Complexity: Medium)
-- [ ] **[HIGH]** `server/services/digital-twin.js` (2823 lines) - Mixed CRUD, LLM testing, enrichment, export. (Complexity: Complex)
-- [ ] **[HIGH]** `server/routes/cos.js` (1253 lines) - Business logic mixed with HTTP handlers. (Complexity: Medium)
-- [ ] **[HIGH]** `client/src/pages/ChiefOfStaff.jsx` (864 lines) - 24 useState hooks. (Complexity: Medium)
-
-### DRY & YAGNI (tracked for future passes)
-- [ ] **[HIGH]** Duplicate DATA_DIR/path constants in 8+ files — should import from PATHS in fileUtils.js
-- [ ] **[MEDIUM]** 39 instances of `mkdir({recursive:true})` vs centralized `ensureDir()`
-- [ ] **[MEDIUM]** JSON read/write pattern variations (203 occurrences)
-
-### Test Coverage (tracked, not auto-remediated)
-- [ ] **[CRITICAL]** `server/services/cos.js` - No tests for 3837-line core service (45 test cases needed)
-- [ ] **[CRITICAL]** `server/services/cosRunnerClient.js` - No tests for 16 fetch functions (32 test cases needed)
-- [ ] **[CRITICAL]** `server/services/agentActionExecutor.js` - No tests for 661-line service (24 test cases needed)
-- [ ] **[CRITICAL]** `server/services/memorySync.js` - No tests for sync service (18 test cases needed)
-- [ ] **[HIGH]** `server/services/autoFixer.js` - No tests for 301-line service
-- [ ] **[HIGH]** `server/services/subAgentSpawner.test.js` - Tests use copy-pasted logic instead of importing real functions
-- [ ] **[HIGH]** `server/services/digital-twin.test.js` - runTests(), validateCompleteness(), getGapRecommendations() untested
+## Code Audits
+
+See [Security Audit](./docs/SECURITY_AUDIT.md) for the 2025-02-19 security hardening (all 10 items resolved).
+
+### Outstanding Audit Findings (2026-03-05)
+
+Three audit passes identified remaining items across architecture, bugs, code quality, and test coverage. Resolved items from Passes 1-3 have been removed (fixed via PRs #67-72).
+
+**Known low-severity:** pm2 ReDoS (GHSA-x5gf-qvw8-r2rm) — no upstream fix, not exploitable via PortOS routes.
+
+#### Architecture & SOLID
+- [ ] **[CRITICAL]** `server/services/cos.js` (~3800 lines) — God file with 40+ exports. Needs decomposition.
+- [ ] **[CRITICAL]** `server/services/subAgentSpawner.js` (~3300 lines) — Mega service spanning model selection, spawning, worktrees, JIRA, git, memory.
+- [ ] **[CRITICAL]** Circular dependency: `cos.js` ↔ `subAgentSpawner.js` via dynamic imports.
+- [ ] **[HIGH]** `client/src/services/api.js` (1627 lines) — Monolithic API client mixing 20+ domains.
+- [ ] **[HIGH]** `server/services/digital-twin.js` (2823 lines) — Mixed CRUD, LLM testing, enrichment, export.
+- [ ] **[HIGH]** `server/routes/cos.js` (1253 lines) — Business logic mixed with HTTP handlers.
+- [ ] **[HIGH]** `server/routes/scaffold.js` (1270 lines) — God route file.
+- [ ] **[HIGH]** `server/routes/apps.js:68-77,126-135` — Duplicated app status computation.
+- [ ] **[HIGH]** `client/src/pages/ChiefOfStaff.jsx` (864 lines) — 24 useState hooks.
+- [ ] **[MEDIUM]** Inconsistent pagination patterns and error response envelope.
+
+#### Bugs & Performance
+- [ ] **[CRITICAL]** `cos.js` TOCTOU race: addTask/updateTask/deleteTask lack withStateLock mutex.
+- [ ] **[CRITICAL]** `cosRunnerClient.js` — 12 fetch calls missing timeouts.
+- [ ] **[HIGH]** `cosRunnerClient.js` — Socket.IO with infinite reconnection, no error handler.
+- [ ] **[HIGH]** `memory.js` — Data race: loadMemory() outside withMemoryLock.
+- [ ] **[HIGH]** `agentActionExecutor.js:137` — Unsafe array fallback may yield non-array.
+- [ ] **[HIGH]** `PromptManager.jsx` — Fetch calls missing response.ok check.
+- [ ] **[MEDIUM]** `cos.js` — Migration rename fallback silently swallowed; agent index lazy-load race.
+- [ ] **[MEDIUM]** `memory.js` — Sort comparison not type-safe for dates.
+
+#### Code Quality
+- [ ] **[HIGH]** `mediaService.js` — Class-based (violates functional convention).
+- [ ] **[HIGH]** `memorySync.js:156` + `db.js:85` — Unsafe `rows[0]` access without bounds check.
+- [ ] **[MEDIUM]** Hardcoded localhost in `lmStudioManager.js`, `memoryClassifier.js`.
+- [ ] **[MEDIUM]** Empty `.catch(() => {})` in 5 client files (Browser, Shell, TaskAddForm, AgentFeedbackToast, HealthCategorySection).
+- [ ] **[MEDIUM]** `DevTools.jsx` — Stale closure risk.
+- [ ] **[MEDIUM]** Silent catch blocks in `useTheme.js`, `runner.js`, `db.js`, `Settings.jsx`.
+- [ ] **[MEDIUM]** `contextUpgrader.js` — Unused 350-line module (DELETE).
+
+#### DRY
+- [ ] **[HIGH]** Duplicate `getDateString` in agentActivity.js + productivity.js.
+- [ ] **[HIGH]** Duplicate HOUR/DAY constants in autonomousJobs.js + taskSchedule.js.
+- [ ] **[HIGH]** `logger.js` — Unused module (DELETE with test).
+- [ ] **[HIGH]** Duplicate DATA_DIR/path constants in 8+ files.
+- [ ] **[MEDIUM]** Missing fetch timeouts in moltworld/moltbook API integrations.
+- [ ] **[MEDIUM]** 39 instances of `mkdir({recursive:true})` vs centralized `ensureDir()`.
+
+#### Test Coverage
+- Overall: ~29% service coverage, ~12% route coverage
+- Critical gaps: cos.js, cosRunnerClient.js, agentActionExecutor.js, memorySync.js
+- High gaps: autoFixer.js, digital-twin.js, memory.js, brain.js, pm2.js, shell.js, instances.js
---
## Next Actions
-1. **M44 P6**: Finish genome/epigenetic migration cleanup — update route comments, remove Genome card from IdentityTab or redirect to `/meatspace/genome`
-2. **M42 P5**: Cross-Insights Engine — connect genome + taste + personality + goals into derived insights
-3. **M45**: Data Backup & Recovery — protect `./data/` from data loss
-4. **M44 P7**: Apple Health Integration — live sync + bulk XML import (spec above)
-5. **M46**: Unified Search (Cmd+K) — cross-cutting search across all data sources
-6. **M48 P1**: Google Calendar — OAuth2 foundation + calendar read
-7. **M49 P1**: Life Goals — Enhanced goal model with todos and progress tracking
-8. **M48 P2**: Google Calendar — Event CRUD and two-way sync
-9. **M52**: Update Detection — GitHub release polling and update notification
+1. **M42 P5**: Cross-Insights Engine — connect genome + taste + personality + goals into derived insights
+2. **M45**: Data Backup & Recovery — protect `./data/` from data loss
+3. **M50 P7-P9**: Messages — Digital Twin voice drafting, CoS automation, auto-send with AI review gate
+4. **M34 P5-P7**: Digital Twin — Multi-modal capture, advanced testing, personas
+5. **M48 P1**: Google Calendar — OAuth2 foundation + calendar read
+6. **M49 P1**: Life Goals — Enhanced goal model with todos and progress tracking
+7. **M47**: Push Notifications — Discord/Telegram alerts for agent completions and errors
+8. **M52**: Update Detection — GitHub release polling and update notification
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 5e1c28efe2..ba6016d72b 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -54,10 +54,10 @@ See [VERSIONING.md](./VERSIONING.md) for full details.
### Quick Reference
-1. Work on `dev` branch
-2. Push triggers CI → auto-bumps build number
-3. Create PR `dev` → `main` for releases
-4. Merge triggers release creation + version prep
+1. Work on `main` branch (or feature branches merged to `main`)
+2. PRs to `main` trigger CI tests
+3. Push `main` to `release` branch to trigger GitHub Release workflow
+4. Push pattern: `git pull --rebase --autostash && git push`
### Commit Messages
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 995ca10d75..d141927289 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -1,311 +1,60 @@
-# GitHub Actions Pattern
+# GitHub Actions Workflows
-This document describes the recommended GitHub Actions workflow pattern for PortOS sub-projects.
-
-## Overview
-
-The pattern uses two workflows:
-1. **CI Workflow** (`ci.yml`) - Tests, linting, and auto version bumps on `dev`
-2. **Release Workflow** (`release.yml`) - Creates releases when merging to `main`
+PortOS uses two GitHub Actions workflows for CI and releases.
## Branch Strategy
| Branch | Purpose |
|--------|---------|
-| `main` | Production releases only |
-| `dev` | Active development |
+| `main` | Active development |
+| `release` | Push `main` to `release` to trigger releases |
## CI Workflow (`ci.yml`)
-### Trigger Configuration
-
-```yaml
-name: CI
-
-on:
- pull_request:
- branches: [main, dev]
- push:
- branches: [dev]
-
-permissions:
- contents: write
-```
-
-### Jobs
-
-#### 1. Test Job
-
-Runs tests on PRs and pushes. Uses `[skip ci]` detection to avoid infinite loops from auto-commits.
-
-```yaml
-jobs:
- test:
- runs-on: ubuntu-latest
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
-
- strategy:
- matrix:
- node-version: [20.x]
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Use Node.js ${{ matrix.node-version }}
- uses: actions/setup-node@v4
- with:
- node-version: ${{ matrix.node-version }}
- cache: 'npm'
-
- - name: Install dependencies
- run: npm ci
- # For monorepos, install each workspace:
- # run: npm run install:all
-
- - name: Run tests
- run: npm test
-
- - name: Build
- run: npm run build
-```
-
-#### 2. Lint Job
-
-Runs in parallel with tests for faster feedback.
-
-```yaml
- lint:
- runs-on: ubuntu-latest
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Use Node.js 20.x
- uses: actions/setup-node@v4
- with:
- node-version: 20.x
- cache: 'npm'
-
- - name: Install dependencies
- run: npm ci
-
- - name: Check for syntax errors
- run: node --check src/index.js
-```
-
-#### 3. Version Bump Job
-
-Auto-increments patch version after successful tests on `dev` branch.
-
-```yaml
- bump-build:
- runs-on: ubuntu-latest
- needs: [test, lint]
- # Only on push to dev, skip if already a version bump commit
- if: github.event_name == 'push' && github.ref == 'refs/heads/dev' && !contains(github.event.head_commit.message, '[skip ci]')
-
- steps:
- - uses: actions/checkout@v4
- with:
- token: ${{ secrets.GITHUB_TOKEN }}
-
- - name: Configure git
- run: |
- git config user.name "github-actions[bot]"
- git config user.email "github-actions[bot]@users.noreply.github.com"
-
- - name: Bump patch version
- run: |
- CURRENT_VERSION=$(node -p "require('./package.json').version")
-
- MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
- MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
- PATCH=$(echo $CURRENT_VERSION | cut -d. -f3)
-
- NEW_PATCH=$((PATCH + 1))
- NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
-
- npm version $NEW_VERSION --no-git-tag-version
-
- git add package.json package-lock.json
- git commit -m "build: bump version to $NEW_VERSION [skip ci]"
- git push
-```
+Triggers on PRs to `main`/`release` and pushes to `main`. Runs two parallel jobs:
-**Monorepo variant** - Update all package.json files:
+### Test Job
-```yaml
- - name: Bump patch version
- run: |
- CURRENT_VERSION=$(node -p "require('./package.json').version")
+- Installs root, server, and client dependencies
+- Runs server tests (`npm test --prefix server`)
+- Builds client (`npm run build --prefix client`)
+- Skips on `[skip ci]` commits
- MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
- MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
- PATCH=$(echo $CURRENT_VERSION | cut -d. -f3)
+### Lint Job
- NEW_PATCH=$((PATCH + 1))
- NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
-
- npm version $NEW_VERSION --no-git-tag-version
- cd client && npm version $NEW_VERSION --no-git-tag-version && cd ..
- cd server && npm version $NEW_VERSION --no-git-tag-version && cd ..
-
- git add package.json package-lock.json client/package.json server/package.json
- git commit -m "build: bump version to $NEW_VERSION [skip ci]"
- git push
-```
+- Checks server entry point for syntax errors (`node --check server/index.js`)
## Release Workflow (`release.yml`)
-### Trigger Configuration
-
-```yaml
-name: Release
-
-on:
- push:
- branches: [main]
-
-permissions:
- contents: write
-```
-
-### Release Job
-
-Creates a GitHub release with changelog when code is merged to `main`.
-
-```yaml
-jobs:
- release:
- runs-on: ubuntu-latest
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
-
- steps:
- - uses: actions/checkout@v4
- with:
- fetch-depth: 0
- token: ${{ secrets.GITHUB_TOKEN }}
-
- - name: Use Node.js 20.x
- uses: actions/setup-node@v4
- with:
- node-version: 20.x
-
- - name: Configure git
- run: |
- git config user.name "github-actions[bot]"
- git config user.email "github-actions[bot]@users.noreply.github.com"
-
- - name: Get version from package.json
- id: package-version
- run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
-
- - name: Check if tag exists
- id: tag-check
- run: |
- if git rev-parse "v${{ steps.package-version.outputs.version }}" >/dev/null 2>&1; then
- echo "exists=true" >> $GITHUB_OUTPUT
- else
- echo "exists=false" >> $GITHUB_OUTPUT
- fi
-
- - name: Generate changelog
- id: changelog
- if: steps.tag-check.outputs.exists == 'false'
- run: |
- PREV_TAG=$(git describe --tags --abbrev=0 2>/dev/null || git rev-list --max-parents=0 HEAD)
- CHANGELOG=$(git log $PREV_TAG..HEAD --pretty=format:"- %s" --no-merges | grep -v "\[skip ci\]" | head -50)
-
- echo "changelog<<EOF" >> $GITHUB_OUTPUT
- echo "$CHANGELOG" >> $GITHUB_OUTPUT
- echo "EOF" >> $GITHUB_OUTPUT
-
- - name: Create Release
- if: steps.tag-check.outputs.exists == 'false'
- uses: softprops/action-gh-release@v2
- with:
- tag_name: v${{ steps.package-version.outputs.version }}
- name: v${{ steps.package-version.outputs.version }}
- body: |
- ## Changes
+Triggers on push to `release` branch. Steps:
- ${{ steps.changelog.outputs.changelog }}
+1. Reads version from `package.json`
+2. Checks if git tag already exists (skips if so)
+3. Looks for changelog file:
+ - First: `.changelog/v{version}.md` (exact match)
+ - Then: `.changelog/v{major}.{minor}.x.md` (pattern match, replaces placeholders)
+ - Fallback: generates changelog from commit messages
+4. Creates GitHub release with tag `v{version}`
+5. Archives changelog on `main` (renames `.x.md` → exact version)
+6. Fast-forwards `release` to match `main`
- ## Installation
+## Working with CI
- ```bash
- git clone https://github.com/YOUR_ORG/YOUR_REPO.git
- cd YOUR_REPO
- npm install
- npm start
- ```
- draft: false
- prerelease: false
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+### Skip CI
- - name: Prep dev branch for next release
- if: steps.tag-check.outputs.exists == 'false'
- run: |
- CURRENT_VERSION=${{ steps.package-version.outputs.version }}
-
- MAJOR=$(echo $CURRENT_VERSION | cut -d. -f1)
- MINOR=$(echo $CURRENT_VERSION | cut -d. -f2)
-
- NEW_MINOR=$((MINOR + 1))
- NEW_VERSION="$MAJOR.$NEW_MINOR.0"
-
- git fetch origin dev
- git checkout dev
-
- npm version $NEW_VERSION --no-git-tag-version
-
- git add package.json package-lock.json
- git commit -m "build: prep v$NEW_VERSION for next release [skip ci]"
- git push origin dev
-```
-
-## Key Patterns
-
-### Skip CI Marker
-
-Use `[skip ci]` in commit messages to prevent CI from running:
-- Auto-version bump commits include this automatically
-- Use manually for non-code changes (docs, configs)
-
-### Version Strategy
-
-- **Patch** (0.0.X): Auto-incremented on every successful push to `dev`
-- **Minor** (0.X.0): Auto-incremented when merging to `main` (release)
-- **Major** (X.0.0): Manually updated for breaking changes
-
-### Changelog Generation
-
-The release workflow auto-generates changelogs from commit messages between tags, excluding `[skip ci]` commits.
-
-### Git Configuration
-
-Always configure git identity in workflows that make commits:
-
-```yaml
-- name: Configure git
- run: |
- git config user.name "github-actions[bot]"
- git config user.email "github-actions[bot]@users.noreply.github.com"
-```
+Add `[skip ci]` to commit messages for non-code changes (docs, configs). Auto-generated commits from the release workflow include this automatically.
-## Working with Auto-Commits
+### Rebase Before Push
-Since CI auto-commits version bumps, always rebase before pushing:
+Since CI may auto-commit changelog archives, always rebase before pushing:
```bash
git pull --rebase --autostash && git push
```
-## Adapting for Your Project
+## Adapting for Sub-Projects
-1. Copy `.github/workflows/ci.yml` and `.github/workflows/release.yml`
-2. Update the installation instructions in the release body
-3. For monorepos, add the additional package.json update steps
-4. Adjust test and build commands for your project structure
+1. Copy `.github/workflows/ci.yml` and `release.yml`
+2. Update installation and build commands for your project structure
+3. For monorepos, add package.json update steps for each workspace
+4. Update the changelog file path pattern if different
diff --git a/docs/VERSIONING.md b/docs/VERSIONING.md
index a3e42c56b5..a2b7f3d316 100644
--- a/docs/VERSIONING.md
+++ b/docs/VERSIONING.md
@@ -16,68 +16,44 @@ Example progression: `0.22.0` → `0.22.1` (fix) → `0.23.0` (feature) → `1.0
| Branch | Purpose |
|--------|---------|
-| `main` | Production releases only |
-| `dev` | Active development |
+| `main` | Active development |
+| `release` | Push `main` to `release` to trigger GitHub Release workflow |
## Workflow
-### Version Bumping (Manual)
+### Version Bumping
-Version bumps happen in the same commit as the code change:
+Version is managed by the `/release` slash command. Do not bump `package.json` version manually during development.
-```bash
-# Bump version (choose one)
-npm version patch --no-git-tag-version # bug fix
-npm version minor --no-git-tag-version # new feature
-npm version major --no-git-tag-version # breaking change
-
-# Stage version files along with your code changes
-git add package.json package-lock.json [other files]
-git commit -m "feat: add new feature"
-```
-
-### On Push to `dev`
+### On Push/PR to `main`
CI runs tests and linting. No version changes.
-### On Merge `dev` → `main`
+### On Push `main` → `release`
1. Release workflow triggers
-2. Creates git tag with current version (e.g., `v0.23.0`)
+2. Creates git tag with current version (e.g., `v1.31.0`)
3. Generates GitHub release with changelog from `.changelog/v{major}.{minor}.x.md`
-4. Archives the changelog (renames `v0.23.x.md` → `v0.23.0.md`)
-5. Merges `main` back into `dev` to share the changelog archive commit
-
-## Manual Steps
+4. Archives the changelog (renames `v1.31.x.md` → `v1.31.0.md`) on `main`
+5. Fast-forwards `release` to match `main`
### Regular Development
```bash
-git checkout dev
+# Work on main or feature branches
+git checkout main
git pull
-# Make changes, bump version, commit, push
-npm version patch --no-git-tag-version
-git add package.json package-lock.json [changed files]
+# Make changes, commit, push
+git add [changed files]
git commit -m "fix: resolve issue"
git pull --rebase --autostash && git push
```
### Creating a Release
-```bash
-git checkout dev
-git pull
-
-# Create PR from dev to main
-gh pr create --base main --head dev --title "Release v0.23.x"
-
-# After PR is merged:
-# - GitHub creates tag v0.23.0
-# - GitHub creates release with changelog
-# - Changelog archived on main, merged back to dev
-```
+Use the `/release` slash command from `main`. It handles version bumping, changelog finalization, and pushing to the `release` branch.
## CI Skip
-Use `[skip ci]` in commit messages to prevent CI from running (used by automation for changelog archives and merges).
+Use `[skip ci]` in commit messages to prevent CI from running (used by automation for changelog archives).