Skip to content

feat(detect): the detection scripts and the report (FIX-1159, sub-PR a) - #1355

Merged
jhoffner merged 4 commits into
mainfrom
fix/FIX-1159-detection
Aug 26, 2026
Merged

jhoffner merged 4 commits into
mainfrom
fix/FIX-1159-detection

Conversation

@jhoffner

@jhoffner jhoffner commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

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.config value 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. parseAsCli is 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. parseAsNextDev uses the dotenv grammar @next/env actually 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.md to be in this diff — the spec PR closes unmerged at approval and the spec never lands on main (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 parseEnvFile served both runtimes and faithfully mirrored neither; all three env findings lived in it. Split into parseAsCli (now an asserted twin of packages/cli/src/load-env.ts) and parseAsNextDev (the dotenv grammar @next/env@16.1.6 bundles: export prefix, : separator, backticks, trailing #). Expansion is reported unreadable rather than guessed at. And destination selection now consults both loaders — it used the CLI answer alone, so on a mounted-route host the file next dev actually 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 helper const example = { flows: {} } above the real call reported a live registry that already owns hello as free. Extracted to source-scan.mjs and fixed once inside it — comments and string bodies blanked before anything is searched, the registry read anchored on the single createFlowState( 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.typescript is the string "strip" on Node 22.22.2, never true. Both call sites tested === true, so next.config.mts was 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 under packages/ or apps/ changes, so no published package needs a version bump. The Linear ref stays; the guard requires it and passes.

Accepted mechanically: the dead host-unknown branch (classifyHost returns only node/next/next-unsupported), the dead isDirectory / nextConfigDirOf / listDir re-export, and the (starters.length > 1 ? null : null) tautology. Comment volume trimmed, with the defect history moved to detect/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[].ignored kept, 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 of repositoryRoot/readManifest on 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 at plugins/flow-state-dev gives the tests a home without making the scripts importable from anywhere. FIX-1160 adds plugin.json and 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. Only taken refuses.

A container is reported as workspace-root, never as node. The refusal alone was not enough: a report that still said node hands 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-dev and from the script's own directory, not the repo root — the root is where cwd-sensitive failures hide. Rebased onto a main that already contains sub-PR b, and re-verified against it.

$ cd plugins/flow-state-dev && pnpm test
 Test Files  5 passed (5)
      Tests  125 passed (125)

$ pnpm typecheck                   # root, incl. boundary validators
 package boundary validation passed
 [updater-purity] OK   [side-chain-vocabulary] OK

$ pnpm knip:ci                     # no unlisted / unresolved findings
$ node scripts/validate-changeset-refs.mjs
 ✓ every new changeset names its Linear issue
$ pnpm install --frozen-lockfile   # clean

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 — a package.json, a packageManager field, and an ignorable .env.local, nothing else — it reports node / second-process with no refusals (EXIT=0).

Six checks demonstrated able to go red, by restoring the implementation each exists to catch:

implementation restored what went red
scan only the enabled route extensions × refuses our own stale file at an extension pageExtensions no longer enables → expected [] to include 'route-slot-stale'
ask the env chain "is it non-empty anywhere?" × takes the NEAREST file across the walk, even when it is empty, and × refuses when the file that will be filled is tracked
bound the workspace search at the nearest lockfile × a stale lockfile inside a workspace app does not decide the manager → expected 'npm' to be 'pnpm'
make resolution 10 a single file again four red, incl. × refuses when the TOKEN's file is tracked even though the provider key's is clean
flip parseAsCli'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
blank string bodies when reading imports × finds our own entry by the import it resolves to — the regression the Root B extraction introduced

Two 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
sub-PR deliverables depends_on state
a detection scripts + the report, both renderers — this PR
b the next-steps block — merged — #1352
c the install-fsd skill content, the wiring contract, docs a, b unblocks when this merges

Two follow-ups on the merged block are in #1358 — an IPv6 dev URL whose port was misread, and a dev script named --help that 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 adds plugin.json and .claude-plugin/marketplace.json alongside; 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-dev workspace: dependency-free ESM that runs from the Claude Code plugin before any scaffold writes files.

node detect.mjs builds a versioned JSON report (and optional prose) by walking numbered resolutions—workspace/write roots, package manager precedence, Next host and next.config loading, route slots, fsdev.config registry, and per-runtime secret status (never values). Refusals are evaluated only from unmodified repo state; exit 0 / 1 / 2 mirrors “safe to act”, “refused with remediation”, and bad argv.

The design narrows static config reading to an explicit whitelist (source-scan.mjs); complex next.config shapes and env expansion are handed off rather than guessed. Separate CLI vs next dev env parsers mirror load-env.ts and @next/env, with twin tests against the real CLI source.

Adds plugins/flow-state-dev/package.json (Vitest), pnpm-workspace.yaml entry for plugins/*, lockfile workspace slice, and an internal-only changeset (no packages/ / apps/ version bumps).

Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.

@linear-code

linear-code Bot commented Aug 20, 2026

Copy link
Copy Markdown

FIX-1159

@vercel

vercel Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

3 Skipped Deployments
Project Deployment Actions Updated (UTC)
flow-state-dev-docs Ignored Ignored Aug 26, 2026 9:26pm
flow-state-dev-kitchen-sink Ignored Ignored Aug 26, 2026 9:26pm
flow-state-dev-ui Ignored Ignored Preview Aug 26, 2026 9:26pm

Request Review

@cursor

cursor Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping — still the agreed one-shot path. Detection is a single report; caching repositoryRoot is not worth a second contract. Not reopening.

Comment on lines +95 to +97
const vars = parseEnvFile(content);
if (!vars.has(key)) continue;
return { status: statusOf(vars.get(key)), from: "an env file", path };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

Fix in Cursor

@@ -0,0 +1,5 @@
---
"@flow-state-dev/fsdev": patch

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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!

Fix in Cursor

cursor[bot]
cursor Bot approved these changes Aug 20, 2026 •
Comment on lines +161 to +164
} else if (host.value === "unknown") {
refusals.push(
refusal("host-unknown", "I can't tell what kind of project this is.", "Nothing was written."),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +64 to +91
/** 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();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +302 to +325
/** 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 };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grok / simplify — should-fix (dead exports):

  • nextConfigDirOf is exported and never imported.
  • export { listDir } is unused; callers already take listDir from fs-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 };

Comment on lines +1 to +26
/**
* 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping — already trimmed in the Aug 20–21 pass. Leaving the remaining header. Out of scope for this revision.

Comment on lines +181 to +185
return [...files.values()].map((entry) => ({
...entry,
exists: existsSync(entry.path),
tracked: isTrackedByGit(entry.path),
ignored: isIgnoredByGit(entry.path),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 } = {}) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +173 to +176
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`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +95 to +97
const vars = parseEnvFile(content);
if (!vars.has(key)) continue;
return { status: statusOf(vars.get(key)), from: "an env file", path };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +66 to +67
const pattern = new RegExp(`(^|[\\s{,])${key}\\s*:\\s*`, "m");
const match = pattern.exec(source);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@jhoffner
jhoffner force-pushed the fix/FIX-1159-detection branch from 09ec6a7 to f99f37d Compare August 21, 2026 19:40
@cursor

cursor Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot 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)

Copy link
Copy Markdown
Collaborator Author

Round 1 applied in f99f37d9c. Eight findings, fixed as two roots plus one P1 — because both roots were this module's own headline invariant being violated, and patching six instances is how you get a seventh.

Root A — the env parser did not mirror the loaders it claimed to mirror

All three env findings lived in one function. The module modelled two runtimes with opposite tie-breaks and then parsed both with a single parseEnvFile that faithfully mirrored neither.

Split into parseAsCli and parseAsNextDev, and — the structural part — parseAsCli is now an asserted twin, which is the mechanism this file already had and had not applied here:

// 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:

× agrees with the CLI on "KEY=first\nKEY=second"
  → expected { KEY: 'first' } to deeply equal { KEY: 'second' }

Both findings confirmed against the real @next+env@16.1.6 bundle rather than taken on report:

  • Expansion is real. processEnv does e = expand(e); _interpolate handles $VAR, ${VAR}, ${VAR:-default} and \$, falling back to "".
  • export is real. dotenv's key regex is literally (?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)… — export optional, : an alternative separator, all three quote styles, trailing # stripped.

Expansion refuses rather than guesses, per your steer and for the reason you gave: faithfully reproducing expand means reproducing its precedence, escapes and last-match-first recursion, and getting one subtly wrong is the defect class being fixed. A value carrying expansion syntax resolves to unreadable — same posture as an unreadable basePath. Single-quoted and \$-escaped forms stay readable, because dotenv does not expand those either.

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:

✓ includes the file next dev decides from, and checks it for git tracking
   .env.development.local is named, its reason says "next dev",
   and because it is tracked the run refuses instead of pointing a key at it

Root B — first textual match instead of the effective export

One bug, two copies. Extracted to source-scan.mjs, with the anchoring fixed once inside it: comments and string bodies blanked before anything is searched, the registry read anchored on the single createFlowState( call, and a key assigned twice reported unreadable rather than resolved to the first.

✓ ignores a commented-out setting, in both comment syntaxes
✓ reads the registry createFlowState is given, not the first flows: in the file
✓ refuses a setting assigned twice rather than picking one

The extraction introduced its own regression and the existing tests caught it before review did: blanking string bodies to find assignments also blanked import x from "./y" down to " ", so every registry entry resolved to nothing. The two callers want opposite treatment, so blanking is a parameter now, and a test pins the specifier case.

The claim you told me to check first — Codex is right

node v22.22.2
typeof: string
value: "strip"
=== true: false

Both call sites tested === true, so next.config.mts was dropped from the candidate list on exactly the machines where Next accepts it. P1, real. And the reason it survived: both of that check's existing tests passed typescriptSupport explicitly, so the default was never exercised. The new test drives the production path with no argument.

The changeset — checked against the diff, and you're right

$ git diff --name-only origin/main...HEAD | grep -E "^(packages|apps)/"
NONE

Nothing published changes, so it is --empty now. The Linear ref stays — scripts/validate-changeset-refs.mjs requires it, and it passes.

Accepted mechanically

Dead host-unknown branch (classifyHost returns only node/next/next-unsupported), dead isDirectory / nextConfigDirOf / listDir re-export, the (starters.length > 1 ? null : null) tautology. The two github-code-quality always-false guards were in the rawSettingValue code Root B deleted, so they are gone with it. Comments trimmed, defect history moved to detect/README.md.

secretFiles[].ignored kept, 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 rather than by writing and checking afterwards.

Skipped, as agreed

Splitting next-project.mjs; repositoryRoot()/readManifest() recomputation on a one-shot path.

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: 125 passed (125).

Rebased onto the main that now carries sub-PR b; no semantic interaction, as expected. PR body updated — the DAG table said b was open.

🤖 Generated with Claude Code


Generated by Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +141 to +144
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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +248 to +251
const fsdevConfig = resolveLoadedConfig(writeRoot);
const registry = fsdevConfig.winnerIsOurs
? { extendable: true, entries: [], demoKind: "free", ourEntry: null }
: inspectRegistry(fsdevConfig.winner);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +119 to +123
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +157 to +158
const match = /kind\s*:\s*(["'])([\w-]+)\1/.exec(source);
return match === null ? null : match[2];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +92 to +93
const isContainer =
host.value === "node" && (declaration.declares || children.length > 1) && children.length > 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping — already applied. CONTAINER_SCAN_DEPTH = 4 with a boundary test. Not reopening.

Comment on lines +150 to +153
export function plainString(raw) {
if (raw === null) return null;
const match = /^(['"])(.*)\1$/s.exec(raw);
return match === null ? null : match[2];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@jhoffner
jhoffner force-pushed the fix/FIX-1159-detection branch from f99f37d to 6419d73 Compare August 21, 2026 20:08
@jhoffner
jhoffner changed the base branch from main to fix/FIX-1159-next-steps-followups August 21, 2026 20:08

Copy link
Copy Markdown
Collaborator Author

Applied in 6419d7314. I stopped fixing siblings and made the pairs single rules, per your direction. Two things need your attention: one instruction I did not carry out, and an honest limit on the enumeration checks.

The pairs are now one rule each

Destination 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. 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, and both checks go red

× FSD_DEMO_TOKEN was resolved from 1 runtime(s):
    expected [ 'your CLI' ] to deeply equal [ 'your CLI', 'next dev' ]
× fsdev-config.mjs reads foreign source directly; route it through source-scan.mjs

The 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 SECRET_KEYS — and the check passed. That is correct rather than broken: a key added to the set is automatically routed by the shared rule, so there is nothing to catch. What the check catches is the bypass — a hand-written branch that consults one loader — which is the defect that actually occurred, twice. I have said so in the commit rather than letting "walks every secret" imply more coverage than it has.

The scan check has a vacuity guard, and it earned its place: my first version asserted source-scan.mjs itself matched the offender pattern, which it does not, because it blanks comments into a different variable. Worse, testing the predicate directly then showed it missed the source.matchAll(...) shape entirely — it only caught exec(source). Both fixed.

The instruction I did not carry out

You 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 --help, so a refusal at print time was the barrier being 95% true. After the {{runSep}} reversal the renderer separates the name and the printed command runs — so a phase-1 refusal would now reject a project that works fine.

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. Detection reports the fact; the renderer spends it; neither refuses.

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

  • report.mjs:251 — the write barrier now checks the path it would write. A project can own flows/hello/flow.mts without registering it; asking the registry was checking a proxy for the thing, same as the dev-script gap.
  • report.mjs:93 — the container scan reached two levels via a hand-unrolled loop, so a workspace nested deeper evaded the refusal and reported as a plain Node host. Depth is a declared constant with a boundary test.
  • fsdev-config.mjs:123 — an unparseable registry member is undetermined, not silently dropped.
  • source-scan.mjs:153 — plainString decodes escape sequences; basePath: "/docs\x2fv1" is /docs/v1 to Next and was two literal characters to us. An escape it cannot decode returns null, which callers already treat as unreadable.

Verification

plugins/flow-state-dev  149 passed
packages/cli            238 passed
pnpm typecheck          package boundary validation passed
pnpm knip:ci            0 unlisted / unresolved
changeset guard         ✓

Re-run against examples/hello-chat from the script's own directory: still refuses both route slots, still resolves pnpm from the repository-root declaration.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +190 to +191
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` });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +99 to +100
const extensionsHit = settingValue(source, "pageExtensions");
const basePathHit = settingValue(source, "basePath");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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"))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cursor

cursor Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot 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)

Copy link
Copy Markdown
Collaborator Author

Applied in 457234dde — stacked on top of 6419d7314, not amended. No force-push; the history is the review record from here on.

The scope call, written into the artifacts

"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."

That framing is now in three places a future reviewer will actually hit: the source-scan.mjs module header, a Scope: simple projects section at the top of detect/README.md, and the PR body. A "you don't handle exotic config X" finding should now read as scope, not as a defect.

The inversion

A shape is undetermined unless it is on the list:

  1. module.exports = { … }
  2. export default { … }
  3. const NAME = { … } — with or without a TypeScript type annotation — exported by name
  4. 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.

What a refusal looks like

I can't read next.config.mjs safely — the exported value `withMDX` is not a
plain object literal.
This detector only reads a few simple config shapes on purpose — a plain object
exported directly, or assigned to a name and exported. Yours is past that, and
guessing at it is how a run scaffolds into the wrong place.

    Two ways forward: ask a coding agent to wire FSD in for you (it can read
    your config properly), or follow
    https://flow-state.dev/docs/getting-started/existing-project to do it by
    hand. Nothing has been written.

The diagnostic you asked for — and it is a real cost

Against ten config shapes real Next apps use: 4 read, 6 handed off.

read handed off
create-next-app default @next/mdx wrapper
plain module.exports @sentry/nextjs wrapper
TypeScript, type-annotated @next/bundle-analyzer wrapper
const with a commented-out setting next-intl wrapper
async function config
spread over a base object

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: @next/mdx commonly rewrites pageExtensions — the very setting we would be reading. Reading the object a wrapper wraps and hoping it doesn't touch our settings is precisely the guessing this design removed. If the turn-away rate is too high, the answer is the agent path, not a looser parser.

All three Next apps in this repository read cleanly (they are all shape 3, with nested objects and a function-valued key). test/accepted-shapes.test.mjs pins both numbers so neither drifts without someone deciding it should.

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. That is the single most ordinary shape there is, and our own three configs (all untyped .mjs) could never have surfaced it. Fixed, and in the pinned sample.

The enumeration gap

You were right that consolidating duplication is not the same as completing the rule. region is now a required parameter — settingValue throws without one — and the enumeration test asserts every caller passes one, rather than asserting the entry point exists. Both layers demonstrated red by making one caller unanchored:

× every caller reads a setting from an accepted region, never unanchored
  → next-project.mjs: settingValue(...) is called with no region
× (and at runtime) settingValue("pageExtensions") was called with no region.

The token bug

Fixed properly. Generated provenance now chooses own for an empty ancestor assignment exactly as it does for a non-empty one. Both halves are one it.each, and restoring the defect shows why it survived — the empty case fails while non-empty stays green:

× never writes a generated secret outside the app — ancestor assignment is empty
  → expected [ '<root>/.env.local' ] to include '<root>/apps/web/.env.local'

Verification

plugins/flow-state-dev  178 passed
pnpm typecheck          package boundary validation passed
pnpm knip:ci            0 unlisted / unresolved
changeset guard         ✓

🤖 Generated with Claude Code


Generated by Claude Code

Base automatically changed from fix/FIX-1159-next-steps-followups to main August 21, 2026 20:54
@jhoffner
jhoffner force-pushed the fix/FIX-1159-detection branch from 457234d to 7886cfb Compare August 21, 2026 20:54

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +181 to +184
} 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)` });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +140 to +141
function isOurFlowSpecifier(specifier) {
return specifier.replace(/\.m?[jt]s$/, "") === DEMO_FLOW.modulePath.replace(/\.m?[jt]s$/, "");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +252 to +254
export function plainStringArray(raw) {
if (raw === null || !raw.startsWith("[")) return null;
const inner = raw.slice(1, raw.lastIndexOf("]"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping — P2. Same as the concat-string sibling: a trailing array suffix stays unreadable and hands off. Out of scope for this revision.

Comment on lines +278 to +281
export function plainString(raw) {
if (raw === null) return null;
const match = /^(['"])(.*)\1$/s.exec(raw);
if (match === null) return null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhoffner

Copy link
Copy Markdown
Collaborator Author

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/?

@jhoffner

Copy link
Copy Markdown
Collaborator Author

That question is sub-PR c, not this PR.

Detection is the read-only half: scripts a skill runs, no SKILL.md here on purpose. The skill, how it is invoked (node ${SKILL_DIR}/detect/detect.mjs . --json), and the wiring it writes are #1471, stacked on this branch.

plugin.json and a marketplace manifest are FIX-1160. This directory is a workspace member so the scripts have CI; it is not a packaged plugin yet. agent-plugins.org is a 1160 question — whether we publish on Claude's marketplace, that registry, or both — and is out of scope for the detector.

claude added 2 commits August 26, 2026 11:18
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
@jhoffner
jhoffner force-pushed the fix/FIX-1159-detection branch from 7886cfb to d3d7aff Compare August 26, 2026 15:18

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.

Fix All in Cursor

❌ 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 };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}/`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d3d7aff. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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) });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}/`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]*/, ""));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

cursoragent and others added 2 commits August 26, 2026 21:20
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>
@jhoffner
jhoffner merged commit c9eb21a into main Aug 26, 2026
11 checks passed
cursor Bot pushed a commit that referenced this pull request Aug 27, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants