diff options
6 files changed, 315 insertions, 13 deletions
diff --git a/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs b/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs index 2188c03..a5a19db 100644 --- a/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs +++ b/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs @@ -56,3 +56,152 @@ exit 66 await rm(scratch, { recursive: true, force: true }); } }); + +test('collect-signals: uses Vercel account billing.plan before empty-contract heuristics', async () => { + const scratch = await mkdtemp(join(tmpdir(), 'vo-plan-preflight-')); + const bin = join(scratch, 'bin'); + try { + await mkdir(bin, { recursive: true }); + await mkdir(join(scratch, '.vercel'), { recursive: true }); + await writeFile(join(scratch, 'package.json'), JSON.stringify({ + dependencies: { next: '^15.3.0' }, + }), 'utf-8'); + await writeFile(join(scratch, '.vercel', 'project.json'), JSON.stringify({ + projectId: 'prj_test', + orgId: 'team_hobby', + }), 'utf-8'); + const fakeVercel = join(bin, 'vercel'); + await writeFile(fakeVercel, `#!/usr/bin/env node +const args = process.argv.slice(2); +function json(value, code = 0) { + process.stdout.write(JSON.stringify(value, null, 2) + '\\n'); + process.exit(code); +} +if (args[0] === '--version') { + process.stdout.write('54.1.0\\n'); + process.exit(0); +} +if (args[0] === 'whoami') { + process.stdout.write('test-user\\n'); + process.exit(0); +} +if (args[0] === 'api') { + const path = args[1]; + if (path.startsWith('/v1/observability/manage/configuration/projects')) { + json({ error: { code: 'not_found', message: 'Observability Plus is not enabled' } }, 1); + } + if (path === '/v9/projects/prj_test?teamId=team_hobby') { + json({ id: 'prj_test', name: 'fixture-site' }); + } + if (path === '/v2/teams/team_hobby') { + json({ id: 'team_hobby', slug: 'fixture', billing: { plan: 'hobby' } }); + } +} +if (args[0] === 'contract') { + json({ context: 'fixture', commitments: [], totalCommitments: 0 }); +} +if (args[0] === 'usage') { + json({ + context: 'fixture', + groupBy: { dimension: 'project', data: [] }, + services: [], + totals: { billedCost: 0 }, + }); +} +process.stderr.write('unexpected vercel call: ' + args.join(' ') + '\\n'); +process.exit(66); +`, 'utf-8'); + await chmod(fakeVercel, 0o755); + + const { stdout, stderr } = await exec('node', [COLLECT, '--continue-without-observability'], { + cwd: scratch, + env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + maxBuffer: 8 * 1024 * 1024, + }); + const out = JSON.parse(stdout); + assert.equal(out.plan.plan, 'hobby'); + assert.match(out.plan.reason, /team\.billing\.plan=hobby/); + assert.deepEqual(out.contract, { context: 'fixture', commitments: [], totalCommitments: 0 }); + assert.equal(out.usageError, null); + assert.doesNotMatch(stderr, /unexpected vercel call/); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +}); + +test('collect-signals: no orgId uses current CLI team billing.plan before user billing.plan', async () => { + const scratch = await mkdtemp(join(tmpdir(), 'vo-current-team-plan-')); + const bin = join(scratch, 'bin'); + try { + await mkdir(bin, { recursive: true }); + await mkdir(join(scratch, '.vercel'), { recursive: true }); + await writeFile(join(scratch, 'package.json'), JSON.stringify({ + dependencies: { next: '^15.3.0' }, + }), 'utf-8'); + await writeFile(join(scratch, '.vercel', 'project.json'), JSON.stringify({ + projectId: 'prj_test', + }), 'utf-8'); + const fakeVercel = join(bin, 'vercel'); + await writeFile(fakeVercel, `#!/usr/bin/env node +const args = process.argv.slice(2); +function json(value, code = 0) { + process.stdout.write(JSON.stringify(value, null, 2) + '\\n'); + process.exit(code); +} +if (args[0] === '--version') { + process.stdout.write('54.1.0\\n'); + process.exit(0); +} +if (args[0] === 'whoami' && args[1] === '--format') { + json({ + username: 'test-user', + billing: { plan: 'hobby' }, + team: { id: 'team_current', slug: 'current-team', name: 'Current Team' }, + }); +} +if (args[0] === 'whoami') { + process.stdout.write('test-user\\n'); + process.exit(0); +} +if (args[0] === 'api') { + const path = args[1]; + if (path === '/v9/projects/prj_test') { + json({ id: 'prj_test', name: 'fixture-site' }); + } + if (path === '/v2/teams/team_current') { + json({ id: 'team_current', slug: 'current-team', billing: { plan: 'pro' } }); + } + if (path === '/v2/user') { + json({ user: { username: 'test-user', billing: { plan: 'hobby' } } }); + } +} +if (args[0] === 'contract') { + json({ context: 'current-team', commitments: [], totalCommitments: 0 }); +} +if (args[0] === 'usage') { + json({ + context: 'current-team', + groupBy: { dimension: 'project', data: [] }, + services: [], + totals: { billedCost: 0 }, + }); +} +process.stderr.write('unexpected vercel call: ' + args.join(' ') + '\\n'); +process.exit(66); +`, 'utf-8'); + await chmod(fakeVercel, 0o755); + + const { stdout, stderr } = await exec('node', [COLLECT, '--continue-without-observability'], { + cwd: scratch, + env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + maxBuffer: 8 * 1024 * 1024, + }); + const out = JSON.parse(stdout); + assert.equal(out.plan.plan, 'pro'); + assert.match(out.plan.reason, /team\.billing\.plan=pro/); + assert.equal(out.orgId, null); + assert.doesNotMatch(stderr, /unexpected vercel call/); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/vercel-optimize-tests/test/fixtures/signals.hobby.json b/packages/vercel-optimize-tests/test/fixtures/signals.hobby.json index bc4d62a..581a686 100644 --- a/packages/vercel-optimize-tests/test/fixtures/signals.hobby.json +++ b/packages/vercel-optimize-tests/test/fixtures/signals.hobby.json @@ -5,7 +5,7 @@ "orgId": null, "projectIdSource": "file", "observabilityPlus": false, - "plan": { "plan": "uncertain", "reason": "no commitments found" }, + "plan": { "plan": "hobby", "reason": "user.billing.plan=hobby" }, "project": { "id": "prj_test_hobby", "framework": "nextjs", diff --git a/packages/vercel-optimize-tests/test/infer-plan.test.mjs b/packages/vercel-optimize-tests/test/infer-plan.test.mjs index 3fe7323..2eaac19 100644 --- a/packages/vercel-optimize-tests/test/infer-plan.test.mjs +++ b/packages/vercel-optimize-tests/test/infer-plan.test.mjs @@ -1,9 +1,67 @@ -// Two-tier plan inference: commitment-category first, then usage>$0 → Pro -// (closes the live gap where commitments=[] but the team has billed usage). +// Plan inference source order: Vercel account billing.plan first, then +// commitment-category fallback, then usage>$0 legacy fallback. import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { filterUsageByProject, inferPlan } from '../../../skills/vercel-optimize/lib/vercel.mjs'; +import { extractBillingPlan, filterUsageByProject, inferPlan } from '../../../skills/vercel-optimize/lib/vercel.mjs'; + +test('extractBillingPlan: reads team billing.plan from Vercel API response', () => { + assert.deepEqual( + extractBillingPlan({ billing: { plan: 'enterprise' } }), + { plan: 'enterprise', rawPlan: 'enterprise' }, + ); +}); + +test('extractBillingPlan: reads user billing.plan from /v2/user response wrapper', () => { + assert.deepEqual( + extractBillingPlan({ user: { billing: { plan: 'hobby' } } }), + { plan: 'hobby', rawPlan: 'hobby' }, + ); +}); + +test('extractBillingPlan: ignores unknown plan strings', () => { + assert.equal(extractBillingPlan({ billing: { plan: 'custom' } }), null); +}); + +test('inferPlan: account billing.plan=hobby is exact', () => { + const r = inferPlan({ commitments: [{ commitmentCategory: 'Spend' }] }, { + accountPlan: { plan: 'hobby', source: 'user.billing.plan' }, + usageTotalCost: 100, + }); + assert.equal(r.plan, 'hobby'); + assert.match(r.reason, /user\.billing\.plan=hobby/); +}); + +test('inferPlan: account billing.plan=pro is exact', () => { + const r = inferPlan({ commitments: [] }, { + accountPlan: { plan: 'pro', source: 'team.billing.plan' }, + usageTotalCost: 0, + }); + assert.equal(r.plan, 'pro'); + assert.match(r.reason, /team\.billing\.plan=pro/); +}); + +test('inferPlan: account billing.plan=enterprise is exact', () => { + const r = inferPlan({ commitments: [{ commitmentCategory: 'Spend' }] }, { + accountPlan: { plan: 'enterprise', source: 'team.billing.plan' }, + }); + assert.equal(r.plan, 'enterprise'); + assert.match(r.reason, /team\.billing\.plan=enterprise/); +}); + +test('inferPlan: string account plan is accepted for callers with a direct plan value', () => { + const r = inferPlan({ commitments: [] }, { accountPlan: 'hobby' }); + assert.equal(r.plan, 'hobby'); + assert.match(r.reason, /billing\.plan=hobby/); +}); + +test('inferPlan: unknown account plan falls back to contract category', () => { + const r = inferPlan({ commitments: [{ commitmentCategory: 'Usage' }] }, { + accountPlan: { plan: 'unknown', reason: 'team.billing.plan unavailable' }, + }); + assert.equal(r.plan, 'enterprise'); + assert.match(r.reason, /category=Usage/); +}); test('inferPlan: commitment category=Spend → Pro', () => { const r = inferPlan({ commitments: [{ category: 'Spend' }] }); diff --git a/skills/vercel-optimize/lib/vercel.mjs b/skills/vercel-optimize/lib/vercel.mjs index 55d8c47..f9a63d9 100644 --- a/skills/vercel-optimize/lib/vercel.mjs +++ b/skills/vercel-optimize/lib/vercel.mjs @@ -383,9 +383,81 @@ export async function getContract(scope) { return r.ok ? r.data : null; } -// Hobby teams don't bill — commitments=[] AND usage>$0 ⇒ Pro pay-as-you-go. -// `commitments=[] AND usage=$0` is genuinely uncertain (Hobby OR Pro with no recent billing). +export async function getAccountPlan(scope) { + const currentTeamId = scope ? null : await getCurrentTeamId(); + const teamScope = scope || currentTeamId; + + if (teamScope && !String(teamScope).startsWith('usr_')) { + const team = await getBillingPlanFromPath(`/v2/teams/${encodeURIComponent(teamScope)}`, 'team.billing.plan'); + if (team.plan !== 'unknown' || !/not_found|404/i.test(String(team.error ?? ''))) { + return team; + } + // Older project links can carry a user/org id instead of a team id. If the + // team lookup misses, fall back to the authenticated user's billing record. + } + + return await getBillingPlanFromPath('/v2/user', 'user.billing.plan'); +} + +async function getCurrentTeamId() { + const r = await runVercelJson(['whoami', '--format', 'json']); + return r.ok ? (r.data?.team?.id ?? null) : null; +} + +async function getBillingPlanFromPath(path, source) { + const r = await runVercelJson(['api', path]); + if (!r.ok) { + return { + plan: 'unknown', + reason: `${source} unavailable (${r.code ?? 'unknown'})`, + source, + error: r.code ?? 'unknown', + }; + } + + const parsed = extractBillingPlan(r.data); + if (!parsed) { + return { + plan: 'unknown', + reason: `${source} missing from Vercel API response`, + source, + }; + } + + return { + ...parsed, + reason: `${source}=${parsed.plan}`, + source, + }; +} + +export function extractBillingPlan(data) { + const raw = + data?.billing?.plan ?? + data?.team?.billing?.plan ?? + data?.user?.billing?.plan ?? + null; + const plan = normalizeBillingPlan(raw); + return plan ? { plan, rawPlan: raw } : null; +} + +function normalizeBillingPlan(raw) { + const value = String(raw ?? '').trim().toLowerCase(); + if (value === 'hobby' || value === 'pro' || value === 'enterprise') return value; + return null; +} + +// Primary source: billing.plan from `/v2/teams/:team` or `/v2/user`. +// Fallbacks: contract category, then recent billed usage for legacy CLI/API gaps. export function inferPlan(contract, opts = {}) { + const accountPlan = extractPlanOption(opts?.accountPlan); + if (accountPlan) { + return { + plan: accountPlan.plan, + reason: accountPlan.reason ?? `${accountPlan.source ?? 'billing.plan'}=${accountPlan.plan}`, + }; + } + const commits = contract?.commitments ?? []; if (commits.length > 0) { @@ -417,6 +489,26 @@ export function inferPlan(contract, opts = {}) { }; } +function extractPlanOption(accountPlan) { + if (!accountPlan) return null; + if (typeof accountPlan === 'string') { + const plan = normalizeBillingPlan(accountPlan); + return plan ? { plan, reason: `billing.plan=${plan}` } : null; + } + + const plan = normalizeBillingPlan(accountPlan.plan); + if (!plan) return null; + return { + plan, + reason: accountPlan.reason ?? ( + accountPlan.source + ? `${accountPlan.source}=${plan}` + : `billing.plan=${plan}` + ), + source: accountPlan.source ?? null, + }; +} + export async function detectStack(cwd = process.cwd()) { const pkgPath = join(cwd, 'package.json'); let pkg = {}; diff --git a/skills/vercel-optimize/references/data-collection.md b/skills/vercel-optimize/references/data-collection.md index 8407c31..2ee7e3d 100644 --- a/skills/vercel-optimize/references/data-collection.md +++ b/skills/vercel-optimize/references/data-collection.md @@ -41,7 +41,7 @@ The merged `signals.json` has this top-level shape: "observabilityPlusUsable": true | false | null, "observabilityPlusBlocker": null | "no_oplus_probe" | "project_disabled" | "payment_required" | "forbidden" | "daily_quota_exceeded" | "project_not_found" | "not_linked" | "all_failed_other" | "no_traffic", "observabilityPlusBlockerDetail": "...", - "plan": { "plan": "pro" | "enterprise" | "uncertain", "reason": "..." }, + "plan": { "plan": "hobby" | "pro" | "enterprise" | "uncertain", "reason": "..." }, "project": { /* /v9/projects/:id response, scoped to orgId via ?teamId */ }, "contract": { "context": "...", "commitments": [], "totalCommitments": 0 }, "usage": { /* vercel usage --format json --breakdown daily, or null */ }, @@ -68,7 +68,7 @@ Downstream consumers reference `signals.<field>` paths verbatim. Bumping `schema | Observability Plus configuration | Vercel CLI/API probe plus one metric access check | All `metrics.*` signals | Stop early when the team lacks Observability Plus or this project is disabled | | Observability Plus metrics access | One canary `vercel metrics vercel.request.count --since 14d --limit 1`, then full fan-out only if it succeeds | All `metrics.*` signals | Set `observabilityPlusUsable=false` with blocker detail; emit a minimal blocker document before slower project config / usage collection unless `--continue-without-observability` is passed | | Project config | `vercel api /v9/projects/:id?teamId=<orgId>` | Fluid Compute, BotID, Speed Insights, security flags | `{error: "..."}` placeholder; gates that need it skip | -| Plan tier | `vercel contract --format json --scope <orgId>` → `inferPlan()` | Cost-context framing only | `plan="uncertain"`; cost magnitudes still computed from `usage.services[].billedCost` | +| Plan tier | `vercel api /v2/teams/:orgId` (or `/v2/user` for user-owned projects) → `billing.plan`, then `vercel contract --format json --scope <orgId>` fallback → `inferPlan()` | Cost-context framing only | `plan="uncertain"`; cost magnitudes still computed from `usage.services[].billedCost` | | Billing usage | `vercel usage --format json --from <14d> --to <today>` with best-effort project grouping when supported by the installed CLI | Cost magnitude framing, billing-driven candidates | `null` + `usageError` set; cost magnitudes degrade to "small" by default | | Stack | local `package.json` + dir scan | Version-aware citation filtering, scanner gating | "unknown" framework → all framework-specific citations filtered | | `metrics.fnDurationP95ByRoute` | `vercel metrics vercel.function_invocation.function_duration_ms -a p95 --group-by route --since 14d` | `slow_route`, `platform_fluid_compute` gates | `{ok:false}`; gate emits no candidates | @@ -184,7 +184,9 @@ Calling without `?teamId=` returns 404 when the project belongs to a team other { "context": "example-team", "commitments": [], "totalCommitments": 0 } ``` -`commitments[]` field names are not stable. `inferPlan()` tries `category`, `commitmentCategory`, and `type`; empty array → `plan="uncertain"`. +The direct account billing record is the primary plan signal: `billing.plan` from `vercel api /v2/teams/:orgId` or `vercel api /v2/user` is expected to be `hobby`, `pro`, or `enterprise`. + +`vercel contract` is only a fallback. `commitments[]` field names are not stable, so `inferPlan()` tries `category`, `commitmentCategory`, and `type`; category `Spend` means Pro and `Usage` means Enterprise. Empty commitments no longer imply Hobby by themselves. ### `vercel usage --format json` diff --git a/skills/vercel-optimize/scripts/collect-signals.mjs b/skills/vercel-optimize/scripts/collect-signals.mjs index 64a40a3..5c586d5 100755 --- a/skills/vercel-optimize/scripts/collect-signals.mjs +++ b/skills/vercel-optimize/scripts/collect-signals.mjs @@ -11,6 +11,7 @@ import { checkObservabilityPlusConfiguration, getMetricsSchema, getProjectConfig, + getAccountPlan, getContract, getUsage, filterUsageByProject, @@ -214,9 +215,10 @@ async function main() { log('continuing after Observability Plus blocker because --continue-without-observability was set'); } - log('pulling project config + contract + usage in parallel…'); - const [projectCfg, contract, usageResult] = await Promise.all([ + log('pulling project config + account plan + contract + usage in parallel…'); + const [projectCfg, accountPlan, contract, usageResult] = await Promise.all([ getProjectConfig(project.projectId, project.orgId), + getAccountPlan(scope), getContract(scope), getUsage({ days: 14, scope }), ]); @@ -251,8 +253,7 @@ async function main() { log(`usage: unavailable (${usageResult?.code ?? 'unknown'}) — degrading to scanner+metrics-only mode`); } - // Hobby teams don't bill, so commitments=[] + usage>$0 ⇒ Pro pay-as-you-go. - const planInfo = inferPlan(contract, { usageTotalCost }); + const planInfo = inferPlan(contract, { accountPlan, usageTotalCost }); log(`plan=${planInfo.plan} (${planInfo.reason})`); if (projectCfg?.error) { |
