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 release-gate findings: bench real usage limits, gate PR merges on auto-run, keep old Stacker News hashes valid
[._.]/ Adam Eivy49222d1cfa3c
diff --git a/.changelog/v2.40.0.md b/.changelog/v2.40.0.mdindex 5d7ca383eb..43e9aedb3a 100644--- a/.changelog/v2.40.0.md+++ b/.changelog/v2.40.0.md@@ -13,7 +13,7 @@ Released: 2026-08-08**Agent reliability**- A provider that goes down mid-queue no longer takes every waiting task with it — provider-attributable failures now sideline that provider for a cooldown scaled to the cause, so retries land on a fallback instead of repeating the same three-second death.- Grok and Kimi agents actually start now, and an agent that fails to spawn reports the real reason immediately instead of sitting in "initializing" until a sweeper calls it a crash.-- Pull requests opened under a "merge when CI is green" policy get merged again; the watch no longer depends on an optional scheduled task that ships disabled.+- Pull requests opened under a "merge when CI is green" policy get merged again; the watch no longer depends on an optional scheduled task that ships disabled. It currently drains on CoS evaluation — daemon start and an explicit Evaluate — so a PR that turns green mid-session may wait for the next one; giving it its own timer is tracked in #3630. It also now honors the auto-run mode, so `off` and `dry-run` no longer merge.**Code review**- Every reviewer row can pin a reasoning-effort tier alongside its model, offering only the tiers that reviewer's CLI actually accepts.@@ -56,6 +56,9 @@ Released: 2026-08-08- **Updated documentation index and feature references.** Added missing feature deep dive links for Quota-burn automation (`QUOTA-BURN.md`), Three.js procedural 3D models (`THREEJS_MODELS.md`), Stacker News stewardship (`stacker-news.md`), and the PortDeck native companion app API contract (`COMPANION_APP_API.md`) across `README.md` and `docs/README.md`. Improved inline JSDoc comments for client and server utility modules.## Fixed+- **A genuine Claude usage limit sidelines the provider again.** The provider-sidelining gate above keys on whether the failure came from the *provider* rather than from the agent's own output — which is right, but the detector only granted that provenance to a few phrasings, and Claude Code's actual banners ("Claude usage limit reached. Your limit will reset at 5pm.", "5-hour limit reached · resets 3am") were not among them. So the exact case the sideline exists for — a five-hour window opening mid-queue — was the one it missed, and every subsequent task re-picked the dead provider and died the same way. Those vendor-branded banners are now recognized as provider chrome. Generic phrasings a task's own failing test can print ("quota exceeded", "daily limit") are deliberately still NOT promoted, so an agent's transcript cannot sideline a healthy provider.+- **Auto-run set to `off` or `dry-run` no longer merges pull requests.** The pending-merge drain that keeps "merge when CI is green" PRs moving ran whenever CoS was not globally paused — but it did not consult the auto-run mode, so the one action that writes to a default branch was also the one action a user could not switch off, including on the evaluation that runs at boot. It now requires auto-run to be in `execute`, like every other autonomous tier.+- **Upgrading with Stacker News items already stored no longer re-sorts the whole triage list.** This release folded a post's image URLs into the digest that decides whether an item changed since the last sync, which changes that digest for every row already on disk. The first sync after upgrading would therefore have treated the entire back catalogue as freshly changed — re-running analysis on all of it, re-stamping arrival times, and pushing months of old items to the top of the queue — while any action already awaiting or holding review would have failed permanently with "Source content changed after review" about content that had not changed. Both comparisons now accept the previous digest as equal, and each row quietly adopts the new one the next time it is seen.- **A provider that goes down mid-queue no longer takes every waiting task with it.** When an agent run failed because the *provider* failed, PortOS sidelined that provider only if the failure was a usage or rate limit. Every other provider-side failure — an expired credential, a refused account, an Antigravity install still waiting on Google to verify eligibility — left it marked healthy, so the next task off the queue picked the same provider and died the same way, and the next, and the next. The most visible version: `agy` reporting "We're finishing verifying your account eligibility… please try again shortly" would burn down a whole queue of tasks in about a minute, each in three seconds, with nothing to show for it. A failure the run can attribute to the provider itself now sidelines it for a cooldown scaled to the cause (minutes for a transient block, longer for something needing a human), which is what makes the retries land on a fallback provider instead of repeating the failure; the sideline expires on its own, so the provider comes back without anyone visiting settings. Failures that describe the *request* rather than the provider — a bad model id, a content refusal, an off-shape response — still never sideline anything, since the provider's other models are fine. And a failure diagnosed only by keyword-matching the agent's own transcript can't sideline a provider either; that takes a structured signal from the provider itself. One shared cooldown policy now answers this for both agent runs and one-shot prompts, which previously disagreed about how long the same failure was worth.- **The Antigravity account-verification banner no longer blocks the task it interrupts.** PortOS recognized the banner and failed the run promptly rather than waiting out the idle reaper, but filed it as something a human had to fix — which blocked the task outright, over a condition whose own error message says it clears itself. It now takes the ordinary retry path, which (with the provider sidelined per the entry above) lands on a fallback rather than re-reading the same banner three seconds later.- **A `--model` you baked into a TUI provider's own arguments is now honored instead of silently overridden.** The CoS-agent TUI spawn path respected a hand-pinned `--model` for OpenCode providers only; for every other TUI it appended the UI's model choice as a *second* `--model` flag, and last-flag-wins meant your pin was quietly discarded (or the CLI rejected the duplicate outright). It now honors the pin for every provider, matching what the one-shot TUI path and the CLI path already did, and what the rest of the app documents. This only affects providers whose saved arguments hand-pin a model — no shipped provider does.@@ -73,6 +76,7 @@ Released: 2026-08-08- **[issue-3618] Adding a coding-agent provider is now one table row instead of eight coordinated edits.** Teaching PortOS about a new vendor's CLI/TUI meant editing open-coded dispatch branches across five files — argv builders, prompt-delivery rules, TUI posture flags, the command allowlist — and two of those sites (the TUI model-injection paths) had already drifted apart once before being collapsed into a shared helper. A `PROVIDER_VENDORS` registry now holds one row per vendor (claude, codex, antigravity, opencode, grok, kimi, cursor), and every one of those dispatch points reads from it instead of hand-rolling its own if-chain. No vendor's argv-building logic changed — this only relocates dispatch, verified against the full existing test suite plus a byte-for-byte check that the derived command allowlist still matches the prior hand-maintained list exactly.- **The six provider-seed migrations share one shell instead of six copies of it.** Every migration that ships a new AI provider to already-installed setups (OpenCode Ollama, its TUI sibling, Grok, Cerebras, Kimi, Cursor) repeated the same byte-identical read → validate → add-missing-ids → write body, so any hardening of it was a six-file sweep nobody did — and none of the six had picked up the reserved-key guard (`__proto__` / `constructor` / `prototype`) the split-migration family already applies. They now call a shared `makeProviderSeedMigration` factory that carries that guard, and each migration keeps only its own frozen provider payload, since a migration is the historical record of what it installed. Their duplicated shell tests collapse into one suite against the factory; every payload assertion each migration already made still runs unchanged.- **Whether a provider can refresh its model list is now the server's answer, not the client's guess.** The "Refresh Models" button used to be gated by a hand-written client-side re-derivation of the server's model-refresh dispatch — a mirror kept in step by a comment, backed by a parity test that transcribed the same dispatch a *second* time (so it only ever proved the mirror matched the test's copy). It drifted, silently, in both directions: too generous showed a button that errored on every click, too stingy hid the feature with no error at all. A gemini provider configured by absolute path was in the second bucket. The server now derives the answer from one per-vendor table and sends it on the providers payload as `canRefreshModels`; the client just reads it. The three keying conventions that had accumulated as prose above each branch (exact command string, path-tolerant command basename, display-name substring — and which of them a TUI provider is allowed to use) are columns in that table now, so adding the next vendor is one row instead of four coordinated edits across two repos' worth of files. The field is computed per response and never stored, so it can't go stale against the dispatch it describes. No shipped provider's button visibility changes; the one behavior that does is that a provider whose *command* is literally `gemini` now refreshes as gemini even if someone named it "Claude Something", which is the same "an exact command beats a display-name substring" rule the dispatch had already grown for cursor and Antigravity.+- **Federated peers stop mis-grading each other's one-off agent runs across this version boundary.** Two of this release's task-metadata additions — the `workTracker` dispatch marker and the per-reviewer `reviewerEfforts` pins — change how a task *runs*, not how it validates, so an older peer accepts a synced task and then executes it wrong: it doesn't know the tracker marker exempts a run from the "did it leave a commit?" check, so a run that correctly filed issues and left the tree clean is graded a failure, dragged through that provider's learning bucket, and pushed back onto the newer machine as damaged state. The `cosTasks` wire version bumps 3 → 4 so a machine still on v2.39.x gently pauses cos-task sync with a clear "schema ahead" log until it upgrades, instead of silently corrupting run outcomes. Only cos-task sync pauses; every other sync category is unaffected.## Full Changelogdiff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 0b6907b718..19bcc7df1f 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -38,11 +38,17 @@ import { normalizeUrl as normalizeUrlShared } from '../../../utils/urlNormalize'/*** True once a link has a malware-scan report that can actually be opened. A- * capture-time scan is stamped `queued` before the agent runs — it has a- * reportId but no file yet, so the "Scan Reports" filter must not offer it.- * Legacy records carry no `status` at all and are treated as readable.+ * capture-time scan is stamped `queued` before the agent runs, and a scan whose+ * agent never wrote a report file finalizes as `failed` — both carry a reportId+ * with no file behind it, so the "Scan Reports" filter must not offer either+ * (the report route would 404). Legacy records carry no `status` at all and are+ * treated as readable.*/-const hasScanReport = (link) => Boolean(link.malwareScan?.reportId) && link.malwareScan.status !== 'queued';+const hasScanReport = (link) => {+ if (!link.malwareScan?.reportId) return false;+ const { status } = link.malwareScan;+ return status === undefined || status === 'completed';+};/** Normalize a user-entered URL the way the quick-add form does. */function normalizeUrl(raw) {@@ -693,14 +699,20 @@ export default function LinksTab({ onRefresh }) {)}{/* A capture-time scan is stamped `queued` before the agent runs,- so there is no report to open yet — say so instead of linking- at a 404. finalizeMalwareScan flips it once the run lands. */}+ and `failed` when the run landed without writing a report —+ neither has a file to open, so say so instead of linking at a+ 404. finalizeMalwareScan flips it once the run lands. */}{link.malwareScan?.status === 'queued' ? (<span className="flex items-center gap-1 text-xs text-gray-400" title="Malware scan queued — track it in Chief of Staff"><ShieldCheck size={12} />Scan queued</span>- ) : link.malwareScan?.reportId && (+ ) : link.malwareScan?.status === 'failed' ? (+ <span className="flex items-center gap-1 text-xs text-port-error" title="Malware scan finished without producing a report — re-run it from Chief of Staff">+ <ShieldCheck size={12} />+ Scan failed+ </span>+ ) : hasScanReport(link) && (<Linkto={api.brainScanReportPath(link.id)}className={`flex items-center gap-1 text-xs ${link.malwareScan.verdict === 'DANGEROUS' ? 'text-port-error' : 'text-port-accent'} hover:underline`}diff --git a/client/src/pages/X.jsx b/client/src/pages/X.jsxindex 2f5e94a658..11e813afed 100644--- a/client/src/pages/X.jsx+++ b/client/src/pages/X.jsx@@ -63,7 +63,15 @@ export default function XPage() {const accountPath = (id, tab = activeRouteTab) => `/x/${id}/${tab}`;const accountFormMode = searchParams.get('xAccount');const accountDrawerOpen = accountFormMode === 'new' || (accountFormMode === 'edit' && Boolean(selected));- const accountFormDirty = accountFormMode === 'edit' && !sameAccount(accountForm, savedAccountForm);+ // The diagnostic and "open on X" actions resolve `account.username` SERVER-side+ // from the saved record, so an unsaved handle edit would silently run against the+ // old handle while the form shows the new one. Dirtiness is deliberately NOT+ // scoped to `accountFormMode === 'edit'`: closing the drawer keeps the draft, so+ // the mismatch outlives the drawer. Mirrors StackerNews.jsx's gate.+ const accountFormDirty = Boolean(selected) && !sameAccount(accountForm, savedAccountForm);+ const accountActionsDisabled = accountFormDirty || Boolean(busy);+ const discardAccountEdits = () => { setAccountForm(savedAccountForm); setAccountFormError(''); };+ const unsavedAccountNotice = accountFormDirty && <div className="mt-4 flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/10 p-3"><p className="text-sm text-port-warning">Unsaved changes to this account. Save it before running these checks.</p><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={discardAccountEdits}>Discard changes</button></div>;const visiblePosts = resourcesAccountId === accountId ? posts : [];const visibleDrafts = resourcesAccountId === accountId ? drafts : [];@@ -227,9 +235,10 @@ export default function XPage() {<section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">Reach diagnostics for @{selected.username}</h2><p className="mt-1 text-sm text-gray-400">Read-only checks of the public profile, X search, and visible post metrics.</p></div>- <div className="flex flex-wrap gap-2"><button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={sync}><RefreshCw size={15} className="mr-1 inline" />Run diagnostic</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('profile')}><ExternalLink size={15} className="mr-1 inline" />Open profile</button></div>+ <div className="flex flex-wrap gap-2"><button type="button" className={buttonClass} disabled={accountActionsDisabled} onClick={sync}><RefreshCw size={15} className="mr-1 inline" />Run diagnostic</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={() => openDestination('profile')}><ExternalLink size={15} className="mr-1 inline" />Open profile</button></div></div>{!selected.profileSnapshot?.diagnostics && <div className="mt-4 rounded border border-port-warning/40 bg-port-warning/10 p-3 text-sm text-port-warning">No snapshot yet. Run a diagnostic to capture the evidence PortOS can verify.</div>}+ {unsavedAccountNotice}<div className="mt-4 grid gap-3 sm:grid-cols-4">{[['Followers', profile.followers], ['Following', profile.following], ['Lifetime posts', profile.postCount], ['Captured posts', visiblePosts.length]].map(([label, value]) => <div key={label} className="rounded border border-port-border p-3"><div className="text-xs uppercase tracking-wide text-gray-500">{label}</div><div className="mt-1 text-2xl font-semibold text-white">{formatCount(value)}</div></div>)}</div>@@ -238,17 +247,17 @@ export default function XPage() {</div>{selected.lastSyncAt && <p className="mt-3 text-xs text-gray-500">Last checked {formatDate(selected.lastSyncAt)}{selected.lastError ? ` · Last error: ${selected.lastError}` : ''}</p>}</section>- <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">What this can and cannot conclude</h2><div className="mt-2 space-y-2 text-sm text-gray-300"><p>These checks rule out several hard visibility failures: the profile is public, the handle is searchable, and recent posts are returned in Latest search when a snapshot succeeds.</p><p>They cannot prove that X is recommending the account in Home or Explore. PortOS intentionally reports that as unknown instead of calling ordinary low reach a shadowban.</p><p className="text-gray-400">Automatic posting, follow/unfollow behavior, and background AI activity are off. Approved drafts only open X’s compose screen for a final human check.</p></div><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('people')}>Open account search</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('latest')}>Open Latest search</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => openDestination('settings')}>Open X account settings</button></div></section>+ <section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">What this can and cannot conclude</h2><div className="mt-2 space-y-2 text-sm text-gray-300"><p>These checks rule out several hard visibility failures: the profile is public, the handle is searchable, and recent posts are returned in Latest search when a snapshot succeeds.</p><p>They cannot prove that X is recommending the account in Home or Explore. PortOS intentionally reports that as unknown instead of calling ordinary low reach a shadowban.</p><p className="text-gray-400">Automatic posting, follow/unfollow behavior, and background AI activity are off. Approved drafts only open X’s compose screen for a final human check.</p></div><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={() => openDestination('people')}>Open account search</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={() => openDestination('latest')}>Open Latest search</button><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={() => openDestination('settings')}>Open X account settings</button></div></section></div>;};- const renderPosts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">Captured post reach</h2><p className="mt-1 text-sm text-gray-400">Public metrics from the last browser diagnostic; counts are impressions, not unique people.</p></div><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={sync}><RefreshCw size={15} className="mr-1 inline" />Refresh</button></div>{!visiblePosts.length ? <p className="mt-4 text-sm text-gray-500">No captured posts yet. Run a diagnostic from Reach & health.</p> : <div className="mt-4 space-y-2">{visiblePosts.map((post) => <article key={post.id} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-500"><span>{post.kind === 'reply' ? 'Reply' : 'Post'} · {formatDate(post.remoteCreatedAt)}</span><span>{post.sourceUrl ? <a className="text-port-accent hover:underline" href={post.sourceUrl} target="_blank" rel="noreferrer">Open on X</a> : null}</span></div><p className="mt-2 whitespace-pre-wrap text-sm text-gray-200">{post.body || '(no text captured)'}</p><div className="mt-3 flex flex-wrap gap-3 text-xs text-gray-400"><span><strong className="text-white">{formatCount(post.impressions)}</strong> impressions</span><span><strong className="text-white">{formatCount(post.engagements)}</strong> engagements</span><span>{formatCount(post.likes)} likes</span><span>{formatCount(post.reposts)} reposts</span><span>{formatCount(post.replies)} replies</span></div></article>)}</div>}</section>;+ const renderPosts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">Captured post reach</h2><p className="mt-1 text-sm text-gray-400">Public metrics from the last browser diagnostic; counts are impressions, not unique people.</p></div><button type="button" className={secondaryButton} disabled={accountActionsDisabled} onClick={sync}><RefreshCw size={15} className="mr-1 inline" />Refresh</button></div>{!visiblePosts.length ? <p className="mt-4 text-sm text-gray-500">No captured posts yet. Run a diagnostic from Reach & health.</p> : <div className="mt-4 space-y-2">{visiblePosts.map((post) => <article key={post.id} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-500"><span>{post.kind === 'reply' ? 'Reply' : 'Post'} · {formatDate(post.remoteCreatedAt)}</span><span>{post.sourceUrl ? <a className="text-port-accent hover:underline" href={post.sourceUrl} target="_blank" rel="noreferrer">Open on X</a> : null}</span></div><p className="mt-2 whitespace-pre-wrap text-sm text-gray-200">{post.body || '(no text captured)'}</p><div className="mt-3 flex flex-wrap gap-3 text-xs text-gray-400"><span><strong className="text-white">{formatCount(post.impressions)}</strong> impressions</span><span><strong className="text-white">{formatCount(post.engagements)}</strong> engagements</span><span>{formatCount(post.likes)} likes</span><span>{formatCount(post.reposts)} reposts</span><span>{formatCount(post.replies)} replies</span></div></article>)}</div>}</section>;const renderDrafts = () => <div className="space-y-4"><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Draft a post for review</h2><p className="mt-1 text-sm text-gray-400">Drafts stay local until you submit them to Review Hub. PortOS will never publish automatically.</p><form className="mt-3 space-y-3" onSubmit={createDraft}><label htmlFor="x-draft-body" className="sr-only">X draft text</label><textarea id="x-draft-body" className={fieldClass} rows="5" maxLength="4000" placeholder="Write something you actually want to say…" value={draftBody} onChange={(event) => setDraftBody(event.target.value)} /><div className="flex flex-wrap items-center justify-between gap-2"><span className="text-xs text-gray-500">{draftBody.length}/4000</span><button className={buttonClass} disabled={!draftBody.trim() || Boolean(busy)}>Save draft</button></div></form></section><section className="rounded border border-port-border bg-port-card p-4"><h2 className="font-semibold text-white">Draft queue</h2>{!visibleDrafts.length ? <p className="mt-3 text-sm text-gray-500">No drafts for @{selected.username}.</p> : <div className="mt-3 space-y-2">{visibleDrafts.map((draft) => <article key={draft.id} className="rounded border border-port-border p-3"><div className="flex flex-wrap items-center justify-between gap-2"><StatusBadge value={draft.state === 'approved' || draft.state === 'opened'}>{stateLabel(draft.state)}</StatusBadge><span className="text-xs text-gray-500">{formatDate(draft.updatedAt)}</span></div><p className="mt-3 whitespace-pre-wrap text-sm text-gray-200">{draft.body}</p><div className="mt-3 flex flex-wrap gap-2">{draft.state === 'draft' && <button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'pending_review')}>Submit for review</button>}{draft.state === 'pending_review' && <><button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'approved')}>Approve</button><button type="button" className={secondaryButton} disabled={Boolean(busy)} onClick={() => reviewDraft(draft, 'rejected')}>Reject</button></>}{draft.state === 'approved' && <button type="button" className={buttonClass} disabled={Boolean(busy)} onClick={() => openDraft(draft)}><ExternalLink size={15} className="mr-1 inline" />Open compose in X</button>}{draft.reviewNote && <span className="self-center text-xs text-gray-500">{draft.reviewNote}</span>}</div></article>)}</div>}</section></div>;const renderAccounts = () => <section className="rounded border border-port-border bg-port-card p-4"><div className="flex flex-wrap items-start justify-between gap-3"><div><h2 className="font-semibold text-white">X accounts</h2><p className="mt-1 text-sm text-gray-400">Browser-only diagnostics and review-gated compose handoffs. No X credentials are stored.</p></div><button type="button" className={buttonClass} onClick={() => { setAccountForm(emptyAccount); openAccountForm('new'); }}><Plus size={15} className="mr-1 inline" />Add account</button></div>{!accounts.length ? <div className="mt-4 rounded border border-port-border p-4 text-sm text-gray-400">Add an X account to begin. Sync is manual, so nothing contacts X at boot.</div> : <div className="mt-4 grid gap-3 md:grid-cols-2">{accounts.map((account) => <article key={account.id} className="rounded border border-port-border p-4"><div className="flex items-start justify-between gap-2"><div><h3 className="font-semibold text-white">{account.label}</h3><p className="text-sm text-gray-400">@{account.username}</p></div><StatusBadge value={account.enabled}>{account.enabled ? 'Enabled' : 'Disabled'}</StatusBadge></div><p className="mt-3 text-xs text-gray-500">{account.lastSyncAt ? `Last diagnostic ${formatDate(account.lastSyncAt)}` : 'No diagnostic yet'}</p><div className="mt-3 flex flex-wrap gap-2"><button type="button" className={secondaryButton} onClick={() => openEditAccount(account)}>Edit</button><button type="button" className={secondaryButton} onClick={() => navigate(accountPath(account.id, 'health'))}>Open</button>{deleteAccountId === account.id ? <><button type="button" className="rounded border border-port-error px-3 py-2 text-sm text-port-error disabled:opacity-50" disabled={Boolean(busy)} onClick={() => removeAccount(account.id)}>Delete</button><button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(null)}>Cancel</button></> : <button type="button" className={secondaryButton} onClick={() => setDeleteAccountId(account.id)}>Remove</button>}</div></article>)}</div>}</section>;- const accountDrawer = <Drawer open={accountDrawerOpen} onClose={closeAccountForm} title={accountFormMode === 'edit' ? 'Edit X account' : 'Add X account'} subtitle="Read-only diagnostics with human-reviewed drafts" size="md"><form className="space-y-4" onSubmit={saveAccount}><label className="block text-sm text-gray-300" htmlFor="x-account-label">Local label<input id="x-account-label" className={`${fieldClass} mt-1`} required value={accountForm.label} onChange={(event) => updateAccountForm('label', event.target.value)} /></label><label className="block text-sm text-gray-300" htmlFor="x-account-username">X username<input id="x-account-username" className={`${fieldClass} mt-1`} required placeholder="example_user" value={accountForm.username} onChange={(event) => updateAccountForm('username', event.target.value)} /><span className="mt-1 block text-xs text-gray-500">Enter the handle without or with @. PortOS normalizes it.</span></label><label className="block text-sm text-gray-300" htmlFor="x-account-notes">Notes<textarea id="x-account-notes" className={`${fieldClass} mt-1`} rows="4" value={accountForm.notes} onChange={(event) => updateAccountForm('notes', event.target.value)} /></label><label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="x-account-enabled"><input id="x-account-enabled" type="checkbox" checked={accountForm.enabled} onChange={(event) => updateAccountForm('enabled', event.target.checked)} /> Allow diagnostics and compose handoffs</label><div className="rounded border border-port-border bg-port-bg p-3 text-xs text-gray-400">The managed browser reads public X pages. PortOS does not store your X password or API token, does not run background posting, and only opens an approved draft for final manual submission.</div>{accountFormError && <p className="text-sm text-port-error">{accountFormError}</p>}<div className="flex justify-end gap-2"><button type="button" className={secondaryButton} onClick={closeAccountForm}>Cancel</button><button className={buttonClass} disabled={Boolean(busy) || accountFormDirty && accountFormMode === 'edit' && !accountForm.label.trim()}>{accountFormMode === 'edit' ? 'Save account' : 'Add account'}</button></div></form></Drawer>;+ const accountDrawer = <Drawer open={accountDrawerOpen} onClose={closeAccountForm} title={accountFormMode === 'edit' ? 'Edit X account' : 'Add X account'} subtitle="Read-only diagnostics with human-reviewed drafts" size="md"><form className="space-y-4" onSubmit={saveAccount}><label className="block text-sm text-gray-300" htmlFor="x-account-label">Local label<input id="x-account-label" className={`${fieldClass} mt-1`} required value={accountForm.label} onChange={(event) => updateAccountForm('label', event.target.value)} /></label><label className="block text-sm text-gray-300" htmlFor="x-account-username">X username<input id="x-account-username" className={`${fieldClass} mt-1`} required placeholder="example_user" value={accountForm.username} onChange={(event) => updateAccountForm('username', event.target.value)} /><span className="mt-1 block text-xs text-gray-500">Enter the handle without or with @. PortOS normalizes it.</span></label><label className="block text-sm text-gray-300" htmlFor="x-account-notes">Notes<textarea id="x-account-notes" className={`${fieldClass} mt-1`} rows="4" value={accountForm.notes} onChange={(event) => updateAccountForm('notes', event.target.value)} /></label><label className="flex items-center gap-2 text-sm text-gray-300" htmlFor="x-account-enabled"><input id="x-account-enabled" type="checkbox" checked={accountForm.enabled} onChange={(event) => updateAccountForm('enabled', event.target.checked)} /> Allow diagnostics and compose handoffs</label><div className="rounded border border-port-border bg-port-bg p-3 text-xs text-gray-400">The managed browser reads public X pages. PortOS does not store your X password or API token, does not run background posting, and only opens an approved draft for final manual submission.</div>{accountFormError && <p className="text-sm text-port-error">{accountFormError}</p>}<div className="flex justify-end gap-2"><button type="button" className={secondaryButton} onClick={closeAccountForm}>Cancel</button><button className={buttonClass} disabled={Boolean(busy) || !accountForm.label.trim() || !accountForm.username.trim()}>{accountFormMode === 'edit' ? 'Save account' : 'Add account'}</button></div></form></Drawer>;const notFound = Boolean(accountId && !selected);if (loading) return <PageSkeleton header="bar" label="Loading X" tabs={TABS.length} cards={3} />;diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 1a02bd335d..9c8e474df5 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -521,7 +521,20 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// back onto the v3 peer, which is exactly the bump trigger (see the// `creativeDirectorProjects` 2→3 precedent). Per-category gate → only cos-tasks// sync pauses until the peer upgrades.- cosTasks: 3,+ // v4 = the `workTracker` dispatch marker (repo-study / tracker-filing tasks) and+ // the `reviewerEfforts` per-reviewer effort pins. Same EXECUTION-semantics break+ // as v3, for the same reason: both ride the permissive `metadata` map, so a ≤v3+ // receiver validates and stores the task fine — and then MIS-RUNS it.+ // `taskTypeHooks.isTrackerFilingDispatch` reads `metadata.workTracker` to decide+ // that a run which filed issues and left the tree clean SATISFIED its criterion;+ // a ≤v3 peer only knows the `TRACKER_FILING_TASK_TYPES` set, so it grades that+ // same run a validation miss, finalizes it failed, poisons the provider/model+ // learning bucket, and LWW-pushes the damaged state back onto the v4 peer.+ // `reviewerEfforts` is the milder instance: a ≤v3 peer runs the review at the+ // reviewer CLI's default effort instead of the pinned tier, silently downgrading+ // a review the user deliberately strengthened. Per-category gate → only cos-tasks+ // sync pauses until the peer upgrades.+ cosTasks: 4,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the// comparator walks the union of keys), so declaring a brand-new key woulddiff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 1e1cca59de..4e0b60ccd5 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -155,7 +155,7 @@ export const ERROR_PATTERNS = [},{// Catches both "hit your usage limit" and session limits like "hit your limit · resets 6am"- pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit|(?:^|\n)\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$))/i,+ pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit|\d+-hour limit reached|(?:^|\n)\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$))/i,category: 'usage-limit',actionable: true, // Need to switch provider// Promote only the distinctive provider-billing idioms (the matched@@ -163,7 +163,15 @@ export const ERROR_PATTERNS = [// phrasings like "quota exceeded" / "plan limit" / "daily limit" that a task's// own output can print stay output-scan and count as genuine failures (#2642).origin: 'provider',- structuredMarker: /hit your (?:usage )?limit|Upgrade to Pro|Now using extra usage/i,+ // The vendor-branded "<Product> usage limit reached" and "<N>-hour limit+ // reached" banners belong here too: they are the wordings Claude Code and its+ // siblings actually print, and WITHOUT them a genuine 5-hour window stayed+ // `origin: 'output-scan'` — which agentFinalization's provenance gate does not+ // bench, so every subsequent dequeue re-picked the dead provider and died the+ // same way. They stay distinctive enough that a task's own output does not+ // trip them (unlike the bare `quota exceeded` / `plan limit` alternatives,+ // which remain deliberately unpromoted).+ structuredMarker: /hit your (?:usage )?limit|(?:usage|session) limit reached|\d+-hour limit reached|Upgrade to Pro|Now using extra usage/i,extract: (match, output) => {const timeMatch = output.match(/(?:try again in|resets?)\s+(.+?)(?:\.|·|\n|$)/im);const waitTime = timeMatch ? timeMatch[1].trim() : null;diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex 88a235d231..da5bdf9c64 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -43,7 +43,10 @@ vi.mock('./providerStatus.js', () => ({vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));-vi.mock('./agentErrorAnalysis.js', () => ({+// Partial mock: the two finalize-path helpers are stubbed, but `analyzeAgentFailure`+// passes through to the REAL detector so the banner tests below exercise what ships.+vi.mock('./agentErrorAnalysis.js', async (importOriginal) => ({+ ...(await importOriginal()),resolveFailedTaskUpdate: vi.fn(async () => ({ status: 'pending', metadata: {} })),resolveTypeFailureSignal: vi.fn(() => ({ record: 'skip' })),}));@@ -66,6 +69,7 @@ import { finalizeAgent } from './agentFinalization.js';// The real detector and the real cooldown table supply the analysis shape and// the window, so the assertions below can't drift from what actually ships.import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';+import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { COOLDOWN_MS_BY_CATEGORY } from '../lib/providerCooldown.js';const failedRun = (errorAnalysis, providerId = 'antigravity-tui') => finalizeAgent({@@ -105,6 +109,43 @@ describe('finalizeAgent provider sidelining', () => {expect(markProviderUsageLimitMock).not.toHaveBeenCalled();});+ // The provenance gate is only as good as what `analyzeAgentFailure` promotes to+ // `origin: 'provider'`. The case above hand-stamps that origin, which is exactly+ // how a real regression shipped green: Claude Code's actual banners classified as+ // `origin: 'output-scan'`, so a genuine 5-hour window never benched the provider+ // and every subsequent dequeue re-picked it. These drive the REAL detector.+ it.each([+ ['Claude usage limit reached. Your limit will reset at 5pm.'],+ ['5-hour limit reached · resets 3am'],+ ])('benches the provider on the real usage-limit banner %#', async (banner) => {+ const analysis = analyzeAgentFailure(+ `${banner}\nthe transcript tail continues past the banner.`,+ { id: 'task-1' },+ 'claude',+ {}+ );+ expect(analysis).toMatchObject({ category: 'usage-limit', origin: 'provider', requiresFallback: true });+ await failedRun(analysis, 'claude-code-tui');+ expect(markProviderUsageLimitMock).toHaveBeenCalledWith('claude-code-tui', expect.objectContaining({+ category: 'usage-limit',+ }));+ });++ // The other half of the same gate: a generic limit phrasing a task's own output+ // can print must stay `output-scan` and leave the provider healthy.+ it('does not bench on a generic limit phrasing from the agent transcript', async () => {+ const analysis = analyzeAgentFailure(+ 'Error: the daily limit for widgets was exceeded in our test fixture.\nmore output.',+ { id: 'task-1' },+ 'claude',+ {}+ );+ expect(analysis).toMatchObject({ category: 'usage-limit', origin: 'output-scan' });+ await failedRun(analysis, 'claude-code-tui');+ expect(markProviderUsageLimitMock).not.toHaveBeenCalled();+ expect(markProviderUnavailableMock).not.toHaveBeenCalled();+ });+it('leaves the usage-limit marker owning its own cooldown', async () => {await failedRun({hasError: true,diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 6b09a57b01..debabf142f 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -733,6 +733,31 @@ describe('cos.js source — priority + capacity invariants', () => {expect(evUserIdx, 'user/autonomous tiers must sit inside the !paused gate').toBeGreaterThan(evPauseGateIdx);});+ it('pending-merge sweep is gated on CoS auto-run being in execute mode', () => {+ // The sweep is the ONE tier in evaluateTasks that writes to a default branch+ // (git.mergePR). It deliberately sits ABOVE the agent-slot gate — a merge+ // claims no lane — which also puts it above `resolveAutonomyBudget`, so it+ // must read the auto-run mode itself. It shipped gated on `!paused` alone,+ // which meant `off` / `dry-run` still merged PRs, including on the boot-time+ // `evaluateTasks({ initialStartup: true })`.+ const evalFn = extractFnBody(GEN_SRC, GEN_SRC.indexOf('export async function evaluateTasks'));+ const sweepIdx = evalFn.indexOf('sweepPendingMergePrs()');+ expect(sweepIdx, 'evaluateTasks must invoke sweepPendingMergePrs').toBeGreaterThan(-1);++ // The gate is the `if (...)` immediately preceding the sweep call.+ const gateIdx = evalFn.lastIndexOf('if (', sweepIdx);+ const gate = evalFn.slice(gateIdx, sweepIdx);+ expect(gate, 'the merge sweep must stay gated on !paused').toMatch(/!\s*paused/);+ expect(gate, 'the merge sweep must also gate on auto-run being in execute mode')+ .toMatch(/getDomainMode\(\s*state\.config\s*,\s*'cos'\s*\)\s*===\s*'execute'/);++ // …and it must still run before the agent-slot early-return, or a full agent+ // roster wedges the merge queue (the reason it is not folded into the tiers).+ const slotGateIdx = evalFn.indexOf('if (availableSlots <= 0)');+ expect(slotGateIdx, 'evaluateTasks must keep its agent-slot gate').toBeGreaterThan(-1);+ expect(sweepIdx, 'the merge sweep must run before the agent-slot gate').toBeLessThan(slotGateIdx);+ });+it('per-project cap defaults to global cap when unset', () => {// The fallback `state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents`// is the safety net for older state.json files that pre-date thediff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 261d2ea8bd..f82333f272 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1191,9 +1191,16 @@ export async function evaluateTasks(options) {// task's, which most installs leave disabled — that coupling stranded every// green PortOS-opened PR at `ticks: 0` forever. Runs BEFORE the agent-slot// gate below because a deterministic merge claims no lane, so a full agent- // roster must not also wedge the merge queue. Gated on `!paused` to match the- // autonomous tiers: merging is an autonomous action a global pause suppresses.- if (!paused) {+ // roster must not also wedge the merge queue.+ //+ // Gated on `!paused` AND on CoS auto-run being in `execute`, like every other+ // autonomous tier: merging writes to a default branch, so it is the LAST thing+ // that may run while the user has auto-run set to `off` or `dry-run`. The mode+ // is read directly rather than via `resolveAutonomyBudget` (which runs further+ // down, after the agent-slot gate) because the daily minutes/actions budget+ // meters agent RUNS — a deterministic merge spawns nothing and consumes none+ // of it — while the mode is the user's "may PortOS act on its own" switch.+ if (!paused && getDomainMode(state.config, 'cos') === 'execute') {const prWatcher = await import('./prWatcher.js');const sweep = await prWatcher.sweepPendingMergePrs();if (sweep.merged || sweep.escalated || sweep.timedOut) {diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.jsindex e6de6990a7..df5f69b912 100644--- a/server/services/sharing/cosTasksSync.test.js+++ b/server/services/sharing/cosTasksSync.test.js@@ -69,7 +69,7 @@ describe('buildCosTasksPayload', () => {vi.mocked(getUserTasks).mockResolvedValue({ tasks: [task('task-a', 'pending')] });vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress', { metadata: { claimedBy: 'i1' } })] });const p = await buildCosTasksPayload();- expect(p.schemaVersion).toBe(3); // v3: PR-follow-up disposition markers (mergeOnly / leaveOpen)+ expect(p.schemaVersion).toBe(4); // v4: workTracker dispatch marker + reviewerEfforts pinsexpect(p.listHash).toMatch(/^[a-f0-9]{64}$/);expect(p.tasks).toHaveLength(2);const user = p.tasks.find((t) => t.id === 'task-a');@@ -104,7 +104,7 @@ describe('buildCosTasksPayload', () => {it('returns an empty payload when there are no tasks', async () => {const p = await buildCosTasksPayload();expect(p.tasks).toEqual([]);- expect(p.schemaVersion).toBe(3); // v3: PR-follow-up disposition markers (mergeOnly / leaveOpen)+ expect(p.schemaVersion).toBe(4); // v4: workTracker dispatch marker + reviewerEfforts pins});});diff --git a/server/services/stackerNews.js b/server/services/stackerNews.jsindex d0bea9b726..db499c7436 100644--- a/server/services/stackerNews.js+++ b/server/services/stackerNews.js@@ -59,6 +59,19 @@ const itemContentHash = ({ title = '', body = '', imageUrls = [] } = {}) => stabtext: normalizedText({ title, body }),imageUrls: (Array.isArray(imageUrls) ? imageUrls : []).map(boundedImageUrl).filter(Boolean),});+// The pre-image-aware digest, kept ONLY so an upgrading install's already-stored+// hashes still compare equal to unchanged content. `itemContentHash` folded the+// image list into the digest, which changes the value for EVERY row already in+// `stacker_news_items` — without this, the first sync after upgrading would see+// the entire back catalogue as "changed" (re-stamping `received_at` and re-sorting+// it to the top of the triage list), and every action already `pending_review` /+// `approved` would fail permanently with "Source content changed after review"+// when nothing about the content had changed. Comparisons accept EITHER digest;+// the row is rewritten with the current one on ingest, so this self-heals per row+// and the legacy value stops appearing once an install has synced.+const legacyItemContentHash = ({ title = '', body = '' } = {}) => stableHash(normalizedText({ title, body }));+const contentHashMatches = (storedHash, content) => storedHash === itemContentHash(content)+ || storedHash === legacyItemContentHash(content);const normalizeSyncItemLimit = (value) => Number.isInteger(value)? Math.max(1, Math.min(MAX_SYNC_ITEM_LIMIT, value)): DEFAULT_SYNC_ITEM_LIMIT;@@ -327,6 +340,10 @@ export async function ingestItem({const content = boundedContent({ title, body });const safeImageUrls = [...new Set((Array.isArray(imageUrls) ? imageUrls : []).map(boundedImageUrl).filter(Boolean))].slice(0, 12);const contentHash = itemContentHash({ ...content, imageUrls: safeImageUrls });+ // Accept the pre-image-aware digest as "unchanged" too, so upgrading installs do+ // not re-stamp `received_at` on every already-stored row and re-sort the whole+ // back catalogue to the top of the triage list. See `legacyItemContentHash`.+ const legacyHash = legacyItemContentHash(content);const result = await query(`INSERT INTO stacker_news_items(id,account_id,territory_id,remote_id,kind,author_name,title,body,source_url,image_urls,content_hash,remote_created_at,remote_updated_at)@@ -335,9 +352,10 @@ export async function ingestItem({author_name=EXCLUDED.author_name,title=EXCLUDED.title,body=EXCLUDED.body,source_url=EXCLUDED.source_url,image_urls=EXCLUDED.image_urls,content_hash=EXCLUDED.content_hash,remote_created_at=EXCLUDED.remote_created_at,remote_updated_at=EXCLUDED.remote_updated_at,- received_at=CASE WHEN stacker_news_items.content_hash IS DISTINCT FROM EXCLUDED.content_hash THEN NOW() ELSE stacker_news_items.received_at END,+ received_at=CASE WHEN stacker_news_items.content_hash IN (EXCLUDED.content_hash, $14)+ THEN stacker_news_items.received_at ELSE NOW() END,updated_at=NOW() RETURNING *`,- [randomUUID(), accountId, territoryId, String(remoteId), kind, authorName, content.title, content.body, sourceUrl, safeImageUrls, contentHash, remoteCreatedAt, remoteUpdatedAt],+ [randomUUID(), accountId, territoryId, String(remoteId), kind, authorName, content.title, content.body, sourceUrl, safeImageUrls, contentHash, remoteCreatedAt, remoteUpdatedAt, legacyHash],);return itemView(result.rows[0]);}@@ -508,9 +526,11 @@ async function syncAccountUnlocked(accountId, { force = false } = {}) {const remoteItems = [...(page?.items || [])].sort(compareRemoteItems).slice(0, remaining);for (const remoteItem of remoteItems) {const imageUrls = imageUrlsForItem({ body: remoteItem.text || '', url: remoteItem.url || '' });- const nextHash = itemContentHash({ title: remoteItem.title || '', body: remoteItem.text || '', imageUrls });+ const nextContent = { title: remoteItem.title || '', body: remoteItem.text || '', imageUrls };const previous = await query('SELECT content_hash FROM stacker_news_items WHERE account_id=$1 AND remote_id=$2', [accountId, String(remoteItem.id)]);- const changed = previous.rows[0]?.content_hash !== nextHash;+ const storedHash = previous.rows[0]?.content_hash;+ // A row we have never seen has no stored hash — that is new, not unchanged.+ const changed = storedHash === undefined || !contentHashMatches(storedHash, nextContent);const item = await ingestItem({accountId,territoryId: territory.id,@@ -730,7 +750,14 @@ export async function executeApprovedAction(id) {remoteItemId: item?.remote_id || '',};if (stableHash(currentTarget) !== stableHash(action.reviewed_target || {})) throw new Error('External account or destination changed after review');- if (item && item.content_hash !== action.source_content_hash) throw new Error('Source content changed after review');+ // An action reviewed BEFORE the image-aware digest landed stamped the legacy+ // hash, so compare the item's current content against both digests rather than+ // the two stored strings — otherwise every already-approved action fails+ // permanently on an upgrade, blaming a content change that never happened.+ // See `legacyItemContentHash`.+ if (item && !contentHashMatches(action.source_content_hash, { title: item.title, body: item.body, imageUrls: item.image_urls })) {+ throw new Error('Source content changed after review');+ }if (action.policy_version !== POLICY_VERSION) throw new Error('Policy version changed after review');const rules = resolveStackerNewsRules(account.rules, territory?.rules, territory?.inherit_account_rules ?? true);if (hashStackerNewsRules(rules) !== action.rules_hash) throw new Error('Community rules changed after review');diff --git a/server/services/stackerNewsSync.test.js b/server/services/stackerNewsSync.test.jsindex 728f59a5a1..6918199244 100644--- a/server/services/stackerNewsSync.test.js+++ b/server/services/stackerNewsSync.test.js@@ -172,4 +172,40 @@ describe('Stacker News sync', () => {},}]);});++ // An install that synced BEFORE the image-aware digest landed has legacy hashes+ // in every stacker_news_items row. If those no longer compare equal, the first+ // sync after upgrading treats the whole back catalogue as changed: it re-runs+ // analysis on every item and re-stamps received_at, re-sorting the triage list.+ it('treats a legacy-digest row as unchanged so an upgrade does not re-analyze the back catalogue', async () => {+ const { createHash } = await import('node:crypto');+ // The pre-image-aware digest: sha256 over `${title}\n${body}` with no envelope.+ const legacyHash = createHash('sha256').update('Example work\nA post').digest('hex');+ accountRow = { ...baseAccount, read_transport: 'api', analysis_enabled: true };+ // `beforeEach` only mockClear()s this one, so pin the page explicitly rather+ // than inheriting whatever a prior test's mockImplementation left behind —+ // the hash under test is derived from the item's title/body.+ executeStackerNewsOperation.mockImplementation(async (name, input) => {+ if (name === 'me') return { me: { id: 'owner-1', name: 'example_user' } };+ if (name === 'sub') return { sub: { name: 'art', userId: 'owner-1' } };+ return itemsPage(input.cursor);+ });+ query.mockImplementation(async (sql) => {+ if (sql.startsWith('SELECT * FROM stacker_news_accounts')) return { rows: [accountRow] };+ if (sql.startsWith('SELECT api_key_enc')) return { rows: credentialRows };+ if (sql.startsWith('SELECT * FROM stacker_news_territories')) return { rows: [{ id: territoryId, account_id: accountId, slug: 'art', label: 'Art', is_owned: true, monitoring_enabled: true, inherit_account_rules: true, rules: {}, remote_settings: {} }] };+ if (sql.startsWith('SELECT content_hash')) return { rows: [{ content_hash: legacyHash }] };+ if (sql.includes('INSERT INTO stacker_news_items')) return { rows: [{ id: '00000000-0000-4000-8000-000000000003', account_id: accountId, territory_id: territoryId, remote_id: '42', kind: 'post', author_name: 'artist', title: 'Example work', body: 'A post', source_url: 'https://stacker.news/items/42', image_urls: [], content_hash: 'hash', received_at: new Date() }] };+ return { rows: [], rowCount: 1 };+ });++ await expect(syncAccount(accountId)).resolves.toMatchObject({ ingested: 1, analyzed: 0 });++ // The upsert must also tell Postgres the row is unchanged, or received_at is+ // re-stamped even though analysis was skipped.+ const upsert = query.mock.calls.find(([sql]) => sql.includes('INSERT INTO stacker_news_items'));+ expect(upsert[0]).toContain('stacker_news_items.content_hash IN (EXCLUDED.content_hash, $14)');+ expect(upsert[1]).toHaveLength(14);+ expect(upsert[1][13]).toBe(legacyHash);+ });});