diff --git a/apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts b/apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts new file mode 100644 index 0000000000..a9451507da --- /dev/null +++ b/apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts @@ -0,0 +1,63 @@ +/** + * The VM agent tells a SAM AI usage-limit refusal from a provider overload by the refusal's + * message (packages/vm-agent/internal/acp/sam_usage_limit.go, samUsageLimitMarkers). Both are + * 429s, so if a message here drifts away from those markers, users see "Provider overloaded" + * again (idea 01M89JXTFHW4W3PQ65GTED6D0K). The markers are read from the Go source itself. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import { monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy'; +import { describe, expect, it } from 'vitest'; + +import { anthropicUsageGateError as anthropicSupportError } from '../../../src/routes/ai-proxy-anthropic-support'; +import { + anthropicUsageGateError, + openaiUsageGateError, +} from '../../../src/routes/ai-proxy-passthrough-errors'; + +/** The marker list as the VM agent compiles it, read from its source rather than copied. */ +function goMarkers(): string[] { + const source = readFileSync( + resolve(__dirname, '../../../../../packages/vm-agent/internal/acp/sam_usage_limit.go'), + 'utf8' + ); + const block = /var samUsageLimitMarkers = \[\]string\{([^}]*)\}/.exec(source)?.[1] ?? ''; + return [...block.matchAll(/"([^"]+)"/g)].map((m) => m[1]!); +} +const GO_MARKERS = goMarkers(); + +it('reads the VM agent marker list (a broken parse cannot pass as an empty list)', () => { + expect(GO_MARKERS).toHaveLength(3); + expect(GO_MARKERS.every((m) => m === m.toLowerCase())).toBe(true); +}); + +const administrator = { allowed: false, limitSource: 'administrator' } as Parameters< + typeof monthlyCostCapMessage +>[0]; + +describe('SAM AI usage-limit refusals carry a marker the VM agent recognizes', () => { + it.each([ + ['administrator ceiling', monthlyCostCapMessage(administrator)], + ['personal cap', monthlyCostCapMessage(undefined)], + ])('monthly message: %s', (_name, message) => { + expect(GO_MARKERS.some((marker) => message.toLowerCase().includes(marker))).toBe(true); + }); + + it.each([ + ['anthropic passthrough', anthropicUsageGateError], + ['anthropic support', anthropicSupportError], + ['openai passthrough', openaiUsageGateError], + ])('%s: every refusal is a 429 whose message has a marker', async (_name, build) => { + for (const response of [ + build('daily-token-budget'), + build('monthly-cost-cap', administrator), + build('monthly-cost-cap'), + ]) { + expect(response.status).toBe(429); + const body = (await response.json()) as { error: { message: string } }; + const message = body.error.message.toLowerCase(); + expect(GO_MARKERS.some((marker) => message.includes(marker))).toBe(true); + } + }); +}); diff --git a/apps/api/tests/unit/services/inbox-system-errors.test.ts b/apps/api/tests/unit/services/inbox-system-errors.test.ts index c0606149b2..094e9999a3 100644 --- a/apps/api/tests/unit/services/inbox-system-errors.test.ts +++ b/apps/api/tests/unit/services/inbox-system-errors.test.ts @@ -233,6 +233,18 @@ describe('failed tasks file one error item for their owner', () => { expect(errorAsks()[0]!.failure_count).toBe(1); }); + // Idea 01M89JXTFHW4W3PQ65GTED6D0K: a task that stops on SAM's AI usage limit has failed, and its + // owner must hear about it, without being told to retry. + it('files a task stopped by the SAM AI usage limit, with the limit sentence', async () => { + task('t-limit', { status: 'in_progress', started_at: new Date().toISOString() }); + await markTaskFailedIfNonTerminal(env.DATABASE, 't-limit', 'sam_ai_usage_limit_reached'); + expect((await runInboxSystemErrorSweep(env)).filed).toBe(1); + const [item] = (await listInbox(ctx('owner'), { projectId: P1 })).items; + expect(item?.taskId).toBe('t-limit'); + expect(item?.body).toMatch(/AI usage limit was reached/); + expect(edges.createNotification).toHaveBeenCalledTimes(1); + }); + it('does not offer Retry to a task owner who cannot run the project owner’s retry', async () => { task('t-colleague', { user_id: 'colleague' }); await markTaskFailedIfNonTerminal(env.DATABASE, 't-colleague', 'Session creation failed'); diff --git a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx index 1e2c4ae518..184b2c8a43 100644 --- a/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx +++ b/apps/web/src/components/ai-usage/AiBudgetSettingsSection.tsx @@ -23,7 +23,7 @@ function BudgetBar({ }) { const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0; const format = unit === '$' ? formatCost : formatTokens; - const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent-emphasis'; + const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent'; return (
diff --git a/apps/web/src/components/ai-usage/AiUsageSection.tsx b/apps/web/src/components/ai-usage/AiUsageSection.tsx index ee99cec1c3..1fca287e90 100644 --- a/apps/web/src/components/ai-usage/AiUsageSection.tsx +++ b/apps/web/src/components/ai-usage/AiUsageSection.tsx @@ -49,7 +49,7 @@ export function AiUsageSection() {
LLM Usage - SAM-managed AI Gateway traffic only + Model calls made through SAM only
{AI_PERIODS.map((opt) => ( @@ -60,7 +60,7 @@ export function AiUsageSection() { onClick={() => handlePeriodChange(opt.value)} className={`px-3 py-2.5 rounded-md text-sm font-medium transition-colors min-h-[44px] ${ period === opt.value - ? 'bg-accent-emphasis text-fg-on-accent' + ? 'bg-accent text-fg-on-accent' : 'bg-surface text-fg-muted hover:bg-surface-hover border border-border-default' }`} > @@ -87,8 +87,8 @@ export function AiUsageSection() {
)}
diff --git a/apps/web/src/components/project-chat/attachments/ComposerAttachmentList.tsx b/apps/web/src/components/project-chat/attachments/ComposerAttachmentList.tsx index de312ab355..11ab6fa225 100644 --- a/apps/web/src/components/project-chat/attachments/ComposerAttachmentList.tsx +++ b/apps/web/src/components/project-chat/attachments/ComposerAttachmentList.tsx @@ -175,7 +175,7 @@ function AttachmentItem({ attachment: a, onOpen, onRemove, disabled }: ItemProps {(a.status === 'uploading' || a.status === 'pending') && ( )} diff --git a/apps/web/src/components/task/TaskSubmitForm.tsx b/apps/web/src/components/task/TaskSubmitForm.tsx index 4965c036dd..da5393642c 100644 --- a/apps/web/src/components/task/TaskSubmitForm.tsx +++ b/apps/web/src/components/task/TaskSubmitForm.tsx @@ -333,7 +333,7 @@ export const TaskSubmitForm: FC = ({ {att.status === 'uploading' && (
)} diff --git a/apps/web/tests/playwright/ai-usage-audit.spec.ts b/apps/web/tests/playwright/ai-usage-audit.spec.ts index 92b812d128..57b8e2faf8 100644 --- a/apps/web/tests/playwright/ai-usage-audit.spec.ts +++ b/apps/web/tests/playwright/ai-usage-audit.spec.ts @@ -1,5 +1,7 @@ import { expect, type Page, type Route, test } from '@playwright/test'; +import { assertNoOverflow as assertNoClippedOrDocumentOverflow, seedTheme } from './audit-helpers'; + // --------------------------------------------------------------------------- // Mock Data // --------------------------------------------------------------------------- @@ -138,6 +140,10 @@ type MockOptions = { async function setupMocks(page: Page, options: MockOptions = {}) { const aiUsageData = options.aiUsage ?? makeAiUsageResponse(); + // Without this the first-run setup dialog covers the page and screenshots show the dialog. + await page.addInitScript(() => { + localStorage.setItem('sam-onboarding-wizard-dismissed-user-test-1', 'true'); + }); await page.route('**/api/**', async (route: Route) => { const url = new URL(route.request().url()); @@ -156,6 +162,25 @@ async function setupMocks(page: Page, options: MockOptions = {}) { if (path === '/api/projects') return respond(200, { projects: [] }); if (path.endsWith('/health')) return respond(200, { status: 'ok' }); + // Budget settings (AiBudgetSettingsSection), the shape GET /api/usage/ai/budget returns. + if (path === '/api/usage/ai/budget') { + return respond(200, { + settings: { + dailyInputTokenLimit: null, + dailyOutputTokenLimit: null, + monthlyCostCapUsd: 10, + alertThresholdPercent: 80, + }, + isCustom: true, + dailyUsage: { inputTokens: 120_000, outputTokens: 40_000 }, + effectiveLimits: { dailyInputTokenLimit: 500_000, dailyOutputTokenLimit: 200_000 }, + monthCostUsd: 4.2, + monthlyCostCap: { available: true, ceilingUsd: null, effectiveCapUsd: 10 }, + utilization: { dailyInputPercent: 24, dailyOutputPercent: 20, monthlyCostPercent: 42 }, + exceeded: false, + }); + } + // AI usage endpoint if (path === '/api/usage/ai') { if (options.aiUsageError) return respond(500, { error: 'Gateway error' }); @@ -332,7 +357,10 @@ test.describe('AI Usage — Mobile (375x667)', () => { test('disclaimer text visible', async ({ page }) => { await setupMocks(page); await goToUsage(page); - await expect(page.locator('text=SAM-managed AI Gateway traffic only')).toBeVisible(); + await expect( + page.getByText('Model calls made through SAM only', { exact: true }) + ).toBeVisible(); + await expect(page.getByText('AI Gateway', { exact: false })).toHaveCount(0); await screenshot(page, 'ai-usage-disclaimer-mobile'); await assertNoOverflow(page); }); @@ -350,8 +378,8 @@ test.describe('AI Usage — Desktop (1280x800)', () => { await goToUsage(page); await expect(page.locator('text=LLM Usage')).toBeVisible(); await expect(page.locator('text=Total Cost')).toBeVisible(); - await expect(page.locator('text=Input Tokens')).toBeVisible(); - await expect(page.locator('text=Output Tokens')).toBeVisible(); + await expect(page.getByText('Input Tokens', { exact: true })).toBeVisible(); + await expect(page.getByText('Output Tokens', { exact: true })).toBeVisible(); await screenshot(page, 'ai-usage-normal-desktop'); await assertNoOverflow(page); }); @@ -384,3 +412,27 @@ test.describe('AI Usage — Desktop (1280x800)', () => { await assertNoOverflow(page); }); }); + +// Idea 01M89JXTFHW4W3PQ65GTED6D0K: the selected period button used `bg-accent-emphasis`, which is +// not a defined token, so its white label sat on no background (invisible in the light theme). +for (const theme of ['light', 'dark'] as const) { + test(`selected period button is readable (${theme} theme)`, async ({ page }, testInfo) => { + await seedTheme(page, theme); + await setupMocks(page); + await goToUsage(page); + const selected = page.getByRole('button', { name: 'This Month', pressed: true }); + await expect(selected).toBeVisible(); + const colors = await selected.evaluate((el) => { + const style = getComputedStyle(el); + return { bg: style.backgroundColor, fg: style.color }; + }); + // A painted background, distinct from the label colour. + expect(colors.bg).not.toBe('rgba(0, 0, 0, 0)'); + expect(colors.bg).not.toBe(colors.fg); + await page.getByRole('button', { name: '7 Days' }).click(); + await expect(page.getByRole('button', { name: '7 Days', pressed: true })).toBeVisible(); + await assertNoClippedOrDocumentOverflow(page); + const viewport = testInfo.project.name.includes('Desktop') ? 'desktop' : 'mobile'; + await screenshot(page, `ai-usage-period-${theme}-${viewport}`); + }); +} diff --git a/apps/web/tests/playwright/project-chat-recoverable-error-audit.spec.ts b/apps/web/tests/playwright/project-chat-recoverable-error-audit.spec.ts index d93bb1bdb4..7c0166cc06 100644 --- a/apps/web/tests/playwright/project-chat-recoverable-error-audit.spec.ts +++ b/apps/web/tests/playwright/project-chat-recoverable-error-audit.spec.ts @@ -199,6 +199,27 @@ async function assertNoHorizontalOverflow(page: Page) { } test.describe('Project chat recoverable error banner', () => { + // Idea 01M89JXTFHW4W3PQ65GTED6D0K: SAM's own AI usage limit read as "Provider overloaded". + for (const [code, label, recoverable] of [ + ['sam_ai_usage_limit_reached', 'AI usage limit reached', false], + ['provider_overloaded', 'Provider overloaded', true], + ] as const) { + test(`failure card for ${code}`, async ({ page }, testInfo) => { + await setupApiMocks( + page, + { ...MOCK_TASK, errorMessage: code, executionStep: code }, + true, + MOCK_MESSAGES + ); + await page.goto('/projects/proj-test-1/chat/session-recoverable-1'); + await expect(page.getByText(label, { exact: true })).toBeVisible(); + await expect(page.getByText('Recoverable', { exact: true })).toHaveCount(recoverable ? 1 : 0); + await assertNoHorizontalOverflow(page); + const viewport = testInfo.project.name.includes('Desktop') ? 'desktop' : 'mobile'; + await screenshot(page, `chat-failure-${code}-${viewport}`); + }); + } + test('startup missing credential reaches existing agent connections', async ({ page }, testInfo) => { const systemMessage = { ...MOCK_MESSAGES[0], diff --git a/apps/web/tests/playwright/visual-audit-quarantine.txt b/apps/web/tests/playwright/visual-audit-quarantine.txt index c5d98a3521..f37268add6 100644 --- a/apps/web/tests/playwright/visual-audit-quarantine.txt +++ b/apps/web/tests/playwright/visual-audit-quarantine.txt @@ -19,7 +19,6 @@ admin-users-signup-approval-audit.spec.ts agent-context-audit.spec.ts agent-crash-report-audit.spec.ts agent-guided-connect-audit.spec.ts -ai-usage-audit.spec.ts auth-flows-audit.spec.ts chat-dom-bound-audit.spec.ts chat-file-viewer-audit.spec.ts diff --git a/apps/web/tests/unit/debug-failure-card.test.tsx b/apps/web/tests/unit/debug-failure-card.test.tsx index 04fe208f09..91755e1f3d 100644 --- a/apps/web/tests/unit/debug-failure-card.test.tsx +++ b/apps/web/tests/unit/debug-failure-card.test.tsx @@ -186,6 +186,51 @@ describe('FailureCard', () => { expect(screen.getByText('Recoverable')).toBeInTheDocument(); }); + // Idea 01M89JXTFHW4W3PQ65GTED6D0K: SAM's own usage limit is not a provider overload, and + // retrying in the same conversation cannot help until the limit changes. + it('shows the AI usage limit without a Recoverable badge or retry advice', async () => { + renderWithQuery( + + ); + + expect(screen.getByText('AI usage limit reached')).toBeInTheDocument(); + expect(screen.queryByText('Provider overloaded')).not.toBeInTheDocument(); + expect(screen.queryByText('Recoverable')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { expanded: false })); + expect(await screen.findByText(/Settings > Usage/)).toBeInTheDocument(); + expect(screen.queryByText(/Send another message to retry/)).not.toBeInTheDocument(); + expect(screen.getByText(/This session is still open. Fix the cause above/)).toBeInTheDocument(); + }); + + it('control: a real provider overload still reads as recoverable', async () => { + renderWithQuery( + + ); + + expect(screen.getByText('Provider overloaded')).toBeInTheDocument(); + expect(screen.getByText('Recoverable')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { expanded: false })); + expect(await screen.findByText(/Send another message to retry/)).toBeInTheDocument(); + }); + it('expands detail on click', async () => { renderWithQuery( { it.each([ ['task failed', { task: { id: 't-1', status: 'failed' } }, 'failed'], + // SAM's AI usage limit ended the task: a failure the owner must see, not a normal stop. + [ + 'task failed on the SAM AI usage limit', + { task: { id: 't-1', status: 'failed', errorMessage: 'sam_ai_usage_limit_reached' } }, + 'failed', + ], ['task completed', { task: { id: 't-1', status: 'completed' } }, 'completed'], ['task cancelled', { task: { id: 't-1', status: 'cancelled' } }, 'stopped'], ['session failed', { status: 'failed' }, 'error'], diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index e98426ee8d..dbda3ee792 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -2273,6 +2273,10 @@ logged as `ai_proxy.monthly_cost_ceiling_unreadable`. The same protection applie isolate; no extra last-known ceiling is reused during an outage (`services/ai-proxy-ports.ts`). Gateway calls and locally own-funded calls do not read this ceiling. A failed monthly-spend read also refuses inference with a retryable 503, without reporting that the cap has been reached. +A call refused by the monthly cap or the daily token budget is a 429 whose message names that +limit. The VM agent reports it as `sam_ai_usage_limit_reached`, not `provider_overloaded`, so the +chat shows "AI usage limit reached" without a retry suggestion +(`packages/vm-agent/internal/acp/sam_usage_limit.go`, `packages/shared/src/failure-classification.ts`). Once a ceiling is set, every gated call on such an installation reads the month's priced total (one Durable Object call), not only calls by users with their own cap. Passthrough calls served by a platform-owned credential are priced too; a user's or project's own credential diff --git a/deploy/selfhost/README.md b/deploy/selfhost/README.md index 0eddaa21e2..cfccc16251 100644 --- a/deploy/selfhost/README.md +++ b/deploy/selfhost/README.md @@ -203,8 +203,14 @@ backup, still hold the value until later seals replace them. in `secrets.env` plus the admin settings `aiProxy.testUpstreamUserIds` and `aiProxy.directUpstreamEnabled` make the listed users' SAM-managed model calls get a metered fake reply (configuration reference, "Test-only fake AI upstream"). Remove it with `--unset` as above. -Create `secrets.env` with a normal umask in its own shell: a restrictive umask inherited by -`pnpm selfhost:upgrade` makes the checked-out files unreadable to the key agent. +The operator commands (`selfhost:upgrade`, its rollback, `selfhost:deploy`, `selfhost:rebuild`, +`selfhost:restore`) clear any umask bits stricter than `022` (so `umask 077` runs as `022`). After every checkout they make +the tracked files readable by everyone again. A restrictive umask (for example `umask 077` while +creating `secrets.env`) therefore cannot leave checked-out files unreadable to the key agent +(`scripts/selfhost/operator-files.ts`). Private files (`.state/`, backups, keys) are written 0600 +in 0700 directories by their writers, not by the umask. An upgrade runs the upgrader already +checked out, so the first upgrade *from* a version without this protection still needs a normal +umask (`umask 022`). **Switching providers** is never a silent change at a deploy: diff --git a/packages/shared/src/failure-classification.ts b/packages/shared/src/failure-classification.ts index 01aba1793e..238fe8a8eb 100644 --- a/packages/shared/src/failure-classification.ts +++ b/packages/shared/src/failure-classification.ts @@ -21,6 +21,7 @@ export type FailureCode = | 'mcp-auth-required' | 'unsupported-loopback-auth' | 'model-unavailable' + | 'sam-ai-usage-limit' | 'provider-overload' | 'agent-prompt-failed' | 'prompt-timeout' @@ -164,6 +165,21 @@ const FAILURE_RULES: FailureRule[] = [ diagnosable: true, patterns: [/^model_provider_credential_rejected$/], }, + { + // Emitted by the VM agent when the 429 came from SAM's own AI proxy limit (monthly spending + // limit or daily token budget), not from the provider (vm-agent internal/acp/sam_usage_limit.go). + code: 'sam-ai-usage-limit', + label: 'AI usage limit reached', + explanation: + 'SAM refused the model call because your AI usage limit was reached (a monthly spending limit or the daily token budget).', + guidance: + 'Retrying will not help until the limit resets. Check Settings > Usage, or ask an administrator to raise the limit.', + retryable: false, + // A task that stops on its usage limit has failed: the inbox system-error item and the + // failed-session grouping both read `diagnosable` (inbox/system-errors.ts, chat-session-utils.ts). + diagnosable: true, + patterns: [/^sam_ai_usage_limit_reached$/], + }, { code: 'provider-overload', label: 'Provider overloaded', @@ -322,6 +338,7 @@ const STRUCTURAL_FAILURE_CODES = new Set([ 'model-credential-missing', 'model-credential-rejected', 'agent-prompt-failed', + 'sam-ai-usage-limit', ]); /** diff --git a/packages/shared/tests/unit/failure-classification.test.ts b/packages/shared/tests/unit/failure-classification.test.ts index 28a767d267..6467c2dd73 100644 --- a/packages/shared/tests/unit/failure-classification.test.ts +++ b/packages/shared/tests/unit/failure-classification.test.ts @@ -162,3 +162,44 @@ describe('classifyFailure', () => { } ); }); + +// Idea 01M89JXTFHW4W3PQ65GTED6D0K: a refusal by SAM's own AI usage limit (a 429 from the SAM +// AI proxy) read as "Provider overloaded · Recoverable". The VM agent now reports it as its own code. +describe('SAM AI usage limit', () => { + it('shows the usage-limit outcome, not a provider overload, and does not suggest a retry', () => { + expect(classifyFailure('sam_ai_usage_limit_reached', 'sam_ai_usage_limit_reached')).toEqual({ + code: 'sam-ai-usage-limit', + label: 'AI usage limit reached', + explanation: expect.stringContaining('monthly spending limit'), + guidance: expect.stringContaining('Settings > Usage'), + retryable: false, + diagnosable: true, + }); + }); + + it.each([ + ['provider_overloaded', undefined], + ['provider_overloaded', 'provider_overloaded'], + ['Provider returned 529 overloaded', undefined], + ['Rate limit exceeded (429 Too Many Requests)', undefined], + ])('control: a real provider overload is unchanged (%s)', (message, step) => { + expect(classifyFailure(message, step)).toEqual({ + code: 'provider-overload', + label: 'Provider overloaded', + explanation: 'The LLM provider was temporarily overloaded or rate-limited the request.', + guidance: 'This is usually transient. Wait a few minutes and retry.', + retryable: true, + diagnosable: true, + }); + }); + + it.each([ + ['provider_overloaded', 'sam_ai_usage_limit_reached'], + ['Assistant said sam_ai_usage_limit_reached after a 429', undefined], + ])( + 'is only taken from the exact callback code, never from steps or text (%s)', + (message, step) => { + expect(classifyFailure(message, step).code).toBe('provider-overload'); + } + ); +}); diff --git a/packages/vm-agent/internal/acp/auth_failure.go b/packages/vm-agent/internal/acp/auth_failure.go index 2da92fb249..900f6262ea 100644 --- a/packages/vm-agent/internal/acp/auth_failure.go +++ b/packages/vm-agent/internal/acp/auth_failure.go @@ -13,6 +13,10 @@ import ( // would either miss provider failures or let untrusted metadata spoof one. // MCP tool errors without explicit source evidence stay generic. func ClassifyPromptError(err error) string { + // Before the provider-limit and overload checks: SAM's own limit is also a 429. + if isSAMUsageLimitRequestError(err) { + return samUsageLimitReason + } if limit := ClassifyProviderLimit(err, time.Now()); limit != nil { return limit.Error() } @@ -57,7 +61,7 @@ func ClassifyPromptError(err error) string { func ClassifyPromptFailure(message string) string { text := strings.ToLower(strings.TrimSpace(strings.SplitN(message, "\n", 2)[0])) switch text { - case "model_provider_credential_missing", "model_provider_credential_rejected", "model_unavailable", "provider_overloaded", "provider_limit_reached", "agent_crash", "network_error": + case "model_provider_credential_missing", "model_provider_credential_rejected", "model_unavailable", "provider_overloaded", "provider_limit_reached", samUsageLimitReason, "agent_crash", "network_error": return text } for _, marker := range []string{" url=", " schema=", " https://", " http://"} { @@ -65,16 +69,20 @@ func ClassifyPromptFailure(message string) string { text = text[:at] } } - if (strings.HasPrefix(text, "provider ") || strings.HasPrefix(text, "api error: ") || strings.HasPrefix(text, "internal error: api error: ")) && + if hasProviderErrorPrefix(text) && (strings.Contains(text, "unsupported_model") || strings.Contains(text, "model_not_supported") || (strings.Contains(text, "model") && (strings.Contains(text, "not supported") || strings.Contains(text, "not available for")))) { return "model_unavailable" } - if (strings.HasPrefix(text, "provider ") && (strings.Contains(text, "http 401") || strings.Contains(text, "invalid_api_key") || strings.Contains(text, "invalid authentication"))) || - (strings.HasPrefix(text, "api error: 401") || strings.HasPrefix(text, "internal error: api error: 401")) { + if (strings.HasPrefix(text, providerPrefix) && (strings.Contains(text, "http 401") || strings.Contains(text, "invalid_api_key") || strings.Contains(text, "invalid authentication"))) || + (strings.HasPrefix(text, apiErrorPrefix+"401") || strings.HasPrefix(text, internalAPIErrorPrefix+"401")) { return "model_provider_credential_rejected" } - if (strings.HasPrefix(text, "provider ") || strings.HasPrefix(text, "api error: ") || strings.HasPrefix(text, "internal error: api error: ")) && + // SAM's own proxy limit is a 429 too; it must not read as a provider overload. + if hasProviderErrorPrefix(text) && isSAMUsageLimitText(text) { + return samUsageLimitReason + } + if hasProviderErrorPrefix(text) && (strings.Contains(text, "http 429") || strings.Contains(text, "http 529") || strings.Contains(text, "http 503") || strings.Contains(text, "rate limit") || strings.Contains(text, "overloaded")) { return "provider_overloaded" } @@ -86,3 +94,15 @@ func ClassifyPromptFailure(message string) string { } return "" } + +// The source prefixes a provider failure's first line carries (lowercased). Arbitrary MCP or +// tool text without one of them never classifies as a provider failure. +const ( + providerPrefix = "provider " + apiErrorPrefix = "api error: " + internalAPIErrorPrefix = "internal error: " + apiErrorPrefix +) + +func hasProviderErrorPrefix(text string) bool { + return strings.HasPrefix(text, providerPrefix) || strings.HasPrefix(text, apiErrorPrefix) || strings.HasPrefix(text, internalAPIErrorPrefix) +} diff --git a/packages/vm-agent/internal/acp/provider_limit.go b/packages/vm-agent/internal/acp/provider_limit.go index 96aa35eb1a..4d2771cc2e 100644 --- a/packages/vm-agent/internal/acp/provider_limit.go +++ b/packages/vm-agent/internal/acp/provider_limit.go @@ -35,6 +35,10 @@ func ClassifyProviderLimit(err error, now time.Time) *ProviderLimitError { if errors.As(err, &safe) { return safe } + // SAM's own proxy limit is not the provider's plan limit: never park it for a reset. + if isSAMUsageLimitRequestError(err) { + return nil + } var request *acpsdk.RequestError if errors.As(err, &request) { if request.Code != -32603 { @@ -85,7 +89,7 @@ func ClassifyProviderLimit(err error, now time.Time) *ProviderLimitError { if isPlanLimitMessage(text) { return &ProviderLimitError{ResetsAt: clockReset(text, now)} } - if strings.HasPrefix(text, "Provider HTTP 429") || strings.HasPrefix(text, "API Error: 429") { + if (strings.HasPrefix(text, "Provider HTTP 429") || strings.HasPrefix(text, "API Error: 429")) && !hasSAMUsageLimitMarker(text) { // Reset-bearing API failures are also allowed to use an ISO timestamp. for _, word := range strings.Fields(text) { if parsed, e := time.Parse(time.RFC3339, strings.Trim(word, `",;`)); e == nil && parsed.After(now) { diff --git a/packages/vm-agent/internal/acp/sam_usage_limit.go b/packages/vm-agent/internal/acp/sam_usage_limit.go new file mode 100644 index 0000000000..ef43860c08 --- /dev/null +++ b/packages/vm-agent/internal/acp/sam_usage_limit.go @@ -0,0 +1,84 @@ +package acp + +import ( + "errors" + "regexp" + "strings" + + acpsdk "github.com/coder/acp-go-sdk" +) + +// samUsageLimitReason is the prompt failure code for a refusal by SAM's own AI proxy +// spending or token limit. The UI maps it to "SAM AI usage limit reached" +// (packages/shared/src/failure-classification.ts), not to a provider overload: +// retrying does not help until the limit resets or an administrator changes it. +const samUsageLimitReason = "sam_ai_usage_limit_reached" + +// samUsageLimitMarkers are the messages the SAM AI proxy returns with HTTP 429 when +// its own limit refuses a call. Keep in sync with monthlyCostCapMessage +// (packages/ai-proxy/src/ai-monthly-cost-cap.ts) and the daily token budget refusal +// (apps/api/src/routes/ai-proxy-admission.ts); apps/api tests pin the TS side. +var samUsageLimitMarkers = []string{ + "monthly ai spending limit reached", + "monthly cost cap exceeded", + "daily token budget exceeded", +} + +func hasSAMUsageLimitMarker(message string) bool { + text := strings.ToLower(message) + for _, marker := range samUsageLimitMarkers { + if strings.Contains(text, marker) { + return true + } + } + return false +} + +// status429 is a standalone 429 (not part of a longer number such as a request id). +var status429 = regexp.MustCompile(`(^|[^0-9])429([^0-9]|$)`) + +// isSAMUsageLimitText reports a 429 whose message is a SAM AI proxy limit refusal. +// A provider's own 429 (rate limit, overload) never carries these sentences, so a +// real overload keeps classifying as provider_overloaded. +func isSAMUsageLimitText(message string) bool { + return status429.MatchString(message) && hasSAMUsageLimitMarker(message) +} + +// apiError429 is the terminal API error prefix the pinned adapters give an HTTP 429. +func apiError429(message string) bool { + text := strings.ToLower(message) + // "request rejected (429)" is how claude-agent-acp 0.102.0 words it (sam_usage_limit_live_test.go). + for _, prefix := range []string{internalAPIErrorPrefix + "429", apiErrorPrefix + "429", internalAPIErrorPrefix + "request rejected (429)", apiErrorPrefix + "request rejected (429)"} { + if strings.HasPrefix(text, prefix) { + return true + } + } + return false +} + +// isSAMUsageLimitRequestError reads only the terminal error message fields the +// adapters put the API error in (RequestError.Message, or data.message under a +// generic "Internal error"), never other wrapper metadata such as URLs or schemas. +func isSAMUsageLimitRequestError(err error) bool { + var request *acpsdk.RequestError + if !errors.As(err, &request) || request.Code != -32603 { + return false + } + data, _ := request.Data.(map[string]any) + if data["errorKind"] == "authentication_failed" || data["codexErrorInfo"] == "unauthorized" { + return false + } + message := request.Message + if message == "Internal error" { + message, _ = data["message"].(string) + } + if !hasSAMUsageLimitMarker(message) { + return false + } + // Structured evidence that this was an HTTP 429 from the model endpoint, as the + // provider-limit classifier requires: Claude's typed rate_limit, a Codex turn + // error, or the adapter's own "API Error: 429" prefix. A marker in arbitrary + // echoed text is not enough. + _, codex := data["codexErrorInfo"].(string) + return data["errorKind"] == "rate_limit" || (codex && isSAMUsageLimitText(message)) || apiError429(message) +} diff --git a/packages/vm-agent/internal/acp/sam_usage_limit_live_test.go b/packages/vm-agent/internal/acp/sam_usage_limit_live_test.go new file mode 100644 index 0000000000..140d53ef28 --- /dev/null +++ b/packages/vm-agent/internal/acp/sam_usage_limit_live_test.go @@ -0,0 +1,112 @@ +package acp + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "sync/atomic" + "testing" + "time" + + acpsdk "github.com/coder/acp-go-sdk" +) + +// Opt-in contract test with the real pinned Claude ACP adapter (idea 01M89JXTFHW4W3PQ65GTED6D0K). +// The adapter talks to a local server that answers every model call with the exact 429 the SAM +// AI proxy sends, and the error the adapter returns over ACP is classified the way the prompt +// path classifies it. The control answers with a provider's own 429, which must stay +// provider_overloaded. Never contacts a model. +// +// SAM_LIVE_CLAUDE_ACP=$(command -v claude-agent-acp) go test ./internal/acp -run LiveClaudeAdapter -v +func TestLiveClaudeAdapterSAMUsageLimit(t *testing.T) { + adapter := os.Getenv("SAM_LIVE_CLAUDE_ACP") + if adapter == "" { + t.Skip("set SAM_LIVE_CLAUDE_ACP to the claude-agent-acp binary") + } + for _, tc := range []struct{ name, body, want string }{ + {"administrator monthly ceiling", samAdminCapBody, samUsageLimitReason}, + {"personal monthly cap", samUserCapBody, samUsageLimitReason}, + {"daily token budget", samDailyBody, samUsageLimitReason}, + {"control: provider rate limit", providerRateBody, "provider_overloaded"}, + } { + t.Run(tc.name, func(t *testing.T) { + promptErr, calls := promptLiveClaudeAdapter(t, adapter, tc.body) + if calls == 0 { + t.Fatal("the adapter never reached the local model server") + } + if got := ClassifyPromptError(promptErr); got != tc.want { + t.Fatalf("reason = %q, want %q", got, tc.want) + } + }) + } +} + +// promptLiveClaudeAdapter runs one prompt through the real adapter against a local server that +// answers every model call with a 429 carrying body. Returns the prompt error and the call count. +func promptLiveClaudeAdapter(t *testing.T, adapter, body string) (error, int32) { + t.Helper() + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("retry-after", "0") + w.Header().Set("x-should-retry", "false") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, body) + })) + defer server.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, adapter) + cmd.Env = append(os.Environ(), + "ANTHROPIC_BASE_URL="+server.URL, + "ANTHROPIC_API_KEY=sk-test-not-a-real-key", + "HOME="+t.TempDir(), + "CLAUDE_CODE_MAX_RETRIES=0", + "DISABLE_TELEMETRY=1", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", + ) + cmd.Stderr = io.Discard + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + + host := newTestSessionHost(t) + defer host.Stop() + conn := acpsdk.NewClientSideConnection(&sessionHostClient{host: host}, stdin, stdout) + if _, err := conn.Initialize(ctx, acpsdk.InitializeRequest{ProtocolVersion: acpsdk.ProtocolVersionNumber}); err != nil { + t.Fatalf("initialize: %v", err) + } + session, err := conn.NewSession(ctx, acpsdk.NewSessionRequest{Cwd: t.TempDir(), McpServers: []acpsdk.McpServer{}}) + if err != nil { + t.Fatalf("new session: %v", err) + } + _, promptErr := conn.Prompt(ctx, acpsdk.PromptRequest{ + SessionId: session.SessionId, + Prompt: []acpsdk.ContentBlock{acpsdk.TextBlock("Reply with PONG.")}, + }) + if promptErr == nil { + t.Fatal("prompt succeeded against a server that only answers 429") + } + var request *acpsdk.RequestError + if errors.As(promptErr, &request) { + data, _ := json.Marshal(request.Data) + t.Logf("adapter error: code=%d message=%.160q data=%.240s (model calls: %d)", request.Code, request.Message, data, calls.Load()) + } + return promptErr, calls.Load() +} diff --git a/packages/vm-agent/internal/acp/sam_usage_limit_test.go b/packages/vm-agent/internal/acp/sam_usage_limit_test.go new file mode 100644 index 0000000000..769e8004d5 --- /dev/null +++ b/packages/vm-agent/internal/acp/sam_usage_limit_test.go @@ -0,0 +1,133 @@ +package acp + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + acpsdk "github.com/coder/acp-go-sdk" +) + +// The bodies SAM's AI proxy sends with its own 429s (ai-proxy-admission.ts). +const ( + samAdminCapBody = `{"error":{"message":"Administrator monthly AI spending limit reached. Contact your administrator or wait until next month.","type":"rate_limit_error","monthlyCost":{"usedUsd":5.01,"limitUsd":5}}}` + samUserCapBody = `{"error":{"message":"Monthly cost cap exceeded. Adjust your cap in Settings > Usage.","type":"rate_limit_error"}}` + samDailyBody = `{"error":{"message":"Daily token budget exceeded. Resets at midnight UTC.","type":"rate_limit_error"}}` + providerRateBody = `{"type":"error","error":{"type":"rate_limit_error","message":"Number of request tokens has exceeded your per-minute rate limit"}}` +) + +func wireRequestError(t *testing.T, wire string) *acpsdk.RequestError { + t.Helper() + var requestError acpsdk.RequestError + if err := json.Unmarshal([]byte(wire), &requestError); err != nil { + t.Fatal(err) + } + return &requestError +} + +func jsonString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +func TestSAMUsageLimitRefusalIsNotAProviderOverload(t *testing.T) { + for _, tc := range []struct { + name, wire, want string + }{ + // The exact shape the pinned claude-agent-acp 0.102.0 returns (sam_usage_limit_live_test.go). + {"Claude 0.102.0 wire shape", `{"code":-32603,"message":"Internal error: API Error: Request rejected (429) · Administrator monthly AI spending limit reached. Contact your administrator or wait until next month.","data":{"errorKind":"rate_limit"}}`, samUsageLimitReason}, + {"control: Claude 0.102.0 wire shape for a provider 429", `{"code":-32603,"message":"Internal error: API Error: Request rejected (429) · Number of request tokens has exceeded your per-minute rate limit","data":{"errorKind":"rate_limit"}}`, "provider_overloaded"}, + {"Claude admin monthly ceiling", `{"code":-32603,"message":` + jsonString("Internal error: API Error: 429 "+samAdminCapBody) + `,"data":{"errorKind":"rate_limit"}}`, samUsageLimitReason}, + {"Claude user monthly cap, nested", `{"code":-32603,"message":"Internal error","data":{"errorKind":"rate_limit","message":` + jsonString("API Error: 429 "+samUserCapBody) + `}}`, samUsageLimitReason}, + {"Claude daily token budget", `{"code":-32603,"message":` + jsonString("Internal error: API Error: 429 "+samDailyBody) + `,"data":{"errorKind":"rate_limit"}}`, samUsageLimitReason}, + {"typed rate_limit without the status in the text", `{"code":-32603,"message":"Internal error","data":{"errorKind":"rate_limit","message":"Administrator monthly AI spending limit reached."}}`, samUsageLimitReason}, + {"Codex retry exhaustion on SAM's 429", `{"code":-32603,"message":"Internal error","data":{"codexErrorInfo":"usageLimitExceeded","message":` + jsonString("exceeded retry limit, last status: 429 Too Many Requests, "+samAdminCapBody) + `}}`, samUsageLimitReason}, + // Controls: hosted and self-hosted provider overloads keep their classification. + {"control: provider rate limit", `{"code":-32603,"message":` + jsonString("Internal error: API Error: 429 "+providerRateBody) + `,"data":{"errorKind":"rate_limit"}}`, "provider_overloaded"}, + {"control: provider overloaded", `{"code":-32603,"message":"Internal error: API Error: 529 overloaded_error","data":{"errorKind":"overloaded"}}`, "provider_overloaded"}, + {"control: marker only in wrapper metadata", `{"code":-32603,"message":"Internal error","data":{"errorKind":"rate_limit","message":"API Error: 429 slow down","url":"https://evil.example/monthly ai spending limit reached 429"}}`, "provider_overloaded"}, + {"control: untyped top-level message echoing the marker", `{"code":-32603,"message":"tool said: daily token budget exceeded (429)","data":{}}`, ""}, + {"control: overloaded kind with the marker in echoed text", `{"code":-32603,"message":"Internal error","data":{"errorKind":"overloaded","message":"note: monthly cost cap exceeded, see 429 docs"}}`, "provider_overloaded"}, + {"control: marker in data.message under a specific top-level message", `{"code":-32603,"message":"Prompt failed","data":{"errorKind":"rate_limit","message":"API Error: 429 Monthly cost cap exceeded."}}`, "provider_overloaded"}, + {"control: request id containing 429", `{"code":-32603,"message":"Internal error","data":{"codexErrorInfo":"other","message":"request req_14290 failed: monthly cost cap exceeded"}}`, ""}, + {"control: not an internal error", `{"code":-32602,"message":` + jsonString("API Error: 429 "+samAdminCapBody) + `}`, ""}, + {"control: auth failure stays auth", `{"code":-32603,"message":"Internal error","data":{"errorKind":"authentication_failed","message":` + jsonString("API Error: 429 "+samAdminCapBody) + `}}`, "model_provider_credential_rejected"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := ClassifyPromptError(wireRequestError(t, tc.wire)); got != tc.want { + t.Fatalf("reason = %q, want %q", got, tc.want) + } + }) + } +} + +func TestSAMUsageLimitTextPath(t *testing.T) { + for _, tc := range []struct{ name, message, want string }{ + {"API error text", "API Error: 429 " + samAdminCapBody, samUsageLimitReason}, + {"provider text", "Provider HTTP 429 Monthly cost cap exceeded. Adjust your cap in Settings > Usage.", samUsageLimitReason}, + {"round-trip of the code", samUsageLimitReason, samUsageLimitReason}, + {"adapter wire shape without errorKind", "Internal error: API Error: Request rejected (429) · Monthly cost cap exceeded. Adjust your cap in Settings > Usage.", samUsageLimitReason}, + {"control: provider 429", "API Error: 429 " + providerRateBody, "provider_overloaded"}, + {"control: provider 503", "API Error: HTTP 503 overloaded", "provider_overloaded"}, + {"control: marker in a URL", "Provider HTTP 429 rate limit url=https://evil.example/monthly cost cap exceeded", "provider_overloaded"}, + {"control: marker without a provider prefix", "tool said monthly cost cap exceeded 429", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := ClassifyPromptFailure(tc.message); got != tc.want { + t.Fatalf("reason = %q, want %q", got, tc.want) + } + }) + } +} + +// A Codex usageLimitExceeded normally means the provider plan limit and parks the task for +// its reset; SAM's own limit has no provider reset to wait for. +func TestSAMUsageLimitIsNotParkedAsAProviderPlanLimit(t *testing.T) { + future := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + if limit := ClassifyProviderLimit(errors.New("API Error: 429 Monthly cost cap exceeded. "+future), time.Now()); limit != nil { + t.Fatalf("SAM's limit text with a timestamp parked as a provider limit: %+v", limit) + } + if ClassifyProviderLimit(errors.New("API Error: 429 rate limited until "+future), time.Now()) == nil { + t.Fatal("control: a provider 429 with a reset time must still park") + } + sam := wireRequestError(t, `{"code":-32603,"message":"Internal error","data":{"codexErrorInfo":"usageLimitExceeded","message":`+jsonString("last status: 429, "+samAdminCapBody)+`}}`) + if limit := ClassifyProviderLimit(sam, time.Now()); limit != nil { + t.Fatalf("SAM's limit classified as provider limit: %+v", limit) + } + plan := wireRequestError(t, `{"code":-32603,"message":"Internal error","data":{"codexErrorInfo":"usageLimitExceeded","message":"You've hit your usage limit."}}`) + if ClassifyProviderLimit(plan, time.Now()) == nil { + t.Fatal("control: a provider plan limit must still classify as one") + } +} + +// Through the prompt path the VM agent runs: the reason broadcast to the chat and handed to +// the task callback is the SAM limit code, never the provider's message. +func TestSAMUsageLimitPromptPathReportsTheLimitCode(t *testing.T) { + host := newTestSessionHost(t) + defer host.Stop() + completed := make(chan error, 1) + host.config.OnPromptComplete = func(_ string, promptErr error) { completed <- promptErr } + host.finishPromptWithError(context.Background(), json.RawMessage(`"req-cap"`), + promptStartInfo{startedAt: time.Now(), viewerID: "viewer-1"}, + wireRequestError(t, `{"code":-32603,"message":`+jsonString("Internal error: API Error: 429 "+samAdminCapBody)+`,"data":{"errorKind":"rate_limit"}}`)) + select { + case promptErr := <-completed: + if got := ClassifyPromptError(promptErr); got != samUsageLimitReason { + t.Fatalf("prompt callback reason = %q, want %q", got, samUsageLimitReason) + } + case <-time.After(time.Second): + t.Fatal("prompt completion callback not called") + } + host.bufMu.RLock() + defer host.bufMu.RUnlock() + found := false + for _, buffered := range host.messageBuf { + found = found || strings.Contains(string(buffered.Data), samUsageLimitReason) + } + if !found { + t.Fatal("prompt did not broadcast the SAM usage limit reason") + } +} diff --git a/packages/vm-agent/internal/acp/session_host_prompt_retry.go b/packages/vm-agent/internal/acp/session_host_prompt_retry.go index 920957dfc1..3cb4b7619a 100644 --- a/packages/vm-agent/internal/acp/session_host_prompt_retry.go +++ b/packages/vm-agent/internal/acp/session_host_prompt_retry.go @@ -24,6 +24,11 @@ func (h *SessionHost) shouldRetryPromptError(promptCtx context.Context, err erro if h.promptProviderLimit(err, accepted...) != nil { return false } + // SAM's own AI usage limit is a 429 too, but no retry can succeed until the limit resets + // or an administrator changes it (sam_usage_limit.go). + if ClassifyPromptError(err) == samUsageLimitReason { + return false + } return isTransientProviderPromptError(err) } diff --git a/packages/vm-agent/internal/acp/session_host_prompt_retry_test.go b/packages/vm-agent/internal/acp/session_host_prompt_retry_test.go index 981fffdc1d..6bf98c49dc 100644 --- a/packages/vm-agent/internal/acp/session_host_prompt_retry_test.go +++ b/packages/vm-agent/internal/acp/session_host_prompt_retry_test.go @@ -198,6 +198,36 @@ func TestHandlePromptDoesNotRetryNonRetryableError(t *testing.T) { } } +// Idea 01M89JXTFHW4W3PQ65GTED6D0K: SAM's own AI usage limit is a 429, but retrying cannot help. +// A provider 429 control with the same shape still retries. +func TestHandlePromptDoesNotRetrySAMUsageLimit(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + message string + requests int + }{ + // Both carry rate_limit_error, which isTransientProviderPromptError treats as retryable. + {"SAM limit fails at once", "Internal error: API Error: 429 " + samAdminCapBody, 1}, + {"control: provider 429 retries", "Internal error: API Error: 429 " + providerRateBody, 3}, + } { + t.Run(tc.name, func(t *testing.T) { + host, server := newPromptRetryTestHost(t, promptRetryScript{ + responses: []promptRetryResponse{{errMessage: tc.message}, {errMessage: tc.message}, {errMessage: tc.message}}, + }) + done := make(chan error, 1) + host.config.OnPromptComplete = func(_ string, promptErr error) { done <- promptErr } + host.HandlePrompt(context.Background(), json.RawMessage(`9`), promptRetryParams(), "viewer-1", false) + if promptErr := <-done; promptErr == nil { + t.Fatal("prompt succeeded, want the 429 error") + } + if got := server.RequestCount(); got != tc.requests { + t.Fatalf("prompt request count = %d, want %d", got, tc.requests) + } + }) + } +} + type promptRetryResponse struct { beforeReply func(*promptRetryFakeAgent) errMessage string diff --git a/scripts/selfhost/backup.test.ts b/scripts/selfhost/backup.test.ts index 9176a71f4a..2d6629abbb 100644 --- a/scripts/selfhost/backup.test.ts +++ b/scripts/selfhost/backup.test.ts @@ -1250,6 +1250,9 @@ describe('runRollback', () => { let inspectFailure = partial === 'replacement'; const deleted: string[] = []; context.run = (command, args, env) => { + // The checkout's mode repair (operator-files.ts) reads an empty index under root. + if (command === 'git' && args[1] === '--show-toplevel') + return { status: 0, stdout: root, stderr: '' }; if (command === 'git' || command === 'pnpm') return { status: 0, stdout: '', stderr: '' }; const result = invoke(command, args, env); if (command !== 'docker') return result; diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts index 198c8a8869..9251e21cd7 100644 --- a/scripts/selfhost/deploy.ts +++ b/scripts/selfhost/deploy.ts @@ -106,6 +106,7 @@ import { smtpWorkerVars, writeMailCollectorFiles, } from './mail-settings.js'; +import { useOperatorUmask } from './operator-files.js'; import { assertSecretsKeepPlatformKeys, type PlatformKeysMode, @@ -124,10 +125,7 @@ const API_DIR = join(REPO_ROOT, 'apps/api'); /** Upper bound on captured celld output (bundle reports are a few KiB). */ const CHILD_OUTPUT_MAX_BYTES = 64 * 1024 * 1024; -interface RunResult { - status: number; - output: string; -} +type RunResult = { status: number; output: string }; /** Secret values scrubbed from any child output before it is printed. */ let knownSecrets: string[] = []; @@ -493,6 +491,7 @@ async function main(): Promise { } try { + useOperatorUmask(); // operator-files.ts: children never inherit a restrictive umask await main(); } catch (error: unknown) { console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); diff --git a/scripts/selfhost/legacy-adoption.ts b/scripts/selfhost/legacy-adoption.ts index ad3c25923b..e12aa98441 100644 --- a/scripts/selfhost/legacy-adoption.ts +++ b/scripts/selfhost/legacy-adoption.ts @@ -46,6 +46,7 @@ import { removeVolume, returnHelperName, } from './legacy-adoption-volumes'; +import { checkoutWithTrackedModes } from './operator-files'; import { assertOperatorExecution } from './operator-only'; import { readPrivateJson, replacePrivateFile } from './secret-files'; import { readPendingFrom, UPGRADE_PENDING_FILE, upgradeCompletedTo } from './upgrade-journal'; @@ -98,6 +99,11 @@ function git(ctx: BoxContext, args: string[], what: string): string { return check(ctx.run('git', args), what).stdout.trim(); } +/** `git checkout --detach`, making tracked files readable again (operator-files.ts). */ +function checkout(ctx: BoxContext, ref: string, what: string): void { + check(checkoutWithTrackedModes(ctx.run, ref, ctx.log), what); +} + function installationIdOf(stateDir: string): string { const keys = join(stateDir, 'platform-keys.json'); if (!existsSync(keys)) @@ -453,8 +459,7 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): ctx.log(`resuming legacy adoption at phase ${journal.phase}`); if (journal.rollingBack) { // Finish the interrupted rollback; never resume forward from a half-removed copy. - if (head !== journal.from) - git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + if (head !== journal.from) checkout(ctx, journal.from, 'check out --from'); await rollbackToLegacy(ctx, opts, journal); throw new Error( 'legacy adoption was rolled back after an interrupted rollback; rerun to retry' @@ -471,7 +476,7 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): if (!phaseAtLeast(journal, 'adopted')) { // The stack's bind mounts and compose files must be the deployed version while it moves. - if (head !== journal.from) git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + if (head !== journal.from) checkout(ctx, journal.from, 'check out --from'); try { await adopt(ctx, opts, journal); } catch (error) { @@ -486,7 +491,7 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): // restarted, the journal is kept so the next run restarts it before anything else. if (journal.backupStarted) restartLegacyCelld(ctx, journal); clearAdoptionJournal(ctx.stateDir); - git(ctx, ['checkout', '--detach', journal.to], 'restore target checkout'); + checkout(ctx, journal.to, 'restore target checkout'); } throw error; } @@ -501,7 +506,7 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): !existsSync(pendingPath) && git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD') !== journal.from ) - git(ctx, ['checkout', '--detach', journal.from], 'check out --from'); + checkout(ctx, journal.from, 'check out --from'); const finished = journal; try { await opts.upgrade(withProject(ctx, journal.canonicalProject), { @@ -524,7 +529,7 @@ export async function runLegacyAdoption(ctx: BoxContext, opts: AdoptionOptions): if (upgradeCompletedTo(ctx.stateDir, journal.to)) { // The deployed version is the target: the checkout follows it before the marker is cleared. if (git(ctx, ['rev-parse', 'HEAD'], 'git rev-parse HEAD') !== journal.to) - git(ctx, ['checkout', '--detach', journal.to], 'check out the upgraded target'); + checkout(ctx, journal.to, 'check out the upgraded target'); readPendingFrom(ctx.stateDir, journal.to); } clearAdoptionJournal(ctx.stateDir); diff --git a/scripts/selfhost/live/legacy-adoption-fixture.ts b/scripts/selfhost/live/legacy-adoption-fixture.ts index ae385f2ecb..b09ea63be9 100644 --- a/scripts/selfhost/live/legacy-adoption-fixture.ts +++ b/scripts/selfhost/live/legacy-adoption-fixture.ts @@ -7,6 +7,7 @@ import { spawnSync } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { parseDotenv } from '../secret-files.js'; @@ -162,6 +163,9 @@ export class FakeGit { const ref = (args[2] ?? '').replace(/\^\{commit\}$/, ''); return ref === TO || ref === FROM ? ok(`${ref}\n`) : { status: 128, stdout: '', stderr: '' }; } + // The mode repair after each checkout (operator-files.ts): an empty index changes nothing. + if (args[0] === 'rev-parse' && args[1] === '--show-toplevel') return ok(`${tmpdir()}\n`); + if (args[0] === 'ls-files') return ok(''); if (args[0] === 'checkout') { this.head = args[2] ?? this.head; this.checkouts.push(this.head); diff --git a/scripts/selfhost/operator-files.test.ts b/scripts/selfhost/operator-files.test.ts new file mode 100644 index 0000000000..afd67e7061 --- /dev/null +++ b/scripts/selfhost/operator-files.test.ts @@ -0,0 +1,333 @@ +/** + * operator-files.ts against a real git repository and real umasks (idea 01M89H1MQHJH432BFT2N43GHJJ). + * + * git runs in a child shell that sets `umask 077` first, the way the operator's shell did on + * 2026-11-25: every file a checkout writes then lands 0600. The key agent's build inputs are the + * files its real Dockerfile copies. + */ +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { join, resolve } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { prepareBackupParent } from './backup-destination.js'; +import { encryptBackupTree } from './backup-encryption.js'; +import { + checkoutWithTrackedModes, + OPERATOR_UMASK, + restoreTrackedModes, + useOperatorUmask, +} from './operator-files.js'; +import { ensurePrivateDir, replacePrivateFile, writePrivateFile } from './secret-files.js'; + +const KEY_AGENT_DIR = 'deploy/selfhost/key-agent'; + +/** The files the key agent image copies (its Dockerfile's COPY line), read from the real file. */ +function keyAgentInputs(): string[] { + const dockerfile = readFileSync(resolve(KEY_AGENT_DIR, 'Dockerfile'), 'utf8'); + const copy = dockerfile + .replace(/\\\n/g, ' ') + .split('\n') + .find((line) => line.startsWith('COPY ')); + const files = (copy ?? '').split(/\s+/).filter((f) => f.endsWith('.ts')); + return files.map((f) => `${KEY_AGENT_DIR}/${f}`); +} + +let root: string; +let repo: string; +let logs: string[]; + +/** git in `repo`, run by a shell that first sets the operator's restrictive umask. */ +function gitUnderUmask077(command: string, args: string[]) { + const result = spawnSync('sh', ['-c', 'umask 077; exec "$0" "$@"', command, ...args], { + cwd: repo, + encoding: 'utf8', + }); + return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr }; +} + +const git = (...args: string[]) => { + const result = gitUnderUmask077('git', args); + if (result.status !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`); + return result.stdout.trim(); +}; +const mode = (path: string) => statSync(join(repo, path)).mode & 0o777; + +let inputs: string[]; +let oldRef: string; +let newRef: string; + +beforeEach(() => { + mkdirSync(resolve('.tmp'), { recursive: true }); + root = mkdtempSync(join(resolve('.tmp'), 'operator-files-')); + repo = join(root, 'repo'); + mkdirSync(join(repo, KEY_AGENT_DIR), { recursive: true }); + logs = []; + inputs = keyAgentInputs(); + git('init', '-q'); + git('config', 'user.email', 'test@example.invalid'); + git('config', 'user.name', 'test'); + git('config', 'core.fileMode', 'true'); + for (const path of inputs) writeFileSync(join(repo, path), 'v1\n', { mode: 0o644 }); + writeFileSync(join(repo, 'run.sh'), '#!/bin/sh\n', { mode: 0o755 }); + git('add', '-A'); + git('commit', '-qm', 'old'); + oldRef = git('rev-parse', 'HEAD'); + for (const path of inputs) writeFileSync(join(repo, path), 'v2\n'); + writeFileSync(join(repo, 'run.sh'), '#!/bin/sh\necho v2\n'); + git('add', '-A'); + git('commit', '-qm', 'new'); + newRef = git('rev-parse', 'HEAD'); + git('checkout', '-q', '--detach', oldRef); +}); + +afterEach(() => { + rmSync(root, { recursive: true, force: true }); +}); + +describe('checkoutWithTrackedModes under umask 077', () => { + it('finds the key agent build inputs (a broken COPY parse cannot pass as "all readable")', () => { + expect(inputs.length).toBeGreaterThanOrEqual(10); + expect(inputs).toContain(`${KEY_AGENT_DIR}/bundle-store.ts`); + expect(inputs).toContain(`${KEY_AGENT_DIR}/server.ts`); + }); + + it('control: a plain checkout under umask 077 leaves the key agent inputs unreadable', () => { + git('checkout', '-q', '--detach', newRef); + for (const path of inputs) expect(mode(path)).toBe(0o600); + expect(mode('run.sh')).toBe(0o700); + }); + + it('upgrade checkout: the key agent inputs are world-readable at their git modes', () => { + expect(checkoutWithTrackedModes(gitUnderUmask077, newRef, (m) => logs.push(m)).status).toBe(0); + expect(git('rev-parse', 'HEAD')).toBe(newRef); + for (const path of inputs) expect(mode(path)).toBe(0o644); + expect(mode('run.sh')).toBe(0o755); + expect(logs).toEqual([`restored git file modes on ${inputs.length + 1} tracked paths`]); + }); + + it('rollback checkout: returning to the old ref repairs files a bad upgrade left 0600', () => { + git('checkout', '-q', '--detach', newRef); // the failed upgrade, without the repair + expect(checkoutWithTrackedModes(gitUnderUmask077, oldRef, (m) => logs.push(m)).status).toBe(0); + expect(git('rev-parse', 'HEAD')).toBe(oldRef); + for (const path of inputs) expect(mode(path)).toBe(0o644); + expect(mode('run.sh')).toBe(0o755); + }); + + it('makes a directory the target ref adds traversable (git records no directory modes)', () => { + git('checkout', '-q', '--detach', newRef); + mkdirSync(join(repo, KEY_AGENT_DIR, 'providers')); + writeFileSync(join(repo, KEY_AGENT_DIR, 'providers', 'extra.ts'), 'x\n'); + git('add', '-A'); + git('commit', '-qm', 'adds a directory'); + const withDir = git('rev-parse', 'HEAD'); + git('checkout', '-q', '--detach', oldRef); + expect(checkoutWithTrackedModes(gitUnderUmask077, withDir, (m) => logs.push(m)).status).toBe(0); + // Control: git under umask 077 created the directory 0700. + expect(statSync(join(repo, KEY_AGENT_DIR, 'providers')).mode & 0o777).toBe(0o755); + expect(mode(`${KEY_AGENT_DIR}/providers/extra.ts`)).toBe(0o644); + }); + + it('control: without the repair, the new directory is 0700', () => { + git('checkout', '-q', '--detach', newRef); + mkdirSync(join(repo, KEY_AGENT_DIR, 'providers')); + writeFileSync(join(repo, KEY_AGENT_DIR, 'providers', 'extra.ts'), 'x\n'); + git('add', '-A'); + git('commit', '-qm', 'adds a directory'); + const withDir = git('rev-parse', 'HEAD'); + git('checkout', '-q', '--detach', oldRef); + git('checkout', '-q', '--detach', withDir); + expect(statSync(join(repo, KEY_AGENT_DIR, 'providers')).mode & 0o777).toBe(0o700); + }); + + it('only adds bits: a tracked file a looser umask made 0664 is left as it is', () => { + git('checkout', '-q', '--detach', newRef); + const path = `${KEY_AGENT_DIR}/server.ts`; + chmodSync(join(repo, path), 0o664); + restoreTrackedModes(gitUnderUmask077); + expect(mode(path)).toBe(0o664); + }); + + it('keeps setgid on a shared checkout directory while making it traversable', () => { + chmodSync(join(repo, KEY_AGENT_DIR), 0o2700); + restoreTrackedModes(gitUnderUmask077); + expect(statSync(join(repo, KEY_AGENT_DIR)).mode & 0o7777).toBe(0o2755); + }); + + it('leaves untracked files alone (operator state and keys keep their own modes)', () => { + writeFileSync(join(repo, 'untracked-secret'), 'x', { mode: 0o600 }); + checkoutWithTrackedModes(gitUnderUmask077, newRef, (m) => logs.push(m)); + expect(mode('untracked-secret')).toBe(0o600); + }); + + it('returns a failed checkout without touching modes', () => { + const result = checkoutWithTrackedModes(gitUnderUmask077, 'f'.repeat(40), (m) => logs.push(m)); + expect(result.status).not.toBe(0); + expect(logs).toEqual([]); + }); + + it('never follows a symlinked directory out of the repository', () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'bundle-store.ts'), 'secret\n', { mode: 0o600 }); + rmSync(join(repo, KEY_AGENT_DIR), { recursive: true }); + symlinkSync(outside, join(repo, KEY_AGENT_DIR)); + const repair = restoreTrackedModes(gitUnderUmask077); + expect(statSync(join(outside, 'bundle-store.ts')).mode & 0o777).toBe(0o600); + expect(repair.failed).toContain(`${KEY_AGENT_DIR}/bundle-store.ts`); + }); + + it('refuses to report a clean repair when git cannot list the index', () => { + const broken = () => ({ status: 128, stdout: '', stderr: 'not a git repository' }); + expect(() => restoreTrackedModes(broken)).toThrow(/cannot list the git index/); + }); +}); + +describe('useOperatorUmask', () => { + let before: number; + beforeEach(() => { + before = process.umask(0o077); + }); + afterEach(() => { + process.umask(before); + }); + + it('only loosens: an operator umask looser than 022 is kept', () => { + process.umask(0o002); + expect(useOperatorUmask()).toBe(0o002); + expect(process.umask()).toBe(0o002); + }); + + it('children inherit 022 even when the operator shell had 077', () => { + expect(useOperatorUmask()).toBe(0o077); + expect(process.umask()).toBe(OPERATOR_UMASK); + const child = spawnSync('sh', ['-c', 'umask'], { encoding: 'utf8' }); + expect(child.stdout.trim()).toBe('0022'); + git('checkout', '-q', '--detach', newRef); + // git here still runs through a shell that sets 077 itself; a child that inherits does not. + const inherited = spawnSync('git', ['checkout', '-q', '--detach', oldRef], { cwd: repo }); + expect(inherited.status).toBe(0); + for (const path of inputs) expect(mode(path)).toBe(0o644); + }); +}); + +// Files that must stay private never rely on the umask: their writers set the mode, so the +// operator umask (and even umask 000) cannot widen them. +describe('private writers under the operator umask', () => { + let before: number; + afterEach(() => { + process.umask(before); + vi.unstubAllEnvs(); + }); + + it.each([ + ['operator umask 022', OPERATOR_UMASK], + ['umask 000', 0o000], + ])('state files, state dirs and encrypted backups stay private (%s)', (_name, umask) => { + for (const name of Object.keys(process.env)) { + if (name === 'CI' || name === 'GITHUB_ACTIONS' || name.startsWith('RUNNER_')) + vi.stubEnv(name, undefined); + } + before = process.umask(umask); + const state = join(root, 'state'); + ensurePrivateDir(state); + writePrivateFile(join(state, 'secrets.env'), 'A=1\n'); + replacePrivateFile(join(state, 'upgrade-pending.json'), '{}\n'); + const key = join(root, 'backup.key'); + writePrivateFile(key, ''); + writeFileSync(key, Buffer.alloc(32, 7)); + const plain = join(root, 'plain'); + mkdirSync(join(plain, 'state'), { recursive: true, mode: 0o700 }); + writeFileSync(join(plain, 'state', 'platform-keys.json'), '{}', { mode: 0o600 }); + // As runBackup does: missing parents are created private, then the encrypted tree. + prepareBackupParent(join(root, 'backups', 'snap')); + encryptBackupTree(plain, join(root, 'backups', 'snap'), key); + + const bits = (path: string) => statSync(path).mode & 0o777; + expect(bits(state)).toBe(0o700); + expect(bits(join(state, 'secrets.env'))).toBe(0o600); + expect(bits(join(state, 'upgrade-pending.json'))).toBe(0o600); + expect(bits(join(root, 'backups'))).toBe(0o700); + expect(bits(join(root, 'backups', 'snap'))).toBe(0o700); + expect(bits(join(root, 'backups', 'snap', 'state'))).toBe(0o700); + expect(bits(join(root, 'backups', 'snap', 'state', 'platform-keys.json'))).toBe(0o600); + }); +}); + +// The real entry points, started from a shell with umask 077 the way the 2026-11-25 operator ran +// them. A preload records the process umask when the command exits; each command is given +// arguments that make it stop early, after its entry checks and before it touches anything. +describe('operator entry points', () => { + const tsx = resolve('node_modules/.bin/tsx'); + const umaskAtExit = (args: string[]) => { + const record = join(root, 'umask-at-exit'); + const preload = join(root, 'record-umask.cjs'); + // tsx runs the script in a child process: record every process, then pick the script's. + writeFileSync( + preload, + `process.on('exit', () => require('node:fs').appendFileSync(${JSON.stringify(record)}, ` + + `JSON.stringify({ argv: process.argv.slice(1), umask: process.umask().toString(8) }) + '\\n'));\n` + ); + const env = Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => name !== 'CI' && name !== 'GITHUB_ACTIONS' && !name.startsWith('RUNNER_') + ) + ); + spawnSync('sh', ['-c', 'umask 077; exec "$0" "$@"', tsx, ...args], { + encoding: 'utf8', + env: { ...env, NODE_OPTIONS: `--require=${preload}` }, + }); + const lines = readFileSync(record, 'utf8').trim().split('\n'); + const runs = lines.map((l) => JSON.parse(l) as { argv: string[]; umask: string }); + const script = runs.find((r) => r.argv[0] === args[0]) ?? runs[0]; + return script?.umask; + }; + // An existing env file readable by others: tsx hands `--env-file` to node too (which loads it), + // and the command then refuses it as not private, right after its entry checks. + const publicEnv = () => { + const path = join(root, 'public.env'); + writeFileSync(path, '', { mode: 0o644 }); + return path; + }; + + it('control: the harness observes an inherited umask 077', () => { + const script = join(root, 'noop.ts'); + writeFileSync(script, 'export {};\n'); + expect(umaskAtExit([script])).toBe('77'); + }); + + it.each([ + ['upgrade.ts', () => []], + ['deploy.ts', () => ['--env-file', publicEnv(), '--dry-run']], + ['rebuild.ts', () => ['--env-file', publicEnv()]], + ['restore.ts', () => []], + ] as const)('%s runs its children with umask 022', (file, args) => { + expect(umaskAtExit([resolve('scripts/selfhost', file), ...args()])).toBe('22'); + }); + + // Rule 61's enumeration: no operator code checks out a ref except through the helper that + // re-applies git's modes. + it('every checkout in the operator scripts goes through checkoutWithTrackedModes', () => { + const sources = readdirSync(resolve('scripts/selfhost')).filter( + (f) => f.endsWith('.ts') && !f.endsWith('.test.ts') + ); + expect(sources.length).toBeGreaterThan(50); + const offenders = sources.filter( + (f) => + f !== 'operator-files.ts' && + /['"]checkout['"]/.test(readFileSync(resolve('scripts/selfhost', f), 'utf8')) + ); + expect(offenders).toEqual([]); + }); +}); diff --git a/scripts/selfhost/operator-files.ts b/scripts/selfhost/operator-files.ts new file mode 100644 index 0000000000..20357be7fd --- /dev/null +++ b/scripts/selfhost/operator-files.ts @@ -0,0 +1,134 @@ +/** + * Operator commands must not depend on the shell's umask (idea 01M89H1MQHJH432BFT2N43GHJJ). + * + * On 2026-11-25 an upgrade run under `umask 077` checked out 111 tracked files as 0600. The key + * agent image copies `deploy/selfhost/key-agent/*.ts` and runs as the non-root + * `SAM_KEY_AGENT_UID`, so it crash-looped with EACCES, and the automatic rollback checked the old + * ref out under the same umask and failed the same way. + * + * Two guards, each sufficient for tracked files on its own: + * - `useOperatorUmask()` at every operator entry point, so git, pnpm and docker children create + * files group/world-readable, as on a stock install. + * - `checkoutWithTrackedModes()` makes tracked files world-readable (and 100755 files + * world-executable) after every checkout, so a file already rewritten 0600 (or a caller that + * bypassed the entry point) is repaired too. + * + * Files that must stay private do not rely on the umask: their writers set 0600/0700 explicitly + * (secret-files.ts, backup-encryption.ts, backup-destination.ts), which a umask can only narrow. + */ +import { chmodSync, lstatSync, realpathSync } from 'node:fs'; +import { dirname, isAbsolute, join, sep } from 'node:path'; + +/** + * The most restrictive umask operator commands run with (owner-writable, readable by everyone). + * The operator's umask is only loosened down to this, never past it: 077 becomes 022, and a + * looser 002 stays 002. + */ +export const OPERATOR_UMASK = 0o022; + +/** + * Clears from the process umask every bit that would hide new files from group or others, so + * every child command creates readable files. Returns the previous umask. + */ +export function useOperatorUmask(): number { + const previous = process.umask(); + process.umask(previous & OPERATOR_UMASK); + return previous; +} + +interface RunResult { + status: number; + stdout: string; + stderr: string; +} +type Runner = (command: string, args: string[], env?: NodeJS.ProcessEnv) => RunResult; + +/** + * The bits everyone needs on a tracked file of this git index mode: read, plus execute for + * 100755. Null for symlinks and submodules (no mode). + */ +function requiredBitsFor(gitMode: string): number | null { + if (gitMode === '100644') return 0o444; + if (gitMode === '100755') return 0o555; + return null; +} + +export interface ModeRepair { + changed: number; + /** Tracked paths whose mode could not be set (not owned by this user); never their contents. */ + failed: string[]; +} + +/** + * Makes every tracked regular file readable by everyone (and executable by everyone when git + * records 100755), and every directory holding a tracked file traversable by everyone. Bits are + * only added, never removed: a file a looser umask made 0664 is left alone, one a umask 077 + * checkout made 0600 becomes 0644. Git records no directory modes, and a checkout under umask + * 077 creates new directories 0700, which the non-root key agent cannot enter. Throws when git + * cannot list the index, so a broken repair is never mistaken for a clean tree. A path it cannot + * chmod is reported, not fatal: a rollback must not stop at a file the checkout could write. + */ +export function restoreTrackedModes(run: Runner): ModeRepair { + const top = run('git', ['rev-parse', '--show-toplevel']); + const listed = run('git', ['ls-files', '--stage', '-z', '--full-name']); + const root = top.stdout.trim(); + if (top.status !== 0 || listed.status !== 0 || !isAbsolute(root)) + throw new Error('restore tracked file modes failed: cannot list the git index'); + const repair: ModeRepair = { changed: 0, failed: [] }; + const realRoot = realpathSync(root); + /** True when `path` resolves inside the repository (no symlinked parent leads out of it). */ + const inside = (path: string) => { + const real = realpathSync(dirname(path)); + return real === realRoot || real.startsWith(realRoot + sep); + }; + // Any error (EACCES, ENOTDIR, a path leaving the repo) is reported, never thrown: the + // rollback that calls this must not stop at one path. + const fix = (relative: string, kind: 'file' | 'dir', want: (mode: number) => number) => { + const path = join(root, relative); + try { + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (!stat || !(kind === 'file' ? stat.isFile() : stat.isDirectory())) return; + // 0o7777 keeps setuid/setgid/sticky: a shared checkout's setgid directories must keep + // passing their group to later checkouts. + const mode = stat.mode & 0o7777; + if (want(mode) === mode) return; + if (!inside(path)) throw new Error('outside the repository'); + chmodSync(path, want(mode)); + repair.changed++; + } catch { + repair.failed.push(relative); + } + }; + const directories = new Set(); + for (const entry of listed.stdout.split('\0')) { + // ` \t` + const tab = entry.indexOf('\t'); + if (tab < 0) continue; + const required = requiredBitsFor(entry.slice(0, entry.indexOf(' '))); + if (required === null) continue; + const relative = entry.slice(tab + 1); + fix(relative, 'file', (mode) => mode | required); + for (let dir = dirname(relative); dir !== '.'; dir = dirname(dir)) directories.add(dir); + } + // Only add group/other read+search; never narrow a directory an operator widened. + for (const dir of directories) fix(dir, 'dir', (mode) => mode | 0o055); + return repair; +} + +/** `git checkout --detach `, then `restoreTrackedModes`. Returns the checkout's result. */ +export function checkoutWithTrackedModes( + run: Runner, + ref: string, + log: (message: string) => void +): RunResult { + const checkout = run('git', ['checkout', '--detach', ref]); + if (checkout.status !== 0) return checkout; + const { changed, failed } = restoreTrackedModes(run); + if (changed > 0) log(`restored git file modes on ${changed} tracked paths`); + if (failed.length > 0) + log( + `could not restore the git mode of ${failed.length} tracked paths (first: ${failed[0]}); ` + + 'run the command as the checkout owner' + ); + return checkout; +} diff --git a/scripts/selfhost/rebuild.ts b/scripts/selfhost/rebuild.ts index 937d1965c5..5a7a9cc844 100644 --- a/scripts/selfhost/rebuild.ts +++ b/scripts/selfhost/rebuild.ts @@ -13,6 +13,7 @@ import { parseArgs } from 'node:util'; import { log, SELFHOST_DIR } from './backup-cli'; import { loadBoxEnv } from './box-settings'; import { detectKeyCandidates } from './key-platforms'; +import { useOperatorUmask } from './operator-files'; import { assertOperatorExecution } from './operator-only'; import { fleetBucket } from './replaceable-box'; import { runRebuild } from './replaceable-rebuild'; @@ -28,6 +29,8 @@ const { values } = parseArgs({ }, }); assertOperatorExecution(); +// Operator commands never inherit a restrictive umask (operator-files.ts). +useOperatorUmask(); const envFile = resolve(values['env-file'] ?? join(SELFHOST_DIR, '.env')); // It holds the bucket credential (or names the box's identity's bucket): it must stay private. assertPrivateFile(envFile); diff --git a/scripts/selfhost/restore.ts b/scripts/selfhost/restore.ts index dc4ef2730b..de2d769d93 100644 --- a/scripts/selfhost/restore.ts +++ b/scripts/selfhost/restore.ts @@ -13,6 +13,7 @@ import { LOCAL_BUNDLE_SUBDIR } from '../../deploy/selfhost/key-agent/bundle-stor import { loadBox, log, SELFHOST_DIR } from './backup-cli'; import { composeArgs, runRestore } from './backup-lib'; import { expectedComposeProjectFor } from './install-record'; +import { useOperatorUmask } from './operator-files'; const { values } = parseArgs({ options: { @@ -23,6 +24,8 @@ const { values } = parseArgs({ 'state-dir': { type: 'string' }, }, }); +// Operator commands never inherit a restrictive umask (operator-files.ts). +useOperatorUmask(); if (!values.from) throw new Error('--from is required'); const from = resolve(values.from); const envFile = resolve(values['box-env'] ?? join(SELFHOST_DIR, '.env')); diff --git a/scripts/selfhost/upgrade-lib.ts b/scripts/selfhost/upgrade-lib.ts index ea42e8d010..1f12c2e91f 100644 --- a/scripts/selfhost/upgrade-lib.ts +++ b/scripts/selfhost/upgrade-lib.ts @@ -23,6 +23,7 @@ import { loadBoxEnv } from './box-settings.js'; import { composeFilesFor } from './compose-env.js'; import { log, REPO_ROOT, SELFHOST_DIR } from './deploy-steps.js'; import { COMPOSE_PATH, imageRebuilds } from './image-rebuilds.js'; +import { checkoutWithTrackedModes } from './operator-files.js'; import { assertOperatorExecution } from './operator-only.js'; import { recoverRollbackState } from './rollback-state.js'; import { assertPrivateFile, replacePrivateFile } from './secret-files.js'; @@ -191,7 +192,7 @@ export async function recoverUpgrade( join(ctx.stateDir, UPGRADE_PENDING_FILE), `${JSON.stringify({ from, backupDir, ...(to ? { to } : {}) })}\n` ); - check(ctx.run('git', ['checkout', '--detach', from]), 'restore previous checkout'); + check(checkoutWithTrackedModes(ctx.run, from, ctx.log), 'restore previous checkout'); check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); const stateDir = composeStateDirOverride(ctx); const env = stateDir === null ? undefined : { ...process.env, SAM_SELFHOST_STATE_DIR: stateDir }; @@ -273,7 +274,6 @@ interface UpgradeProgress { async function applyUpgrade( ctx: BoxContext, opts: UpgradeOptions, - git: Git, plan: UpgradePlan, progress: UpgradeProgress ): Promise { @@ -286,7 +286,7 @@ async function applyUpgrade( ctx.run('docker', composeArgs(ctx, args), composeEnv), `docker compose ${args.join(' ')}` ); - git(['checkout', '--detach', plan.to]); + check(checkoutWithTrackedModes(ctx.run, plan.to, ctx.log), `check out ${plan.to}`); pnpm(['install', '--frozen-lockfile']); assertMigrationProgression(plan.installed, sourceMigrations(backupContext(ctx))); ctx.log('DO migration preflight passed against the active deployment and target checkout'); @@ -358,7 +358,6 @@ function stopCelldAfterFailure(ctx: BoxContext): void { async function rollbackFailedUpgrade( ctx: BoxContext, opts: UpgradeOptions, - git: Git, from: string, backupDir: string, progress: UpgradeProgress @@ -368,7 +367,7 @@ async function rollbackFailedUpgrade( if (progress.deploymentStarted) { await recoverUpgrade(ctx, from, backupDir, progress.imagesRebuilt, opts); } else { - git(['checkout', '--detach', from]); + check(checkoutWithTrackedModes(ctx.run, from, ctx.log), 'restore previous checkout'); check(ctx.run('pnpm', ['install', '--frozen-lockfile']), 'restore previous dependencies'); clearUpgradeJournal(ctx.stateDir); } @@ -478,12 +477,11 @@ export async function runUpgrade(ctx: BoxContext, opts: UpgradeOptions): Promise composeRestarted = await applyUpgrade( ctx, opts, - git, { to, composeFilesChanged, rebuilds, boxArgs, installed }, progress ); } catch (error) { - await rollbackFailedUpgrade(ctx, opts, git, from, backupDir, progress); + await rollbackFailedUpgrade(ctx, opts, from, backupDir, progress); throw error; } diff --git a/scripts/selfhost/upgrade-rollback-cli.test.ts b/scripts/selfhost/upgrade-rollback-cli.test.ts index c90be0902f..f13b75089a 100644 --- a/scripts/selfhost/upgrade-rollback-cli.test.ts +++ b/scripts/selfhost/upgrade-rollback-cli.test.ts @@ -165,7 +165,7 @@ cp.spawnSync = (command, args, options) => { if (!['git', 'pnpm', 'docker', 'gcloud'].includes(command)) return original(command,args,options); fs.appendFileSync(${JSON.stringify(join(root, 'calls'))}, command+' '+args.join(' ')+'\\n'); let stdout = ''; - if(command === 'git' && args[0] === 'rev-parse') stdout = 'b'.repeat(40); + if(command === 'git' && args[0] === 'rev-parse') stdout = args[1] === '--show-toplevel' ? ${JSON.stringify(root)} : 'b'.repeat(40); if (command === 'docker') { if(args[0]==='container' && args[1]==='rm') container=''; if(args[0]==='volume' && args[1]==='rm') volume=false; diff --git a/scripts/selfhost/upgrade-rollback.test.ts b/scripts/selfhost/upgrade-rollback.test.ts index b7c9e4f213..1bbca2578a 100644 --- a/scripts/selfhost/upgrade-rollback.test.ts +++ b/scripts/selfhost/upgrade-rollback.test.ts @@ -1,5 +1,14 @@ /** The manual command enters the same populated-install recovery path as automatic rollback. */ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -58,6 +67,9 @@ beforeEach(() => { encryptionKeyFile: join(root, 'backup key'), log: vi.fn(), run: (command, args, env) => { + // The mode repair after each checkout (operator-files.ts): an empty index changes nothing. + if (args[1] === '--show-toplevel') return { status: 0, stdout: root, stderr: '' }; + if (args[0] === 'ls-files') return { status: 0, stdout: '', stderr: '' }; if (args[0] === 'status') return { status: 0, stdout: dirty ? ' M tracked' : '', stderr: '' }; if (args[0] === 'rev-parse') return { status: 0, stdout: OPERATOR_REF, stderr: '' }; steps.push(`${command} ${args.join(' ')}`); @@ -140,6 +152,50 @@ describe('manual owned rollback', () => { } ); + // Idea 01M89H1MQHJH432BFT2N43GHJJ: the manual rollback's checkout runs real git in a shell + // with umask 077 (as the operator's did). The previous ref's key agent sources must come back + // world-readable, including a directory the bad upgrade had left 0700. + it('restores git file modes when the previous ref is checked out under umask 077', async () => { + const repo = join(root, 'repo'); + const keyAgent = join(repo, 'deploy/selfhost/key-agent'); + mkdirSync(keyAgent, { recursive: true }); + const git = (...args: string[]) => { + const r = spawnSync('sh', ['-c', 'umask 077; exec git "$@"', 'git', ...args], { + cwd: repo, + encoding: 'utf8', + }); + return { status: r.status ?? 1, stdout: r.stdout, stderr: r.stderr }; + }; + git('init', '-q'); + git('config', 'user.email', 'test@example.invalid'); + git('config', 'user.name', 'test'); + writeFileSync(join(keyAgent, 'server.ts'), 'old\n', { mode: 0o644 }); + git('add', '-A'); + git('commit', '-qm', 'previous'); + const previous = git('rev-parse', 'HEAD').stdout.trim(); + writeFileSync(join(keyAgent, 'server.ts'), 'new\n'); + git('add', '-A'); + git('commit', '-qm', 'failed upgrade'); + // The failed upgrade's checkout under umask 077: the file rewritten 0600, the directory 0700. + git('checkout', '-q', '--detach', 'HEAD~1'); + git('checkout', '-q', '--detach', 'HEAD@{1}'); + rmSync(keyAgent, { recursive: true }); + git('checkout', '-q', '--', '.'); + expect(statSync(keyAgent).mode & 0o777).toBe(0o700); + expect(statSync(join(keyAgent, 'server.ts')).mode & 0o777).toBe(0o600); + const runner = ctx.run; + ctx.run = (command, args, env) => { + if (command !== 'git') return runner(command, args, env); + if (args[0] === 'checkout') return git('checkout', '-q', '--detach', previous); + if (args[0] === 'ls-files' || args[1] === '--show-toplevel') return git(...args); + return runner(command, args, env); + }; + await rollback(); + expect(git('rev-parse', 'HEAD').stdout.trim()).toBe(previous); + expect(statSync(keyAgent).mode & 0o777).toBe(0o755); + expect(statSync(join(keyAgent, 'server.ts')).mode & 0o777).toBe(0o644); + }); + it('retries after dependency failure with the removed cache receipt still retained', async () => { const receipt = join(ctx.stateDir, 'rollback-cache-pending.json'); let removed = false; diff --git a/scripts/selfhost/upgrade-rollback.ts b/scripts/selfhost/upgrade-rollback.ts index dde5485f60..2cc5fca8a9 100644 --- a/scripts/selfhost/upgrade-rollback.ts +++ b/scripts/selfhost/upgrade-rollback.ts @@ -3,6 +3,7 @@ import { rmSync } from 'node:fs'; import { join } from 'node:path'; import { composeArgs, composeRunEnv } from './backup-lib.js'; +import { checkoutWithTrackedModes } from './operator-files.js'; import { assertOperatorExecution } from './operator-only.js'; import { recoverRollbackState } from './rollback-state.js'; import { type BoxContext, recoverUpgrade, UPGRADE_PENDING_FILE } from './upgrade-lib.js'; @@ -49,7 +50,7 @@ export async function runManualRollback( /* best effort */ } try { - const checkout = ctx.run('git', ['checkout', '--detach', operatorRef]); + const checkout = checkoutWithTrackedModes(ctx.run, operatorRef, ctx.log); if (checkout.status === 0) ctx.run('pnpm', ['install', '--frozen-lockfile']); } catch { /* best effort; keep the application stopped */ diff --git a/scripts/selfhost/upgrade-safeguards.test.ts b/scripts/selfhost/upgrade-safeguards.test.ts index 8ee3ee0e4b..215f74d71b 100644 --- a/scripts/selfhost/upgrade-safeguards.test.ts +++ b/scripts/selfhost/upgrade-safeguards.test.ts @@ -41,6 +41,10 @@ let invalidCacheMount: boolean; let failureStopStateDirs: (string | undefined)[]; function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { + // The mode repair after each checkout (operator-files.ts): an empty index changes nothing. + if (command === 'git' && args[1] === '--show-toplevel') + return { status: 0, stdout: root, stderr: '' }; + if (command === 'git' && args[0] === 'ls-files') return { status: 0, stdout: '', stderr: '' }; if (command === 'docker' && args.slice(-2).join(' ') === 'stop celld') failureStopStateDirs.push(env?.SAM_SELFHOST_STATE_DIR); const ok = (stdout = '') => ({ status: 0, stdout, stderr: '' }); diff --git a/scripts/selfhost/upgrade.test.ts b/scripts/selfhost/upgrade.test.ts index 9226175dff..c447c8e2b7 100644 --- a/scripts/selfhost/upgrade.test.ts +++ b/scripts/selfhost/upgrade.test.ts @@ -7,7 +7,16 @@ * the printed rollback selects the same box and matches whether the upgrade carried a D1 migration. */ import * as fs from 'node:fs'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -88,6 +97,15 @@ const FILES_AT_TO: Record = { /** SAM_SELFHOST_STATE_DIR in each docker command's environment (undefined: not set). */ let dockerStateEnv: (string | undefined)[]; +/** Tracked files of the fake checkout (under /repo) and their git index modes. */ +let trackedModes: Record; +/** `pnpm install` fails while the target ref is checked out (before any deploy). */ +let failTargetInstall: boolean; + +/** A checkout under the operator's `umask 077`: git rewrites every checked-out file as 0600. */ +function checkoutUnderUmask077(): void { + for (const path of Object.keys(trackedModes)) chmodSync(join(root, 'repo', path), 0o600); +} function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResult { if (command === 'docker') dockerStateEnv.push(env?.SAM_SELFHOST_STATE_DIR); @@ -96,7 +114,17 @@ function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResul if (command === 'git') { if (args[0] === 'status') return ok(dirty ? ' M apps/api/src/index.ts' : ''); if (args[0] === 'rev-parse' && args[1] === 'HEAD') return ok(head); - if (args[0] === 'checkout') head = args[2] ?? head; + if (args[0] === 'checkout') { + head = args[2] ?? head; + checkoutUnderUmask077(); + } + if (args[0] === 'rev-parse' && args[1] === '--show-toplevel') return ok(join(root, 'repo')); + if (args[0] === 'ls-files') + return ok( + Object.entries(trackedModes) + .map(([path, mode]) => `${mode} ${'c'.repeat(40)} 0\t${path}\0`) + .join('') + ); if (args[0] === 'rev-parse') return ok(TO); if (args[0] === 'diff') return ok(diff.join('\n')); if (args[0] === 'show') { @@ -124,6 +152,9 @@ function run(command: string, args: string[], env?: NodeJS.ProcessEnv): RunResul } if (command === 'docker' && args.includes('config')) return ok((head === FROM ? (previousServices ?? activeServices) : activeServices).join('\n')); + if (command === 'pnpm' && args[0] === 'install' && failTargetInstall && head === TO) { + return { status: 1, stdout: '', stderr: 'EACCES' }; + } if (deploy && !args.includes('--init') && failDeploy) { return { status: 1, stdout: '', stderr: 'migration 0219 failed' }; } @@ -173,6 +204,17 @@ beforeEach(() => { composeAt = { [FROM]: COMPOSE(), [TO]: COMPOSE() }; trackedAt = {}; dockerStateEnv = []; + failTargetInstall = false; + // The key agent image copies these; it runs as a non-root uid (deploy/selfhost/key-agent). + trackedModes = { + 'deploy/selfhost/key-agent/bundle-store.ts': '100644', + 'deploy/selfhost/key-agent/server.ts': '100644', + 'scripts/selfhost/hosted-git-smoke.sh': '100755', + }; + for (const path of Object.keys(trackedModes)) { + mkdirSync(join(root, 'repo', path, '..'), { recursive: true }); + writeFileSync(join(root, 'repo', path), 'tracked\n', { mode: 0o600 }); + } activeServices = ['celld', 'caddy']; previousServices = undefined; }); @@ -584,6 +626,51 @@ describe('runUpgrade', () => { // without what the override added. // S4: the box's ports are checked against the lease range when the upgrade loads the box, before it // fetches, checks out or runs docker compose (not only inside Caddy's start.sh once it is up). +// Idea 01M89H1MQHJH432BFT2N43GHJJ: under `umask 077` every checkout rewrote tracked files 0600, +// the non-root key agent failed with EACCES, and the automatic rollback failed the same way. +describe('runUpgrade under a restrictive operator umask', () => { + const modes = () => + Object.fromEntries( + Object.keys(trackedModes).map((path) => [ + path, + (statSync(join(root, 'repo', path)).mode & 0o777).toString(8), + ]) + ); + const GIT_MODES = { + 'deploy/selfhost/key-agent/bundle-store.ts': '644', + 'deploy/selfhost/key-agent/server.ts': '644', + 'scripts/selfhost/hosted-git-smoke.sh': '755', + }; + + it('leaves the target checkout at git modes, so the key agent can read its sources', async () => { + await upgrade(); + expect(head).toBe(TO); + expect(modes()).toEqual(GIT_MODES); + expect(logs).toContain('restored git file modes on 3 tracked paths'); + }); + + it('restores git modes when a failed deploy rolls back to the previous ref', async () => { + failDeploy = true; + await expect(upgrade()).rejects.toThrow(/command output withheld/); + expect(logs.join('\n')).toContain('automatic rollback completed'); + expect(head).toBe(FROM); + expect(modes()).toEqual(GIT_MODES); + }); + + it('restores git modes when the rollback runs before any deploy (failed install)', async () => { + failTargetInstall = true; + await expect(upgrade()).rejects.toThrow(/pnpm install --frozen-lockfile failed/); + expect(logs.join('\n')).toContain('automatic rollback completed'); + expect(head).toBe(FROM); + expect(modes()).toEqual(GIT_MODES); + }); + + it('control: the fake checkout does leave files 0600 until the repair runs', () => { + checkoutUnderUmask077(); + expect(new Set(Object.values(modes()))).toEqual(new Set(['600'])); + }); +}); + describe('loadBox refuses a box port inside the lease range', () => { const envWith = (line: string) => { const envFile = join(root, 'ports.env'); diff --git a/scripts/selfhost/upgrade.ts b/scripts/selfhost/upgrade.ts index 10c3d53096..60cf247aa6 100644 --- a/scripts/selfhost/upgrade.ts +++ b/scripts/selfhost/upgrade.ts @@ -14,11 +14,14 @@ import { parseArgs } from 'node:util'; import { celldPort, SELFHOST_DIR, waitForHealth } from './deploy-steps.js'; import { runLegacyAdoption } from './legacy-adoption.js'; +import { useOperatorUmask } from './operator-files.js'; import { assertOperatorExecution } from './operator-only.js'; import { loadBox, runUpgrade } from './upgrade-lib.js'; import { runManualRollback } from './upgrade-rollback.js'; assertOperatorExecution(); +// Operator commands never inherit a restrictive umask (operator-files.ts). +useOperatorUmask(); const { values } = parseArgs({ options: { diff --git a/tasks/archive/2026-11-25-selfhost-umask-and-spending-limit-label.md b/tasks/archive/2026-11-25-selfhost-umask-and-spending-limit-label.md new file mode 100644 index 0000000000..f4b45d62f4 --- /dev/null +++ b/tasks/archive/2026-11-25-selfhost-umask-and-spending-limit-label.md @@ -0,0 +1,62 @@ +# Self-host hardening: umask-independent upgrade, spending-limit failure label + +## Problem +1. (idea 01M89H1MQHJH432BFT2N43GHJJ) `pnpm selfhost:upgrade` under `umask 077` rewrote 111 tracked + files as 0600 on `git checkout --detach`; the non-root key agent got EACCES, and the automatic + rollback failed the same way. Self-hosting only. +2. (idea 01M89JXTFHW4W3PQ65GTED6D0K) A SAM AI proxy spending-limit 429 is reported by the VM agent as + `provider_overloaded`, so the chat failure card says "Provider overloaded · Recoverable". Settings > + Usage says "AI Gateway traffic only" on gateway-less installs, and its selected period button is + invisible (`bg-accent-emphasis` is not a defined token). Shared with hosted SAM. + +## Research +- Checkouts: `upgrade-lib.ts` (`applyUpgrade`, `recoverUpgrade`, `rollbackFailedUpgrade`) and + `upgrade-rollback.ts` (operator ref restore). Real runner `runCommand` spawns with cwd REPO_ROOT. +- Entry scripts: upgrade.ts, deploy.ts, rebuild.ts, restore.ts (rollback is `upgrade.ts --rollback-from`). +- Private writers already pass explicit modes: `secret-files.ts` (fchmod 0600, dir 0700), + `backup-encryption.ts` (0600/0700), `backup-destination.ts` (0700), upgrade-lib stateDir (0700). +- Key agent image copies `deploy/selfhost/key-agent/*.ts` and runs as `SAM_KEY_AGENT_UID`. +- VM agent: `acp.ClassifyPromptError` maps claude `errorKind: rate_limit` and `api error: 429` text to + `provider_overloaded`; task callback sends the bare code (`taskCallbackErrorMessage`). UI classifies + via `packages/shared/src/failure-classification.ts`. +- Proxy messages: `monthlyCostCapMessage` (packages/ai-proxy), daily token budget in + `apps/api/src/routes/ai-proxy-admission.ts`. + +## Checklist +- [x] `operator-files.ts`: `useOperatorUmask()` (0o022) + `checkoutWithTrackedModes()` re-applying git modes +- [x] Call umask at entry of upgrade/deploy/rebuild/restore; use the checkout helper at every checkout +- [x] Tests: real git checkout under umask 077 (upgrade + rollback paths) leaves key-agent inputs world-readable; private writers stay 0600/0700 under umask 000/022; guard deletion goes red +- [x] README note updated +- [x] VM agent: `sam_ai_usage_limit_reached` reason when the rate-limit error carries SAM's proxy limit text; real overload unchanged (tests) +- [x] Shared classifier: structural rule "SAM AI usage limit reached", not retryable; provider-overload unchanged (tests) +- [x] Usage page: subtitle/empty-state wording; selected button + bars use defined `bg-accent` +- [x] Playwright audit 375/1280 +- [x] Live: self-host live suite + upgrade/rollback live tests on celld; box end-to-end of the banner + +## Acceptance +- Upgrade and rollback under umask 077 leave tracked files at git modes; key agent starts. +- `.state/*`, backups, keys remain 0600/0700. +- Spending-limit refusal shows the spending-limit label; real provider overloads still show "Provider overloaded". + +## Review notes +- Local reviewers: task-completion-validator, go-specialist, security-auditor, ui-ux-specialist. No CRITICAL/HIGH. + Addressed: directory modes repaired too; chmod never follows a symlinked parent out of the repo and + never throws; entry points proven by spawning them under umask 077; real-git manual rollback test; + legacy adoption uses an explicit checkout helper plus an enumeration test; Go detector requires + typed 429 evidence (rate_limit kind, Codex turn error, or `API Error: 429` prefix) and a standalone 429. +- Guard deletion: mode repair off -> 7 mode tests red; restore.ts umask call removed -> its entry test red; + Go ClassifyPromptError check off -> 6 cases red; ClassifyProviderLimit guard off -> parking test red; + FailureCard gate off -> usage-limit card test red. +- Found while testing (pre-existing, not changed): `tsx script.ts --env-file X` also hands `--env-file` to + node, which loads X into process.env (and fails if X is missing). + +## Live results +- Local self-host Docker live suite: 19/19 files, 289 tests. +- Box, item 1: + - a real upgrade and a `--rollback-from` rollback, both under `umask 077`, repaired 13 and 14 paths, and the box stayed healthy; + - found and fixed that the repair narrowed 0664 files, so it now only adds bits. +- Box, item 2: a real Claude Code chat in `sam` mode on a GCP node, refused by the administrator's monthly ceiling through the #3009 fake upstream: + - the task's `errorMessage` is `sam_ai_usage_limit_reached`; + - the chat card reads "AI usage limit reached", with no Recoverable badge. +- Staging (hosted) regression: two chats on fresh nodes running the branch's VM agent completed normally, and the Usage page wording is correct. +- Flaky test found, unrelated: `tasks/backlog/2026-11-25-flaky-selfhost-runtime-secrets-rotation-fallback.md`. diff --git a/tasks/backlog/2026-11-25-flaky-selfhost-runtime-secrets-rotation-fallback.md b/tasks/backlog/2026-11-25-flaky-selfhost-runtime-secrets-rotation-fallback.md new file mode 100644 index 0000000000..3c02bc2b99 --- /dev/null +++ b/tasks/backlog/2026-11-25-flaky-selfhost-runtime-secrets-rotation-fallback.md @@ -0,0 +1,17 @@ +# Flaky: selfhost-runtime-secrets "refreshes the rotation read fallback with the new bundle" + +## Problem +`apps/api/tests/unit/selfhost-runtime-secrets.test.ts` > wrapDurableObject > a resident object > +"refreshes the rotation read fallback with the new bundle (Codex P1)" failed once in CI +(run 45691341052, job 139477627441, PR #3012): `expected 'k1' to be 'k2'` at line 560, after two +`settle()` calls. It passed 3/3 locally on the same head, and PR #3012 does not touch this code. + +## Context +Found while waiting on CI for PR #3012 (self-host umask + usage-limit label). The test waits a fixed +number of `settle()` ticks for an asynchronous bundle refresh, so a slower CI runner can observe +the old key. + +## Acceptance Criteria +- [ ] The test waits on the refresh itself (a promise or a deferred the refresh resolves), not a fixed number of ticks +- [ ] 50 consecutive local runs pass +- [ ] The discrimination check still turns the test red when the refresh is removed