diff options
| author | John Pham <john.pham@vercel.com> | 2026-05-22 09:57:46 -0700 |
|---|---|---|
| committer | John Pham <john.pham@vercel.com> | 2026-05-22 09:57:46 -0700 |
| commit | 72dd69e06bc51368d53ca7de2c8d75bc42fe75f7 (patch) | |
| tree | c87fdcee95d7935cacd0e1eecc2d8ea6a6e1ccdf | |
| parent | c865495cd414c6105b56ae33a11ad3dc16a770cf (diff) | |
Harden vercel optimize project scopingjohnphamous/harden-vercel-optimize-scopingfeat/vercel-optimize-skill
20 files changed, 1032 insertions, 126 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..d0365aa 100644 --- a/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs +++ b/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs @@ -34,6 +34,10 @@ if [ "$1" = "whoami" ]; then echo "test-user" exit 0 fi +if [ "$1" = "teams" ] && [ "$2" = "list" ]; then + echo '{"teams":[{"id":"team_test","slug":"test-team"}]}' + exit 0 +fi echo "unexpected vercel call: $*" >&2 exit 66 `, 'utf-8'); @@ -41,7 +45,7 @@ exit 66 const { stdout, stderr } = await exec('node', [COLLECT], { cwd: scratch, - env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, VERCEL_PROJECT_ID: '', VERCEL_ORG_ID: '' }, maxBuffer: 8 * 1024 * 1024, }); const out = JSON.parse(stdout); @@ -56,3 +60,111 @@ exit 66 await rm(scratch, { recursive: true, force: true }); } }); + +test('collect-signals: ambiguous multi-project link stops before framework and metric calls', async () => { + const scratch = await mkdtemp(join(tmpdir(), 'vo-scope-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: '^16.1.6' }, + }), 'utf-8'); + await writeFile(join(scratch, '.vercel', 'repo.json'), JSON.stringify({ + projects: [ + { id: 'prj_web', orgId: 'team_test', name: 'web' }, + { id: 'prj_docs', orgId: 'team_test', name: 'docs' }, + ], + }), 'utf-8'); + const fakeVercel = join(bin, 'vercel'); + await writeFile(fakeVercel, `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "53.0.0" + exit 0 +fi +if [ "$1" = "whoami" ]; then + echo "test-user" + exit 0 +fi +echo "unexpected vercel call: $*" >&2 +exit 66 +`, 'utf-8'); + await chmod(fakeVercel, 0o755); + + const { stdout, stderr } = await exec('node', [COLLECT], { + cwd: scratch, + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, VERCEL_PROJECT_ID: '', VERCEL_ORG_ID: '' }, + maxBuffer: 8 * 1024 * 1024, + }); + const out = JSON.parse(stdout); + assert.equal(out.scopeBlocker, 'ambiguous_project'); + assert.equal(out.usageError, 'NOT_COLLECTED_SCOPE_BLOCKED'); + assert.equal(out.scopeChoices.length, 2); + assert.match(stderr, /scope resolution blocked: ambiguous_project/); + assert.doesNotMatch(stderr, /unexpected vercel call/); + assert.doesNotMatch(stderr, /checking framework support/); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +}); + +test('collect-signals: repo-linked project rootDirectory drives framework detection', async () => { + const scratch = await mkdtemp(join(tmpdir(), 'vo-repo-root-framework-')); + const bin = join(scratch, 'bin'); + try { + await mkdir(bin, { recursive: true }); + await mkdir(join(scratch, '.vercel'), { recursive: true }); + await mkdir(join(scratch, 'apps', 'web'), { recursive: true }); + await writeFile(join(scratch, 'package.json'), JSON.stringify({ + private: true, + workspaces: ['apps/*'], + }), 'utf-8'); + await writeFile(join(scratch, 'apps', 'web', 'package.json'), JSON.stringify({ + dependencies: { next: '^16.1.6' }, + }), 'utf-8'); + await writeFile(join(scratch, '.vercel', 'repo.json'), JSON.stringify({ + orgId: 'team_test', + projects: { + 'apps/web': 'prj_web', + 'apps/docs': 'prj_docs', + }, + }), 'utf-8'); + const fakeVercel = join(bin, 'vercel'); + await writeFile(fakeVercel, `#!/bin/sh +if [ "$1" = "--version" ]; then + echo "53.0.0" + exit 0 +fi +if [ "$1" = "whoami" ]; then + echo "test-user" + exit 0 +fi +if [ "$1" = "teams" ] && [ "$2" = "list" ]; then + echo '{"teams":[{"id":"team_test","slug":"test-team"}]}' + exit 0 +fi +if [ "$1" = "api" ]; then + echo '{"error":{"code":"not_found","message":"Observability Plus is not enabled"}}' + exit 1 +fi +echo "unexpected vercel call: $*" >&2 +exit 66 +`, 'utf-8'); + await chmod(fakeVercel, 0o755); + + const { stdout, stderr } = await exec('node', [COLLECT, 'prj_web'], { + cwd: scratch, + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, VERCEL_PROJECT_ID: '', VERCEL_ORG_ID: '' }, + maxBuffer: 8 * 1024 * 1024, + }); + const out = JSON.parse(stdout); + assert.equal(out.scopeBlocker, null); + assert.equal(out.stack.framework, 'next'); + assert.equal(out.stack.rootDirectory, 'apps/web'); + assert.equal(out.observabilityPlusBlocker, 'oplus_not_enabled'); + assert.match(stderr, /framework=next@16\.1\.6 support=supported/); + assert.doesNotMatch(stderr, /unexpected vercel call/); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/vercel-optimize-tests/test/collection-command-docs.test.mjs b/packages/vercel-optimize-tests/test/collection-command-docs.test.mjs index b891d70..a366134 100644 --- a/packages/vercel-optimize-tests/test/collection-command-docs.test.mjs +++ b/packages/vercel-optimize-tests/test/collection-command-docs.test.mjs @@ -19,6 +19,9 @@ test('collection docs keep JSON stdout separate from status logs', async () => { } assert.match(skill, /JSON\.parse\(require\("fs"\)\.readFileSync\(process\.argv\[1\], "utf8"\)\)/); + assert.match(skill, /jq '\{scopeBlocker, scopeBlockerDetail, scopeChoices/); + assert.match(skill, /before scanning source/); + assert.match(skill, /Do not run `scan-codebase\.mjs`, `merge-signals\.mjs`, gating, or scanner-only mode from an unresolved project\/team/); assert.match(skill, /Do not combine streams/); }); diff --git a/packages/vercel-optimize-tests/test/observability-preflight.test.mjs b/packages/vercel-optimize-tests/test/observability-preflight.test.mjs index 1a05373..d642029 100644 --- a/packages/vercel-optimize-tests/test/observability-preflight.test.mjs +++ b/packages/vercel-optimize-tests/test/observability-preflight.test.mjs @@ -33,7 +33,7 @@ test('classifyObservabilityPlusConfiguration: project_disabled when this project }); }); -test('classifyObservabilityPlusConfiguration: no_oplus_probe on public API not-enabled response', () => { +test('classifyObservabilityPlusConfiguration: oplus_not_enabled on public API not-enabled response', () => { const r = classifyObservabilityPlusConfiguration({ ok: false, code: 'not_found', @@ -42,12 +42,13 @@ test('classifyObservabilityPlusConfiguration: no_oplus_probe on public API not-e assert.equal(r.ok, true); assert.equal(r.access, false); - assert.equal(r.blocker, 'no_oplus_probe'); - assert.match(r.detail, /^Route-level metrics are unavailable/); + assert.equal(r.blocker, 'oplus_not_enabled'); + assert.match(r.detail, /^The metrics API reported/); assert.match(r.detail, /not enabled/); + assert.match(r.detail, /current Vercel scope/); }); -test('classifyObservabilityPlusConfiguration: no_oplus_probe on CLI OPLUS_REQUIRED response', () => { +test('classifyObservabilityPlusConfiguration: oplus_not_enabled on CLI OPLUS_REQUIRED response', () => { const r = classifyObservabilityPlusConfiguration({ ok: false, code: 'OPLUS_REQUIRED', @@ -56,7 +57,57 @@ test('classifyObservabilityPlusConfiguration: no_oplus_probe on CLI OPLUS_REQUIR assert.equal(r.ok, true); assert.equal(r.access, false); - assert.equal(r.blocker, 'no_oplus_probe'); + assert.equal(r.blocker, 'oplus_not_enabled'); +}); + +test('classifyObservabilityPlusConfiguration: project_disabled on project-level not-enabled response', () => { + const r = classifyObservabilityPlusConfiguration({ + ok: false, + code: 'OPLUS_REQUIRED', + stderr: 'Observability Plus is not enabled for this project', + }, { projectId: 'prj_target' }); + + assert.equal(r.ok, true); + assert.equal(r.access, false); + assert.equal(r.blocker, 'project_disabled'); + assert.match(r.detail, /not enabled for this project/); +}); + +test('classifyObservabilityPlusConfiguration: project_disabled on project disabled wording', () => { + const r = classifyObservabilityPlusConfiguration({ + ok: false, + code: 'OPLUS_REQUIRED', + stderr: 'Observability Plus is disabled for this project', + }, { projectId: 'prj_target' }); + + assert.equal(r.ok, true); + assert.equal(r.access, false); + assert.equal(r.blocker, 'project_disabled'); +}); + +test('classifyObservabilityPlusConfiguration: project_disabled on does-not-have-enabled wording', () => { + const r = classifyObservabilityPlusConfiguration({ + ok: false, + code: 'OPLUS_REQUIRED', + stderr: 'This project does not have Observability Plus enabled', + }, { projectId: 'prj_target' }); + + assert.equal(r.ok, true); + assert.equal(r.access, false); + assert.equal(r.blocker, 'project_disabled'); +}); + +test('classifyObservabilityPlusConfiguration: generic Observability Plus failure is inconclusive', () => { + const r = classifyObservabilityPlusConfiguration({ + ok: false, + code: 'EXIT_1', + stderr: 'Failed to query Observability Plus configuration endpoint.', + }, { projectId: 'prj_target' }); + + assert.equal(r.ok, false); + assert.equal(r.access, null); + assert.equal(r.blocker, 'unknown'); + assert.doesNotMatch(r.detail, /not enabled/i); }); test('classifyObservabilityPlusConfiguration: generic 404 not-enabled text is inconclusive', () => { diff --git a/packages/vercel-optimize-tests/test/oplus-diagnose.test.mjs b/packages/vercel-optimize-tests/test/oplus-diagnose.test.mjs index 94abf62..c9f9737 100644 --- a/packages/vercel-optimize-tests/test/oplus-diagnose.test.mjs +++ b/packages/vercel-optimize-tests/test/oplus-diagnose.test.mjs @@ -6,10 +6,58 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { diagnoseObservabilityPlus } from '../../../skills/vercel-optimize/scripts/collect-signals.mjs'; -test('oplus diag: probe failed → no_oplus_probe', () => { +test('oplus diag: probe failed → oplus_probe_failed without disabled claim', () => { const r = diagnoseObservabilityPlus({}, false); assert.equal(r.usable, false); - assert.equal(r.blocker, 'no_oplus_probe'); + assert.equal(r.blocker, 'oplus_probe_failed'); + assert.doesNotMatch(r.detail, /does not have Observability Plus enabled|not enabled/i); +}); + +test('oplus diag: schema probe generic failure → oplus_probe_failed without disabled claim', () => { + const r = diagnoseObservabilityPlus({}, { + ok: false, + access: null, + code: 'EXIT_1', + stderr: 'Failed to query Observability Plus configuration endpoint.', + }); + assert.equal(r.usable, false); + assert.equal(r.blocker, 'oplus_probe_failed'); + assert.match(r.detail, /code=EXIT_1/); + assert.doesNotMatch(r.detail, /not enabled/i); +}); + +test('oplus diag: generated inconclusive detail is not reclassified as disabled', () => { + const r = diagnoseObservabilityPlus({}, { + ok: false, + access: null, + code: 'EXIT_1', + detail: 'This does not prove Observability Plus is disabled.', + }); + assert.equal(r.usable, false); + assert.equal(r.blocker, 'oplus_probe_failed'); +}); + +test('oplus diag: schema probe project-level not-enabled response → project_disabled', () => { + const r = diagnoseObservabilityPlus({}, { + ok: false, + access: false, + code: 'OPLUS_REQUIRED', + stderr: 'Observability Plus is not enabled for this project.', + }); + assert.equal(r.usable, false); + assert.equal(r.blocker, 'project_disabled'); + assert.match(r.detail, /not enabled for this project/); +}); + +test('oplus diag: schema probe project disabled wording → project_disabled', () => { + const r = diagnoseObservabilityPlus({}, { + ok: false, + access: false, + code: 'OPLUS_REQUIRED', + stderr: 'This project does not have Observability Plus enabled.', + }); + assert.equal(r.usable, false); + assert.equal(r.blocker, 'project_disabled'); }); test('oplus diag: queries all returned payment_required → payment_required blocker', () => { @@ -27,7 +75,7 @@ test('oplus diag: queries all returned payment_required → payment_required blo assert.match(r.detail, /4\/4/); }); -test('oplus diag: payment_required with subscription-required text → no_oplus_probe', () => { +test('oplus diag: payment_required with subscription-required text → oplus_not_enabled', () => { const metrics = { observabilityPlusCanary: { ok: false, @@ -37,8 +85,22 @@ test('oplus diag: payment_required with subscription-required text → no_oplus_ }; const r = diagnoseObservabilityPlus(metrics, true); assert.equal(r.usable, false); - assert.equal(r.blocker, 'no_oplus_probe'); - assert.match(r.detail, /route-level Observability Plus data/); + assert.equal(r.blocker, 'oplus_not_enabled'); + assert.match(r.detail, /Observability Plus is not enabled/); +}); + +test('oplus diag: payment_required with project-not-enabled text → project_disabled', () => { + const metrics = { + observabilityPlusCanary: { + ok: false, + code: 'payment_required', + message: 'Observability Plus is not enabled for this project', + }, + }; + const r = diagnoseObservabilityPlus(metrics, true); + assert.equal(r.usable, false); + assert.equal(r.blocker, 'project_disabled'); + assert.match(r.detail, /not enabled for this project/); }); test('oplus diag: queries all hit daily quota → daily_quota_exceeded blocker', () => { @@ -128,10 +190,11 @@ test('oplus diag: mixed success + daily quota → still usable when any query re assert.equal(r.blocker, null); }); -test('oplus diag: probe OK but no metrics attempted → no_oplus_probe (defensive)', () => { +test('oplus diag: probe OK but no metrics attempted → oplus_probe_failed (defensive)', () => { const r = diagnoseObservabilityPlus({}, true); assert.equal(r.usable, false); - assert.equal(r.blocker, 'no_oplus_probe'); + assert.equal(r.blocker, 'oplus_probe_failed'); + assert.doesNotMatch(r.detail, /does not have Observability Plus enabled|not enabled/i); }); test('oplus diag: unknown failure code falls back to all_failed_other', () => { diff --git a/packages/vercel-optimize-tests/test/public-release-safety.test.mjs b/packages/vercel-optimize-tests/test/public-release-safety.test.mjs index f263910..83e0035 100644 --- a/packages/vercel-optimize-tests/test/public-release-safety.test.mjs +++ b/packages/vercel-optimize-tests/test/public-release-safety.test.mjs @@ -55,6 +55,7 @@ test('public release safety: public docs do not imply project ID replaces linkag const text = await readFile(file, 'utf8'); assert.doesNotMatch(text, /Linked Vercel project(?:,| directory) or `VERCEL_PROJECT_ID`/, file); assert.doesNotMatch(text, /Linked Vercel project, or `VERCEL_PROJECT_ID`/, file); + assert.match(text, /vercel link --repo|repo root from `vercel link --repo`/, file); } }); diff --git a/packages/vercel-optimize-tests/test/render-report.test.mjs b/packages/vercel-optimize-tests/test/render-report.test.mjs index aa3c116..ec7da20 100644 --- a/packages/vercel-optimize-tests/test/render-report.test.mjs +++ b/packages/vercel-optimize-tests/test/render-report.test.mjs @@ -270,12 +270,65 @@ test('renderReport: handles missing observabilityPlus gracefully', () => { const md = renderReport({ recommendations: [], gated: [], - signals: { ...baseSignals, observabilityPlus: false }, + signals: { + ...baseSignals, + observabilityPlus: false, + observabilityPlusBlocker: 'oplus_not_enabled', + observabilityPlusBlockerDetail: 'The metrics API reported that Observability Plus is not enabled for the current Vercel scope.', + }, }); - assert.match(md, /Not enabled — analysis based on billing \+ scanner findings/); + assert.match(md, /Observability Plus not enabled — analysis based on billing \+ scanner findings/); assert.match(md, /Observability Plus not enabled/); }); +test('renderReport: inconclusive Observability probe does not claim Observability Plus is disabled', () => { + const md = renderReport({ + recommendations: [], + gated: [], + signals: { + ...baseSignals, + observabilityPlus: false, + observabilityPlusUsable: false, + observabilityPlusBlocker: 'oplus_probe_failed', + observabilityPlusBlockerDetail: '`vercel metrics schema` returned non-OK. This does not prove Observability Plus is disabled.', + }, + }); + assert.match(md, /Per-route metrics probe failed/); + assert.doesNotMatch(md, /Not enabled — analysis based/); + assert.doesNotMatch(md, /Observability Plus not enabled/); +}); + +test('renderReport: missing Observability fields do not imply metrics were included', () => { + const { observabilityPlus, observabilityPlusUsable, observabilityPlusBlocker, ...signals } = baseSignals; + const md = renderReport({ + recommendations: [], + gated: [], + signals, + }); + + assert.match(md, /Per-route metrics unavailable — analysis based on billing \+ scanner findings/); + assert.match(md, /Per-route metrics unavailable — route latency \/ cache-hit \/ cold-start analysis was skipped/); + assert.doesNotMatch(md, /Observability Plus enabled — per-route metrics included/); +}); + +test('renderReport: unresolved project scope does not claim metrics were included', () => { + const md = renderReport({ + recommendations: [], + gated: [], + signals: { + ...baseSignals, + scopeBlocker: 'ambiguous_project', + scopeBlockerDetail: 'This directory is linked to multiple Vercel projects.', + observabilityPlus: null, + observabilityPlusUsable: null, + observabilityPlusBlocker: null, + }, + }); + assert.match(md, /Project\/team scope unresolved — analysis cannot use Vercel metrics/); + assert.match(md, /Project\/team scope unresolved — Vercel usage and route metrics were not collected/); + assert.doesNotMatch(md, /Observability Plus enabled — per-route metrics included/); +}); + test('renderReport: hides sanitizerTrail by default and does not emit generic review notes', () => { const rec = { ...sampleRec, diff --git a/packages/vercel-optimize-tests/test/scope-resolution.test.mjs b/packages/vercel-optimize-tests/test/scope-resolution.test.mjs new file mode 100644 index 0000000..d585b91 --- /dev/null +++ b/packages/vercel-optimize-tests/test/scope-resolution.test.mjs @@ -0,0 +1,178 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + readProjectJson, + resolveProjectId, +} from '../../../skills/vercel-optimize/lib/vercel.mjs'; + +async function withScratch(fn) { + const scratch = await mkdtemp(join(tmpdir(), 'vo-scope-')); + try { + await mkdir(join(scratch, '.vercel'), { recursive: true }); + return await fn(scratch); + } finally { + await rm(scratch, { recursive: true, force: true }); + } +} + +function withEnv(env, fn) { + const prev = {}; + for (const key of Object.keys(env)) { + prev[key] = process.env[key]; + if (env[key] == null) delete process.env[key]; + else process.env[key] = env[key]; + } + return Promise.resolve() + .then(fn) + .finally(() => { + for (const key of Object.keys(env)) { + if (prev[key] == null) delete process.env[key]; + else process.env[key] = prev[key]; + } + }); +} + +async function writeRepoJson(cwd, projects, extra = {}) { + await writeFile(join(cwd, '.vercel', 'repo.json'), JSON.stringify({ ...extra, projects }), 'utf-8'); +} + +async function writeProjectJson(cwd, project) { + await writeFile(join(cwd, '.vercel', 'project.json'), JSON.stringify(project), 'utf-8'); +} + +test('resolveProjectId: blocks multi-project repo.json without an explicit project', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, [ + { id: 'prj_web', orgId: 'team_a', name: 'web' }, + { id: 'prj_docs', orgId: 'team_a', name: 'docs' }, + ]); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId(null, cwd)); + + assert.equal(r.ok, false); + assert.equal(r.blocker, 'ambiguous_project'); + assert.equal(r.choices.length, 2); +})); + +test('resolveProjectId: explicit project selects the matching repo.json project and team', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, [ + { id: 'prj_web', orgId: 'team_a', name: 'web' }, + { id: 'prj_docs', orgId: 'team_b', name: 'docs', rootDirectory: 'apps/docs' }, + ]); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId('prj_docs', cwd)); + + assert.equal(r.ok, true); + assert.equal(r.projectId, 'prj_docs'); + assert.equal(r.orgId, 'team_b'); + assert.equal(r.rootDirectory, 'apps/docs'); +})); + +test('resolveProjectId: repo.json project map inherits top-level team scope', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, { + 'apps/web': 'prj_web', + 'apps/docs': { id: 'prj_docs', name: 'docs' }, + }, { orgId: 'team_a', teamSlug: 'acme' }); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId('prj_docs', cwd)); + + assert.equal(r.ok, true); + assert.equal(r.projectId, 'prj_docs'); + assert.equal(r.orgId, 'team_a'); + assert.equal(r.orgSlug, 'acme'); + assert.equal(r.rootDirectory, 'apps/docs'); +})); + +test('resolveProjectId: repo.json project array inherits top-level team scope', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, [ + { id: 'prj_docs', name: 'docs', rootDirectory: 'apps/docs' }, + ], { orgId: 'team_a', teamSlug: 'acme' }); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId(null, cwd)); + + assert.equal(r.ok, true); + assert.equal(r.projectId, 'prj_docs'); + assert.equal(r.orgId, 'team_a'); + assert.equal(r.orgSlug, 'acme'); +})); + +test('resolveProjectId: generic repo.json slug is not treated as a team slug', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, [ + { id: 'prj_docs', orgId: 'team_b', slug: 'docs-project-slug' }, + ]); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId(null, cwd)); + + assert.equal(r.ok, true); + assert.equal(r.orgId, 'team_b'); + assert.equal(r.orgSlug, null); +})); + +test('resolveProjectId: explicit project mismatch blocks instead of mixing API and metrics scope', async () => withScratch(async (cwd) => { + await writeProjectJson(cwd, { projectId: 'prj_linked', orgId: 'team_a' }); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId('prj_requested', cwd)); + + assert.equal(r.ok, false); + assert.equal(r.blocker, 'project_link_mismatch'); + assert.equal(r.choices[0].projectId, 'prj_linked'); +})); + +test('resolveProjectId: env project ID must match the linked project', async () => withScratch(async (cwd) => { + await writeProjectJson(cwd, { projectId: 'prj_linked', orgId: 'team_a' }); + + const r = await withEnv({ VERCEL_PROJECT_ID: 'prj_other', VERCEL_ORG_ID: null }, () => resolveProjectId(null, cwd)); + + assert.equal(r.ok, false); + assert.equal(r.blocker, 'project_link_mismatch'); +})); + +test('resolveProjectId: VERCEL_ORG_ID conflict with linked team blocks collection', async () => withScratch(async (cwd) => { + await writeProjectJson(cwd, { projectId: 'prj_linked', orgId: 'team_a' }); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: 'team_b' }, () => resolveProjectId(null, cwd)); + + assert.equal(r.ok, false); + assert.equal(r.blocker, 'team_scope_conflict'); +})); + +test('resolveProjectId: missing linked team blocks even when VERCEL_ORG_ID is set', async () => withScratch(async (cwd) => { + await writeProjectJson(cwd, { projectId: 'prj_linked' }); + + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: 'team_from_env' }, () => resolveProjectId(null, cwd)); + + assert.equal(r.ok, false); + assert.equal(r.blocker, 'team_scope_missing'); + assert.match(r.detail, /cannot verify/); +})); + +test('resolveProjectId: unlinked cwd blocks even when project ID was supplied', async () => withScratch(async (cwd) => { + const r = await withEnv({ VERCEL_PROJECT_ID: null, VERCEL_ORG_ID: null }, () => resolveProjectId('prj_requested', cwd)); + + assert.equal(r.ok, false); + assert.equal(r.blocker, 'not_linked'); + assert.match(r.detail, /project ID alone is not enough/); +})); + +test('readProjectJson: multi-project repo returns exact match when projectId is supplied', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, [ + { id: 'prj_web', orgId: 'team_a', name: 'web' }, + { id: 'prj_docs', orgId: 'team_b', name: 'docs' }, + ]); + + const r = await readProjectJson(cwd, { projectId: 'prj_docs' }); + + assert.equal(r.projectId, 'prj_docs'); + assert.equal(r.orgId, 'team_b'); +})); + +test('readProjectJson: multi-project repo without projectId is intentionally ambiguous', async () => withScratch(async (cwd) => { + await writeRepoJson(cwd, [ + { id: 'prj_web', orgId: 'team_a', name: 'web' }, + { id: 'prj_docs', orgId: 'team_b', name: 'docs' }, + ]); + + assert.equal(await readProjectJson(cwd), null); +})); diff --git a/packages/vercel-optimize-tests/test/time-window.test.mjs b/packages/vercel-optimize-tests/test/time-window.test.mjs index dcfb2f9..046dabb 100644 --- a/packages/vercel-optimize-tests/test/time-window.test.mjs +++ b/packages/vercel-optimize-tests/test/time-window.test.mjs @@ -34,3 +34,12 @@ test('collect-signals.mjs: passes TIME_WINDOW (not a string literal) to queryMet assert.equal(literalSince, null, `collect-signals.mjs must not hard-pin since to a literal; found: ${literalSince}`); }); + +test('metric query call sites pass explicit projectId to avoid currentTeam drift', async () => { + const collectSrc = await readFile(join(HERE, '..', '..', '..', 'skills', 'vercel-optimize', 'scripts', 'collect-signals.mjs'), 'utf-8'); + const deepDiveSrc = await readFile(join(HERE, '..', '..', '..', 'skills', 'vercel-optimize', 'scripts', 'deep-dive.mjs'), 'utf-8'); + assert.match(collectSrc, /queryMetric\('vercel\.request\.count'[\s\S]*projectId:\s*project\.projectId/); + assert.match(collectSrc, /queryMetric\(entry\.metricId[\s\S]*projectId,\s*\n/); + assert.match(deepDiveSrc, /const scope = merged\.scopeResolution\?\.cliScope \|\| merged\.orgId \|\| undefined/); + assert.match(deepDiveSrc, /queryMetric\(spec\.metricId[\s\S]*projectId:\s*merged\.projectId/); +}); diff --git a/packages/vercel-optimize-tests/test/voice-drift.test.mjs b/packages/vercel-optimize-tests/test/voice-drift.test.mjs index 750de6c..6e87942 100644 --- a/packages/vercel-optimize-tests/test/voice-drift.test.mjs +++ b/packages/vercel-optimize-tests/test/voice-drift.test.mjs @@ -41,22 +41,22 @@ test('voice drift: no markdown file uses Observability Plus shorthand', async () test('voice drift: Observability Plus blocker question uses exact plain copy', async () => { const content = await readFile(join(ROOT, 'references', 'observability-plus.md'), 'utf-8'); - assert.match(content, /"header": "Observability Plus"/); + assert.match(content, /"header": "Metrics access"/); assert.match( content, - /"question": "Enable Observability Plus and re-run, or continue with a limited scanner-only audit\?"/ + /"question": "Fix per-route metrics access and re-run, or continue with a limited scanner-only audit\?"/ ); - assert.match(content, /"label": "Enable and re-run"/); + assert.match(content, /"label": "Fix and re-run"/); assert.match(content, /"label": "Run scanner-only"/); assert.doesNotMatch(content, /\b(O11y|OPlus|Oplus|O-Plus|perf|CWV)\b|obs\+/); }); test('voice drift: Observability Plus post-choice copy avoids IDs and pricing language', async () => { const content = await readFile(join(ROOT, 'references', 'observability-plus.md'), 'utf-8'); - assert.match(content, /If the user chooses \*\*Enable and re-run\*\*/); + assert.match(content, /If the user chooses \*\*Fix and re-run\*\*/); assert.match( content, - /Enable Observability Plus from the Vercel dashboard's Observability tab, then tell me to rerun\./ + /Fix per-route metrics access, then tell me to rerun\./ ); assert.match(content, /Do not include raw team IDs, org IDs, project IDs, pricing language/); assert.doesNotMatch(content, /paid add-on|paid feature|just say the word/i); diff --git a/skills/vercel-optimize/AGENTS.md b/skills/vercel-optimize/AGENTS.md index 66cc82f..acc4df2 100644 --- a/skills/vercel-optimize/AGENTS.md +++ b/skills/vercel-optimize/AGENTS.md @@ -11,7 +11,7 @@ Do not use it for projects that are not deployed on Vercel, greenfield projects - Node.js 20+ - Vercel CLI with `vercel metrics`, `vercel usage`, `vercel contract`, and `vercel api` support; v53+ is this skill's compatibility floor - Authenticated Vercel CLI session -- Linked Vercel project directory (`vercel link`) for route metrics. `VERCEL_PROJECT_ID` can help resolve project config, but it does not replace directory linkage for `vercel metrics`. +- Linked Vercel directory (`vercel link` for one project, or the repo root from `vercel link --repo` for multi-project repos) for route metrics. `VERCEL_PROJECT_ID` can select a project only when it matches the linked cwd; it does not replace directory linkage for `vercel metrics`. Multi-project links require an explicit matching project ID. - Observability Plus for per-route metric analysis ## Procedure diff --git a/skills/vercel-optimize/README.md b/skills/vercel-optimize/README.md index b24d512..e2463d2 100644 --- a/skills/vercel-optimize/README.md +++ b/skills/vercel-optimize/README.md @@ -21,7 +21,7 @@ Manual install: copy `skills/vercel-optimize` into `.agents/skills/vercel-optimi - Node.js 20+ - Vercel CLI with `vercel metrics`, `vercel usage`, `vercel contract`, and `vercel api` support (`npm i -g vercel@latest`). The skill enforces v53+ as its compatibility floor. - Authenticated Vercel CLI session (`vercel login`) -- Linked Vercel project directory (`vercel link`) for route metrics. `VERCEL_PROJECT_ID` can resolve project config, but it does not replace directory linkage for `vercel metrics`. +- Linked Vercel directory (`vercel link` for one project, or the repo root from `vercel link --repo` for multi-project repos) for route metrics. `VERCEL_PROJECT_ID` can select a project only when it matches the linked cwd; it does not replace directory linkage for `vercel metrics`. Multi-project links require an explicit matching project ID. - Observability Plus for metric-backed route ranking - Code-backed recommendation coverage is strongest for Next.js and SvelteKit, supported for Nuxt route mapping with generic checks, and limited for Astro. Hono, Remix, and unknown frameworks pause up front. diff --git a/skills/vercel-optimize/SKILL.md b/skills/vercel-optimize/SKILL.md index 8ae79f9..43d0525 100644 --- a/skills/vercel-optimize/SKILL.md +++ b/skills/vercel-optimize/SKILL.md @@ -21,7 +21,7 @@ Core doctrine: read [references/doctrine.md](references/doctrine.md) if any rule - Vercel CLI v53+ with `vercel metrics`, `vercel usage`, `vercel contract`, and `vercel api`. - Authenticated CLI session: `vercel login`. -- Linked app directory: `vercel link`. `VERCEL_PROJECT_ID` can help resolve project config, but `vercel metrics` still requires directory linkage. +- Linked Vercel directory: `vercel link` for a single project, or the repo root created by `vercel link --repo` for multi-project repositories. `VERCEL_PROJECT_ID` can select a project only when it matches the linked cwd; `vercel metrics` still requires directory linkage. Multi-project links require an explicit matching project ID. - Node.js 20+. - Observability Plus for route-level metric-backed recommendations. @@ -60,13 +60,21 @@ RUN_DIR="$(mktemp -d -t vercel-optimize-XXXXXX)" ## Pipeline -### 1. Collect, scan, and merge signals +### 1. Collect Vercel signals and stop on blockers -Run from the linked app directory or pass `--cwd` where a script supports it. Keep stdout JSON separate from stderr logs. Do not combine streams. +Run from the linked Vercel directory or pass `--cwd` where a script supports it. For `vercel link --repo`, use the repo root and pass the exact project ID. Keep stdout JSON separate from stderr logs. Do not combine streams. ```bash node scripts/collect-signals.mjs [projectId] > "$RUN_DIR/vercel-signals.json" 2> "$RUN_DIR/collect.stderr" node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$RUN_DIR/vercel-signals.json" +jq '{scopeBlocker, scopeBlockerDetail, scopeChoices, frameworkSupportBlocker, observabilityPlus, observabilityPlusUsable, observabilityPlusBlocker, observabilityPlusBlockerDetail}' "$RUN_DIR/vercel-signals.json" +``` + +If any blocker field is non-null, follow Step 1.1 before scanning source. Do not run `scan-codebase.mjs`, `merge-signals.mjs`, gating, or scanner-only mode from an unresolved project/team or metrics-access state. + +If collection is clear, scan and merge: + +```bash node scripts/scan-codebase.mjs <repo-root> > "$RUN_DIR/codebase.json" node scripts/merge-signals.mjs "$RUN_DIR/vercel-signals.json" "$RUN_DIR/codebase.json" --out "$RUN_DIR/signals.json" @@ -76,18 +84,21 @@ Collection details, schemas, metric IDs, and degradation behavior live in [refer ### 1.1 Stop on blockers -Check blockers before gating: +Check blockers before scanning when using `vercel-signals.json`, and again before gating when using merged `signals.json`: ```bash -jq '{frameworkSupportBlocker, observabilityPlus, observabilityPlusUsable, observabilityPlusBlocker, observabilityPlusBlockerDetail}' "$RUN_DIR/signals.json" +jq '{scopeBlocker, scopeBlockerDetail, scopeChoices, frameworkSupportBlocker, observabilityPlus, observabilityPlusUsable, observabilityPlusBlocker, observabilityPlusBlockerDetail}' "$RUN_DIR/signals.json" ``` Required actions: +- `scopeBlocker !== null`: stop before scanning or gating. Ask the user to confirm the exact Vercel team and project. If `scopeChoices` is non-empty, show the choices; otherwise ask them to run `vercel link --yes --project <project-name-or-id> --cwd <app-dir>` and include `--team <team-id-or-slug>` when known. Do not run a scanner-only audit from an unresolved scope. - `frameworkSupportBlocker === "unsupported_framework"`: use the unsupported-framework prompt above. - `observabilityPlusBlocker === null`: continue. - `no_traffic`: tell the user route metrics are sparse; continue only if they accept limited output. -- `payment_required` or `no_oplus_probe`: render [references/observability-plus.md](references/observability-plus.md) verbatim and ask. +- `oplus_not_enabled`: render [references/observability-plus.md](references/observability-plus.md) verbatim and ask. +- `payment_required`: tell the user route-level metrics were recognized but unusable; check subscription, quota, or access, or continue with a limited audit. +- `oplus_probe_failed`: tell the user the probe was inconclusive, show `observabilityPlusBlockerDetail`, and ask them to verify the linked project/team or provide `$RUN_DIR/collect.stderr`. Do not say Observability Plus is disabled. - `project_disabled`: tell the user to enable Observability Plus for the project or accept a limited audit. - `daily_quota_exceeded`: stop and tell the user the Observability query quota is exhausted; retry after the next UTC midnight reset, or ask whether to continue with a limited code-only audit. - `not_linked`: link the app directory, then rerun Step 1. If app path and project are known: @@ -295,12 +306,16 @@ Use these messages without adding sales copy or process detail. **Route-level metrics unavailable:** -> Use the verbatim choice template in [references/observability-plus.md](references/observability-plus.md). Do not silently fall back to code-only mode; present the two-path choice: enable Observability Plus and rerun the metric-backed audit, or accept a limited code-only run. +> Use the blocker-specific copy in [references/observability-plus.md](references/observability-plus.md). Do not silently fall back to code-only mode. If the blocker is inconclusive, say the probe failed and ask for project/team/link verification; only tell the user to enable Observability Plus when the metrics API explicitly reported that it is not enabled. **Project is not linked:** > This worktree is not linked to a Vercel project. Run `vercel link --yes --project <project-name-or-id> --cwd <app-dir>` and rerun the audit. If the team is known, add `--team <team-id-or-slug>`. +**Project/team scope is ambiguous:** + +> I found more than one linked Vercel project for this directory. Which team and project should I audit? I need the exact project and team before collecting metrics so I do not mix data from another scope. + **Most route-to-file mappings failed:** > The route inventory matched fewer than half of the routes we saw in observability. This is common in monorepos with custom routing. I've surfaced what I can match; the rest appear in the "Not investigated in this run" section. diff --git a/skills/vercel-optimize/lib/render-report.mjs b/skills/vercel-optimize/lib/render-report.mjs index 673c211..7fd2a75 100644 --- a/skills/vercel-optimize/lib/render-report.mjs +++ b/skills/vercel-optimize/lib/render-report.mjs @@ -17,7 +17,6 @@ export function renderReport({ recommendations = [], gated = [], abstentions = [ const projectName = opts.projectName ?? signals.project?.name ?? '<project>'; const stack = signals.stack ?? signals.codebase?.stack ?? {}; const usage = signals.usage ?? null; - const oplus = signals.observabilityPlus !== false; const plan = signals.plan ?? { plan: 'unknown', reason: '(not detected)' }; // Sub-agents don't always propagate o11ySignal/aliasRoutes — look them up by candidateRef and canonicalize the displayed ref. @@ -27,7 +26,7 @@ export function renderReport({ recommendations = [], gated = [], abstentions = [ const lines = []; lines.push(`# Vercel Optimization Report — ${projectName}`); lines.push(''); - lines.push(renderMetadataLine(stack, plan, usage, oplus)); + lines.push(renderMetadataLine(stack, plan, usage, signals)); const coverageLine = renderCoverageLine(candidates, recommendations, signals, { abstentions, heldBackCount: opts.heldBackCount, @@ -307,7 +306,7 @@ function renderCoverageLine(candidates, recommendations, signals, opts = {}) { return `**Coverage**: ${parts.join(' · ')} · [details](#not-investigated-in-this-run)`; } -function renderMetadataLine(stack, plan, usage, oplus) { +function renderMetadataLine(stack, plan, usage, signals) { const fw = `${stack.framework ?? 'unknown'}@${stack.frameworkVersion ?? '?'}`; const router = stack.hasAppRouter ? 'app-router' : stack.hasPagesRouter ? 'pages-router' : null; const orm = stack.orm && stack.orm !== 'none' ? stack.orm : null; @@ -315,14 +314,32 @@ function renderMetadataLine(stack, plan, usage, oplus) { const period = usage?.period ? `${usage.period.from ?? '?'} → ${usage.period.to ?? '?'}` : '(unavailable)'; - const oplusLabel = oplus - ? 'Observability Plus enabled — per-route metrics included' - : 'Not enabled — analysis based on billing + scanner findings'; // Plan-inference reason is debug detail — only surface when plan is uncertain. const planLabel = plan.plan === 'uncertain' ? `${plan.plan} (${plan.reason ?? 'no signal'})` : (plan.plan ?? 'unknown'); - return `**Stack**: ${stackParts} · **Plan**: ${planLabel} · **Period**: ${period} · **Observability**: ${oplusLabel}`; + return `**Stack**: ${stackParts} · **Plan**: ${planLabel} · **Period**: ${period} · **Observability**: ${renderObservabilityMetadata(signals)}`; +} + +function observabilityMetricsIncluded(signals) { + if (signals.scopeBlocker) return false; + if (signals.observabilityPlusBlocker) return false; + if (signals.observabilityPlusUsable === true) return true; + if (signals.observabilityPlusUsable === false) return false; + if (signals.observabilityPlus === true) return true; + if (signals.observabilityPlus === false) return false; + return false; +} + +function renderObservabilityMetadata(signals) { + if (signals.scopeBlocker) return 'Project/team scope unresolved — analysis cannot use Vercel metrics'; + const blocker = signals.observabilityPlusBlocker; + if (observabilityMetricsIncluded(signals)) return 'Observability Plus enabled — per-route metrics included'; + if (blocker === 'oplus_not_enabled') return 'Observability Plus not enabled — analysis based on billing + scanner findings'; + if (blocker === 'project_disabled') return 'Observability Plus disabled for this project — analysis based on billing + scanner findings'; + if (blocker === 'oplus_probe_failed') return 'Per-route metrics probe failed — analysis based on billing + scanner findings'; + if (blocker === 'no_traffic') return 'Observability Plus enabled — no route traffic in this window'; + return 'Per-route metrics unavailable — analysis based on billing + scanner findings'; } function renderCostHeader(signals) { @@ -660,7 +677,8 @@ function renderConfigurationNotes(signals) { function renderDataGaps(signals) { const lines = []; - if (signals.observabilityPlus === false) lines.push('- Observability Plus not enabled — per-route latency / cache-hit / cold-start metrics unavailable.'); + const observabilityGap = renderObservabilityDataGap(signals); + if (observabilityGap) lines.push(observabilityGap); if (!signals.usage) lines.push('- `vercel usage` was unavailable — cost breakdown derived from observability where possible.'); const cwv = signals.metrics?.cwvCount?.rows?.[0]?.value ?? 0; if (cwv === 0) lines.push('- No Speed Insights measurements — Core Web Vitals analysis dormant. Wire up Speed Insights to enable LCP/INP/CLS recommendations.'); @@ -674,6 +692,36 @@ function renderDataGaps(signals) { return lines; } +function renderObservabilityDataGap(signals) { + if (observabilityMetricsIncluded(signals)) return null; + if (signals.scopeBlocker) { + const reason = signals.scopeBlockerDetail ? formatPublicText(signals.scopeBlockerDetail) : formatPublicText(signals.scopeBlocker); + return `- Project/team scope unresolved — Vercel usage and route metrics were not collected (${reason}).`; + } + const blocker = signals.observabilityPlusBlocker; + const detail = signals.observabilityPlusBlockerDetail; + if (blocker === 'oplus_not_enabled') { + return '- Observability Plus not enabled — per-route latency / cache-hit / cold-start metrics unavailable.'; + } + if (blocker === 'project_disabled') { + return '- Observability Plus is disabled for this project — per-route latency / cache-hit / cold-start metrics unavailable.'; + } + if (blocker === 'oplus_probe_failed') { + return `- Per-route metrics probe failed — route latency / cache-hit / cold-start analysis was skipped${detail ? ` (${formatPublicText(detail)})` : '.'}`; + } + if (blocker === 'no_traffic') { + return '- No route traffic observed in the metrics window — route ranking is dormant until traffic accumulates.'; + } + if (blocker) { + const reason = detail ? formatPublicText(detail) : formatPublicText(blocker); + return `- Per-route metrics unavailable — route latency / cache-hit / cold-start analysis was skipped (${reason}).`; + } + if (signals.observabilityPlus === false) { + return '- Per-route metrics unavailable — route latency / cache-hit / cold-start analysis was skipped.'; + } + return '- Per-route metrics unavailable — route latency / cache-hit / cold-start analysis was skipped.'; +} + function sortRecs(recs) { return recs.slice().sort((a, b) => priorityScore(b) - priorityScore(a)); } diff --git a/skills/vercel-optimize/lib/vercel.mjs b/skills/vercel-optimize/lib/vercel.mjs index 55d8c47..e54290e 100644 --- a/skills/vercel-optimize/lib/vercel.mjs +++ b/skills/vercel-optimize/lib/vercel.mjs @@ -41,13 +41,17 @@ export async function checkAuth() { } // Supports newer `.vercel/repo.json` (multi-project) + legacy `.vercel/project.json` (single-project). -export async function readProjectJson(cwd = process.cwd()) { +export async function readLinkedProjects(cwd = process.cwd()) { try { const raw = await readFile(join(cwd, '.vercel', 'repo.json'), 'utf-8'); const parsed = JSON.parse(raw); - const first = parsed?.projects?.[0]; - if (first?.id) { - return { projectId: first.id, orgId: first.orgId ?? null, source: 'repo.json' }; + const defaults = { + orgId: parsed?.orgId ?? parsed?.teamId ?? parsed?.accountId ?? null, + orgSlug: parsed?.orgSlug ?? parsed?.teamSlug ?? null, + }; + const projects = normalizeRepoProjects(parsed?.projects, defaults); + if (projects.length > 0) { + return { source: 'repo.json', projects }; } } catch { /* fall through */ } @@ -55,31 +59,191 @@ export async function readProjectJson(cwd = process.cwd()) { try { const raw = await readFile(join(cwd, '.vercel', 'project.json'), 'utf-8'); const parsed = JSON.parse(raw); - if (parsed?.projectId) { - return { projectId: parsed.projectId, orgId: parsed.orgId ?? null, source: 'project.json' }; + const project = normalizeLinkedProject(parsed, 'project.json'); + if (project) { + return { source: 'project.json', projects: [project] }; } } catch { /* fall through */ } + return { source: null, projects: [] }; +} + +export async function readProjectJson(cwd = process.cwd(), opts = {}) { + const linked = await readLinkedProjects(cwd); + if (linked.projects.length === 0) return null; + if (opts.projectId) { + return linked.projects.find((p) => p.projectId === opts.projectId) ?? null; + } + if (linked.projects.length === 1) return linked.projects[0]; return null; } // Does NOT auto-run `vercel link` — interactive surprises bad. export async function resolveProjectId(explicit, cwd = process.cwd()) { - if (explicit) { + const linked = await readLinkedProjects(cwd); + const explicitProjectId = explicit || null; + const envProjectId = process.env.VERCEL_PROJECT_ID || null; + const envOrgId = process.env.VERCEL_ORG_ID || null; + const requestedProjectId = explicitProjectId || envProjectId || null; + const inputSource = explicitProjectId ? 'arg' : envProjectId ? 'env' : null; + const choices = linked.projects.map(scopeChoice); + + const blocked = (blocker, detail, extra = {}) => ({ + ok: false, + blocker, + detail, + source: linked.source ?? inputSource ?? null, + projectId: requestedProjectId, + orgId: envOrgId, + inputProjectId: requestedProjectId, + inputProjectIdSource: inputSource, + choices, + ...extra, + }); + + if (linked.projects.length === 0) { + return blocked( + 'not_linked', + requestedProjectId + ? 'This directory is not linked to a Vercel project. Passing a project ID alone is not enough for route-level metrics because the CLI also resolves project context from the linked cwd.' + : 'This directory is not linked to a Vercel project.' + ); + } + + let selected = null; + if (requestedProjectId) { + selected = linked.projects.find((p) => p.projectId === requestedProjectId) ?? null; + if (!selected) { + return blocked( + 'project_link_mismatch', + 'The requested project does not match the Vercel project linked in this directory. Use the directory linked to that project, or relink this directory before collecting metrics.', + { linkedProjectCount: linked.projects.length } + ); + } + } else if (linked.projects.length === 1) { + selected = linked.projects[0]; + } else { + return blocked( + 'ambiguous_project', + 'This directory is linked to multiple Vercel projects. The skill cannot safely choose one automatically.', + { linkedProjectCount: linked.projects.length } + ); + } + + if (envOrgId && selected.orgId && envOrgId !== selected.orgId) { + return blocked( + 'team_scope_conflict', + 'VERCEL_ORG_ID does not match the linked project team. Unset VERCEL_ORG_ID or relink the directory before collecting metrics.', + { selected: scopeChoice(selected) } + ); + } + + if (!selected.orgId) { + return blocked( + 'team_scope_missing', + 'The linked project did not include a team ID. VERCEL_ORG_ID cannot be used to infer it because the skill cannot verify that environment value against the linked project.', + { selected: scopeChoice(selected) } + ); + } + + return { + ...selected, + ok: true, + orgId: selected.orgId ?? envOrgId, + inputProjectId: requestedProjectId, + inputProjectIdSource: inputSource, + choices: [scopeChoice(selected)], + }; +} + +export async function resolveTeamScope(orgId) { + if (!orgId) { + return { ok: false, blocker: 'team_scope_missing', detail: 'No team ID was available for Vercel CLI scoping.' }; + } + if (!/^team_[A-Za-z0-9]+$/.test(orgId)) { + return { ok: true, orgId, cliScope: orgId, source: 'org-id-as-scope' }; + } + const r = await runVercelJson(['teams', 'list', '--format', 'json']); + if (!r.ok) { return { - projectId: explicit, - orgId: process.env.VERCEL_ORG_ID || null, - source: 'arg', + ok: false, + blocker: 'team_scope_unresolved', + detail: 'Could not resolve a team slug for the linked team; Vercel CLI subcommands may otherwise use the global currentTeam.', + code: r.code, + stderr: r.stderr, }; } - if (process.env.VERCEL_PROJECT_ID) { + const teams = Array.isArray(r.data) + ? r.data + : Array.isArray(r.data?.teams) + ? r.data.teams + : Array.isArray(r.data?.data) + ? r.data.data + : []; + const team = teams.find((t) => String(t?.id ?? '') === orgId); + const slug = team?.slug ?? null; + if (!slug) { return { - projectId: process.env.VERCEL_PROJECT_ID, - orgId: process.env.VERCEL_ORG_ID || null, - source: 'env', + ok: false, + blocker: 'team_scope_unresolved', + detail: 'Could not find the linked team in `vercel teams list --format json`. Ask the user to confirm the team slug before collecting metrics.', }; } - return await readProjectJson(cwd); + return { ok: true, orgId, cliScope: slug, source: 'teams-list' }; +} + +function normalizeLinkedProject(project, source) { + if (typeof project === 'string') { + return { projectId: project, orgId: null, orgSlug: null, name: null, rootDirectory: null, source }; + } + const projectId = project?.projectId ?? project?.id ?? null; + if (!projectId) return null; + return { + projectId, + orgId: project.orgId ?? project.teamId ?? project.accountId ?? null, + orgSlug: project.orgSlug ?? project.teamSlug ?? null, + name: project.name ?? project.projectName ?? null, + rootDirectory: project.rootDirectory ?? project.rootDir ?? project.directory ?? null, + source, + }; +} + +function normalizeRepoProjects(projects, defaults = {}) { + if (Array.isArray(projects)) { + return projects.map((p) => withLinkedDefaults(normalizeLinkedProject(p, 'repo.json'), defaults)).filter(Boolean); + } + if (projects && typeof projects === 'object') { + return Object.entries(projects) + .map(([rootDirectory, value]) => { + const raw = value && typeof value === 'object' + ? { rootDirectory, ...value } + : { projectId: value, rootDirectory }; + return withLinkedDefaults(normalizeLinkedProject(raw, 'repo.json'), defaults); + }) + .filter(Boolean); + } + return []; +} + +function withLinkedDefaults(project, defaults = {}) { + if (!project) return null; + return { + ...project, + orgId: project.orgId ?? defaults.orgId ?? null, + orgSlug: project.orgSlug ?? defaults.orgSlug ?? null, + }; +} + +function scopeChoice(project) { + if (!project) return null; + return { + projectId: project.projectId, + orgId: project.orgId ?? null, + orgSlug: project.orgSlug ?? null, + name: project.name ?? null, + rootDirectory: project.rootDirectory ?? null, + source: project.source ?? null, + }; } // Some commands emit `{error: {...}}` on stdout AND exit non-zero — parse stdout first; embedded `error` is the most reliable signal. @@ -152,7 +316,8 @@ export function redactSensitiveText(value) { function categorizeError(exitCode, stderr) { const lc = (stderr || '').toLowerCase(); if (isDailyQuotaExceeded({ ok: false, stderr })) return 'DAILY_QUOTA_EXCEEDED'; - if (lc.includes('observability plus')) return 'OPLUS_REQUIRED'; + if (mentionsObservabilityPlusNotEnabled(lc)) return 'OPLUS_REQUIRED'; + if (/payment required[\s\S]{0,160}observability plus/.test(lc) || /observability plus[\s\S]{0,160}payment required/.test(lc)) return 'PAYMENT_REQUIRED'; if (lc.includes('costs not found')) return 'USAGE_UNAVAILABLE'; if (lc.includes('project not found')) return 'PROJECT_NOT_FOUND'; if (lc.includes('not linked') || lc.includes('no project')) return 'NOT_LINKED'; @@ -163,9 +328,46 @@ function categorizeError(exitCode, stderr) { return `EXIT_${exitCode}`; } +export function mentionsObservabilityPlusNotEnabled(text) { + const value = String(text ?? '').toLowerCase(); + return ( + /observability plus[\s\S]{0,160}not enabled/.test(value) || + /observability plus[\s\S]{0,160}disabled/.test(value) || + /not enabled[\s\S]{0,160}observability plus/.test(value) || + /disabled[\s\S]{0,160}observability plus/.test(value) || + /(does\s+not|doesn't|do\s+not|don't|did\s+not|didn't)[\s\S]{0,80}(have\s+)?observability plus[\s\S]{0,80}enabled/.test(value) || + /(has|have)\s+not[\s\S]{0,80}enabled[\s\S]{0,80}observability plus/.test(value) || + /subscription to observability plus[\s\S]{0,160}required/.test(value) + ); +} + +export function classifyObservabilityPlusAccessText(text) { + const value = String(text ?? '').toLowerCase(); + if (!mentionsObservabilityPlusNotEnabled(value)) return null; + const projectScoped = + /project[\s\S]{0,160}(observability plus[\s\S]{0,160})?(not enabled|disabled)/.test(value) || + /project[\s\S]{0,160}(does\s+not|doesn't|do\s+not|don't|did\s+not|didn't|has\s+not|have\s+not)[\s\S]{0,160}observability plus[\s\S]{0,160}enabled/.test(value) || + /(not enabled|disabled)[\s\S]{0,160}(for|on)\s+(this\s+)?project/.test(value) || + /observability plus[\s\S]{0,160}(not enabled|disabled)[\s\S]{0,160}project/.test(value); + return projectScoped ? 'project_disabled' : 'oplus_not_enabled'; +} + // Schema is global per team — pass scope so we hit the right team rather than user's currentTeam. -export async function hasObservabilityPlus(scope) { +export async function probeObservabilityPlusSchema(scope) { const r = await runVercelJson(scopedArgs(['metrics', 'schema', '--format', 'json'], scope)); + if (r.ok) return { ok: true, access: true, data: r.data, code: null, source: 'metrics-schema' }; + const text = `${r.message ?? ''}\n${r.stderr ?? ''}`; + const blocker = classifyObservabilityPlusAccessText(text); + return { + ...r, + access: blocker ? false : null, + blocker: blocker ?? 'oplus_probe_failed', + source: 'metrics-schema', + }; +} + +export async function hasObservabilityPlus(scope) { + const r = await probeObservabilityPlusSchema(scope); return r.ok; } @@ -220,17 +422,16 @@ export function classifyObservabilityPlusConfiguration(result, { projectId } = { const code = String(result?.code ?? 'unknown').toLowerCase(); const text = `${result?.message ?? ''}\n${result?.stderr ?? ''}`.toLowerCase(); - const mentionsObservabilityPlusNotEnabled = - /observability plus[\s\S]{0,160}not enabled/.test(text) || - /not enabled[\s\S]{0,160}observability plus/.test(text) || - /subscription to observability plus[\s\S]{0,160}required/.test(text); - if (code === 'oplus_required' || ((code === 'not_found' || code === '404') && mentionsObservabilityPlusNotEnabled)) { + const accessBlocker = classifyObservabilityPlusAccessText(text); + if ((code === 'oplus_required' && accessBlocker) || ((code === 'not_found' || code === '404') && accessBlocker)) { return { ok: true, source, access: false, - blocker: 'no_oplus_probe', - detail: 'Route-level metrics are unavailable because Observability Plus is not enabled for this team.', + blocker: accessBlocker, + detail: accessBlocker === 'project_disabled' + ? 'The metrics API reported that Observability Plus is not enabled for this project.' + : 'The metrics API reported that Observability Plus is not enabled for the current Vercel scope.', }; } if (/forbidden|not_authorized|403/.test(code) || /forbidden|not authorized|permission|403/.test(text)) { @@ -269,6 +470,7 @@ export async function queryMetric(metricId, opts = {}) { if (opts.since) args.push('--since', opts.since); if (opts.until) args.push('--until', opts.until); if (opts.limit) args.push('--limit', String(opts.limit)); + if (opts.projectId) args.push('--project', opts.projectId); // 3-layer protection: semaphore (8 concurrent) + sliding-window (80/60s) + retryOnRateLimit (3× 60-90s jitter). payment_required is terminal. const throttle = getMetricThrottle(); @@ -506,12 +708,8 @@ async function pathExists(p) { try { await access(p); return true; } catch { return false; } } -// `--scope <teamId>` is buggy on several subcommands (silently falls back to currentTeam) — only pass slugs. function scopedArgs(args, scope) { if (!scope) return args; - if (typeof scope === 'string' && /^team_[A-Za-z0-9]+$/.test(scope)) { - return args; - } return [...args, '--scope', scope]; } diff --git a/skills/vercel-optimize/references/data-collection.md b/skills/vercel-optimize/references/data-collection.md index 8407c31..fff813e 100644 --- a/skills/vercel-optimize/references/data-collection.md +++ b/skills/vercel-optimize/references/data-collection.md @@ -14,7 +14,7 @@ All shapes here are covered by sanitized CLI fixtures in `packages/vercel-optimi ## The `signals.json` shape -`node scripts/collect-signals.mjs` emits the Vercel-side signal document. `node scripts/scan-codebase.mjs <repo-root>` emits the local codebase scan. `node scripts/merge-signals.mjs vercel-signals.json codebase.json --out signals.json` combines them into the artifact consumed by the gate, deep-dive, verifier, and renderer. The merge step also annotates scanner findings with route-level observability, `COLD-PATH`, or `NO-ROUTE-MAPPING`; scanner gates reject non-traffic-independent findings that do not carry one of those deterministic annotations. +`node scripts/collect-signals.mjs` emits the Vercel-side signal document. Check `scopeBlocker`, `frameworkSupportBlocker`, and `observabilityPlusBlocker` in that file before scanning source; unresolved project/team scope or metrics access must pause the workflow before scanner-only mode. `node scripts/scan-codebase.mjs <repo-root>` emits the local codebase scan. `node scripts/merge-signals.mjs vercel-signals.json codebase.json --out signals.json` combines them into the artifact consumed by the gate, deep-dive, verifier, and renderer. The merge step also annotates scanner findings with route-level observability, `COLD-PATH`, or `NO-ROUTE-MAPPING`; scanner gates reject non-traffic-independent findings that do not carry one of those deterministic annotations. The merged `signals.json` has this top-level shape: @@ -25,7 +25,21 @@ The merged `signals.json` has this top-level shape: "timeWindow": "14d", "projectId": "prj_xxx", "orgId": "team_xxx", - "projectIdSource": "repo.json" | "project.json" | "arg" | "env", + "projectIdSource": "repo.json" | "project.json", + "scopeResolution": { + "ok": true, + "projectId": "prj_xxx", + "orgId": "team_xxx", + "orgSlug": "team-slug-or-null", + "cliScope": "team-slug-used-for-cli-subcommands", + "projectName": "project-name-or-null", + "projectIdSource": "repo.json" | "project.json", + "inputProjectId": "optional-prj_xxx-from-argv-or-env", + "inputProjectIdSource": "arg" | "env" | null + }, + "scopeBlocker": null | "not_linked" | "ambiguous_project" | "project_link_mismatch" | "team_scope_conflict" | "team_scope_missing" | "team_scope_unresolved", + "scopeBlockerDetail": "...", + "scopeChoices": [ /* candidate linked projects shown to the user when scopeBlocker is set */ ], "frameworkSupport": { "ok": true, "status": "supported" | "limited" | "unsupported", @@ -39,7 +53,7 @@ The merged `signals.json` has this top-level shape: "observabilityPlus": true | false | null, "observabilityPlusPreflight": { /* CLI/API configuration probe result */ }, "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", + "observabilityPlusBlocker": null | "oplus_not_enabled" | "oplus_probe_failed" | "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": "..." }, "project": { /* /v9/projects/:id response, scoped to orgId via ?teamId */ }, @@ -57,20 +71,28 @@ All metric queries use the same `timeWindow` constant (`14d`) — defined as `TI Downstream consumers reference `signals.<field>` paths verbatim. Bumping `schemaVersion` is required when any consumed path is renamed or removed. +## Scope safety + +The skill must never infer a Vercel project by position. When `.vercel/repo.json` contains multiple projects, whether as an array or a directory-to-project map, collection stops with `scopeBlocker="ambiguous_project"` unless argv or `VERCEL_PROJECT_ID` exactly matches one linked project. If argv or `VERCEL_PROJECT_ID` names a different project than the linked cwd, collection stops with `scopeBlocker="project_link_mismatch"` because route-level metrics still depend on cwd project linkage. + +`VERCEL_ORG_ID` can confirm the linked team, but it cannot override the team in `.vercel/project.json` or `.vercel/repo.json`, and it cannot fill in a missing linked team. A mismatch stops collection with `scopeBlocker="team_scope_conflict"`; a link with no team stops with `scopeBlocker="team_scope_missing"`. + +For CLI commands that accept global `--scope`, the collector resolves the linked team ID to a team slug with `vercel teams list --format json`, then uses that slug for `vercel contract`, `vercel usage`, `vercel metrics schema`, and every `vercel metrics` query. Every route-level metric query also passes `--project <projectId>` so a wrong global `currentTeam` cannot silently select a different project. + ## Per-signal source matrix | Signal | CLI command | Required for | Fallback when missing | |---|---|---|---| | Auth | `vercel whoami` | Everything | Exit with "run `vercel login`" | | CLI version | `vercel --version` | Everything | Exit with "upgrade to v53+" — v53 is the skill's compatibility floor | -| Project ID + Org ID | `.vercel/repo.json` (newer) or `.vercel/project.json` (legacy) → `VERCEL_PROJECT_ID` + `VERCEL_ORG_ID` → argv | Everything | Exit with "run `vercel link` or pass projectId" | +| Project/team scope | `.vercel/repo.json` (newer, project array or map) or `.vercel/project.json` (legacy), optionally matched against argv or `VERCEL_PROJECT_ID`; `VERCEL_ORG_ID` may only confirm, not override or infer, the linked team | Everything | Emit `scopeBlocker` and stop before framework, usage, or metric collection | | Framework support | local `package.json` via `detectStack()` + `classifyFrameworkSupport()` | Code-backed route recommendations | Stop before metric fan-out on unsupported frameworks unless the user chooses `--continue-unsupported-framework` | -| 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 | +| Observability Plus configuration | Vercel CLI/API probe plus one metric access check | All `metrics.*` signals | Stop early when Vercel reports Observability Plus is unavailable for the current scope or disabled for this project | +| Observability Plus metrics access | One canary `vercel metrics vercel.request.count --project <projectId> --scope <teamSlug> --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` | -| 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 | +| Plan tier | `vercel contract --format json --scope <teamSlug>` → `inferPlan()` | Cost-context framing only | `plan="uncertain"`; cost magnitudes still computed from `usage.services[].billedCost` | +| Billing usage | `vercel usage --format json --scope <teamSlug> --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 | selected linked project's `rootDirectory` when present, otherwise cwd `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 | | `metrics.requestsByRouteCache` | `vercel metrics vercel.request.count --group-by route --group-by cache_result --since 14d` | `uncached_route`, traffic-total computation | `{ok:false}` | | `metrics.fnStatusByRoute` | `vercel metrics vercel.function_invocation.count --group-by route --group-by http_status --since 14d` | Canonical function-level 5xx source for `route_errors` and `slow_route` error disqualification | `{ok:false}`; fall back to `requestsByRouteStatus` only for older fixtures | @@ -103,8 +125,14 @@ Downstream consumers reference `signals.<field>` paths verbatim. Bumping `schema | Code | Meaning | Skill behavior | |---|---|---| +| `not_linked` | The cwd has no `.vercel/project.json` or `.vercel/repo.json`; a project ID alone is not enough for route metrics | Stop before framework, usage, or metric collection; ask the user to link the exact app directory with the target project and team | +| `ambiguous_project` | `.vercel/repo.json` contains multiple linked projects and no explicit project ID selected one | Stop before collection; show `scopeChoices` and ask which team/project to audit | +| `project_link_mismatch` | argv or `VERCEL_PROJECT_ID` does not match the project linked in this cwd | Stop before collection; ask the user to switch to the correct app directory or relink this directory | +| `team_scope_conflict` | `VERCEL_ORG_ID` conflicts with the team in the linked project file | Stop before collection; ask the user to unset the env var or relink/switch to the intended team | +| `team_scope_missing` / `team_scope_unresolved` | The skill cannot derive a safe CLI scope from the linked team; environment values are not enough when the link itself has no team | Stop before collection; ask the user to confirm the team slug or rerun `vercel link --team <team-id-or-slug>` | | `unsupported_framework` | Detected framework cannot reliably map Vercel route metrics back to source files | Stop before metric fan-out; ask whether to continue with a limited platform/scanner audit | -| `no_oplus_probe` | Observability Plus not enabled on team | Stop before full metric fan-out; ask whether to enable Observability Plus or run scanner-only | +| `oplus_not_enabled` | Vercel reported Observability Plus is not enabled for the current team/project scope | Stop before full metric fan-out; ask whether to enable Observability Plus or run scanner-only | +| `oplus_probe_failed` | The skill could not confirm route-level metric access from the current CLI/project context | Stop before full metric fan-out; ask the user to verify link/team/auth context or share `collect.stderr`; do not claim Observability Plus is disabled | | `project_disabled` | Observability Plus enabled for team but disabled for project | Stop before full metric fan-out; ask the user to enable Observability Plus for this project or continue scanner-only | | `daily_quota_exceeded` | Observability Plus query quota is exhausted for the day | Stop before full metric fan-out; tell the user to retry after the next UTC midnight reset or ask whether to continue scanner-only | | `USAGE_UNAVAILABLE` | `vercel usage` 404 — team has no Costs feature enabled | `usage=null`; cost-tier gates emit lower-priority candidates; billing section of the report shows "unavailable" | diff --git a/skills/vercel-optimize/references/doctrine.md b/skills/vercel-optimize/references/doctrine.md index 41e0a35..f2b46fc 100644 --- a/skills/vercel-optimize/references/doctrine.md +++ b/skills/vercel-optimize/references/doctrine.md @@ -12,7 +12,7 @@ The skill never reads a source file without an observability signal pointing at When `plan === 'enterprise'`, the gate run must surface these four checks before code-level recommendations. Field engineers confirm these are the highest-leverage account-level levers across every renewal audit: -1. **Observability Plus enabled?** From `signals.observabilityPlus`. If false, the whole audit degrades; surface as a top-of-report item. +1. **Project/team scope and per-route metrics usable?** From `signals.scopeBlocker`, `signals.observabilityPlusUsable`, and `signals.observabilityPlusBlocker`. If scope is unresolved, stop and ask for the exact team/project. If metrics are unusable, the whole audit degrades; surface the blocker as a top-of-report item without guessing the subscription state. 2. **Reverse proxy in front?** Heuristic from response headers / CNAME chain (when collected). A non-Vercel CDN over Vercel ISR is usually a "dumb pipe" — wasted spend. 3. **WAF rules enabled?** From `signals.project.security`. BotID + managed rules absent on a project with bot evidence is the most common cost spike. 4. **ISR read:write ratio.** From `metrics.isrReadsByRoute` + `metrics.isrWritesByRoute`. Include CDN-tier reads (see [data-collection.md](data-collection.md)) before flagging "writes > reads." diff --git a/skills/vercel-optimize/references/observability-plus.md b/skills/vercel-optimize/references/observability-plus.md index a069583..55ecfb5 100644 --- a/skills/vercel-optimize/references/observability-plus.md +++ b/skills/vercel-optimize/references/observability-plus.md @@ -1,6 +1,6 @@ # Observability Plus Stop-And-Ask -Use this file only when `signals.observabilityPlusBlocker` is set. Do not silently continue into scanner-only mode unless the user chooses that path. +Use this file only when `signals.observabilityPlusBlocker` is set. Do not silently continue into scanner-only mode unless the user chooses that path. Do not claim Observability Plus is disabled unless the blocker is `oplus_not_enabled` or the raw detail explicitly says the subscription is not enabled. ## Why This Check Exists @@ -33,7 +33,7 @@ This audit needs route-level metrics to rank fixes by observed latency, cache hi Docs: https://vercel.com/docs/observability/observability-plus Choose one: -1. Enable Observability Plus, then re-run the metric-backed audit. +1. Fix per-route metrics access, then re-run the metric-backed audit. 2. Continue in scanner-only mode for a limited audit. ``` @@ -41,11 +41,11 @@ If the host supports a structured question tool, use this exact customer-facing ```json { - "question": "Enable Observability Plus and re-run, or continue with a limited scanner-only audit?", - "header": "Observability Plus", + "question": "Fix per-route metrics access and re-run, or continue with a limited scanner-only audit?", + "header": "Metrics access", "options": [ { - "label": "Enable and re-run", + "label": "Fix and re-run", "description": "Use route-level metrics to rank the routes that matter most for cost and performance." }, { @@ -56,14 +56,14 @@ If the host supports a structured question tool, use this exact customer-facing } ``` -Use the full product name in this question. Do not abbreviate product names or metrics in customer-facing blocker copy. +Use the full product name when naming Observability Plus. Do not abbreviate product names or metrics in customer-facing blocker copy. ## After The User Chooses -If the user chooses **Enable and re-run**, stop after this short response: +If the user chooses **Fix and re-run**, stop after this short response: ```md -Enable Observability Plus from the Vercel dashboard's Observability tab, then tell me to rerun. I'll restart the metric-backed audit once route-level metrics are available. +Fix per-route metrics access, then tell me to rerun. I'll restart the metric-backed audit once route-level metrics are available. ``` Do not include raw team IDs, org IDs, project IDs, pricing language, dashboard screenshots, or extra persuasion. The docs link in the blocker message already covers availability and billing details. @@ -74,8 +74,10 @@ If the user chooses **Run scanner-only**, continue with the scanner-only steps b | Blocker | Detail | |---|---| +| `oplus_not_enabled` | `Detected: Vercel reported that Observability Plus is not enabled for the current team/project scope.` | +| `oplus_probe_failed` | `Detected: I could not confirm route-level metric access from the current CLI and project context.` | | `payment_required` | `Detected: route-level metrics were recognized for this team, but these metric queries are not usable.` | -| `no_oplus_probe` | `Detected: this team does not expose the route-level metrics this audit needs.` | +| `no_oplus_probe` | Legacy blocker from older skill versions. Treat as inconclusive unless the raw detail explicitly says Observability Plus is not enabled. Use `Detected: route-level metrics are unavailable from the current CLI and project context.` | | `not_linked` | `Detected: this app directory is not linked to a Vercel project.` | | `forbidden` | `Detected: the Vercel CLI is authenticated to a team that cannot read this project.` | | `project_not_found` | `Detected: the project ID is not visible to the authenticated team.` | @@ -94,6 +96,8 @@ For `forbidden` and `project_not_found`, ask the user to run `vercel switch <tea For `project_disabled`, do not present it as a team subscription problem. Ask the user to enable Observability Plus for this project, then re-run. +For `oplus_probe_failed` and legacy `no_oplus_probe`, do not present the blocker as a subscription problem. Say the probe was inconclusive, show `signals.observabilityPlusBlockerDetail`, and ask the user to verify the linked project/team context or share `$RUN_DIR/collect.stderr`. + For `no_traffic`, do not use this template. Tell the user the project has no meaningful traffic in the 14-day window, then ask whether to run scanner-only mode now or come back after traffic accumulates. ## Scanner-Only Mode diff --git a/skills/vercel-optimize/references/scoring.md b/skills/vercel-optimize/references/scoring.md index ebe2195..2622bf5 100644 --- a/skills/vercel-optimize/references/scoring.md +++ b/skills/vercel-optimize/references/scoring.md @@ -98,7 +98,7 @@ The agent renders this as the final output of Step 4. The shape is fixed; the co **Stack**: {framework}@{frameworkVersion} | {router} | {orm} **Plan**: {plan.plan} ({plan.reason}) **Period**: {usage.period.from} → {usage.period.to} -**Observability**: {observabilityPlus ? "Observability Plus enabled — per-route metrics included" : "Not enabled — analysis based on billing + scanner findings"} +**Observability**: {blocker-specific label, e.g. "Observability Plus enabled — per-route metrics included", "Project/team scope unresolved — analysis cannot use Vercel metrics", "Observability Plus not enabled — analysis based on billing + scanner findings", or "Per-route metrics probe failed — analysis based on billing + scanner findings"} ## Cost breakdown @@ -161,7 +161,7 @@ This section earns the user's trust. For every metric signal we considered but d ## Data gaps -(what we couldn't measure — Observability Plus disabled means no per-route latency, etc.) +(what we couldn't measure — missing or unavailable per-route metrics means no route-level latency/cache/cold-start ranking, etc.) ``` Common data gaps to call out when the underlying metric returned empty rows: diff --git a/skills/vercel-optimize/scripts/collect-signals.mjs b/skills/vercel-optimize/scripts/collect-signals.mjs index 64a40a3..a277875 100755 --- a/skills/vercel-optimize/scripts/collect-signals.mjs +++ b/skills/vercel-optimize/scripts/collect-signals.mjs @@ -7,7 +7,8 @@ import { checkCliVersion, checkAuth, resolveProjectId, - hasObservabilityPlus, + resolveTeamScope, + probeObservabilityPlusSchema, checkObservabilityPlusConfiguration, getMetricsSchema, getProjectConfig, @@ -18,9 +19,11 @@ import { queryMetric, detectStack, redactSensitiveText, + classifyObservabilityPlusAccessText, } from '../lib/vercel.mjs'; import { classifyFrameworkSupport } from '../lib/framework-support.mjs'; import { QUERIES, TIME_WINDOW, normalizerFor } from '../lib/queries.mjs'; +import { join } from 'node:path'; const SCHEMA_VERSION = '1.2'; @@ -66,17 +69,28 @@ async function main() { log('resolving project id…'); const project = await resolveProjectId(explicitProjectId); - if (!project) { - throw new Error( - 'NO_PROJECT_ID: pass one as argv, set VERCEL_PROJECT_ID, or run `vercel link` in this directory.' - ); + if (!project?.ok) { + log(`scope resolution blocked: ${project?.blocker ?? 'unknown'} (${project?.detail ?? 'no detail'})`); + writeOutput(scopeBlockedOutput(project), { usable: true, blocker: null, detail: 'Scope was not resolved.' }); + return; } log(`project link resolved (source=${project.source}; teamScope=${project.orgId ? 'yes' : 'no'})`); - const scope = project.orgId || undefined; + const teamScope = project.orgSlug + ? { ok: true, orgId: project.orgId, cliScope: project.orgSlug, source: 'link' } + : await resolveTeamScope(project.orgId); + if (!teamScope.ok) { + log(`team scope blocked: ${teamScope.blocker} (${teamScope.detail})`); + writeOutput(scopeBlockedOutput({ ...project, ...teamScope }), { usable: true, blocker: null, detail: 'Scope was not resolved.' }); + return; + } + const scope = teamScope.cliScope || project.orgId || undefined; + log(`team scope resolved (source=${teamScope.source})`); log('checking framework support…'); - const stack = await detectStack(); + const stackRoot = projectRootCwd(project); + const stack = await detectStack(stackRoot); + stack.rootDirectory = project.rootDirectory ?? null; const frameworkSupport = classifyFrameworkSupport(stack); log(`framework=${stack.framework}@${stack.frameworkVersion ?? '?'} support=${frameworkSupport.status}`); @@ -88,6 +102,7 @@ async function main() { projectId: project.projectId, orgId: project.orgId, projectIdSource: project.source, + ...scopeFields(project, teamScope), frameworkSupport, frameworkSupportBlocker: frameworkSupport.blocker, frameworkSupportDetail: frameworkSupport.detail, @@ -124,14 +139,18 @@ async function main() { }); log(`observabilityPlusPreflight=${observabilityPlusConfig.access === true ? 'enabled' : observabilityPlusConfig.blocker ?? 'unknown'} (${observabilityPlusConfig.source})`); - let oplus = observabilityPlusConfig.access === true; + let oplus = observabilityPlusConfig.access; + let schemaProbe = null; if (observabilityPlusConfig.access == null) { log('Observability Plus configuration preflight inconclusive; falling back to metrics schema probe…'); - oplus = await hasObservabilityPlus(scope); + schemaProbe = await probeObservabilityPlusSchema(scope); + oplus = schemaProbe.access === true ? true : schemaProbe.access === false ? false : null; } log(`observabilityPlus=${oplus}`); - const schema = oplus ? await getMetricsSchema(scope) : null; + const schema = oplus === true + ? (schemaProbe?.ok ? schemaProbe.data : await getMetricsSchema(scope)) + : null; if (oplus && schema) { const count = Array.isArray(schema) ? schema.length : (schema.metrics?.length ?? 0); log(`metric catalog: ${count} metrics available`); @@ -141,7 +160,7 @@ async function main() { // the orchestrator can ask the user immediately instead of waiting on billing. let metrics = {}; let metricsCanaryOk = false; - if (oplus) { + if (oplus === true) { log(`checking Observability Plus metrics access (window=${TIME_WINDOW})…`); const t0 = Date.now(); const canary = await queryMetric('vercel.request.count', { @@ -149,6 +168,7 @@ async function main() { since: TIME_WINDOW, limit: 1, scope, + projectId: project.projectId, }); metricsCanaryOk = !!canary?.ok; if (!metricsCanaryOk) { @@ -175,7 +195,7 @@ async function main() { } : (metricsCanaryOk ? { usable: true, blocker: null, detail: 'Observability Plus metrics access check passed.' } - : diagnoseObservabilityPlus(metrics, oplus)); + : diagnoseObservabilityPlus(metrics, schemaProbe ?? oplus)); if (!oplusDiag.usable && !continueWithoutObservability) { writeOutput({ @@ -185,6 +205,7 @@ async function main() { projectId: project.projectId, orgId: project.orgId, projectIdSource: project.source, + ...scopeFields(project, teamScope), observabilityPlus: oplus, observabilityPlusPreflight: observabilityPlusConfig, observabilityPlusUsable: oplusDiag.usable, @@ -203,7 +224,7 @@ async function main() { usageScope: null, usageTeamTotal: null, usageError: 'NOT_COLLECTED_OBSERVABILITY_BLOCKED', - stack: null, + stack, metrics, metricsSchema: schema, }, oplusDiag); @@ -229,7 +250,12 @@ async function main() { if (usageResult?.ok) { usage = usageResult.data; const contractContext = contract?.context; - if (usage?.context && contractContext && usage.context !== contractContext) { + const expectedContext = scope; + if (usage?.context && expectedContext && !sameContext(usage.context, expectedContext)) { + usageContextMismatch = true; + log(`usage: WARNING context mismatch — returned context=${usage.context} but resolved team scope=${expectedContext}; treating usage as unavailable for this project`); + usage = null; + } else if (usage?.context && contractContext && !sameContext(usage.context, contractContext)) { usageContextMismatch = true; log(`usage: WARNING context mismatch — returned context=${usage.context} but project team=${contractContext}; treating usage as unavailable for this project`); usage = null; @@ -262,10 +288,10 @@ async function main() { log(`stack: ${stack.framework}@${stack.frameworkVersion ?? '?'} ${stack.hasAppRouter ? 'app-router' : ''}${stack.hasPagesRouter ? ' pages-router' : ''}${stack.orm !== 'none' ? ` orm=${stack.orm}` : ''}`); // Each query is wrapped; one failure degrades only that metric. - if (oplus && metricsCanaryOk) { + if (oplus === true && metricsCanaryOk) { log(`querying observability metrics (${QUERIES.length} metrics in parallel)…`); const t0 = Date.now(); - metrics = await collectMetrics(scope); + metrics = await collectMetrics(scope, project.projectId); const wallMs = Date.now() - t0; const counts = Object.fromEntries( Object.entries(metrics).map(([k, v]) => { @@ -289,7 +315,7 @@ async function main() { blocker: observabilityPlusConfig.blocker, detail: observabilityPlusConfig.detail, } - : diagnoseObservabilityPlus(metrics, oplus); + : diagnoseObservabilityPlus(metrics, schemaProbe ?? oplus); const output = { @@ -299,6 +325,7 @@ async function main() { projectId: project.projectId, orgId: project.orgId, projectIdSource: project.source, + ...scopeFields(project, teamScope), observabilityPlus: oplus, observabilityPlusPreflight: observabilityPlusConfig, observabilityPlusUsable: oplusDiag.usable, @@ -324,7 +351,21 @@ async function main() { writeOutput(output, oplusDiag); } +function sameContext(a, b) { + return String(a ?? '').toLowerCase() === String(b ?? '').toLowerCase(); +} + +function projectRootCwd(project) { + const root = String(project?.rootDirectory ?? '').trim(); + if (!root || root === '.') return process.cwd(); + return join(process.cwd(), root); +} + function writeOutput(output, oplusDiag, frameworkSupport = output.frameworkSupport) { + if (output.scopeBlocker) { + log(`⚠ Vercel project/team scope is not confirmed: blocker=${output.scopeBlocker} (${output.scopeBlockerDetail})`); + log(' The orchestrator should PAUSE and ask the user to confirm the exact team and project before proceeding.'); + } if (frameworkSupport?.blocker) { log(`⚠ Framework is not supported for metric-backed route-to-file optimization: ${frameworkSupport.detail}`); log(' The orchestrator should PAUSE and ask whether to continue with a limited platform/scanner audit.'); @@ -338,7 +379,69 @@ function writeOutput(output, oplusDiag, frameworkSupport = output.frameworkSuppo log('done'); } -async function collectMetrics(scope) { +function scopeFields(project, teamScope) { + return { + scopeResolution: { + ok: true, + projectId: project.projectId, + orgId: project.orgId, + orgSlug: project.orgSlug ?? null, + cliScope: teamScope.cliScope ?? null, + projectName: project.name ?? null, + projectIdSource: project.source, + inputProjectId: project.inputProjectId ?? null, + inputProjectIdSource: project.inputProjectIdSource ?? null, + }, + scopeBlocker: null, + scopeBlockerDetail: null, + scopeChoices: project.choices ?? [], + }; +} + +function scopeBlockedOutput(resolution = {}) { + return { + schemaVersion: SCHEMA_VERSION, + collectedAt: new Date().toISOString(), + timeWindow: TIME_WINDOW, + projectId: resolution.projectId ?? null, + orgId: resolution.orgId ?? null, + projectIdSource: resolution.source ?? null, + scopeResolution: { + ok: false, + blocker: resolution.blocker ?? 'unknown', + detail: resolution.detail ?? 'Could not resolve Vercel project/team scope.', + inputProjectId: resolution.inputProjectId ?? resolution.projectId ?? null, + inputProjectIdSource: resolution.inputProjectIdSource ?? null, + linkedProjectCount: Array.isArray(resolution.choices) ? resolution.choices.length : 0, + }, + scopeBlocker: resolution.blocker ?? 'unknown', + scopeBlockerDetail: resolution.detail ?? 'Could not resolve Vercel project/team scope.', + scopeChoices: resolution.choices ?? [], + frameworkSupport: null, + frameworkSupportBlocker: null, + frameworkSupportDetail: null, + observabilityPlus: null, + observabilityPlusPreflight: null, + observabilityPlusUsable: null, + observabilityPlusBlocker: null, + observabilityPlusBlockerDetail: null, + plan: { + plan: 'uncertain', + reason: 'not collected before project/team scope confirmation', + }, + project: null, + contract: null, + usage: null, + usageScope: null, + usageTeamTotal: null, + usageError: 'NOT_COLLECTED_SCOPE_BLOCKED', + stack: null, + metrics: {}, + metricsSchema: null, + }; +} + +async function collectMetrics(scope, projectId) { const results = await Promise.all( QUERIES.map(async (entry) => { const r = await queryMetric(entry.metricId, { @@ -348,6 +451,7 @@ async function collectMetrics(scope) { since: TIME_WINDOW, limit: entry.limit, scope, + projectId, }); return [entry, r]; }) @@ -401,21 +505,38 @@ function sumUsageCosts(usage) { } // Returns { usable, blocker, detail }. `blocker` enum: -// null | 'no_oplus_probe' | 'project_disabled' | 'payment_required' | -// 'forbidden' | 'daily_quota_exceeded' | 'project_not_found' | -// 'not_linked' | 'all_failed_other' | 'no_traffic' +// null | 'oplus_not_enabled' | 'oplus_probe_failed' | +// 'project_disabled' | 'payment_required' | 'forbidden' | +// 'daily_quota_exceeded' | 'project_not_found' | 'not_linked' | +// 'all_failed_other' | 'no_traffic' export function diagnoseObservabilityPlus(metrics, oplusProbe) { - if (!oplusProbe) { + const probe = normalizeObservabilityProbe(oplusProbe); + if (!probe.confirmed) { + const accessBlocker = explicitAccessBlocker(probe.result); + if (accessBlocker) { + return { + usable: false, + blocker: accessBlocker, + detail: accessBlocker === 'project_disabled' + ? 'The metrics probe reported that Observability Plus is not enabled for this project.' + : 'The metrics probe reported that Observability Plus is not enabled for the current Vercel scope.', + }; + } + const code = probe.result?.code ? ` (code=${probe.result.code})` : ''; return { usable: false, - blocker: 'no_oplus_probe', - detail: 'vercel metrics schema returned non-OK; the team does not have Observability Plus enabled.', + blocker: 'oplus_probe_failed', + detail: `\`vercel metrics schema\` returned non-OK${code}. This does not prove Observability Plus is disabled; verify the linked project/team context and inspect collect.stderr.`, }; } const entries = Object.values(metrics); if (entries.length === 0) { - return { usable: false, blocker: 'no_oplus_probe', detail: 'No metrics were attempted.' }; + return { + usable: false, + blocker: 'oplus_probe_failed', + detail: 'No per-route metric queries were attempted. This is an internal collection gap, not evidence that Observability Plus is disabled.', + }; } const failures = entries.filter((m) => m && m.ok === false); @@ -441,14 +562,14 @@ export function diagnoseObservabilityPlus(metrics, oplusProbe) { .map((f) => `${f.message ?? ''}\n${f.stderr ?? ''}`) .join('\n') .toLowerCase(); - if ( - /subscription to observability plus[\s\S]{0,160}required/.test(text) || - /observability plus[\s\S]{0,160}not enabled/.test(text) - ) { + const accessBlocker = classifyObservabilityPlusAccessText(text); + if (accessBlocker) { return { usable: false, - blocker: 'no_oplus_probe', - detail: `${top[1]}/${entries.length} metric queries need route-level Observability Plus data. Enable Observability Plus, then re-run the metric-backed audit.`, + blocker: accessBlocker, + detail: accessBlocker === 'project_disabled' + ? `${top[1]}/${entries.length} metric queries reported that Observability Plus is not enabled for this project.` + : `${top[1]}/${entries.length} metric queries reported that Observability Plus is not enabled for the current Vercel scope.`, }; } return { @@ -499,6 +620,23 @@ export function diagnoseObservabilityPlus(metrics, oplusProbe) { return { usable: true, blocker: null, detail: 'Observability Plus is usable; queries returned data.' }; } +function normalizeObservabilityProbe(probe) { + if (probe === true) return { confirmed: true, result: null }; + if (probe && typeof probe === 'object') { + return { + confirmed: probe.access === true || probe.ok === true, + result: probe, + }; + } + return { confirmed: false, result: null }; +} + +function explicitAccessBlocker(result) { + if (result?.blocker === 'oplus_not_enabled' || result?.blocker === 'project_disabled') return result.blocker; + const text = `${result?.message ?? ''}\n${result?.stderr ?? ''}`; + return classifyObservabilityPlusAccessText(text); +} + // Run main() only as a CLI; the test suite imports diagnoseObservabilityPlus directly. import { fileURLToPath } from 'node:url'; import { realpathSync } from 'node:fs'; diff --git a/skills/vercel-optimize/scripts/deep-dive.mjs b/skills/vercel-optimize/scripts/deep-dive.mjs index 5af567a..2fa4229 100755 --- a/skills/vercel-optimize/scripts/deep-dive.mjs +++ b/skills/vercel-optimize/scripts/deep-dive.mjs @@ -4,7 +4,7 @@ // Byte-stable apart from totalWallMs; each CLI query is isolated. import { readFile } from 'node:fs/promises'; -import { queryMetric, readProjectJson } from '../lib/vercel.mjs'; +import { queryMetric, readLinkedProjects } from '../lib/vercel.mjs'; import { specsForCandidate, mergeIntoEvidence, SCANNER_KINDS, TIME_WINDOW } from '../lib/deep-dive.mjs'; const SCHEMA_VERSION = '1.0'; @@ -43,21 +43,24 @@ async function main() { log(`cwd: ${process.cwd()} (via --cwd)`); } - const link = await readProjectJson(process.cwd()); - if (!link) { + const linked = await readLinkedProjects(process.cwd()); + if (linked.projects.length === 0) { console.error(`[deep-dive] FATAL: cwd ${process.cwd()} has no .vercel/project.json or .vercel/repo.json.`); console.error(' Re-run with --cwd <project-dir> pointing at the linked project, or cd into it first.'); console.error(' (The Vercel CLI resolves team/project from cwd; without a .vercel/ linkage every query returns empty rows for the wrong team.)'); process.exit(2); } - if (merged.projectId && link.projectId !== merged.projectId) { - console.error('[deep-dive] FATAL: cwd .vercel/ links a different project than merged.json.'); + const link = merged.projectId + ? linked.projects.find((p) => p.projectId === merged.projectId) + : (linked.projects.length === 1 ? linked.projects[0] : null); + if (!link) { + console.error('[deep-dive] FATAL: cwd .vercel/ does not unambiguously link to the collected project in merged.json.'); console.error(' Re-run with --cwd <dir-linked-to-the-collected-project>.'); process.exit(2); } log(`cwd link OK (source ${link.source})`); - const scope = merged.orgId || undefined; + const scope = merged.scopeResolution?.cliScope || merged.orgId || undefined; const toLaunch = Array.isArray(gate.toLaunch) ? gate.toLaunch : []; const platform = Array.isArray(gate.platform) ? gate.platform : []; @@ -111,7 +114,7 @@ async function main() { // One CLI call per unique dedup key; jobs sharing a key share the result. const queryGroups = new Map(); for (const job of remainingJobs) { - const key = queryKey(job.spec, scope); + const key = queryKey(job.spec, scope, merged.projectId); if (!queryGroups.has(key)) { queryGroups.set(key, { spec: job.spec, jobs: [] }); } @@ -130,6 +133,7 @@ async function main() { since: spec.since, limit: spec.limit, scope, + projectId: merged.projectId, }); return { spec, jobs, response: r }; })); @@ -262,7 +266,7 @@ function tryExtractFromBroadPass(spec, merged) { // Two specs sharing this key answer the same question — one CLI call serves both. // Must include everything that affects the CLI's arg list. -function queryKey(spec, scope) { +function queryKey(spec, scope, projectId) { const groupBy = [...(spec.groupBy ?? [])].sort(); return JSON.stringify({ metricId: spec.metricId, @@ -272,6 +276,7 @@ function queryKey(spec, scope) { since: spec.since ?? null, limit: spec.limit ?? null, scope: scope ?? null, + projectId: projectId ?? null, }); } |
