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
fix: separate agent workspace lookup from JIRA prompt support
[._.]/ Adam Eivy269d9728ecee
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 0483e70045..1dc659fcb2 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -39,6 +39,12 @@ const reaches = (entry, target) => staticImportClosure(abs(entry)).files.has(abs// Each row: the entry that was narrowed, the module it must no longer// statically reach, and why the entry only ever needed a slice of it.const NARROWED = [+ ['services/agentAppWorkspace.js', 'services/promptRunner.js',+ 'resolves app records without AI-backed JIRA title generation'],+ ['services/agentAppWorkspace.js', 'services/jira.js',+ 'reads workspace metadata without ticket creation'],+ ['services/agentAppWorkspace.js', 'services/agentPromptBuilder.js',+ 'owns workspace resolution independently of prompt assembly'],['services/providerRuntimeInstaller.js', 'lib/harnessOutput.js','loads version and catalog parsers only when probing a harness'],['lib/db.js', 'lib/db/schema/index.js',@@ -71,6 +77,7 @@ describe('narrowed imports stay narrow (#6009)', () => {// Positive controls. Without these the negatives above would also pass if// `staticImportClosure` stopped resolving these files at all.it('still sees the modules the narrowed entries were pointed AT', () => {+ expect(reaches('services/agentAppWorkspace.js', 'lib/fileUtils.js')).toBe(true);expect(reaches('lib/pipelineValidation.js', 'lib/editorial/checkInfra/taxonomy.js')).toBe(true);expect(reaches('services/apps.js', 'lib/cosValidation.js')).toBe(true);expect(reaches('services/memoryEmbeddings.js', 'services/memoryConfig.js')).toBe(true);diff --git a/server/services/agentAppWorkspace.js b/server/services/agentAppWorkspace.jsnew file mode 100644index 0000000000..5871b32e3a--- /dev/null+++ b/server/services/agentAppWorkspace.js@@ -0,0 +1,74 @@+/**+ * Read-only managed-app resolution for CoS dispatch and workspace preparation.+ * Preserve legacy registry shapes without bootstrapping or rewriting the registry.+ */++import { join } from 'path';+import { PATHS, readJSONFile, expandHome } from '../lib/fileUtils.js';++const ROOT_DIR = PATHS.root;++/**+ * Get the workspace path for an app, or `null` when it can't be resolved.+ *+ * This used to substitute the PortOS repo root for every failure — registry+ * missing, app not found, app carrying no `repoPath` — which made an+ * unresolvable app indistinguishable from a working one: the agent quietly+ * wrote its files into the PortOS checkout and nothing said otherwise+ * (issue #3180). A downstream existence check can't recover that case either,+ * because the substituted root is a real directory.+ *+ * So this returns an explicit `null` sentinel and lets each caller decide+ * whether "no workspace" is legal for it (per the sentinel-and-validate rule in+ * AGENTS.md — absent must not collapse into a valid-looking value). The reason+ * is logged here, where it's known.+ *+ * @returns {Promise<string|null>} the app's repoPath, or null if unresolvable+ */+export async function getAppWorkspace(appName) {+ const appsFile = join(ROOT_DIR, 'data/apps.json');+ const unresolved = (why) => { console.warn(`⚠️ ${why} — no agent workspace resolved`); return null; };++ const data = await readJSONFile(appsFile, null);+ if (!data) return unresolved(`No apps registry at ${appsFile}`);++ // Handle both object format { apps: { id: {...} } } and array format [...]+ const apps = data.apps || data;++ const app = Array.isArray(apps)+ ? apps.find(a => a.name === appName || a.id === appName)+ // Object format - keys are app IDs+ : (apps[appName] || Object.values(apps).find(a => a.name === appName));++ if (!app) return unresolved(`App '${appName}' not found in apps registry`);+ if (!app.repoPath) return unresolved(`App '${appName}' has no repoPath`);+ // Expand here, not just at the spawn boundary. Callers do more with this than+ // spawn into it: agentLifecycle persists it as an agent's `sourceWorkspace`,+ // and the worktree cleanup/merge paths later hand that value to a child+ // process as its cwd. Node never shell-expands `~`, so returning the raw+ // tilde form would let a task start (the spawn path expands) and then strand+ // its worktree and branch when cleanup runs against a path that doesn't exist.+ return expandHome(app.repoPath);+}++/**+ * Get full app data for a task (including jira config).+ * Returns the app object or null if not found.+ */+export async function getAppDataForTask(task) {+ const appName = task?.metadata?.app;+ if (!appName) return null;++ const appsFile = join(ROOT_DIR, 'data/apps.json');+ const data = await readJSONFile(appsFile, null);+ if (!data) return null;++ const apps = data.apps || data;++ if (Array.isArray(apps)) {+ return apps.find(a => a.name === appName || a.id === appName) || null;+ }++ return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;+}+diff --git a/server/services/agentAppWorkspace.test.js b/server/services/agentAppWorkspace.test.jsnew file mode 100644index 0000000000..a3205bd9a1--- /dev/null+++ b/server/services/agentAppWorkspace.test.js@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { join } from 'path';+import { homedir } from 'os';++vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ readJSONFile: vi.fn(),+}));++import { readJSONFile } from '../lib/fileUtils.js';+import { getAppDataForTask, getAppWorkspace } from './agentAppWorkspace.js';++beforeEach(() => vi.resetAllMocks());++// A moved lookup must still resolve persisted legacy registries and refuse to+// substitute the PortOS checkout when a task's app cannot be resolved (#3180).+describe('read-only agent app resolution', () => {+ it.each([+ app => ({ apps: { 'example-app': app } }),+ app => ({ 'example-app': app }),+ app => [app],+ ])('resolves IDs and names in a supported registry shape', async (registry) => {+ const app = { id: 'example-app', name: 'Example App', repoPath: '~/example-repo', jira: { enabled: false } };+ readJSONFile.mockResolvedValue(registry(app));+ for (const name of ['example-app', 'Example App']) {+ expect(await getAppWorkspace(name)).toBe(join(homedir(), 'example-repo'));+ expect(await getAppDataForTask({ metadata: { app: name } })).toEqual(app);+ }+ });++ it('keeps missing registry, unknown app and absent repo paths unresolved', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ for (const registry of [null, { apps: {} }, { apps: { missing: { name: 'Missing' } } }]) {+ readJSONFile.mockResolvedValue(registry);+ expect(await getAppWorkspace('missing')).toBeNull();+ }+ readJSONFile.mockResolvedValue(null);+ expect(await getAppDataForTask({ metadata: { app: 'missing' } })).toBeNull();+ readJSONFile.mockClear();+ expect(await getAppDataForTask({})).toBeNull();+ expect(readJSONFile).not.toHaveBeenCalled();+ vi.restoreAllMocks();+ });+});diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 608f176550..4e5662a5ce 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -40,7 +40,8 @@ import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratcimport { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';import { resolveTaskForkHead } from '../lib/forkHead.js';-import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';+import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';+import { createJiraTicketForTask } from './promptSections/appContext.js';import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';import { isNonCommittingCoordinatorTask } from './taskTypeHooks.js';diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex c8a44f481a..164ddad8df 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -40,9 +40,11 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({findAdoptableWorktreeForBranch: vi.fn().mockResolvedValue(null),mergeBaseIntoFeatureWorktree: vi.fn(),}));-vi.mock('./agentPromptBuilder.js', () => ({+vi.mock('./agentAppWorkspace.js', () => ({getAppWorkspace: vi.fn().mockResolvedValue('/repos/app-x'),getAppDataForTask: vi.fn().mockResolvedValue(null),+}));+vi.mock('./promptSections/appContext.js', () => ({createJiraTicketForTask: vi.fn(),}));vi.mock('../lib/fileUtils.js', async (importOriginal) => {@@ -58,7 +60,7 @@ import { updateTask, getAgents } from './cos.js';import { ensureLatest } from './git.js';import { execGit } from '../lib/execGit.js';import { detectConflicts } from './taskConflict.js';-import { getAppWorkspace } from './agentPromptBuilder.js';+import { getAppWorkspace } from './agentAppWorkspace.js';import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch } from './worktreeManager.js';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';diff --git a/server/services/promptSections/README.md b/server/services/promptSections/README.mdindex 4c1e6b6c98..069f100ce2 100644--- a/server/services/promptSections/README.md+++ b/server/services/promptSections/README.md@@ -4,7 +4,7 @@ Leaf modules used by `agentPromptBuilder.js`. The builder remains the public fac| Module | Responsibility || --- | --- |-| `appContext.js` | Managed-app workspace lookup and JIRA ticket helpers. |+| `appContext.js` | JIRA ticket helpers; compatibility exports for read-only app lookup in `../agentAppWorkspace.js`. || `completion.js` | Worktree, completion-workflow, and sentinel sections. || `constants.js` | Constants shared across full and light prompt paths. || `forge.js` | Forge CLI selection for generated workflow text. |@@ -14,3 +14,10 @@ Leaf modules used by `agentPromptBuilder.js`. The builder remains the public fac| `reviewLifecycle.js` | Reviewer, CI-gate, and merge sections. || `slashdo.js` | Slashdo invocation and procedure expansion. || `taskContext.js` | Task, attachment, split-context, and compaction sections. |++CoS dispatch/workspace code should import read-only app resolution from+`../agentAppWorkspace.js`; it owns legacy registry-shape support, name/ID lookup,+null-on-unresolved semantics, and home expansion without registry writes or AI+dependencies. `apps.js#getAppById` is not interchangeable: its registry loader+reconciles persisted defaults and its lookup is ID-only. Keep ticket generation+here; preserve the builder and app-context exports for existing callers.diff --git a/server/services/promptSections/appContext.js b/server/services/promptSections/appContext.jsindex 94035a40a4..f46de6f450 100644--- a/server/services/promptSections/appContext.js+++ b/server/services/promptSections/appContext.js@@ -1,79 +1,13 @@/**- * Managed-app workspace lookup and JIRA ticket prompt support.+ * JIRA ticket prompt support. Workspace exports remain for compatibility.*/-import { join } from 'path';-import { PATHS, readJSONFile, expandHome } from '../../lib/fileUtils.js';import { runPromptThroughProvider } from '../promptRunner.js';import { getActiveProvider } from '../providers.js';import * as jiraService from '../jira.js';import { emitLog } from '../cosEvents.js';-const ROOT_DIR = PATHS.root;--/**- * Get the workspace path for an app, or `null` when it can't be resolved.- *- * This used to substitute the PortOS repo root for every failure — registry- * missing, app not found, app carrying no `repoPath` — which made an- * unresolvable app indistinguishable from a working one: the agent quietly- * wrote its files into the PortOS checkout and nothing said otherwise- * (issue #3180). A downstream existence check can't recover that case either,- * because the substituted root is a real directory.- *- * So this returns an explicit `null` sentinel and lets each caller decide- * whether "no workspace" is legal for it (per the sentinel-and-validate rule in- * AGENTS.md — absent must not collapse into a valid-looking value). The reason- * is logged here, where it's known.- *- * @returns {Promise<string|null>} the app's repoPath, or null if unresolvable- */-export async function getAppWorkspace(appName) {- const appsFile = join(ROOT_DIR, 'data/apps.json');- const unresolved = (why) => { console.warn(`⚠️ ${why} — no agent workspace resolved`); return null; };-- const data = await readJSONFile(appsFile, null);- if (!data) return unresolved(`No apps registry at ${appsFile}`);-- // Handle both object format { apps: { id: {...} } } and array format [...]- const apps = data.apps || data;-- const app = Array.isArray(apps)- ? apps.find(a => a.name === appName || a.id === appName)- // Object format - keys are app IDs- : (apps[appName] || Object.values(apps).find(a => a.name === appName));-- if (!app) return unresolved(`App '${appName}' not found in apps registry`);- if (!app.repoPath) return unresolved(`App '${appName}' has no repoPath`);- // Expand here, not just at the spawn boundary. Callers do more with this than- // spawn into it: agentLifecycle persists it as an agent's `sourceWorkspace`,- // and the worktree cleanup/merge paths later hand that value to a child- // process as its cwd. Node never shell-expands `~`, so returning the raw- // tilde form would let a task start (the spawn path expands) and then strand- // its worktree and branch when cleanup runs against a path that doesn't exist.- return expandHome(app.repoPath);-}--/**- * Get full app data for a task (including jira config).- * Returns the app object or null if not found.- */-export async function getAppDataForTask(task) {- const appName = task?.metadata?.app;- if (!appName) return null;-- const appsFile = join(ROOT_DIR, 'data/apps.json');- const data = await readJSONFile(appsFile, null);- if (!data) return null;-- const apps = data.apps || data;-- if (Array.isArray(apps)) {- return apps.find(a => a.name === appName || a.id === appName) || null;- }-- return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;-}+export { getAppWorkspace, getAppDataForTask } from '../agentAppWorkspace.js';/*** Generate a concise JIRA ticket title from a task description using AI.