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
test: pin the X draft safety gates, the reviewer-effort map, and the real failure detector in provider benching (#3635)
[._.]/ Adam Eivy8684e4b4436f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a9075ec96d..15d62c3529 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -29,3 +29,5 @@- Ten Digital Twin AI passes now actually run. Each shipped a `stage-config.json` entry with no prompt template behind it, so `buildPrompt()` threw "Template not found" and every call site's `.catch(() => null)` quietly took the fallback path — contradiction detection returned no issues, test generation and writing analysis produced nothing, trait extraction and confidence scoring never ran, enrichment served a generic canned question and stored answers unformatted, test scoring degraded to keyword matching, and import/interview analysis was skipped. All ten templates are now authored against what each call site's parser expects, `twin-interview-analyze` gained the config entry it was also missing, and a migration seeds both into existing installs. A new parity guard fails the build if a stage-config entry ever ships without its template again.- Four sentinel/lifecycle gaps from the v2.40.0 diff are closed. A redirected X handoff (login wall, X redirect) left the Chrome tab it owned open forever, because `openXHandoff` verifies the landing path *after* taking ownership with `closeAfterRead: false` — the tab is now closed before the verification error bubbles. A pending-merge PR whose `gh pr view` fails permanently (deleted PR, renamed repo, revoked token) never ticked, so `MAX_PENDING_MERGE_TICKS` never fired and the entry re-shelled to `gh` forever with nothing surfaced; an unreadable cycle now counts as a tick and times out with a notification naming the PR. The `collaborators` author filter fetched the 100 *oldest* issues by any author and filtered them in memory, hiding a claimable collaborator-filed issue on any busy repo while `self` worked fine — it now fans out one server-side `--author` query per trusted login (capped at 25, with the truncation logged) and merges. And an `api` provider whose `/models` returns HTTP 200 with a non-JSON or unrecognized body no longer overwrites the stored model list with `[]` under a "Models refreshed" toast; it throws with the real reason and leaves the list untouched, the same posture the CLI arms already take. A genuinely empty catalog still saves as empty.++- Three behaviors that shipped with a suite that stayed green when they were deleted now have tests that fail without them. The X reach feature's two safety gates — the 24h stale-approval window and the state-transition guard that stop an approval the user no longer intends from opening a compose window — plus its sync/draft-open re-entrancy guards and the numeric-status-id filter on ingested posts; the review loop's per-reviewer reasoning-effort map, whose whole feature could be dropped from the resolved options with nothing failing; and the remaining provider-benching cases, which asserted against hand-written `{ category, origin }` objects instead of running a transcript through the real detector — the exact pattern that let a genuine usage-limit regression ship green. Each new test was verified by deleting the line it names and watching it fail.diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex 34709e9d65..53a1c73e58 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -9,6 +9,13 @@* carries `benchMs`, and finalizeAgent honors it via the generic* `markProviderUnavailable` marker so `resolveAgentProviderAndModel` routes the* retry to a fallback until the deadline auto-recovers the provider.+ *+ * Every case here builds its `errorAnalysis` by running a real transcript through+ * `detectImmediateFallbackSignal` / `analyzeAgentFailure` rather than hand-stamping+ * `{ category, origin }`. A hand-stamped origin is how a real regression shipped+ * green (#3635): the detector was rewritten so Claude Code's genuine usage-limit+ * banners classified as `output-scan`, the gate stopped benching, and this suite+ * never noticed because it had asserted against a shape it had written itself.*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -186,13 +193,14 @@ describe('finalizeAgent provider sidelining', () => {});it('leaves the usage-limit marker owning its own cooldown', async () => {- await failedRun({- hasError: true,- category: 'usage-limit',- origin: 'provider',- message: 'hit your usage limit',- requiresFallback: true,- }, 'claude-code-tui');+ const analysis = analyzeAgentFailure(+ 'hit your usage limit · resets 6am\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');// markUsageLimit parses its own window out of the provider's message, so it// keeps the dedicated marker rather than the flat per-category cooldown.@@ -209,10 +217,17 @@ describe('finalizeAgent provider sidelining', () => {// loose alternatives (a bare "rate limit" / "quota exceeded" a failing test in// the agent's own workspace can print), and this gate used to key on the// category alone — so an agent's transcript could bench a healthy provider.- it.each(['auth-error', 'rate-limit', 'usage-limit'])(+ // Each transcript below is text a task's OWN run can print.+ it.each([+ ['auth-error', 'Error: unauthorized while writing the snapshot fixture in the widget suite.\nmore output follows.'],+ ['rate-limit', 'Error: the fixture asserted a rate limit banner renders for the widget list.\nmore output follows.'],+ ['usage-limit', 'Error: quota exceeded for the fixture bucket while uploading the report artifact.\nmore output.'],+ ])('does not bench an output-scan %s that merely looks provider-ish',- async (category) => {- await failedRun({ hasError: true, category, origin: 'output-scan', message: 'looks provider-ish', requiresFallback: true });+ async (category, transcript) => {+ const analysis = analyzeAgentFailure(transcript, { id: 'task-1' }, 'claude', {});+ expect(analysis).toMatchObject({ category, origin: 'output-scan' });+ await failedRun(analysis);expect(markProviderUnavailableMock).not.toHaveBeenCalled();expect(markProviderUsageLimitMock).not.toHaveBeenCalled();// No marker fired, so the lazy active-provider lookup must stay unread.@@ -221,15 +236,30 @@ describe('finalizeAgent provider sidelining', () => {);it('does not bench an ordinary agent-work failure', async () => {- await failedRun({ hasError: true, category: 'test-failure', origin: 'output-scan', message: 'suite failed' });+ const analysis = analyzeAgentFailure(+ 'The suite reported a test failure in the widget list module. Review the assertions and retry.',+ { id: 'task-1' },+ 'claude',+ {}+ );+ expect(analysis).toMatchObject({ category: 'test-failure', origin: 'output-scan' });+ await failedRun(analysis);expect(markProviderUnavailableMock).not.toHaveBeenCalled();expect(markProviderUsageLimitMock).not.toHaveBeenCalled();});// A bad model id is REQUEST-specific: benching would take the provider's other- // working models offline over one wrong id.+ // working models offline over one wrong id. Driven through the real detector so+ // the `origin: 'provider'` half of the case is the one the classifier assigns.it('does not bench a provider-origin model-not-found', async () => {- await failedRun({ hasError: true, category: 'model-not-found', origin: 'provider', message: 'no such model' });+ const analysis = analyzeAgentFailure(+ 'API Error: 404 Not Found model: example-model-v1\nthe run stopped here without retrying.',+ { id: 'task-1' },+ 'claude',+ {}+ );+ expect(analysis).toMatchObject({ category: 'model-not-found', origin: 'provider' });+ await failedRun(analysis);expect(markProviderUnavailableMock).not.toHaveBeenCalled();});diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.jsindex c9388bfa43..be30b109bb 100644--- a/server/services/codeReview.test.js+++ b/server/services/codeReview.test.js@@ -282,6 +282,71 @@ describe('codeReview helpers', () => {const cleared = await resolveReviewLoopOptions({ reviewerMaxRounds: {} }, testDeps)expect(cleared.reviewerMaxRounds).toEqual({})})++ // The effort map is the twin of the model map above and rides the same+ // returned bundle. Dropping the `reviewerEfforts` key here silently disables+ // every per-reviewer effort pin across the review loop, so these pin the key+ // itself as much as the precedence.+ it('assembles a reviewer-keyed effort map from the per-reviewer scalars', async () => {+ mockedSettings.current = {+ codeReview: {+ reviewers: ['codex', 'claude'],+ codexEffort: 'xhigh',+ claudeEffort: 'high',+ },+ }+ const out = await resolveReviewLoopOptions({}, testDeps)+ expect(out.reviewerEfforts).toEqual({ codex: 'xhigh', claude: 'high' })+ })++ it('omits reviewers with no configured effort (absent = the reviewer\'s own default)', async () => {+ mockedSettings.current = { codeReview: { reviewers: ['codex', 'claude'], codexEffort: 'high' } }+ const out = await resolveReviewLoopOptions({}, testDeps)+ expect(out.reviewerEfforts).toEqual({ codex: 'high' })+ })++ it('returns an empty effort map when no reviewer has one configured', async () => {+ mockedSettings.current = { codeReview: { reviewers: ['copilot', 'codex'] } }+ const out = await resolveReviewLoopOptions({}, testDeps)+ expect(out.reviewerEfforts).toEqual({})+ })++ it('carries a local-LLM effort pin too, so a per-task one can reach the endpoint', async () => {+ // `/api/code-review/local`'s own default reads the GLOBAL settings scalar+ // and can't see a task-level pin, so the pin travels in this map instead.+ mockedSettings.current = { codeReview: { reviewers: ['copilot', 'ollama'], ollamaEffort: 'low' } }+ const out = await resolveReviewLoopOptions({}, testDeps)+ expect(out.reviewerEfforts).toEqual({ ollama: 'low' })+ })++ it('lets a task-level effort map (including an explicitly empty one) override the defaults', async () => {+ mockedSettings.current = { codeReview: { reviewers: ['codex'], codexEffort: 'high' } }+ const pinned = await resolveReviewLoopOptions({ reviewerEfforts: { codex: 'minimal' } }, testDeps)+ expect(pinned.reviewerEfforts).toEqual({ codex: 'minimal' })+ // An explicit `{}` is a real "use each reviewer's own default effort for+ // this task" choice, not an absent field.+ const cleared = await resolveReviewLoopOptions({ reviewerEfforts: {} }, testDeps)+ expect(cleared.reviewerEfforts).toEqual({})+ })++ it('drops an effort pin a reviewer\'s own ladder does not accept', async () => {+ mockedSettings.current = { codeReview: { reviewers: ['antigravity', 'copilot'] } }+ // `agy` really does reject `--effort max`, and `copilot` is a GitHub review+ // with no effort control at all — both are dropped, not clamped.+ const out = await resolveReviewLoopOptions(+ { reviewerEfforts: { antigravity: 'max', copilot: 'high', '@bot': 'high' } },+ testDeps,+ )+ expect(out.reviewerEfforts).toEqual({})+ })++ it('drops a stale out-of-ladder scalar from the saved defaults', async () => {+ // settings.json is hand-editable, so the scalars are re-validated rather+ // than trusted — an unusable level must not surface as a pin.+ mockedSettings.current = { codeReview: { reviewers: ['antigravity'], antigravityEffort: 'ultra' } }+ const out = await resolveReviewLoopOptions({}, testDeps)+ expect(out.reviewerEfforts).toEqual({})+ })})describe('runLocalCodeReview', () => {diff --git a/server/services/x.test.js b/server/services/x.test.jsindex 2bcbdae973..9c06e7da34 100644--- a/server/services/x.test.js+++ b/server/services/x.test.js@@ -6,7 +6,8 @@ vi.mock('./xBrowser.js', () => ({ openXHandoff: vi.fn() }));const { query, withTransaction } = await import('../lib/db.js');const { executeXBrowserRead } = await import('../integrations/x/index.js');-const { buildXReadError, deriveXDiagnostics, syncAccount } = await import('./x.js');+const { openXHandoff } = await import('./xBrowser.js');+const { buildXReadError, deriveXDiagnostics, syncAccount, reviewDraft, openApprovedDraft } = await import('./x.js');describe('X diagnostics', () => {it('distinguishes observable public/search reach from unknown recommendation eligibility', () => {@@ -158,4 +159,182 @@ describe('syncAccount error reporting', () => {expect(result.diagnostics.appearsInPeopleSearch).toBe(true);expect(update[1][2]).toBe('');});++ // A browser read can hand back a "post" whose id is a slug, an `analytics`+ // path segment, or an empty string — anything that is not the numeric status+ // id X actually keys on. Persisting one writes a row that can never+ // ON CONFLICT-merge with the real post, so the same post ingests twice.+ it('drops remote posts whose id is not a numeric X status id', async () => {+ executeXBrowserRead.mockImplementation(async (name) => {+ if (name === 'people') return { handles: [], exactMatch: false };+ if (name === 'profile') {+ return {+ profile: { username: 'example_user' },+ posts: [+ { authorHandle: 'example_user', remoteId: '1750000000000000001' },+ { authorHandle: 'example_user', remoteId: 'analytics' },+ ],+ };+ }+ return {+ posts: [+ { authorHandle: 'example_user', remoteId: '' },+ { authorHandle: 'example_user', remoteId: '17500000000000000zz' },+ { authorHandle: 'example_user', remoteId: '1750000000000000002' },+ ],+ };+ });++ const client = { query: vi.fn().mockResolvedValue({ rows: [] }) };+ withTransaction.mockImplementation(async (callback) => callback(client));+ const result = await syncAccount('acct-1');++ const inserted = client.query.mock.calls+ .filter(([sql]) => /INSERT INTO x_posts/.test(sql))+ .map(([, params]) => params[2]);+ expect(inserted).toEqual(['1750000000000000001', '1750000000000000002']);+ expect(result.ingested).toBe(2);+ });++ // Re-entrancy guard, not a concurrency defense (see the Security Model): the+ // UI can fire the same sync twice — from a button and a socket refresh — and+ // the second must join the in-flight read instead of opening a second browser+ // session against the same account.+ it('joins an in-flight sync for the same account instead of reading twice', async () => {+ executeXBrowserRead.mockImplementation(async (name) => (name === 'people'+ ? { handles: ['example_user'], exactMatch: true }+ : { profile: { username: 'example_user' }, posts: [] }));+ const client = { query: vi.fn().mockResolvedValue({ rows: [] }) };+ withTransaction.mockImplementation(async (callback) => callback(client));++ const first = syncAccount('acct-1');+ const second = syncAccount('acct-1');+ await Promise.all([first, second]);++ // profile + latest + people, once — not six reads.+ expect(executeXBrowserRead).toHaveBeenCalledTimes(3);++ // The lock releases once the run settles, so a later sync is a fresh read.+ await syncAccount('acct-1');+ expect(executeXBrowserRead).toHaveBeenCalledTimes(6);+ });+});++describe('reviewDraft state transitions', () => {+ const accountRow = { id: 'acct-1', username: 'example_user', enabled: true, label: 'Example' };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ const runReview = async (id, state, rows) => {+ query.mockImplementation(async (sql) => {+ if (/UPDATE x_drafts/.test(sql)) return { rows };+ if (/FROM x_accounts/.test(sql)) return { rows: [accountRow] };+ return { rows: [] };+ });+ const draft = await reviewDraft(id, state);+ const update = query.mock.calls.find(([sql]) => /UPDATE x_drafts/.test(sql));+ return { draft, params: update?.[1] };+ };++ it('only promotes a draft to pending_review from draft', async () => {+ const { params } = await runReview('draft-1', 'pending_review', [+ { id: 'draft-1', account_id: 'acct-1', body: 'hello', state: 'pending_review' },+ ]);+ // The WHERE clause pins the state the caller believed it was acting on, so a+ // second click (or a stale UI) can't re-run the transition.+ expect(params[3]).toBe('draft');+ });++ it.each(['approved', 'rejected'])('only moves a draft to %s from pending_review', async (state) => {+ const { params } = await runReview('draft-1', state, [+ { id: 'draft-1', account_id: 'acct-1', body: 'hello', state },+ ]);+ expect(params[3]).toBe('pending_review');+ });++ it('returns null when the draft was no longer in the expected state', async () => {+ const { draft } = await runReview('draft-1', 'approved', []);+ expect(draft).toBeNull();+ });++ it.each(['draft', 'opened', 'deleted'])('rejects %s as a review target state', async (state) => {+ await expect(reviewDraft('draft-1', state)).rejects.toThrow('Unsupported X draft review state');+ });+});++describe('openApprovedDraft approval gates', () => {+ const draftRow = (overrides = {}) => ({+ id: 'draft-1',+ account_id: 'acct-1',+ body: 'hello world',+ state: 'approved',+ approved_at: new Date().toISOString(),+ account_label: 'Example',+ username: 'example_user',+ enabled: true,+ ...overrides,+ });++ const mockDraft = (row) => {+ query.mockImplementation(async (sql) => {+ if (/UPDATE x_drafts/.test(sql)) return { rows: row ? [{ ...row, state: 'opened' }] : [] };+ if (/FROM x_drafts/.test(sql)) return { rows: row ? [row] : [] };+ return { rows: [] };+ });+ };++ beforeEach(() => {+ vi.clearAllMocks();+ openXHandoff.mockResolvedValue({ url: 'https://x.com/compose/post' });+ });++ it('opens a compose window for a freshly approved draft', async () => {+ mockDraft(draftRow());+ const opened = await openApprovedDraft('draft-1');+ expect(openXHandoff).toHaveBeenCalledWith({ kind: 'compose', value: 'hello world' });+ expect(opened.state).toBe('opened');+ });++ // The 24h gate is the feature's safety story: an approval the user made+ // yesterday must not silently open a compose window they no longer intend.+ it('refuses a draft approved more than 24h ago', async () => {+ mockDraft(draftRow({ approved_at: new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString() }));+ await expect(openApprovedDraft('draft-stale')).rejects.toThrow('X draft approval is stale');+ expect(openXHandoff).not.toHaveBeenCalled();+ });++ it('still opens a draft approved just inside the 24h window', async () => {+ mockDraft(draftRow({ approved_at: new Date(Date.now() - 23 * 60 * 60 * 1000).toISOString() }));+ await expect(openApprovedDraft('draft-fresh')).resolves.toMatchObject({ state: 'opened' });+ });++ it('refuses an approved-state draft with no approval timestamp', async () => {+ mockDraft(draftRow({ approved_at: null }));+ await expect(openApprovedDraft('draft-no-stamp')).rejects.toThrow('X draft approval is stale');+ expect(openXHandoff).not.toHaveBeenCalled();+ });++ it.each(['draft', 'pending_review', 'rejected', 'opened'])('returns null for a %s draft', async (state) => {+ mockDraft(draftRow({ state }));+ await expect(openApprovedDraft(`draft-${state}`)).resolves.toBeNull();+ expect(openXHandoff).not.toHaveBeenCalled();+ });++ it('refuses to open a draft whose account is disabled', async () => {+ mockDraft(draftRow({ enabled: false }));+ await expect(openApprovedDraft('draft-disabled')).rejects.toThrow('Selected X account is disabled');+ expect(openXHandoff).not.toHaveBeenCalled();+ });++ // Same re-entrancy guard as syncAccount: a double-click must not open two+ // compose windows for one approval.+ it('joins an in-flight open for the same draft instead of handing off twice', async () => {+ mockDraft(draftRow());+ const first = openApprovedDraft('draft-1');+ const second = openApprovedDraft('draft-1');+ await Promise.all([first, second]);+ expect(openXHandoff).toHaveBeenCalledTimes(1);+ });});