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: splice nested CLAUDE.md files into API-provider agent prompts (#3866)
[._.]/ Adam Eivyfd170abb5361
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ff580e60c9..272cc89d7e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -39,3 +39,4 @@- The theme switcher, the media collection picker, and the Shell photo composer now dismiss through the shared click-outside hook instead of three private copies of the same two-ref check, so the rule that a portaled panel counts as "inside" its own trigger lives in one place. Escape still closes each of them.- Collapsible section headers in the canon cards, the character detail editor, and the digital-twin interview analysis card now announce their open/closed state to a screen reader. They were five separate hand-rolled copies of the same header, none of which reported that state, and all five now share one primitive so a layout fix lands in one place instead of three.- The memory list and timeline endpoints now validate their query strings against the Zod schemas that were written for them. Both handlers had been hand-parsing `req.query`, so the declared bounds went unenforced: an unknown memory type, a garbled `limit`, or a nonsense date range was quietly accepted and passed to the database. Both schemas now also accept the comma-separated, string-valued form a query string actually arrives in, and the list `limit` ceiling is 500 — the bound the route has always enforced in practice — rather than the 100 its schema claimed. The timeline endpoint also finally honours an `appId` filter, which both of its backends have always supported but the hand-written parsing never passed along.+- Agents run on an API provider (LM Studio, raw OpenAI/Anthropic — anything with no native filesystem tools) now receive the per-directory `CLAUDE.md` files too, not just the global and repo-root ones. Those agents read nothing off disk on their own, so a convention that lived in `server/CLAUDE.md` or `client/src/CLAUDE.md` reached them as a pointer with no contents — which is how relocating a backup rsync-exclude rule out of the root file silently removed a data-loss guard from that whole class of agent. Nested files are now discovered under the workspace and spliced in after the root one, each labeled with its repo-relative path, bounded to 10 files and 5 levels deep and skipping vendored, generated, and runtime trees.\ No newline at end of filediff --git a/CLAUDE.md b/CLAUDE.mdindex b6888a04e6..fab142e11d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -77,7 +77,7 @@ Client- and server-specific conventions live in nested memory files that load wh- `server/CLAUDE.md` — schema parity, write serialization, peer fan-out in tests, prompt-template migrations- `server/lib/aiToolkit/CLAUDE.md` — the override-consistency contract for the vendored provider/runner/prompt toolkit (self-contained: no imports out to other PortOS modules). PortOS overrides `executeCliRun`/`stopRun`/`isRunActive` and mirrors time-based provider-status recovery on read — read it before editing the runner or provider config.-**Safety-class rules stay in THIS file, even when they're subtree-specific.** Nested `CLAUDE.md` files load on demand in Claude Code, but `getClaudeMdContext()` in `server/services/agentPromptBuilder.js` splices only `~/.claude/CLAUDE.md` and the **workspace-root** `CLAUDE.md` into the prompts PortOS builds for its own API-provider agents — it never walks nested ones. So a rule guarding data loss, a destructive action, privacy, or spend must live here regardless of which subtree it governs (that is why the backup-exclude anchoring rule above sits in root rather than `server/CLAUDE.md`). Relocating a *convention* to a nested file is fine; relocating a *safety rule* silently removes it from an entire class of agent.+**Nested files reach API-provider agents too — but the walk is bounded.** Nested `CLAUDE.md` files load on demand in Claude Code, and `getClaudeMdContext()` in `server/services/agentPromptBuilder.js` splices them into the prompts PortOS builds for its own API-provider agents as well (`~/.claude/CLAUDE.md`, then the workspace-root file, then every nested one as its own labeled section). The walk is capped at depth 5 / 10 files and skips dot-dirs, `node_modules/`, `data/`, build output, and `lib/slashdo/`. Two consequences: **a rule that must reach every agent has to sit inside that budget** — if the repo ever exceeds 10 nested files, the overflow is silently dropped, so raise the cap in the same change rather than assuming coverage; and **the root file is the only guaranteed-first slot**, so a rule guarding data loss, a destructive action, privacy, or spend still belongs here when it must outrank a subtree convention (that is why the backup-exclude anchoring rule above sits in root rather than `server/CLAUDE.md`).### Command Palette & Voice Nav — shared backbonediff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 7e1b95f382..c53f5aed16 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -7,7 +7,7 @@*/import { join, basename } from 'path';-import { stat } from 'fs/promises';+import { readdir, stat } from 'fs/promises';import { homedir } from 'os';import { getMemorySection } from './memoryRetriever.js';import { getDigitalTwinForPrompt } from './digital-twin.js';@@ -113,9 +113,76 @@ export async function loadSkillTemplate(skillName) {return content;}+// Nested-CLAUDE.md discovery bounds (#3866). On-demand nested memory files are a+// Claude Code feature — an API-provider agent reads nothing natively, so PortOS+// has to splice them in itself or a subtree rule (including a data-loss guard)+// never reaches that class of agent. The walk is bounded on three axes so a repo+// that grows nested files can't silently balloon every agent prompt or turn one+// prompt build into a full-tree crawl.+const NESTED_CLAUDE_MD_MAX_DEPTH = 5;+const NESTED_CLAUDE_MD_MAX_FILES = 10;+const NESTED_CLAUDE_MD_MAX_DIRS = 2000;+// Dot-directories are skipped wholesale (covers `.git`), so these are the+// non-dot trees that are either vendored, generated, or runtime state.+const NESTED_CLAUDE_MD_SKIP_DIRS = new Set([+ 'node_modules', 'data', 'data.reference', 'dist', 'build', 'coverage',+ 'out', 'venv', '__pycache__',+]);+// Workspace-relative paths skipped by exact match — `lib/slashdo` is a git+// submodule carrying its own CLAUDE.md that is not this project's instructions.+const NESTED_CLAUDE_MD_SKIP_PATHS = new Set(['lib/slashdo']);++/**+ * Collect workspace-relative paths of nested `CLAUDE.md` files (the root one is+ * excluded — its caller reads it separately and must keep it first). Depth-first+ * in lexicographic order, so the result is deterministic and prompt caching stays+ * stable across builds.+ * @param {string} workspaceDir+ * @returns {Promise<string[]>} repo-relative paths, e.g. `['server/CLAUDE.md']`+ */+async function findNestedClaudeMdFiles(workspaceDir) {+ const found = [];+ let dirsVisited = 0;++ const walk = async (dir, relDir, depth) => {+ if (found.length >= NESTED_CLAUDE_MD_MAX_FILES) return;+ if (depth > NESTED_CLAUDE_MD_MAX_DEPTH) return;+ if (dirsVisited >= NESTED_CLAUDE_MD_MAX_DIRS) return;+ dirsVisited += 1;++ const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);+ if (!entries) return;+ const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));++ const subdirs = [];+ for (const entry of sorted) {+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ if (entry.name.startsWith('.')) continue;+ if (NESTED_CLAUDE_MD_SKIP_DIRS.has(entry.name)) continue;+ if (NESTED_CLAUDE_MD_SKIP_PATHS.has(rel)) continue;+ subdirs.push({ path: join(dir, entry.name), rel });+ } else if (entry.name === 'CLAUDE.md' && relDir && entry.isFile()) {+ found.push(rel);+ if (found.length >= NESTED_CLAUDE_MD_MAX_FILES) return;+ }+ }++ for (const sub of subdirs) {+ if (found.length >= NESTED_CLAUDE_MD_MAX_FILES) return;+ await walk(sub.path, sub.rel, depth + 1);+ }+ };++ await walk(workspaceDir, '', 0);+ return found;+}+/*** Read CLAUDE.md files for agent context.- * Reads both global (~/.claude/CLAUDE.md) and project-specific (./CLAUDE.md).+ * Reads the global (`~/.claude/CLAUDE.md`), the workspace-root `CLAUDE.md`, and+ * every nested `CLAUDE.md` under the workspace (#3866) — nested last, each as its+ * own labeled section, so precedence still reads root-then-specific.*/export async function getClaudeMdContext(workspaceDir) {const contexts = [];@@ -134,6 +201,15 @@ export async function getClaudeMdContext(workspaceDir) {contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent.trim() });}+ // Nested per-directory instructions, appended after the root file.+ for (const rel of await findNestedClaudeMdFiles(workspaceDir)) {+ const nestedPath = join(workspaceDir, rel);+ const nestedContent = await tryReadFile(nestedPath);+ if (nestedContent?.trim()) {+ contexts.push({ type: `Project Instructions (${rel})`, path: nestedPath, content: nestedContent.trim() });+ }+ }+if (contexts.length === 0) {return null;}diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 7d202c5c69..4f9f0cb26a 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -2338,3 +2338,96 @@ describe('getAppWorkspace — tilde expansion (#3180)', () => {expect(await getAppWorkspace('abs-app')).toBe('/srv/repos/abs-app');});});++// #3866 — getClaudeMdContext used to splice only the global + workspace-root+// CLAUDE.md, so a subtree rule (including a data-loss guard) never reached an+// API-provider agent. These pin the nested walk and its bounds.+describe('getClaudeMdContext — nested CLAUDE.md discovery (#3866)', () => {+ let workspace;++ const writeClaudeMd = (relDir, body) => {+ const dir = relDir ? join(workspace, relDir) : workspace;+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'CLAUDE.md'), body);+ };++ beforeAll(() => {+ workspace = mkdtempSync(join(process.env.TMPDIR || '/tmp', 'portos-nested-claudemd-'));+ writeClaudeMd('', '# Root rules\nAnchor every backup exclude.');+ writeClaudeMd('server', '# Server rules\nSchema parity when adding fields.');+ writeClaudeMd('client/src/components/dashboard', '# Dashboard rules\nRegister the widget.');+ // Ignored trees: each carries a CLAUDE.md that must NOT be spliced.+ writeClaudeMd('node_modules/some-dep', '# Vendored dep rules');+ writeClaudeMd('data/cos/worktrees/claim-issue-1', '# Runtime worktree rules');+ writeClaudeMd('lib/slashdo', '# Submodule rules');+ writeClaudeMd('.hidden', '# Dot dir rules');+ // Past the depth cap (depth 6): a/b/c/d/e/f/CLAUDE.md.+ writeClaudeMd('a/b/c/d/e/f', '# Too deep rules');+ });++ afterAll(() => {+ rmSync(workspace, { recursive: true, force: true });+ });++ it('splices nested files after the root one, each labeled with its repo-relative path', async () => {+ const section = await getClaudeMdContext(workspace);++ expect(section).toContain('### Project Instructions\n');+ expect(section).toContain('Anchor every backup exclude.');+ // The whole point of the issue: subtree content reaches the prompt.+ expect(section).toContain('### Project Instructions (server/CLAUDE.md)');+ expect(section).toContain('Schema parity when adding fields.');+ expect(section).toContain('### Project Instructions (client/src/components/dashboard/CLAUDE.md)');+ expect(section).toContain('Register the widget.');++ // Root stays first so precedence still reads root-then-specific, and the+ // nested pair is ordered lexicographically by path (client before server)+ // so prompt caching stays stable across builds.+ const rootAt = section.indexOf('Anchor every backup exclude.');+ const dashboardAt = section.indexOf('Register the widget.');+ const serverAt = section.indexOf('Schema parity when adding fields.');+ expect(rootAt).toBeLessThan(dashboardAt);+ expect(dashboardAt).toBeLessThan(serverAt);+ });++ it('skips vendored, runtime, submodule, dot, and over-depth trees', async () => {+ const section = await getClaudeMdContext(workspace);++ expect(section).not.toContain('Vendored dep rules');+ expect(section).not.toContain('Runtime worktree rules');+ expect(section).not.toContain('Submodule rules');+ expect(section).not.toContain('Dot dir rules');+ expect(section).not.toContain('Too deep rules');+ });++ it('caps the number of nested files spliced', async () => {+ const capped = mkdtempSync(join(process.env.TMPDIR || '/tmp', 'portos-nested-claudemd-cap-'));+ mkdirSync(capped, { recursive: true });+ writeFileSync(join(capped, 'CLAUDE.md'), '# Root of capped workspace');+ // 12 nested files > the 10-file cap. Zero-padded so lexicographic order+ // matches numeric order and the assertions below are unambiguous.+ for (let i = 1; i <= 12; i++) {+ const dir = join(capped, `pkg-${String(i).padStart(2, '0')}`);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'CLAUDE.md'), `# Nested rule ${String(i).padStart(2, '0')}`);+ }++ const section = await getClaudeMdContext(capped);+ const spliced = section.match(/### Project Instructions \(/g) || [];+ expect(spliced).toHaveLength(10);+ // Non-vacuous: the survivors are the first 10 by path, and the overflow is+ // dropped rather than truncated mid-file.+ expect(section).toContain('# Nested rule 10');+ expect(section).not.toContain('# Nested rule 11');+ expect(section).not.toContain('# Nested rule 12');++ rmSync(capped, { recursive: true, force: true });+ });++ it('returns null for a workspace with no CLAUDE.md at any level', async () => {+ const empty = mkdtempSync(join(process.env.TMPDIR || '/tmp', 'portos-nested-claudemd-empty-'));+ mkdirSync(join(empty, 'sub'), { recursive: true });+ expect(await getClaudeMdContext(empty)).toBeNull();+ rmSync(empty, { recursive: true, force: true });+ });+});