Skip to content

fix(adf): gate the ESM extension rule on moduleResolution - #314

Merged
stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-294
Sep 20, 2026
Merged

stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-294

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Closes #294

Root cause

packages/cli/src/commands/adf-populate.ts gated the constraint

Use .js extensions for all ESM imports (never .ts in import paths)

on pkg.type === 'module' in any project-local package.json. That is the wrong
signal. type: "module" says the files are ESM; it says nothing about whether
relative imports need an explicit extension. Vite's React template — and every
esbuild/webpack/modern-Workers project — sets "type": "module" together with
moduleResolution: "bundler", where extensionless relative imports are the
correct and near-universal convention.

The constraint lands in .ai/core.adf under ⚠ 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 exactly
pkg.type === 'module', so the rule could not have fired without it. Vite's
template does set it. The real configuration is type: "module" and
moduleResolution: "Bundler", which is precisely why the rule fired and
precisely why it was wrong.

Fix

The signal is now TypeScript's compilerOptions.moduleResolution, read from the
tsconfig next to each ESM package.json (falling back to the root tsconfig for a
nested package that has none).

tsconfig state signal rule emitted
moduleResolution: node16 / nodenext (any casing) required yes
moduleResolution: bundler (any casing) not-required no
moduleResolution: node / node10 / classic not-required no
moduleResolution absent, module: node16 / nodenext required yes
moduleResolution absent, module: ESNext / commonjs not-required no
resolved via one level of relative extends as resolved per the base
solution-style (files: [] + references, no compilerOptions) unknown no
tsconfig.json unparseable (JSONC) unknown no
extends is an array or a bare package name unknown no
no tsconfig anywhere, no typescript dependency required yes
no tsconfig anywhere, typescript is a dependency unknown no

Casing is normalised with toLowerCase() before comparison — the reporter's
repo 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 required and no ESM package
reports not-required. A client/ (bundler) plus worker/ (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 relative extends is followed, resolved against the
config's own directory (not cwd), with .json appended when the literal path
does not exist.

The resolver is load-bearing for the veto, not a convenience. Without the hop, a
client/tsconfig.json of {"extends": "./tsconfig.base.json"} over a bundler
base yields unknown — and unknown does not veto. Pair that client with an
inline-nodenext worker/ and the rule emits for a repository that is half
bundler, 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.json in this repo sets "type": "module", so the ESM signal set is
always 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 project
references are not resolved and all yield unknown. The one-hop bound is
pinned 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.json routinely carries comments and trailing commas, which
JSON.parse rejects. The throw is caught and mapped to unknown, which
withholds 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 no typescript in its own or the root
package's dependencies/devDependencies still gets the rule. If TypeScript is
in play but no tsconfig was found, the configuration is somewhere this resolver
does not look, so the signal is unknown and 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:

  • omits the rule for a bundler project (Vite: type:module + moduleResolution Bundler)
  • omits the rule when a relative extends resolves to bundler
  • omits the rule for a solution-style tsconfig that only lists references
  • omits the rule when tsconfig.json is JSONC and cannot be parsed
  • omits the rule when extends points at a bare package name
  • omits the rule when typescript is a dependency but no tsconfig was found
  • lets a single bundler package veto the rule for the whole repo
  • falls back to the root tsconfig for a nested package that has none

The five that passed under the old code are the positive cases (nodenext,
module: node16, NodeNext via extends, plain JS ESM with no tsconfig) plus
the no-type: module case. Those passing beforehand is what proves the fixtures
reach the code path at all — the block only runs when the scaffolded core.adf
has a CONSTRAINTS list section, so a fixture that failed to produce one would
make every negative assertion pass trivially.

All 13 pass after the fix. Review round 2 added two more, both verified by
mutation: raising MAX_EXTENDS_DEPTH to 2 fails the depth test, and removing
the root-tsconfig candidate fails the inheritance test. 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, and now a pinned decision rather than an
untested consequence. 15 pass in total.

  • pnpm test — 916/916 passed, 64 files (baseline on main is 901)
  • pnpm run typecheck — clean
  • pre-commit tsc --noEmit + ADF evidence gate — PASS, not bypassed

adf-populate.ts carries no LOC ceiling; the eight tracked ceilings all still
report PASS.

🤖 Generated with Claude Code

…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 stackbilt-admin left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

  1. [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. No package.json in this repository carries "type": "module" (checked root and all of packages/*), so esmSignals at :217-219 is always empty here and the resolver is never exercised on charter at all. packages/cli/tsconfig.json → ../../tsconfig.base.json is therefore not evidence for anything. The real justification is stronger: without the hop, a client/tsconfig.json of {"extends": "./tsconfig.base.json"} over a bundler base yields 'unknown', which does not veto — pair it with an inline-nodenext worker/ 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.

  2. [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 (root nodenext, nested type: module package 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.

  3. [NIT] packages/cli/src/commands/adf-populate.ts:319-323 — usesTypeScript consults only ctx and the root package, so a monorepo where typescript lives solely in a sibling's devDependencies reports false and 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.

  4. [NIT] packages/cli/src/commands/adf-populate.ts:224 + :293 — the plain-JS branch (type: module, no tsconfig, no typescript dep) emits text ending "(never .ts in import paths)" into a project that has no .ts files. 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.

  5. [NIT] packages/cli/src/__tests__/adf-populate.test.ts:88-100 — one-hop extends is tested, two-hop is not, so MAX_EXTENDS_DEPTH has 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]>
@stackbilt-admin
stackbilt-admin merged commit 214ff5b into main Sep 20, 2026
5 checks passed
@stackbilt-admin
stackbilt-admin deleted the auto/bugfix/issue-294 branch September 20, 2026 13:20
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.

bug(bootstrap): injects a stack-incorrect ESM extension rule as a load-bearing constraint

1 participant