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
show a live task card for the checks a Run Now runs before any agent exists
[._.]/ Adam Eivyda7ecbabd490
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsxindex 6e45565462..53d76fb885 100644--- a/client/src/components/apps/tabs/PullRequestsTab.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx@@ -173,7 +173,17 @@ export default function PullRequestsTab({ appId, appName }) {const applyTaskUpdate = useCallback(task => {if (!task?.id) return;- const nextStatus = task.metadata?.preflightFailure ? 'failed' : actionStatusForTask(task.status);+ // A task that names a SUCCESSOR finished by starting something else, so it+ // is not this row's completion. The preflight card (#7258) is the case that+ // exists today: it closes the instant the review agent task is created.+ // Rebinding the row onto the successor keeps the action live — reading the+ // card's own `completed` would park the row at "Completed" and then ignore+ // every update the real review task emits, because a row binds to one task+ // id for good.+ const handedOff = task.metadata?.preflightResultTaskId || null;+ const nextStatus = task.metadata?.preflightFailure+ ? 'failed'+ : handedOff ? 'active' : actionStatusForTask(task.status);if (!nextStatus) return;replaceActions(current => {@@ -185,7 +195,14 @@ export default function PullRequestsTab({ appId, appName }) {const matches = action.taskId === task.id|| (!action.taskId && ACTION_KINDS[kind].matches(task, appId, Number(number)));if (!matches || actionRank(nextStatus) < actionRank(action.status)) continue;- updated[number] = { ...action, taskId: action.taskId || task.id, status: nextStatus, error: task.metadata?.note };+ // A hand-off re-points the row at the review task the card started;+ // every other update keeps whatever id the row already bound.+ updated[number] = {+ ...action,+ taskId: handedOff || action.taskId || task.id,+ status: nextStatus,+ error: task.metadata?.note,+ };changed = true;}next[kind] = updated;@@ -499,12 +516,21 @@ export default function PullRequestsTab({ appId, appName }) {const { label, Icon, title } = ACTION_KINDS[kind];const action = actions[kind][pullRequest.number];const actionStatus = action?.status;+ // The task record this row's run is tracked by, once it has+ // one. The preflight card gives it a task id immediately,+ // and that card is where the live pre-agent checks are+ // shown — the old link went unconditionally to the Agents+ // page, so "Queued — view" landed on a page with nothing on+ // it until an agent actually spawned.+ const taskHref = action?.taskId+ ? `/cos/tasks?task=${encodeURIComponent(action.taskId)}&source=internal`+ : null;if (actionStatus === 'failed') {return (<div key={kind} className="max-w-md text-xs text-port-error space-y-2" role="alert"><p>{action.error || (kind === 'review' ? 'PR review failed. View the failure record for details.' : 'Resolve & merge failed. View the failure record for details.')}</p><div className="flex flex-wrap gap-3">- <Link className="underline" to={`/cos/tasks?task=${encodeURIComponent(action.taskId)}&source=internal`}>View failure record</Link>+ <Link className="underline" to={taskHref}>View failure record</Link>{kind === 'review' && <Link className="underline" to="/models/llms/abuse">Abuse Guard setup</Link>}<button type="button" className="underline" onClick={() => onQueue(pullRequest)}>{kind === 'review' ? 'Retry PR review' : 'Retry resolve & merge'}</button></div>@@ -515,7 +541,7 @@ export default function PullRequestsTab({ appId, appName }) {return (<Linkkey={kind}- to="/cos/agents"+ to={taskHref || '/cos/agents'}className="px-3 py-1.5 bg-port-success/20 text-port-success hover:bg-port-success/30 border border-port-border rounded-lg text-xs flex items-center gap-1.5 transition-colors"><Icon size={14} /> {label}: {ACTION_STATUS_LABEL[actionStatus] || 'Queued — view'}diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsxindex 08229248f0..4d2eba9c95 100644--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx@@ -352,6 +352,37 @@ describe('PullRequestsTab', () => {expect(await screen.findByRole('link', { name: /PR review: Queued/ })).toBeInTheDocument();});+ // #7258: the preflight card is the programmatic phase of this row's run, and+ // it COMPLETES the moment the review agent task is created. Reading that as+ // the row's own completion would freeze it at "Completed" and ignore every+ // later update, because a row binds to one task id for good.+ it('follows a finished preflight card onto the review task it started', async () => {+ await renderTab();+ fireEvent.click(await screen.findByRole('button', { name: /PR review/ }));+ await screen.findByRole('link', { name: /PR review: Queued/ });+ act(() => socketHandlers.get('cos:tasks:changed')({ task: {+ id: 'preflight-demand-1', status: 'in_progress',+ metadata: { app: 'app-1', analysisType: 'pr-reviewer', targetPullRequest: 17,+ preflight: { phase: 'preparing', steps: [] } },+ } }));+ expect(await screen.findByRole('link', { name: /PR review: Active/ })).toBeInTheDocument();++ act(() => socketHandlers.get('cos:tasks:changed')({ task: {+ id: 'preflight-demand-1', status: 'completed',+ metadata: { app: 'app-1', analysisType: 'pr-reviewer', targetPullRequest: 17,+ preflightResultTaskId: 'app-improve-17',+ preflight: { phase: 'done', outcome: 'handed-off', steps: [] } },+ } }));+ expect(await screen.findByRole('link', { name: /PR review: Active/ })).toBeInTheDocument();++ act(() => socketHandlers.get('cos:tasks:changed')({ task: {+ id: 'app-improve-17', status: 'completed',+ metadata: { app: 'app-1', analysisType: 'pr-reviewer', targetPullRequest: 17 },+ } }));+ expect(await screen.findByRole('link', { name: /PR review: Completed/ }))+ .toHaveAttribute('href', '/cos/tasks?task=app-improve-17&source=internal');+ });+it('names a failed resolve retry as a merge action and retries that same action', async () => {api.getAppPullRequests.mockResolvedValue(okPayload([{...PULL_REQUEST,diff --git a/client/src/components/cos/tabs/PreflightProgress.jsx b/client/src/components/cos/tabs/PreflightProgress.jsxnew file mode 100644index 0000000000..185434aec4--- /dev/null+++ b/client/src/components/cos/tabs/PreflightProgress.jsx@@ -0,0 +1,62 @@+import { AlertCircle, Check, CircleDashed, Loader2, MinusCircle } from 'lucide-react';++/**+ * The live step list for the programmatic phase of a user-triggered run.+ *+ * Pressing "Run Now" (or "Review this PR") used to show nothing on the Tasks+ * page until an agent existed — which for pr-reviewer is after the whole+ * security preflight has screened every contributor diff. The server now opens+ * a card the moment the request is queued (services/preflightTaskCard.js) and+ * reports each deterministic step into it; this renders that, so the user can+ * see exactly which check is running rather than an empty page.+ *+ * The shape is owned by server/lib/preflightPlan.js.+ */++// One row per step status, so adding a status is one entry rather than an edit+// to two parallel maps that degrade silently when only one is updated.+const STEP_STYLE = {+ done: { icon: <Check size={13} aria-hidden="true" className="text-port-success" />, text: 'text-gray-300' },+ active: { icon: <Loader2 size={13} aria-hidden="true" className="text-port-accent animate-spin" />, text: 'text-white' },+ failed: { icon: <AlertCircle size={13} aria-hidden="true" className="text-port-error" />, text: 'text-port-error' },+ skipped: { icon: <MinusCircle size={13} aria-hidden="true" className="text-gray-600" />, text: 'text-gray-600' },+ pending: { icon: <CircleDashed size={13} aria-hidden="true" className="text-gray-600" />, text: 'text-gray-500' },+};++export default function PreflightProgress({ preflight, idScope, taskId }) {+ const steps = Array.isArray(preflight?.steps) ? preflight.steps : null;+ if (!steps?.length) return null;+ const running = preflight.phase === 'queued' || preflight.phase === 'preparing';+ const footer = preflight.note+ || (!running && preflight.reason ? `Reason: ${preflight.reason}` : null);++ return (+ <section+ className="mt-2 px-2 py-2 bg-port-bg border border-port-border rounded text-sm"+ aria-label="Pre-agent checks"+ aria-busy={running}+ >+ <div className="flex items-center gap-2 text-gray-300">+ <span className="font-medium">Pre-agent checks</span>+ <span className="text-xs text-gray-500">+ {running ? 'running now — no agent has started yet' : 'finished'}+ </span>+ </div>+ <ol className="mt-1 space-y-1">+ {steps.map((step) => {+ const style = STEP_STYLE[step.status] || STEP_STYLE.pending;+ return (+ <li key={`${idScope}-${taskId}-preflight-${step.key}`} className="flex items-start gap-2">+ <span className="mt-0.5 shrink-0">{style.icon}</span>+ <span className="min-w-0">+ <span className={`text-xs ${style.text}`}>{step.label}</span>+ {step.detail && <span className="block text-xs text-gray-500">{step.detail}</span>}+ </span>+ </li>+ );+ })}+ </ol>+ {footer && <p className="mt-2 text-xs text-gray-400">{footer}</p>}+ </section>+ );+}diff --git a/client/src/components/cos/tabs/PreflightProgress.test.jsx b/client/src/components/cos/tabs/PreflightProgress.test.jsxnew file mode 100644index 0000000000..3cf605feea--- /dev/null+++ b/client/src/components/cos/tabs/PreflightProgress.test.jsx@@ -0,0 +1,39 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import PreflightProgress from './PreflightProgress';++const preflight = (overrides = {}) => ({+ phase: 'preparing',+ steps: [+ { key: 'queued', label: 'Waiting for a free task slot', status: 'done', detail: null },+ { key: 'security-scan', label: 'Screening PR content for hidden Unicode and prompt injection', status: 'active', detail: 'Screening 2 pull requests through the abuse guard' },+ { key: 'dispatch', label: 'Handing off to the agent', status: 'pending', detail: null },+ ],+ ...overrides,+});++describe('PreflightProgress', () => {+ it('renders nothing for a task with no programmatic phase', () => {+ const { container } = render(<PreflightProgress preflight={undefined} idScope="cos" taskId="t-1" />);+ expect(container).toBeEmptyDOMElement();+ });++ it('names the check that is running and says no agent has started', () => {+ render(<PreflightProgress preflight={preflight()} idScope="cos" taskId="t-1" />);+ expect(screen.getByText('Screening PR content for hidden Unicode and prompt injection')).toBeInTheDocument();+ expect(screen.getByText('Screening 2 pull requests through the abuse guard')).toBeInTheDocument();+ expect(screen.getByLabelText('Pre-agent checks')).toHaveAttribute('aria-busy', 'true');+ });++ it('stops reading as busy once the phase is terminal, and surfaces the note', () => {+ render(<PreflightProgress+ preflight={preflight({ phase: 'failed', note: 'Repair the abuse guard, then retry PR review.' })}+ idScope="cos"+ taskId="t-1"+ />);+ const section = screen.getByLabelText('Pre-agent checks');+ expect(section).toHaveAttribute('aria-busy', 'false');+ expect(screen.getByText('finished')).toBeInTheDocument();+ expect(screen.getByText('Repair the abuse guard, then retry PR review.')).toBeInTheDocument();+ });+});diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 402fa0cc01..947b7cc46f 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -35,6 +35,7 @@ import InstancePicker from '../InstancePicker';import EffortSelect from '../EffortSelect';import RelaunchAgentModal from './RelaunchAgentModal';import AgentCard from './AgentCard';+import PreflightProgress from './PreflightProgress';const statusIcons = {pending: <Clock size={16} aria-hidden="true" className="text-yellow-500" />,@@ -633,6 +634,11 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spaclassName="text-sm text-gray-500 mt-1"/>)}+ <PreflightProgress+ preflight={task.metadata?.preflight}+ idScope={idScope}+ taskId={task.id}+ /><SecurityScanReportscan={task.metadata?.pipeline?.securityScan}idScope={idScope}diff --git a/server/lib/README.md b/server/lib/README.mdindex 4d652be2b5..ad9b813390 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -572,6 +572,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. || `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. || `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary, alreadyReprompted})` classifies a run that did (`merged` / `unreadable` / `leave-open-stated` / `needs-reprompt` / `reprompt-exhausted`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |+| `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. || `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. || `prReviewReport.js` | Owns the structured PR-decision contract end to end: `PR_REVIEW_DECISION_CONTRACT` is the envelope both review producers (pr-reviewer stage 3, issue-watcher reasoning pass) interpolate into their prompts, `normalizeReviewReport` bounds what comes back, `reviewReportText` hands every model-authored string to the abuse scan, and `renderReviewBody`/`renderFinding` turn it into the markdown a human reads on the PR page — verdict banner, scope line, blocking/non-blocking index anchored to `path:line`, test-evidence bullets (`TEST_EVIDENCE_STATUSES` keeps `fail` for "the change is broken", with `expected-fail` and `blocked` for the non-zero exits that say nothing about it), notes, collapsed verified-claims list, and inline comments with an optional GitHub suggestion block. Bounded by `MAX_REVIEW_BODY_CHARS`, dropping whole low-priority sections instead of truncating mid-sentence. Pure. |diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 3a49bb59b8..af8a9f63a1 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -451,7 +451,14 @@ describe('deferred imports stay deferred (#6156)', () => {// the new modules themselves rather than a new heavy subtree. There is nothing// to narrow — bufferedSpawn IS how this tree captures a subprocess's output —// so raise by exactly that delta and keep the existing headroom.-const MAX_STATIC_INSTANTIATIONS = 103384;+// The preflight task card (#7258) adds lib/preflightPlan.js — a zero-import+// leaf — and services/preflightTaskCard.js, which reaches only cosTaskStore.js+// (already in every closure that drains on-demand requests). Nearly all of the+// measured +136 is the barrel: registering the leaf in lib/index.js, which the+// module-organization rule requires, instantiates one more module in every+// closure that reaches the barrel. There is nothing to narrow — the leaf pulls+// nothing — so raise by exactly that delta and keep the existing headroom.+const MAX_STATIC_INSTANTIATIONS = 103520;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex e106d5810b..803744dc99 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -556,6 +556,7 @@ export * from './openapiDowngrade.js';export * from './orchestrationProfile.js';export * from './apiToolResource.js';export * from './mergeGateContract.js';+export * from './preflightPlan.js';export * from './prDisposition.js';export * from './prHandbackPolicy.js';export * from './prReviewReport.js';diff --git a/server/lib/preflightPlan.js b/server/lib/preflightPlan.jsnew file mode 100644index 0000000000..f1a3ba775a--- /dev/null+++ b/server/lib/preflightPlan.js@@ -0,0 +1,170 @@+/**+ * The programmatic phase of a user-triggered pipeline run, as a renderable plan.+ *+ * A "Run Now" — the scheduled-task Run button, or the PR/MR row's "Review this+ * PR" — does not become an agent task immediately. The request is queued, a+ * drain engine picks it up, and for some task types a deterministic preflight+ * runs BEFORE any agent exists: pr-reviewer lists the app's external PRs and+ * pushes their content through the model-abuse guard (hidden-Unicode and+ * prompt-injection screening) first. Until that finished, the Tasks page had+ * nothing to show and the click read as a no-op (the button said "queued" and+ * the page it linked to was empty).+ *+ * This module owns the SHAPE of that phase — the step list, the reducer that+ * advances it, and the terminal shapes — as pure data so both the writer+ * (services/preflightTaskCard.js, which persists it onto a task card) and the+ * UI render the same thing. It performs no I/O and knows nothing about tasks.+ *+ * A step is never invented by the reporter: every key a caller reports must+ * exist in the plan, so the card cannot drift into claiming work the preflight+ * does not actually do.+ */++export const PREFLIGHT_PHASES = Object.freeze({+ QUEUED: 'queued',+ PREPARING: 'preparing',+ DONE: 'done',+ FAILED: 'failed',+ INTERRUPTED: 'interrupted',+});++export const PREFLIGHT_STEP_STATUSES = Object.freeze(['pending', 'active', 'done', 'skipped', 'failed']);++const QUEUED_STEP = Object.freeze({ key: 'queued', label: 'Waiting for a free task slot' });+const DISPATCH_STEP = Object.freeze({ key: 'dispatch', label: 'Handing off to the agent' });+const DEFAULT_WORK_STEPS = Object.freeze([+ Object.freeze({ key: 'prepare', label: 'Building the task and its prompt' }),+]);++/**+ * pr-reviewer's preflight, in the order `runPrReviewerSecurityPreflight`+ * actually performs it. The security scan is the step users are waiting on and+ * the one they most need named: it is where contributor diffs are screened for+ * hidden Unicode and prompt injection before any model reads them.+ */+const PR_REVIEWER_WORK_STEPS = Object.freeze([+ Object.freeze({ key: 'cadence', label: 'Checking run cadence and park state' }),+ Object.freeze({ key: 'list-prs', label: 'Listing reviewable open pull requests' }),+ Object.freeze({ key: 'in-flight', label: 'Checking for a review already in flight' }),+ Object.freeze({ key: 'security-scan', label: 'Screening PR content for hidden Unicode and prompt injection' }),+ Object.freeze({ key: 'snapshot', label: 'Recording the screened review inputs' }),+]);++const WORK_STEPS_BY_TASK_TYPE = Object.freeze({+ 'pr-reviewer': PR_REVIEWER_WORK_STEPS,+});++export function preflightStepPlan(taskType) {+ const work = WORK_STEPS_BY_TASK_TYPE[taskType] || DEFAULT_WORK_STEPS;+ return [QUEUED_STEP, ...work, DISPATCH_STEP].map((step) => ({ ...step, status: 'pending', detail: null }));+}++/**+ * The initial persisted state. `queued` is already `active`, because the card+ * is created the moment the request is queued — that immediacy is the point.+ */+export function createPreflightState({ requestId, taskType, appId = null, appName = null, targetPullRequest = null } = {}) {+ const steps = preflightStepPlan(taskType);+ steps[0] = { ...steps[0], status: 'active' };+ const startedAt = new Date().toISOString();+ return {+ requestId: requestId || null,+ taskType: taskType || null,+ appId,+ appName,+ targetPullRequest,+ phase: PREFLIGHT_PHASES.QUEUED,+ startedAt,+ updatedAt: startedAt,+ steps,+ outcome: null,+ reason: null,+ note: null,+ resultTaskId: null,+ };+}++const isTerminal = (phase) => [PREFLIGHT_PHASES.DONE, PREFLIGHT_PHASES.FAILED, PREFLIGHT_PHASES.INTERRUPTED].includes(phase);++/**+ * Advance one step. Reporting a step `active` closes every earlier unfinished+ * step as `done`: a preflight that reached step 4 necessarily passed steps 2+ * and 3, and making each of them report twice would put the card's accuracy at+ * the mercy of an early return the reporter forgot about.+ *+ * Returns the SAME object when nothing changed (unknown key, already terminal),+ * so a caller can skip a persist rather than rewrite the task file.+ */+export function applyPreflightStep(preflight, key, { status = 'active', detail = null } = {}) {+ if (!preflight || !Array.isArray(preflight.steps) || isTerminal(preflight.phase)) return preflight;+ if (!PREFLIGHT_STEP_STATUSES.includes(status)) return preflight;+ const index = preflight.steps.findIndex((step) => step.key === key);+ if (index === -1) return preflight;++ const steps = preflight.steps.map((step, i) => {+ if (i < index) return ['pending', 'active'].includes(step.status) ? { ...step, status: 'done' } : step;+ if (i > index) return step;+ return { ...step, status, detail: detail ?? step.detail };+ });+ return {+ ...preflight,+ steps,+ phase: PREFLIGHT_PHASES.PREPARING,+ updatedAt: new Date().toISOString(),+ };+}++/**+ * Close the plan out. `outcome` is what happened to the RUN, not to a step:+ *+ * 'handed-off' → an agent task exists now; `resultTaskId` names it.+ * 'programmatic' → the request was satisfied deterministically; no agent was+ * ever needed (the programmatic on-demand handlers).+ * 'nothing-to-do'→ the preflight completed and produced no work (no external+ * PRs, already reviewed, parked).+ * 'failed' → the preflight itself could not complete.+ * 'interrupted' → the server restarted while it was running.+ *+ * Unreached steps become `skipped` rather than staying `pending`, so a finished+ * card never renders as though it were still working.+ */+export function finalizePreflight(preflight, { outcome, reason = null, note = null, resultTaskId = null } = {}) {+ if (!preflight || !Array.isArray(preflight.steps)) return preflight;+ // Already closed. The first close is the true one: a later generic "the drain+ // produced no task" must not overwrite the specific reason the preflight+ // itself recorded on the way out.+ if (isTerminal(preflight.phase)) return preflight;+ const failed = outcome === 'failed';+ const phase = failed+ ? PREFLIGHT_PHASES.FAILED+ : outcome === 'interrupted' ? PREFLIGHT_PHASES.INTERRUPTED : PREFLIGHT_PHASES.DONE;+ const steps = preflight.steps.map((step) => {+ if (step.status === 'active') return { ...step, status: failed ? 'failed' : 'done', detail: failed ? (reason || step.detail) : step.detail };+ if (step.status === 'pending') return { ...step, status: 'skipped' };+ return step;+ });+ return {+ ...preflight,+ steps,+ phase,+ outcome: outcome || null,+ reason,+ note,+ resultTaskId,+ updatedAt: new Date().toISOString(),+ };+}++/** One line naming where the run is, for the task description and the PR row. */+export function preflightHeadline(preflight) {+ if (!preflight) return null;+ if (preflight.phase === PREFLIGHT_PHASES.FAILED) return preflight.reason ? `Preflight failed: ${preflight.reason}` : 'Preflight failed';+ if (preflight.phase === PREFLIGHT_PHASES.INTERRUPTED) return 'Preflight interrupted by a server restart';+ if (preflight.phase === PREFLIGHT_PHASES.DONE) {+ if (preflight.outcome === 'handed-off') return 'Preflight passed — agent started';+ if (preflight.outcome === 'programmatic') return 'Completed without an agent';+ return 'Preflight found nothing to do';+ }+ const active = preflight.steps?.find((step) => step.status === 'active');+ return active ? active.label : 'Preparing';+}diff --git a/server/lib/preflightPlan.test.js b/server/lib/preflightPlan.test.jsnew file mode 100644index 0000000000..c6bbfc7b6a--- /dev/null+++ b/server/lib/preflightPlan.test.js@@ -0,0 +1,86 @@+import { describe, it, expect } from 'vitest';+import {+ PREFLIGHT_PHASES,+ applyPreflightStep,+ createPreflightState,+ finalizePreflight,+ preflightHeadline,+ preflightStepPlan,+} from './preflightPlan.js';++const keys = (preflight) => preflight.steps.map((step) => `${step.key}:${step.status}`);++describe('preflightPlan', () => {+ it('names pr-reviewer\'s real checks, and falls back to a generic plan for other types', () => {+ expect(preflightStepPlan('pr-reviewer').map((step) => step.key))+ .toEqual(['queued', 'cadence', 'list-prs', 'in-flight', 'security-scan', 'snapshot', 'dispatch']);+ expect(preflightStepPlan('code-quality').map((step) => step.key)).toEqual(['queued', 'prepare', 'dispatch']);+ });++ it('opens already waiting, so the card means something the instant the request is queued', () => {+ const state = createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' });+ expect(state.phase).toBe(PREFLIGHT_PHASES.QUEUED);+ expect(state.steps[0]).toMatchObject({ key: 'queued', status: 'active' });+ expect(preflightHeadline(state)).toBe('Waiting for a free task slot');+ });++ it('closes every earlier unfinished step when a later one starts', () => {+ const state = createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' });+ const scanning = applyPreflightStep(state, 'security-scan', { detail: 'Screening 2 pull requests' });+ expect(keys(scanning)).toEqual([+ 'queued:done', 'cadence:done', 'list-prs:done', 'in-flight:done',+ 'security-scan:active', 'snapshot:pending', 'dispatch:pending',+ ]);+ expect(preflightHeadline(scanning)).toBe('Screening PR content for hidden Unicode and prompt injection');+ expect(scanning.steps[4].detail).toBe('Screening 2 pull requests');+ });++ it('ignores a step key the plan does not declare, so a card cannot claim work the preflight never does', () => {+ const state = createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' });+ expect(applyPreflightStep(state, 'invent-a-check')).toBe(state);+ expect(applyPreflightStep(state, 'cadence', { status: 'bogus' })).toBe(state);+ });++ it('marks unreached steps skipped on a close, so a finished card never renders as still working', () => {+ const state = applyPreflightStep(createPreflightState({ requestId: 'd', taskType: 'pr-reviewer' }), 'list-prs');+ const closed = finalizePreflight(state, { outcome: 'nothing-to-do', reason: 'no-external-open-prs' });+ expect(closed.phase).toBe(PREFLIGHT_PHASES.DONE);+ expect(keys(closed)).toEqual([+ 'queued:done', 'cadence:done', 'list-prs:done', 'in-flight:skipped',+ 'security-scan:skipped', 'snapshot:skipped', 'dispatch:skipped',+ ]);+ expect(preflightHeadline(closed)).toBe('Preflight found nothing to do');+ });++ it('fails the step that was running, and reports its reason', () => {+ const state = applyPreflightStep(createPreflightState({ requestId: 'd', taskType: 'pr-reviewer' }), 'security-scan');+ const closed = finalizePreflight(state, { outcome: 'failed', reason: 'security-guard-unavailable' });+ expect(closed.phase).toBe(PREFLIGHT_PHASES.FAILED);+ expect(closed.steps.find((step) => step.key === 'security-scan')).toMatchObject({+ status: 'failed', detail: 'security-guard-unavailable',+ });+ expect(preflightHeadline(closed)).toBe('Preflight failed: security-guard-unavailable');+ });++ it('keeps the FIRST close: a generic drain sweep must not overwrite the specific reason', () => {+ const failed = finalizePreflight(+ applyPreflightStep(createPreflightState({ requestId: 'd', taskType: 'pr-reviewer' }), 'security-scan'),+ { outcome: 'failed', reason: 'security-guard-unavailable' },+ );+ expect(finalizePreflight(failed, { outcome: 'nothing-to-do', reason: 'idle' })).toBe(failed);+ });++ it('refuses to advance a closed card', () => {+ const closed = finalizePreflight(createPreflightState({ requestId: 'd', taskType: 'pr-reviewer' }), { outcome: 'handed-off' });+ expect(applyPreflightStep(closed, 'security-scan')).toBe(closed);+ });++ it('distinguishes a hand-off from work that never needed an agent', () => {+ const base = createPreflightState({ requestId: 'd', taskType: 'pr-reviewer' });+ expect(preflightHeadline(finalizePreflight(base, { outcome: 'handed-off', resultTaskId: 't-1' })))+ .toBe('Preflight passed — agent started');+ expect(preflightHeadline(finalizePreflight(base, { outcome: 'programmatic' }))).toBe('Completed without an agent');+ expect(preflightHeadline(finalizePreflight(base, { outcome: 'interrupted' })))+ .toBe('Preflight interrupted by a server restart');+ });+});diff --git a/server/services/cos.js b/server/services/cos.jsindex e370be98fa..bac9f3681f 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -795,8 +795,25 @@ async function resetOrphanedTasks({ bootRecovery = false } = {}) {// cooldown enforcement, and max-spawn limits (prevents runaway respawning)const { handleOrphanedTask } = await import('./agentManagement.js');+ // A programmatic-phase card (services/preflightTaskCard.js) is `in_progress`+ // with no agent BY DESIGN — it describes deterministic pre-agent work, has no+ // prompt, and must never be handed to `handleOrphanedTask`, which would flip+ // it to `pending` and spawn an agent on a task that is only a progress+ // display. A card stranded by a restart is closed as interrupted instead, and+ // one still inside its grace window is left alone: a pr-reviewer security+ // scan is minutes of real work, and reaping a live preflight would make the+ // card lie in the one direction that matters.+ const { finishPreflightCard, isPreflightCard, isStalePreflightCard } = await import('./preflightTaskCard.js');+const processOrphanedTasks = async (tasks) => {for (const task of tasks) {+ if (isPreflightCard(task)) {+ if (isStalePreflightCard(task)) {+ emitLog('info', `Closing preflight card ${task.id} — no process is still running its checks`, { taskId: task.id });+ await finishPreflightCard(task.id, { outcome: 'interrupted' });+ }+ continue;+ }if (runningAgentTaskIds.includes(task.id)) {// A local agent is actively working this task — renew its federation// lease (the heartbeat, issue #1563) so a peer sharing this task listdiff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 2f7c117e92..d776a2e9e2 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2160,7 +2160,7 @@ export async function drainProgrammaticOnDemandRequests({ taskScheduleMod, reque* user-initiated on-demand path, so the client can toast it without* background-park noise.*/-export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig }) {+export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig, preflightCardId = null }) {const appId = targetApp?.id || null;const parkInfo = await taskScheduleMod.getPerpetualParkInfo(request.taskType, appId).catch(() => null);const isDetectorDriven = taskConfig?.perpetual === true;@@ -2207,28 +2207,39 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, tif (health && !health.ok && health.remedy) forge = { cli: 'gh', remedy: health.remedy };}- // A preflight has no agent lifecycle, but an explicit failed run still needs- // a durable record. Terminal status prevents either spawn engine from running- // this diagnostic as a task; retry must enter through the security scan again.- if (request.taskType === 'pr-reviewer' && appId && reason?.startsWith('security-') && reason !== 'security-scan-report-pending') {- const note = `PR review stopped before an agent started (${reason}). No PR actions were taken. `- + (reason.startsWith('security-guard-')- ? 'Open Models → LLMs → Abuse Guard, check its setup and repair it if needed, then retry PR review. The classifier did not return a usable safety verdict; this is not a finding against the PR.'- : 'Check the repository connection and security scan configuration, then retry PR review.');- await addTask({- id: `pr-review-preflight-${request.id}`,- status: 'completed',- priority: 'MEDIUM',- priorityValue: 2,- taskType: 'internal',- description: `PR review preflight failed for ${targetApp.name}${request.targetPullRequest ? ` #${request.targetPullRequest}` : ''}`,- metadata: {- app: appId, analysisType: 'pr-reviewer',- targetPullRequest: request.targetPullRequest ?? null,- preflightFailure: reason, note,- completedAt: new Date().toISOString(),- },- }, 'internal', { raw: true, suppressDequeue: true });+ // Close the run's card — or, for an automated run that never opened one, mint+ // it in its terminal state. A preflight has no agent lifecycle, but an+ // explicit failure still needs a durable record: terminal status prevents+ // either spawn engine from running this diagnostic as a task, and a retry has+ // to enter through the security scan again. The PR row paints from the+ // `preflightFailure` + `note` this stamps.+ const securityFailure = request.taskType === 'pr-reviewer' && appId+ && reason?.startsWith('security-') && reason !== 'security-scan-report-pending';+ const { finishPreflightCard, recordPreflightOutcome } = await import('./preflightTaskCard.js');+ if (securityFailure) {+ // Minted when absent: an automated cadence run reaches the same failure with+ // no card to close, and it needs the record just as much.+ await recordPreflightOutcome({+ requestId: request.id,+ taskType: request.taskType,+ appId,+ appName: targetApp?.name || null,+ targetPullRequest: request.targetPullRequest ?? null,+ outcome: 'failed',+ reason,+ note: `PR review stopped before an agent started (${reason}). No PR actions were taken. `+ + (reason.startsWith('security-guard-')+ ? 'Open Models → LLMs → Abuse Guard, check its setup and repair it if needed, then retry PR review. The classifier did not return a usable safety verdict; this is not a finding against the PR.'+ : 'Check the repository connection and security scan configuration, then retry PR review.'),+ });+ } else {+ // An ordinary empty outcome — parked, transient, plain nothing to do. Only+ // ever closes a card that already exists: minting one for an automated run+ // nobody is watching would fill the Tasks page with cadence noise.+ await finishPreflightCard(preflightCardId, {+ outcome: 'nothing-to-do',+ reason: reason || parkInfo?.parkReason || outcome,+ });}cosEvents.emit('schedule:on-demand-empty', {@@ -2586,7 +2597,10 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {targetPullRequest = null,// Per-request provider/model/effort pin — see applyProviderModelPins.providerOverride = null,- runOverrides = null+ runOverrides = null,+ // The user's programmatic-phase card, when a human triggered this run. The+ // deterministic pre-agent work reports its progress into it.+ preflightCardId = null} = {}) {const { updateAppActivity } = await import('./appActivity.js');const taskSchedule = await import('./taskSchedule.js');@@ -2640,7 +2654,10 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {if (taskType === 'pr-reviewer') ensurePrReviewerPipeline(metadata);initializePipelineMetadata(metadata);- const securityPreflight = await runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule);+ const { preflightReporter } = await import('./preflightTaskCard.js');+ const securityPreflight = await runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule, {+ progress: preflightReporter(preflightCardId),+ });// Record (or clear a stale) skip reason in the SAME call: clearing on a passed// gate matters too, or an unrelated later idle outcome for this app (e.g. a// downstream precondition skip below) could read back a reason that no longerdiff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 495116432a..1ff0b248fa 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -1742,7 +1742,7 @@ describe('pr-reviewer security preflight wiring', () => {it('runs the direct preflight before stage gates and resolves the next-stage prompt', () => {const start = GEN_SRC.indexOf('export async function prepareManagedAppImprovementTask');const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return { task, pendingPerpetualDispatch };', start));- const preflightAt = body.indexOf('runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule)');+ const preflightAt = body.indexOf('runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule, {');const preconditionAt = body.indexOf('shouldSkipForPrecondition(metadata, app, taskType)');const promptAt = body.indexOf('getStagePrompt(taskType, currentStageIndex)');diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.jsindex abf3fb8122..8241576b0b 100644--- a/server/services/onDemandDrain.js+++ b/server/services/onDemandDrain.js@@ -33,7 +33,9 @@ import { getActiveApps } from './apps.js';import { loadState, saveState, withStateLock, isImprovementEnabled } from './cosState.js';import { markAppReviewCooldown, bindAppReviewAgent } from './appActivity.js';import { isManualOnDemandRequest, onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';+import { isUserOriginRequest } from './taskScheduleConstants.js';import { addTask, reviveBlockedTask } from './cosTaskStore.js';+import { finishPreflightCard, preflightCardId, reportPreflightStep, startPreflightCard } from './preflightTaskCard.js';/*** Drain the on-demand request queue, generating + persisting a task per request@@ -93,21 +95,61 @@ export async function drainOnDemandRequests(ctx, adapter) {}for (const request of onDemandRequests) {+ // This request's programmatic-phase card, or null for the automated origins+ // that are never carded. Derived rather than stamped on the request: the id+ // is a pure function of the request id, so every report and close site below+ // needs no branch of its own — a null id short-circuits each of them BEFORE+ // it reads the task file, which matters because an automated refill drain+ // would otherwise pay a cold whole-file parse per request just to discover+ // it has no card.+ const cardId = isUserOriginRequest(request) ? preflightCardId(request.id) : null;+// Already handled above (and its request cleared) — `onDemandRequests` is// a snapshot taken before that drain.- if (handledProgrammatically.has(request.id)) continue;+ if (handledProgrammatically.has(request.id)) {+ await finishPreflightCard(cardId, { outcome: 'programmatic' });+ continue;+ }++ // Open the card BEFORE the capacity check, so a Run that has to wait for a+ // free slot still shows up on the Tasks page as waiting. Until this existed+ // nothing appeared there until an agent task did — which for pr-reviewer is+ // after the whole security preflight — and the click read as a no-op. Only+ // a human's Run is carded: a drain refill or a quota-burn step has nobody+ // waiting on it, and carding those would fill the page with noise. Repeat+ // cycles re-enter here and `addTask` rejects the duplicate id, so a request+ // that waits several cycles keeps ONE card rather than gaining one per tick.+ if (cardId) {+ await startPreflightCard({+ requestId: request.id,+ taskType: request.taskType,+ appId: request.appId ?? null,+ appName: apps.find(app => app.id === request.appId)?.name || null,+ targetPullRequest: request.targetPullRequest ?? null,+ });+ }++ // Abandon this request: clear it from the queue and tell the user's card why.+ // One helper so the log line and the card can never name different reasons —+ // the same hand-mirroring this module's header exists to eliminate.+ const dropRequest = async (level, reason, note) => {+ emitLog(level, `On-demand request dropped — ${note}`, { requestId: request.id, taskType: request.taskType });+ await taskScheduleMod.clearOnDemandRequest(request.id);+ await finishPreflightCard(cardId, { outcome: 'failed', reason, note });+ };+if (capacityExhausted()) break;if (!isImprovementEnabled(state)) {- emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });- await taskScheduleMod.clearOnDemandRequest(request.id);+ await dropRequest('warn', 'improvement-disabled',+ 'Improvement is turned off for this install. Turn it on in Config → Improve, then run this again.');continue;}// Removed tasks never run; only automated requests honor schedule disablement.if (!schedule.tasks[request.taskType] || (!isManualOnDemandRequest(request) && !schedule.tasks[request.taskType].enabled)) {- emitLog('info', `On-demand request skipped — task type '${request.taskType}' is disabled`, { requestId: request.id });- await taskScheduleMod.clearOnDemandRequest(request.id);+ await dropRequest('info', 'task-type-disabled',+ `The scheduled task type '${request.taskType}' is disabled or no longer registered.`);continue;}@@ -123,13 +165,17 @@ export async function drainOnDemandRequests(ctx, adapter) {if (request.appId) {targetApp = apps.find(a => a.id === request.appId);if (!targetApp) {- emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });- await taskScheduleMod.clearOnDemandRequest(request.id);+ await dropRequest('warn', 'app-unknown',+ `App '${request.appId}' is no longer active, so this run has nothing to target.`);continue;}}await taskScheduleMod.clearOnDemandRequest(request.id);+ // Off the queue and into preparation. A task type with its own preflight+ // (pr-reviewer) has no `prepare` step and reports its real first step+ // moments later, so this is a no-op there rather than a competing claim.+ await reportPreflightStep(cardId, 'prepare');const preparationStartedAt = performance.now();const requestedAt = Date.parse(request.requestedAt);@@ -155,6 +201,9 @@ export async function drainOnDemandRequests(ctx, adapter) {const prepared = await prepareManagedAppImprovementTask(request.taskType, targetApp, state, {skipPreconditions: true,targetPullRequest: request.targetPullRequest ?? null,+ // The deterministic pre-agent work reports into the user's card as it+ // runs — this is the whole reason the card exists early.+ preflightCardId: cardId,providerOverride: request.providerOverride ?? null,// A quota-burn step's per-invocation run parameters. They must reach// the PROMPT, so unlike the provider/model/effort pins they cannot@@ -202,6 +251,8 @@ export async function drainOnDemandRequests(ctx, adapter) {// it to `completed` — so without excluding it the re-issued claim is// rejected as a duplicate of the run that just finished and the drain stalls.const persisted = await addTask(task, 'internal', { raw: true, ...addTaskOptions, suppressDequeue: true });+ await reportPreflightStep(cardId, 'dispatch');+ await finishPreflightCard(cardId, { outcome: 'handed-off', resultTaskId: persisted?.id || task.id });if (!persisted?.duplicate) {await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);emitSpawn(task);@@ -224,8 +275,13 @@ export async function drainOnDemandRequests(ctx, adapter) {// `userInitiated` only: a drain refill ends by converging (that's the point),// and nobody is waiting on it, so toasting "nothing to do" for every automated// hop would turn a healthy overnight drain into a pile of notifications.- await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType] });+ await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType], preflightCardId: cardId });}+ // Every other exit from this iteration (a task that capacity refused, or a+ // refill with no task) still owes the card a close — a card left open would+ // keep animating until the orphan sweep reaped it. Already-closed cards are+ // a no-op, so the specific reason each path recorded above survives.+ await finishPreflightCard(cardId, { outcome: 'nothing-to-do' });if (userInitiated) {const preparationMs = Math.round(performance.now() - preparationStartedAt);emitLog('info', `On-demand preparation finished: ${request.taskType} (${request.id}) — queue wait ${queueWaitMs ?? 'unknown'}ms, preparation ${preparationMs}ms, ${task ? 'task generated' : 'no task generated'}`, {diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.jsindex bb90b03c2d..ff99e1619e 100644--- a/server/services/onDemandDrain.test.js+++ b/server/services/onDemandDrain.test.js@@ -40,6 +40,10 @@ const mocks = vi.hoisted(() => ({applyOnDemandConsent: vi.fn((t) => t),drainProgrammaticOnDemandRequests: vi.fn(async () => new Set()),emitOnDemandEmpty: vi.fn(async () => {}),+ startPreflightCard: vi.fn(async () => {}),+ recordPreflightOutcome: vi.fn(async () => null),+ reportPreflightStep: vi.fn(async () => {}),+ finishPreflightCard: vi.fn(async () => null),}));vi.mock('./apps.js', () => ({ getActiveApps: (...a) => mocks.getActiveApps(...a) }));@@ -64,6 +68,13 @@ vi.mock('./taskSchedule.js', () => ({applyOnDemandRunResets: (...a) => mocks.applyOnDemandRunResets(...a),recordExecution: (...a) => mocks.recordExecution(...a),}));+vi.mock('./preflightTaskCard.js', () => ({+ preflightCardId: (requestId) => `preflight-${requestId}`,+ startPreflightCard: (...a) => mocks.startPreflightCard(...a),+ recordPreflightOutcome: (...a) => mocks.recordPreflightOutcome(...a),+ reportPreflightStep: (...a) => mocks.reportPreflightStep(...a),+ finishPreflightCard: (...a) => mocks.finishPreflightCard(...a),+}));vi.mock('./cosTaskGenerator.js', () => ({prepareManagedAppImprovementTask: (...a) => mocks.prepareManagedAppImprovementTask(...a),generateSelfImprovementTaskForType: (...a) => mocks.generateSelfImprovementTaskForType(...a),@@ -467,3 +478,87 @@ describe('schedule disablement at dispatch', () => {expect(spawned).toHaveLength(shouldSpawn ? 1 : 0);});});++/**+ * The programmatic-phase card (#7258). A "Run Now" used to put nothing on the+ * Tasks page until an agent task existed — which for a task type with a real+ * preflight (pr-reviewer screens every contributor diff for hidden Unicode and+ * prompt injection first) is a minute or more later, so the click read as a+ * no-op. The card is opened here, advanced by the preflight, and closed on+ * every exit from the loop.+ */+describe('preflight task card', () => {+ it('opens a card for a human Run before the capacity check, so a waiting Run is still visible', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ targetPullRequest: 42 })]);+ const { adapter } = generatorAdapter({ availableSlots: 0 });+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(mocks.startPreflightCard).toHaveBeenCalledWith({+ requestId: 'req-1', taskType: 'code-quality', appId: 'acme', appName: 'Acme App', targetPullRequest: 42,+ });+ });++ it.each([['refill'], ['quota-burn']])('opens no card for the automated origin %s', async (origin) => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ origin })]);+ const { adapter } = generatorAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(mocks.startPreflightCard).not.toHaveBeenCalled();+ // No card means no card id either: every report and close site short-circuits+ // on null rather than reading the task file to discover there is nothing there.+ expect(mocks.prepareManagedAppImprovementTask).toHaveBeenCalledWith(+ 'code-quality', APP, STATE, expect.objectContaining({ preflightCardId: null }),+ );+ expect(mocks.finishPreflightCard).not.toHaveBeenCalledWith(expect.stringContaining('preflight-'), expect.anything());+ });++ it('hands the card to the generator so the preflight reports into the card the user is watching', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ const { adapter } = generatorAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(mocks.prepareManagedAppImprovementTask).toHaveBeenCalledWith(+ 'code-quality', APP, STATE, expect.objectContaining({ preflightCardId: 'preflight-req-1' }),+ );+ });++ it('closes the card against the persisted task id once an agent task exists', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ const { adapter } = generatorAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(mocks.reportPreflightStep).toHaveBeenCalledWith('preflight-req-1', 'dispatch');+ expect(mocks.finishPreflightCard).toHaveBeenCalledWith('preflight-req-1', {+ outcome: 'handed-off', resultTaskId: 'persisted-1',+ });+ });++ it.each([+ ['improvement disabled', () => mocks.isImprovementEnabled.mockReturnValue(false), 'improvement-disabled'],+ ['task type disabled', () => mocks.loadSchedule.mockResolvedValue({ tasks: {} }), 'task-type-disabled'],+ ['unknown app', () => mocks.getActiveApps.mockResolvedValue([]), 'app-unknown'],+ ])('closes the card with a reason when the run is dropped: %s', async (_label, arrange, reason) => {+ arrange();+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ const { adapter } = generatorAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(mocks.finishPreflightCard).toHaveBeenCalledWith('preflight-req-1', expect.objectContaining({+ outcome: 'failed', reason,+ }));+ });++ it('closes a card whose request a programmatic handler satisfied without any agent', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.drainProgrammaticOnDemandRequests.mockResolvedValue(new Set(['req-1']));+ const { adapter } = generatorAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(mocks.finishPreflightCard).toHaveBeenCalledWith('preflight-req-1', { outcome: 'programmatic' });+ expect(mocks.startPreflightCard).not.toHaveBeenCalled();+ });++ it('leaves no card open when the run produces nothing', async () => {+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: null, pendingPerpetualDispatch: null });+ const { adapter } = generatorAdapter();+ await drainOnDemandRequests({ state: STATE }, adapter);+ // emitOnDemandEmpty owns the specific reason; this is the backstop close.+ expect(mocks.emitOnDemandEmpty).toHaveBeenCalledWith(expect.objectContaining({ preflightCardId: 'preflight-req-1' }));+ expect(mocks.finishPreflightCard).toHaveBeenCalledWith('preflight-req-1', { outcome: 'nothing-to-do' });+ });+});diff --git a/server/services/prReviewerPipeline.js b/server/services/prReviewerPipeline.jsindex b616780a9c..2fb6c24489 100644--- a/server/services/prReviewerPipeline.js+++ b/server/services/prReviewerPipeline.js@@ -203,9 +203,20 @@ async function findActiveSecurityScanTask(appId, scanKey) {* hook's strict envelope check) is scoped to that one PR by construction rather* than by a prompt asking the agent to ignore the rest.*/-export async function runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest = null, taskSchedule = null) {+export async function runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest = null, taskSchedule = null, { progress = null } = {}) {if (taskType !== 'pr-reviewer') return { skipped: false };+ // Report the deterministic phase into the user's task card as it happens, so+ // a run that spends a minute screening contributor diffs is visible from the+ // moment the button was pressed rather than only once an agent exists. A run+ // with no card (an automated cadence sweep) passes no reporter and every+ // call below is a no-op. Failure to paint the card must never stop the scan.+ const step = async (key, options) => {+ if (!progress) return;+ await progress(key, options).catch((err) => console.error(`❌ Preflight progress for '${key}' could not be recorded: ${err.message}`));+ };+ await step('cadence');+// A churn park has to be a STOP, not just a log line (#6124). pr-reviewer runs// on the ON_DEMAND cadence, and `shouldRunTask` only reads `parkedUntil` on a// `perpetual` interval — so the park `observeAgentChurn` stamps when a stage@@ -232,6 +243,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, taconst { listExternalOpenPullRequests, runPrReviewerSecurityScan, securityScanFingerprint } = await import('./prReviewerSecurity.js');const { writePublicReviewInputSnapshot } = await import('./modelAbuseGuard.js');+ await step('list-prs', targetPullRequest ? { detail: `Scoped to pull request #${targetPullRequest}` } : undefined);let target = await listExternalOpenPullRequests(app);if (!target.ok) {const reason = target.code || 'security-scan-target-unavailable';@@ -262,6 +274,8 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta};metadata.targetPullRequest = targetPullRequest;}+ await step('list-prs', { status: 'done', detail: `${target.prs.length} reviewable pull request${target.prs.length === 1 ? '' : 's'}` });+ await step('in-flight');const scanKey = securityScanFingerprint(target);const active = await findActiveSecurityScanTask(app.id, scanKey);if (active.unavailable) {@@ -274,6 +288,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, tareturn { skipped: true, reason: 'security-scan-report-pending', task: active.task };}+ await step('security-scan', { detail: `Screening ${target.prs.length} pull request${target.prs.length === 1 ? '' : 's'} through the abuse guard` });const scan = await runPrReviewerSecurityScan({app,target,@@ -301,6 +316,12 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta}const status = !scan.ok ? 'unavailable' : (scan.passed ? 'passed' : 'findings');+ const flagged = reports.filter((report) => !reportIsSafe(report)).length;+ await step('security-scan', {+ status: 'done',+ detail: `Scan ${status} — ${reports.length} screened, ${flagged} flagged`,+ });+ await step('snapshot');const snapshotWritten = await writePublicReviewInputSnapshot({scanKey: scan.scanKey || scanKey,pullRequests: scan.ok ? (scan.reviewInputs || []) : [],@@ -310,6 +331,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, taemitLog('warn', `Skipping pr-reviewer for ${app.name}: ${reason}`, { appId: app.id, analysisType: taskType });return { skipped: true, reason };}+ await step('snapshot', { status: 'done', detail: `${reports.length} report${reports.length === 1 ? '' : 's'} recorded` });const reviewOutput = buildSecurityScanPipelineOutput(scan, reports, status);// A partial/unavailable scan is never a usable allowlist. Keeping already// safe-looking reports here would let a later stage review a subset whilediff --git a/server/services/prReviewerPipeline.test.js b/server/services/prReviewerPipeline.test.jsindex 245210a878..3cf2941c71 100644--- a/server/services/prReviewerPipeline.test.js+++ b/server/services/prReviewerPipeline.test.js@@ -431,6 +431,52 @@ describe('runPrReviewerSecurityPreflight', () => {expect(guardMock.writePublicReviewInputSnapshot).not.toHaveBeenCalled();});+ // #7258: the whole preflight runs before any agent exists, so the Tasks page+ // had nothing to show while contributor diffs were being screened. The card is+ // driven from HERE — the one place that knows which check is actually running.+ it('reports each check into the run card as it happens, naming the screening step', async () => {+ listed(externalPr(12, HEAD_12), externalPr(13, HEAD_13));+ securityMock.runPrReviewerSecurityScan.mockResolvedValue(scanResult({+ reports: [report(12, HEAD_12, true), report(13, HEAD_13, false)],+ reviewInputs: [reviewInput(12, HEAD_12)],+ passed: false,+ }));+ const progress = vi.fn(async () => {});+ await runPrReviewerSecurityPreflight('pr-reviewer', APP, preflightMetadata(), null, schedule(), { progress });++ const keys = progress.mock.calls.map(([key]) => key);+ expect(keys).toEqual(['cadence', 'list-prs', 'list-prs', 'in-flight', 'security-scan', 'security-scan', 'snapshot', 'snapshot']);+ const scanStart = progress.mock.calls.find(([key, options]) => key === 'security-scan' && options?.status !== 'done');+ expect(scanStart[1].detail).toBe('Screening 2 pull requests through the abuse guard');+ const scanDone = progress.mock.calls.find(([key, options]) => key === 'security-scan' && options?.status === 'done');+ expect(scanDone[1].detail).toBe('Scan findings — 2 screened, 1 flagged');+ });++ it('names the single request a targeted run covers, and reports nothing when no card is watching', async () => {+ listed(externalPr(12, HEAD_12), externalPr(13, HEAD_13));+ securityMock.runPrReviewerSecurityScan.mockResolvedValue(scanResult({+ reports: [report(12, HEAD_12, true)], reviewInputs: [reviewInput(12, HEAD_12)],+ }));+ const progress = vi.fn(async () => {});+ await runPrReviewerSecurityPreflight('pr-reviewer', APP, preflightMetadata(), 12, schedule(), { progress });+ expect(progress).toHaveBeenCalledWith('list-prs', { detail: 'Scoped to pull request #12' });++ // An automated cadence sweep passes no reporter; the scan must run regardless.+ securityMock.runPrReviewerSecurityScan.mockClear();+ await runPrReviewerSecurityPreflight('pr-reviewer', APP, preflightMetadata(), 12, schedule());+ expect(securityMock.runPrReviewerSecurityScan).toHaveBeenCalledTimes(1);+ });++ it('keeps the scan running when the card cannot be painted', async () => {+ listed(externalPr(12, HEAD_12));+ securityMock.runPrReviewerSecurityScan.mockResolvedValue(scanResult({+ reports: [report(12, HEAD_12, true)], reviewInputs: [reviewInput(12, HEAD_12)],+ }));+ const progress = vi.fn(async () => { throw new Error('task file is locked'); });+ const result = await runPrReviewerSecurityPreflight('pr-reviewer', APP, preflightMetadata(), null, schedule(), { progress });+ expect(result.skipped).toBe(false);+ });+it('passes every other task type straight through', async () => {const metadata = {};await expect(runPrReviewerSecurityPreflight('claim-work', APP, metadata, null, schedule())).resolves.toEqual({ skipped: false });diff --git a/server/services/preflightTaskCard.js b/server/services/preflightTaskCard.jsnew file mode 100644index 0000000000..bc77794bd7--- /dev/null+++ b/server/services/preflightTaskCard.js@@ -0,0 +1,208 @@+/**+ * The task card for the programmatic phase of a user-triggered run.+ *+ * Pressing "Run Now" on a scheduled task, or "Review this PR" on an app's+ * PRs/MRs tab, queues an on-demand request. Nothing appeared on the Tasks page+ * until an agent task existed — which, for pr-reviewer, is after the whole+ * deterministic preflight has run (list the external PRs, screen every diff+ * through the model-abuse guard). The click therefore read as a no-op: the+ * button said "queued" and the page it linked to was empty.+ *+ * So a card is written the moment the request is queued, and the preflight+ * reports into it as it goes. The card is a normal internal task carrying+ * `metadata.preflight` (shape owned by lib/preflightPlan.js), which is what the+ * Tasks page renders as a live step list and what tells the PR row which run+ * its button started.+ *+ * Two properties keep it from becoming a fake agent task:+ *+ * - It is created `in_progress`, never `pending`, so no spawn engine can+ * admit it — a card has no prompt and no agent, and never will.+ * - `metadata.preflight` marks it for the orphan sweep, which finishes a+ * stale card as `interrupted` instead of requeueing it onto an agent+ * (cos.js#resetOrphanedTasks).+ *+ * Every write here is best-effort: a card is UI, and losing one must never+ * take down the run it describes.+ */++import { applyPreflightStep, createPreflightState, finalizePreflight, preflightHeadline } from '../lib/preflightPlan.js';+import { addTask, getTaskById, updateTask } from './cosTaskStore.js';++/**+ * How long a card may sit `in_progress` before the orphan sweep calls it+ * interrupted. Generous on purpose: a pr-reviewer security scan over a busy+ * repo is minutes of real model work, and reaping a live preflight would make+ * the card lie in the one direction that matters.+ */+export const PREFLIGHT_CARD_STALE_MS = 15 * 60 * 1000;++export const preflightCardId = (requestId) => `preflight-${requestId}`;++export const isPreflightCard = (task) => Boolean(task?.metadata?.preflight?.requestId);++function cardDescription(preflight) {+ const target = preflight.targetPullRequest ? ` #${preflight.targetPullRequest}` : '';+ const scope = preflight.appName ? ` for ${preflight.appName}` : '';+ return `Preparing ${preflight.taskType}${scope}${target}: ${preflightHeadline(preflight)}`;+}++/**+ * Create the card for a queued on-demand request. Callers address the card by+ * `preflightCardId(requestId)` rather than by a return value: the drain re-enters+ * this on a later cycle for a request still waiting on a slot, and `addTask`+ * rejects the repeat as a duplicate id — so a request keeps ONE card, and every+ * report and close site can derive the id without threading one around.+ */+export async function startPreflightCard({ requestId, taskType, appId = null, appName = null, targetPullRequest = null } = {}) {+ if (!requestId || !taskType) return;+ const preflight = createPreflightState({ requestId, taskType, appId, appName, targetPullRequest });+ const id = preflightCardId(requestId);+ await addTask({+ id,+ status: 'in_progress',+ priority: 'HIGH',+ priorityValue: 3,+ taskType: 'internal',+ description: cardDescription(preflight),+ metadata: {+ ...(preflight.appId ? { app: preflight.appId } : {}),+ ...(preflight.appName ? { appName: preflight.appName } : {}),+ analysisType: taskType,+ ...(targetPullRequest ? { targetPullRequest } : {}),+ preflight,+ },+ }, 'internal', { raw: true, suppressDequeue: true }).catch((err) => {+ console.error(`❌ Could not open a preflight card for ${taskType}: ${err.message}`);+ });+}++async function writePreflight(cardId, next) {+ if (!next) return null;+ return updateTask(cardId, {+ description: cardDescription(next),+ metadata: { preflight: next },+ }, 'internal', { suppressDequeue: true }).catch((err) => {+ console.error(`❌ Could not update preflight card ${cardId}: ${err.message}`);+ return null;+ });+}++async function readPreflight(cardId) {+ if (!cardId) return null;+ const task = await getTaskById(cardId).catch(() => null);+ return task?.metadata?.preflight || null;+}++/**+ * Report one programmatic step. Unknown step keys and already-finished cards+ * are no-ops that write nothing — see `applyPreflightStep`.+ */+export async function reportPreflightStep(cardId, key, { status = 'active', detail = null } = {}) {+ const preflight = await readPreflight(cardId);+ if (!preflight) return;+ const next = applyPreflightStep(preflight, key, { status, detail });+ if (next === preflight) return;+ await writePreflight(cardId, next);+}++/**+ * A reporter bound to one card, for code that must not import the task store —+ * `runPrReviewerSecurityPreflight` takes one of these so the pipeline contract+ * stays testable without a task file. Returns a no-op when there is no card, so+ * call sites never branch on it.+ */+export function preflightReporter(cardId) {+ if (!cardId) return () => Promise.resolve();+ return (key, options) => reportPreflightStep(cardId, key, options);+}++/**+ * Close the card out. `outcome` is one of 'handed-off' | 'nothing-to-do' |+ * 'failed' | 'interrupted' (lib/preflightPlan.js).+ *+ * `preflightFailure` is stamped alongside for a failed outcome because the PR+ * row reads that key to paint its "review failed" state — the same contract the+ * standalone failure task used before the card existed.+ */+export async function finishPreflightCard(cardId, { outcome, reason = null, note = null, resultTaskId = null } = {}) {+ const preflight = await readPreflight(cardId);+ if (!preflight) return null;+ const next = finalizePreflight(preflight, { outcome, reason, note, resultTaskId });+ // `finalizePreflight` returns the same object for an already-closed card, and+ // a second close is expected: the drain closes generically after a path that+ // already closed with the specific reason. Writing again would only re-stamp+ // the task and re-emit `tasks:changed`.+ if (next === preflight) return null;+ return updateTask(cardId, {+ status: 'completed',+ description: cardDescription(next),+ metadata: {+ preflight: next,+ ...(outcome === 'failed' ? { preflightFailure: reason, note } : {}),+ ...(resultTaskId ? { preflightResultTaskId: resultTaskId } : {}),+ completedAt: new Date().toISOString(),+ },+ }, 'internal', { suppressDequeue: true }).catch((err) => {+ console.error(`❌ Could not close preflight card ${cardId}: ${err.message}`);+ return null;+ });+}++/**+ * Record a terminal preflight outcome whether or not a card was ever opened.+ *+ * A run that failed its preflight needs a durable record for the user and for+ * the PR row's `preflightFailure` contract — but only a HUMAN's Run opens a card+ * up front, so an automated cadence run reaching the same failure has nothing to+ * close. Minting the card in its terminal state here keeps that one event to ONE+ * shape: before this, the generator wrote a separate standalone task for the+ * uncarded case, so the same failure looked like two different records depending+ * on who triggered it, and two writers had to agree on the same metadata keys.+ */+export async function recordPreflightOutcome({+ requestId, taskType, appId = null, appName = null, targetPullRequest = null,+ outcome, reason = null, note = null,+} = {}) {+ if (!requestId || !taskType) return null;+ const cardId = preflightCardId(requestId);+ const closed = await finishPreflightCard(cardId, { outcome, reason, note });+ if (closed) return closed;++ const preflight = finalizePreflight(+ createPreflightState({ requestId, taskType, appId, appName, targetPullRequest }),+ { outcome, reason, note },+ );+ return addTask({+ id: cardId,+ status: 'completed',+ priority: 'MEDIUM',+ priorityValue: 2,+ taskType: 'internal',+ description: cardDescription(preflight),+ metadata: {+ ...(appId ? { app: appId } : {}),+ ...(appName ? { appName } : {}),+ analysisType: taskType,+ ...(targetPullRequest ? { targetPullRequest } : {}),+ preflight,+ ...(outcome === 'failed' ? { preflightFailure: reason, note } : {}),+ completedAt: new Date().toISOString(),+ },+ }, 'internal', { raw: true, suppressDequeue: true }).catch((err) => {+ console.error(`❌ Could not record the preflight outcome for ${taskType}: ${err.message}`);+ return null;+ });+}++/**+ * Has this card been sitting unfinished long enough that the process running it+ * is certainly gone? Read by the orphan sweep, which must distinguish a live+ * multi-minute security scan from a card stranded by a restart.+ */+export function isStalePreflightCard(task, now = Date.now()) {+ const preflight = task?.metadata?.preflight;+ if (!preflight) return false;+ const stamp = Date.parse(preflight.updatedAt || preflight.startedAt || '');+ return !Number.isFinite(stamp) || (now - stamp) > PREFLIGHT_CARD_STALE_MS;+}diff --git a/server/services/preflightTaskCard.test.js b/server/services/preflightTaskCard.test.jsnew file mode 100644index 0000000000..6e9f9b5149--- /dev/null+++ b/server/services/preflightTaskCard.test.js@@ -0,0 +1,115 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++vi.mock('./cosTaskStore.js', () => ({+ addTask: vi.fn(),+ getTaskById: vi.fn(),+ updateTask: vi.fn(),+}));++const { addTask, getTaskById, updateTask } = await import('./cosTaskStore.js');+const {+ PREFLIGHT_CARD_STALE_MS,+ finishPreflightCard,+ isPreflightCard,+ isStalePreflightCard,+ preflightCardId,+ preflightReporter,+ recordPreflightOutcome,+ reportPreflightStep,+ startPreflightCard,+} = await import('./preflightTaskCard.js');++const cardFor = (preflight) => ({ id: preflightCardId('demand-1'), metadata: { preflight } });++beforeEach(() => {+ vi.clearAllMocks();+ addTask.mockResolvedValue({ id: preflightCardId('demand-1') });+ updateTask.mockResolvedValue({ id: preflightCardId('demand-1') });+});++describe('preflightTaskCard', () => {+ it('opens the card in_progress so no spawn engine can admit a task with no prompt', async () => {+ await startPreflightCard({ requestId: 'demand-1', taskType: 'pr-reviewer', appId: 'portos', appName: 'PortOS', targetPullRequest: 42 });+ const [task, taskType, options] = addTask.mock.calls[0];+ expect(task.status).toBe('in_progress');+ expect(taskType).toBe('internal');+ expect(options).toMatchObject({ raw: true, suppressDequeue: true });+ // The PR/MR row finds the run its button started through these three keys.+ expect(task.metadata).toMatchObject({ app: 'portos', analysisType: 'pr-reviewer', targetPullRequest: 42 });+ expect(task.description).toContain('PortOS');+ expect(task.metadata.preflight.steps[0]).toMatchObject({ key: 'queued', status: 'active' });+ });++ it('writes nothing when there is no card — an automated run carries no reporter branch', async () => {+ getTaskById.mockResolvedValue(null);+ await reportPreflightStep('preflight-missing', 'security-scan');+ await finishPreflightCard('preflight-missing', { outcome: 'handed-off' });+ expect(updateTask).not.toHaveBeenCalled();+ const readsBefore = getTaskById.mock.calls.length;+ await preflightReporter(null)('security-scan');+ expect(getTaskById.mock.calls.length).toBe(readsBefore);+ });++ it('persists the advanced step and re-headlines the card', async () => {+ const { createPreflightState } = await import('../lib/preflightPlan.js');+ getTaskById.mockResolvedValue(cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer', appName: 'PortOS' })));+ await reportPreflightStep(preflightCardId('demand-1'), 'security-scan', { detail: '2 screened' });+ const [, updates] = updateTask.mock.calls[0];+ expect(updates.description).toContain('hidden Unicode');+ expect(updates.metadata.preflight.steps.find(step => step.key === 'security-scan')).toMatchObject({ status: 'active', detail: '2 screened' });+ });++ it('stamps preflightFailure on a failed close, the key the PR row paints from', async () => {+ const { createPreflightState } = await import('../lib/preflightPlan.js');+ getTaskById.mockResolvedValue(cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' })));+ await finishPreflightCard(preflightCardId('demand-1'), { outcome: 'failed', reason: 'security-guard-unavailable', note: 'Repair the guard.' });+ const [, updates] = updateTask.mock.calls[0];+ expect(updates.status).toBe('completed');+ expect(updates.metadata).toMatchObject({ preflightFailure: 'security-guard-unavailable', note: 'Repair the guard.' });+ });++ it('writes once for a second close, so a generic sweep cannot re-stamp a card', async () => {+ const { createPreflightState, finalizePreflight } = await import('../lib/preflightPlan.js');+ const closed = finalizePreflight(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' }), { outcome: 'handed-off', resultTaskId: 't-1' });+ getTaskById.mockResolvedValue(cardFor(closed));+ expect(await finishPreflightCard(preflightCardId('demand-1'), { outcome: 'nothing-to-do' })).toBeNull();+ expect(updateTask).not.toHaveBeenCalled();+ });++ it('mints a terminal card for a run that never opened one, so one failure is one record', async () => {+ getTaskById.mockResolvedValue(null);+ await recordPreflightOutcome({+ requestId: 'demand-1', taskType: 'pr-reviewer', appId: 'portos', appName: 'PortOS', targetPullRequest: 42,+ outcome: 'failed', reason: 'security-guard-unavailable', note: 'Repair the guard.',+ });+ const [task, taskType, options] = addTask.mock.calls[0];+ expect(task.id).toBe('preflight-demand-1');+ expect(task.status).toBe('completed');+ expect(taskType).toBe('internal');+ expect(options).toMatchObject({ raw: true, suppressDequeue: true });+ expect(task.metadata).toMatchObject({+ app: 'portos', analysisType: 'pr-reviewer', targetPullRequest: 42,+ preflightFailure: 'security-guard-unavailable', note: 'Repair the guard.',+ });+ expect(task.metadata.preflight.phase).toBe('failed');+ });++ it('closes the existing card instead of minting a second record', async () => {+ const { createPreflightState } = await import('../lib/preflightPlan.js');+ getTaskById.mockResolvedValue(cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' })));+ await recordPreflightOutcome({ requestId: 'demand-1', taskType: 'pr-reviewer', outcome: 'failed', reason: 'security-guard-unavailable' });+ expect(updateTask).toHaveBeenCalledTimes(1);+ expect(addTask).not.toHaveBeenCalled();+ });++ it('treats a card as stale only once nothing could still be running it', async () => {+ const { createPreflightState } = await import('../lib/preflightPlan.js');+ const fresh = cardFor(createPreflightState({ requestId: 'demand-1', taskType: 'pr-reviewer' }));+ expect(isPreflightCard(fresh)).toBe(true);+ expect(isPreflightCard({ metadata: {} })).toBe(false);+ expect(isStalePreflightCard(fresh)).toBe(false);+ // A multi-minute security scan is live work; only a restart leaves one older than the grace.+ expect(isStalePreflightCard(fresh, Date.now() + PREFLIGHT_CARD_STALE_MS + 1)).toBe(true);+ expect(isStalePreflightCard(cardFor({ requestId: 'd', steps: [], updatedAt: 'nonsense' }))).toBe(true);+ });+});