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([med-ai-dispatch-server-services-aidetect-js-242]): migrate aiDetect to runPromptThroughProvider so TUI providers work
[._.]/ Adam Eivy99261ccded0c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a3d162b5fc..bf7c65ceb4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **[med-ai-dispatch-server-services-aidetect-js-242] `aiDetect.js` migrated to `runPromptThroughProvider` — TUI providers now work on Settings → Detect App.** `server/services/aiDetect.js` had a legacy `if (provider.type === 'cli') … else if ('api') … else 'Unknown provider type'` dispatch that rejected TUI providers outright and duplicated spawn/fetch logic the central handler already covers. The two inline functions (`executeCliDetection`, `executeApiDetection`) and the local `spawn`/`fetch` machinery are gone; detection now flows through `runPromptThroughProvider` from `server/lib/promptRunner.js` with `source: 'ai-app-detect'`, `cwd: dirPath` (so a spawned CLI/TUI runs against the analyzed repo, not PortOS's own cwd), and a 60s default timeout. `parseAiResponse` also moved to the shared `extractJson` helper from `server/lib/jsonExtract.js`, which strips CLI banner text and repairs trailing-comma JSON — relevant for TUI providers that emit banner output around the JSON payload. New `server/services/aiDetect.test.js` locks in the dispatch behavior (regression test ensures TUI no longer fails with "Unknown provider type") plus directory + provider-disabled error paths and the banner-stripping JSON case.+- **Retire `DONE.md` — the audit trail for completed work is now `git log` + `.changelog/`.** Slashdo v2.18.0 dropped DONE.md handling from `/do:replan` and friends; PortOS follows suit. Bumped the slashdo submodule to `v2.18.0`, deleted the repo-root `DONE.md`, and updated PLAN.md's preamble to point at the changelog and `git log` instead. `/claim` (`.claude/commands/claim.md`) now removes the picked item from PLAN.md outright and appends an entry to `.changelog/NEXT.md`. Server prompts retire DONE.md too: `feature-ideas` (PROMPT_VERSIONS v8→v9) and `plan-task` (v5→v6) no longer read DONE.md or write archive entries — they scan `.changelog/` + `git log` for completed-work signal and remove items from PLAN.md outright. Old v8/v5 bodies are captured in `PREVIOUS_DEFAULT_PROMPTS` so existing schedules on stock prompts auto-upgrade on next read. Also stripped DONE.md mentions from `documentation`, `do-replan`, `code-reviewer-review`, and `code-reviewer-implement` task prompts (unversioned — stock copies behave like custom and stick until the user resets, which is fine). `server/routes/apps.js#ALLOWED_DOCUMENTS` no longer lists DONE.md so the Documents tab won't surface it for managed apps. `server/services/cos.js#applyPlanIdMetadata` stopped reading DONE.md for slug-uniqueness (PLAN.md is now the only source). `server/lib/planIds.js` comments/tests updated. Client copy in `SlashDoPanel.jsx` (`/do:replan` button) + `TaskItem.jsx` reflect the new replan behavior. Existing repos with a DONE.md on disk are left untouched — slashdo simply no longer reads or writes them.## Addeddiff --git a/PLAN.md b/PLAN.mdindex 76982255de..84083c3a11 100644--- a/PLAN.md+++ b/PLAN.md@@ -39,7 +39,6 @@ _Nothing currently parked — pick the next item from the Backlog._- [ ] [med-pipeline-server-services-pipeline-arcplanner-2] **[MED][PIPELINE]** `server/services/pipeline/arcPlanner.js:929-942` — `buildSeasonRemap` Pass 3 (positional fallback) silently invents wrong mappings when the LLM structurally reshapes the arc. Log a warning when Pass 3 fires; consider only firing when unmatched count ≤ 1.- [ ] [med-pipeline-server-routes-pipeline-js-1416-1452] **[MED][PIPELINE]** `server/routes/pipeline.js:1416, 1452, 470-472, 498-500` — cover render routes always overwrite `script` with the resolved value (treats absent vs empty-string identically). Only update `script` from render when the request body actually carried the field, OR drop script writes from render routes entirely (blur-save owns the field).- [ ] [med-sharing-server-services-sharing-version-js] **[MED][SHARING]** `server/services/sharing/version.js` — `SHARING_SCHEMA_VERSION` not bumped despite series-schema canon-field removal. Cross-peer share-bucket import from a pre-B.4 install silently loses series-side canon. Either bump the version (force refusal) or mirror migration logic in the importer for legacy canon fields.-- [ ] [med-ai-dispatch-server-services-aidetect-js-242] **[MED][AI-DISPATCH]** `server/services/aiDetect.js:242-250` — still has legacy `if (provider.type === 'cli') ... else if (api) ... else 'Unknown provider type'`. TUI providers fail on Settings → Detect App. Migrate to `runPromptThroughProvider`.- [ ] [med-ai-dispatch-server-services-digital-twin] **[MED][AI-DISPATCH]** `server/services/digital-twin-helpers.js:56-130` — `callProviderAI` still has ad-hoc CLI/API split with TUI falling into the CLI branch (will hang or render banner into pipe). Migrate to `runPromptThroughProvider`.- [ ] [med-ai-dispatch-server-lib-tuipromptrunner-js-198] **[MED][AI-DISPATCH]** `server/lib/tuiPromptRunner.js:198-200` — `OUTPUT_BUFFER_CAP = 1MB` silently truncates the _head_ of TUI responses >1.25MB mid-token. Persists to disk AND returns truncated. Either stream incrementally to `output.txt` (like agentTuiSpawning does) or raise the cap + log a warning.- [ ] [med-tests-no-tests-for-server-lib-ansistrip-js] **[MED][TESTS]** No tests for `server/lib/ansiStrip.js` (streaming escape-split-across-chunks logic) or `server/lib/tuiHandshake.js` (paste timing constants both production paths depend on). Add coverage for: escape split across two chunks, bare `\x1B` at chunk end, OSC sequences, unterminated bytes past the 4096-byte window.diff --git a/server/services/aiDetect.js b/server/services/aiDetect.jsindex 200320055c..ef01b22b2e 100644--- a/server/services/aiDetect.js+++ b/server/services/aiDetect.js@@ -2,8 +2,11 @@ import { readFile, readdir, stat } from 'fs/promises';import { existsSync } from 'fs';import { join, basename } from 'path';import { getActiveProvider, getProviderById } from './providers.js';-import { spawn } from 'child_process';-import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { tryReadFile } from '../lib/fileUtils.js';+import { extractJson } from '../lib/jsonExtract.js';+import { runPromptThroughProvider } from '../lib/promptRunner.js';++const DEFAULT_AI_DETECT_TIMEOUT_MS = 60000;/*** Gather project context for AI analysis@@ -113,97 +116,14 @@ Rules:- If the app has both frontend and backend, suggest separate PM2 processes`;}-/**- * Execute AI detection using CLI provider- */-async function executeCliDetection(provider, prompt, cwd) {- return new Promise((resolve, reject) => {- const args = [...(provider.args || []), prompt];- let output = '';-- const child = spawn(provider.command, args, {- cwd,- env: process.env,- shell: false,- windowsHide: true- });-- child.stdout.on('data', (data) => {- output += data.toString();- });-- child.stderr.on('data', (data) => {- output += data.toString();- });-- child.on('close', (code) => {- if (code === 0) {- resolve(output);- } else {- reject(new Error(`CLI exited with code ${code}`));- }- });-- child.on('error', reject);-- // Timeout after provider timeout or 60s- setTimeout(() => {- child.kill();- reject(new Error('Detection timed out'));- }, provider.timeout || 60000);- });-}--/**- * Execute AI detection using API provider- */-async function executeApiDetection(provider, prompt) {- const headers = { 'Content-Type': 'application/json' };- if (provider.apiKey) {- headers['Authorization'] = `Bearer ${provider.apiKey}`;- }-- const response = await fetch(`${provider.endpoint}/chat/completions`, {- method: 'POST',- headers,- body: JSON.stringify({- model: provider.defaultModel,- messages: [{ role: 'user', content: prompt }],- temperature: 0.1- }),- signal: AbortSignal.timeout(provider.timeout || 60000)- });-- if (!response.ok) {- throw new Error(`API error: ${response.status}`);- }-- const data = await response.json();- return data.choices?.[0]?.message?.content || '';-}--/**- * Parse AI response to extract JSON- */function parseAiResponse(response) {- // Try to extract JSON from response- let jsonStr = response.trim();-- // Remove markdown code blocks if present- const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);- if (jsonMatch) {- jsonStr = jsonMatch[1].trim();- }-- // Try to find JSON object- const objectMatch = jsonStr.match(/\{[\s\S]*\}/);- if (objectMatch) {- jsonStr = objectMatch[0];- }-- const parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'AI app detection' });- if (!parsed) throw new Error('Failed to parse AI detection response');- return parsed;+ // Route through the shared extractor so banner-stripping, trailing-comma+ // repair, and the `[...]` placeholder elision the rest of PortOS's LLM+ // callers benefit from also apply here — TUI providers in particular emit+ // banner text around the JSON payload that the legacy regex would miss.+ const { value } = extractJson(response);+ if (!value || typeof value !== 'object') throw new Error('Failed to parse AI detection response');+ return value;}/**@@ -237,17 +157,14 @@ export async function detectAppWithAi(dirPath, providerId = null) {const context = await gatherProjectContext(dirPath);const prompt = buildAnalysisPrompt(context);- // Execute detection- let response;- if (provider.type === 'cli') {- response = await executeCliDetection(provider, prompt, dirPath)- .catch(err => { throw new Error(`CLI detection failed: ${err.message}`); });- } else if (provider.type === 'api') {- response = await executeApiDetection(provider, prompt)- .catch(err => { throw new Error(`API detection failed: ${err.message}`); });- } else {- return { success: false, error: 'Unknown provider type' };- }+ // cwd: dirPath so any spawned CLI/TUI runs against the analyzed repo, not PortOS's own cwd.+ const { text: response } = await runPromptThroughProvider({+ provider,+ prompt,+ source: 'ai-app-detect',+ timeout: provider.timeout || DEFAULT_AI_DETECT_TIMEOUT_MS,+ cwd: dirPath,+ });// Parse responseconst detected = parseAiResponse(response);diff --git a/server/services/aiDetect.test.js b/server/services/aiDetect.test.jsnew file mode 100644index 0000000000..d09da9ed25--- /dev/null+++ b/server/services/aiDetect.test.js@@ -0,0 +1,136 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mkdtemp, writeFile, rm } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++// aiDetect used to spawn CLI providers + fetch API providers directly; it now+// delegates to runPromptThroughProvider so TUI providers (which previously+// fell through to the "Unknown provider type" branch) work the same way.+vi.mock('./providers.js', () => ({+ getActiveProvider: vi.fn(),+ getProviderById: vi.fn()+}));++vi.mock('../lib/promptRunner.js', () => ({+ runPromptThroughProvider: vi.fn()+}));++import { getActiveProvider, getProviderById } from './providers.js';+import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { detectAppWithAi } from './aiDetect.js';++const VALID_DETECTION_JSON = JSON.stringify({+ name: 'Test App',+ description: 'sample',+ uiPort: 3000,+ apiPort: 3001,+ startCommands: ['npm run dev'],+ pm2ProcessNames: ['test-app'],+ hasFrontend: true,+ hasBackend: true+});++async function makeProjectDir(files = {}) {+ const dir = await mkdtemp(join(tmpdir(), 'aidetect-test-'));+ for (const [name, content] of Object.entries(files)) {+ await writeFile(join(dir, name), content, 'utf-8');+ }+ return dir;+}++async function withProjectDir(files, fn) {+ const dir = await makeProjectDir(files);+ try { return await fn(dir); } finally { await rm(dir, { recursive: true, force: true }); }+}++beforeEach(() => {+ vi.resetAllMocks();+});++describe('detectAppWithAi', () => {+ it('returns error when directory does not exist', async () => {+ const result = await detectAppWithAi('/path/that/does/not/exist');+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/does not exist/i);+ });++ it('returns error when no provider is configured', async () => {+ getActiveProvider.mockResolvedValue(null);+ await withProjectDir({}, async (dir) => {+ const result = await detectAppWithAi(dir);+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/no ai provider/i);+ });+ });++ it('returns error when provider is disabled', async () => {+ getActiveProvider.mockResolvedValue({ id: 'p1', type: 'api', enabled: false });+ await withProjectDir({}, async (dir) => {+ const result = await detectAppWithAi(dir);+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/disabled/i);+ });+ });++ it('routes TUI providers through runPromptThroughProvider (regression: used to fail "Unknown provider type")', async () => {+ const tuiProvider = { id: 'claude-tui', name: 'Claude TUI', type: 'tui', enabled: true, timeout: 30000 };+ getProviderById.mockResolvedValue(tuiProvider);+ runPromptThroughProvider.mockResolvedValue({ text: VALID_DETECTION_JSON, runId: 'r1', model: 'm1' });++ await withProjectDir({ 'package.json': JSON.stringify({ name: 'my-app' }) }, async (dir) => {+ const result = await detectAppWithAi(dir, 'claude-tui');++ expect(result.success).toBe(true);+ expect(result.provider).toBe('Claude TUI');+ expect(runPromptThroughProvider).toHaveBeenCalledTimes(1);+ const call = runPromptThroughProvider.mock.calls[0][0];+ expect(call.provider).toBe(tuiProvider);+ expect(call.source).toBe('ai-app-detect');+ expect(call.cwd).toBe(dir);+ expect(call.timeout).toBe(30000);+ });+ });++ it('uses default 60s timeout when provider does not specify one', async () => {+ const provider = { id: 'p', name: 'P', type: 'api', enabled: true };+ getActiveProvider.mockResolvedValue(provider);+ runPromptThroughProvider.mockResolvedValue({ text: VALID_DETECTION_JSON, runId: 'r1', model: 'm1' });++ await withProjectDir({}, async (dir) => {+ await detectAppWithAi(dir);+ expect(runPromptThroughProvider.mock.calls[0][0].timeout).toBe(60000);+ });+ });++ it('parses fenced JSON responses', async () => {+ const provider = { id: 'p', name: 'P', type: 'cli', enabled: true };+ getActiveProvider.mockResolvedValue(provider);+ runPromptThroughProvider.mockResolvedValue({+ text: '```json\n' + VALID_DETECTION_JSON + '\n```',+ runId: 'r1',+ model: 'm1'+ });++ await withProjectDir({}, async (dir) => {+ const result = await detectAppWithAi(dir);+ expect(result.success).toBe(true);+ expect(result.detected.name).toBe('Test App');+ });+ });++ it('parses JSON with leading CLI banner text (TUI/Codex case)', async () => {+ const provider = { id: 'p', name: 'P', type: 'tui', enabled: true };+ getActiveProvider.mockResolvedValue(provider);+ runPromptThroughProvider.mockResolvedValue({+ text: 'Initializing...\nWorking on it...\n' + VALID_DETECTION_JSON + '\nDone.',+ runId: 'r1',+ model: 'm1'+ });++ await withProjectDir({}, async (dir) => {+ const result = await detectAppWithAi(dir);+ expect(result.success).toBe(true);+ expect(result.detected.name).toBe('Test App');+ });+ });+});