Skip to content

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

fix: close review gaps in AI-detect prompt fencing (#5657)

Adam Eivy5fff43d767d1
diff --git a/server/services/aiDetect.js b/server/services/aiDetect.js
index 2661b28672..e3d5fc992b 100644
--- a/server/services/aiDetect.js
+++ b/server/services/aiDetect.js
@@ -21,11 +21,24 @@ const MAX_CONFIG_FILE_CHARS = 2000;
const MAX_ENV_LINES_CHARS = 500;
const MAX_README_CHARS = 1000;
const MAX_FILE_LIST_CHARS = 1000;
+const MAX_DIR_NAME_CHARS = 200;
// PM2 process names become the identity of a spawned process; keep them to the
// same conservative shape PortOS itself uses for app process names.
const PM2_PROCESS_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
+// `all` is pm2's reserved every-process target, not a name. Stored as this app's
+// process name it would turn a scoped `pm2 stop <name>` into `pm2 stop all` and
+// take down every app on the shared daemon — the exact target
+// `PM2_ALL_TARGET_VERBS` blocks in commandSecurity.js.
+const PM2_RESERVED_TARGETS = new Set(['all']);
+
+const isUsablePm2ProcessName = (n) => (
+ typeof n === 'string'
+ && PM2_PROCESS_NAME_PATTERN.test(n)
+ && !PM2_RESERVED_TARGETS.has(n.toLowerCase())
+);
+
const DEFAULT_START_COMMAND = 'npm run dev';
// The scanned directory's name is operator-supplied rather than model output,
@@ -123,6 +136,7 @@ function buildAnalysisPrompt(context) {
// instruction that fenced content is data — because the answer's
// `startCommands` is later handed to pm2 as a process command line.
const sections = [
+ fenceBlock('Directory', context.dirName, MAX_DIR_NAME_CHARS),
fenceBlock('Files', context.files.slice(0, 50).join(', '), MAX_FILE_LIST_CHARS),
fenceBlock('package.json', context.packageJson, MAX_PACKAGE_JSON_CHARS),
...context.configFiles.map(f => fenceBlock(f.name, f.content, MAX_CONFIG_FILE_CHARS)),
@@ -134,8 +148,6 @@ function buildAnalysisPrompt(context) {
${UNTRUSTED_CONTENT_NOTICE}
-Directory: ${context.dirName}
-
${sections.join('\n\n')}
Return ONLY valid JSON (no markdown, no explanation) with this exact structure:
@@ -174,9 +186,9 @@ function sanitizeStartCommands(value) {
function sanitizePm2ProcessNames(value, fallbackName) {
const fallback = [fallbackName];
if (!Array.isArray(value)) return fallback;
- const kept = value.filter(n => typeof n === 'string' && PM2_PROCESS_NAME_PATTERN.test(n));
+ const kept = value.filter(isUsablePm2ProcessName);
if (kept.length !== value.length) {
- console.warn(`🛡️ ai-detect dropped ${value.length - kept.length} of ${value.length} pm2ProcessNames (malformed process name)`);
+ console.warn(`🛡️ ai-detect dropped ${value.length - kept.length} of ${value.length} pm2ProcessNames (malformed or reserved process name)`);
}
return kept.length ? kept : fallback;
}
@@ -191,7 +203,13 @@ const isDetectionShape = (v) => (
);
function parseAiResponse(response) {
- const { value } = extractJson(response, { shapePredicate: isDetectionShape });
+ // skipInnerFence: the prompt now wraps every repository section in a ```text
+ // fence, so a prompt-echoing provider replays fences AHEAD of its answer.
+ // extractJson's "first inner fence is the wrapper" heuristic would lock onto
+ // the echoed Files/package.json block and never reach the real response — the
+ // exact case its docblock says this option exists for. Balanced-block walking
+ // plus the shape gate below still finds the answer.
+ const { value } = extractJson(response, { shapePredicate: isDetectionShape, skipInnerFence: true });
if (!isDetectionShape(value)) throw new Error('Failed to parse AI detection response');
return value;
}
diff --git a/server/services/aiDetect.test.js b/server/services/aiDetect.test.js
index b24dba84d0..13aa48e21f 100644
--- a/server/services/aiDetect.test.js
+++ b/server/services/aiDetect.test.js
@@ -195,6 +195,43 @@ describe('detectAppWithAi', () => {
expect(result.detected.pm2ProcessNames).toEqual(['test-app']);
});
+ it("rejects pm2's reserved 'all' target as a process name", async () => {
+ // Stored as this app's process name, `all` turns a scoped `pm2 stop <name>`
+ // into `pm2 stop all` and takes down every app on the shared daemon.
+ const hostile = JSON.stringify({
+ ...JSON.parse(VALID_DETECTION_JSON),
+ pm2ProcessNames: ['all'],
+ });
+ const { result } = await runDetect({}, hostile);
+
+ expect(result.detected.pm2ProcessNames).not.toContain('all');
+ });
+
+ it('fences the scanned directory name, which a crafted checkout path controls', async () => {
+ const { prompt } = await runDetect({});
+ // The dir name is no longer a bare `Directory: <value>` prompt line an
+ // embedded newline could break out of.
+ expect(prompt).not.toMatch(/^Directory: /m);
+ expect(prompt).toContain('Directory:\n```text');
+ });
+
+ it('still finds the detection JSON when a provider echoes the now-fenced prompt', async () => {
+ // The prompt itself now carries ```text fences; a prompt-echoing TUI
+ // replays them ahead of the real answer, so extraction must skip a fenced
+ // block whose content is not detection-shaped.
+ const pkg = JSON.stringify({ name: 'echoed-from-prompt', scripts: { dev: 'vite' } });
+ const echo = [
+ 'Files:', FENCE + 'text', 'package.json, README.md', FENCE,
+ 'package.json:', FENCE + 'text', pkg, FENCE,
+ 'My answer:', VALID_DETECTION_JSON,
+ ].join('\n');
+ const { result } = await runDetect({ 'package.json': pkg }, echo);
+
+ expect(result.success).toBe(true);
+ expect(result.detected.name).toBe('Test App');
+ expect(result.detected.uiPort).toBe(3000);
+ });
+
it('drops a malformed pm2ProcessNames entry and falls back to the directory name', async () => {
const hostile = JSON.stringify({
...JSON.parse(VALID_DETECTION_JSON),