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(apps): browse every root markdown file and the whole docs/ tree
Adam Eivyadb07dd8da7e
diff --git a/PLAN.md b/PLAN.mddeleted file mode 100644index 0a0f710052..0000000000--- a/PLAN.md+++ /dev/null@@ -1,4 +0,0 @@-# PLAN--- [x] [today-agenda-dashboard-widget] Today's Agenda dashboard widget — glanceable list of today's remaining calendar events (new `GET /api/calendar/agenda` with a timezone-correct day window, gated on a connected calendar account, seeded into the Everything and Morning Review layouts)-- [x] [on-this-day-dashboard-widget] On This Day dashboard widget — resurfaces Brain journal entries, memories, and ideas written on today's date in past years (new `GET /api/brain/on-this-day` with timezone-correct date matching, journal rows deep-link into the Daily Log via a new `?date=` param, seeded into the Everything and Morning Review layouts)diff --git a/client/src/components/apps/tabs/DocumentsTab.jsx b/client/src/components/apps/tabs/DocumentsTab.jsxindex 86660d2686..642aed8e8a 100644--- a/client/src/components/apps/tabs/DocumentsTab.jsx+++ b/client/src/components/apps/tabs/DocumentsTab.jsx@@ -1,12 +1,19 @@-import { useState, useEffect, useCallback, useRef } from 'react';+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { RefreshCw, FileText, Pencil, Save, X, Plus } from 'lucide-react';import toast from '../../ui/Toast';import BrailleSpinner from '../../BrailleSpinner';import MarkdownOutput from '../../cos/MarkdownOutput';import * as api from '../../../services/api';+const DOCS_ROOT = 'docs';++/** `docs/decisions/x.md` → `docs/decisions`, `docs/API.md` → `docs` (the group header). */+const dirOf = (path) => path.slice(0, path.lastIndexOf('/')) || path;+const baseOf = (path) => path.slice(path.lastIndexOf('/') + 1);+export default function DocumentsTab({ appId, repoPath }) {const [documents, setDocuments] = useState([]);+ const [docs, setDocs] = useState([]);const [hasPlanning, setHasPlanning] = useState(false);const [loading, setLoading] = useState(true);const [selectedDoc, setSelectedDoc] = useState(null);@@ -17,6 +24,8 @@ export default function DocumentsTab({ appId, repoPath }) {const [editing, setEditing] = useState(false);const [editContent, setEditContent] = useState('');const [saving, setSaving] = useState(false);+ // dir → explicit open/closed, overriding the default-open rule below+ const [groupOverrides, setGroupOverrides] = useState({});const loadDocument = useCallback(async (filename) => {setSelectedDoc(filename);@@ -29,15 +38,16 @@ export default function DocumentsTab({ appId, repoPath }) {const fetchDocuments = useCallback(async () => {setLoading(true);- const data = await api.getAppDocuments(appId).catch(() => ({ documents: [], hasPlanning: false }));+ const data = await api.getAppDocuments(appId).catch(() => ({ documents: [], docs: [], hasPlanning: false }));setDocuments(data.documents || []);+ setDocs(data.docs || []);setHasPlanning(data.hasPlanning || false);setLoading(false);- // Auto-select first existing document- const firstExisting = (data.documents || []).find(d => d.exists);+ // Auto-select the first root document, falling back to the docs/ tree+ const firstExisting = (data.documents || []).find(d => d.exists)?.filename || (data.docs || [])[0];if (firstExisting && !selectedDocRef.current) {- loadDocument(firstExisting.filename);+ loadDocument(firstExisting);}}, [appId, loadDocument]);@@ -84,6 +94,18 @@ export default function DocumentsTab({ appId, repoPath }) {fetchDocuments();}, [fetchDocuments]);+ // docs/ entries grouped by their containing directory, preserving the sorted+ // order the server returned so the tree reads top-down.+ const docGroups = useMemo(() => {+ const groups = new Map();+ for (const path of docs) {+ const dir = dirOf(path);+ if (!groups.has(dir)) groups.set(dir, []);+ groups.get(dir).push(path);+ }+ return [...groups.entries()];+ }, [docs]);+if (loading) {return <BrailleSpinner text="Loading documents" />;}@@ -91,13 +113,20 @@ export default function DocumentsTab({ appId, repoPath }) {const existingDocs = documents.filter(d => d.exists);const missingDocs = documents.filter(d => !d.exists);+ const docButtonClass = (filename) => `px-3 py-2 rounded-lg text-sm text-left transition-colors ${+ selectedDoc === filename+ ? 'bg-port-accent/20 text-port-accent border border-port-accent/30'+ : 'bg-port-card border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50'+ }`;+return (<div className="max-w-5xl space-y-4"><div className="flex items-center justify-between"><div><h3 className="text-lg font-semibold text-white">Documents</h3><p className="text-sm text-gray-500">- Key project documents from {repoPath ? repoPath.split('/').pop() : 'repo'}+ Markdown from {repoPath ? repoPath.split('/').pop() : 'repo'}+ {docs.length > 0 && <span className="ml-2">· {docs.length} in docs/</span>}{hasPlanning && <span className="text-port-accent ml-2">.planning/ exists</span>}</p></div>@@ -109,15 +138,15 @@ export default function DocumentsTab({ appId, repoPath }) {</button></div>- {existingDocs.length === 0 && !editing ? (+ {existingDocs.length === 0 && docs.length === 0 && !editing ? (<div className="bg-port-card border border-port-border rounded-lg p-8 text-center"><FileText size={32} className="text-gray-600 mx-auto mb-3" /><p className="text-gray-400 mb-2">No documents found</p><p className="text-xs text-gray-500 mb-4">- Looking for: {documents.map(d => d.filename).join(', ')}+ No markdown in the repo root or a docs/ directory</p>{missingDocs.length > 0 && (- <div className="flex gap-2 justify-center">+ <div className="flex gap-2 justify-center flex-wrap">{missingDocs.map(doc => (<buttonkey={doc.filename}@@ -133,23 +162,50 @@ export default function DocumentsTab({ appId, repoPath }) {) : (<div className="flex flex-col sm:flex-row gap-4">{/* Document selector */}- <div className="sm:w-48 flex sm:flex-col gap-2">+ <div className="sm:w-56 max-h-64 sm:max-h-[600px] overflow-y-auto flex flex-col gap-2 shrink-0">{existingDocs.map(doc => (<buttonkey={doc.filename}onClick={() => loadDocument(doc.filename)}- className={`px-3 py-2 rounded-lg text-sm text-left transition-colors ${- selectedDoc === doc.filename- ? 'bg-port-accent/20 text-port-accent border border-port-accent/30'- : 'bg-port-card border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50'- }`}+ className={docButtonClass(doc.filename)}><FileText size={14} className="inline mr-2" />{doc.filename}</button>))}++ {docGroups.map(([dir, paths]) => (+ <details+ key={dir}+ open={groupOverrides[dir] ?? (dir === DOCS_ROOT || paths.includes(selectedDoc))}+ onToggle={e => {+ // Read `open` now — the state updater runs after React has+ // released the synthetic event's currentTarget.+ const open = e.target.open;+ setGroupOverrides(prev => ({ ...prev, [dir]: open }));+ }}+ >+ <summary className="cursor-pointer text-xs text-gray-500 hover:text-gray-300 py-1">+ {dir}/ <span className="text-gray-600">({paths.length})</span>+ </summary>+ <div className="mt-1 space-y-1">+ {paths.map(path => (+ <button+ key={path}+ onClick={() => loadDocument(path)}+ title={path}+ className={`w-full truncate ${docButtonClass(path)}`}+ >+ <FileText size={12} className="inline mr-2" />+ {baseOf(path)}+ </button>+ ))}+ </div>+ </details>+ ))}+{missingDocs.length > 0 && (- <div className="hidden sm:block mt-2 space-y-1">+ <div className="mt-2 space-y-1"><div className="text-xs text-gray-600">Create:</div>{missingDocs.map(doc => (<button@@ -165,7 +221,7 @@ export default function DocumentsTab({ appId, repoPath }) {</div>{/* Document content */}- <div className="flex-1 bg-port-card border border-port-border rounded-lg p-4 min-h-[300px] overflow-auto">+ <div className="flex-1 min-w-0 bg-port-card border border-port-border rounded-lg p-4 min-h-[300px] overflow-auto">{loadingDoc ? (<BrailleSpinner text="Loading document" />) : editing ? (@@ -200,10 +256,11 @@ export default function DocumentsTab({ appId, repoPath }) {</div>) : docContent ? (<div>- <div className="flex justify-end mb-2">+ <div className="flex items-center justify-between mb-2 gap-2">+ <span className="text-xs text-gray-500 truncate">{selectedDoc}</span><buttononClick={enterEditMode}- className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1"+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1 shrink-0"><Pencil size={14} /> Edit</button>diff --git a/client/src/components/apps/tabs/DocumentsTab.test.jsx b/client/src/components/apps/tabs/DocumentsTab.test.jsxnew file mode 100644index 0000000000..f52b13a699--- /dev/null+++ b/client/src/components/apps/tabs/DocumentsTab.test.jsx@@ -0,0 +1,66 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import DocumentsTab from './DocumentsTab';++vi.mock('../../../services/api', () => ({+ getAppDocuments: vi.fn(),+ getAppDocument: vi.fn(),+ saveAppDocument: vi.fn()+}));++import * as api from '../../../services/api';++const listing = {+ documents: [+ { filename: 'ARCHITECTURE.md', exists: true },+ { filename: 'README.md', exists: true },+ { filename: 'AGENTS.md', exists: false }+ ],+ docs: ['docs/API.md', 'docs/decisions/2026-01-01-choice.md'],+ hasPlanning: false+};++describe('DocumentsTab', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getAppDocuments.mockResolvedValue(listing);+ api.getAppDocument.mockImplementation((_id, filename) =>+ Promise.resolve({ filename, content: `# ${filename}` }));+ });++ it('lists every root markdown file, not just the conventional four', async () => {+ render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);++ expect(await screen.findByRole('button', { name: /ARCHITECTURE\.md/ })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /README\.md/ })).toBeInTheDocument();+ // Auto-selects the first existing root document+ await waitFor(() => expect(api.getAppDocument).toHaveBeenCalledWith('app-1', 'ARCHITECTURE.md'));+ });++ it('groups the docs/ tree by directory and opens a nested file by its full path', async () => {+ render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);++ expect(await screen.findByText('docs/')).toBeInTheDocument();+ expect(screen.getByText('docs/decisions/')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /2026-01-01-choice\.md/ }));++ await waitFor(() =>+ expect(api.getAppDocument).toHaveBeenCalledWith('app-1', 'docs/decisions/2026-01-01-choice.md'));+ });++ it('still offers to create a conventional document the repo is missing', async () => {+ render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);++ expect(await screen.findByRole('button', { name: /AGENTS\.md/ })).toBeInTheDocument();+ });++ it('shows the empty state only when the root and docs/ are both empty', async () => {+ api.getAppDocuments.mockResolvedValue({ documents: [], docs: [], hasPlanning: false });++ render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);++ expect(await screen.findByText('No documents found')).toBeInTheDocument();+ expect(api.getAppDocument).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 891d6126fa..88dff4ddff 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -197,9 +197,14 @@ export const installXcodeScripts = (id, scripts) => request(`/apps/${id}/xcode-sbody: JSON.stringify({ scripts })});export const getAppDocuments = (id, options) => request(`/apps/${id}/documents`, options);-export const getAppDocument = (id, filename) => request(`/apps/${id}/documents/${filename}`);+// Document paths are repo-relative and may be nested (`docs/decisions/x.md`), so+// encode per segment — encodeURIComponent on the whole path would escape the+// separators the wildcard route splits on.+const documentPath = (id, filename) =>+ `/apps/${id}/documents/${String(filename).split('/').map(encodeURIComponent).join('/')}`;+export const getAppDocument = (id, filename) => request(documentPath(id, filename));export const saveAppDocument = (id, filename, content, commitMessage) =>- request(`/apps/${id}/documents/${filename}`, {+ request(documentPath(id, filename), {method: 'PUT',body: JSON.stringify({ content, ...(commitMessage && { commitMessage }) })});diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 05c055ab10..d83e3d79a3 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -1290,29 +1290,29 @@"sources": [{"source": "server/routes/apps/documents.js",- "line": 26+ "line": 109}]},{"method": "GET",- "path": "/api/apps/:id/documents/:filename",+ "path": "/api/apps/:id/documents/*docPath","mountPath": "/api/apps","sources": [{"source": "server/routes/apps/documents.js",- "line": 54+ "line": 143}]},{"method": "PUT",- "path": "/api/apps/:id/documents/:filename",+ "path": "/api/apps/:id/documents/*docPath","mountPath": "/api/apps","sources": [{"source": "server/routes/apps/documents.js",- "line": 83+ "line": 158}]},@@ -11938,7 +11938,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 534+ "line": 540}]},@@ -11949,7 +11949,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 557+ "line": 563}]},@@ -11960,7 +11960,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 605+ "line": 611}]},@@ -11971,7 +11971,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 542+ "line": 548}]},@@ -11982,7 +11982,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 592+ "line": 598}]},@@ -11993,7 +11993,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 573+ "line": 579}]},@@ -12004,7 +12004,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 598+ "line": 604}]},@@ -12015,7 +12015,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 629+ "line": 635}]},@@ -12026,7 +12026,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 665+ "line": 671}]},@@ -12037,7 +12037,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 656+ "line": 662}]},@@ -12048,7 +12048,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 636+ "line": 642}]},@@ -12070,7 +12070,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 515+ "line": 521}]},@@ -12081,7 +12081,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 360+ "line": 366}]},@@ -12092,7 +12092,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 212+ "line": 218}]},@@ -12103,7 +12103,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 310+ "line": 316}]},@@ -12114,7 +12114,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 244+ "line": 250}]},@@ -12125,7 +12125,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 698+ "line": 704}]},@@ -12136,7 +12136,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 712+ "line": 718}]},@@ -12147,7 +12147,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 739+ "line": 745}]},@@ -12158,7 +12158,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 724+ "line": 730}]},@@ -12169,7 +12169,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 679+ "line": 685}]},@@ -12180,7 +12180,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 732+ "line": 738}]},@@ -12191,7 +12191,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 690+ "line": 696}]},@@ -12202,7 +12202,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 750+ "line": 756}]},@@ -12213,7 +12213,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 292+ "line": 298}]},@@ -12224,7 +12224,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 410+ "line": 416}]},@@ -12235,7 +12235,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 384+ "line": 390}]},@@ -12246,7 +12246,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 802+ "line": 808}]},@@ -12257,7 +12257,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 830+ "line": 836}]},@@ -12268,7 +12268,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 841+ "line": 847}]},@@ -12279,7 +12279,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 821+ "line": 827}]},@@ -12290,7 +12290,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 780+ "line": 786}]},@@ -12301,7 +12301,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 775+ "line": 781}]},@@ -12312,7 +12312,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 795+ "line": 801}]},@@ -12323,7 +12323,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 261+ "line": 267}]},@@ -12334,7 +12334,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 859+ "line": 865}]},@@ -12356,7 +12356,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 203+ "line": 209}]},@@ -12389,7 +12389,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 368+ "line": 374}]},@@ -12400,7 +12400,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 454+ "line": 460}]},@@ -12411,7 +12411,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 467+ "line": 473}]},@@ -12433,7 +12433,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 433+ "line": 439}]},@@ -12444,7 +12444,7 @@"sources": [{"source": "server/routes/localLlm.js",- "line": 343+ "line": 349}]},diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 09de8871a5..3c41d300e1 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1986,7 +1986,7 @@ export const llmSchema = z.object({// =============================================================================/**- * Body schema for PUT /api/apps/:id/documents/:filename and+ * Body schema for PUT /api/apps/:id/documents/*docPath and* PUT /api/cos/gsd/projects/:appId/documents/:docName.* Both routes accept a content string plus an optional commit message.*/diff --git a/server/routes/apps/documents.js b/server/routes/apps/documents.jsindex 598d469c8e..52246deb0c 100644--- a/server/routes/apps/documents.js+++ b/server/routes/apps/documents.js@@ -1,16 +1,22 @@/**- * App document endpoints — read/list a fixed allowlist of planning docs and- * write-with-git-commit updates.+ * App document endpoints — browse/read/write the markdown a managed app keeps+ * in its repo, and commit edits back through git.*- * GET /:id/documents → { documents, hasPlanning, gsd }- * GET /:id/documents/:filename → { filename, content }- * PUT /:id/documents/:filename → { success, hash?, created } (git commit)+ * GET /:id/documents → { documents, docs, hasPlanning, gsd }+ * GET /:id/documents/*docPath → { filename, content }+ * PUT /:id/documents/*docPath → { success, hash?, created } (git commit)+ *+ * The browsable set is a RULE, not a fixed allowlist (#5773): every markdown+ * file in the repo root, plus everything under a `docs/` directory when the app+ * has one. `SUGGESTED_DOCUMENTS` only seeds the "create this file" affordance+ * for the conventional agent-facing docs a repo may be missing.*/import { Router } from 'express';-import { readFile } from 'fs/promises';-import { join, resolve } from 'path';-import { atomicWrite } from '../../lib/fileUtils.js';+import { readdir, readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite, listDirectoryByExtension } from '../../lib/fileUtils.js';+import { isPathInsideDir, isSafeFilename, isTopLevelEntryName } from '../../lib/pathSafety.js';import { documentUpdateSchema } from '../../lib/validation.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';import * as git from '../../services/git.js';@@ -18,22 +24,105 @@ import { loadApp, pathExists } from './shared.js';const router = Router();-// Both agent-instruction names are listed (#4852): AGENTS.md is canonical, while a-// managed app's CLAUDE.md is either its one-line AGENTS.md bridge or its only file.-const ALLOWED_DOCUMENTS = ['PLAN.md', 'AGENTS.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];+// Offered as "Create <file>" when absent from the repo root. Both agent-instruction+// names are listed (#4852): AGENTS.md is canonical, while a managed app's CLAUDE.md+// is either its one-line AGENTS.md bridge or its only file. PLAN.md stays here+// because it is a selectable work tracker for apps with no forge issue tracker.+const SUGGESTED_DOCUMENTS = ['AGENTS.md', 'CLAUDE.md', 'GOALS.md', 'PLAN.md', 'REVIEW.md', 'REJECTED.md'];++// Renderable text extensions. A docs/ tree also holds images and data files;+// those are skipped rather than handed to a markdown renderer as mojibake.+const DOC_EXTENSIONS = ['.md', '.markdown', '.mdx', '.txt'];++const DOCS_DIR = 'docs';+const MAX_DOCS_DEPTH = 5; // directory levels walked below the repo root+const MAX_DOCS_FILES = 500; // guard against a pathological docs tree++const isDocFile = (name) => isSafeFilename(name, DOC_EXTENSIONS);++const byPath = (a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' });++/**+ * Every renderable file under `docs/`, as repo-relative `docs/...` paths.+ * Skips dot-directories, and symlinks fall out on their own — `withFileTypes`+ * reports them as neither a file nor a directory.+ */+async function listDocsTree(repoPath) {+ const found = [];+ const walk = async (relDir, depth) => {+ if (depth > MAX_DOCS_DEPTH || found.length >= MAX_DOCS_FILES) return;+ const entries = await readdir(join(repoPath, relDir), { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (found.length >= MAX_DOCS_FILES) return;+ if (entry.name.startsWith('.') || !isTopLevelEntryName(entry.name)) continue;+ const rel = `${relDir}/${entry.name}`;+ if (entry.isDirectory()) await walk(rel, depth + 1);+ else if (entry.isFile() && isDocFile(entry.name)) found.push(rel);+ }+ };+ if (await pathExists(join(repoPath, DOCS_DIR))) await walk(DOCS_DIR, 1);+ return found.sort(byPath);+}++/**+ * Shape check for a requested document path: a renderable file that is either+ * at the repo root or somewhere under `docs/`. `isSafeFilename` covers the leaf+ * (null bytes, separators, `.`/`..`, extension); the directory segments get the+ * same traversal rule via `isTopLevelEntryName`.+ */+function isAllowedDocumentPath(rel) {+ const parts = String(rel || '').split('/');+ const leaf = parts.pop();+ if (!isDocFile(leaf)) return false;+ if (parts.length === 0) return true;+ if (parts[0] !== DOCS_DIR || parts.length > MAX_DOCS_DEPTH) return false;+ return parts.every(isTopLevelEntryName);+}++/**+ * Validate `*docPath` and resolve it inside the app's repo. Throws the same+ * 400s the single-file allowlist used to, so client error handling is unchanged.+ */+function resolveDocumentPath(app, docPath) {+ const filename = Array.isArray(docPath) ? docPath.join('/') : String(docPath || '');++ if (!isAllowedDocumentPath(filename)) {+ throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });+ }++ const resolved = join(app.repoPath, filename);+ if (!isPathInsideDir(app.repoPath, resolved)) {+ throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });+ }++ return { filename, resolved };+}-// GET /api/apps/:id/documents - List which documents exist+/** 400s when the app has no usable checkout — shared by the read/write routes. */+async function requireRepoPath(app) {+ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }+}++// GET /api/apps/:id/documents - List root markdown + the docs/ treerouter.get('/:id/documents', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;if (!app.repoPath || !await pathExists(app.repoPath)) {- return res.json({ documents: [], hasPlanning: false });+ return res.json({ documents: [], docs: [], hasPlanning: false });}- const documents = await Promise.all(ALLOWED_DOCUMENTS.map(async filename => ({- filename,- exists: await pathExists(join(app.repoPath, filename))- })));+ const [rootNames, docs] = await Promise.all([+ listDirectoryByExtension(app.repoPath, { extensions: DOC_EXTENSIONS, mapEntry: name => name }),+ listDocsTree(app.repoPath),+ ]);+ const rootDocs = rootNames.sort(byPath);++ const documents = [+ ...rootDocs.map(filename => ({ filename, exists: true })),+ ...SUGGESTED_DOCUMENTS.filter(f => !rootDocs.includes(f)).map(filename => ({ filename, exists: false })),+ ];const planningDir = join(app.repoPath, '.planning');const hasPlanning = await pathExists(planningDir);@@ -47,29 +136,15 @@ router.get('/:id/documents', loadApp, asyncHandler(async (req, res) => {hasConcerns: await pathExists(join(planningDir, 'CONCERNS.md')),};- res.json({ documents, hasPlanning, gsd });+ res.json({ documents, docs, hasPlanning, gsd });}));-// GET /api/apps/:id/documents/:filename - Read a single document-router.get('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) => {+// GET /api/apps/:id/documents/*docPath - Read a single document+router.get('/:id/documents/*docPath', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;- const { filename } = req.params;-- if (!ALLOWED_DOCUMENTS.includes(filename)) {- throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });- }+ await requireRepoPath(app);- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- const filePath = join(app.repoPath, filename);- const resolved = resolve(filePath);-- // Path traversal guard- if (!resolved.startsWith(resolve(app.repoPath))) {- throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });- }+ const { filename, resolved } = resolveDocumentPath(app, req.params.docPath);if (!await pathExists(resolved)) {throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });@@ -79,25 +154,12 @@ router.get('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) =>res.json({ filename, content });}));-// PUT /api/apps/:id/documents/:filename - Update a document and git commit-router.put('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) => {+// PUT /api/apps/:id/documents/*docPath - Update a document and git commit+router.put('/:id/documents/*docPath', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;- const { filename } = req.params;-- if (!ALLOWED_DOCUMENTS.includes(filename)) {- throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });- }+ await requireRepoPath(app);- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- const filePath = join(app.repoPath, filename);- const resolved = resolve(filePath);-- if (!resolved.startsWith(resolve(app.repoPath))) {- throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });- }+ const { filename, resolved } = resolveDocumentPath(app, req.params.docPath);const { content, commitMessage } = documentUpdateSchema.parse(req.body);const created = !await pathExists(resolved);diff --git a/server/routes/apps/documents.test.js b/server/routes/apps/documents.test.jsnew file mode 100644index 0000000000..3c3e3a7980--- /dev/null+++ b/server/routes/apps/documents.test.js@@ -0,0 +1,134 @@+/**+ * Documents route — the browsable set is a rule (every root markdown file plus+ * the whole `docs/` tree), not the old six-name allowlist (#5773). These run+ * against a real temp repo so the directory walk, the extension filter, and the+ * nested-path guards are exercised end to end; only the apps service and the+ * git commit plumbing are mocked.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import express from 'express';+import { mkdtemp, mkdir, writeFile, rm, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { request } from '../../lib/testHelper.js';++vi.mock('../../services/apps.js', () => ({ getAppById: vi.fn() }));+vi.mock('../../services/git.js', () => ({+ stageFiles: vi.fn().mockResolvedValue(undefined),+ getStatus: vi.fn().mockResolvedValue({ clean: false }),+ commit: vi.fn().mockResolvedValue({ hash: 'abc1234' })+}));++import * as appsService from '../../services/apps.js';+import * as git from '../../services/git.js';+import documentRoutes from './documents.js';++describe('Apps Document Routes', () => {+ let app;+ let repoPath;++ beforeEach(async () => {+ vi.clearAllMocks();+ repoPath = await mkdtemp(join(tmpdir(), 'portos-docs-'));++ // Root: two markdown files a fixed allowlist would never have named, plus a+ // non-markdown file that must stay out of the listing.+ await writeFile(join(repoPath, 'README.md'), '# Readme');+ await writeFile(join(repoPath, 'ARCHITECTURE.md'), '# Architecture');+ await writeFile(join(repoPath, 'package.json'), '{}');++ await mkdir(join(repoPath, 'docs', 'decisions'), { recursive: true });+ await writeFile(join(repoPath, 'docs', 'API.md'), '# API');+ await writeFile(join(repoPath, 'docs', 'diagram.png'), 'not-markdown');+ await writeFile(join(repoPath, 'docs', 'decisions', '2026-01-01-choice.md'), '# Choice');++ appsService.getAppById.mockResolvedValue({ id: 'app-1', name: 'App', repoPath });++ app = express();+ app.use(express.json());+ app.use('/api/apps', documentRoutes);+ });++ afterEach(async () => {+ await rm(repoPath, { recursive: true, force: true });+ });++ it('lists every root markdown file plus the docs/ tree, skipping non-markdown', async () => {+ const res = await request(app).get('/api/apps/app-1/documents');++ expect(res.status).toBe(200);+ const existing = res.body.documents.filter(d => d.exists).map(d => d.filename);+ expect(existing).toEqual(['ARCHITECTURE.md', 'README.md']);+ expect(existing).not.toContain('package.json');++ // Conventional docs the repo lacks are still offered for creation.+ const missing = res.body.documents.filter(d => !d.exists).map(d => d.filename);+ expect(missing).toContain('AGENTS.md');++ expect(res.body.docs).toEqual(['docs/API.md', 'docs/decisions/2026-01-01-choice.md']);+ });++ it('omits docs when the app has no docs/ directory', async () => {+ await rm(join(repoPath, 'docs'), { recursive: true, force: true });++ const res = await request(app).get('/api/apps/app-1/documents');++ expect(res.status).toBe(200);+ expect(res.body.docs).toEqual([]);+ });++ it('reads a nested docs/ file', async () => {+ const res = await request(app).get('/api/apps/app-1/documents/docs/decisions/2026-01-01-choice.md');++ expect(res.status).toBe(200);+ expect(res.body).toEqual({ filename: 'docs/decisions/2026-01-01-choice.md', content: '# Choice' });+ });++ it('reads a root file that was never in the old allowlist', async () => {+ const res = await request(app).get('/api/apps/app-1/documents/ARCHITECTURE.md');++ expect(res.status).toBe(200);+ expect(res.body.content).toBe('# Architecture');+ });++ it('404s a markdown path that does not exist', async () => {+ const res = await request(app).get('/api/apps/app-1/documents/docs/missing.md');++ expect(res.status).toBe(404);+ });++ it('rejects a non-markdown file, a path outside docs/, and traversal', async () => {+ const cases = [+ '/api/apps/app-1/documents/package.json',+ '/api/apps/app-1/documents/server/secret.md',+ '/api/apps/app-1/documents/docs/..%2F..%2Fetc%2Fpasswd.md',+ ];++ for (const path of cases) {+ const res = await request(app).get(path);+ expect(res.status, path).toBe(400);+ expect(res.body.code, path).toBe('INVALID_DOCUMENT');+ }+ });++ it('writes and commits a nested docs/ file', async () => {+ const res = await request(app)+ .put('/api/apps/app-1/documents/docs/decisions/2026-01-01-choice.md')+ .send({ content: '# Revised' });++ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ success: true, hash: 'abc1234', created: false });+ expect(git.stageFiles).toHaveBeenCalledWith(repoPath, ['docs/decisions/2026-01-01-choice.md']);+ expect(await readFile(join(repoPath, 'docs', 'decisions', '2026-01-01-choice.md'), 'utf-8')).toBe('# Revised');+ });++ it('refuses to write outside the browsable set', async () => {+ const res = await request(app)+ .put('/api/apps/app-1/documents/server/index.js')+ .send({ content: 'pwned' });++ expect(res.status).toBe(400);+ expect(git.stageFiles).not.toHaveBeenCalled();+ });+});