From d95d997f3f66742aaa3dd1d1d42d941b4a351a5d Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Sun, 26 Jul 2026 21:23:58 -0600 Subject: [PATCH 1/3] feat(core): fold cross-file references into active lexicon package exports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1020 taught fold to resolve an identifier across the module graph, but only through relative/absolute specifiers — `isProjectFileSpecifier` skipped bare package specifiers outright. So an identifier imported from a LEXICON package failed as "unresolved identifier" even when what it named was plain static data: azure's `Azure` and gcp's `GCP` pseudo-parameter namespaces, aws's `S3Actions`, gitlab's `CI`. Every one of those is an `as const` object literal the folder has always handled; the gap was purely the resolver's scope. `buildExternals` now follows a bare specifier into a package, and only into a package, that is an ACTIVE LEXICON of this build. The allowlist is the lexicon names the build already resolved before discovery ran, threaded down as `DiscoveryOptions.lexicons` and matched by TEXT — nothing is resolved to find out what it is, which is what keeps `resolveModulePath`'s pathological cold-resolution path (measured at up to ~361s for a genuinely new bare specifier, regressed twice during #1020) out of reach. Subpaths are excluded for the same reason: the fast resolver only recognizes a package root, so a subpath specifier would fall through to exactly that slow path, and lexicons re-export their whole surface from the barrel anyway. What comes back is the real export off the real module, imported through the session-wide import cache — the same module object the run path gets, since `importModule` is a plain `import()` with no cache-busting. So identity holds by construction, and `reviveFoldedValue` grows a passthrough for live `Intrinsic` instances: without it the generic object walk rebuilds `Azure.ResourceGroupLocation` as a plain `{}`, dropping the prototype that carries `toJSON` and serializing `{}` where run emits `[resourceGroup().location]`. Callable exports stay out. A lexicon's resource classes, composite factories and intrinsic functions already have resolution paths that know how to invoke them; binding them as identifier values would widen what folds well beyond what this needs. No `liveSources` edge is recorded for a lexicon-package value. That mechanism exists for a folded file that captured another discovered FILE's objects, so it can be invalidated when that file is forced back to run. A lexicon package has no fold/run duality: it is not a discovered file, `planFoldTaint` filters to the discovered set anyway, and both paths reach it through the identical import of the identical path. `process` and every other ambient environment read still fail, with a test that pins it alongside an active lexicon package in scope. --- packages/core/src/build.ts | 9 + packages/core/src/cli/commands/build.ts | 9 + .../core/src/discovery/fold-import.test.ts | 235 ++++++++++++++++++ packages/core/src/discovery/fold-import.ts | 189 +++++++++++++- packages/core/src/discovery/index.ts | 17 +- 5 files changed, 451 insertions(+), 8 deletions(-) diff --git a/packages/core/src/build.ts b/packages/core/src/build.ts index 96d89fe468..8b19dc0175 100644 --- a/packages/core/src/build.ts +++ b/packages/core/src/build.ts @@ -170,6 +170,14 @@ export interface BuildOptions { */ intrinsics?: IntrinsicDef[]; + /** + * chant #1063 — the lexicon names loaded for this build. Passed straight + * through to {@link DiscoveryOptions.lexicons} in `./discovery/index`; + * ignored unless {@link fold} is set. The CLI populates this from + * `options.plugins.map(p => p.name)`. + */ + lexicons?: readonly string[]; + /** * chant #1045 Phase 2 — opt-in: run-fallback files (or, when {@link fold} * isn't set, every file) execute together, isolated, in one sandboxed @@ -513,6 +521,7 @@ export async function build( const discoveryResult = await discover(path, { fold: options?.fold, intrinsics: options?.intrinsics, + lexicons: options?.lexicons, sandbox: options?.sandbox, buildParams: options?.buildParams, }); diff --git a/packages/core/src/cli/commands/build.ts b/packages/core/src/cli/commands/build.ts index e00bf79872..911ab1886a 100644 --- a/packages/core/src/cli/commands/build.ts +++ b/packages/core/src/cli/commands/build.ts @@ -201,6 +201,14 @@ export async function buildCommand(options: BuildOptions): Promise // any), hence the guard. const intrinsics = options.plugins?.flatMap((plugin) => plugin.intrinsics?.() ?? []) ?? []; + // #1063 — the same loaded plugins, by NAME, are this build's allowlist for + // following a bare import specifier into a lexicon package (so `Azure`, + // `GCP`, `S3Actions`, `CI` fold as values). A plugin's `name` is the + // lexicon name `loadPlugin()` was called with, which is exactly what + // `@intentius/chant-lexicon-` was imported from — see + // ../plugins.ts and fold-import.ts's `lexiconPackageName`. + const lexicons = options.plugins?.map((plugin) => plugin.name) ?? []; + // Run the build const result = await build(infraPath, options.serializers, undefined, { ownership, @@ -208,6 +216,7 @@ export async function buildCommand(options: BuildOptions): Promise fold, sandbox, intrinsics, + lexicons, buildParams: paramsResolution.provenance, }); diff --git a/packages/core/src/discovery/fold-import.test.ts b/packages/core/src/discovery/fold-import.test.ts index cf9d3a159e..97bede4516 100644 --- a/packages/core/src/discovery/fold-import.test.ts +++ b/packages/core/src/discovery/fold-import.test.ts @@ -7,6 +7,7 @@ import { tryFoldFile, createFoldSession } from "./fold-import"; import { isDeclarable } from "../declarable"; import { isCompositeInstance } from "../composite"; import { isAttrRefLike } from "../utils"; +import { isIntrinsic } from "../intrinsic"; import { params as sharedParams } from "../params"; import type { AttrRef } from "../attrref"; import type { IntrinsicDef } from "../lexicon"; @@ -1596,3 +1597,237 @@ describe("tryFoldFile — registered call-form intrinsics (#1044)", () => { expect(result.reason).toContain("same-file resource reference"); }); }); + +/** + * chant #1063 — cross-file references into an ACTIVE LEXICON PACKAGE's + * exports. + * + * #1020 taught fold to follow an identifier into another module, but only + * through a relative/absolute specifier — a bare package specifier was + * skipped outright, so `Azure`, `GCP`, `S3Actions` and gitlab's `CI` all + * failed as "unresolved identifier" even though every one of them is a plain + * `as const` object the folder already handles. These tests install a real + * package into the fixture tree's own `node_modules` and drive the identical + * resolution a real `@intentius/chant-lexicon-azure` import takes: a genuine + * bare specifier, resolved by {@link fastResolveBareSpecifier} walking up to + * `/node_modules`, then really imported. + * + * Every fixture package gets a UNIQUE name. `bareSpecifierPathCache` is + * process-wide and keyed by specifier alone (deliberately — see its doc), so + * two tests reusing one name would have the second silently resolve to the + * first's already-deleted directory. + */ +describe("tryFoldFile — active lexicon package exports (#1063)", () => { + let testDir: string; + let seq = 0; + + beforeEach(async () => { + testDir = join(tmpdir(), `chant-fold-import-lexpkg-test-${Date.now()}-${Math.random()}`); + await mkdir(testDir, { recursive: true }); + }); + + afterEach(async () => { + await rm(testDir, { recursive: true, force: true }); + }); + + /** + * Install a package into `/node_modules/` and return its + * bare specifier. `lexiconName` is what a build would list in + * `chant.config.ts`'s `lexicons`; the package name follows chant's one + * naming convention (`@intentius/chant-lexicon-`), same as + * `loadPlugin()` uses. + */ + async function installLexiconPackage(source: string): Promise<{ lexicon: string; specifier: string }> { + const lexicon = `fold1063x${seq++}${Date.now().toString(36)}`; + const specifier = `@intentius/chant-lexicon-${lexicon}`; + const dir = join(testDir, "node_modules", specifier); + await mkdir(dir, { recursive: true }); + await writeFile( + join(dir, "package.json"), + JSON.stringify({ name: specifier, version: "0.0.0", type: "module", exports: { ".": "./index.js" } }), + ); + await writeFile(join(dir, "index.js"), source); + return { lexicon, specifier }; + } + + /** A pseudo-parameter namespace shaped exactly like `lexicons/azure/src/pseudo.ts`'s `Azure`, plus a plain-data constants object and a callable export. */ + const LEXICON_SOURCE = ` + const INTRINSIC_MARKER = Symbol.for("chant.intrinsic"); + class ArmPseudoParameter { + constructor(expression) { + this[INTRINSIC_MARKER] = true; + this.expression = expression; + } + toJSON() { return this.expression; } + } + export const ResourceGroupLocation = new ArmPseudoParameter("[resourceGroup().location]"); + export const Azure = { ResourceGroupLocation }; + export const CI = { CommitBranch: "$CI_COMMIT_BRANCH", DefaultBranch: "$CI_DEFAULT_BRANCH" }; + export const S3Actions = { ReadOnly: ["s3:GetObject", "s3:ListBucket"] }; + export function defaultTags(tags) { return tags; } + `; + + test("a lexicon package's plain-data export resolves and folds when referenced as a value", async () => { + const { lexicon, specifier } = await installLexiconPackage(LEXICON_SOURCE); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { CI, S3Actions } from ${JSON.stringify(specifier)}; + throw new Error("must never execute — sentinel for #1063 fold verification"); + export const branch = CI.CommitBranch; + export const rule = \`\${CI.CommitBranch} == \${CI.DefaultBranch}\`; + export const actions = S3Actions.ReadOnly; + `, + ); + + const result = await tryFoldFile(file, [], createFoldSession([], undefined, [lexicon])); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.exportedValues.get("branch")).toBe("$CI_COMMIT_BRANCH"); + // A template literal is the real test that the VALUE arrived, not a + // symbolic envelope: an envelope would stringify to "[object Object]". + expect(result.exportedValues.get("rule")).toBe("$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"); + expect(result.exportedValues.get("actions")).toEqual(["s3:GetObject", "s3:ListBucket"]); + }); + + test("a pseudo-parameter reached through the namespace stays the REAL live Intrinsic instance, prototype intact", async () => { + const { lexicon, specifier } = await installLexiconPackage(LEXICON_SOURCE); + await writeFile( + join(testDir, "resources.ts"), + ` + import { createResource } from ${JSON.stringify(runtimePath)}; + export const Group = createResource("Test::Group", "azure", {}); + `, + ); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { Azure } from ${JSON.stringify(specifier)}; + import { Group } from "./resources"; + export const group = new Group({ location: Azure.ResourceGroupLocation }); + `, + ); + + const result = await tryFoldFile(file, [], createFoldSession([], undefined, [lexicon])); + + expect(result.ok).toBe(true); + if (!result.ok) return; + const [, entity] = result.entities[0]; + const location = (entity as unknown as { props: { location: unknown } }).props.location; + // Not a plain-object copy: the generic revive walk would have rebuilt it + // as `{ expression: … }` and dropped `toJSON`, which is what actually + // reaches the serializer. + expect(isIntrinsic(location)).toBe(true); + expect((location as { toJSON(): unknown }).toJSON()).toBe("[resourceGroup().location]"); + // Identity: the very object the module exports, not a reconstruction — + // the same one a run-path import of this package would hand the file. + const mod = (await import(join(testDir, "node_modules", specifier, "index.js"))) as { + Azure: { ResourceGroupLocation: unknown }; + }; + expect(location).toBe(mod.Azure.ResourceGroupLocation); + }); + + test("a lexicon package NOT active for this build is not resolved", async () => { + const { specifier } = await installLexiconPackage(LEXICON_SOURCE); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { CI } from ${JSON.stringify(specifier)}; + export const branch = CI.CommitBranch; + `, + ); + + // The package is installed and importable — the ONLY thing missing is + // this build having loaded it as a lexicon. + const result = await tryFoldFile(file, [], createFoldSession([], undefined, ["aws"])); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toContain("unresolved identifier: CI"); + }); + + test("with no active lexicons at all, a bare specifier is skipped exactly as before", async () => { + const { specifier } = await installLexiconPackage(LEXICON_SOURCE); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { CI } from ${JSON.stringify(specifier)}; + export const branch = CI.CommitBranch; + `, + ); + + const result = await tryFoldFile(file); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toContain("unresolved identifier: CI"); + }); + + test("a non-lexicon package is never followed, even when it is installed right next to one that is", async () => { + const { lexicon } = await installLexiconPackage(LEXICON_SOURCE); + const vendorDir = join(testDir, "node_modules", "some-vendor-pkg"); + await mkdir(vendorDir, { recursive: true }); + await writeFile( + join(vendorDir, "package.json"), + JSON.stringify({ name: "some-vendor-pkg", version: "0.0.0", type: "module", exports: { ".": "./index.js" } }), + ); + await writeFile(join(vendorDir, "index.js"), `export const SETTINGS = { region: "us-east-1" };`); + + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { SETTINGS } from "some-vendor-pkg"; + export const region = SETTINGS.region; + `, + ); + + const result = await tryFoldFile(file, [], createFoldSession([], undefined, [lexicon])); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toContain("unresolved identifier: SETTINGS"); + }); + + test("a lexicon package's CALLABLE export is not bound as an identifier value", async () => { + const { lexicon, specifier } = await installLexiconPackage(LEXICON_SOURCE); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { defaultTags } from ${JSON.stringify(specifier)}; + export const tags = defaultTags; + `, + ); + + const result = await tryFoldFile(file, [], createFoldSession([], undefined, [lexicon])); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toContain("unresolved identifier: defaultTags"); + }); + + test("process.env still rejects, with the build-parameter guidance, even with an active lexicon package in scope", async () => { + const { lexicon, specifier } = await installLexiconPackage(LEXICON_SOURCE); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { CI } from ${JSON.stringify(specifier)}; + export const branch = CI.CommitBranch; + export const region = process.env.AWS_REGION; + `, + ); + + const result = await tryFoldFile(file, [], createFoldSession([], undefined, [lexicon])); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toContain(`ambient "process" read is not foldable`); + }); +}); diff --git a/packages/core/src/discovery/fold-import.ts b/packages/core/src/discovery/fold-import.ts index f313dbfdc6..9cd89c37a9 100644 --- a/packages/core/src/discovery/fold-import.ts +++ b/packages/core/src/discovery/fold-import.ts @@ -7,6 +7,7 @@ import { createRequire } from "node:module"; import { isDeclarable, type Declarable } from "../declarable"; import { isCompositeInstance, type CompositeInstance } from "../composite"; import { isAttrRefLike } from "../utils"; +import { isIntrinsic } from "../intrinsic"; import { collectConsts, foldResource, @@ -171,14 +172,58 @@ export interface FoldSession { * doesn't use build-time parameters pays nothing extra here. */ readonly buildParams?: Readonly>; + /** + * chant #1063 — the exact package specifiers of the lexicons LOADED for + * this build (`@intentius/chant-lexicon-aws`, …), derived from the lexicon + * names the build already resolved (`resolveProjectLexicons` -> + * `loadPlugins`, see ../cli/plugins.ts). This is the entire allowlist + * {@link buildExternals} will follow a bare import specifier into — see + * {@link activeLexiconPackage} for why the set is matched by TEXT and + * built from names the build already knows, rather than by resolving + * specifiers to find out what they are. + * + * Empty when the caller supplied no lexicon list, which disables + * lexicon-package resolution entirely rather than falling back to + * something more permissive: "an active lexicon of this build" is the + * boundary, and a build that can't say what its lexicons are hasn't + * established one. + */ + readonly lexiconPackages: ReadonlySet; +} + +/** + * chant #1063 — the package specifier a lexicon NAME (`"aws"`, `"gitlab"`) + * is installed under. The one naming convention the whole CLI already + * depends on: `loadPlugin(name)` imports exactly this + * (../cli/plugins.ts), `detectLexicons` scans source for exactly this + * (../detectLexicon.ts), and `chant init` writes exactly this into + * package.json. + */ +export function lexiconPackageName(lexiconName: string): string { + return `@intentius/chant-lexicon-${lexiconName}`; } -/** Create a fresh, empty {@link FoldSession}. */ +/** + * Create a fresh, empty {@link FoldSession}. + * + * @param lexicons - chant #1063: the lexicon NAMES active for this build + * (`["aws", "k8s"]`). Converted to package specifiers via + * {@link lexiconPackageName}; see {@link FoldSession.lexiconPackages}. + */ export function createFoldSession( intrinsics: readonly IntrinsicDef[] = [], buildParams?: Readonly>, + lexicons: readonly string[] = [], ): FoldSession { - return { intrinsics, cache: new Map(), stack: [], importCache: new Map(), resolvePathCache: new Map(), buildParams }; + return { + intrinsics, + cache: new Map(), + stack: [], + importCache: new Map(), + resolvePathCache: new Map(), + buildParams, + lexiconPackages: new Set(lexicons.map(lexiconPackageName)), + }; } /** @@ -805,6 +850,100 @@ function paramsModulePath(): string | null { return paramsModulePathMemo; } +/** + * chant #1063 — is `specifier` a bare import of a package that is an ACTIVE + * LEXICON of this build? Returns the specifier itself when so, `undefined` + * otherwise. + * + * Three deliberate restrictions, each of which is the point rather than an + * omission: + * + * - **Text only, no resolution.** The answer is a `Set.has` on a set built + * from the lexicon names the build ALREADY resolved before discovery ran + * (`resolveProjectLexicons` -> `loadPlugins`). Nothing is probed, read, or + * resolved to decide whether a specifier is in scope — so an import of + * some unrelated package costs a string comparison and is then left alone, + * never resolved "just to find out what it is". That matters here more + * than anywhere: `resolveModulePath`'s bare branch can fall through to + * `createRequire(fromFile).resolve(specifier)`, measured at up to ~361s + * for the first resolution of a genuinely new bare specifier in a process + * (see {@link bareSpecifierPathCache}/{@link fastResolveBareSpecifier} — + * this exact class of cost regressed twice during chant#1020). + * + * - **Exact package specifier, no subpaths.** `@intentius/chant-lexicon-aws` + * matches; `@intentius/chant-lexicon-aws/actions` does not. Every lexicon + * re-exports its whole public surface from its barrel and every example + * imports it that way, so subpaths buy nothing — and they would cost + * something real: {@link fastResolveBareSpecifier} only recognizes a + * package ROOT (it looks for `//package.json`), + * so a subpath specifier falls through to exactly the slow + * `createRequire().resolve()` path this restriction exists to avoid. + * + * - **Lexicons of THIS build only.** Not "any `@intentius/chant-lexicon-*` + * package on disk", and emphatically not "any bare specifier". A lexicon + * the build did not load is as out of scope as `node:fs`. + */ +function activeLexiconPackage(specifier: string, lexiconPackages: ReadonlySet): string | undefined { + return lexiconPackages.has(specifier) ? specifier : undefined; +} + +/** + * chant #1063 — resolve one named import binding against an active lexicon + * package's REAL exports, for {@link buildExternals}. + * + * The lexicon module is imported (through the session-wide + * {@link FoldSession.importCache}, so at most one real `import()` per package + * per build) and the requested export read straight off it. That is the same + * module object the run path gets — `importModule` is a plain dynamic + * `import()` with no cache-busting — so what fold captures here is not a + * reconstruction of the lexicon's data but the identical value, down to + * object identity for `Azure.ResourceGroupLocation`-style singletons. It is + * also the same two-step (resolve path, then import) that + * `resolveImportedExport` has always used to reach a lexicon's constructors + * and intrinsic functions; the only thing new is that a plain DATA export is + * now reachable too. + * + * Callable exports are deliberately excluded. A lexicon's functions — its + * resource classes, composite factories, intrinsic implementations — already + * have dedicated resolution paths that know how to INVOKE them + * (`resolveResourceEntity`, `resolveCallExpression`, `reviveFoldedValue`), and + * binding them as plain identifier values here would widen what folds in ways + * this issue neither needs nor measured: none of the references #1063 exists + * to unblock (`Azure`, `GCP`, `S3Actions`, gitlab's `CI`) is a function. + * + * Returns `undefined` — never throws — for a package that isn't an active + * lexicon, an export the package doesn't have, a callable export, or an + * import that fails. The binding is then simply absent from `externals`, + * exactly as before, and `fold()`'s ordinary "unresolved identifier" failure + * still fires if the name is actually referenced. + */ +async function resolveActiveLexiconExport( + binding: ImportBinding, + fromFile: string, + session: FoldSession, +): Promise<{ value: unknown } | undefined> { + if (!activeLexiconPackage(binding.specifier, session.lexiconPackages)) return undefined; + + let modulePath: string; + try { + modulePath = resolveModulePathMemoized(binding.specifier, fromFile, session.resolvePathCache); + } catch { + return undefined; + } + + let mod: Record; + try { + mod = await importModuleMemoized(modulePath, session.importCache); + } catch { + return undefined; + } + + if (!(binding.imported in mod)) return undefined; + const value = mod[binding.imported]; + if (typeof value === "function") return undefined; + return { value }; +} + // ───────────────────────────────────────────────────────────────────────── // Resolution: given the scan + import map, compute the REAL runtime value // (Declarable | CompositeInstance) each foldable export would have had if @@ -1161,7 +1300,17 @@ async function reviveFoldedValue(value: FoldedValue, ctx: ResolveCtx, requireLiv // destroying the very identity #1020 exists to preserve. Passed through // completely unchanged, exactly like `resolveCallExpression`'s own // `live.value` passthrough for a composite-call argument. - if (isAttrRefLike(value) || isDeclarable(value) || isCompositeInstance(value)) { + // chant #1063 adds the third kind of real object cross-file resolution can + // now put here: a live `Intrinsic` instance read off an active lexicon + // package (`Azure.ResourceGroupLocation`, `GCP.ProjectId` — see + // `resolveActiveLexiconExport`). Same hazard, same fix: the generic walk + // below would rebuild it as a plain `{}` copy, dropping the prototype that + // carries `toJSON()` and so serializing `{}` where the run path emits + // `[resourceGroup().location]`. `isIntrinsic` keys off + // `Symbol.for("chant.intrinsic")` (../intrinsic.ts), a GLOBAL symbol, so it + // holds across separately-loaded copies of chant-core the way a bare + // `instanceof` would not. + if (isAttrRefLike(value) || isDeclarable(value) || isCompositeInstance(value) || isIntrinsic(value)) { return value; } @@ -1585,10 +1734,36 @@ async function buildExternals( } if (!isProjectFileSpecifier(binding.specifier)) { - // Every other bare specifier (a lexicon/vendor package) is left alone - // here, exactly as before #1064: it resolves lazily, through the - // pre-existing `importModule` mechanism, only once a constructor/ - // composite-factory/intrinsic tag actually consumes it. + // chant #1063 — a bare specifier naming one of THIS BUILD's active + // lexicon packages resolves to that package's real export, so a plain + // data export a lexicon publishes (`Azure`/`GCP`'s pseudo-parameter + // namespaces, AWS's `S3Actions`, gitlab's `CI`) is an ordinary + // identifier value here rather than fold's most common remaining + // "unresolved identifier" failure. See + // {@link resolveActiveLexiconExport} for the allowlist, the no-cold- + // resolution rule, and why callable exports stay out. + // + // No `liveSources` edge is recorded for what comes back, unlike the + // project-file case just below. `liveSources` (chant #1044) exists so + // that a folded file which captured ANOTHER FILE's objects is + // invalidated when that file is forced back to run — a fold/run + // disagreement about identity. A lexicon package has no such duality: + // it is not a discovered source file, `planFoldTaint` never considers + // it (it filters to the discovered `files` set), it never falls back to + // run, and both paths reach it through the identical un-cache-busted + // `import()` of the identical resolved path — so the object fold + // captures IS the object the run path holds. There is nothing for the + // two sides to disagree about, hence nothing to taint. + const lexiconExport = await resolveActiveLexiconExport(binding, file, session); + if (lexiconExport) { + externals.set(localName, lexiconExport.value); + continue; + } + // Every other bare specifier (a non-lexicon vendor package, a lexicon + // this build didn't load) is left alone here, exactly as before #1064: + // it resolves lazily, through the pre-existing `importModule` + // mechanism, only once a constructor/composite-factory/intrinsic tag + // actually consumes it. continue; } let targetPath: string; diff --git a/packages/core/src/discovery/index.ts b/packages/core/src/discovery/index.ts index d0c5ca3a6e..7dc4ef926a 100644 --- a/packages/core/src/discovery/index.ts +++ b/packages/core/src/discovery/index.ts @@ -56,6 +56,19 @@ export interface DiscoveryOptions { */ intrinsics?: IntrinsicDef[]; + /** + * chant #1063 — the lexicon NAMES loaded for this build (`["aws", "k8s"]`), + * i.e. what `resolveProjectLexicons()` returned and `loadPlugins()` then + * imported. Threaded into the fold session as the ALLOWLIST of packages a + * bare import specifier may be resolved into, so a lexicon's plain data + * exports (`Azure`/`GCP`'s pseudo-parameter namespaces, AWS's `S3Actions`, + * gitlab's `CI`) fold as identifier values instead of failing the file. + * Only meaningful when {@link fold} is set. Default: none — a caller that + * doesn't say which lexicons are active gets no bare-specifier resolution + * at all, rather than a looser fallback. + */ + lexicons?: readonly string[]; + /** * chant #1045 Phase 2 — opt-in: whatever would otherwise reach the * in-process `importModule` step (every file, when {@link fold} isn't set; @@ -156,7 +169,9 @@ export async function discover(path: string, options?: DiscoveryOptions): Promis // a project file imported by several others is folded exactly once, so // every referrer shares the identical constructed Declarable/ // CompositeInstance objects rather than each building its own copy. - const foldSession = options?.fold ? createFoldSession(options.intrinsics, buildParamValuesMap) : undefined; + const foldSession = options?.fold + ? createFoldSession(options.intrinsics, buildParamValuesMap, options.lexicons) + : undefined; if (options?.fold) { for (const file of files) { foldAttempts.set(file, await tryFoldFile(file, options.intrinsics, foldSession)); From b0b43893e9c200223479abee2c993ec817e10047 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Sun, 26 Jul 2026 21:24:07 -0600 Subject: [PATCH 2/3] =?UTF-8?q?test(fold):=20measure=20the=20lexicon-packa?= =?UTF-8?q?ge=20coverage=20jump=20=E2=80=94=2032/98=20to=2053/98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The differentials build through core's `build()` rather than the CLI, so they have to reproduce `cli/commands/build.ts`'s active-lexicon step the same way they already reproduce its `intrinsics` one — otherwise fold is measured without the allowlist real `chant build --fold` gives it. Corpus entries now carry their lexicon names: the full set for the root tutorials (which deliberately mix lexicons), the one lexicon for a `lexicons/*/examples/*` fixture, matching how serializers and intrinsics are already selected. 21 entries move run-fallback to fold: all 13 azure examples and all 8 gcp examples. Each was a single file failing on `Azure.` / `GCP.`. Nothing else changes — 45 entries still fall back, drift stays 0, and the suite runs in 4.31s against 4.33s before. The same change clears every remaining `S3Actions`, `CI` and value-position `AWS` failure in the corpus, but those sit in `docs-snippets` entries with several unrelated blockers apiece, so they move no entry on their own. --- .../docs/concepts/typescript-as-data.mdx | 2 +- examples/differential-corpus.ts | 22 ++++++++++- examples/fold-differential.test.ts | 39 +++++++++++++++++-- examples/sandbox-differential.test.ts | 2 + scripts/generate-fold-coverage.ts | 2 +- 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/docs/src/content/docs/concepts/typescript-as-data.mdx b/docs/src/content/docs/concepts/typescript-as-data.mdx index 29a143ed5c..a948bce168 100644 --- a/docs/src/content/docs/concepts/typescript-as-data.mdx +++ b/docs/src/content/docs/concepts/typescript-as-data.mdx @@ -287,7 +287,7 @@ None of this is something you opt into piecemeal or write differently for — it ### Fold coverage today {/* GENERATED:fold-coverage:start */} -As of this measurement, **32 of 98** example projects in the corpus fold completely — every file in them reduces to a value with zero module execution. The remaining **66** have at least one file that falls back to running. +As of this measurement, **53 of 98** example projects in the corpus fold completely — every file in them reduces to a value with zero module execution. The remaining **45** have at least one file that falls back to running. {/* GENERATED:fold-coverage:end */} This is measured over the same corpus [`just fold-differential`](#byte-identical-output) builds both ways: every tutorial under `examples/*/src`, plus each lexicon's own build fixtures under `lexicons/*/examples/*/src`. It's a count of chant's own example suite, not a sample of real-world source — read it as "how much of chant's examples fold today," not as an estimate for any other codebase. diff --git a/examples/differential-corpus.ts b/examples/differential-corpus.ts index 097a86465e..7780257427 100644 --- a/examples/differential-corpus.ts +++ b/examples/differential-corpus.ts @@ -124,8 +124,21 @@ export interface CorpusEntry { serializers: Serializer[]; /** Intrinsics to fold with (chant #1039) — see {@link ALL_INTRINSICS}/{@link INTRINSICS_BY_LEXICON}. */ intrinsics: IntrinsicDef[]; + /** + * chant #1063 — the lexicon NAMES active for this entry, matching the + * serializer/intrinsic selection below. The differentials build through + * core's `build()` rather than the CLI, so — exactly as they already do for + * `intrinsics` — they have to reproduce `cli/commands/build.ts`'s own + * `options.plugins.map(p => p.name)` step, or the fold path would be + * measured without the bare-specifier allowlist real `chant build --fold` + * gives it. + */ + lexicons: string[]; } +/** Every lexicon name the corpus can build with — the keys of {@link SERIALIZER_BY_LEXICON}. */ +export const ALL_LEXICONS: string[] = Object.keys(SERIALIZER_BY_LEXICON); + function isDir(p: string): boolean { try { return statSync(p).isDirectory(); @@ -169,7 +182,13 @@ export function discoverCorpus(): CorpusEntry[] { if (!dirent.isDirectory()) continue; const srcDir = resolve(examplesDir, dirent.name, "src"); if (isDir(srcDir)) { - entries.push({ name: `examples/${dirent.name}`, srcDir, serializers: ALL_SERIALIZERS, intrinsics: ALL_INTRINSICS }); + entries.push({ + name: `examples/${dirent.name}`, + srcDir, + serializers: ALL_SERIALIZERS, + intrinsics: ALL_INTRINSICS, + lexicons: ALL_LEXICONS, + }); } } @@ -189,6 +208,7 @@ export function discoverCorpus(): CorpusEntry[] { srcDir, serializers: [serializer], intrinsics: INTRINSICS_BY_LEXICON[lexDirent.name] ?? [], + lexicons: [lexDirent.name], }); } } diff --git a/examples/fold-differential.test.ts b/examples/fold-differential.test.ts index ded3a071c9..ee34e1f7d0 100644 --- a/examples/fold-differential.test.ts +++ b/examples/fold-differential.test.ts @@ -115,6 +115,18 @@ const report: ReportRow[] = []; * stopped on `Azure.ResourceGroupLocation` — a lexicon-package namespace * access, #1063. That is the measured ceiling this PR reports: azure's * remaining corpus is gated on #1063, not on #1044. + * + * chant #1063 grew it from 32 to 53 — the largest single jump so far, and + * the whole of azure's and gcp's corpora at once. The 21 added entries are + * every azure example (13) and every gcp example (8): each had exactly one + * file, failing on `Azure.` / `GCP.` — an + * identifier imported from the LEXICON PACKAGE rather than from a sibling + * project file, which #1020's cross-file resolution skipped by construction + * (it followed relative specifiers only). Following a bare specifier into an + * ACTIVE lexicon package also cleared every remaining `S3Actions` (aws), + * `CI` (gitlab) and value-position `AWS` (aws) failure in the corpus, but + * those all live in `docs-snippets` entries carrying several unrelated + * blockers apiece, so they move no entry on their own. */ const EXPECTED_FOLD: readonly string[] = [ "examples/alert-triage", @@ -135,7 +147,28 @@ const EXPECTED_FOLD: readonly string[] = [ "lexicons/aws/examples/multi-service-alb", "lexicons/aws/examples/rds-postgres", "lexicons/aws/examples/vpc", + "lexicons/azure/examples/aks-cluster", + "lexicons/azure/examples/basic-storage", + "lexicons/azure/examples/container-instance", + "lexicons/azure/examples/cosmos-db", + "lexicons/azure/examples/function-app", + "lexicons/azure/examples/key-vault", + "lexicons/azure/examples/multi-resource", + "lexicons/azure/examples/private-endpoint", + "lexicons/azure/examples/redis-cache", + "lexicons/azure/examples/service-bus", + "lexicons/azure/examples/sql-database", + "lexicons/azure/examples/vnet-vms", + "lexicons/azure/examples/web-app", "lexicons/docker/examples/basic-app", + "lexicons/gcp/examples/basic-bucket", + "lexicons/gcp/examples/cloud-function", + "lexicons/gcp/examples/cloud-run", + "lexicons/gcp/examples/cloud-sql", + "lexicons/gcp/examples/cloud-storage-lifecycle", + "lexicons/gcp/examples/gke-cluster", + "lexicons/gcp/examples/pubsub", + "lexicons/gcp/examples/vpc-network", "lexicons/gitlab/examples/node-pipeline", "lexicons/gitlab/examples/python-pipeline", "lexicons/helm/examples/composites-basic", @@ -182,7 +215,7 @@ async function buildBothWays( entry: CorpusEntry, ): Promise<{ run: Awaited>; fold: Awaited>; neededIsolation: boolean }> { const run = await build(entry.srcDir, entry.serializers, undefined, { fold: false }); - const fold = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics }); + const fold = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics, lexicons: entry.lexicons }); if (outputsEqual(normalizeOutputs(fold.outputs), normalizeOutputs(run.outputs))) { return { run, fold, neededIsolation: false }; @@ -191,7 +224,7 @@ async function buildBothWays( vi.resetModules(); const freshRun = await build(entry.srcDir, entry.serializers, undefined, { fold: false }); vi.resetModules(); - const freshFold = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics }); + const freshFold = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics, lexicons: entry.lexicons }); return { run: freshRun, fold: freshFold, neededIsolation: true }; } @@ -209,7 +242,7 @@ describe("fold differential — fold output === run output (#1025, epic #1019)", // both-ways comparison + module-reset retry; that retry (which reloads the // whole module graph) is what makes the full corpus intractable now that // many entries fall back, and it buys nothing for entries we don't gate. - const probe = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics }); + const probe = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics, lexicons: entry.lexicons }); const mode = classifyFoldMode(probe.foldDecisions); if (mode !== "fold") { report.push({ name: entry.name, mode, identical: true, fileCount: probe.foldDecisions.length, neededIsolation: false }); diff --git a/examples/sandbox-differential.test.ts b/examples/sandbox-differential.test.ts index a18ae21ea7..0a76a78cc3 100644 --- a/examples/sandbox-differential.test.ts +++ b/examples/sandbox-differential.test.ts @@ -216,6 +216,7 @@ async function buildBothWays(entry: CorpusEntry) { fold: true, sandbox: true, intrinsics: entry.intrinsics, + lexicons: entry.lexicons, }); const runResult = await run(); @@ -276,6 +277,7 @@ describe("sandbox differential — sandboxed-run output === in-process-run outpu const plainFold = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics, + lexicons: entry.lexicons, }); expect( classifyMode(sandboxedResult.foldDecisions), diff --git a/scripts/generate-fold-coverage.ts b/scripts/generate-fold-coverage.ts index 321a1d70d5..b8f6ea66ef 100644 --- a/scripts/generate-fold-coverage.ts +++ b/scripts/generate-fold-coverage.ts @@ -30,7 +30,7 @@ const corpus = discoverCorpus(); let foldCount = 0; for (const entry of corpus) { - const result = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics }); + const result = await build(entry.srcDir, entry.serializers, undefined, { fold: true, intrinsics: entry.intrinsics, lexicons: entry.lexicons }); const mode = classifyFoldMode(result.foldDecisions); if (mode === "fold") foldCount++; console.error(` ${mode.padEnd(12)} ${entry.name}`); From a17b29ab5a22dc568cf99b8489a5a6124d48ac9f Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Sun, 26 Jul 2026 21:29:14 -0600 Subject: [PATCH 3/3] docs(fold): lexicon package exports in the subset, and the post-#1063 blocker snapshot Adds the new subset bullet, and refreshes the measured blocker breakdown the page carries: the lexicon-package cause is gone (116 files, 36 entries -> 0), a nested `new Type(...)` used as a value is now the largest at 63 files and 22 sole-blocker entries, and the per-lexicon lines read azure 13/13, gcp 8/8, aws 12/18. --- docs/src/content/docs/concepts/typescript-as-data.mdx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/src/content/docs/concepts/typescript-as-data.mdx b/docs/src/content/docs/concepts/typescript-as-data.mdx index a948bce168..8205bd7e23 100644 --- a/docs/src/content/docs/concepts/typescript-as-data.mdx +++ b/docs/src/content/docs/concepts/typescript-as-data.mdx @@ -269,6 +269,7 @@ Fold covers more than a single leaf resource now: - **Registered intrinsic tagged templates** — a lexicon can register a tagged template (e.g. a string-substitution helper) as foldable; when it's registered, an interpolation inside it folds like any other value in the subset. A tagged template whose tag *isn't* registered falls outside the subset. See your lexicon's intrinsics page for which of its intrinsics are tagged templates. - **Registered intrinsic calls** — the same, for an intrinsic authored as a plain call (`Ref(...)`, `Concat(...)`), where its lexicon has opted that intrinsic in (#1044). Arguments fold by the ordinary subset rules; the real function is resolved through the file's own imports and invoked, so the intrinsic object is the one the run path would have built. Opt-in is per intrinsic and off by default — see [Registered intrinsic calls](#registered-intrinsic-calls). - **Cross-file references** — an imported `const`, or an imported resource referenced through an attribute, resolves through the module graph and folds in the defining file's own scope, including re-export chains (#1020). Each cross-file export folds exactly once per build and every referrer shares that one instance, so a symbolic reference always points at the same entity the defining file produced. An import cycle is rejected with a located error rather than followed. +- **Lexicon package exports** — the same resolution follows a bare import into a lexicon package, so a lexicon's plain data exports fold as values: Azure's and GCP's pseudo-parameter namespaces (`Azure.ResourceGroupLocation`, `GCP.ProjectId`), AWS's `S3Actions`, GitLab's `CI` (#1063). Only lexicons this build actually loaded are followed, and only the package itself, never a subpath or an unrelated package — the boundary is the lexicon list your project already declares or chant already detected, not `node_modules` at large. The lexicon module is imported the same way the run path imports it, so what fold captures is the same object, not a copy. What still forces a fallback to run, per file: **a function call used as a value that is neither a registered authoring helper nor an opted-in intrinsic** — your own helper, an array `.map(...)`, a method call, an intrinsic whose lexicon has not opted it in. Also: a composite call or `new Type(...)` nested as a *value* inside something else rather than being the file's own top-level export, a re-export, `export default`, `let`/`var`, and an exported function or class declaration. @@ -294,9 +295,9 @@ This is measured over the same corpus [`just fold-differential`](#byte-identical That corpus is also chant's own maintained examples, and some of them are expected to be rewritten into foldable shapes over time, or dropped. Both changes move this number without the folder gaining or losing any actual capability: rewriting an example raises the count for a reason unrelated to what `--fold` can do, and adding or removing an example moves the denominator the same way. Treat a change here as "the corpus changed," not as evidence either way about fold coverage of your own project. -As measured on the corpus after #1044 (chant `1fb1b375`, per-file fallback reasons classified by cause): a function call used as a value blocks 37 files and is the only blocker in 9 entries — down from 77 files and 21 entries before opting the AWS and Azure intrinsics in. What's left there is a lexicon that hasn't been audited yet (github's `Checkout`, 6 entries; helm's `include`/`printf`, 3) plus array `.map(...)` and project-local helpers, which are arbitrary JavaScript and stay rejected by construction. Cross-file references into a lexicon package's own exports (rather than a project's own source files) now block 116 files across 36 entries, tracked as [#1063](https://github.com/INTENTIUS/chant/issues/1063), and are the largest remaining cause. +As measured on the corpus after #1063 (per-file fallback reasons classified by cause): cross-file references into a lexicon package's own exports no longer block anything — that cause went from 116 files across 36 entries to zero. The largest remaining cause is a `new Type(...)` nested as a value inside something else: 63 files, and the only blocker in 22 entries. Next is a function call used as a value that is neither a registered authoring helper nor an opted-in intrinsic: 38 files, the only blocker in 9 entries, mostly a lexicon that hasn't been audited yet (github's `Checkout`, helm's `include`/`printf`) plus array `.map(...)` and project-local helpers, which are arbitrary JavaScript and stay rejected by construction. Unresolved identifiers still block 67 files, but every one of those is now a project-file chain the folder doesn't reach yet or an environment read it refuses on purpose — 9 of them are `process.env`. -Per lexicon, so the two can be judged separately: the AWS corpus went from 4 of 18 entries folding to **12 of 18**, and the 6 that remain are blocked by cross-file references, shape gaps, and composite-factory calls — not by intrinsics. The Azure corpus went from **0 of 13 to 0 of 13**: `Concat(...)` stopped blocking both entries where it was the only blocker, and both then stopped on `Azure.ResourceGroupLocation` used as a plain value, which is #1063. Azure's fold coverage is capped at zero by that, not by anything #1044 could have fixed. This is also the correction to what #1039 predicted: the intrinsics wiring was called "the single biggest lever" and moved one entry; the call form moved eight; and for Azure specifically the lever that matters is a different issue entirely. +Per lexicon, so the causes can be judged separately: the Azure corpus went from **0 of 13 to 13 of 13** and the GCP corpus from **0 of 8 to 8 of 8**. Both were capped at zero by a single line per example — a pseudo-parameter read through the lexicon's own namespace — and nothing else. AWS holds at **12 of 18**; its remaining 6 are nested constructors and composite-factory calls, unaffected by #1063 even though the same change cleared every `S3Actions` and value-position `AWS` failure in that corpus. This is the second correction to what #1039 predicted: the intrinsics wiring was called "the single biggest lever" and moved one entry, the call form moved eight, and reaching into lexicon package exports moved twenty-one. These counts are a snapshot, not refreshed by the mechanism above; they'll drift from the corpus over time the same way the rest of this page would without #1062. One gap the earlier snapshot named — a resource constructor whose first argument isn't the props object literal — is closed as of #1082: constructor arguments are folded positionally, so a class like the AWS `Parameter` (`new Parameter("String", {...})`) folds like any other.