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: end a stopped autopilot run as canceled instead of filing a bug for it
[._.]/ Adam Eivybb9feafcb0f1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 970657506e..4b3de16860 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -48,3 +48,5 @@- **The rollback comparison now ignores write-path-owned fields on every kind of canon entry, not just characters.** The fix that stopped a faithful foundation rollback from reporting itself as a corrupted checkpoint stripped the server-owned per-entry fields (the LWW timestamp and the sheet/render pointers) from `characters` only, which happened to be the sole canon array the foundation snapshot tracked. The universe write path stamps those fields across characters, places, and objects alike, so extending the snapshot to worldbuilding canon would have quietly brought the same bogus "restored foundation fields did not match the checkpoint" pause back with no test to catch it. The comparison now walks every canon array the story bible defines, and the universe write path's three separate hardcoded copies of that list were collapsed onto the shared one so a future canon kind flows through instead of being silently skipped by the timestamp stamper.- **A managed app pinned to a self-hosted GitHub/GitLab is now reconciled the same way its Issues tab lists it.** When an app's work tracker is explicitly set to GitHub or GitLab, that pin lets PortOS query a forge whose hostname spells out neither `github.` nor `gitlab.` — a self-hosted Enterprise/GitLab instance can live on any domain the operator picked. The app's Issues tab honored the pin, but the background zombie/park reconciler that feeds scheduled CoS tasks still classified the origin from its hostname alone, so it silently treated the very same repo as "not a forge" and skipped every scan. Both paths now go through one composed resolver that carries the pin, so the tab and the scan can't drift again: threading it by hand is invisible on an ordinary github.com/gitlab.com origin and only fails on exactly the hosts that need it.++- **Stopping an autonomous run no longer reports it as a crash and files a bug for it.** Cancelling a Series Autopilot run — or stopping the LLM call it is sitting on from the Runs page, or restarting PortOS mid-run — kills the provider process, which the run then met as `TUI canceled (signal 15)` on its way out. The two lower layers already knew that signal was a deliberate stop rather than a provider fault (they neither bench the provider nor scan the story text for a bogus quota marker), but the autopilot itself only recognized a cancellation that arrived between steps. One that interrupted a step landed in the run's failure handler instead: the series was left in `error` rather than the resumable `paused`, a self-improvement post-mortem spent a long call diagnosing an automation defect that did not exist, and a CoS task was filed reading "The autonomous run failed and stopped" — a bug report about you pressing Stop. An interrupted step now ends the run the same way the between-steps cancel does, with the reason recorded on the series so Resume picks it back up. The foundation gate's two repair paths get the same treatment: they used to pause on "switch the repair provider/model first" for a repair the user themselves stopped, and the optional teaser step used to file a "retry this deliverable" task. Genuine step failures are unchanged — still `error`, still diagnosed, still filed. While fixing this, the pause and error terminals also moved their task filing to before the terminal status frame: the filing emits its own progress frame, and a client that opened the series after the run ended replayed that one and never learned the run had stopped.diff --git a/server/lib/aiToolkit/CLAUDE.md b/server/lib/aiToolkit/CLAUDE.mdindex e32248d1a6..199601a3c3 100644--- a/server/lib/aiToolkit/CLAUDE.md+++ b/server/lib/aiToolkit/CLAUDE.md@@ -13,7 +13,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.-- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.+- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.The worked example for "barrel + documented exports" (see root `CLAUDE.md` → Module Organization) is this directory's `index.js`.diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 26958d89e6..7069814b77 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -23,6 +23,29 @@ export const ERROR_CATEGORIES = {UNKNOWN: 'unknown'};+/**+ * Was this rejection an intentional stop rather than a failed AI attempt?+ *+ * A canceled terminal — a Stop of the in-flight run, a coordinator cancelling+ * its own active LLM call, or a host shutdown tree-killing the child — is+ * finalized with `canceled: true` on the run metadata, and the prompt runner+ * stamps `code: 'RUN_CANCELED'` onto the rejection it raises from it.+ *+ * Every caller that CLASSIFIES a failure — picks a pause kind, files a gap /+ * investigation task, benches a provider, marks a run `error` — must ask this+ * FIRST. A cancellation is evidence about the operator, not about the provider+ * or the automation: treating it as a defect files spurious follow-up work and+ * spends a post-mortem diagnosing a human pressing Stop. Lives here (rather+ * than beside the code that stamps it) so the classifying callers can ask+ * without importing the whole provider/runner graph.+ *+ * @param {*} err — a rejection from an LLM call+ * @returns {boolean}+ */+export const isRunCanceledError = (err) => (+ !!err && (err.code === 'RUN_CANCELED' || err.canceled === true)+);+// Order matters — more specific patterns first.const ERROR_PATTERNS = [{diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex 687b0810a4..ad2a679de3 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -9,6 +9,7 @@ import {detectTerminalModelError,detectTerminalRequestTimeout,extractWaitTime,+ isRunCanceledError,ERROR_CATEGORIES} from './errorDetection.js';@@ -519,4 +520,21 @@ describe('Error Detection', () => {expect(result.waitTime).toBeTruthy();});});++ describe('isRunCanceledError', () => {+ it('recognizes both markers the runners stamp on a canceled terminal', () => {+ // promptRunner stamps the code; the runner metadata carries the flag.+ expect(isRunCanceledError(Object.assign(new Error('TUI canceled (signal 15)'), { code: 'RUN_CANCELED' }))).toBe(true);+ expect(isRunCanceledError(Object.assign(new Error('CLI canceled (signal SIGTERM)'), { canceled: true }))).toBe(true);+ });++ it('does not claim an ordinary provider failure — which would suppress a real diagnosis', () => {+ expect(isRunCanceledError(new Error('TUI exited with code 1: model unavailable'))).toBe(false);+ // A run that merely mentions cancellation in its text is still a failure.+ expect(isRunCanceledError(new Error('the user canceled their subscription'))).toBe(false);+ expect(isRunCanceledError({ canceled: false, code: 'RUN_FAILED' })).toBe(false);+ expect(isRunCanceledError(null)).toBe(false);+ expect(isRunCanceledError(undefined)).toBe(false);+ });+ });});diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex ace3b2a4d6..ae35cf0ff5 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -31,7 +31,7 @@ import { getActiveProvider, getProviderById, getAllProviders } from '../servicesimport { executeTuiRun } from './tuiPromptRunner.js';import { ServerError } from './errorHandler.js';import { PROVIDER_TYPES } from './aiToolkit/constants.js';-import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';+import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from './aiToolkit/errorDetection.js';import { isSchemaTypeCategory, resolveProviderBench } from './providerCooldown.js';import { isGenerationModel } from './localModelHeuristics.js';import { getAIToolkitInstance } from './aiToolkitState.js';@@ -615,7 +615,7 @@ export async function runPromptThroughProvider(args) {// An explicit Stop or host shutdown is a lifecycle outcome, not a failed AI// attempt. Do not enter any correction/fallback tier, mark the provider// unavailable, or escalate an investigation task.- if (firstError?.canceled || firstError?.code === 'RUN_CANCELED') {+ if (isRunCanceledError(firstError)) {throw stripFallbackContext(firstError);}diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 5428b158e0..be177f19d6 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -3363,6 +3363,70 @@ describe('autopilot conductor', () => {}});+ // fileGap emits its own `gap:filed` frame and SSE replay keeps only the last+ // payload — so a gap filed after the terminal frame leaves a client that+ // attaches post-run replaying `gap:filed` and never learning the run ended.+ it('keeps the terminal frame last when a pause also files a gap task', async () => {+ verifyFindings = [{ severity: 'high', problem: 'unresolved plot hole' }];+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, maxArcVerifyRounds: 1 });+ await waitFor(runFinished(seriesId));+ expect(addTask).toHaveBeenCalled();+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('paused');+ });++ // An intentional stop reaches the conductor as a rejection, not as a step+ // result it can inspect: this run's Cancel calls stopRun on the active LLM+ // run, /runs Stop kills the same pty, and a restart tree-kills it — all three+ // surface as RUN_CANCELED out of the prompt runner. Landing that in the error+ // terminal marked the series `error`, spent a post-mortem diagnosing the+ // operator, and filed a `run-error` CoS task for a human pressing Stop.+ const canceledRejection = () => Object.assign(new Error('TUI canceled (signal 15)'), {+ code: 'RUN_CANCELED',+ canceled: true,+ });+ const filedGapKinds = () => addTask.mock.calls.map(([task]) => task.description);++ it('ends as canceled — not error — when a step\'s LLM call is stopped mid-flight', async () => {+ arcSpies.verifyArc.mockRejectedValueOnce(canceledRejection());+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true });+ await waitFor(runFinished(seriesId));+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('canceled');+ const series = await seriesSvc.getSeries(seriesId);+ // `paused`, so Resume picks the run back up from the next missing step.+ expect(series.autopilot?.status).toBe('paused');+ expect(series.autopilot?.lastError).toMatch(/canceled/i);+ expect(filedGapKinds().some((d) => /run-error/.test(d))).toBe(false);+ });++ it('still reports a genuine step failure as error and files the run-error gap', async () => {+ arcSpies.verifyArc.mockRejectedValueOnce(new Error('provider returned nothing'));+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true });+ await waitFor(runFinished(seriesId));+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('error');+ const series = await seriesSvc.getSeries(seriesId);+ expect(series.autopilot?.status).toBe('error');+ expect(filedGapKinds().some((d) => /run-error/.test(d))).toBe(true);+ });++ // The foundation gate catches its own repair failures and pauses on+ // `providerFailed` ("switch the repair provider/model first") — advice that+ // makes no sense for a repair the user themselves stopped.+ it('treats a stopped foundation repair as canceled, not a provider failure', async () => {+ foundationScore = 5;+ applyFoundationFix.mockRejectedValueOnce(canceledRejection());+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true });+ await waitFor(runFinished(seriesId));+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('canceled');+ const series = await seriesSvc.getSeries(seriesId);+ expect(series.autopilot?.status).toBe('paused');+ expect(series.autopilot?.pauseKind).toBeNull();+ expect(filedGapKinds().some((d) => /stalled|run-error/.test(d))).toBe(false);+ });+it('recoverStuckAutopilots demotes a running marker to paused', async () => {const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P' });await seriesSvc.updateSeries(series.id, { autopilot: { status: 'running', runId: 'dead' } });diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 300a865895..4df3b4e50a 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -5,6 +5,7 @@*/import { sleep } from '../../../lib/fileUtils.js';+import { isRunCanceledError } from '../../../lib/aiToolkit/errorDetection.js';import { recordDomainUsage } from '../../domainUsage.js';import { getSeries, AUTOPILOT_DISCARDED_MAX } from '../series.js';import { listIssues, getIssue, isStageReady } from '../issues.js';@@ -506,6 +507,11 @@ export async function runCharacterFoundation(seriesId, record) {broadcast(seriesId, {type: 'foundation:fix', phase: 'pre-arc', dimension: 'character', applied: false, reason: detail,});+ // A Stop (this run's Cancel, a /runs Stop, a host shutdown) killed the call+ // mid-flight. The spend above is real, but the run ended by request — hand+ // the loop a cancellation so it reaches the `canceled` terminal instead of+ // pausing with a "fix the provider" banner nobody asked for.+ if (isRunCanceledError(err)) return { canceled: true };return {pause: true,pauseKind: 'providerFailed',@@ -760,6 +766,10 @@ export async function runFoundationGate(seriesId, record) {broadcast(seriesId, {type: 'foundation:fix', round, dimension: weak.dimension, applied: false, reason: detail,});+ // Same rule as the pre-arc pass: an intentional stop is not a provider+ // failure, so end the run as canceled rather than pausing on a defect the+ // user never hit.+ if (isRunCanceledError(err)) return { canceled: true };return {pause: true,pauseKind: 'providerFailed',diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.jsindex d2008418a9..8cc80f4b28 100644--- a/server/services/pipeline/seriesAutopilot/orchestrator.js+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js@@ -6,6 +6,7 @@import { randomUUID } from 'crypto';import { getDomainMode } from '../../../lib/domainAutonomy.js';+import { isRunCanceledError } from '../../../lib/aiToolkit/errorDetection.js';import { mergeSeverityWeights, resolveBlockingSet } from '../../../lib/editorial/index.js';import { loadState } from '../../cosState.js';import { getDomainBudgetStatus } from '../../domainUsage.js';@@ -282,6 +283,10 @@ export async function startSeriesAutopilot(sId, options = {}) {// Fire-and-forget coordinator. The try/catch is the permitted boundary use —// an unhandled LLM rejection here would crash the process on Node ≥15.+ // `ordinal` (completed-step count) lives outside the try so the catch's+ // cancellation terminal can report how far the run got, exactly as the+ // cooperative between-steps cancel does.+ let ordinal = 0;(async () => {try {// DRY-RUN: enumerate the plan, no side effects.@@ -317,7 +322,6 @@ export async function startSeriesAutopilot(sId, options = {}) {broadcast(sId, { type: 'note', message: 'Draft visual rendering is not enabled in this build — running to text-ready + editorial review.' });}- let ordinal = 0;while (!record.cancelRequested) {const series = await getSeries(sId);const issues = await listIssues({ seriesId: sId });@@ -419,8 +423,10 @@ export async function startSeriesAutopilot(sId, options = {}) {...pm,};await persistMarker(sId, { status: 'paused', currentStep: step.kind, lastError: result.reason, ...pausePayload });- broadcast(sId, { type: 'paused', scope: step.kind, reason: result.reason, ...pausePayload, completedAt: new Date().toISOString() });- await notifyPause(record, sId, { reason: result.reason, pauseKind: result.pauseKind || null, currentStep: step.kind });+ // File BEFORE the terminal frame, for the same reason the post-mortem+ // runs first: fileGap emits its own `gap:filed` frame, and SSE replay+ // keeps only the LAST payload — filing afterwards leaves a client that+ // attaches post-run replaying `gap:filed` and never seeing the pause.// Only file the generic stalled task when the step didn't already file// a more specific gap (canon-undescribed, visual-no-pages, …) — else// fileGaps would create two CoS tasks for one underlying problem (the@@ -433,6 +439,8 @@ export async function startSeriesAutopilot(sId, options = {}) {context: JSON.stringify(result.residual || []).slice(0, 1000),});}+ broadcast(sId, { type: 'paused', scope: step.kind, reason: result.reason, ...pausePayload, completedAt: new Date().toISOString() });+ await notifyPause(record, sId, { reason: result.reason, pauseKind: result.pauseKind || null, currentStep: step.kind });console.log(`⏸️ autopilot paused (${step.kind}) — series=${sId.slice(0, 12)}: ${result.reason}`);return;}@@ -448,18 +456,36 @@ export async function startSeriesAutopilot(sId, options = {}) {console.log(`🛑 autopilot canceled — series=${sId.slice(0, 12)} after ${ordinal} steps`);} catch (err) {const message = (err?.message || String(err)).slice(0, 1000);+ // A step's LLM call can be stopped mid-flight — this run's Cancel reaches+ // through to `stopRun(activeLlmRunId)`, /runs Stop kills the same pty, and+ // a PortOS restart tree-kills it — and the prompt runner surfaces all+ // three as a RUN_CANCELED rejection rather than a step result the loop+ // could inspect. That is a lifecycle outcome, not an automation defect:+ // route it to the same resumable `paused` + `canceled` terminal the+ // cooperative between-steps cancel uses. Reporting `error` here would+ // spend a post-mortem diagnosing the operator and file a `run-error` gap+ // task for a human pressing Stop.+ if (isRunCanceledError(err)) {+ await observerIdle();+ await persistMarker(sId, { status: 'paused', runId, currentStep: null, lastError: message });+ broadcast(sId, { type: 'canceled', runId, steps: ordinal, reason: message, completedAt: new Date().toISOString() });+ console.log(`🛑 autopilot canceled — series=${sId.slice(0, 12)} after ${ordinal} steps: ${message}`);+ return;+ }console.error(`❌ autopilot failed — series=${sId.slice(0, 12)} ${message}`);// Same ordering as the other terminals: diagnose first so the verdict can// ride the `error` frame + marker rather than arriving after the client// has torn its stream down.const pm = await postMortem('error', message);await persistMarker(sId, { status: 'error', runId, lastError: message, ...pm });- broadcast(sId, { type: 'error', runId, error: message, ...pm, failedAt: new Date().toISOString() });+ // Filed before the frame for the same replay reason as the pause terminal:+ // `gap:filed` would otherwise be the last retained payload.await fileGap(record, sId, {gapKind: 'run-error',summary: `The autonomous run failed and stopped: ${message}`,context: message,}).catch(() => {});+ broadcast(sId, { type: 'error', runId, error: message, ...pm, failedAt: new Date().toISOString() });} finally {record.finished = true;scheduleCleanup(sId, record);diff --git a/server/services/pipeline/seriesAutopilot/visualSteps.js b/server/services/pipeline/seriesAutopilot/visualSteps.jsindex 1b65f0244b..7f92179db0 100644--- a/server/services/pipeline/seriesAutopilot/visualSteps.js+++ b/server/services/pipeline/seriesAutopilot/visualSteps.js@@ -6,6 +6,7 @@import { buildRenderSlot } from '../../../lib/renderSlot.js';import { parseComicScript } from '../../../lib/comicScriptParser.js';+import { isRunCanceledError } from '../../../lib/aiToolkit/errorDetection.js';import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';import { getIssue, updateStageWithLatest } from '../issues.js';import { slotKeyForVariant } from '../owners.js';@@ -219,6 +220,13 @@ export async function runProduceTeaser(sId, issueId, record) {return {};} catch (err) {const message = (err?.message || String(err)).slice(0, 300);+ // A Stop that lands during the treatment call is not a failed deliverable —+ // end the run as canceled rather than filing a "retry the teaser" gap task+ // for work the user themselves interrupted.+ if (isRunCanceledError(err)) {+ broadcast(sId, { type: 'step:skip', kind: 'produceTeaser', issueId, reason: `teaser production canceled: ${message}` });+ return { canceled: true };+ }broadcast(sId, { type: 'step:skip', kind: 'produceTeaser', issueId, reason: `teaser production failed: ${message}` });await fileGap(record, sId, {gapKind: 'teaser-failed',