summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Pham <john.pham@vercel.com>2026-05-22 10:24:06 -0700
committerJohn Pham <john.pham@vercel.com>2026-05-22 10:24:06 -0700
commitcb122aa341137e86eb79e568eedd1c07115ba5c3 (patch)
treeaad9ca2bb86053fd9264360d85405ca6a7145277
parentda22a4c9e85b3a3f6f4b4e8cd415016117643bb2 (diff)
fix: harden vercel optimize project scope preflightjohnphamous/vercel-optimize-project-scope-preflight
-rw-r--r--packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs181
-rw-r--r--packages/vercel-optimize-tests/test/collection-command-docs.test.mjs8
-rw-r--r--skills/vercel-optimize/SKILL.md14
-rw-r--r--skills/vercel-optimize/lib/vercel.mjs41
-rw-r--r--skills/vercel-optimize/references/data-collection.md12
-rw-r--r--skills/vercel-optimize/references/observability-plus.md2
-rwxr-xr-xskills/vercel-optimize/scripts/collect-signals.mjs59
7 files changed, 300 insertions, 17 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 acf3e23..a34ca21 100644
--- a/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs
+++ b/packages/vercel-optimize-tests/test/collect-framework-preflight.test.mjs
@@ -243,6 +243,85 @@ process.exit(66);
}
});
+test('collect-signals: stops on project/team mismatch before Observability Plus checks', async () => {
+ const scratch = await mkdtemp(join(tmpdir(), 'vo-project-scope-mismatch-'));
+ const bin = join(scratch, 'bin');
+ try {
+ await mkdir(bin, { recursive: true });
+ await mkdir(join(scratch, '.vercel'), { recursive: true });
+ await writeFile(join(scratch, 'package.json'), JSON.stringify({
+ dependencies: { next: '^15.3.0' },
+ }), 'utf-8');
+ await writeFile(join(scratch, '.vercel', 'project.json'), JSON.stringify({
+ projectId: 'prj_target',
+ orgId: 'team_wrong',
+ }), 'utf-8');
+ const fakeVercel = join(bin, 'vercel');
+ await writeFile(fakeVercel, `#!/usr/bin/env node
+const args = process.argv.slice(2);
+function json(value, code = 0) {
+ process.stdout.write(JSON.stringify(value, null, 2) + '\\n');
+ process.exit(code);
+}
+if (args[0] === '--version') {
+ process.stdout.write('54.1.0\\n');
+ process.exit(0);
+}
+if (args[0] === 'whoami' && args[1] === '--format') {
+ json({
+ username: 'test-user',
+ team: { id: 'team_other', slug: 'other-team', name: 'Other Team' },
+ });
+}
+if (args[0] === 'whoami') {
+ process.stdout.write('test-user\\n');
+ process.exit(0);
+}
+if (args[0] === 'api') {
+ const path = args[1];
+ if (path === '/v2/teams/team_wrong') {
+ json({ id: 'team_wrong', slug: 'wrong-team', billing: { plan: 'pro' } });
+ }
+ if (path === '/v9/projects/prj_target?teamId=team_wrong') {
+ json({ error: { code: 'PROJECT_NOT_FOUND', message: 'Project not found' } }, 1);
+ }
+ if (path.startsWith('/v1/observability/manage/configuration/projects')) {
+ process.stderr.write('observability should not be checked before project ownership is verified\\n');
+ process.exit(68);
+ }
+}
+if (args[0] === 'metrics' || args[0] === 'usage' || args[0] === 'contract') {
+ process.stderr.write('scoped collection should not run before project ownership is verified: ' + args.join(' ') + '\\n');
+ process.exit(69);
+}
+process.stderr.write('unexpected vercel call: ' + args.join(' ') + '\\n');
+process.exit(66);
+`, 'utf-8');
+ await chmod(fakeVercel, 0o755);
+
+ let err;
+ try {
+ await exec('node', [COLLECT], {
+ cwd: scratch,
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
+ maxBuffer: 8 * 1024 * 1024,
+ });
+ } catch (e) {
+ err = e;
+ }
+
+ assert.ok(err, 'collector should stop when the resolved team cannot read the project');
+ assert.equal(err.code, 1);
+ assert.equal(err.stdout, '');
+ assert.match(err.stderr, /PROJECT_SCOPE_MISMATCH/);
+ assert.doesNotMatch(err.stderr, /observability should not be checked/);
+ assert.doesNotMatch(err.stderr, /scoped collection should not run/);
+ assert.doesNotMatch(err.stderr, /Observability Plus is NOT usable/);
+ } finally {
+ await rm(scratch, { recursive: true, force: true });
+ }
+});
+
test('collect-signals: user-owned projects use username scope without teamId query params', async () => {
const scratch = await mkdtemp(join(tmpdir(), 'vo-user-scope-'));
const bin = join(scratch, 'bin');
@@ -452,3 +531,105 @@ process.exit(66);
await rm(scratch, { recursive: true, force: true });
}
});
+
+test('collect-signals: explicit projectId resolves matching owner from multi-project repo.json', async () => {
+ const scratch = await mkdtemp(join(tmpdir(), 'vo-explicit-repo-project-'));
+ const bin = join(scratch, 'bin');
+ try {
+ await mkdir(bin, { recursive: true });
+ await mkdir(join(scratch, '.vercel'), { recursive: true });
+ await writeFile(join(scratch, 'package.json'), JSON.stringify({
+ dependencies: { next: '^15.3.0' },
+ }), 'utf-8');
+ await writeFile(join(scratch, '.vercel', 'repo.json'), JSON.stringify({
+ projects: [
+ { id: 'prj_first', orgId: 'team_first' },
+ { id: 'prj_second', orgId: 'team_second' },
+ ],
+ }), 'utf-8');
+ const fakeVercel = join(bin, 'vercel');
+ await writeFile(fakeVercel, `#!/usr/bin/env node
+const args = process.argv.slice(2);
+function json(value, code = 0) {
+ process.stdout.write(JSON.stringify(value, null, 2) + '\\n');
+ process.exit(code);
+}
+function requireScope(expected) {
+ const i = args.indexOf('--scope');
+ if (i === -1 || args[i + 1] !== expected || args.includes('team_second')) {
+ process.stderr.write('missing expected scope ' + expected + ': ' + args.join(' ') + '\\n');
+ process.exit(67);
+ }
+}
+if (args[0] === '--version') {
+ process.stdout.write('54.1.0\\n');
+ process.exit(0);
+}
+if (args[0] === 'whoami' && args[1] === '--format') {
+ json({
+ username: 'test-user',
+ team: { id: 'team_first', slug: 'first-team', name: 'First Team' },
+ });
+}
+if (args[0] === 'whoami') {
+ process.stdout.write('test-user\\n');
+ process.exit(0);
+}
+if (args[0] === 'api') {
+ const path = args[1];
+ if (path === '/v2/teams/team_second') {
+ json({ id: 'team_second', slug: 'second-team', billing: { plan: 'pro' } });
+ }
+ if (path === '/v9/projects/prj_second?teamId=team_second') {
+ json({ id: 'prj_second', accountId: 'team_second', name: 'second-site' });
+ }
+ if (path.startsWith('/v1/observability/manage/configuration/projects')) {
+ json({ error: { code: 'not_found', message: 'Observability Plus is not enabled' } }, 1);
+ }
+}
+if (args[0] === 'contract') {
+ requireScope('second-team');
+ json({ context: 'second-team', commitments: [], totalCommitments: 0 });
+}
+if (args[0] === 'usage') {
+ requireScope('second-team');
+ json({
+ context: 'second-team',
+ groupBy: {
+ dimension: 'project',
+ data: [{
+ projectId: 'prj_second',
+ name: 'second-site',
+ services: [{ name: 'Function Invocations', billedCost: 2 }],
+ totals: { billedCost: 2 },
+ }],
+ },
+ services: [{ name: 'Function Invocations', billedCost: 2 }],
+ totals: { billedCost: 2 },
+ });
+}
+process.stderr.write('unexpected vercel call: ' + args.join(' ') + '\\n');
+process.exit(66);
+`, 'utf-8');
+ await chmod(fakeVercel, 0o755);
+
+ const { stdout, stderr } = await exec('node', [COLLECT, 'prj_second', '--continue-without-observability'], {
+ cwd: scratch,
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
+ maxBuffer: 8 * 1024 * 1024,
+ });
+ const out = JSON.parse(stdout);
+ assert.equal(out.projectId, 'prj_second');
+ assert.equal(out.orgId, 'team_second');
+ assert.equal(out.projectIdSource, 'arg+repo.json');
+ assert.equal(out.commandScope.cliScope, 'second-team');
+ assert.equal(out.commandScope.source, 'team-api');
+ assert.equal(out.project.accountId, 'team_second');
+ assert.equal(out.usageScope, 'project');
+ assert.equal(out.usage.project.projectId, 'prj_second');
+ assert.doesNotMatch(stderr, /unexpected vercel call/);
+ assert.doesNotMatch(stderr, /missing expected scope/);
+ } 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..a307df7 100644
--- a/packages/vercel-optimize-tests/test/collection-command-docs.test.mjs
+++ b/packages/vercel-optimize-tests/test/collection-command-docs.test.mjs
@@ -22,6 +22,14 @@ test('collection docs keep JSON stdout separate from status logs', async () => {
assert.match(skill, /Do not combine streams/);
});
+test('collection docs include an exact scope-confirmation prompt', async () => {
+ const skill = await readFile(join(ROOT, 'SKILL.md'), 'utf-8');
+ assert.match(skill, /Use this prompt for `PROJECT_SCOPE_UNRESOLVED`, `SCOPE_UNRESOLVED`, or `PROJECT_SCOPE_MISMATCH`/);
+ assert.match(skill, /I can't safely identify the Vercel project and account for this audit yet\./);
+ assert.match(skill, /Please confirm the Vercel project name or ID and the team slug\/name/);
+ assert.match(skill, /before checking metrics/);
+});
+
test('Observability Plus scanner-only instructions preserve separate stderr logs', async () => {
const reference = await readFile(join(ROOT, 'references', 'observability-plus.md'), 'utf-8');
assert.match(
diff --git a/skills/vercel-optimize/SKILL.md b/skills/vercel-optimize/SKILL.md
index 427a290..492652d 100644
--- a/skills/vercel-optimize/SKILL.md
+++ b/skills/vercel-optimize/SKILL.md
@@ -74,9 +74,17 @@ node scripts/merge-signals.mjs "$RUN_DIR/vercel-signals.json" "$RUN_DIR/codebase
Collection details, schemas, metric IDs, and degradation behavior live in [references/data-collection.md](references/data-collection.md). The metric registry is [lib/queries.mjs](lib/queries.mjs); keep all queries on the shared 14-day window.
-`collect-signals.mjs` resolves the linked project owner to `commandScope.cliScope`; downstream scripts reuse that scope for every Vercel CLI command that accepts `--scope`. Do not run `vercel usage`, `vercel metrics`, or `vercel contract` manually without the same scope; unscoped usage can report the user's personal organization while route metrics come from the team project.
+`collect-signals.mjs` resolves the linked project owner to `commandScope.cliScope` and verifies that the resolved account can read the resolved project before it checks Observability Plus. Downstream scripts reuse that scope for every Vercel CLI command that accepts `--scope`. Do not run `vercel usage`, `vercel metrics`, or `vercel contract` manually without the same scope; unscoped usage can report the user's personal organization while route metrics come from the team project.
-If project or scope resolution is ambiguous, stop and ask the user which Vercel project and team/personal scope they want audited. Do not infer the intended scope from the current `vercel whoami` team, and do not proceed with metrics, usage, or contract collection until the link or `VERCEL_PROJECT_ID` + `VERCEL_ORG_ID` identifies the intended account.
+If project or scope resolution is ambiguous, stop and ask the user which Vercel project and team/personal scope they want audited. Do not infer the intended scope from the current `vercel whoami` team, and do not proceed with metrics, usage, or contract collection until the link, an exact project match in `.vercel/repo.json`, or `VERCEL_PROJECT_ID` + `VERCEL_ORG_ID` identifies the intended account.
+
+Use this prompt for `PROJECT_SCOPE_UNRESOLVED`, `SCOPE_UNRESOLVED`, or `PROJECT_SCOPE_MISMATCH`:
+
+```text
+I can't safely identify the Vercel project and account for this audit yet.
+
+Please confirm the Vercel project name or ID and the team slug/name, or tell me it's under your personal account. Once confirmed, I'll relink or rerun collection against that exact scope before checking metrics.
+```
### 1.1 Stop on blockers
@@ -89,7 +97,7 @@ jq '{frameworkSupportBlocker, observabilityPlus, observabilityPlusUsable, observ
Required actions:
- `frameworkSupportBlocker === "unsupported_framework"`: use the unsupported-framework prompt above.
-- `PROJECT_SCOPE_UNRESOLVED` or `SCOPE_UNRESOLVED`: stop and ask which Vercel team/personal scope owns the project. For team projects, rerun after `vercel link --yes --project <project-name-or-id> --team <team-slug>`; for personal projects, rerun after linking under the intended user account or after setting both `VERCEL_PROJECT_ID` and `VERCEL_ORG_ID`.
+- `PROJECT_SCOPE_UNRESOLVED`, `SCOPE_UNRESOLVED`, or `PROJECT_SCOPE_MISMATCH`: stop and ask which Vercel project and team/personal scope the user wants audited. For team projects, rerun after `vercel link --yes --project <project-name-or-id> --team <team-slug>`; for personal projects, rerun after linking under the intended user account or after setting both `VERCEL_PROJECT_ID` and `VERCEL_ORG_ID`.
- `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.
diff --git a/skills/vercel-optimize/lib/vercel.mjs b/skills/vercel-optimize/lib/vercel.mjs
index 038fec1..9e19b75 100644
--- a/skills/vercel-optimize/lib/vercel.mjs
+++ b/skills/vercel-optimize/lib/vercel.mjs
@@ -78,22 +78,55 @@ export async function readProjectJson(cwd = process.cwd()) {
// Does NOT auto-run `vercel link` — interactive surprises bad.
export async function resolveProjectId(explicit, cwd = process.cwd()) {
if (explicit) {
+ const linked = process.env.VERCEL_ORG_ID
+ ? null
+ : await readLinkedOwnerForProjectId(explicit, cwd);
return {
projectId: explicit,
- orgId: process.env.VERCEL_ORG_ID || null,
- source: 'arg',
+ orgId: process.env.VERCEL_ORG_ID || linked?.orgId || null,
+ source: linked?.source ? `arg+${linked.source}` : 'arg',
};
}
if (process.env.VERCEL_PROJECT_ID) {
+ const linked = process.env.VERCEL_ORG_ID
+ ? null
+ : await readLinkedOwnerForProjectId(process.env.VERCEL_PROJECT_ID, cwd);
return {
projectId: process.env.VERCEL_PROJECT_ID,
- orgId: process.env.VERCEL_ORG_ID || null,
- source: 'env',
+ orgId: process.env.VERCEL_ORG_ID || linked?.orgId || null,
+ source: linked?.source ? `env+${linked.source}` : 'env',
};
}
return await readProjectJson(cwd);
}
+async function readLinkedOwnerForProjectId(projectId, cwd = process.cwd()) {
+ try {
+ const raw = await readFile(join(cwd, '.vercel', 'repo.json'), 'utf-8');
+ const parsed = JSON.parse(raw);
+ const matches = (Array.isArray(parsed?.projects) ? parsed.projects : [])
+ .filter((p) => p?.id && String(p.id) === String(projectId));
+ if (matches.length > 1) {
+ throw new Error('AMBIGUOUS_PROJECT_LINK: `.vercel/repo.json` contains multiple entries for the requested projectId. Ask the user to confirm the intended Vercel team/personal scope.');
+ }
+ const match = matches[0];
+ if (match?.orgId) return { orgId: match.orgId, source: 'repo.json' };
+ } catch (err) {
+ if (err?.message?.startsWith('AMBIGUOUS_PROJECT_LINK:')) throw err;
+ /* fall through */
+ }
+
+ try {
+ const raw = await readFile(join(cwd, '.vercel', 'project.json'), 'utf-8');
+ const parsed = JSON.parse(raw);
+ if (String(parsed?.projectId ?? '') === String(projectId) && parsed?.orgId) {
+ return { orgId: parsed.orgId, source: 'project.json' };
+ }
+ } catch { /* fall through */ }
+
+ return null;
+}
+
export async function resolveCommandScope(project = {}) {
const orgId = project?.orgId ?? null;
diff --git a/skills/vercel-optimize/references/data-collection.md b/skills/vercel-optimize/references/data-collection.md
index a40eca0..140c787 100644
--- a/skills/vercel-optimize/references/data-collection.md
+++ b/skills/vercel-optimize/references/data-collection.md
@@ -25,7 +25,7 @@ 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" | "arg" | "env" | "arg+repo.json" | "arg+project.json" | "env+repo.json" | "env+project.json",
"commandScope": {
"ok": true,
"cliScope": "team-slug-or-username",
@@ -72,12 +72,13 @@ Downstream consumers reference `signals.<field>` paths verbatim. Bumping `schema
|---|---|---|---|
| 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". Multi-project `repo.json` or project ID without owner account scope is ambiguous; ask the user to clarify the intended project/account |
+| Project ID + Org ID | `.vercel/repo.json` (newer) or `.vercel/project.json` (legacy) → `VERCEL_PROJECT_ID` + `VERCEL_ORG_ID` → argv. When the user passes a project ID and multi-project `repo.json` contains exactly one matching entry, the collector uses that entry's owner account. | Everything | Exit with "run `vercel link` or pass projectId". Multi-project `repo.json` without an explicit matching project ID, or any project ID without owner account scope, is ambiguous; ask the user to clarify the intended project/account |
| 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` |
| CLI command scope | `vercel whoami --format json`, then `vercel api /v2/teams/:orgId` when a linked `team_...` ID must be converted to a slug | Keeps `vercel metrics`, `vercel usage`, and `vercel contract` on the linked project's account instead of the user's current/personal scope | `PROJECT_SCOPE_UNRESOLVED` or `SCOPE_UNRESOLVED`; stop and ask the user to clarify the intended project/account, then re-link under the intended team or personal account |
+| Project/scope verification | `vercel api /v9/projects/:id?teamId=<orgId>` for team-owned projects; omit `teamId` for `usr_...` user-owned projects | Proves the resolved account can read the resolved project before Observability Plus or billing conclusions | `PROJECT_SCOPE_MISMATCH`; stop and ask the user to confirm the exact project and team/personal scope. Do not report Observability Plus as missing until this check passes |
| Observability Plus configuration | Vercel CLI/API probe plus one metric access check; user-owned projects skip the team configuration endpoint and rely on the scoped metrics probe | All `metrics.*` signals | Stop early when the account lacks Observability Plus or this project is disabled |
-| Observability Plus metrics access | One canary `vercel metrics vercel.request.count --since 14d --limit 1`, then full fan-out only if it succeeds | All `metrics.*` signals | Set `observabilityPlusUsable=false` with blocker detail; emit a minimal blocker document before slower project config / usage collection unless `--continue-without-observability` is passed |
-| Project config | `vercel api /v9/projects/:id?teamId=<orgId>` for team-owned projects; omit `teamId` for `usr_...` user-owned projects | Fluid Compute, BotID, Speed Insights, security flags | `{error: "..."}` placeholder; gates that need it skip |
+| 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 blocker document after project/scope verification but before billing collection unless `--continue-without-observability` is passed |
+| Project config | Verified project API response from project/scope verification | Fluid Compute, BotID, Speed Insights, security flags | Stop on ownership mismatch; otherwise gates that need missing optional fields skip |
| Plan tier | `vercel api /v2/teams/:orgId` (or `/v2/user` for user-owned projects) → `billing.plan`, then scoped `vercel contract --format json` fallback → `inferPlan()` | Cost-context framing only | `plan="uncertain"`; cost magnitudes still computed from `usage.services[].billedCost` |
| Billing usage | Scoped `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 when queried and unavailable; `NOT_COLLECTED_*` when a preflight stop happened before billing collection |
| Stack | local `package.json` + dir scan | Version-aware citation filtering, scanner gating | "unknown" framework → all framework-specific citations filtered |
@@ -114,8 +115,9 @@ Downstream consumers reference `signals.<field>` paths verbatim. Bumping `schema
| Code | Meaning | Skill behavior |
|---|---|---|
| `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 |
-| `PROJECT_SCOPE_UNRESOLVED` | The project was found without an owner account, or `.vercel/repo.json` contains multiple linked projects | Stop before `vercel metrics`, `vercel usage`, or `vercel contract`; ask the user which Vercel project and team/personal scope to audit |
+| `PROJECT_SCOPE_UNRESOLVED` | The project was found without an owner account, or `.vercel/repo.json` contains multiple linked projects and no explicit matching project ID was supplied | Stop before `vercel metrics`, `vercel usage`, or `vercel contract`; ask the user which Vercel project and team/personal scope to audit |
| `SCOPE_UNRESOLVED` | The linked project belongs to a specific team/user, but the collector could not resolve a CLI-safe `--scope` value | Stop before `vercel metrics`, `vercel usage`, or `vercel contract`; ask the user to switch/re-link with the correct team |
+| `PROJECT_SCOPE_MISMATCH` | The resolved team/personal account cannot read the resolved project, or the project API returns a different owner/project | Stop before Observability Plus, metrics, usage, or contract checks; ask the user to confirm the exact Vercel project and team/personal scope |
| `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 |
| `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 |
diff --git a/skills/vercel-optimize/references/observability-plus.md b/skills/vercel-optimize/references/observability-plus.md
index a069583..908ca8c 100644
--- a/skills/vercel-optimize/references/observability-plus.md
+++ b/skills/vercel-optimize/references/observability-plus.md
@@ -90,7 +90,7 @@ vercel link --yes --project <project-name-or-id> --cwd <app-dir>
Add `--team <team-id-or-slug>` when the team is known. If the user supplied both app path and project name, run the link command instead of asking them what to do.
-For `forbidden` and `project_not_found`, ask the user to run `vercel switch <team>` or verify the project ID before presenting the Observability Plus choice.
+For `forbidden` and `project_not_found`, ask the user to confirm the exact Vercel project and team/personal scope before presenting the Observability Plus choice.
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.
diff --git a/skills/vercel-optimize/scripts/collect-signals.mjs b/skills/vercel-optimize/scripts/collect-signals.mjs
index f5ae245..2831fb9 100755
--- a/skills/vercel-optimize/scripts/collect-signals.mjs
+++ b/skills/vercel-optimize/scripts/collect-signals.mjs
@@ -130,6 +130,14 @@ async function main() {
const scope = commandScope.cliScope || undefined;
log(`command scope resolved (source=${commandScope.source}; scoped=${scope ? 'yes' : 'no'})`);
+ log('validating linked project belongs to the resolved scope…');
+ const projectCfg = await getProjectConfig(project.projectId, project.orgId);
+ const projectScope = validateProjectScope(projectCfg, project);
+ if (!projectScope.ok) {
+ throw new Error(`PROJECT_SCOPE_MISMATCH: ${projectScope.detail} Ask the user to confirm the exact Vercel project and team/personal scope, then rerun after \`vercel link --yes --project <project-name-or-id> --team <team-slug>\` or after setting both VERCEL_PROJECT_ID and VERCEL_ORG_ID for the intended scope.`);
+ }
+ log(`project scope verified (source=${projectScope.source})`);
+
log('checking Observability Plus configuration…');
const observabilityPlusConfig = await checkObservabilityPlusConfiguration({
orgId: project.orgId,
@@ -211,7 +219,7 @@ async function main() {
plan: 'uncertain',
reason: 'not collected before Observability Plus blocker confirmation',
},
- project: null,
+ project: projectCfg,
contract: null,
usage: null,
usageScope: null,
@@ -228,9 +236,8 @@ async function main() {
log('continuing after Observability Plus blocker because --continue-without-observability was set');
}
- log('pulling project config + account plan + contract + usage in parallel…');
- const [projectCfg, accountPlan, contract, usageResult] = await Promise.all([
- getProjectConfig(project.projectId, project.orgId),
+ log('pulling account plan + contract + usage in parallel…');
+ const [accountPlan, contract, usageResult] = await Promise.all([
getAccountPlan(project.orgId || scope),
getContract(scope),
getUsage({ days: 14, scope }),
@@ -353,6 +360,50 @@ function writeOutput(output, oplusDiag, frameworkSupport = output.frameworkSuppo
log('done');
}
+function validateProjectScope(projectCfg, project) {
+ if (!projectCfg || projectCfg.error) {
+ return {
+ ok: false,
+ source: 'project-api',
+ detail: `The resolved account could not read the resolved project (project API error=${projectCfg?.error ?? 'unknown'}).`,
+ };
+ }
+
+ if (projectCfg.id && String(projectCfg.id) !== String(project.projectId)) {
+ return {
+ ok: false,
+ source: 'project-api',
+ detail: 'The project API returned a different project than the collector resolved from the link or environment.',
+ };
+ }
+
+ const ownerId = firstString(
+ projectCfg.accountId,
+ projectCfg.orgId,
+ projectCfg.ownerId,
+ projectCfg.teamId,
+ projectCfg.team?.id,
+ projectCfg.account?.id,
+ projectCfg.owner?.id,
+ );
+ if (ownerId && project.orgId && String(ownerId) !== String(project.orgId)) {
+ return {
+ ok: false,
+ source: 'project-api',
+ detail: 'The project API returned an owner account that differs from the collector-resolved account.',
+ };
+ }
+
+ return {
+ ok: true,
+ source: ownerId ? 'project-api-owner' : 'project-api-readable',
+ };
+}
+
+function firstString(...values) {
+ return values.find((value) => typeof value === 'string' && value.trim() !== '') ?? null;
+}
+
async function collectMetrics(scope) {
const results = await Promise.all(
QUERIES.map(async (entry) => {