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: remove dead cos-runner /run devtools endpoint (Windows spawn ENOENT) (#2256)
Adam Eivy5cfd58047507
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9b3525df44..0eb3bb2783 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -127,6 +127,8 @@## Internal+- **[issue-2256] Removed the dead cos-runner `/run` devtools endpoint (latent Windows ENOENT bug).** The CoS runner's `POST /run` devtools path spawned a bare command under `shell:false` with the prompt passed as an argv — the same Windows `spawn ENOENT` bug the CoS agent path had (#2243), but no code called it: the live "Run Prompt" flow goes through `server/services/runner.js` (already fixed), and `executeCliRunViaRunner` + the `/runs`, `/runs/:id/output`, `/runs/:id/active`, `/runs/:id/stop` sibling endpoints and their client wrappers (`getActiveRunsFromRunner`, `isRunActiveInRunner`, `getRunOutputFromRunner`, `stopRunViaRunner`) were referenced only by their own tests. Rather than refactor dead code to be Windows-safe (a prompt-via-stdin rewrite to dodge the ~8191-char `cmd.exe /c` command-line limit), the whole devtools-run cluster is removed — the endpoint, its in-memory `activeRuns` map + `ensureRunsDir` helper, the `run:data`/`run:complete`/`run:error` socket forwarders, and the now-orphaned client functions and their tests. The main server and cos-runner sidecar ship in one repo and deploy together, so there's no cross-install compatibility concern. (`server/cos-runner/index.js`, `server/services/cosRunnerClient.js`, `server/services/cosRunnerClient.test.js`)+- **[issue-2249] The `issue-reconcile` zombie-scan is now forge-aware — it heals stranded issues on GitLab (`glab`) as well as GitHub (`gh`).** The v1 deterministic scan resolved the repo via `getOriginInfo().isGithub` and queried `gh` only, so enabling `issue-reconcile` on a GitLab-tracked app was a silent no-op. `server/services/issueReconcile.js` now resolves the forge from the app's git `origin` host inside `reconcile()` (github.* → GitHub, gitlab.* → GitLab, anything else → skip/park) and delegates to a per-forge state gatherer. Both gatherers normalize into ONE common issue shape (`{ number, title, url, labels, assignees }`) + change shape (`{ number, headRefName, body, url }`), so the pure classifier (`classifyIssue`), the boundary-safe ref matchers, and the `zombieSignature` convergence guard stay shared and unit-testable with zero forge branching — GitLab maps `iid`→number, MR `source_branch`→head ref (carries `claim/issue-<iid>`), MR `description`→body (carries `Refs #<iid>`). It remains a SINGLE task type (not three): the coordinator prompt is shared and simply gets the resolved forge + the matching `gh`/`glab` command table injected via `{zombieIssues}` (prompt bumped to v2, v1 preserved in `PREVIOUS_DEFAULT_PROMPTS` per the cross-install upgrade contract). A cwd-aware `glab` exec helper was added at `server/services/gitlab.js` (mirrors `execGh`). The JIRA sibling — a status-based "In Review with remaining scope" analog healed through the PortOS JIRA API rather than a forge CLI — is deferred to a follow-up (`Refs #2249`). (`server/services/issueReconcile.js`, `server/services/gitlab.js`, `server/services/cosTaskGenerator.js`, `server/services/taskPromptDefaults/`)- **[issue-2183] Creative Tool Registry + gated dispatch (CDO Phase 1).** Foundation for the Creative Director orchestrator (epic #2182): a single registry (`server/services/creative/toolRegistry.js` + per-domain modules under `creative/tools/`) of creative-suite tools an orchestrating agent can call — universe, story builder, writers room, pipeline, media, catalog — each a thin conductor wrapper over an existing service entry point (`createUniverse`, `generateStep`, `startSeriesAutopilot`, `enqueueJob`, …), never a re-implementation. All orchestrator calls flow through one governed chokepoint, `dispatchCreativeTool(name, args, ctx)`, which validates args (Zod), enforces a new `creative` autonomy mode, charges the daily action budget for `llm`/`render` tools, and appends a `{tool, argsDigest, outcome, timing}` entry to the calling project's run ledger. The `creative` autonomy domain (`server/lib/domainAutonomy.js` `getCreativeAutonomyMode`) is kept separate from the four core domains and defaults to mirror the `cos` mode, so existing autopilot users get consistent behavior with no migration, while an explicit `domainAutonomy.creative` value can override it later. Direct user actions through the existing routes are unchanged — the gate lives only on the orchestrator path. No user-facing surface yet; the directive composer and plan board arrive in later CDO phases.diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 3aa0baaec7..f6ea2639e7 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -46,11 +46,10 @@ const SHUTDOWN_DRAIN_MS = 5000; // SIGTERM drain window before closing the// Path + listen constants. These lived adjacent to the command allowlist before// it was extracted to ./allowedCommands.js; they must stay here — they're-// referenced throughout (RUNS_DIR/AGENTS_DIR/ROOT_DIR for spawn cwd + dirs, and+// referenced throughout (AGENTS_DIR/ROOT_DIR for spawn cwd + dirs, and// server.listen(PORT, HOST)) and dropping them crashes the runner on boot.const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;-const RUNS_DIR = PATHS.runs;const PORT = process.env.PORT || PORTS.COS;const HOST = process.env.HOST || '127.0.0.1';@@ -58,9 +57,6 @@ const HOST = process.env.HOST || '127.0.0.1';// Active agent processes (in memory)const activeAgents = new Map();-// Active devtools runs (in memory)-const activeRuns = new Map();-// Express app setupconst app = express();app.use(express.json({ limit: '10mb' }));@@ -78,15 +74,6 @@ function emitToServer(event, data) {console.log(`📡 Emitted ${event}`);}-/**- * Ensure runs directory exists- */-async function ensureRunsDir() {- if (!existsSync(RUNS_DIR)) {- await ensureDir(RUNS_DIR);- }-}-/*** Health check endpoint*/@@ -94,7 +81,6 @@ app.get('/health', (req, res) => {res.json({status: 'ok',activeAgents: activeAgents.size,- activeRuns: activeRuns.size,uptime: process.uptime()});});@@ -575,211 +561,6 @@ app.get('/agents/:agentId/output', (req, res) => {res.json({ agentId, output: agent.outputBuffer });});-// ============================================-// DEVTOOLS RUNS - CLI execution for devtools-// ============================================--/**- * Execute a CLI run (devtools runner)- */-app.post('/run', async (req, res) => {- const {- runId,- command,- args = [],- prompt,- workspacePath,- envVars = {},- timeout- } = req.body;-- if (!runId || !command || !prompt) {- return res.status(400).json({ error: 'Missing required fields: runId, command, prompt' });- }-- await ensureRunsDir();-- console.log(`🔧 Starting devtools run ${runId}: ${command} ${args.join(' ')}`);-- // Build command args - add prompt at the end- const spawnArgs = [...args, prompt];-- // Ensure workspacePath is valid- const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;-- // Spawn the CLI process- const childProcess = spawn(command, spawnArgs, {- cwd,- shell: false,- stdio: ['pipe', 'pipe', 'pipe'],- env: (() => { const e = { ...process.env, ...envVars }; delete e.CLAUDECODE; return e; })(),- windowsHide: true- });-- const startTime = Date.now();-- // Store in memory- activeRuns.set(runId, {- process: childProcess,- pid: childProcess.pid,- startedAt: startTime,- outputBuffer: ''- });-- // Handle stdout- childProcess.stdout.on('data', (data) => {- const text = data.toString();- const run = activeRuns.get(runId);- if (run) {- run.outputBuffer += text;- }- emitToServer('run:data', { runId, text });- });-- // Handle stderr- childProcess.stderr.on('data', (data) => {- const text = data.toString();- const run = activeRuns.get(runId);- if (run) {- run.outputBuffer += text;- }- emitToServer('run:data', { runId, text });- });-- // Handle errors- childProcess.on('error', (err) => {- console.error(`❌ Run ${runId} spawn error: ${err.message}`);- emitToServer('run:error', { runId, error: err.message });- activeRuns.delete(runId);- });-- // Handle process exit- childProcess.on('close', async (code) => {- try {- const run = activeRuns.get(runId);- const duration = Date.now() - startTime;- const output = run?.outputBuffer || '';-- console.log(`${code === 0 ? '✅' : '❌'} Run ${runId} exited with code ${code} (${duration}ms)`);-- // Save output to run directory- const runDir = join(RUNS_DIR, runId);- if (!existsSync(runDir)) {- await ensureDir(runDir);- }- await writeFile(join(runDir, 'output.txt'), output).catch(err => console.error(`❌ Run ${runId} failed to persist output.txt: ${err.message}`));-- // Persist completion status to disk BEFORE emitting event- // This ensures recovery is possible even if the socket event is lost- const metadataPath = join(runDir, 'metadata.json');- const existingMetadata = JSON.parse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));- const updatedMetadata = {- ...existingMetadata,- endTime: new Date().toISOString(),- exitCode: code,- success: code === 0,- duration,- outputSize: Buffer.byteLength(output)- };- await writeFile(metadataPath, JSON.stringify(updatedMetadata, null, 2)).catch(err => console.error(`❌ Run ${runId} failed to persist completion metadata: ${err.message}`));-- // Emit completion event- emitToServer('run:complete', {- runId,- exitCode: code,- success: code === 0,- duration,- outputLength: output.length- });-- activeRuns.delete(runId);- } catch (err) {- console.error(`❌ Run ${runId} close handler error: ${err.message}`);- activeRuns.delete(runId);- }- });-- // Set timeout if specified- if (timeout) {- setTimeout(() => {- if (activeRuns.has(runId)) {- console.log(`⏰ Run ${runId} timed out after ${timeout}ms`);- childProcess.kill('SIGTERM');- }- }, timeout);- }-- res.json({- success: true,- runId,- pid: childProcess.pid- });-});--/**- * Get list of active runs- */-app.get('/runs', (req, res) => {- const runs = [];- for (const [runId, run] of activeRuns) {- runs.push({- id: runId,- pid: run.pid,- startedAt: run.startedAt,- runningTime: Date.now() - run.startedAt- });- }- res.json(runs);-});--/**- * Get run output- */-app.get('/runs/:runId/output', (req, res) => {- const { runId } = req.params;- const run = activeRuns.get(runId);-- if (!run) {- return res.status(404).json({ error: 'Run not found or not active' });- }-- res.json({ runId, output: run.outputBuffer });-});--/**- * Check if a run is active- */-app.get('/runs/:runId/active', (req, res) => {- const { runId } = req.params;- res.json({ runId, active: activeRuns.has(runId) });-});--/**- * Stop a run- */-app.post('/runs/:runId/stop', (req, res) => {- const { runId } = req.params;- const run = activeRuns.get(runId);-- if (!run) {- return res.status(404).json({ error: 'Run not found or not active' });- }-- console.log(`🛑 Stopping run ${runId}`);-- run.process.kill('SIGTERM');-- // Force kill after timeout- setTimeout(() => {- if (activeRuns.has(runId)) {- run.process.kill('SIGKILL');- activeRuns.delete(runId);- }- }, SIGKILL_GRACE_MS);-- res.json({ success: true, runId });-});-/*** Socket.IO connection handling*/diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 7d398264e0..2d5a809f54 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -82,11 +82,6 @@ export function initCosRunnerConnection() {// Batch orphaned agents event (startup cleanup)socket.on('agents:orphaned', (data) => dispatch('agents:orphaned', data));-- // Forward devtools run events to registered handlers- socket.on('run:data', (data) => dispatch('run:data', data));- socket.on('run:complete', (data) => dispatch('run:complete', data));- socket.on('run:error', (data) => dispatch('run:error', data));}/**@@ -250,92 +245,3 @@ export async function getAgentOutputFromRunner(agentId) {}return readRunnerJson(response);}--// ============================================-// DEVTOOLS RUNS - CLI execution via runner-// ============================================--/**- * Execute a CLI run via the CoS Runner- */-export async function executeCliRunViaRunner(options) {- const {- runId,- command,- args,- prompt,- workspacePath,- envVars,- timeout- } = options;-- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/run`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- runId,- command,- args,- prompt,- workspacePath,- envVars,- timeout- }),- }, 60000);-- if (!response.ok) {- const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to execute run');- }-- return readRunnerJson(response);-}--/**- * Get list of active runs from runner- */-export async function getActiveRunsFromRunner() {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs`, {}, 10000);- if (!response.ok) {- throw new Error('Failed to get runs');- }- return readRunnerJson(response);-}--/**- * Check if a run is active in the runner- */-export async function isRunActiveInRunner(runId) {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs/${runId}/active`, {}, 10000);- if (!response.ok) {- return false;- }- const data = await readRunnerJson(response);- return data.active;-}--/**- * Get run output from runner- */-export async function getRunOutputFromRunner(runId) {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs/${runId}/output`, {}, 10000);- if (!response.ok) {- return null;- }- const data = await readRunnerJson(response);- return data.output;-}--/**- * Stop a run via the runner- */-export async function stopRunViaRunner(runId) {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs/${runId}/stop`, {- method: 'POST'- }, 30000);- if (!response.ok) {- const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to stop run');- }- return readRunnerJson(response);-}diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsindex ca36232000..28a168a8bc 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -34,12 +34,7 @@ import {killAgentViaRunner,getAgentStatsFromRunner,terminateAllAgentsViaRunner,- getAgentOutputFromRunner,- executeCliRunViaRunner,- getActiveRunsFromRunner,- isRunActiveInRunner,- getRunOutputFromRunner,- stopRunViaRunner+ getAgentOutputFromRunner} from './cosRunnerClient.js';// The client reads the body via text() and tolerantly JSON.parses it, so a@@ -379,118 +374,4 @@ describe('cosRunnerClient', () => {await expect(getAgentOutputFromRunner('bad-id')).rejects.toThrow('Not found');});});-- // ===========================================================================- // executeCliRunViaRunner- // ===========================================================================- describe('executeCliRunViaRunner', () => {- it('should POST run request and return result', async () => {- const runResult = { runId: 'r1', started: true };- fetchWithTimeout.mockResolvedValue(mockResponse(true, runResult));-- const result = await executeCliRunViaRunner({- runId: 'r1',- command: 'npm',- args: ['test'],- prompt: 'run tests',- workspacePath: '/tmp/ws',- timeout: 30000- });-- expect(result).toEqual(runResult);- expect(fetchWithTimeout).toHaveBeenCalledWith(- expect.stringContaining('/run'),- expect.objectContaining({ method: 'POST' }),- 60000- );-- const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);- expect(callBody.runId).toBe('r1');- expect(callBody.command).toBe('npm');- expect(callBody.args).toEqual(['test']);- });-- it('should throw on failure', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'No slots' }));- await expect(executeCliRunViaRunner({ runId: 'r1' })).rejects.toThrow('No slots');- });- });-- // ===========================================================================- // getActiveRunsFromRunner- // ===========================================================================- describe('getActiveRunsFromRunner', () => {- it('should return active runs', async () => {- const runs = [{ id: 'r1' }, { id: 'r2' }];- fetchWithTimeout.mockResolvedValue(mockResponse(true, runs));- const result = await getActiveRunsFromRunner();- expect(result).toEqual(runs);- });-- it('should throw on failure', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));- await expect(getActiveRunsFromRunner()).rejects.toThrow('Failed to get runs');- });- });-- // ===========================================================================- // isRunActiveInRunner- // ===========================================================================- describe('isRunActiveInRunner', () => {- it('should return true when run is active', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(true, { active: true }));- const result = await isRunActiveInRunner('r1');- expect(result).toBe(true);- });-- it('should return false when run is not active', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(true, { active: false }));- const result = await isRunActiveInRunner('r1');- expect(result).toBe(false);- });-- it('should return false on non-ok response', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));- const result = await isRunActiveInRunner('r1');- expect(result).toBe(false);- });- });-- // ===========================================================================- // getRunOutputFromRunner- // ===========================================================================- describe('getRunOutputFromRunner', () => {- it('should return run output', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(true, { output: 'test passed' }));- const result = await getRunOutputFromRunner('r1');- expect(result).toBe('test passed');- });-- it('should return null on non-ok response', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));- const result = await getRunOutputFromRunner('r1');- expect(result).toBeNull();- });- });-- // ===========================================================================- // stopRunViaRunner- // ===========================================================================- describe('stopRunViaRunner', () => {- it('should POST stop and return result', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(true, { stopped: true }));- const result = await stopRunViaRunner('r1');- expect(result).toEqual({ stopped: true });- expect(fetchWithTimeout).toHaveBeenCalledWith(- expect.stringContaining('/runs/r1/stop'),- { method: 'POST' },- 30000- );- });-- it('should throw on failure', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Not running' }));- await expect(stopRunViaRunner('r1')).rejects.toThrow('Not running');- });- });});