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
tell agents no human is present, and name an unanswered prompt as the stall cause
[._.]/ Adam Eivycd32a7196dd6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cbd48af364..e169af1173 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@- **[issue-3202] Restarting PortOS no longer marks a running agent "completed" or burns its retry budget** — a restart kills every agent PortOS owns, and the terminal-based ones reported that as a clean finish. The task was recorded as done with nothing but two startup lines to show for it, and the folder holding its work was deleted on the way out. When the task did come back, the restart was counted against it as a failure: three routine restarts were enough to block the task outright, and two in a row left it sitting in a 30-minute cooldown. PortOS now recognizes that it was the one that pulled the plug. An agent cut short by a restart — terminal-based or headless — is recorded as interrupted rather than finished, its working folder is left untouched, and the task returns to the queue immediately, resuming from what the interrupted run left behind with no retry charged and no cooldown. An agent that had already reported its results still completes normally, one you terminated yourself is still recorded as terminated, and agents that genuinely fail on their own are unaffected. Agents still stop when PortOS restarts; keeping them running across one is separate work.- **[issue-3211] Orphaned agents now close their run history during recovery** — a process that disappeared before normal completion left its run permanently unfinished, with no end time, outcome, transcript size, or usage reconciliation. The recovery sweep now closes that run exactly once before requeuing the task, records PortOS-restart interruptions separately from ordinary failures, and safely handles older agents or missing run data.- **A brief internet outage no longer kills a working CoS agent.** When the machine lost its connection, a running agent's terminal went quiet — it couldn't reach the model — and after a few minutes the idle watchdog mistook that silence for a hung or finished agent and reaped it, throwing away in-progress work. PortOS now checks whether the machine is actually online before reaping an idle agent: while the connection is down, the reap is deferred and the agent is left alone to resume the moment the network returns (with a short grace so it isn't reaped in the instant between reconnecting and picking back up). Genuinely stuck agents on a healthy connection are still reaped on the same schedule as before, and the long absolute run-time ceiling still bounds an agent kept alive through a very long outage.+- **Agents are now told nobody is there to answer them, and a run that stalled on a question says so.** An agent PortOS launches runs unattended, but nothing in its briefing said that — so an agent that hit a multiple-choice question or an approval gate would sit there presenting it to an empty room until the idle watchdog killed the run and discarded the work. One task was retried into the same question three times and filed nothing. Every agent briefing now states that no human is present, to decide for itself and record the assumption rather than ask, and to invoke slash commands in their non-interactive form. When a run does stall this way, the failure is no longer reported as a bare idle-out — PortOS notices the transcript ends on an unanswered prompt and says that's what happened, so the next step is skipping the gate rather than hunting for a stalled provider.- **An agent killed by a server restart now picks up where it left off instead of starting over.** Restarting PortOS kills every running agent mid-edit, and the task went back in the queue for a brand-new agent that built a fresh worktree from `main` — so hours of in-progress work sat on disk, untouched, while the replacement redid it from scratch. PortOS now records what the interrupted run left behind and hands the retry its actual working directory: its commits, its uncommitted edits, and its untracked files, exactly as they were. The retry is told up front that it's continuing someone else's run and to check `git status`, the commit log, and whether a PR was already opened or merged before writing any code. Work that already landed is still never resumed onto, and if the leftover folder can't be handed over for any reason the retry starts clean rather than failing to start.## Image generationdiff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 287652e456..14240a554f 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -639,6 +639,63 @@ export const COMPLETION_REASON_ANALYSES = {}};+/**+ * Screen signatures of a TUI parked on an interactive prompt — a multiple-choice+ * selector, an approval gate, a confirmation. A CoS agent is unattended, so+ * nothing ever answers: the session repaints the prompt until the idle reaper+ * kills it, and the run lands as a plain idle-out. That verdict is true but+ * diagnostically useless — it sends the reader hunting for a stalled provider+ * request, and a retry re-runs the same command straight into the same gate.+ * (Observed cost: three identical `/do:plan-task` attempts, each parked on a+ * scope question, filing nothing. Prevention is `UNATTENDED_RUN_RULE` in+ * `agentPromptBuilder.js`; this is the diagnosis when one slips through.)+ */+// Each marker must be chrome no narrative prose would produce — a bare+// `to navigate` matches an agent describing a button it just added, so the+// navigate hint keeps its arrow glyphs.+export const AWAITING_INPUT_MARKERS = [+ /Enter to select/i,+ /↑\/↓ to navigate/,+ /❯\s*1\./,+ /Do you want to proceed\?/i,+ /Press Enter to continue/i+];++/**+ * Only the TAIL of the failure window is searched: the claim is "still sitting+ * here when the reaper fired", not "asked something at some point". A TUI+ * transcript is repaint-mangled and nearly newline-free (see+ * getFailureAnalysisWindow), so a character tail is the only reliable "end of+ * the session" boundary available.+ */+export const AWAITING_INPUT_TAIL_CHARS = 2500;++/** True when the end of the transcript looks like an unanswered prompt. Pure. */+export function endsAwaitingUserInput(analysisOutput) {+ const tail = (analysisOutput || '').slice(-AWAITING_INPUT_TAIL_CHARS);+ return AWAITING_INPUT_MARKERS.some(marker => marker.test(tail));+}++/** Idle-out reasons worth re-explaining as an unanswered prompt. */+const AWAITING_INPUT_REFINABLE_REASONS = new Set(['idle-no-changes', 'idle-no-activity']);++/**+ * Re-word an idle-out whose transcript ends on an unanswered prompt. The+ * original `category` is preserved — downstream taxonomies (auto-fix tiers,+ * layered-intelligence failure buckets) keep classifying it exactly as they did,+ * and both idle reasons already escalate rather than blind-retry. Only the prose+ * a human reads changes. Pure.+ */+function refineIdleReasonAnalysis(def, completionReason, analysisOutput) {+ if (!def || !AWAITING_INPUT_REFINABLE_REASONS.has(completionReason)) return def;+ if (!endsAwaitingUserInput(analysisOutput)) return def;+ return {+ ...def,+ message: 'Agent stalled on an interactive prompt with nobody to answer it',+ suggestedFix: 'The transcript ends on an unanswered prompt (a choice selector or approval gate), so the agent never got past it and the idle reaper killed the run. Agents run unattended — re-running as-is will stall the same way. Invoke the command in its non-interactive form (e.g. `/do:plan-task --yes`) or reword the task so no approval is needed.'+ };+}+/*** Build the analysis object for a runner-resolved completion reason. The* snippet comes from the runner's own error prose — clean, already-scoped text —@@ -673,8 +730,14 @@ function structuralReasonAnalysis(def, completionReason, completionError) {*/export function analyzeAgentFailure(output, task, model, options = {}) {const completionReason = options?.completionReason || null;- const structuralDef = completionReason ? COMPLETION_REASON_ANALYSES[completionReason] : null;const analysisOutput = getFailureAnalysisWindow(output || '');+ // An idle-out whose transcript ends on an unanswered prompt gets that named as+ // the cause; every other reason passes through untouched.+ const structuralDef = refineIdleReasonAnalysis(+ completionReason ? COMPLETION_REASON_ANALYSES[completionReason] : null,+ completionReason,+ analysisOutput+ );// Agent produced no meaningful output — likely failed to start. Measured on// the CLEANED window: a transcript that is nothing but cursor repaints carriesdiff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex f183c5b3f3..c25af7c9ad 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -16,6 +16,8 @@ import {createInvestigationTask,buildInvestigationFingerprint,redactFailureSnippet,+ endsAwaitingUserInput,+ AWAITING_INPUT_TAIL_CHARS,MAX_TASK_RETRIES,INVESTIGATION_CIRCUIT_WINDOW_MS,INVESTIGATION_CIRCUIT_MAX_CREATIONS,@@ -739,6 +741,64 @@ describe('analyzeAgentFailure — runner completion reason (COMPLETION_REASON_ANexpect(analysis.category).toBe('rate-limit');});+ // Verbatim-shaped tail of the real incident: a `/do:plan-task` run parked on the+ // skill's scope question until the idle reaper killed it. The transcript is+ // repaint-mangled (the TUI spools a SCREEN, not a log), which is why the marker+ // set only leans on fragments that survive a repaint.+ const parkedOnSelector = [+ 'Initializing agent session and preparing the working directory.',+ 'Found the real gap. Let me confirm the reuse surface.',+ '☐ Scope The drum-kit Web Audio play-along already exists in play mode. Which gap should I file?',+ '❯1.Audible preview in edit + import (Recommended) 2. Edit-mode preview only',+ 'Enter to select · ↑/↓ to navigate · Esc to ancel',+ ].join('\n');++ it('names the unanswered prompt as the cause of an idle-no-changes run', () => {+ const analysis = analyzeAgentFailure(parkedOnSelector, { id: 't' }, 'x', {+ completionReason: 'idle-no-changes',+ completionError: 'TUI agent idled out with zero uncommitted file changes',+ });+ expect(analysis.message).toMatch(/interactive prompt/i);+ expect(analysis.suggestedFix).toMatch(/non-interactive/i);+ // Category is deliberately unchanged so the auto-fix tier and the+ // layered-intelligence failure bucket keep classifying it identically.+ expect(analysis.category).toBe(COMPLETION_REASON_ANALYSES['idle-no-changes'].category);+ expect(analysis.completionReason).toBe('idle-no-changes');+ expect(analysis.origin).toBe('runner');+ });++ it('preserves the original category when refining an idle-no-activity stall', () => {+ const analysis = analyzeAgentFailure(parkedOnSelector, { id: 't' }, 'x', {+ completionReason: 'idle-no-activity',+ });+ expect(analysis.category).toBe('startup-failure');+ expect(analysis.message).toMatch(/interactive prompt/i);+ });++ it('leaves a plain idle-out alone when no prompt is on screen', () => {+ const analysis = analyzeAgentFailure(withLead('Ran 4 shell commands and read 2 files.'), { id: 't' }, 'x', {+ completionReason: 'idle-no-changes',+ });+ expect(analysis.message).toBe(COMPLETION_REASON_ANALYSES['idle-no-changes'].message);+ });++ it('does not re-word a non-idle reason that happens to show a prompt', () => {+ const analysis = analyzeAgentFailure(parkedOnSelector, { id: 't' }, 'x', {+ completionReason: 'max-runtime-timeout',+ });+ expect(analysis.message).toBe(COMPLETION_REASON_ANALYSES['max-runtime-timeout'].message);+ });++ it('ignores a prompt the agent got PAST — only the tail counts as parked', () => {+ const answeredEarly = [+ 'Enter to select · ↑/↓ to navigate',+ // Enough subsequent work to push the selector out of the tail window.+ ...Array.from({ length: 60 }, (_, i) => `Edited server/services/file${i}.js and ran the suite.`),+ ].join('\n');+ expect(answeredEarly.length).toBeGreaterThan(AWAITING_INPUT_TAIL_CHARS);+ expect(endsAwaitingUserInput(answeredEarly)).toBe(false);+ });+it('maps every reason to a category ERROR_PATTERNS already produces (no orphan taxonomy tokens)', () => {const known = new Set([...ERROR_PATTERNS.map(p => p.category), 'startup-failure']);for (const [reason, def] of Object.entries(COMPLETION_REASON_ANALYSES)) {diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 70306809c0..4617c3c431 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -39,6 +39,21 @@ const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');export const PM2_SAFETY_RULE = `## ⚠️ PM2 Safety (shared server)PortOS runs MANY apps under one shared pm2 daemon. To restart an app, use a SCOPED command — \`pm2 restart <that-app's-process-name>\`. NEVER run \`pm2 kill\`, \`pm2 stop\`, \`pm2 delete\`, \`pm2 startup\`/\`unstartup\`, or any \`pm2 <verb> all\` form: they take down EVERY app on this machine, including PortOS itself, and are blocked (they will fail).`;+// Also appended to every agent briefing. A CoS agent runs headless: the TUI has+// no human attached, so an interactive selector or approval gate is a dead end —+// the session repaints it until the idle reaper kills the run and the work is+// discarded. Nothing in the briefing used to SAY that, so a `/do:plan-task` run+// (whose skill shows its drafted issue for approval before filing) parked on a+// scope question for its whole life and was retried into the same gate three+// times, filing nothing. The rule names the escape hatch too: slash commands+// that gate on approval take a flag to skip it.+export const UNATTENDED_RUN_RULE = `## ⚠️ Unattended Run (no human is present)+PortOS launched you autonomously. Nobody is watching this session and nothing can answer you — if you present an interactive choice (a multiple-choice question, an approval gate, a "which option?" selector, a confirmation), the session sits there until the idle reaper kills it and **your work is thrown away**.+- **Never ask the user to choose or approve.** Make the call yourself, state the assumption in your summary, and proceed.+- **Invoke commands and skills in their non-interactive form.** If one drafts something and gates on approval before acting, pass the flag that skips that gate (\`--yes\` for the slashdo commands that have one).+- **Ambiguous task?** Pick the most reasonable reading, do the work, and note the alternatives you rejected in your completion summary.+- **Genuinely blocked** (missing credential, contradictory requirements)? Write why to the completion sentinel and stop. Do NOT wait for a reply.`;+/*** Skill template keyword matchers.* Each entry maps a skill template filename to its trigger keywords.@@ -1435,7 +1450,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch}).catch(() => null);if (promptData?.prompt) {- return `${promptData.prompt}\n\n${PM2_SAFETY_RULE}`;+ return `${promptData.prompt}\n\n${UNATTENDED_RUN_RULE}\n\n${PM2_SAFETY_RULE}`;}const taskBlock = buildTaskBlock(task, { screenshotsAsList: false });@@ -1512,6 +1527,8 @@ ${discardWorktree ? '' : worktreeInfo ? `- **Your PR should contain only your ta## Working Directory${task.metadata?.app ? `You are working in the target app directory: \`${workspaceDir}\`. All code changes, research, plans, and docs for this task belong in this directory — NOT in the PortOS repo.` : 'You are working in the project directory.'} Use the available tools to explore, modify, and test code.+${UNATTENDED_RUN_RULE}+${PM2_SAFETY_RULE}Begin working on the task now.`;@@ -1643,6 +1660,12 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// system prompt.sections = contractSections;+ // --- Unattended run ----------------------------------------------------+ // First contract section, and unconditional: the light path is the one that+ // actually stalled on an approval gate, and "no human will answer you" is not+ // something the agent can infer from CLAUDE.md or its cwd.+ sections.push(UNATTENDED_RUN_RULE);+// --- Worktree ----------------------------------------------------------if (worktreeInfo) {sections.push([