Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: Workspace Contexts — save/restore project working context (#902)
Adam Eivy10a5d87937b8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fe4ab6f394..a8f4c99cfa 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,8 @@- **[issue-901] Legacy Export — download your whole identity as a portable bundle (server foundation).** A new `POST /api/legacy-export` endpoint gathers your identity across every PortOS domain — digital-twin prompt, autobiography, brain notes, memories, goals + milestones, key decisions, and a health summary — into a single self-contained `.zip` of human-readable Markdown plus machine-readable JSON and a SHA-256 `manifest.json`. The bundle is readable with **zero PortOS running** (plain files, no database), opens with a privacy banner, and degrades gracefully when a domain is empty. Secrets accidentally pasted into notes are redacted before anything leaves the box. `GET /api/legacy-export/preview` reports which sections are present and the estimated size without building the file. This is the server core of the Knowledge Legacy export; PDF rendering and a one-click UI are tracked as follow-ups. (#901)+- **[issue-902] Workspace Contexts — save and restore a project's full working context.** A new **Workspaces** view (Dev Tools → Workspaces) lists every active app/project and, for each, captures the *working context* you'd otherwise have to rebuild by hand: the repo's current **git branch** (plus dirty/clean state), the live **shell sessions** rooted in that repo, and the **CoS/user tasks** scoped to it (the PortOS project also collects its `_self`/unscoped tasks). **Save** snapshots that context; **Restore** reconciles the snapshot against what's live now — reporting which saved shell sessions are still alive (re-attachable, one click to open in the Shell page via its existing attach/claim contract) versus gone, and whether the saved branch is still checked out. It's deliberately **read-only with respect to your work**: it never stashes, switches branches, or kills/respawns shells, so an open editor or uncommitted changes are never clobbered (the #902 hard constraints). Deep-linkable (`/workspace-contexts` and `/workspace-contexts/:appId`), reachable via ⌘K / voice. Stored machine-local in `data/workspace-contexts.json` (shell sessions and repo paths are machine-specific — a context never federates). New endpoints under `/api/workspace-contexts`. (`server/services/workspaceContext.js`, `server/routes/workspaceContexts.js`, `client/src/pages/WorkspaceContexts.jsx`, `client/src/services/apiWorkspaceContexts.js`) (#902)+- **[issue-899] Knowledge Graph now includes Goals and Daily Log entries.** The Brain Graph 3D view (Brain → Graph) extends from the five brain entity types to a full knowledge graph: active Goals and Daily Log journal entries now appear as colored nodes (orange for Goals, teal for Journal) and connect to related entities via semantic similarity and tag overlap. Goals show a progress bar, horizon, and target date in the detail panel; journals link by shared vocabulary in their embedded content. (#899)- **[issue-898] Goal Decomposition Engine — auto-decompose a goal into milestones pre-populated with tasks.** Goals already had AI phase-planning, but `Generate Plan` only produced flat milestones with *no* tasks — you then hand-added every todo. A new **Decompose into Tasks** action (Goals → a goal's Plan section) turns a high-level goal into 3–7 ordered milestones, each carrying 2–5 concrete, estimated tasks (priority + minute estimate), in a single LLM pass. The proposal is fully reviewable before accept — reorder milestones, edit titles/descriptions, drop tasks or whole milestones — and only `Accept Tasks` persists it, normalizing each task with its own id and `pending` status (mirrors the existing generate→accept-phases review flow). Accepted tasks render nested under their milestone with check-off, and unlike phase-planning, decomposition works **without** a goal target date (relative ordering only). Server adds `decomposeGoal` / `acceptGoalDecomposition` / `completeMilestoneTask` (file-backed in `goals.json`, mirrored to MortalLoom iCloud — no Postgres migration) with three new validated routes; existing goals lazily gain `milestone.tasks = []` on load with no data loss. (`server/services/identity/goals.js`, `server/lib/identityValidation.js`, `server/routes/identity.js`, `client/src/hooks/useGoalDetail.js`, `client/src/components/goals/{GoalPlanSection,GoalMilestones}.jsx`, #898)diff --git a/client/src/App.jsx b/client/src/App.jsxindex bbef865c62..66c9fe0fb0 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -74,6 +74,7 @@ const JiraReports = lazyWithReload(() => import('./pages/JiraReports'));const DataManager = lazyWithReload(() => import('./pages/DataManager'));const Insights = lazyWithReload(() => import('./pages/Insights'));const Instances = lazyWithReload(() => import('./pages/Instances'));+const WorkspaceContexts = lazyWithReload(() => import('./pages/WorkspaceContexts'));const SystemHealthPage = lazyWithReload(() => import('./pages/SystemHealthPage'));const CapabilityMap = lazyWithReload(() => import('./pages/CapabilityMap'));const MeatSpace = lazyWithReload(() => import('./pages/MeatSpace'));@@ -228,6 +229,8 @@ export default function App() {<Route path="insights" element={<Navigate to="/insights/overview" replace />} /><Route path="insights/:tab" element={<Insights />} /><Route path="instances" element={<Instances />} />+ <Route path="workspace-contexts" element={<WorkspaceContexts />} />+ <Route path="workspace-contexts/:appId" element={<WorkspaceContexts />} /><Route path="system-health" element={<SystemHealthPage />} /><Route path="capabilities" element={<CapabilityMap />} /><Route path="loops" element={<Loops />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex c52d76e61d..8bc3309913 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -239,6 +239,7 @@ const navItems = [{ to: '/system-health', label: 'System Health', icon: Activity },{ to: '/uploads', label: 'Uploads', icon: Upload },{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 },+ { to: '/workspace-contexts', label: 'Workspaces', icon: Layers },],},{ to: '/goals/list', label: 'Goals', icon: Target, single: true },diff --git a/client/src/pages/WorkspaceContexts.jsx b/client/src/pages/WorkspaceContexts.jsxnew file mode 100644index 0000000000..02b8302a59--- /dev/null+++ b/client/src/pages/WorkspaceContexts.jsx@@ -0,0 +1,259 @@+import { useState, useEffect, useCallback } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import {+ Layers, GitBranch, SquareTerminal, ListChecks, Save, RotateCcw,+ Trash2, RefreshCw, FolderGit2, AlertCircle, CheckCircle2, ArrowRight+} from 'lucide-react';+import toast from '../components/ui/Toast';+import { useAsyncAction } from '../hooks/useAsyncAction';+import { timeAgo } from '../utils/formatters';+import {+ listWorkspaceContexts, getWorkspaceContext, saveWorkspaceContext,+ restoreWorkspaceContext, deleteWorkspaceContext+} from '../services/api';++// Light-weight project switcher (#902): pick a project to see and save/restore+// its working context — git branch, in-repo shell sessions, scoped tasks.+// Deep-linkable: /workspace-contexts (list) and /workspace-contexts/:appId.++function StatChip({ icon: Icon, label, value }) {+ return (+ <div className="flex items-center gap-1.5 text-xs text-gray-400">+ <Icon size={13} />+ <span>{value} {label}</span>+ </div>+ );+}++function ContextDetail({ appId }) {+ const navigate = useNavigate();+ const [ctx, setCtx] = useState(null);+ const [loading, setLoading] = useState(true);++ const load = useCallback(async () => {+ setLoading(true);+ const data = await getWorkspaceContext(appId, { silent: true }).catch(() => null);+ if (!data) {+ toast.error('Could not load workspace context');+ setLoading(false);+ return;+ }+ setCtx(data);+ setLoading(false);+ }, [appId]);++ useEffect(() => { load(); }, [load]);++ const [save, saving] = useAsyncAction(async () => {+ const saved = await saveWorkspaceContext(appId, { silent: true });+ toast.success('Workspace context saved');+ await load();+ return saved;+ }, { errorMessage: 'Failed to save context' });++ const [restore, restoring] = useAsyncAction(async () => {+ const result = await restoreWorkspaceContext(appId, { silent: true });+ const reattach = result?.restorable?.shellSessions?.length || 0;+ const missing = result?.restorable?.missingShellSessionIds?.length || 0;+ toast.success(`Restored: ${reattach} shell session(s) live${missing ? `, ${missing} gone` : ''}`);+ await load();+ return result;+ }, { errorMessage: 'Failed to restore context' });++ const [removeSaved, removing] = useAsyncAction(async () => {+ await deleteWorkspaceContext(appId, { silent: true });+ toast.success('Saved context cleared');+ await load();+ }, { errorMessage: 'Failed to clear context' });++ if (loading) {+ return <div className="text-gray-500 text-sm flex items-center gap-2"><RefreshCw size={14} className="animate-spin" /> Loading…</div>;+ }+ if (!ctx) return null;++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <button+ onClick={() => navigate('/workspace-contexts')}+ className="text-gray-400 hover:text-white text-sm"+ >+ ← All projects+ </button>+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">+ <FolderGit2 size={18} /> {ctx.appName}+ </h2>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={save}+ disabled={saving}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-sm disabled:opacity-50"+ >+ <Save size={14} /> Save context+ </button>+ <button+ onClick={restore}+ disabled={restoring || !ctx.saved}+ title={ctx.saved ? 'Reconcile the saved context against what is live now' : 'Nothing saved yet'}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-card border border-port-border text-gray-200 hover:bg-port-border text-sm disabled:opacity-40"+ >+ <RotateCcw size={14} /> Restore+ </button>+ {ctx.saved && (+ <button+ onClick={removeSaved}+ disabled={removing}+ className="flex items-center gap-1.5 px-2 py-1.5 rounded text-port-error hover:bg-port-error/10 text-sm disabled:opacity-50"+ >+ <Trash2 size={14} />+ </button>+ )}+ </div>+ </div>++ {/* Live context */}+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="text-xs uppercase tracking-wide text-gray-500">Live now</div>+ <div className="flex items-center gap-2 text-sm text-gray-300">+ <GitBranch size={15} />+ {ctx.isRepo+ ? <span>{ctx.branch || '(detached)'}{ctx.dirty ? <span className="text-port-warning ml-2">{ctx.changedFileCount} uncommitted change(s)</span> : <span className="text-port-success ml-2">clean</span>}</span>+ : <span className="text-gray-500">Not a git repo ({ctx.repoPath || 'no path'})</span>}+ </div>++ <div>+ <div className="flex items-center gap-1.5 text-xs text-gray-500 mb-1">+ <SquareTerminal size={13} /> Shell sessions ({ctx.shellSessions.length})+ </div>+ {ctx.shellSessions.length === 0+ ? <div className="text-sm text-gray-600">No live shells rooted in this repo</div>+ : (+ <ul className="space-y-1">+ {ctx.shellSessions.map(s => (+ <li key={s.sessionId} className="flex items-center justify-between text-sm bg-port-bg rounded px-2 py-1">+ <span className="text-gray-300 truncate">{s.label || s.kind || 'shell'} <span className="text-gray-600">— {s.cwd}</span></span>+ <button+ onClick={() => navigate(`/shell/${s.sessionId}`)}+ className="text-port-accent hover:underline flex items-center gap-1 shrink-0"+ >+ Open <ArrowRight size={12} />+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>++ <div>+ <div className="flex items-center gap-1.5 text-xs text-gray-500 mb-1">+ <ListChecks size={13} /> Tasks ({ctx.tasks.length})+ </div>+ {ctx.tasks.length === 0+ ? <div className="text-sm text-gray-600">No tasks scoped to this project</div>+ : (+ <ul className="space-y-1">+ {ctx.tasks.slice(0, 12).map(t => (+ <li key={t.id} className="flex items-center gap-2 text-sm bg-port-bg rounded px-2 py-1">+ <span className="text-gray-600 text-xs uppercase shrink-0">{t.status}</span>+ <span className="text-gray-300 truncate">{t.description}</span>+ </li>+ ))}+ {ctx.tasks.length > 12 && <li className="text-xs text-gray-600">+{ctx.tasks.length - 12} more</li>}+ </ul>+ )}+ </div>+ </div>++ {/* Saved snapshot */}+ {ctx.saved && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">+ <div className="text-xs uppercase tracking-wide text-gray-500">As you left it · saved {timeAgo(ctx.saved.savedAt)}</div>+ <div className="flex items-center gap-2 text-sm text-gray-400">+ <GitBranch size={14} />+ <span>{ctx.saved.branch || '(none)'}</span>+ {ctx.saved.branch && (ctx.saved.branch === ctx.branch+ ? <span className="text-port-success flex items-center gap-1 text-xs"><CheckCircle2 size={12} /> still checked out</span>+ : <span className="text-port-warning flex items-center gap-1 text-xs"><AlertCircle size={12} /> branch changed</span>)}+ </div>+ <div className="flex items-center gap-4 text-xs text-gray-500">+ <span>{ctx.saved.shellSessionIds?.length || 0} shell(s)</span>+ <span>{ctx.saved.taskIds?.length || 0} task(s)</span>+ </div>+ </div>+ )}+ </div>+ );+}++function ContextList() {+ const navigate = useNavigate();+ const [rows, setRows] = useState([]);+ const [loading, setLoading] = useState(true);++ const load = useCallback(async () => {+ setLoading(true);+ const data = await listWorkspaceContexts({ silent: true }).catch(() => null);+ if (!data) {+ toast.error('Could not load workspace contexts');+ setLoading(false);+ return;+ }+ setRows(data.contexts || []);+ setLoading(false);+ }, []);++ useEffect(() => { load(); }, [load]);++ if (loading) {+ return <div className="text-gray-500 text-sm flex items-center gap-2"><RefreshCw size={14} className="animate-spin" /> Loading projects…</div>;+ }++ if (rows.length === 0) {+ return <div className="text-gray-500 text-sm">No active projects. Add an app on the Apps page first.</div>;+ }++ return (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {rows.map(row => (+ <button+ key={row.appId}+ onClick={() => navigate(`/workspace-contexts/${row.appId}`)}+ className="text-left bg-port-card border border-port-border rounded-lg p-4 hover:border-port-accent transition-colors"+ >+ <div className="flex items-center gap-2 text-white font-medium mb-2">+ <FolderGit2 size={16} /> {row.appName}+ </div>+ <div className="flex flex-wrap gap-x-4 gap-y-1 mb-2">+ <StatChip icon={SquareTerminal} label="shell(s)" value={row.shellSessionCount} />+ <StatChip icon={ListChecks} label="task(s)" value={row.taskCount} />+ </div>+ <div className="text-xs text-gray-500">+ {row.savedAt+ ? <span className="flex items-center gap-1"><GitBranch size={11} /> {row.savedBranch || '—'} · saved {timeAgo(row.savedAt)}</span>+ : <span>No saved context</span>}+ </div>+ </button>+ ))}+ </div>+ );+}++export default function WorkspaceContexts() {+ const { appId } = useParams();++ return (+ <div className="max-w-5xl mx-auto space-y-4">+ <div className="flex items-center gap-2">+ <Layers size={20} className="text-port-accent" />+ <h1 className="text-xl font-semibold text-white">Workspace Contexts</h1>+ </div>+ <p className="text-sm text-gray-500">+ Save and restore each project's working context — the active git branch, the+ shell sessions rooted in its repo, and the tasks scoped to it.+ </p>+ {appId ? <ContextDetail appId={appId} /> : <ContextList />}+ </div>+ );+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 890d67fe3e..0055600480 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -37,6 +37,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| File | Purpose ||---|---|| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart/logs). |+| `apiWorkspaceContexts.js` | Per-project working-context save/restore (branch, shells, tasks). || `apiAccounts.js` | Platform accounts. || `apiAgents.js` | Running-agent process management. || `apiCommands.js` | CLI command dispatch. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex a137391802..514597637f 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -5,6 +5,7 @@ export * from './apiCore.js';export * from './apiHealth.js';export * from './apiSystem.js';export * from './apiApps.js';+export * from './apiWorkspaceContexts.js';export * from './apiReferenceRepos.js';export * from './apiPorts.js';export * from './apiScaffold.js';diff --git a/client/src/services/apiWorkspaceContexts.js b/client/src/services/apiWorkspaceContexts.jsnew file mode 100644index 0000000000..531aa45587--- /dev/null+++ b/client/src/services/apiWorkspaceContexts.js@@ -0,0 +1,18 @@+import { request } from './apiCore.js';++// Workspace Contexts (#902) — per-project working-context save/restore.+// `options` lets callers opt into silent mode when they own their error UI.+export const listWorkspaceContexts = (options = {}) =>+ request('/workspace-contexts', options);++export const getWorkspaceContext = (appId, options = {}) =>+ request(`/workspace-contexts/${encodeURIComponent(appId)}`, options);++export const saveWorkspaceContext = (appId, options = {}) =>+ request(`/workspace-contexts/${encodeURIComponent(appId)}/save`, { method: 'POST', ...options });++export const restoreWorkspaceContext = (appId, options = {}) =>+ request(`/workspace-contexts/${encodeURIComponent(appId)}/restore`, { method: 'POST', ...options });++export const deleteWorkspaceContext = (appId, options = {}) =>+ request(`/workspace-contexts/${encodeURIComponent(appId)}`, { method: 'DELETE', ...options });diff --git a/server/index.js b/server/index.jsindex 222ff852f3..08142e8199 100644--- a/server/index.js+++ b/server/index.js@@ -17,6 +17,7 @@ import avatarRoutes from './routes/avatar.js';import systemHealthRoutes from './routes/systemHealth.js';import capabilitiesRoutes from './routes/capabilities.js';import appsRoutes from './routes/apps.js';+import workspaceContextsRoutes from './routes/workspaceContexts.js';import referenceReposRoutes from './routes/referenceRepos.js';import portsRoutes from './routes/ports.js';import networkExposureRoutes from './routes/networkExposure.js';@@ -429,6 +430,7 @@ app.use('/api/avatar', avatarRoutes);app.use('/api/system', systemHealthRoutes);app.use('/api/capabilities', capabilitiesRoutes);app.use('/api/apps', appsRoutes);+app.use('/api/workspace-contexts', workspaceContextsRoutes);app.use('/api/apps/:appId/reference-repos', referenceReposRoutes);app.use('/api/ports', portsRoutes);app.use('/api/network-exposure', networkExposureRoutes);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 0670f42c13..3a2ae3b89b 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -103,6 +103,7 @@ export const NAV_COMMANDS = [{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },{ id: 'nav.devtools.submodules', path: '/devtools/submodules', label: 'Submodules', section: 'Dev Tools', aliases: ['devtools-submodules'] },{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },+ { id: 'nav.workspace-contexts', path: '/workspace-contexts', label: 'Workspaces', section: 'Dev Tools', aliases: ['workspaces', 'workspace-contexts', 'project-contexts', 'project-switcher'], keywords: ['project', 'context', 'switch project', 'branch', 'shell', 'tasks', 'restore', 'working context'] },{ id: 'nav.twin.overview', path: '/digital-twin/overview', label: 'Overview', section: 'Identity', aliases: ['digital-twin', 'twin'] },{ id: 'nav.twin.accounts', path: '/digital-twin/accounts', label: 'Accounts', section: 'Identity', aliases: ['twin-accounts'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex cf3048c23f..beb6ebea2b 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -251,6 +251,14 @@ export const referenceRepoSchema = z.object({});// App schema for registration/update+// Workspace Context (#902) — the only input is an app id (the apps-registry+// key, or the fixed 'portos-default' baseline). Mirrors the apps-registry id+// shape: uuid-style ids plus the literal baseline id, so a hand-crafted path+// segment can't reach the service with a junk id.+export const workspaceContextParamsSchema = z.object({+ appId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/, 'invalid app id')+});+export const appSchema = z.object({name: z.string().min(1).max(100),repoPath: z.string().min(1),diff --git a/server/routes/workspaceContexts.js b/server/routes/workspaceContexts.jsnew file mode 100644index 0000000000..2550285034--- /dev/null+++ b/server/routes/workspaceContexts.js@@ -0,0 +1,54 @@+/**+ * Workspace Contexts routes (#902)+ *+ * Read-only with respect to user work — save/restore snapshot and reconcile+ * the working context (git branch, in-repo shell sessions, scoped tasks) but+ * never mutate a repo or spawn/attach shells. See services/workspaceContext.js.+ */+import { Router } from 'express';+import * as workspaceContext from '../services/workspaceContext.js';+import { validateRequest, workspaceContextParamsSchema } from '../lib/validation.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';++const router = Router();++// Throws 404 when the app id is unknown — every per-app handler returns null+// in that case, so this collapses the repeated null check.+function assertFound(result, appId) {+ if (result === null) {+ throw new ServerError(`No app with id ${appId}`, { status: 404, code: 'NOT_FOUND' });+ }+ return result;+}++// GET /api/workspace-contexts — project switcher list (one row per active app)+router.get('/', asyncHandler(async (req, res) => {+ res.json({ contexts: await workspaceContext.listContexts() });+}));++// GET /api/workspace-contexts/:appId — live context + last-saved snapshot+router.get('/:appId', asyncHandler(async (req, res) => {+ const { appId } = validateRequest(workspaceContextParamsSchema, req.params);+ res.json(assertFound(await workspaceContext.getContext(appId), appId));+}));++// POST /api/workspace-contexts/:appId/save — snapshot current working context+router.post('/:appId/save', asyncHandler(async (req, res) => {+ const { appId } = validateRequest(workspaceContextParamsSchema, req.params);+ res.json(assertFound(await workspaceContext.saveContext(appId), appId));+}));++// POST /api/workspace-contexts/:appId/restore — reconcile saved vs live+router.post('/:appId/restore', asyncHandler(async (req, res) => {+ const { appId } = validateRequest(workspaceContextParamsSchema, req.params);+ res.json(assertFound(await workspaceContext.restoreContext(appId), appId));+}));++// DELETE /api/workspace-contexts/:appId — drop the saved snapshot+router.delete('/:appId', asyncHandler(async (req, res) => {+ const { appId } = validateRequest(workspaceContextParamsSchema, req.params);+ const deleted = await workspaceContext.deleteContext(appId);+ res.json({ deleted });+}));++export default router;diff --git a/server/routes/workspaceContexts.test.js b/server/routes/workspaceContexts.test.jsnew file mode 100644index 0000000000..df52295bff--- /dev/null+++ b/server/routes/workspaceContexts.test.js@@ -0,0 +1,90 @@+/**+ * Route tests for workspace-contexts (#902): param validation, 404 on+ * unknown app id, and dispatch to the service. The service is mocked — these+ * are guard/wiring tests, not service coverage (that lives in+ * services/workspaceContext.test.js).+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import workspaceContextsRoutes from './workspaceContexts.js';++vi.mock('../services/workspaceContext.js', () => ({+ listContexts: vi.fn().mockResolvedValue([{ appId: 'app-1', appName: 'X' }]),+ getContext: vi.fn(),+ saveContext: vi.fn(),+ restoreContext: vi.fn(),+ deleteContext: vi.fn()+}));++import * as wc from '../services/workspaceContext.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/workspace-contexts', workspaceContextsRoutes);+ app.use((err, _req, res, _next) => {+ res.status(err.status ?? 500).json({ error: err.message, code: err.code });+ });+ return app;+}++describe('workspace-contexts routes', () => {+ beforeEach(() => vi.clearAllMocks());++ it('GET / lists contexts', async () => {+ const res = await request(makeApp()).get('/api/workspace-contexts');+ expect(res.status).toBe(200);+ expect(res.body.contexts).toEqual([{ appId: 'app-1', appName: 'X' }]);+ });++ it('GET /:appId returns the context', async () => {+ wc.getContext.mockResolvedValue({ appId: 'app-1', branch: 'main' });+ const res = await request(makeApp()).get('/api/workspace-contexts/app-1');+ expect(res.status).toBe(200);+ expect(res.body.branch).toBe('main');+ expect(wc.getContext).toHaveBeenCalledWith('app-1');+ });++ it('GET /:appId → 404 when the service returns null', async () => {+ wc.getContext.mockResolvedValue(null);+ const res = await request(makeApp()).get('/api/workspace-contexts/ghost');+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('NOT_FOUND');+ });++ it('rejects an app id with illegal characters → 400', async () => {+ const res = await request(makeApp()).get('/api/workspace-contexts/bad%2Fid');+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(wc.getContext).not.toHaveBeenCalled();+ });++ it('POST /:appId/save dispatches to saveContext', async () => {+ wc.saveContext.mockResolvedValue({ appId: 'app-1', savedAt: 'now' });+ const res = await request(makeApp()).post('/api/workspace-contexts/app-1/save');+ expect(res.status).toBe(200);+ expect(res.body.savedAt).toBe('now');+ expect(wc.saveContext).toHaveBeenCalledWith('app-1');+ });++ it('POST /:appId/restore dispatches to restoreContext', async () => {+ wc.restoreContext.mockResolvedValue({ appId: 'app-1', restorable: { shellSessions: [] } });+ const res = await request(makeApp()).post('/api/workspace-contexts/app-1/restore');+ expect(res.status).toBe(200);+ expect(res.body.restorable.shellSessions).toEqual([]);+ });++ it('POST /:appId/save → 404 when app unknown', async () => {+ wc.saveContext.mockResolvedValue(null);+ const res = await request(makeApp()).post('/api/workspace-contexts/ghost/save');+ expect(res.status).toBe(404);+ });++ it('DELETE /:appId returns the deleted flag', async () => {+ wc.deleteContext.mockResolvedValue(true);+ const res = await request(makeApp()).delete('/api/workspace-contexts/app-1');+ expect(res.status).toBe(200);+ expect(res.body.deleted).toBe(true);+ });+});diff --git a/server/services/workspaceContext.js b/server/services/workspaceContext.jsnew file mode 100644index 0000000000..b6afbc023c--- /dev/null+++ b/server/services/workspaceContext.js@@ -0,0 +1,270 @@+/**+ * Workspace Context Service (#902)+ *+ * Captures and restores a project's full *working context* so switching+ * between projects restores what you were doing — the active git branch,+ * the live shell session(s) you had open, and the CoS/PLAN tasks scoped to+ * that project.+ *+ * What a context record holds (one per app id):+ * {+ * appId, // the project's apps-registry id+ * branch, // git branch captured at save time+ * shellSessionIds: [...], // live shell sessions whose cwd is in the repo+ * taskIds: [...], // CoS/user task ids scoped to this app+ * savedAt // ISO timestamp of last save+ * }+ *+ * STORAGE.md classification: machine-local `file-primary`. Shell sessions are+ * in-memory PTYs on THIS machine and repo paths are machine-specific, so a+ * context record is meaningless on a federated peer — it must not sync. A+ * single `data/workspace-contexts.json` keyed by app id is the right shape+ * (small records, no relational queries, no tombstones/sync cursor). Writes+ * are serialized through a single-tail queue because both the blur/save path+ * and an explicit restore can mutate the same file (CLAUDE.md: "serialize+ * writes server-side… collapse the queue to a single tail per shared file").+ *+ * This service is read-only with respect to user work: it NEVER stashes,+ * checks out, or otherwise mutates a repo's working tree. "Restore" reports+ * the saved git branch and surfaces tasks + re-attachable shell sessions; the+ * client drives any actual shell re-attach through the existing+ * single-subscriber attach/claim contract in services/shell.js. Auto-switching+ * branches / re-spawning dead shells is deliberately deferred (see #902 open+ * decisions and the follow-up issue) to avoid clobbering uncommitted work.+ */++import { join } from 'path';+import { atomicWrite, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { getAppById, getAllApps, PORTOS_APP_ID } from './apps.js';+import { getBranch, getStatus, isRepo } from './git.js';+import { listAllSessions } from './shell.js';+import { getAllTasks } from './cosTaskStore.js';++const CONTEXTS_FILE = join(PATHS.data, 'workspace-contexts.json');++// Single-tail write queue — both save and restore round-trip read→modify→write+// against the one shared file, so they must serialize.+const queueWrite = createFileWriteQueue();++/** Read the contexts map ({ [appId]: record }), tolerating a missing/blank file. */+async function loadContexts() {+ const data = await readJSONFile(CONTEXTS_FILE, { contexts: {} });+ if (!data || typeof data.contexts !== 'object' || data.contexts === null) {+ return { contexts: {} };+ }+ return data;+}++/**+ * Tasks (user + CoS internal) scoped to an app id via `metadata.app`. The+ * PortOS app is special-cased: CoS scopes its own-repo tasks as `_self` OR+ * leaves `metadata.app` absent, so the baseline PortOS context collects both.+ * Returns light task summaries — enough for the UI to list + deep-link, not+ * the full task body.+ */+function tasksForApp(allTasks, appId) {+ const flat = [+ ...(allTasks.user?.tasks || []),+ ...(allTasks.cos?.tasks || [])+ ];+ const isPortos = appId === PORTOS_APP_ID;+ return flat+ .filter(t => {+ const scoped = t.metadata?.app || null;+ if (isPortos) return scoped === null || scoped === '_self' || scoped === PORTOS_APP_ID;+ return scoped === appId;+ })+ .map(t => ({+ id: t.id,+ description: (t.description || '').split('\n')[0].slice(0, 200),+ status: t.status || null,+ priority: t.priority || null+ }));+}++/**+ * Live shell sessions whose cwd is inside the app's repo. Path containment+ * is prefix-based on a normalized (trailing-slash) repoPath so a sibling+ * directory sharing a name prefix (e.g. `/code/app` vs `/code/app-www`)+ * doesn't false-match. The repo root itself also matches.+ */+function shellSessionsForRepo(sessions, repoPath) {+ if (!repoPath) return [];+ const root = repoPath.replace(/\/+$/, '');+ const prefix = `${root}/`;+ return sessions.filter(s => {+ const cwd = (s.cwd || '').replace(/\/+$/, '');+ return cwd === root || `${s.cwd || ''}`.startsWith(prefix);+ });+}++/**+ * Compute the *live* working context for an app WITHOUT persisting it —+ * the current git branch/dirty state, in-repo shell sessions, and scoped+ * tasks. Used both by `saveContext` (to snapshot) and `getContext` (to show+ * the live view alongside the last-saved snapshot).+ *+ * @param {string} appId+ * @returns {Promise<object|null>} null when the app id is unknown.+ */+export async function captureLiveContext(appId) {+ const app = await getAppById(appId);+ if (!app) return null;++ const repoPath = app.repoPath || null;+ // Git reads are best-effort — a missing/non-repo path yields nulls, not a throw.+ const repo = repoPath ? await isRepo(repoPath).catch(() => false) : false;+ const [branch, status, allTasks] = await Promise.all([+ repo ? getBranch(repoPath).catch(() => null) : Promise.resolve(null),+ repo ? getStatus(repoPath).catch(() => null) : Promise.resolve(null),+ getAllTasks().catch(() => ({ user: { tasks: [] }, cos: { tasks: [] } }))+ ]);++ const sessions = shellSessionsForRepo(listAllSessions(), repoPath);+ const tasks = tasksForApp(allTasks, appId);++ return {+ appId,+ appName: app.name,+ repoPath,+ isRepo: repo,+ branch,+ dirty: status ? !status.clean : null,+ changedFileCount: status ? status.files.length : null,+ shellSessions: sessions.map(s => ({+ sessionId: s.sessionId,+ label: s.label,+ cwd: s.cwd,+ kind: s.kind,+ attached: s.attached+ })),+ tasks+ };+}++/** Get the saved context record for an app id (null if never saved). */+export async function getSavedContext(appId) {+ const { contexts } = await loadContexts();+ return contexts[appId] || null;+}++/**+ * Combined view for a single app: the live context plus whatever was last+ * saved. The UI shows "live now" and "as you left it" side by side.+ */+export async function getContext(appId) {+ const [live, saved] = await Promise.all([+ captureLiveContext(appId),+ getSavedContext(appId)+ ]);+ if (!live) return null;+ return { ...live, saved };+}++/**+ * Persist the current working context for an app. Snapshots branch + the ids+ * of in-repo shell sessions + scoped task ids so a later `restoreContext` can+ * reconcile them against what's still live.+ */+export async function saveContext(appId) {+ const live = await captureLiveContext(appId);+ if (!live) return null;++ const record = {+ appId,+ branch: live.branch,+ shellSessionIds: live.shellSessions.map(s => s.sessionId),+ taskIds: live.tasks.map(t => t.id),+ savedAt: new Date().toISOString()+ };++ return queueWrite(async () => {+ const data = await loadContexts();+ data.contexts[appId] = record;+ await ensureDir(PATHS.data);+ await atomicWrite(CONTEXTS_FILE, data);+ console.log(`🗂️ Saved workspace context for ${appId} (branch=${record.branch || 'n/a'}, shells=${record.shellSessionIds.length}, tasks=${record.taskIds.length})`);+ return record;+ });+}++/**+ * Resolve a saved context against current reality. Reports which saved shell+ * sessions are still alive (re-attachable) vs gone, whether the saved branch+ * is still checked out, and the live task list. Does NOT mutate any repo or+ * spawn/attach shells — the client drives re-attach through the existing+ * shell attach/claim contract, and branch switching is left to the user so+ * uncommitted work is never clobbered (#902 hard constraints).+ *+ * @returns {Promise<object|null>} null when the app id is unknown.+ */+export async function restoreContext(appId) {+ const live = await captureLiveContext(appId);+ if (!live) return null;++ const saved = await getSavedContext(appId);+ if (!saved) {+ return { appId, saved: null, live, restorable: { shellSessions: [], missingShellSessionIds: [], branchMatches: null } };+ }++ const savedIds = new Set(saved.shellSessionIds || []);+ const liveSessionIds = new Set(live.shellSessions.map(s => s.sessionId));+ const missing = (saved.shellSessionIds || []).filter(id => !liveSessionIds.has(id));++ return {+ appId,+ saved,+ live,+ restorable: {+ // Live session details for the ids we saved and that still exist — the+ // client re-attaches these via shell.js's claim contract.+ shellSessions: live.shellSessions.filter(s => savedIds.has(s.sessionId)),+ missingShellSessionIds: missing,+ branchMatches: saved.branch == null ? null : saved.branch === live.branch+ }+ };+}++/** Delete a saved context record. Returns true if one existed. */+export async function deleteContext(appId) {+ return queueWrite(async () => {+ const data = await loadContexts();+ if (!data.contexts[appId]) return false;+ delete data.contexts[appId];+ await ensureDir(PATHS.data);+ await atomicWrite(CONTEXTS_FILE, data);+ console.log(`🗂️ Deleted workspace context for ${appId}`);+ return true;+ });+}++/**+ * List every active app with a compact context summary (live counts + last+ * saved-at). Powers the project switcher.+ */+export async function listContexts() {+ const [apps, { contexts }] = await Promise.all([+ getAllApps({ includeArchived: false }),+ loadContexts()+ ]);++ const sessions = listAllSessions();+ const allTasks = await getAllTasks().catch(() => ({ user: { tasks: [] }, cos: { tasks: [] } }));++ return apps.map(app => {+ const saved = contexts[app.id] || null;+ return {+ appId: app.id,+ appName: app.name,+ repoPath: app.repoPath || null,+ shellSessionCount: shellSessionsForRepo(sessions, app.repoPath).length,+ taskCount: tasksForApp(allTasks, app.id).length,+ savedAt: saved?.savedAt || null,+ savedBranch: saved?.branch || null+ };+ });+}++// Exported for unit tests — pure helpers with no I/O.+export const __test = { tasksForApp, shellSessionsForRepo };diff --git a/server/services/workspaceContext.test.js b/server/services/workspaceContext.test.jsnew file mode 100644index 0000000000..3153ab1a7e--- /dev/null+++ b/server/services/workspaceContext.test.js@@ -0,0 +1,208 @@+/**+ * Tests for workspaceContext.js (#902).+ *+ * Covers the pure helpers (task scoping incl. the PortOS `_self`/absent+ * special-case, and prefix-safe shell-cwd containment) and the save→get→+ * restore→delete round-trip against a temp data root, with apps/git/shell/+ * task deps mocked so the orchestration is exercised without a real repo,+ * live PTYs, or the CoS task files.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'workspace-context-test-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));++// Mutable fixtures the mocks read — reassigned per test.+let mockApps = [];+let mockSessions = [];+let mockTasks = { user: { tasks: [] }, cos: { tasks: [] } };+let mockGit = { isRepo: true, branch: 'main', clean: true, files: [] };++vi.mock('./apps.js', () => ({+ PORTOS_APP_ID: 'portos-default',+ getAppById: vi.fn(async (id) => mockApps.find(a => a.id === id) || null),+ getAllApps: vi.fn(async () => mockApps)+}));++vi.mock('./git.js', () => ({+ isRepo: vi.fn(async () => mockGit.isRepo),+ getBranch: vi.fn(async () => mockGit.branch),+ getStatus: vi.fn(async () => ({ clean: mockGit.clean, files: mockGit.files }))+}));++vi.mock('./shell.js', () => ({+ listAllSessions: vi.fn(() => mockSessions)+}));++vi.mock('./cosTaskStore.js', () => ({+ getAllTasks: vi.fn(async () => mockTasks)+}));++const wc = await import('./workspaceContext.js');++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ mockApps = [+ { id: 'portos-default', name: 'PortOS', repoPath: '/code/portos' },+ { id: 'app-1', name: 'BookLoom', repoPath: '/code/bookloom' }+ ];+ mockSessions = [];+ mockTasks = { user: { tasks: [] }, cos: { tasks: [] } };+ mockGit = { isRepo: true, branch: 'main', clean: true, files: [] };+});++describe('tasksForApp', () => {+ const { tasksForApp } = wc.__test;++ it('scopes tasks to the matching app id', () => {+ const all = { user: { tasks: [+ { id: 't1', description: 'a', metadata: { app: 'app-1' } },+ { id: 't2', description: 'b', metadata: { app: 'other' } }+ ] }, cos: { tasks: [] } };+ expect(tasksForApp(all, 'app-1').map(t => t.id)).toEqual(['t1']);+ });++ it('PortOS collects _self, absent, and explicit portos-default scopes', () => {+ const all = { user: { tasks: [+ { id: 's1', description: 'self', metadata: { app: '_self' } },+ { id: 's2', description: 'absent', metadata: {} },+ { id: 's3', description: 'explicit', metadata: { app: 'portos-default' } },+ { id: 's4', description: 'other', metadata: { app: 'app-1' } }+ ] }, cos: { tasks: [] } };+ expect(tasksForApp(all, 'portos-default').map(t => t.id).sort()).toEqual(['s1', 's2', 's3']);+ });++ it('truncates description to the first line', () => {+ const all = { user: { tasks: [+ { id: 't1', description: 'first line\nsecond line', metadata: { app: 'app-1' } }+ ] }, cos: { tasks: [] } };+ expect(tasksForApp(all, 'app-1')[0].description).toBe('first line');+ });+});++describe('shellSessionsForRepo', () => {+ const { shellSessionsForRepo } = wc.__test;++ it('matches the repo root and nested cwds', () => {+ const sessions = [+ { sessionId: 'a', cwd: '/code/app' },+ { sessionId: 'b', cwd: '/code/app/sub/dir' }+ ];+ expect(shellSessionsForRepo(sessions, '/code/app').map(s => s.sessionId)).toEqual(['a', 'b']);+ });++ it('does NOT match a sibling sharing a name prefix', () => {+ const sessions = [+ { sessionId: 'a', cwd: '/code/app' },+ { sessionId: 'b', cwd: '/code/app-www' }+ ];+ expect(shellSessionsForRepo(sessions, '/code/app').map(s => s.sessionId)).toEqual(['a']);+ });++ it('returns [] when repoPath is missing', () => {+ expect(shellSessionsForRepo([{ sessionId: 'a', cwd: '/x' }], null)).toEqual([]);+ });+});++describe('captureLiveContext', () => {+ it('returns null for an unknown app id', async () => {+ expect(await wc.captureLiveContext('nope')).toBeNull();+ });++ it('captures branch, dirty state, in-repo shells, and scoped tasks', async () => {+ mockGit = { isRepo: true, branch: 'feature/x', clean: false, files: [{ path: 'a' }, { path: 'b' }] };+ mockSessions = [+ { sessionId: 's1', cwd: '/code/bookloom', label: 'dev', kind: 'shell', attached: false },+ { sessionId: 's2', cwd: '/code/other', label: 'x', kind: 'shell', attached: true }+ ];+ mockTasks = { user: { tasks: [{ id: 't1', description: 'do thing', status: 'pending', metadata: { app: 'app-1' } }] }, cos: { tasks: [] } };++ const live = await wc.captureLiveContext('app-1');+ expect(live.branch).toBe('feature/x');+ expect(live.dirty).toBe(true);+ expect(live.changedFileCount).toBe(2);+ expect(live.shellSessions.map(s => s.sessionId)).toEqual(['s1']);+ expect(live.tasks.map(t => t.id)).toEqual(['t1']);+ });++ it('tolerates a non-repo path', async () => {+ mockGit = { isRepo: false, branch: null, clean: true, files: [] };+ const live = await wc.captureLiveContext('app-1');+ expect(live.isRepo).toBe(false);+ expect(live.branch).toBeNull();+ expect(live.dirty).toBeNull();+ });+});++describe('save / get / restore / delete round-trip', () => {+ it('persists a snapshot and reconciles it on restore', async () => {+ mockGit = { isRepo: true, branch: 'main', clean: true, files: [] };+ mockSessions = [{ sessionId: 's1', cwd: '/code/bookloom', label: 'dev', kind: 'shell', attached: false }];+ mockTasks = { user: { tasks: [{ id: 't1', description: 'task', status: 'pending', metadata: { app: 'app-1' } }] }, cos: { tasks: [] } };++ const saved = await wc.saveContext('app-1');+ expect(saved.branch).toBe('main');+ expect(saved.shellSessionIds).toEqual(['s1']);+ expect(saved.taskIds).toEqual(['t1']);+ expect(saved.savedAt).toBeTruthy();++ const ctx = await wc.getContext('app-1');+ expect(ctx.saved.branch).toBe('main');+ expect(ctx.branch).toBe('main');++ // s1 still alive → re-attachable; branch unchanged → matches.+ let restore = await wc.restoreContext('app-1');+ expect(restore.restorable.shellSessions.map(s => s.sessionId)).toEqual(['s1']);+ expect(restore.restorable.missingShellSessionIds).toEqual([]);+ expect(restore.restorable.branchMatches).toBe(true);++ // s1 gone + branch switched → reported as missing + mismatch.+ mockSessions = [];+ mockGit = { ...mockGit, branch: 'other' };+ restore = await wc.restoreContext('app-1');+ expect(restore.restorable.shellSessions).toEqual([]);+ expect(restore.restorable.missingShellSessionIds).toEqual(['s1']);+ expect(restore.restorable.branchMatches).toBe(false);++ expect(await wc.deleteContext('app-1')).toBe(true);+ expect(await wc.getSavedContext('app-1')).toBeNull();+ expect(await wc.deleteContext('app-1')).toBe(false);+ });++ it('restore with no saved snapshot returns an empty restorable', async () => {+ const restore = await wc.restoreContext('app-1');+ expect(restore.saved).toBeNull();+ expect(restore.restorable.shellSessions).toEqual([]);+ expect(restore.restorable.branchMatches).toBeNull();+ });++ it('saveContext returns null for an unknown app id', async () => {+ expect(await wc.saveContext('nope')).toBeNull();+ });+});++describe('listContexts', () => {+ it('summarizes every active app with live counts and saved-at', async () => {+ mockSessions = [{ sessionId: 's1', cwd: '/code/bookloom', label: 'dev', kind: 'shell', attached: false }];+ mockTasks = { user: { tasks: [{ id: 't1', description: 'x', metadata: { app: 'app-1' } }] }, cos: { tasks: [] } };+ await wc.saveContext('app-1');++ const list = await wc.listContexts();+ const bookloom = list.find(r => r.appId === 'app-1');+ expect(bookloom.shellSessionCount).toBe(1);+ expect(bookloom.taskCount).toBe(1);+ expect(bookloom.savedAt).toBeTruthy();+ const portos = list.find(r => r.appId === 'portos-default');+ expect(portos.savedAt).toBeNull();+ });+});