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: let the merge coordinator assess PRs when the first eligible provider has no default model
[._.]/ Adam Eivy7889bc3d92f0
diff --git a/client/src/components/models/ModelAbuseGuardPanel.jsx b/client/src/components/models/ModelAbuseGuardPanel.jsxindex ab51ea14e3..6a936817da 100644--- a/client/src/components/models/ModelAbuseGuardPanel.jsx+++ b/client/src/components/models/ModelAbuseGuardPanel.jsx@@ -135,6 +135,11 @@ export default function ModelAbuseGuardPanel() {Screens external issues, pull requests, and messages before analysis. Runs locally on CPU; no GPU required.Required screening blocks analysis when it fails or cannot finish.</p>+ {guardStatus?.contributionAssessment?.ready === false && (+ <p role="status" className="text-xs text-port-warning max-w-2xl">+ GitHub pull request and issue assessment is not ready ({guardStatus.contributionAssessment.code}): no eligible API provider resolves a model, so the pending-merge coordinator cannot merge. Pick a provider and model in Content safety policies below.+ </p>+ )}<details className="text-sm rounded-lg border border-port-border p-3"><summary className="cursor-pointer text-port-accent">How screening works and its limits</summary><div className="mt-3 space-y-2 text-xs leading-relaxed text-gray-400 max-w-2xl">diff --git a/client/src/components/models/ModelAbuseGuardPanel.test.jsx b/client/src/components/models/ModelAbuseGuardPanel.test.jsxindex 1a9328f11b..bce505bb1a 100644--- a/client/src/components/models/ModelAbuseGuardPanel.test.jsx+++ b/client/src/components/models/ModelAbuseGuardPanel.test.jsx@@ -59,6 +59,13 @@ const renderPanel = async () => {};describe('ModelAbuseGuardPanel', () => {+ it('warns when a ready classifier cannot back GitHub contribution assessment', async () => {+ getModelAbuseGuardStatus.mockResolvedValue({ ready: true, stages: STAGES.map(stage => ({ ...stage, ready: true })),+ contributionAssessment: { ready: false, code: 'untrusted-content-model-required' } });+ await renderPanel();+ expect(await screen.findByText(/assessment is not ready \(untrusted-content-model-required\)/)).toBeInTheDocument();+ });+it('offers repair for partial setup and disables installation without Python', async () => {getModelAbuseGuardStatus.mockResolvedValueOnce({ready: false, setupState: 'incomplete', venvReady: true, pythonAvailable: false, stages: STAGES,diff --git a/client/src/components/models/UntrustedContentPolicyPanel.jsx b/client/src/components/models/UntrustedContentPolicyPanel.jsxindex 0faad5dd63..dfc6001240 100644--- a/client/src/components/models/UntrustedContentPolicyPanel.jsx+++ b/client/src/components/models/UntrustedContentPolicyPanel.jsx@@ -45,6 +45,23 @@ export default function UntrustedContentPolicyPanel() {const effectiveValue = name => effective[name];const inheritanceName = isPrivate && source !== 'messages' ? 'message defaults' : 'shared defaults';const selectedProvider = providers.find(provider => provider.id === effectiveValue('providerId'));+ // Mirrors selectUntrustedContentProvider (server/lib/untrustedContent.js):+ // a pinned provider is used as-is; Automatic takes the first eligible+ // provider that resolves a model, never one that cannot.+ const eligibleProvider = provider => provider.enabled !== false && (isPrivate ? localApiProvider : apiProvider)(provider);+ const resolution = (() => {+ const pinned = effectiveValue('providerId');+ const candidates = pinned ? providers.filter(provider => provider.id === pinned) : providers;+ const usable = candidates.filter(eligibleProvider);+ for (const provider of usable) {+ const model = effectiveValue('model') || provider.defaultModel;+ if (model) return { provider, model };+ }+ if (!usable.length) return { problem: pinned ? 'The pinned provider is not available for this source.' : 'No eligible API provider is available for this source.' };+ return { problem: pinned+ ? 'The pinned provider has no default model; pick an installed model.'+ : 'No eligible API provider has a default model; pick an installed model.' };+ })();const patch = fields => setConfig(current => source === 'defaults'? { ...current, defaults: { ...current?.defaults, ...fields } }: { ...current, sources: { ...current?.sources, [source]: { ...current?.sources?.[source], ...fields } } });@@ -145,6 +162,9 @@ export default function UntrustedContentPolicyPanel() {emptyModelOption="Provider default model"alwaysShowModel/>+ {!loading && (resolution.problem+ ? <p role="status" className="text-xs text-port-warning">Analysis is not ready for {source === 'defaults' ? 'sources that use shared defaults' : 'this source'}: {resolution.problem}</p>+ : <p className="text-xs text-gray-400">Resolves to {resolution.provider.name || resolution.provider.id} with model {resolution.model}.</p>)}<p className="text-xs text-gray-500">{isPrivate ? 'Only local API endpoints are eligible for private messages. Cloud APIs, CLI agents, and provider fallback are blocked.' : 'Choose an API provider for text analysis. Automatic selection uses an eligible API provider; a failed provider never falls back. Cloud APIs may receive public sources.'} <a href="/ai" className="text-port-accent hover:underline">Configure providers</a></p></div><details className="rounded-lg border border-port-border p-3">diff --git a/client/src/components/models/UntrustedContentPolicyPanel.test.jsx b/client/src/components/models/UntrustedContentPolicyPanel.test.jsxindex 0adc586e01..d856f2a341 100644--- a/client/src/components/models/UntrustedContentPolicyPanel.test.jsx+++ b/client/src/components/models/UntrustedContentPolicyPanel.test.jsx@@ -5,7 +5,7 @@ vi.mock('../../services/api', () => ({ getSettings: vi.fn(), updateSettings: vi.vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({providers: [{ id: 'local-api', name: 'Local example', type: 'api', endpoint: 'http://127.0.0.1:11434/v1', models: ['example-model'] },- { id: 'cloud-api', name: 'Cloud example', type: 'api', endpoint: 'https://example.com/v1', models: ['example-model'] },+ { id: 'cloud-api', name: 'Cloud example', type: 'api', endpoint: 'https://example.com/v1', models: ['example-model'], defaultModel: 'example-model' },], loading: false,}) }));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn() } }));@@ -42,6 +42,16 @@ describe('content safety policy configuration', () => {await waitFor(() => expect(screen.getByRole('button', { name: 'Save content policies' })).toBeDisabled());});+ it('shows what Automatic resolves to, skipping an eligible provider without a default model', async () => {+ render(<UntrustedContentPolicyPanel />);+ fireEvent.change(await screen.findByLabelText('Source'), { target: { value: 'github-pr' } });+ expect(screen.getByText(/Resolves to Cloud example with model example-model/)).toBeInTheDocument();+ fireEvent.change(screen.getByLabelText('Source'), { target: { value: 'email' } });+ expect(screen.getByRole('status')).toHaveTextContent('No eligible API provider has a default model');+ fireEvent.change(screen.getByLabelText('Analysis API provider'), { target: { value: 'local-api' } });+ expect(screen.getByRole('status')).toHaveTextContent('The pinned provider has no default model');+ });+it('requires loaded settings before editing and supports a failed-read retry', async () => {getSettings.mockRejectedValueOnce(new Error('unavailable'));render(<UntrustedContentPolicyPanel />);diff --git a/server/lib/README.md b/server/lib/README.mdindex 0d939bddf2..882b87f5cd 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -772,7 +772,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `isCancelled` is polled once a second and SIGKILLs the child when it turns true (resolving `{success:false, error:'cancelled'}`) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. || `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. || `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. |-| `untrustedContent.js` | `jevPolicyPatchSchema` validates narrow scorer-management updates. Shared source policies, strict settings schema, data framing and API-only/local-private provider eligibility for untrusted GitHub and messaging content. |+| `untrustedContent.js` | `jevPolicyPatchSchema` validates narrow scorer-management updates. Shared source policies, strict settings schema, data framing and API-only/local-private provider eligibility for untrusted GitHub and messaging content. `selectUntrustedContentProvider` is the one provider+model selection rule (automatic selection skips an eligible provider that resolves no model; a pinned provider fails closed). || `untrustedContentSources.js` | The ingress vocabulary alone — `UNTRUSTED_CONTENT_SOURCES` and `PRIVATE_UNTRUSTED_CONTENT_SOURCES`. Split out of `untrustedContent.js` (which reaches `zod` and `node:crypto`) so the browser can import it: the Abuse Guard panel offers exactly the sources the server screens, instead of restating them and drifting (#7680). || `contributionSecurityPolicy.js` | Trusted host-control security policy and strict tool-free GitHub contribution assessment contract. || `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |diff --git a/server/lib/untrustedContent.js b/server/lib/untrustedContent.jsindex 0a354246a4..7873436f79 100644--- a/server/lib/untrustedContent.js+++ b/server/lib/untrustedContent.js@@ -76,3 +76,32 @@ export function isUntrustedContentProvider(provider, source) {return !PRIVATE_UNTRUSTED_CONTENT_SOURCES.includes(source)|| ['localhost', '127.0.0.1', '[::1]'].includes(endpoint.hostname.toLowerCase());}++const PROVIDER_UNAVAILABLE = Object.freeze({ code: 'untrusted-content-provider-unavailable', message: 'Configure an enabled text API provider in Models > LLMs > Abuse Guard. Private messages require a local API endpoint. CLI agents and provider fallback are disabled for external content.' });++/**+ * Resolve the provider and model an untrusted-content analysis will use.+ *+ * Automatic selection (no explicit provider, no pinned `policy.providerId`)+ * only considers providers that can also resolve a model, so an eligible+ * provider without a default model never shadows a usable one. This is an+ * eligibility rule at selection time, not a fallback after a failed call: a+ * pinned or explicit provider that cannot resolve a model fails closed.+ */+export function selectUntrustedContentProvider({ providers, policy, source, provider = null, model = null }) {+ if (provider || policy.providerId) {+ const selected = provider || (providers || []).find(item => item.id === policy.providerId);+ if (!isUntrustedContentProvider(selected, source)) return PROVIDER_UNAVAILABLE;+ const effectiveModel = model || (provider && provider.id !== policy.providerId ? null : policy.model) || selected.defaultModel;+ return effectiveModel+ ? { provider: selected, model: effectiveModel }+ : { code: 'untrusted-content-model-required', message: 'Select an installed text model in Models > LLMs > Abuse Guard.' };+ }+ const eligible = (providers || []).filter(item => isUntrustedContentProvider(item, source));+ if (!eligible.length) return PROVIDER_UNAVAILABLE;+ for (const candidate of eligible) {+ const effectiveModel = model || policy.model || candidate.defaultModel;+ if (effectiveModel) return { provider: candidate, model: effectiveModel };+ }+ return { code: 'untrusted-content-model-required', message: 'No eligible API provider has a default model. Select an installed text model in Models > LLMs > Abuse Guard.' };+}diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 02f1c70d11..2e00650303 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -252,8 +252,16 @@ router.get('/catalog', asyncHandler(async (req, res) => {// The model-abuse guard has its own lifecycle: it is a pinned, offline// classifier and must never be installed through the general chat-model path.+// `ready` covers only the Prompt Guard classifier. GitHub contribution+// assessment also needs a provider and model, reported separately so a green+// guard cannot hide a coordinator that can never assess a pull request.router.get('/security-guard/status', asyncHandler(async (_req, res) => {- res.json(await getModelAbuseGuardStatus())+ const { getContributionAssessmentReadiness } = await import('../services/untrustedContent.js')+ const [status, contributionAssessment] = await Promise.all([+ getModelAbuseGuardStatus(),+ getContributionAssessmentReadiness(),+ ])+ res.json({ ...status, contributionAssessment })}))router.post('/security-guard/install', asyncHandler(async (req, res) => {diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex bc14799ea0..d6a8f95469 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -50,6 +50,10 @@ vi.mock('../services/modelAbuseGuard.js', () => ({cancelModelAbuseGuardInstall: (...args) => cancelModelAbuseGuardInstall(...args),}));+vi.mock('../services/untrustedContent.js', () => ({+ getContributionAssessmentReadiness: vi.fn(async () => ({ ready: false, code: 'untrusted-content-model-required', sources: {} })),+}));+vi.mock('../services/localLlmPlayground.js', () => ({runLocalLlmTest: vi.fn(),compareLocalLlmModels: vi.fn(),@@ -211,6 +215,8 @@ describe('local LLM playground routes', () => {const status = await request(makeApp()).get('/api/local-llm/security-guard/status');expect(status.status).toBe(200);expect(getModelAbuseGuardStatus).toHaveBeenCalled();+ // A ready classifier must not mask a contribution assessment with no usable provider/model.+ expect(status.body.contributionAssessment).toEqual(expect.objectContaining({ ready: false, code: 'untrusted-content-model-required' }));const install = await request(makeApp()).post('/api/local-llm/security-guard/install').send({});expect(install.status).toBe(200);diff --git a/server/services/prReviewerSecurity.js b/server/services/prReviewerSecurity.jsindex 6918594768..ac6bbb27d3 100644--- a/server/services/prReviewerSecurity.js+++ b/server/services/prReviewerSecurity.js@@ -154,7 +154,13 @@ export async function assessPullRequestForAction({ pr, diff, repoFullName, readP.filter(Boolean).join('\n\n');if (content.length > SECURITY_SCAN_MAX_DIFF_CHARS) return failure('security-action-input-too-large');const screened = await screenUntrustedContent({ content, source: 'github-pr' });- if (screened?.ok !== true || screened.screening?.safe !== true) return failure('security-action-assessment-withheld');+ if (screened?.ok !== true || screened.screening?.safe !== true) {+ // `code`/`message` on a screen failure are server-authored, never model prose.+ return failure('security-action-assessment-withheld', {+ ...(screened?.code ? { cause: screened.code } : {}),+ ...(screened?.message ? { message: screened.message } : {}),+ });+ }const actionState = (row) => JSON.stringify({state: row.state, isDraft: row.isDraft, author: row.author?.login,diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex 62bac3ae58..71c6fd7329 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -53,6 +53,14 @@ const PR_LIST_LIMIT = 200;// stays the sole owner of the budget and of every entry after the cap.export const PENDING_MERGE_SWEEP_INTERVAL_MS = 30 * 60 * 1000;export const MAX_PENDING_MERGE_TICKS = 12;+// Withheld-assessment causes that repeat identically until the head or the+// untrusted-content configuration changes. Transport and readiness failures+// are deliberately absent: they heal without either changing.+const STABLE_ASSESSMENT_CAUSES = new Set([+ 'untrusted-content-model-required', 'untrusted-content-context-too-small', 'untrusted-content-too-large',+ 'untrusted-content-policy-invalid', 'untrusted-content-endpoint-blocked', 'untrusted-content-blocked',+ 'security-model-withheld', 'security-model-uncertain', 'security-model-assessment-required',+]);export const HANDOFF_FOLLOW_UP_INTERVAL_MS = 60 * 1000;export const HANDOFF_FOLLOW_UP_FAST_POLLS = 5;export const HANDOFF_FOLLOW_UP_BACKOFF_MS = 2 * 60 * 1000;@@ -634,7 +642,22 @@ async function runPendingMergePrs(app, { spendTicks, receipts = null }) {}let withheldReason = null;- if (isPendingMergeReady(prView)) {+ // The last assessment withheld for this exact head and configuration. While+ // neither has changed a retry cannot succeed, so skip the classifier run and+ // the repository's merge-admission lease; the entry stays in attention.+ let assessmentWithheld = null;+ const ready = isPendingMergeReady(prView);+ if (ready && entry.assessmentWithheld) {+ const { getContributionAssessmentFingerprint } = await import('./untrustedContent.js');+ const policy = await getContributionAssessmentFingerprint().catch(() => null);+ const held = entry.assessmentWithheld;+ if (policy && held.policy === policy+ && String(prView.headRefOid || '').toLowerCase() === held.headSha) {+ assessmentWithheld = held;+ withheldReason = held.reason;+ }+ }+ if (ready && !assessmentWithheld) {const { withPendingMergeAdmission } = await import('./cosMergeAdmission.js');const admitted = await withPendingMergeAdmission(origin, async () => {const currentPr = await readPendingPullRequest(repoSpec, entry.prNumber, forgeExec);@@ -653,8 +676,23 @@ async function runPendingMergePrs(app, { spendTicks, receipts = null }) {readIssue: async (number) => safeJSONParse(await execGh(['api', '--hostname', githubApiHost(origin.host), `repos/${origin.fullName}/issues/${number}`,], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null), null),- }).catch(() => ({ ok: false }));- withheldReason = assessment.ok ? null : 'the complete current contribution assessment was unavailable or withheld';+ }).catch((err) => {+ console.warn(`⚠️ Contribution assessment for PR #${entry.prNumber} threw: ${err.message}`);+ return { ok: false, code: 'security-action-assessment-error' };+ });+ if (!assessment.ok) {+ const code = assessment.code || 'security-action-assessment-unavailable';+ const detail = assessment.cause ? `${code}: ${assessment.cause}` : code;+ withheldReason = `the complete current contribution assessment was unavailable or withheld (${detail})`;+ // Evidence, mutable-state, transport and provider-readiness failures+ // can clear on a retry of the same head; only a stable outcome of this+ // head under this configuration is cached.+ if (assessment.code === 'security-action-assessment-withheld' && STABLE_ASSESSMENT_CAUSES.has(assessment.cause)) {+ const { getContributionAssessmentFingerprint } = await import('./untrustedContent.js');+ const policy = await getContributionAssessmentFingerprint().catch(() => null);+ if (policy) assessmentWithheld = { headSha: String(expectedHeadSha).toLowerCase(), code: detail, policy, reason: withheldReason };+ }+ } else withheldReason = null;// Re-read the durable owner's policy inside admission, after remote// assessment and immediately before merge. Waiting CI is not authority// to ignore a later manual hold or a changed review requirement.@@ -695,7 +733,8 @@ async function runPendingMergePrs(app, { spendTicks, receipts = null }) {console.error(`❌ Deterministic merge failed for PR #${entry.prNumber}: ${merge.error || 'unknown error'}`);}- const next = { ...entry, ticks: entry.ticks + charge };+ const { assessmentWithheld: _previous, ...settled } = entry;+ const next = { ...settled, ticks: entry.ticks + charge, ...(assessmentWithheld ? { assessmentWithheld } : {}) };if (next.ticks >= MAX_PENDING_MERGE_TICKS) {const reason = String(prView.state || '').toUpperCase() !== 'OPEN'? `it is ${String(prView.state).toLowerCase()} rather than open`diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.jsindex eb112a6c97..a59cc288b2 100644--- a/server/services/prWatcher.test.js+++ b/server/services/prWatcher.test.js@@ -34,8 +34,10 @@ vi.mock('./forgeExecOptions.js', () => ({}));const screenMock = vi.fn();+const fingerprintMock = vi.fn();vi.mock('./untrustedContent.js', () => ({screenUntrustedContent: (...args) => screenMock(...args),+ getContributionAssessmentFingerprint: (...args) => fingerprintMock(...args),}));const mergePrMock = vi.fn();vi.mock('./git.js', () => ({@@ -102,6 +104,7 @@ const pr = (number, login, extra = {}) => ({beforeEach(() => {execGhMock.mockReset();screenMock.mockReset().mockResolvedValue({ ok: true, screening: { safe: true } });+ fingerprintMock.mockReset().mockResolvedValue('policy-1');ensureForgeReachableMock.mockReset();ensureForgeReachableMock.mockResolvedValue({ ok: true, status: 'ok', detail: null, remedy: null });mergePrMock.mockReset();@@ -303,6 +306,86 @@ describe('merge-only PR watcher', () => {expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(1);});+ describe('a withheld contribution assessment', () => {+ const modelRequired = { ok: false, code: 'untrusted-content-model-required', message: 'No eligible API provider has a default model.' };+ const sweep = async (app) => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});+ try { return { result: await processPendingMergePrs(app), lines: logged.mock.calls.map(call => String(call[0])) }; }+ finally { logged.mockRestore(); }+ };++ it('names the assessment code in the log line and the deadline notification', async () => {+ const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);+ mockApps.set(app.id, app);+ installPendingEvidence();+ screenMock.mockResolvedValue(modelRequired);+ const { lines } = await sweep(app);+ expect(lines.some(line => line.includes('Deterministic merge failed for PR #88') && line.includes('untrusted-content-model-required'))).toBe(true);+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({+ description: expect.stringContaining('untrusted-content-model-required'),+ }));+ });++ it('reports a thrown assessment as security-action-assessment-error', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ installPendingEvidence();+ screenMock.mockRejectedValue(new Error('boom'));+ const warned = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const { lines } = await sweep(app);+ warned.mockRestore();+ expect(lines.some(line => line.includes('security-action-assessment-error'))).toBe(true);+ });++ it('is not re-assessed, and takes no admission lease, while the head and policy are unchanged', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ installPendingEvidence();+ screenMock.mockResolvedValue(modelRequired);+ await sweep(app);+ expect(screenMock).toHaveBeenCalledTimes(1);+ expect(readPendingMergePrs(mockApps.get(app.id))[0].assessmentWithheld).toMatchObject({ headSha: 'a'.repeat(40), policy: 'policy-1' });++ // A live parent holding the lease would defer any entry that asked for it.+ const { claimMergeAdmission } = await import('./cosMergeAdmission.js');+ admissionState.state.agents.parent = { id: 'parent', taskId: 'task-parent', startedAt: '2026-01-01', status: 'running',+ metadata: { sourceWorkspace: '/repos/app1', claimPicksOwnBranch: true } };+ const lease = await claimMergeAdmission({ agentId: 'parent', action: 'acquire' });+ expect(lease.admitted).toBe(true);+ const held = await processPendingMergePrs(mockApps.get(app.id));+ expect(held.waiting || 0).toBe(0);+ expect(screenMock).toHaveBeenCalledTimes(1);+ expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(2);+ await claimMergeAdmission({ agentId: 'parent', action: 'release', token: lease.token, outcome: 'leave-open' });+ });++ it.each([+ ['a changed policy', () => fingerprintMock.mockResolvedValue('policy-2'), () => {}],+ ['a new head', () => {}, (e) => { e.pr.headRefOid = 'b'.repeat(40); }],+ ])('is assessed again after %s', async (_name, changePolicy, changeEvidence) => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ const evidence = installPendingEvidence();+ screenMock.mockResolvedValue(modelRequired);+ await sweep(app);+ changePolicy();+ changeEvidence(evidence);+ screenMock.mockResolvedValue({ ok: true, screening: { safe: true } });+ mergePrMock.mockResolvedValue({ success: true });+ expect(await processPendingMergePrs(mockApps.get(app.id))).toMatchObject({ merged: 1 });+ expect(screenMock).toHaveBeenCalledTimes(2);+ });++ it('does not cache a transport failure that can heal without a change', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ installPendingEvidence();+ screenMock.mockResolvedValue({ ok: false, code: 'untrusted-content-reasoner-failed' });+ await sweep(app);+ expect(readPendingMergePrs(mockApps.get(app.id))[0].assessmentWithheld).toBeUndefined();+ });+ });+it.each([['head', (e) => { e.pr.headRefOid = 'b'.repeat(40); }],['title', (e) => { e.pr.title = 'Rewritten title'; }],diff --git a/server/services/untrustedContent.js b/server/services/untrustedContent.jsindex 287b72fe3b..c9358eb87d 100644--- a/server/services/untrustedContent.js+++ b/server/services/untrustedContent.js@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto';import { CONTRIBUTION_SECURITY_ASSESSMENT, contributionSecurityAssessmentSchema } from '../lib/contributionSecurityPolicy.js';import { readSettingsStrict } from './settings.js';import { withAbortTimeout } from '../lib/abortTimeout.js';@@ -6,7 +7,7 @@ import { safeJSONParse } from '../lib/fileUtils.js';import { evaluateSecretEndpoint } from '../lib/aiToolkit/endpointGuard.js';import { getAllProviders } from './providers.js';import { modelAbuseContentFingerprint } from '../lib/modelAbuseGuard.js';-import { formatUntrustedContent, isUntrustedContentProvider, resolveUntrustedContentPolicy, UNTRUSTED_CONTENT_INSTRUCTIONS } from '../lib/untrustedContent.js';+import { formatUntrustedContent, isUntrustedContentProvider, resolveUntrustedContentPolicy, selectUntrustedContentProvider, UNTRUSTED_CONTENT_INSTRUCTIONS } from '../lib/untrustedContent.js';// Deep imports on purpose (#7473): both leaves are cheap (`ollamaContext.js`// is zero-dependency, `providerStatus.js` reaches only the `num_ctx` clamp it// already shares), unlike `services/stageRunner.js#effectiveContextWindow`,@@ -286,16 +287,55 @@ export async function runUntrustedContentAnalysis({ provider, model, content, prreturn analysis;}+/**+ * Whether contribution assessment for github-pr / github-issue can resolve a+ * provider and model under the current policy, for the Abuse Guard status.+ * Reports codes only; never provider endpoints or credentials.+ */+export async function getContributionAssessmentReadiness() {+ const state = await readSettingsStrict();+ if (state.corrupt) return { ready: false, sources: {}, code: 'untrusted-content-settings-unreadable' };+ const providers = (await getAllProviders()).providers || [];+ const sources = {};+ for (const source of ['github-pr', 'github-issue']) {+ const policy = resolveUntrustedContentPolicy(state.settings.untrustedContent, source);+ const selection = policy ? selectUntrustedContentProvider({ providers, policy, source }) : { code: 'untrusted-content-policy-invalid' };+ sources[source] = selection.provider+ ? { ready: true, providerId: selection.provider.id, model: selection.model }+ : { ready: false, code: selection.code };+ }+ const failed = Object.values(sources).find(entry => !entry.ready);+ return { ready: !failed, sources, ...(failed ? { code: failed.code } : {}) };+}++/**+ * Digest of everything that decides whether and how a GitHub PR assessment can+ * run: the resolved source policy and the provider/model it selects. A caller+ * that withheld an action for a configuration-caused failure compares this to+ * know when a settings or provider change makes a retry worthwhile.+ */+export async function getContributionAssessmentFingerprint(source = 'github-pr') {+ const state = await readSettingsStrict();+ if (state.corrupt) return 'settings-unreadable';+ const policy = resolveUntrustedContentPolicy(state.settings.untrustedContent, source);+ const providers = (await getAllProviders()).providers || [];+ const selection = policy ? selectUntrustedContentProvider({ providers, policy, source }) : null;+ const chosen = selection?.provider;+ return createHash('sha256').update(JSON.stringify({+ policy,+ selection: chosen+ ? { id: chosen.id, model: selection.model, endpoint: chosen.endpoint, numCtx: chosen.numCtx ?? null, contextWindow: chosen.contextWindow ?? null }+ : { code: selection?.code ?? 'untrusted-content-policy-invalid' },+ })).digest('hex');+}+// Private transport entry: only callers above can supply a completed screen.async function analyzeScreenedContent({ provider, model, content, prompt, source, responseSchema, screened }) {const config = screened.policy;const providers = provider ? [provider] : (await getAllProviders()).providers || [];- const selected = provider || (config.providerId- ? providers.find(item => item.id === config.providerId)- : providers.find(item => isUntrustedContentProvider(item, source)));- if (!isUntrustedContentProvider(selected, source)) return failure('untrusted-content-provider-unavailable', 'Configure an enabled text API provider in Models > LLMs > Abuse Guard. Private messages require a local API endpoint. CLI agents and provider fallback are disabled for external content.');- const effectiveModel = model || (provider && provider.id !== config.providerId ? null : config.model) || selected.defaultModel;- if (!effectiveModel) return failure('untrusted-content-model-required', 'Select an installed text model in Models > LLMs > Abuse Guard.');+ const selection = selectUntrustedContentProvider({ providers, policy: config, source, provider, model });+ if (!selection.provider) return failure(selection.code, selection.message);+ const { provider: selected, model: effectiveModel } = selection;const taskPrompt = `${UNTRUSTED_CONTENT_INSTRUCTIONS}\n\nTRUSTED TASK:\n${prompt}`;const evidence = formatUntrustedContent(content);const local = isUntrustedContentProvider(selected, 'messages');diff --git a/server/services/untrustedContent.test.js b/server/services/untrustedContent.test.jsindex d2f400920b..a05bf98cd2 100644--- a/server/services/untrustedContent.test.js+++ b/server/services/untrustedContent.test.js@@ -5,7 +5,7 @@ vi.mock('./modelAbuseGuard.js', () => ({ runModelAbuseScan: mocks.scan }));vi.mock('./settings.js', () => ({ readSettingsStrict: mocks.read }));vi.mock('./providers.js', () => ({ getAllProviders: mocks.providers }));vi.mock('./providerExecutionReadiness.js', () => ({ ensureProviderReadyForExecution: async () => ({ success: true }) }));-import { runUntrustedContentAnalysis, screenUntrustedContent } from './untrustedContent.js';+import { getContributionAssessmentReadiness, runUntrustedContentAnalysis, screenUntrustedContent } from './untrustedContent.js';const local = { id: 'local', type: 'api', enabled: true, endpoint: 'http://127.0.0.1:11434/v1', defaultModel: 'example-text' };const cloud = { ...local, id: 'cloud', contextWindow: 32768, endpoint: 'https://api.example.com/v1' };const args = { content: 'Example sender asks about a meeting.', prompt: 'Return {"action":"review"}.', source: 'messages', responseSchema: z.object({ action: z.literal('review') }).strict() };@@ -201,3 +201,39 @@ describe('GitHub security-model admission', () => {expect(mocks.fetch).not.toHaveBeenCalled();});});++// An Ollama-style provider that lists installed models but ships no+// defaultModel used to shadow every provider after it (outage behind #12584).+describe('automatic provider selection requires a resolvable model', () => {+ const noDefault = { ...local, id: 'no-default', defaultModel: null };+ const usable = { ...local, id: 'usable', endpoint: 'http://127.0.0.1:1234/v1', defaultModel: 'example-usable', numCtx: 16384, contextWindow: 32768 };+ it('skips an eligible provider without a default model for one that has it', async () => {+ mocks.providers.mockResolvedValue({ providers: [noDefault, usable] });+ expect(await screenUntrustedContent({ source: 'github-pr', content: 'A proposed change' })).toMatchObject({ ok: true });+ const [url, request] = mocks.fetch.mock.calls[0];+ expect(url).toBe('http://127.0.0.1:1234/v1/chat/completions');+ expect(JSON.parse(request.body).model).toBe('example-usable');+ });+ it('fails with model-required, and reports not ready, when no eligible provider resolves a model', async () => {+ mocks.providers.mockResolvedValue({ providers: [noDefault] });+ expect(await screenUntrustedContent({ source: 'github-pr', content: 'A proposed change' }))+ .toMatchObject({ ok: false, code: 'untrusted-content-model-required', message: expect.stringContaining('No eligible API provider has a default model') });+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(await getContributionAssessmentReadiness()).toMatchObject({+ ready: false, code: 'untrusted-content-model-required',+ sources: { 'github-pr': { ready: false }, 'github-issue': { ready: false } },+ });+ mocks.providers.mockResolvedValue({ providers: [noDefault, usable] });+ expect(await getContributionAssessmentReadiness()).toMatchObject({+ ready: true, sources: { 'github-pr': { ready: true, providerId: 'usable', model: 'example-usable' } },+ });+ });+ it('never switches providers when a pinned provider has no model', async () => {+ mocks.providers.mockResolvedValue({ providers: [noDefault, usable] });+ mocks.read.mockResolvedValue({ corrupt: false, settings: { untrustedContent: { defaults: { providerId: 'no-default' } } } });+ expect(await screenUntrustedContent({ source: 'github-pr', content: 'A proposed change' }))+ .toMatchObject({ ok: false, code: 'untrusted-content-model-required' });+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(await getContributionAssessmentReadiness()).toMatchObject({ ready: false, code: 'untrusted-content-model-required' });+ });+});