Repository navigation
fix(adf): gate the ESM extension rule on moduleResolution - #314
Conversation
…odule (closes #294) adf populate emitted "Use .js extensions for all ESM imports" whenever any package.json declared type: "module", which is true of every Vite, esbuild and modern Workers project. Under moduleResolution: "bundler" extensionless relative imports are the correct convention, so the rule landed in CONSTRAINTS [load-bearing] as a wrong instruction telling agents to rewrite correct code. The rule now reads TypeScript's moduleResolution (falling back to the `module` value that implies it): node16/nodenext emits, bundler/node/classic does not, and ambiguity — unparseable JSONC, a solution-style config, an extends chain this resolver does not follow — withholds it. A single bundler package vetoes the rule for the whole repository. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
stackbilt-admin
left a comment
There was a problem hiding this comment.
APPROVED
Reviewed adversarially against the stated principle: does any uncertain input ever end up EMITTING? I could not construct one that is reachable on a valid TypeScript configuration. Every finding below is a NIT.
Verified empirically
The revert experiment reproduces the claimed split exactly. I restored main's adf-populate.ts in a scratch state, ran packages/cli/src/__tests__/adf-populate.test.ts, and got 8 failed / 5 passed — and the 8 names match the PR body's list item for item (bundler, extends→bundler, solution-style, JSONC, bare-name extends, typescript-without-tsconfig, veto, root fallback). Restored; git status clean, nothing committed or pushed. 13/13 pass on the branch.
The "positives prove the fixtures reach the path" argument is sound. All 13 cases share the same populate() helper (test:44-49), and the four toContain(ESM_RULE) assertions can only pass if addConstraint actually fired — which requires the scaffolded core.adf to carry a CONSTRAINTS list section (adf-populate.ts:203-204). A fixture that silently failed to produce one would have failed those four, not passed them. The negative assertions are therefore not passing vacuously.
Claims checked against source, not description
The veto (adf-populate.ts:217-221). Correct in both directions I was asked about. Empty case: no type: module package anywhere → esmSignals is [] → includes('required') is false → no rule. Mixed monorepo: client/ bundler + worker/ nodenext → ['not-required','required'] → vetoed. Vetoing rather than scoping is the right call given the artifact: the text says "all ESM imports" and there is one core.adf for the repository, so a per-package signal has nowhere correct to land. Per-package scoping would be a different feature, not a fix.
The module fallback (adf-populate.ts:303). The TS5110 reasoning holds. A false positive requires module: node16|nodenext in the child while the effective moduleResolution is something else — which TS5109/TS5110 reject, so it is a broken config rather than a reachable input. When moduleResolution is absent and module is node16/nodenext, TS derives the matching resolution, so the fallback is a true positive, not a guess. Checked the two you flagged: module: "preserve" (TS 5.4+) is not in EXTENSION_REQUIRING_RESOLUTION → not-required, correct (it implies bundler resolution); module: "commonjs" inside a type: module package → not-required → veto, which is the safe direction. Not following extends in this branch only costs resolution when the child sets module and the base sets moduleResolution — a pairing TS already rejects.
The extends resolver (adf-populate.ts:296-316). Depth accounting is right, and it is worth stating why since it reads off-by-one-ish: entry is readModuleResolution(candidate, 0) (:288), 0 >= MAX_EXTENDS_DEPTH is false so the hop is taken, the recursive call is depth + 1 (:316), and 1 >= 1 returns 'unknown'. Exactly one hop. Array extends and bare package names both fall out at :310-311 as 'unknown'; project references never reach the extends branch because a solution-style config has no compilerOptions, so declared is undefined and extends is absent → 'unknown'. .json appending (:314-315) is correct, and an extends pointing at a directory survives safely: existsSync passes, readFileSync throws EISDIR, readJsonFile returns null, → 'unknown'.
Casing (adf-populate.ts:304). "Bundler", "NodeNext", "Node16" all normalise correctly; test:60-68 pins the reporter's literal capitalized "Bundler".
JSONC (adf-populate.ts:266-274). No path falls back to emit-anyway. readJsonFile returns null on throw, and both call sites map null to withholding: :297-298 returns 'unknown', and :218 treats an unparseable package.json as not-type: module, which drops it from esmSignals entirely. Confirmed by test:127-140 failing pre-fix.
existsSync on a case-insensitive mount — noise, not a real risk. tsconfig.json is lowercase by convention and TypeScript itself looks for that exact name, so a checkout where the casing differs would already be broken for tsc. The ${resolved}.json path at :314 compares distinct basenames, not casings. Recording it; no change warranted.
CHANGELOG (CHANGELOG.md:12). Accurate, including the framing. It says adf populate while the issue says bootstrap; that is right — bootstrap.ts:1203-1204 delegates to adfPopulateCommand, so populate is where the behaviour lives and bootstrap is merely the entry point users hit.
Scope. Three files, 295+/8-. Nothing unrelated rides along. On diff size: the ~90 lines are comments (justified for a load-bearing gate — the why here is the whole fix), the extends resolver (justified, see #1 below), and usesTypeScript (~8 lines for a narrow case). I would not cut any of it.
The deliberate false negative (type: module + moduleResolution: "node", real ESM on Node, extensions genuinely required at runtime): recording it is enough, do not emit. It is a miss, which the governing principle prices at one hand-added line, and the configuration is itself one TypeScript flags as wrong for ESM. Emitting there would mean trusting a config that is already internally inconsistent.
Findings
-
[NIT]
packages/cli/src/commands/adf-populate.ts:296-316— the PR description's justification for the extends resolver is false, though the resolver itself is right. Nopackage.jsonin this repository carries"type": "module"(checked root and all ofpackages/*), soesmSignalsat:217-219is always empty here and the resolver is never exercised on charter at all.packages/cli/tsconfig.json→../../tsconfig.base.jsonis therefore not evidence for anything. The real justification is stronger: without the hop, aclient/tsconfig.jsonof{"extends": "./tsconfig.base.json"}over a bundler base yields'unknown', which does not veto — pair it with an inline-nodenextworker/and the rule emits for a repo that is half bundler. The extends resolver is what makes an inherited bundler setting able to veto. Worth correcting in the description so the next reader does not delete the resolver on the grounds that the stated reason does not hold. -
[NIT]
packages/cli/src/commands/adf-populate.ts:286-289— the root-tsconfig fallback is only tested in the withholding direction. test:192-205 covers root =Bundler→ no rule; the mirror case (rootnodenext, nestedtype: modulepackage with no tsconfig of its own) emits a load-bearing rule inferred from a different package's config, and nothing pins it. The inference is defensible — TS's own config lookup walks up, and a real Vite client always ships its own tsconfig — but this is the one remaining path where an uncertain-ish input emits, so it should be a deliberate, tested decision rather than an untested consequence. Add the positive case. -
[NIT]
packages/cli/src/commands/adf-populate.ts:319-323—usesTypeScriptconsults onlyctxand the root package, so a monorepo wheretypescriptlives solely in a sibling'sdevDependenciesreportsfalseand yields'required'instead of'unknown'. Reachable only when there is no tsconfig anywhere in the scanned tree and TypeScript is confined to an unscanned sibling — narrow enough that I would not widen the check, but worth a comment noting the bound. -
[NIT]
packages/cli/src/commands/adf-populate.ts:224+:293— the plain-JS branch (type: module, no tsconfig, notypescriptdep) emits text ending "(never .ts in import paths)" into a project that has no.tsfiles. The extension half is correct for native Node ESM; the parenthetical is TS-flavoured noise in exactly the case that branch exists to serve. Pre-existing wording, not introduced here. -
[NIT]
packages/cli/src/__tests__/adf-populate.test.ts:88-100— one-hopextendsis tested, two-hop is not, soMAX_EXTENDS_DEPTHhas no regression pin. Low stakes: an off-by-one there would over-resolve (find a real answer one level deeper), never mis-emit from a guess. A.json-suffixed grandparent case would lock the boundary in cheaply.
Nothing here blocks the merge. The gate is correct, the ambiguity handling is consistent with the stated principle on every branch I could reach, and the tests were genuinely written against the bug.
…294) Review follow-up. Two paths were load-bearing consequences rather than deliberate, tested decisions: - A nested type:module package with no tsconfig of its own inherits the root config, so a root nodenext emits the rule for a package that never declared it. Defensible, since TypeScript's own lookup walks up, but now pinned. - MAX_EXTENDS_DEPTH stopped at one hop untested. Over-resolving could only find a true answer, never mis-emit from a guess, so the bound is a choice worth recording. Both tests were verified to fail under mutation: raising MAX_EXTENDS_DEPTH to 2 fails the depth test, removing the root-tsconfig candidate fails the inheritance test. Also bounds usesTypeScript in a comment: it consults only the package and the repo root, so typescript confined to an unscanned sibling reads as absent. That is reachable only when no tsconfig exists anywhere in the scanned tree. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Closes #294
Root cause
packages/cli/src/commands/adf-populate.tsgated the constrainton
pkg.type === 'module'in any project-localpackage.json. That is the wrongsignal.
type: "module"says the files are ESM; it says nothing about whetherrelative imports need an explicit extension. Vite's React template — and every
esbuild/webpack/modern-Workers project — sets
"type": "module"together withmoduleResolution: "bundler", where extensionless relative imports are thecorrect and near-universal convention.
The constraint lands in
.ai/core.adfunder⚠ CONSTRAINTS [load-bearing],which Charter's own GUIDE defines as "violation causes incorrect output". So
bootstrap was writing a rule that is false for the repository into the section
agents treat as non-negotiable — a governance tool manufacturing drift, where an
agent "fixes" a correct codebase to satisfy a generated rule.
Note for reviewers: the issue text says the reporter's repo had no
"type": "module". That parenthetical is incorrect — the code gates on exactlypkg.type === 'module', so the rule could not have fired without it. Vite'stemplate does set it. The real configuration is
type: "module"andmoduleResolution: "Bundler", which is precisely why the rule fired andprecisely why it was wrong.
Fix
The signal is now TypeScript's
compilerOptions.moduleResolution, read from thetsconfig next to each ESM
package.json(falling back to the root tsconfig for anested package that has none).
moduleResolution: node16/nodenext(any casing)requiredmoduleResolution: bundler(any casing)not-requiredmoduleResolution: node/node10/classicnot-requiredmoduleResolutionabsent,module: node16/nodenextrequiredmoduleResolutionabsent,module: ESNext/commonjsnot-requiredextendsfiles: []+references, nocompilerOptions)unknowntsconfig.jsonunparseable (JSONC)unknownextendsis an array or a bare package nameunknowntypescriptdependencyrequiredtypescriptis a dependencyunknownCasing is normalised with
toLowerCase()before comparison — the reporter'srepo literally has
"Bundler"capitalized, and TypeScript accepts"NodeNext","nodenext","Bundler"and"bundler"interchangeably.Aggregation. The constraint text says "all ESM imports", so it is only
emitted when at least one ESM package reports
requiredand no ESM packagereports
not-required. Aclient/(bundler) plusworker/(nodenext) repo —exactly the layout
loadPackageContexts()scans for — therefore gets no rule.A single bundler package vetoes it. This was not in the original decision table;
it is a routine call made in the stated safe direction.
Decisions on the edge cases
extends— one level of relativeextendsis followed, resolved against theconfig's own directory (not cwd), with
.jsonappended when the literal pathdoes not exist.
The resolver is load-bearing for the veto, not a convenience. Without the hop, a
client/tsconfig.jsonof{"extends": "./tsconfig.base.json"}over a bundlerbase yields
unknown— andunknowndoes not veto. Pair that client with aninline-
nodenextworker/and the rule emits for a repository that is halfbundler, which is the exact failure this PR exists to remove. Following the hop
is what lets an inherited bundler setting veto the way an inline one does.
Delete the resolver and that hole reopens.
(An earlier revision of this description claimed the resolver was needed to
answer Charter's own repo correctly. That was wrong and has been removed: no
package.jsonin this repo sets"type": "module", so the ESM signal set isalways empty here and the resolver is never exercised on Charter at all.)
A full resolver is out of scope: array
extends(TS 5.0+), bare package names(
@tsconfig/node20/tsconfig.json,astro/tsconfigs/strict) and projectreferencesare not resolved and all yieldunknown. The one-hop bound ispinned by a two-hop test; over-resolving could only ever find a true answer, so
the bound is a deliberate miss rather than a correctness risk.
JSONC —
tsconfig.jsonroutinely carries comments and trailing commas, whichJSON.parserejects. The throw is caught and mapped tounknown, whichwithholds the rule. It does not fall back to the old emit-anyway behaviour: for a
load-bearing constraint, "could not tell" must never produce an instruction.
No tsconfig at all — split rather than guessed. Native Node ESM without
TypeScript genuinely does require extensions on relative specifiers, so a package
with
type: "module", no tsconfig, and notypescriptin its own or the rootpackage's
dependencies/devDependenciesstill gets the rule. If TypeScript isin play but no tsconfig was found, the configuration is somewhere this resolver
does not look, so the signal is
unknownand no rule is emitted.The unifying principle: every ambiguous path resolves to withhold. Missing a
correct constraint costs the user a line they can add by hand; emitting a wrong
one costs them a codebase rewritten to match it.
Verification
Regression tests added in
packages/cli/src/__tests__/adf-populate.test.ts(15 cases), written before the fix and run against the unmodified code to
confirm they actually catch the bug. Under the old behaviour 8 failed:
The five that passed under the old code are the positive cases (
nodenext,module: node16,NodeNextviaextends, plain JS ESM with no tsconfig) plusthe no-
type: modulecase. Those passing beforehand is what proves the fixturesreach the code path at all — the block only runs when the scaffolded
core.adfhas a
CONSTRAINTSlist section, so a fixture that failed to produce one wouldmake every negative assertion pass trivially.
All 13 pass after the fix. Review round 2 added two more, both verified by
mutation: raising
MAX_EXTENDS_DEPTHto 2 fails the depth test, and removingthe root-tsconfig candidate fails the inheritance test. A nested
type: modulepackage with no tsconfig of its own inherits the root config, so a root
nodenextemits the rule for a package that never declared it — defensible,since TypeScript's own lookup walks up, and now a pinned decision rather than an
untested consequence. 15 pass in total.
pnpm test— 916/916 passed, 64 files (baseline onmainis 901)pnpm run typecheck— cleantsc --noEmit+ ADF evidence gate — PASS, not bypassedadf-populate.tscarries no LOC ceiling; the eight tracked ceilings all stillreport PASS.
🤖 Generated with Claude Code