Repository navigation
feat(detect): the detection scripts and the report (FIX-1159, sub-PR a) - #1355
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub. 3 Skipped Deployments
|
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_012f33ba-bced-481e-bbcb-59323333cb48) |
| } | ||
|
|
||
| /** A settings object literal's value for `key`, as raw source text, or `null` when it is not assigned. */ | ||
| function rawSettingValue(source, key) { |
There was a problem hiding this comment.
This bracket/quote walker is duplicated almost verbatim in fsdev-config.mjs (rawFlowsValue + splitTopLevel). Consider extracting an internal source-parse.mjs with rawAssignmentValue(source, key) and splitTopLevelCommas(text) — single place for parser fixes, ~80–100 LOC saved, no behavior change.
| const chosen = | ||
| entries.find(([name]) => name === "dev") ?? | ||
| (starters.length === 1 ? starters[0] : null) ?? | ||
| (starters.length > 1 ? null : null); |
There was a problem hiding this comment.
Dead ternary: both branches return null. Reads like an unfinished "multiple starter scripts → refuse" branch. Either implement that refusal or drop the third operand — leaving it suggests the dev-command logic wasn't fully reviewed.
| } | ||
|
|
||
| /** Directory entries used by the workspace-container check — exported so the report can name them. */ | ||
| export { listDir }; |
There was a problem hiding this comment.
Dead re-export — comment says "exported so the report can name them" but report.mjs uses childProjects from roots.mjs. Drop this export (and the comment) unless something in sub-PR c actually imports it.
| * > **Every refusal is decided from state the run has not modified.** | ||
| * > Nothing is written until every refusal condition has been evaluated and none fired. | ||
| * | ||
| * That invariant is why detection is a separate artifact at all. Three separate defects have been |
There was a problem hiding this comment.
This header (and similar ones in secrets.mjs, roots.mjs) repeats review-round history that detect/README.md already documents. For maintainability, I'd keep the read-only invariant + resolution numbering here and move the "ten findings across four review rounds" narrative to the README only. Lower priority than parser dedup, but it adds ~25–40% comment density in production files.
| * Parse an env file the way our CLI's `parseEnvFile` does — including its tie-break, where a | ||
| * later line overwrites an earlier one for the same key. | ||
| */ | ||
| export function parseEnvFile(content) { |
There was a problem hiding this comment.
parseEnvFile is documented as mirroring packages/cli/src/load-env.ts but isn't covered by twins.test.mjs (unlike CONFIG_FILENAMES, NEXT_MINIMUM_MAJOR, NODE_FLOOR). This is the twin I'd extend next — env parsing drift is load-bearing for both the masking report and the git-tracked refusal tests.
| import { describe, expect, it } from "vitest"; | ||
| import { readFileSync } from "node:fs"; | ||
| import { join } from "node:path"; | ||
| import { |
There was a problem hiding this comment.
Worth extending beyond the three constants pinned today. Candidates in priority order: parseEnvFile semantics vs load-env.ts, NEXT_DEV_ENV_FILES order vs @next/env, displayPath vs load-config.ts:62-65. Optional: export parseEnvFile from CLI as a documented contract (still not imported at plugin runtime) so twins parse one source.
There was a problem hiding this comment.
Skipping — already applied. twins.test.mjs already extracts the CLI parser and the Next range; this revision only flipped the single-quote expansion expectation to match @next/env.
| } | ||
|
|
||
| /** Is this path a directory? */ | ||
| export function isDirectory(path) { |
There was a problem hiding this comment.
isDirectory is exported but never imported anywhere in this PR. Same for nextConfigDirOf in next-project.mjs. Trim unused exports before sub-PR c — they widen the accidental public surface.
|
|
||
| // --- Resolutions 1 and 2: the roots ---------------------------------------------------------- | ||
| const workspace = resolveWorkspaceRoot(writeRoot); | ||
| const repository = repositoryRoot(writeRoot); |
There was a problem hiding this comment.
repositoryRoot(writeRoot) runs here and again inside resolveWorkspaceRoot (roots.mjs:47). Minor for a one-shot CLI, but if you're touching orchestration anyway, compute once and pass through — same applies to repeated readManifest(writeRoot) calls across host/PM/module paths.
There was a problem hiding this comment.
Skipping — still the agreed one-shot path. Detection is a single report; caching repositoryRoot is not worth a second contract. Not reopening.
| const vars = parseEnvFile(content); | ||
| if (!vars.has(key)) continue; | ||
| return { status: statusOf(vars.get(key)), from: "an env file", path }; |
There was a problem hiding this comment.
Next dotenv syntax is misparsed
When a Next project declares FSD_DEMO_TOKEN using accepted dotenv syntax such as export FSD_DEMO_TOKEN=existing-token, this parser reports the token absent and directs the installer to generate another token in .env.local, while Next continues using the higher-precedence existing token and rejects requests carrying the generated one.
| @@ -0,0 +1,5 @@ | |||
| --- | |||
| "@flow-state-dev/fsdev": patch | |||
There was a problem hiding this comment.
Internal change triggers package release
This fragment requests a patch release of @flow-state-dev/fsdev even though its own description says the scripts live outside published packages and do not change a public API. Internal-only work should omit the changeset or use an empty fragment to avoid an unnecessary package version and release note.
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| } else if (host.value === "unknown") { | ||
| refusals.push( | ||
| refusal("host-unknown", "I can't tell what kind of project this is.", "Nothing was written."), | ||
| ); |
There was a problem hiding this comment.
Grok / simplify — should-fix (dead branch): classifyHost only ever returns node | next | next-unsupported (see next-project.mjs). This unknown / host-unknown arm is unreachable.
Delete it rather than keeping a fourth host shape “just in case” — a dead refusal path is how a future reader invents a real unknown return to make the branch make sense.
| /** A settings object literal's value for `key`, as raw source text, or `null` when it is not assigned. */ | ||
| function rawSettingValue(source, key) { | ||
| const pattern = new RegExp(`(^|[\\s{,])${key}\\s*:\\s*`, "m"); | ||
| const match = pattern.exec(source); | ||
| if (match === null) return null; | ||
| const start = match.index + match[0].length; | ||
| // Walk to the end of the value: balanced brackets, then a comma or a closing brace at depth 0. | ||
| let depth = 0; | ||
| let quote = null; | ||
| for (let i = start; i < source.length; i++) { | ||
| const ch = source[i]; | ||
| if (quote !== null) { | ||
| if (ch === "\\") i++; | ||
| else if (ch === quote) quote = null; | ||
| continue; | ||
| } | ||
| if (ch === '"' || ch === "'" || ch === "`") { | ||
| quote = ch; | ||
| continue; | ||
| } | ||
| if (ch === "[" || ch === "{" || ch === "(") depth++; | ||
| else if (ch === "]" || ch === "}" || ch === ")") { | ||
| if (depth === 0) return source.slice(start, i).trim(); | ||
| depth--; | ||
| } else if (ch === "," && depth === 0) return source.slice(start, i).trim(); | ||
| } | ||
| return source.slice(start).trim(); | ||
| } |
There was a problem hiding this comment.
Grok / simplify — should-fix (internal duplication): this quote/depth walker is the same algorithm as rawFlowsValue in fsdev-config.mjs (key match differs; EOF handling differs slightly — trailing slice vs null).
One shared rawPropertyValue(source, key, { unterminated }) in fs-util.mjs (or a tiny static-js.mjs) would cut ~25 lines and stop the two copies drifting. Do not reach for Acorn/@babel/parser here — zero-deps + static-only refusal is the right constraint.
| /** Everything under `dir` that could be a `next.config` — used only to report what was considered. */ | ||
| export function nextConfigDirOf(configPath) { | ||
| return configPath === null ? null : dirname(configPath); | ||
| } | ||
|
|
||
| /** Every dependency of ours the write root already declares, at the version it declares. */ | ||
| export function declaredFsdDependencies(writeRoot) { | ||
| const manifest = readManifest(writeRoot); | ||
| const all = { ...(manifest?.dependencies ?? {}), ...(manifest?.devDependencies ?? {}) }; | ||
| const found = {}; | ||
| for (const [name, range] of Object.entries(all)) { | ||
| if (name.startsWith("@flow-state-dev/")) found[name] = range; | ||
| } | ||
| return found; | ||
| } | ||
|
|
||
| /** The module system the nearest manifest declares — `module`, `commonjs`, or absent. */ | ||
| export function moduleSystemOf(writeRoot) { | ||
| const type = readManifest(writeRoot)?.type; | ||
| return type === "module" || type === "commonjs" ? type : "absent"; | ||
| } | ||
|
|
||
| /** Directory entries used by the workspace-container check — exported so the report can name them. */ | ||
| export { listDir }; |
There was a problem hiding this comment.
Grok / simplify — should-fix (dead exports):
nextConfigDirOfis exported and never imported.export { listDir }is unused; callers already takelistDirfromfs-util.mjs.
Also: the resolveDevCommand chosen ternary at ~276–279 has (starters.length > 1 ? null : null) which is always null, and chosen === undefined after ?? is unreachable. Simplify to:
const chosen =
entries.find(([name]) => name === "dev") ??
(starters.length === 1 ? starters[0] : null);
if (chosen === null) return { script: null, command: null, port: null, url: null };| /** | ||
| * Resolutions 9 and 10 — what each secret variable **resolves to**, per runtime, and which files | ||
| * are therefore about to hold a secret. | ||
| * | ||
| * Not a walk over `.env.local`. Two loaders read these files with different search rules and two | ||
| * different tie-breaks, and asking the filesystem a question only a loader can answer is what | ||
| * produced every defect in this area: | ||
| * | ||
| * - **our CLI** (`loadEnvFiles`) walks from the write root **upward**; the first file that assigns | ||
| * a key wins, and within that file the **last** assignment wins. Inherited `process.env` beats | ||
| * every file. | ||
| * - **`next dev`** (`@next/env`'s `loadEnvConfig`) reads **one directory** — no walk — in the | ||
| * order `.env.development.local`, `.env.local`, `.env.development`, `.env`. Inherited | ||
| * `process.env` beats every file here too. | ||
| * | ||
| * So nearest-wins across files and last-wins inside a file are opposite directions, and the two | ||
| * runtimes disagree about an ancestor's value on purpose. A files-only scan reports `absent` for | ||
| * an exported variable, and reports `absent` for a token sitting in `.env.development.local` — | ||
| * then a fresh one gets generated that Next will ignore, and every request carrying it 401s with | ||
| * nothing to explain why. | ||
| * | ||
| * **No secret value ever leaves this module.** Every answer is `absent` / `empty` / `non-empty` | ||
| * plus the path that decided it. The report is JSON an assistant reads, so anything in it is in a | ||
| * retained transcript — which is the same hazard the run refuses to create by asking for a key. | ||
| * That covers the provider key the developer already had just as much as the token we generate; | ||
| * a rule scoped to the secret we authored would leak the one we did not. |
There was a problem hiding this comment.
Grok / simplify — nit (prose overshoot): this ~26-line module essay (and similar headers on report.mjs / next-project.mjs / roots.mjs) restates the README’s design thesis. The dual-loader fidelity is load-bearing — keep the short “CLI walks up / next-dev is one directory / opposite tie-breaks” contract — but the defect-history paragraphs belong in the README or the PR, not every leaf file.
Same overshoot pattern as the next-steps block PR: mechanism right, commentary volume high. Trim to one contract paragraph per module; leave long rationale only where a future edit would otherwise “simplify” the wrong thing (e.g. averaging the two secret answers).
There was a problem hiding this comment.
Skipping — already trimmed in the Aug 20–21 pass. Leaving the remaining header. Out of scope for this revision.
| return [...files.values()].map((entry) => ({ | ||
| ...entry, | ||
| exists: existsSync(entry.path), | ||
| tracked: isTrackedByGit(entry.path), | ||
| ignored: isIgnoredByGit(entry.path), |
There was a problem hiding this comment.
Grok / simplify — should-discuss (maybe dead work): every secret file pays for both isTrackedByGit and isIgnoredByGit, but report.mjs only refuses on tracked, and render.mjs never mentions ignored. Cost is tiny (one-shot path), so this is not a perf issue.
If sub-PR c’s skill contract needs ignored in the JSON, keep it and say so in a one-line comment. If not, drop the check-ignore call — otherwise the field looks load-bearing when nothing consumes it yet.
There was a problem hiding this comment.
second-look — retrospective approach review of this PR (report only where noted; individual points below are left as inline comments for the implementer to triage, not blocking).
Verdict: appropriately scoped overall, with two small cleanup items. This is a large diff (3006 lines added, 0 removed, 21 files) but it maps closely to the approved spec's 10 numbered resolutions plus their tests, and the "nothing here writes" / "every fact is somebody else's resolution" invariants are followed consistently rather than partially. I did not re-open the scripts-vs-subcommand or library-vs-plugin decisions — those are settled in the spec's §6 and this PR's own review note says to review the code against that direction, not the direction itself.
Two inline comments below (duplicate parsing logic, dead/unused code) are second-look findings — a leaner shape exists and the loss is small. One is a drive-by nit, not a finding.
I did not find a materially different or smaller approach to the detection module itself: the ten resolutions each answer a question that genuinely needs a different algorithm (workspace discovery vs. Next's findDir vs. the CLI's config precedence vs. two independent env-loader search orders), so collapsing them would mean re-deriving one from another — which is exactly the anti-pattern the module's own doc comments call out as the repeated defect in this area.
Generated by Claude Code
| } | ||
|
|
||
| /** The `flows:` value in a config, as raw source, or `null` when it is not statically assigned. */ | ||
| function rawFlowsValue(source) { |
There was a problem hiding this comment.
second-look — duplicate logic (architecture). rawFlowsValue here and rawSettingValue in next-project.mjs (lines 65-91) are the same balanced-bracket/quote scanner: find the text after a key\s*:\s* match, walk forward tracking quote/bracket depth, and stop at the first depth-0 comma or closing delimiter. They differ only in what happens when the source ends before a delimiter — this one returns null; rawSettingValue returns the trailing text instead. That difference doesn't actually change behavior today: an unterminated pageExtensions/basePath value fails plainStringArray/plainString's literal check anyway and ends up null (unreadable) either way, so the two functions are behaviorally equivalent on every real input.
Recommend pulling the walk into one shared helper in fs-util.mjs (e.g. extractBalancedValue(source, key), returning null on an unterminated value) and having both modules call it. Rough net: −52 / +29 lines, and it removes a second copy of hand-rolled parsing that a future change (e.g. widening what resolution 8b reads) would otherwise have to remember to fix twice. This is also the repo's own stated convention — CLAUDE.md → Coding Conventions: "Common helpers... belong in a shared utils file — not inlined per-file. No duplicate copies across packages."
Not blocking — flagging for the implementer to decide.
Generated by Claude Code
| "https://flow-state.dev/docs/getting-started/existing-project has the by-hand path.", | ||
| ), | ||
| ); | ||
| } else if (host.value === "unknown") { |
There was a problem hiding this comment.
second-look — dead code (impossible case). classifyHost (next-project.mjs) only ever returns value: "node", "next", or "next-unsupported" — never "unknown" — so this else if and the host-unknown refusal code are unreachable from buildReport, and no test in test/host-and-next.test.mjs exercises them (grepped the whole plugin tree — host-unknown appears only in this branch).
Per CLAUDE.md §2 ("No error handling for impossible scenarios"): either drop this branch (~5 lines), or, if it's meant as a forward-looking guard for a future host classification value, say so in a comment so it doesn't read as reachable dead code to the next person grepping refusal codes. Not blocking.
Generated by Claude Code
| } | ||
|
|
||
| /** Everything under `dir` that could be a `next.config` — used only to report what was considered. */ | ||
| export function nextConfigDirOf(configPath) { |
There was a problem hiding this comment.
second-look — unused export (YAGNI). nextConfigDirOf has no importer anywhere in plugins/flow-state-dev, including the test files — report.mjs builds everything it needs from resolveNextConfig's own path/candidates fields directly. Same situation for isDirectory in fs-util.mjs (also zero consumers).
Recommend dropping both (~11 lines total) unless a near-term follow-up (sub-PR b or c) already needs one of them — in which case a one-line comment naming that consumer would save the next reviewer the same grep. Not blocking.
Generated by Claude Code
| const chosen = | ||
| entries.find(([name]) => name === "dev") ?? | ||
| (starters.length === 1 ? starters[0] : null) ?? | ||
| (starters.length > 1 ? null : null); |
There was a problem hiding this comment.
Nit, not a second-look finding (too small to be worth a row, noting since I was already here): (starters.length > 1 ? null : null) always evaluates to null regardless of the condition, so it reads as if it's handling the ambiguous-starters case distinctly but it's equivalent to a plain ?? null. Harmless — the outcome is already null via the earlier ?? — just confusing next to the two branches above it that do branch on starters.length.
Generated by Claude Code
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 09ec6a7ebd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| * the `.ts` reads settings that never apply; and an app with no config of its own inherits an | ||
| * ancestor's, which is ordinary in a workspace. | ||
| */ | ||
| export function resolveNextConfig(writeRoot, { typescriptSupport = process.features?.typescript === true } = {}) { |
There was a problem hiding this comment.
Treat string-valued TypeScript feature modes as enabled
On supported Node versions, process.features.typescript is "strip" or "transform" rather than boolean true, and Next uses its truthiness when including next.config.mts. This check therefore ignores a config Next actually loads, so a project whose effective settings live there can be reported with the wrong basePath, pageExtensions, and route-slot verdict, causing installation to target or probe the wrong route.
Useful? React with 👍 / 👎.
| if (resolution.cli.status === "empty" && resolution.cli.path !== null) { | ||
| add(resolution.cli.path, `${key} is an empty assignment here and is what you will fill`); | ||
| } else if (resolution.cli.status === "absent") { | ||
| add(own, `${key} will be written here as an empty line for you to fill`); |
There was a problem hiding this comment.
Honor the Next-deciding provider file
When a Next app has OPENAI_API_KEY= in .env.development.local and no assignment visible to the CLI, this branch selects .env.local as the file to fill because it considers only resolution.cli. Next continues to prefer the empty .env.development.local assignment, so the mounted route still has no credential; the actual deciding file is also omitted from the tracked-file safety check. Destination selection needs to account for the Next resolution on mounted-route hosts.
Useful? React with 👍 / 👎.
| const vars = parseEnvFile(content); | ||
| if (!vars.has(key)) continue; | ||
| return { status: statusOf(vars.get(key)), from: "an env file", path }; |
There was a problem hiding this comment.
Expand Next env references before classifying secrets
For Next hosts, this reuses the CLI's simple parser even though @next/env applies dotenv parsing and variable expansion. With .env.local containing FSD_DEMO_TOKEN=$DOES_NOT_EXIST, detection reports a non-empty reusable token while Next expands it to an empty string, leaving the mounted demo authentication broken despite a green report. Use Next-compatible parsing and expansion, or conservatively refuse expansion syntax.
Useful? React with 👍 / 👎.
| const pattern = new RegExp(`(^|[\\s{,])${key}\\s*:\\s*`, "m"); | ||
| const match = pattern.exec(source); |
There was a problem hiding this comment.
Read settings from the effective Next export
When next.config.* contains a commented-out setting or an unrelated helper object before the exported config, this regex selects that first textual occurrence. For example, // basePath: '/old' makes the report advertise /old/api/flows even though Next serves /api/flows; the detector can then exit successfully while subsequent instructions and probes target a 404. Restrict static parsing to the effective exported config, or report the setting as unreadable when ownership is ambiguous.
Useful? React with 👍 / 👎.
|
|
||
| /** The `flows:` value in a config, as raw source, or `null` when it is not statically assigned. */ | ||
| function rawFlowsValue(source) { | ||
| const match = /(^|[\s{,])flows\s*:\s*/m.exec(source); |
There was a problem hiding this comment.
Read flows from the effective config export
When the config contains an earlier helper such as const example = { flows: {} } before createFlowState({ flows: { hello } }), this first-match regex inspects the helper and reports the demo kind as free. The live registry can already own hello, so acting on the green report attempts a duplicate registration and fails at config load. Anchor the inspection to the exported createFlowState configuration or return undetermined.
Useful? React with 👍 / 👎.
| @@ -0,0 +1,5 @@ | |||
| --- | |||
| "@flow-state-dev/fsdev": patch | |||
There was a problem hiding this comment.
Leave this private-plugin changeset empty
This fragment schedules a patch release of @flow-state-dev/fsdev, but the commit changes only the new private plugin workspace and the fragment itself says no published package API changes. Merging it will unnecessarily bump and publish fsdev and place this internal implementation note in its changelog; internal-only work should use an empty fragment or omit the changeset.
AGENTS.md reference: AGENTS.md:L39-L39
Useful? React with 👍 / 👎.
09ec6a7 to
f99f37d
Compare
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_b5118d43-8d26-42fc-94b6-ba89baec78fc) |
|
Round 1 applied in Root A — the env parser did not mirror the loaders it claimed to mirrorAll three env findings lived in one function. The module modelled two runtimes with opposite tie-breaks and then parsed both with a single Split into // test extracts the CLI's own parseEnvFile from source and runs it as JavaScript,
// so the expectation is the real behaviour, not a third copy of it
expect(Object.fromEntries(parseAsCli(input))).toEqual(Object.fromEntries(cliParser(input)));Demonstrated non-vacuous by flipping the tie-break to first-wins: Both findings confirmed against the real
Expansion refuses rather than guesses, per your steer and for the reason you gave: faithfully reproducing Destination selection now consults both loaders. This was the sharpest one — the PR body was proud of modelling two loaders and then picked a destination from one. Fixed with the fixture that goes red without it: Root B — first textual match instead of the effective exportOne bug, two copies. Extracted to The extraction introduced its own regression and the existing tests caught it before review did: blanking string bodies to find assignments also blanked The claim you told me to check first — Codex is rightBoth call sites tested The changeset — checked against the diff, and you're rightNothing published changes, so it is Accepted mechanicallyDead
Skipped, as agreedSplitting On "85/92 pass" — that reporter's Node is 22.14, below the 22.18 floor this detector refuses beneath. Environment, not a defect. Here: Rebased onto the 🤖 Generated with Claude Code Generated by Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f99f37d9c2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (token.cli.status === "non-empty" && token.cli.path === own) { | ||
| add(own, "the demo token is already here and will be reused"); | ||
| } else { | ||
| add(own, "the demo token will be written here"); |
There was a problem hiding this comment.
Preserve the demo token selected by Next
For a mounted Next app with a non-empty FSD_DEMO_TOKEN in higher-precedence .env.development.local, token.next identifies the effective token while token.cli is absent, but this branch still plans to generate a different token in .env.local. Next continues authenticating with the existing higher-precedence value, so requests carrying the generated token receive 401 responses. Unlike the provider-key handling below, the demo-token destination must account for the Next resolution.
Useful? React with 👍 / 👎.
| const fsdevConfig = resolveLoadedConfig(writeRoot); | ||
| const registry = fsdevConfig.winnerIsOurs | ||
| ? { extendable: true, entries: [], demoKind: "free", ourEntry: null } | ||
| : inspectRegistry(fsdevConfig.winner); |
There was a problem hiding this comment.
Refuse before overwriting an unregistered demo module
When the project already contains a user-owned flows/hello/flow.mts that is not imported by the winning config, registry inspection reports the demo kind as free and the report can exit successfully. Because that same path is the detector's declared demo write destination, acting on the green report can overwrite the existing module; inspect the destination itself and distinguish generated ownership from foreign occupancy before declaring the install safe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Skipping — already fixed as a root. demo-flow-path-occupied fires when the write destination exists and lacks fsd:generated (report.mjs). Tests in config-and-files.test.mjs. Not reopening.
| const named = /^(["']?)([\w-]+)\1\s*:\s*([\w.]+)$/.exec(part); | ||
| const shorthand = /^([A-Za-z_$][\w$]*)$/.exec(part); | ||
| const name = named?.[2] ?? shorthand?.[1] ?? null; | ||
| const identifier = named?.[3] ?? shorthand?.[1] ?? null; | ||
| if (name === null || identifier === null) continue; |
There was a problem hiding this comment.
Treat unparsed registry members as undetermined
A valid registry member outside these two regex shapes, such as { [flow.kind]: flow }, is silently discarded here. If that imported flow has kind hello, unreadable remains empty and demoKind becomes free, allowing the installer to append another hello registration and fail when the config is constructed. Any top-level member that cannot be parsed should make the registry undetermined rather than disappear.
Useful? React with 👍 / 👎.
| const match = /kind\s*:\s*(["'])([\w-]+)\1/.exec(source); | ||
| return match === null ? null : match[2]; |
There was a problem hiding this comment.
Read the effective flow kind instead of the first text match
Although the config-level flows scan now removes comments, this separate scan of each imported flow still applies a raw first-match regex. A comment or helper containing kind: "other" before the live defineFlow({ kind: "hello" }) makes the registry appear free, so the installer can add a duplicate demo registration and break config loading. Strip non-code and anchor this lookup to the effective flow definition, or return undetermined when that cannot be established.
Useful? React with 👍 / 👎.
| const isContainer = | ||
| host.value === "node" && (declaration.declares || children.length > 1) && children.length > 0; |
There was a problem hiding this comment.
Refuse declared workspaces whose members evade the shallow scan
For a declared workspace whose packages are nested more than two directory levels deep, such as services/acme/apps/web/package.json, childProjects() returns an empty list and this condition suppresses the workspace-root refusal. The report then labels the container as a plain Node host with second-process topology and can exit successfully, directing scaffolding into the workspace root rather than the intended app. Resolve declared member patterns or conservatively refuse when a workspace declaration cannot be positively classified as a host.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Skipping — already applied. CONTAINER_SCAN_DEPTH = 4 with a boundary test. Not reopening.
| export function plainString(raw) { | ||
| if (raw === null) return null; | ||
| const match = /^(['"])(.*)\1$/s.exec(raw); | ||
| return match === null ? null : match[2]; |
There was a problem hiding this comment.
Decode or reject escapes in static string settings
For a valid config such as basePath: "/docs\x2fv1", JavaScript evaluates the setting as /docs/v1, but this parser returns the literal backslash sequence. The report therefore advertises and later probes /docs\x2fv1/api/flows, which does not match the route Next serves. Static string parsing should either decode JavaScript escapes or mark escaped literals unreadable rather than returning a different value.
Useful? React with 👍 / 👎.
f99f37d to
6419d73
Compare
|
Applied in The pairs are now one rule eachDestination selection is one function. Every secret goes through it; the only difference between them is provenance — the developer supplies a provider key, the run authors the token — which is one row of a table rather than a branch. The demo token's hand-written branch is gone. Static reading is one entry point. The sets are enumerated, and both checks go redThe first was produced by restoring the exact hand-written one-loader branch; the second by wiring a third scan directly. The honest limit, because I tested for it and it did not fire. I first tried the red demo you described — adding a seventh key to The scan check has a vacuity guard, and it earned its place: my first version asserted The instruction I did not carry outYou asked for a phase-1 refusal on a dash-named dev script. It is deliberately not here, because #1358 reversed the decision it depended on. When you asked, the renderer threw on So the pair is completed the other way: That twin test is why this branch is now stacked on #1358 and its base is retargeted — the test needs both halves to exist. It found the disagreement itself before I noticed it, which is the point. The other four findings
VerificationRe-run against No fourth sibling appeared in this round — every finding I fixed was either one of the two roots or an independent defect. If one shows up next round I will stop and bring it to you rather than grinding another pass. 🤖 Generated with Claude Code Generated by Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6419d73147
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (answer.status === "empty" && answer.path !== null) { | ||
| destinations.push({ path: answer.path, reason: `${key} is an empty assignment here, and this is the line ${runtime} resolves` }); |
There was a problem hiding this comment.
Keep generated tokens in the write root
When a workspace ancestor's .env.local contains an empty FSD_DEMO_TOKEN= and the target app has no nearer assignment, this branch adds the ancestor file as the destination even though generated tokens are supposed to remain app-local. The resulting green report directs the installer to fill a workspace-wide file, unexpectedly writing outside the target app and sharing one authentication token across sibling applications; generated provenance should choose own for empty ancestor assignments just as it does for non-empty ancestor values.
Useful? React with 👍 / 👎.
| const extensionsHit = settingValue(source, "pageExtensions"); | ||
| const basePathHit = settingValue(source, "basePath"); |
There was a problem hiding this comment.
Anchor Next settings to the effective export
Fresh evidence after the earlier comment is that resolveNextSettings still calls settingValue without any export anchor, so the new scanner continues searching the entire module. For example, const example = { basePath: "/old" }; export default {} has one textual basePath, causing detection to advertise /old/api/flows even though Next serves /api/flows; the same problem applies to a uniquely named nested or helper pageExtensions setting. Restrict these reads to the effective exported configuration or return unreadable when that cannot be established.
Useful? React with 👍 / 👎.
| const refusals = []; | ||
|
|
||
| // --- The floor: a directory has to be a project before any of this means anything ------------ | ||
| if (!existsSync(join(writeRoot, "package.json"))) { |
There was a problem hiding this comment.
Reject unreadable package manifests
When package.json exists but contains invalid JSON or cannot be read, this existence-only check treats the directory as a project even though readManifest returns null. If a lockfile supplies the package-manager signal, the report can then exit successfully as a plain Node host, despite subsequent dependency or script updates being unable to parse the manifest and potentially using an incorrect host classification. Distinguish an absent manifest from an unreadable one and refuse both states.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Skipping — P2, out of scope for this revision. An unreadable package.json already yields null from readManifest and the host/manager rules refuse from that. Not expanding the reader this round.
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_946db462-6eba-44d8-892f-68381953bf29) |
|
Applied in The scope call, written into the artifacts
That framing is now in three places a future reviewer will actually hit: the The inversionA shape is
A wrapper call, a function export, a runtime choice, a spread, two exports, or two live assignments of one key are all handed off. What a refusal looks likeThe diagnostic you asked for — and it is a real costAgainst ten config shapes real Next apps use: 4 read, 6 handed off.
Four of the six are wrapper plugins, and those are common. I want that in front of you before this merges, because it is the sharp edge of the scope call. I did not soften it, and the reason is specific: All three Next apps in this repository read cleanly (they are all shape 3, with nested objects and a function-valued key). Running that diagnostic found a real defect, not just a cost. The enumeration gapYou were right that consolidating duplication is not the same as completing the rule. The token bugFixed properly. Generated provenance now chooses Verification🤖 Generated with Claude Code Generated by Claude Code |
457234d to
7886cfb
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7886cfb814
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else if (provenance === PROVENANCE.generated) { | ||
| // An ancestor's token belongs to another app: `next dev` cannot see it, and a | ||
| // workspace-wide token means one leak reaches every sibling. We write our own. | ||
| destinations.push({ path: own, reason: `${key} will be generated here (the value ${runtime} finds is another project's)` }); |
There was a problem hiding this comment.
Reuse a demo token inherited from the environment
When FSD_DEMO_TOKEN is non-empty in the inherited environment, answer.path is null, so this branch misclassifies the effective value as another project's token and schedules a new token in .env.local. Both the CLI and Next continue to prefer the inherited value over that file, so the generated credential never becomes effective and downstream requests using it can receive 401 responses; distinguish inherited values from ancestor-file values and reuse the inherited token.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. A non-empty inherited FSD_DEMO_TOKEN (path: null) is reused and writes nothing — it is not “another project's”. Generating into .env.local is what neither loader would ever see. Test: reuses a non-empty token inherited from the environment, and writes nothing.
| function isOurFlowSpecifier(specifier) { | ||
| return specifier.replace(/\.m?[jt]s$/, "") === DEMO_FLOW.modulePath.replace(/\.m?[jt]s$/, ""); |
There was a problem hiding this comment.
Verify the resolved demo module before claiming ownership
When a config imports a foreign module at the same stem with another extension, such as ./flows/hello/flow.js, this comparison labels it as the installer's entry even though the generated destination is flow.mts and the imported file has no ownership marker. The entry is then excluded from foreignWithOurKind, so a foreign kind: "hello" registry reports demoKind: "free"; acting on that green report can leave the foreign flow registered instead of the demo. Determine ownership from the resolved module path and generated marker rather than the normalized specifier alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. Ownership is the resolved module path plus the fsd:generated marker, not a specifier-stem compare. ./flows/hello/flow.js with kind: "hello" and no marker is ourEntry: null / demoKind: "taken". Test: does not claim a foreign module at our stem as ours.
| export function plainStringArray(raw) { | ||
| if (raw === null || !raw.startsWith("[")) return null; | ||
| const inner = raw.slice(1, raw.lastIndexOf("]")); |
There was a problem hiding this comment.
Reject expressions appended to page-extension arrays
For a valid setting such as pageExtensions: ["ts"].filter(() => false), this slices through the last ] and returns ["ts"], ignoring the expression suffix. Next evaluates the setting to an empty array while detection selects .ts and can exit successfully, so the generated handler is not a route. Require the closing bracket to terminate the value, apart from explicitly supported TypeScript annotations, before accepting it as a plain array literal.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Skipping — P2. Same as the concat-string sibling: a trailing array suffix stays unreadable and hands off. Out of scope for this revision.
| export function plainString(raw) { | ||
| if (raw === null) return null; | ||
| const match = /^(['"])(.*)\1$/s.exec(raw); | ||
| if (match === null) return null; |
There was a problem hiding this comment.
Reject concatenated strings as plain literals
For basePath: "/docs" + "/v1", this greedy expression treats the entire source as one quoted literal and returns /docs" + "/v1 instead of rejecting it. Next evaluates the actual base path as /docs/v1, so the report advertises and probes a different mount URL despite considering the setting readable. Ensure the body contains no unescaped matching quote or otherwise parse only a single string-literal token.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Skipping — P2. The P1 on this file was nested keys (Bugbot), which is fixed. Concatenated string literals stay undetermined and hand off. Out of scope.
|
I'm not convinced this is a proper plugin. Does this follow spec? How is this ran as a skill? Where is SKILL.md? Also should we be considering https://agent-plugins.org/? |
|
That question is sub-PR c, not this PR. Detection is the read-only half: scripts a skill runs, no
|
The cheap, checkable facts about a repository that a coding assistant would
otherwise guess at, produced before anything is written to it. Ten
resolutions, one report with two renderers, and every refusal decided from
state the run has not modified.
NOTHING HERE WRITES, and no fact is read off the directory - each is asked of
the tool that owns it. README.md carries why both rules are shaped that way.
STRUCTURAL CHANGE THIS ROUND: STOP FIXING SIBLINGS, MAKE THE PAIR ONE RULE.
Every defect this module has shipped had the same shape. A pair exists - two
env loaders, two secrets, two static scans - a reviewer names one half, the
fix lands on the half that was named, and the other half surfaces the round
after. Six of the last eight findings were the third instance of two roots
already "fixed". So the pairs are now single rules with the set enumerated:
- DESTINATION SELECTION is one function. Every secret goes through it; the
only thing that differs is provenance (the developer supplies a provider
key, the run authors the token), which is one row of a table rather than
a branch. The demo token's hand-written branch is gone.
- STATIC READING is one entry point. source-scan.mjs owns every read of a
foreign source file - settings, imports, and the flow `kind` scan that
was still raw first-match after the config-level one was fixed.
- THE SETS ARE ENUMERATED IN TESTS. One walks every key in SECRET_KEYS and
asserts each was resolved from every loader that reads it. One walks
every module in detect/ and asserts none scans foreign source itself.
Both demonstrated red by restoring the exact defect:
x FSD_DEMO_TOKEN was resolved from 1 runtime(s):
expected [ 'your CLI' ] to deeply equal [ 'your CLI', 'next dev' ]
x fsdev-config.mjs reads foreign source directly; route it through
source-scan.mjs
Honest limit: adding a key to SECRET_KEYS is automatically routed by the
shared rule, so there is nothing to catch there. What the check catches
is the BYPASS - a hand-written branch that consults one loader - which is
the defect that actually occurred, twice.
Also fixed, each with a test:
- the write barrier now checks the PATH it would write, not the registry.
A project can own `flows/hello/flow.mts` without registering it; asking
the registry was checking a proxy for the thing.
- the container scan reached two levels by hand-unrolled loop, so a
workspace nested deeper evaded the refusal and reported as a plain Node
host. Depth is now a declared constant with a boundary test.
- an unparseable registry member is `undetermined`, not silently dropped.
- `plainString` decodes escape sequences: `basePath: "/docs\\x2fv1"` is the
path /docs/v1 to Next and was two literal characters to us.
THE DEV-SCRIPT REFUSAL WAS ASKED FOR AND IS DELIBERATELY NOT HERE. The
instruction predated #1358 reversing its own dash-script decision: the
renderer no longer throws on `--help`, it emits the separator and the command
runs. A phase-1 refusal would now reject a project that works. So the pair is
completed the other way - `needsRunSeparator` in detect and `runSeparatorFor`
in the CLI answer the same question, and a twin test runs both over one table
and fails if they diverge. That test is why this branch is STACKED on #1358:
it needs both halves to exist.
149 tests.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UVQxJiUzAQfecJzfvyqN4m
…promise (FIX-1159)
Scope call from the owner:
"I'm fine on shrinking the claim for now. I still think having an agent do
the work will be the long term solution, this is used when we have simple
enough projects to add to."
THE DETECTOR IS FOR SIMPLE PROJECTS. A config past what it reads trivially is
not a gap to close by parsing harder — it is out of scope by design, and the
right response is to hand it off. That framing is now in the module header,
detect/README.md, and the PR body, so a future reviewer filing "you don't
handle exotic config X" can see it is scope rather than a defect.
THE INVERSION. A shape is `undetermined` unless it is on an enumerated list:
`module.exports = {…}`, `export default {…}`, or `const NAME = {…}` (with or
without a TS type annotation) exported by name; for a call, a single call given
a direct object literal. A wrapper call, a function export, a runtime choice, a
spread, two exports, or two live assignments of one key are all handed off.
This is what makes the surface finite. The previous version tried to handle
whatever it met and got it wrong a new way each round — commented-out setting,
helper object, second assignment, unanchored read. Not four bugs; one
open-ended promise.
REFUSALS ARE LOUD AND USEFUL. One `config-past-what-i-read` code, a message
naming the file and the shape, and two ways forward (hand it to an agent, or
the by-hand docs) plus "Nothing has been written."
MEASURED, because a scope call is only defensible if its cost is known.
Against ten config shapes real Next apps use: 4 read, 6 handed off — four of
the six are wrapper plugins (@next/mdx, @sentry/nextjs, @next/bundle-analyzer,
next-intl). All three Next apps in this repo read cleanly.
test/accepted-shapes.test.mjs pins both numbers so they cannot drift silently.
Running that diagnostic found a real defect, not just a cost: `const
nextConfig: NextConfig = {…}` — create-next-app's standard TypeScript output —
was being refused, because the declaration pattern had no room for a type
annotation. Fixed. That is the most ordinary shape there is, and our own three
configs (all untyped .mjs) could never have surfaced it.
THE ENUMERATION GAP. `settingValue` went THROUGH source-scan.mjs and still did
not anchor — so the check caught a bypass and missed an incomplete rule applied
through the shared entry point. Consolidating duplication into one file is not
the same as making the one rule complete. `region` is now a REQUIRED parameter
(it throws without one), and the enumeration test asserts every caller passes a
region rather than asserting the entry point exists.
THE TOKEN BUG, fixed properly. A generated secret whose ancestor .env.local
carried an EMPTY FSD_DEMO_TOKEN= picked the ancestor as its destination —
writing a shared auth token outside the target app, where every sibling
inherits it. The write barrier violated on a plain layout. The non-empty branch
already chose the app's own file; only the empty one was wrong, and the reason
it survived is that only one half of the branch had a test. Both halves are now
one it.each, demonstrated red by restoring the defect: the empty case fails
while non-empty stays green.
178 tests.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UVQxJiUzAQfecJzfvyqN4m
7886cfb to
d3d7aff
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.
| const lines = hits.map((at) => code.slice(0, at).split("\n").length); | ||
| return { unreadable: `${key} is assigned ${hits.length} times (lines ${lines.join(", ")})` }; | ||
| } | ||
| return { raw: valueAt(source, hits[0]), line: code.slice(0, hits[0]).split("\n").length }; |
There was a problem hiding this comment.
Nested basePath false refusals
High Severity
settingValue searches the entire exported object region as flat text, so a nested basePath inside redirects or rewrites (commonly basePath: false) is treated as the Next setting. That yields a false config-past-what-i-read refusal on ordinary App Router configs where top-level basePath is unset or set beside redirect entries.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.
There was a problem hiding this comment.
Fixed on a626ce783. settingValue now only accepts the key at object-literal depth 1, so a nested basePath: false on a redirect/rewrite is treated as unset (Next default "", readable). A top-level basePath beside nested ones still wins. Test: does not treat a nested basePath inside redirects as the Next setting.
| } | ||
|
|
||
| if ((answer.status === "empty" || answer.status === "unreadable") && answer.path !== null) { | ||
| const inWriteRoot = answer.path.startsWith(`${writeRoot}/`); |
There was a problem hiding this comment.
Write-root path check broken
High Severity
inWriteRoot is decided with startsWith(${writeRoot}/), but join builds platform paths. On Windows those paths use backslashes, so a non-empty developer secret already inside the write root is treated as outside and never added as a destination. The tracked-by-git refusal then never runs for that file.
Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.
There was a problem hiding this comment.
Fixed on a626ce783. Both destinationsFor sites now use isInside(root, path) — relative(resolve(root), resolve(path)) — so Windows backslashes and a missing trailing separator no longer treat every file as outside the write root.
| outermost = dir; | ||
| via = declaration.via; | ||
| } | ||
| if (repo !== null && dir === repo) break; |
There was a problem hiding this comment.
Repository path equality fails
High Severity
repositoryRoot returns git's raw toplevel string, then resolveWorkspaceRoot and collectManagerSignals compare it to ancestorsFrom paths with ===. On Windows git reports forward slashes while resolve uses backslashes, so the repository and workspace bounds never match and the walk continues past the intended stop.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.
There was a problem hiding this comment.
Fixed on a626ce783. repositoryRoot now resolve()s git rev-parse --show-toplevel, so it === the ancestorsFrom entries (resolve() uses \ on Windows; git prints /). That is what bounds the workspace walk and collectManagerSignals.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3d7aff114
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2"); | ||
| if (quote === '"') value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r"); | ||
| // Single quotes suppress expansion in dotenv's grammar; every other form is expanded. | ||
| vars.set(key, { value, expands: quote !== "'" && EXPANSION.test(value) }); |
There was a problem hiding this comment.
Expand single-quoted Next env references
For a mounted Next app with FSD_DEMO_TOKEN='$DOES_NOT_EXIST', this exemption classifies the token as a readable non-empty literal, while @next/env expands the reference to an empty string and authentication rejects every request. Fresh evidence after the earlier expansion finding is that the attempted conservative fix explicitly exempts single quotes, but direct loadEnvConfig verification shows Next expands those values too; treat them as expandable or unreadable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. After dotenv strips quotes, expands is just EXPANSION.test(value). KEY='$DOES_NOT_EXIST' is unreadable; \$ stays literal via the existing (?<!\\) in EXPANSION. The twins row that expected single quotes to suppress expansion now expects the opposite.
| consulted.push(runtime); | ||
|
|
||
| if (answer.status === "non-empty") { | ||
| const inWriteRoot = answer.path !== null && answer.path.startsWith(`${writeRoot}/`); |
There was a problem hiding this comment.
Use platform-aware containment for secret paths
On Windows, both paths use backslashes, so an app-local path such as C:\app\.env.local never starts with the constructed C:\app/ prefix. A non-empty developer provider key in that file is consequently treated as external and omitted from secretFiles, allowing detection to stay green even when the credential file is tracked by Git; determine containment with path.relative or platform path APIs instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783 — same root as the Bugbot write-root finding. isInside via relative(resolve(), resolve()) at both containment sites.
| continue; | ||
| } | ||
|
|
||
| if ((answer.status === "empty" || answer.status === "unreadable") && answer.path !== null) { |
There was a problem hiding this comment.
Refuse inherited empty secret overrides
When the inherited environment owns a selected provider key or FSD_DEMO_TOKEN with value "", its resolution has status: "empty" and path: null, so this branch is skipped and the value is treated like an absent variable below. The report then directs writing or generating a value in .env.local, but both the CLI and Next continue to prefer the inherited empty value, leaving model calls or demo authentication broken despite a green report. Fresh evidence beyond the earlier inherited-token finding is the distinct empty-value path, which needs an unset-environment remediation rather than a file destination.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. Inherited status: "empty" + path: null no longer falls through to a .env.local destination. New refusal inherited-secret-empty (demo token always; provider key once chosen). Remediation is unset the env var. Test covers the token and a provider key.
| if (chosen === null) return { script: null, command: null, port: null, url: null, needsSeparator: false }; | ||
|
|
||
| const [script, command] = chosen; | ||
| const portMatch = /(?:-p|--port)[= ](\d+)/.exec(command); |
There was a problem hiding this comment.
Read Next's PORT environment setting
When the dev script is PORT=4000 next dev, this flag-only regex finds no port and reports http://localhost:3000, so the printed follow-up and probes target the wrong server. The inspected next dev --help explicitly documents -p, --port <port> as (default: 3000, env: PORT), so the resolver must account for the script's PORT assignment before applying the default.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. resolveDevCommand now also matches PORT=(\d+). -p / --port still win when both are present.
| /** The major version a `next` dependency range asks for, or `null` when it is not a readable range. */ | ||
| export function nextMajorFrom(range) { | ||
| if (typeof range !== "string") return null; | ||
| const match = /(\d+)\s*\./.exec(range.replace(/^[\^~>=<\s]*/, "")); |
There was a problem hiding this comment.
Reject Next ranges that still allow version 14
For a valid dependency range such as ^15.0.0 || ^14.0.0, this returns 15 and classifies the host as supported even when the lockfile has selected Next 14. The subsequent adapter installation requires Next 15 or later and can fail or produce an unsupported runtime; parse the complete range or conservatively reject unions that include versions below the minimum.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. nextMajorFrom takes one major per || disjunct (not every \d+. — that would read the minor in ^15.4.0 as a second major). If any disjunct is below 15 and any is at least 15, it returns null → next-version-unreadable. Pure ^14 is still next-version.
| const code = blankNonCode(source); | ||
|
|
||
| // Shapes 1 and 2: a direct object literal on the export. | ||
| const direct = /(?:module\s*\.\s*exports|export\s+default)\s*=?\s*\{/.exec(code); |
There was a problem hiding this comment.
Reject conditional CommonJS config exports
For if (process.env.CI) module.exports = { basePath: "/ci" }, this regex accepts the assignment as the supported direct-object shape regardless of whether the condition runs. Outside CI, Next receives the default empty export and serves /api/flows, while detection advertises /ci/api/flows. Fresh evidence beyond the prior export-anchoring finding is that the matched assignment is genuinely an export but remains conditionally effective; nested or conditional exports should be reported unreadable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed on a626ce783. exportedObjectRegion refuses when the matched export is preceded by if / else / for / while / switch (including if (cond) { module.exports = {…} }). Two live exports were already unreadable. Test: hands off a conditional CommonJS export rather than reading the assignment that may not run.
Co-authored-by: Jake Hoffner <jhoffner@users.noreply.github.com>
…h equality (FIX-1159) Read only top-level config keys, reuse or refuse inherited process.env instead of writing a file neither loader will see, and compare paths with resolve()/relative() so Windows separators and git toplevel do not miss a containment or repository bound. Co-authored-by: Jake Hoffner <jhoffner@users.noreply.github.com>
Take detection as it landed on main via #1355. Keep this branch's skill, templates, wiring contract, existing-project docs, and plugin test-time fsdev workspace dep. Do not rewrite detection. Co-authored-by: Jake Hoffner <jhoffner@users.noreply.github.com>


The problem
Adding FSD to a project someone already has means answering a set of cheap, checkable questions about their repository first. Which package manager do they actually use. Where does their framework keep its application directory. Which of the four possible config files would our CLI really load. Is the file we are about to put a secret into already committed to git.
Every one of those has a right answer sitting on disk. And every one of them, asked by a coding assistant working from what a directory looks like, has a confidently wrong answer that fails silently — a run that installs through the wrong package manager and leaves a lockfile the project never wanted, or writes an app directory that stops every page they already had from being served, or points a developer at a committed file and asks them to paste their API key into it.
What this does
It answers those questions deterministically, before anything is written, and hands the answers over as a report the assistant reads and is told not to overrule.
Two properties do the work, and they are worth stating in plain terms because they are the whole design.
Nothing here can write anything. Not "does not" — cannot. Every reason this run might refuse is worked out from the repository exactly as the developer left it. Three separate defects in this design were the same mistake: deciding whether to refuse by making a change and then looking at the result, which leaves a mutation behind on a run that then refuses. A component with no way to write is a component that cannot make that mistake again.
Nothing here decides a fact by looking; it decides it by asking what the tool that owns it would do. Which config gets loaded is a precedence order, not a filename. Which file already occupies a route is a matcher's list of extensions, not the name we happened to pick. What an environment variable resolves to is a search with two tie-breakers that run in opposite directions — and a different search, with a different grammar, for each of the two servers that will read it.
No secret value ever leaves this code. For every credential the run touches — the one the developer already had as much as the one we generate — the report carries is it there, is it empty, and which file decided that. Never the value. The report is text an assistant reads, so anything in it is in a saved transcript, which is the same hazard as asking someone to type their key into a chat window.
What's asked of you
This implements the approved direction — the resolution table and refusal conditions in §7 and §9 of the FIX-1159 spec. Nothing here is a new product call.
Two things I decided rather than asking, both worth a glance:
Where we cannot read a project's config faithfully, we refuse rather than guess. Two cases now do this. A
next.configvalue that is computed rather than written literally, and an environment variable whose value Next would expand (TOKEN=$SOMETHING_ELSE) — reproducing Next's expansion exactly is a small pile of precedence rules, and getting one subtly wrong is the failure mode this whole component exists to prevent. So we say "cannot read this" and stop. That trades a small number of unusual projects being turned away for never writing files into a project where we could not tell what would happen.A detection run against a real project found a bug no fixture would have. Pointed at a project that happens to sit inside an unrelated git checkout, the workspace search walked straight past that project's own repository and adopted the outer one's settings — so it would have installed using a package manager belonging to a project the developer has nothing to do with. Now bounded at the repository, with a test.
Parts worth reviewing closely
report.mjs— the refusal list. It is the write barrier made concrete. Each entry should be decidable from an unmodified repository; anything that needs a change made first is a defect in the invariant, not a new case.env-parsers.mjs— two parsers, one per loader.parseAsCliis an asserted twin: the test extracts the CLI's own parser from source and runs it, so the expectation is the real behaviour rather than a third copy of it.parseAsNextDevuses the dotenv grammar@next/envactually bundles. Worth confirming the extraction really finds the function it claims to.source-scan.mjs— the shared walker. One anchoring rule for every static read of somebody else's config. The interesting part is that its two callers want opposite treatment of string literals, which is a real trap: blanking them is right for finding an assignment and wrong for reading an import specifier.next-project.mjs— the slot scan set. Deliberately wider than the extensions a project currently enables, because the narrow version is a check that cannot fail: it reports a slot empty while a file we wrote sits in it.Links
Linear FIX-1159 · spec PR #1310 (closed, approved) · epic FIX-1161 (#1301) · sub-PR a of 3 — merges.
How to review this
How to review this. This implements an approved spec — the approach and the numbered Decisions in its §6 are already signed off by a human, so please review the code against that direction, not the direction itself. The spec lives on the issue's Linear document (the durable copy) and on the closed spec PR (#1310), which keeps its review history. Don't expect
spec/FIX-1159.mdto be in this diff — the spec PR closes unmerged at approval and the spec never lands onmain(BP-037).Most valuable here: correctness on the second path (the legacy shape, the null boundary, the concurrent case, the cancel path), anything deriving an auth or routing decision from caller-controllable input, and a behaviour the tests assert around rather than on.
Already settled upstream: the approach and every §6 Decision (human-approved — if one is wrong, say so as a spec finding and it gets folded back; don't re-argue it inline), and the conventions in
docs/contributing/best-practices.md.Review round 1 — six findings were two roots
Both roots were this module's own headline invariant being violated, so they were fixed as roots rather than as six patches.
Root A — the env parser did not mirror the loaders it claimed to mirror. One
parseEnvFileserved both runtimes and faithfully mirrored neither; all three env findings lived in it. Split intoparseAsCli(now an asserted twin ofpackages/cli/src/load-env.ts) andparseAsNextDev(the dotenv grammar@next/env@16.1.6bundles:exportprefix,:separator, backticks, trailing#). Expansion is reportedunreadablerather than guessed at. And destination selection now consults both loaders — it used the CLI answer alone, so on a mounted-route host the filenext devactually decides from never reached the tracked-by-git check. That last one is fix-applied-to-one-of-a-pair, in the module whose whole point is the pair.Root B — first textual match instead of the effective export. One bug in two copies of the same walker: a commented-out
// basePath: '/old'decided the mount URL, and a helperconst example = { flows: {} }above the real call reported a live registry that already ownshelloas free. Extracted tosource-scan.mjsand fixed once inside it — comments and string bodies blanked before anything is searched, the registry read anchored on the singlecreateFlowState(call, and a key assigned twice reported unreadable rather than resolved to the first.That extraction introduced its own regression, and the registry tests caught it: blanking string bodies also blanked
import x from "./y"down to" ". Blanking is now a parameter, and a test pins the specifier case.One P1 whose premise I checked before fixing.
process.features.typescriptis the string"strip"on Node 22.22.2, nevertrue. Both call sites tested=== true, sonext.config.mtswas dropped from the candidate list on exactly the machines where Next accepts it. Both of that check's existing tests passed the value explicitly, so the default was never exercised — the new test drives the production path.The changeset is now
--empty, verified against the diff rather than taken on faith: no file underpackages/orapps/changes, so no published package needs a version bump. The Linear ref stays; the guard requires it and passes.Accepted mechanically: the dead
host-unknownbranch (classifyHostreturns only node/next/next-unsupported), the deadisDirectory/nextConfigDirOf/listDirre-export, and the(starters.length > 1 ? null : null)tautology. Comment volume trimmed, with the defect history moved todetect/README.md— a rule is easier to follow than a history, but a future "simplification" would re-introduce a specific failure, so the failures stay written down.secretFiles[].ignoredkept, with a comment saying why: sub-PR c's write step must not create a secret file git would not ignore, and that has to be answered from unmodified state.Skipped as out of scope: splitting
next-project.mjs, and recomputation ofrepositoryRoot/readManifeston a one-shot path.Engineering calls
plugins/*joins the pnpm workspace. The scripts ship inside the plugin tree FIX-1160 packages, so they cannot live in a published package — but a directory outside the workspace gets no CI. A private workspace member atplugins/flow-state-devgives the tests a home without making the scripts importable from anywhere. FIX-1160 addsplugin.jsonand the marketplace manifest beside it; the two are additive.Zero dependencies and zero monorepo imports. These run from an installed plugin on somebody else's machine. Constants and behaviours that duplicate framework ones are checked against the real source in
test/twins.test.mjs— parsed out, never re-typed, since a restated expectation is a third copy rather than a check on the second.Two lockfiles that agree are not ambiguous. The spec says "disagreeing, or two at one level". Two lockfiles in the chain that evidence the same manager resolve cleanly; refusing them would reject an ordinary layout over a signal that agrees with itself.
Resolution 8b has three verdicts, not two.
free/taken/undetermined. A registry we cannot read statically is undetermined rather than folded into either — it is the one state where the demo flow really may end up unregistered, and calling it free would write files that never load. Onlytakenrefuses.A container is reported as
workspace-root, never asnode. The refusal alone was not enough: a report that still saidnodehands the skill a host classification for a directory that has none, and the second-process branch is what would then get scaffolded at the top of somebody's repository. Caught by my own test rather than by review.The prose renderer's label column fits the longest label the report can produce.
GOOGLE_GENERATIVE_AI_API_KEY:overran an 18-column field and ran into its value — unreadable exactly where a credential is named. Found by running it, not by a fixture.Verification
Run from
plugins/flow-state-devand from the script's own directory, not the repo root — the root is where cwd-sensitive failures hide. Rebased onto amainthat already contains sub-PR b, and re-verified against it.Run against real projects, from a package subdirectory. Against
examples/hello-chat, a real Next 16 app inside this pnpm workspace: the manager resolves from the repository root's declaration while the write root stays at the app, and both route slots refuse because hello-chat already owns that mount (EXIT=1). Against a project seeded to the minimal floor Q6(b) specifies — apackage.json, apackageManagerfield, and an ignorable.env.local, nothing else — it reportsnode/second-processwith no refusals (EXIT=0).Six checks demonstrated able to go red, by restoring the implementation each exists to catch:
× refuses our own stale file at an extension pageExtensions no longer enables→expected [] to include 'route-slot-stale'× takes the NEAREST file across the walk, even when it is empty, and× refuses when the file that will be filled is tracked× a stale lockfile inside a workspace app does not decide the manager→expected 'npm' to be 'pnpm'× refuses when the TOKEN's file is tracked even though the provider key's is cleanparseAsCli's tie-break to first-wins× agrees with the CLI on "KEY=first\nKEY=second"→expected { KEY: 'first' } to deeply equal { KEY: 'second' }— the twin assert is not vacuous× finds our own entry by the import it resolves to— the regression the Root B extraction introducedTwo of these are worth dwelling on. The env-chain one breaks two checks at once — the masking report and the credential-into-git refusal — because they are the same defect seen from two directions. And the last one is a defect the refactor itself introduced, caught by the existing suite before review saw it.
DAG state
install-fsdskill content, the wiring contract, docsTwo follow-ups on the merged block are in #1358 — an IPv6 dev URL whose port was misread, and a dev script named
--helpthat every package manager swallows.plugins/flow-state-dev/skills/install-fsd/is created here because this issue lands before FIX-1160, which packages the skill. FIX-1160 addsplugin.jsonand.claude-plugin/marketplace.jsonalongside; nothing here claims those filenames.Note
Medium Risk
Detection drives where install would write routes, env files, and credentials; bugs could refuse valid projects or point installs at wrong paths, though secret values are excluded from the report and the module cannot write during detection.
Overview
Introduces the install-fsd detection stack in the private
plugins/flow-state-devworkspace: dependency-free ESM that runs from the Claude Code plugin before any scaffold writes files.node detect.mjsbuilds a versioned JSON report (and optional prose) by walking numbered resolutions—workspace/write roots, package manager precedence, Next host andnext.configloading, route slots,fsdev.configregistry, and per-runtime secret status (never values). Refusals are evaluated only from unmodified repo state; exit0/1/2mirrors “safe to act”, “refused with remediation”, and bad argv.The design narrows static config reading to an explicit whitelist (
source-scan.mjs); complexnext.configshapes and env expansion are handed off rather than guessed. Separate CLI vsnext devenv parsers mirrorload-env.tsand@next/env, with twin tests against the real CLI source.Adds
plugins/flow-state-dev/package.json(Vitest),pnpm-workspace.yamlentry forplugins/*, lockfile workspace slice, and an internal-only changeset (nopackages//apps/version bumps).Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.