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([voice-code-agent-target-managed-app]): voice coding agent can target a managed app
[._.]/ Adam Eivy8aeff5562acd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..e3322e68aa--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,5 @@+# Unreleased++## Added++- **Voice coding agent can target a managed app.** When you dispatch a coding task by voice, you can now name a managed app ("fix the failing test in BookLoom") and the agent runs against that app's workspace instead of PortOS itself. The app name is fuzzy-matched, so "book loom", "BookLoom", and "bookloom" all resolve to the same app; if no app matches what you said, the agent refuses with a short list of valid names rather than silently running against PortOS.diff --git a/PLAN.md b/PLAN.mdindex 93025b14ff..bd93458a6c 100644--- a/PLAN.md+++ b/PLAN.md@@ -8,7 +8,6 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag- [ ] [apple-health-integration-live-sync] **Apple Health integration for MeatSpace.** iOS live sync (HealthKit Shortcut → `POST /api/meatspace/apple-health` endpoint) plus a bulk historical import path for an exported `export.xml`. Wire into existing MeatSpace tabs so steps / sleep / heart rate / VO2 max / resting HR show alongside the alcohol / blood / body / epigenetic tracks already shipped. GOALS.md flags this as a documented Secondary Goal ("Apple Health integration planned") but no implementation tracking existed until this entry. When this lands, also fold an Apple-Health-imported signal into the Capabilities page "Genome & Health" row (`server/lib/capabilityMap.js#genomeRow` + the route's `genome` fetch) so a health-only setup no longer reports "Not set up" purely because no genome is uploaded (codex review of `[codex5-onboarding-capability-map]`, 2026-05-24). _(Deferred 2026-05-25 from the batch-clear: multi-file feature with an iOS Shortcut component that needs a device to verify.)_- [ ] [triage-gemini-out-of-scope-findings] **Triage repo-wide findings gemini surfaced during PR #508 review (UNVERIFIED, out-of-scope from the voice PR).** A `/do:review` gemini pass reviewed the whole repo instead of the branch diff and flagged these pre-existing items in files PR #508 doesn't touch. Not applied to that PR (scope creep); several may be moot under the single-user/private-network trust model — verify before acting: (1) `server/routes/database.js:~236` — DB sync builds a `bash -c` string with `dumpFile` interpolated; consider `spawn` + piped stdin instead of shell string interpolation. (2) `server/services/apps.js:~304` — `updateAppTaskTypeOverride`/`bulkUpdateAppTaskTypeOverride` don't validate `taskType` against `SELF_IMPROVEMENT_TASK_TYPES`. (3) `server/routes/apps.js:~888` — `open-editor`/`open-claude` use `shell:false` for commands that are `.cmd` shims on Windows (would fail on Windows); needs a `needsShell` check + Windows metachar validation. (4) `server/lib/httpClient.js:~110` — `insecureFetch` does a bare `JSON.parse(buffer)` that can throw synchronously; wrap or reject. (5) `server/index.js` god-file (already noted in Deferred Architecture). Surfaced 2026-05-26.-- [ ] [voice-code-agent-target-managed-app] **Voice code-agent delegation can't target a managed app yet.** The `dispatch_code_agent` voice tool (`server/services/voice/tools.js`) creates a CoS user task with no `app` set, so the agent always runs against the PortOS repo (the CoS default workspace). Add an optional spoken target ("…in BookLoom") → resolve to an app id and pass `app` through to `addTask` (cos.js already persists `metadata.app`, and `agentLifecycle.js#registerAgent` already reads it). Needs a phrase→app resolver (fuzzy match against managed app names) and a guard for "app not found." Deferred from the initial build (2026-05-26) to keep v1 scoped to the self-repo case.- [ ] [voice-code-agent-status-query] **No mid-task voice status query for dispatched coding agents.** Once a task is dispatched via `dispatch_code_agent`, the user can only learn the outcome from the completion announcement — there's no "how's that coding task going?" tool. Add a `code_agent_status` voice tool that reads `data/cos/state.json` for running agents tagged `metadata.voiceDispatch` and reports phase/elapsed. Deferred from the initial build (2026-05-26); the completion announcement covers the common case.- [ ] [voice-code-agent-announce-pr-url] **Completion announcement can't speak the PR link.** `agent:completed` (cosAgents.js) fires BEFORE `cleanupAgentWorktree` creates the PR (agentLifecycle.js), so `formatAgentCompletionLine` (proactiveTriggers.js) only speaks success/failure + the task description, not the PR. To include "PR #512 is up," either (a) emit a later `agent:pr-opened` event from the cleanup path carrying `{ taskId, prUrl, voiceDispatch }` and announce on that instead, or (b) have the announcement defer until the agent record gains a `prUrl`. Deferred 2026-05-26 — a spoken GitHub URL is poor UX anyway and the user reviews the PR visually; the "done" announcement is enough for v1.- [ ] [patch-settings-slice-helper] **Add a `patchSettingsSlice(slicePath, partial)` helper in `client/src/services/`.** The settings PUT shallow-merges top-level keys, so every caller that updates a nested field (`imageGen.local.pythonPath`, `sharing.*`, `backup.*`, etc.) re-implements the same fetch-then-spread pattern. Current sites: `ImageGenTab.handleSave` (`client/src/components/settings/ImageGenTab.jsx:211`), `VideoGen.handleSavePythonPath`, `SharingTab`, `BackupTab`, `MortalLoomTab`, `Sharing.jsx`, `StoryboardPanel`, `NounsStage`, `ComicScriptStage` — 9+ sites. A `patchSettingsSlice('imageGen.local', { pythonPath })` helper would eliminate the slice-clobbering bug class. Surfaced by /simplify on 2026-05-28; deferred because it's a cross-cutting refactor of every settings consumer.diff --git a/server/lib/README.md b/server/lib/README.mdindex b732f093a8..a45ebcfd09 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -149,6 +149,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `appResolver.js` | Fuzzy-match a spoken/typed phrase to a managed app (`{ id, name }`). Tiered exact → prefix → substring, used by voice tools that target a specific app. || `capabilityMap.js` | Pure row builders for the Capability Map (per-integration status tiers + rollup); fed by `routes/capabilities.js`. || `civitai.js` | Civitai URL parsing + API client. || `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |diff --git a/server/lib/appResolver.js b/server/lib/appResolver.jsnew file mode 100644index 0000000000..1c830eb7f2--- /dev/null+++ b/server/lib/appResolver.js@@ -0,0 +1,48 @@+// Fuzzy match a spoken/typed phrase ("BookLoom", "book loom", "the bookloom+// app") to a managed app from `getActiveApps()`. Pure helper — caller fetches+// the apps list.+//+// Tiered match strategy mirrors `navManifest.resolveNavCommand`: exact →+// prefix → substring, biased to the longest candidate name on substring ties+// so "book loom" picks "BookLoom" over a stray "Book" app.+//+// Returns the matched app object (with `id`) or `null` when no candidate is+// close enough. Caller decides the not-found UX.++const normalize = (s) => (typeof s === 'string' ? s : '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '');++export function resolveAppByPhrase(phrase, apps) {+ const target = normalize(phrase);+ if (target.length < 2) return null;+ if (!Array.isArray(apps) || apps.length === 0) return null;++ const entries = apps+ .map((app) => ({ app, name: normalize(app?.name), id: normalize(app?.id) }))+ .filter((e) => e.name || e.id);+ if (entries.length === 0) return null;++ const pickLongest = (hits) => hits.reduce((a, b) => (b.name.length >= a.name.length ? b : a)).app;++ // Tier 1: exact id or normalized-name match.+ for (const e of entries) {+ if (e.name === target || e.id === target) return e.app;+ }+ // Tier 2: prefix overlap in either direction. Min 3 chars on the candidate+ // so a 2-letter id (e.g. "ai") doesn't greedily prefix-match every utterance.+ const prefixHits = entries.filter((e) =>+ (e.name.length >= 3 && (e.name.startsWith(target) || target.startsWith(e.name)))+ || (e.id.length >= 3 && (e.id.startsWith(target) || target.startsWith(e.id))));+ if (prefixHits.length) return pickLongest(prefixHits);++ // Tier 3: substring containment in either direction, min 3 chars on both+ // sides so "ax" doesn't match every app whose name contains "ax".+ if (target.length >= 3) {+ const substringHits = entries.filter((e) =>+ (e.name.length >= 3 && (e.name.includes(target) || target.includes(e.name)))+ || (e.id.length >= 3 && (e.id.includes(target) || target.includes(e.id))));+ if (substringHits.length) return pickLongest(substringHits);+ }+ return null;+}diff --git a/server/lib/appResolver.test.js b/server/lib/appResolver.test.jsnew file mode 100644index 0000000000..0d86518c75--- /dev/null+++ b/server/lib/appResolver.test.js@@ -0,0 +1,60 @@+import { describe, it, expect } from 'vitest';+import { resolveAppByPhrase } from './appResolver.js';++const APPS = [+ { id: 'bookloom-abc', name: 'BookLoom' },+ { id: 'portos-default', name: 'PortOS' },+ { id: 'finance-tracker-xyz', name: 'Finance Tracker' },+ { id: 'ai', name: 'AI' },+];++describe('resolveAppByPhrase', () => {+ it('returns null for empty / too-short / non-string input', () => {+ expect(resolveAppByPhrase('', APPS)).toBeNull();+ expect(resolveAppByPhrase(null, APPS)).toBeNull();+ expect(resolveAppByPhrase('a', APPS)).toBeNull();+ expect(resolveAppByPhrase(123, APPS)).toBeNull();+ });++ it('returns null when the apps list is empty or invalid', () => {+ expect(resolveAppByPhrase('BookLoom', [])).toBeNull();+ expect(resolveAppByPhrase('BookLoom', null)).toBeNull();+ });++ it('exact-matches the normalized app name', () => {+ expect(resolveAppByPhrase('BookLoom', APPS)?.id).toBe('bookloom-abc');+ expect(resolveAppByPhrase('bookloom', APPS)?.id).toBe('bookloom-abc');+ expect(resolveAppByPhrase('book loom', APPS)?.id).toBe('bookloom-abc');+ expect(resolveAppByPhrase('Book-Loom', APPS)?.id).toBe('bookloom-abc');+ });++ it('exact-matches the app id', () => {+ expect(resolveAppByPhrase('portos-default', APPS)?.id).toBe('portos-default');+ });++ it('matches multi-word names by prefix / contains', () => {+ expect(resolveAppByPhrase('finance', APPS)?.id).toBe('finance-tracker-xyz');+ expect(resolveAppByPhrase('finance tracker', APPS)?.id).toBe('finance-tracker-xyz');+ expect(resolveAppByPhrase('tracker', APPS)?.id).toBe('finance-tracker-xyz');+ });++ it('returns null when nothing matches', () => {+ expect(resolveAppByPhrase('totally unknown app', APPS)).toBeNull();+ });++ it('does not over-match short candidates by prefix', () => {+ // The "AI" app (2-letter name) must not gobble every utterance starting+ // with "ai" — guard kicks in because its normalized name length < 3.+ expect(resolveAppByPhrase('aim higher', APPS)).toBeNull();+ });++ it('picks the longest candidate on substring overlap', () => {+ const apps = [+ { id: 'book', name: 'Book' },+ { id: 'bookloom', name: 'BookLoom' },+ ];+ // "BookLoom" contains "Book" (so both qualify on substring), but we should+ // prefer the longer, more specific name.+ expect(resolveAppByPhrase('bookloom', apps)?.id).toBe('bookloom');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 87fd7a2749..86195c5f89 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -119,6 +119,7 @@ export * from './taskParser.js';export * from './curatedGenomeMarkers.js';// === Domain utilities ===+export * from './appResolver.js';export * from './capabilityMap.js';export * from './civitai.js';export * from './localLlmCatalog.js';diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex ba6e4f5dc9..b913fa02b8 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -1811,7 +1811,7 @@ const TOOLS = [{name: 'dispatch_code_agent',description:- 'Hand a software-engineering task to an autonomous coding agent that works in an isolated git worktree and opens a pull request for review. Use when the user asks you to write, fix, refactor, debug, or test CODE — e.g. "fix the failing test in X", "add a --dry-run flag to the backup script", "refactor the widget registry". Do NOT use for capturing notes/ideas (that is brain_capture) or for clicking/navigating the UI. The work runs in the background and the user is told when it finishes — do not wait for it. State the task in the user\'s own words with enough detail to act on it. The coding agent and model come from the user\'s configured default; never put a provider or model in this call.',+ 'Hand a software-engineering task to an autonomous coding agent that works in an isolated git worktree and opens a pull request for review. Use when the user asks you to write, fix, refactor, debug, or test CODE — e.g. "fix the failing test in X", "add a --dry-run flag to the backup script", "refactor the widget registry". Do NOT use for capturing notes/ideas (that is brain_capture) or for clicking/navigating the UI. The work runs in the background and the user is told when it finishes — do not wait for it. State the task in the user\'s own words with enough detail to act on it. When the user names a managed app to work in ("…in BookLoom", "fix the bug in the finance tracker"), pass that name as `app`; omit `app` for tasks on PortOS itself. The coding agent and model come from the user\'s configured default; never put a provider or model in this call.',parameters: {type: 'object',properties: {@@ -1819,14 +1819,19 @@ const TOOLS = [type: 'string',description: 'The coding task to perform, phrased as a clear, self-contained instruction (file/feature names, the desired outcome). The agent reads this verbatim as its prompt.',},+ app: {+ type: 'string',+ description: 'Optional managed-app target ("BookLoom", "finance tracker"). Server fuzzy-matches against the user\'s configured apps; omit to run against PortOS itself.',+ },},required: ['task'],},- execute: async ({ task } = {}) => {+ execute: async ({ task, app } = {}) => {const text = typeof task === 'string' ? task.trim() : '';if (!text) {return { ok: false, error: 'task is required', summary: "I didn't catch what you want the coding agent to do." };}+ const appPhrase = typeof app === 'string' ? app.trim() : '';// Backstop for the palette path — pipeline.js already strips this tool// from the LLM's spec list when codeAgent is disabled, but the command@@ -1837,6 +1842,31 @@ const TOOLS = [return { ok: false, error: 'code-agent disabled', summary: 'Coding-agent dispatch is off — turn it on under Settings, Voice, Coding agent.' };}+ // Optional spoken target: fuzzy-resolve "in BookLoom" to a managed-app+ // id so the spawner runs the agent in that app's workspace (cos.js+ // `metadata.app` → agentLifecycle prepareAgentWorkspace). Reject an+ // explicit-but-unknown target rather than silently falling through to+ // the PortOS workspace, so the user hears "I don't see that app."+ let resolvedAppId = null;+ let resolvedAppName = null;+ if (appPhrase) {+ const { getActiveApps } = await import('../apps.js');+ const { resolveAppByPhrase } = await import('../../lib/appResolver.js');+ const apps = await getActiveApps().catch(() => []);+ const match = resolveAppByPhrase(appPhrase, apps);+ if (!match) {+ const names = (apps || []).map((a) => a?.name).filter(Boolean);+ const hint = names.length ? ` Try one of: ${names.slice(0, 4).join(', ')}.` : '';+ return {+ ok: false,+ error: `unknown app "${appPhrase}"`,+ summary: `I don't see a managed app called ${appPhrase}.${hint}`,+ };+ }+ resolvedAppId = match.id;+ resolvedAppName = match.name || match.id;+ }+// Dynamic import: cos.js is a large module with its own import graph;// importing it lazily keeps tools.js load-time light and dodges any// cos → voice cycle.@@ -1884,6 +1914,7 @@ const TOOLS = [priority: 'HIGH',position: 'top',voiceDispatch: true,+ ...(resolvedAppId ? { app: resolvedAppId } : {}),// The promise of this tool (and the changelog / spoken copy) is// isolated work that opens a PR and never touches the user's working// tree. spawnAgentForTask only honors that when the task explicitly@@ -1908,19 +1939,22 @@ const TOOLS = [const running = isRunning();const stoppedNote = ' — but the Chief-of-Staff runner is stopped, so start it to run it';+ const appSuffix = resolvedAppName ? ` in ${resolvedAppName}` : '';+if (created?.duplicate) {return {ok: true,taskId: created.id,duplicate: true,- summary: `That coding task is already queued${running ? ', so I left it as is.' : `${stoppedNote}.`}`,+ app: resolvedAppId,+ summary: `That coding task${appSuffix} is already queued${running ? ', so I left it as is.' : `${stoppedNote}.`}`,};}const summary = running- ? "Queued a coding task — I'll let you know when it's done."- : `Queued the coding task${stoppedNote}.`;- return { ok: true, taskId: created?.id, running, summary };+ ? `Queued a coding task${appSuffix} — I'll let you know when it's done.`+ : `Queued the coding task${appSuffix}${stoppedNote}.`;+ return { ok: true, taskId: created?.id, running, app: resolvedAppId, summary };},},];diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex d42fd93555..0d424f5ea7 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -143,6 +143,16 @@ vi.mock('../cos.js', () => ({addTask: vi.fn(async (data) => ({ id: 'task-test', ...data })),isRunning: vi.fn(() => true),}));+// dispatch_code_agent fuzzy-resolves the optional `app` parameter against the+// user's configured managed apps; default to two apps so the resolve / not-+// found branches can be exercised.+const activeAppsRef = { value: [+ { id: 'bookloom-abc', name: 'BookLoom' },+ { id: 'portos-default', name: 'PortOS' },+] };+vi.mock('../apps.js', () => ({+ getActiveApps: vi.fn(async () => activeAppsRef.value),+}));// dispatch_code_agent resolves a code-capable provider when none is pinned.// Default the active provider to a code-capable (tui) one so the inherit path// is exercised; individual tests override for the API-default / substitution@@ -280,6 +290,33 @@ describe('dispatch_code_agent', () => {expect(r.ok).toBe(true);expect(r.summary).toMatch(/stopped/i);});++ it('resolves a spoken `app` to a managed-app id and threads it through addTask', async () => {+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: 'book loom' });+ expect(r.ok).toBe(true);+ expect(r.app).toBe('bookloom-abc');+ expect(r.summary).toMatch(/in BookLoom/);+ expect(mockedAddTask.mock.calls[0][0]).toMatchObject({ app: 'bookloom-abc' });+ });++ it('omits the `app` field on addTask when no target is spoken (PortOS-self)', async () => {+ await dispatchTool('dispatch_code_agent', { task: 'fix the test' });+ expect(mockedAddTask.mock.calls[0][0]).not.toHaveProperty('app');+ });++ it('errors when the spoken app is unknown — does NOT silently fall through to PortOS', async () => {+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: 'GhostApp' });+ expect(r.ok).toBe(false);+ expect(r.error).toMatch(/GhostApp/);+ expect(r.summary).toMatch(/BookLoom/); // suggestion list pulled from active apps+ expect(mockedAddTask).not.toHaveBeenCalled();+ });++ it('ignores an empty/whitespace `app` string (treats as omitted)', async () => {+ const r = await dispatchTool('dispatch_code_agent', { task: 'fix the test', app: ' ' });+ expect(r.ok).toBe(true);+ expect(mockedAddTask.mock.calls[0][0]).not.toHaveProperty('app');+ });});describe('code intent classification', () => {