Skip to content

fix(cli): name the packages a scaffolded template needs - #6816

Closed
thedjpetersen wants to merge 1 commit into
mainfrom
fix/cli-template-deps
Closed

thedjpetersen wants to merge 1 commit into
mainfrom
fix/cli-template-deps

Conversation

@thedjpetersen

Copy link
Copy Markdown
Contributor

Most Astryx page templates import an icon or chart package, such as @heroicons/react or recharts. When astryx template <name> <path> scaffolds one into a project that doesn't have those packages, it reports success and the project's next build fails on an unresolved import. This PR makes the scaffold name the missing packages and print the one command that installs them with the project's package manager, in both the text output and the --json data. astryx build marks the templates it recommends the same way.

Two terminal panels side by side. Before: scaffolding the dashboard template says only "Copied template", and vite build then fails to resolve "recharts". After: the same scaffold warns that @heroicons/react and recharts are missing, prints "npm install @heroicons/react@2 recharts@3" in text and JSON, and the build exits 0 once that line runs.

At a glance

  • dashboard in a fresh Vite + Astryx project: before, "Copied template…" and then vite build exits 1 with no hint. After, the output lists missingPackages: @heroicons/react, recharts and installCommand: npm install @heroicons/react@2 recharts@3, and running that line makes the build exit 0.
  • Unchanged path: a project that already lists the packages sees only the "Copied template…" line (missingPackages: [], installCommand: null). Exit codes, existing JSON fields, and build's ranking and commands don't change.
  • Tests: 8 new contract tests in template-packages.test.mjs, 7 of which fail on main (the eighth is the unchanged path), plus 12 unit tests for the import reader and install line. 553 focused CLI tests pass.
  • Coverage: 46 of 55 page templates and 86 of 659 block templates import a package a fresh project lacks. All of them are now reported.
  • Compatibility: additive patch (two new fields on template.copy and build.kit). There is no Storybook story because this is CLI output; evidence/repro.sh replaces it.
Second view: `astryx build "analytics dashboard"`

Two terminal panels of `astryx build "analytics dashboard"`. Before: the recommended dashboard templates list only a name and a command. After: each one also lists missingPackages (@heroicons/react, recharts), and the start lists the npm install command.

Every screenshot, measurement file and repro script for this PR: astryx-pr-evidence/cli-template-deps


User impact

Anyone who scaffolds a page or block template into a project with astryx template <name> <path>, whether a person or a coding agent following astryx build. 46 of the 55 page templates (44 of the 52 ready ones) and 86 of the 659 block templates import @heroicons/react, recharts or lucide-react. A fresh Vite + Astryx project lists none of those. On main the scaffold reports Copied template to …, exit 0, and the project's next build fails on an unresolved import. Nothing in the text or the --json data says why.

In a blind agent-built UI benchmark, 18 of 36 builds on main's template-first workflow ran into exactly this and had to delete the scaffolded code. Once the template-first rule was reverted, 4 of 36 did.

After this PR the scaffold still writes the file, then names the packages the file imports that the project doesn't list, plus the one command that installs them with the project's package manager. astryx build marks the templates it recommends the same way, so a builder sees the cost before scaffolding.

Problem and solution fit

  1. Why does the defect occur? A template is starter source, and scaffolding copies its imports into the project as they are. The copy leaf never compares those imports with what the project declares. Its receipt is only {template, outputDir, fileName, filesCopied}.
  2. Why does it harm the task? The scaffold looks like a success. The failure shows up later, in the build, as a bundler error about a module the builder never chose. An agent that sees Rollup failed to resolve import "recharts" usually rips the page out. It rarely installs the package: nothing told it the template depends on the package, or which version line to use.
  3. Why does that matter? astryx build always names a page template to start from (spec:AST-048 FR1). So the broken path is the recommended one, not an edge case. The page frame and spacing the template carries get thrown away together with the imports.

The fix closes the gap at the point where it opens. The command that writes the imports now reports the ones the project can't resolve, and it reports them as data an agent can act on (installCommand), not just as prose.

Expected behavior and authority

  • spec:AST-048 (current) makes a page template the start of every page build (FR1/FR2), and each start is runnable exactly as printed (FR5). A start that scaffolds a file which can't build breaks that promise in practice. This PR changes no ranking, start, or command. It adds data next to them, as FR10/FR11 allow ("new data arrives as new fields").
  • spec:AST-017 FR13 says every response field sits in the canonical response type, contract tests, the text projection, and the schema docs. The two new fields are in all four. FR5 covers additive fields and says they are non-breaking. FR3 counts exit behavior as part of the contract, and exit codes don't change.
  • docs/contributing/cli-conventions.md: text output is a projection of the JSON with matching field names (missingPackages: / installCommand: lines), there are no prompts, and there are no side effects beyond the file written.

Records searched before drafting: spec:AST-046, spec:AST-047, spec:AST-048, spec:AST-017, architecture:cli-surface, the CLI conventions guide, template-integration.test.mjs, and git log for template dependency or install work. No current record or landed change owns "a scaffold names its missing packages", and this PR adds no record. I could not search open pull requests from the environment that prepared this PR, so a reviewer should do a quick duplicate check.

Smallest restoration

I compared three models against the code:

Model Verdict
(a) Detect at scaffold time. Read the written file's imports and check them against the project's package.json files. Chosen. It is derived from the source, so it can't drift. It changes no template. It covers integration templates too.
(b) Templates declare their requirements in template.doc.mjs, and the CLI validates them Would touch about 130 doc files and create a second copy of each template's import list that goes stale when the source changes. Validation would still need (a)'s import reader.
(c) Templates stop depending on icon and chart packages Rewrites about 130 files across 132 templates, changes how they look, and wouldn't stop the next template from adding an import. It is a separate design decision.

What (a) does:

  • foundation/discovery/template-packages.mjs (new, about 200 lines):
    • importedPackages(source) does a Babel parse and reads top-level import / export … from, including type-only imports, since tsc needs those resolved too. It ignores relative paths, Node builtins, scheme: ids, # subpath imports, and @/ or ~/ path aliases. Import-like text inside comments, strings, and JSX is not matched.
    • declaredPackages(dir) unions every package.json from the target directory upward (node resolution walks up, so a workspace root's dependencies count), plus each package's own name.
    • templatePackageNeeds(...) returns {missingPackages, installCommand}. The command uses the project's detected package manager (npm install / pnpm add / yarn add / bun add, with npm as the fallback, the same one getRunPrefix uses). Each package is pinned to the major line (or the minor line below 1.0) that the template's own shipping package declares. For Core templates that is @astryxdesign/cli's devDependencies, so @heroicons/react@2 recharts@3. Ranges it can't read, such as *, catalog:, or unions, install the bare name. No spec contains shell metacharacters, so the line runs as printed in any shell. When the project's package.json isn't in cwd, the command starts with cd <dir> &&.
  • foundation/env/package-manager.mjs: adds getAddPrefix() next to getRunPrefix() / getDlxPrefix().
  • api/template/copy/copy.mjs: after writing, adds missingPackages and installCommand to the template.copy data. The file is still written, nothing is installed, and the exit code stays 0.
  • api/build/_adapter.mjs + kit/kit.mjs: start and each alternatives[] entry carry the same two fields, computed for the project where build runs. That is three extra parses per build, about +50 ms on roughly 2.1 s.
  • Text (clients/cli/commands/template.mjs, build.mjs): a [warn] line followed by a record() with the two fields, named as in the JSON. The record renderer drops both fields when nothing is missing, so the unchanged path prints exactly what it printed before.
  • Docs: template.type.mjs / build.type.mjs typedefs, the FunctionDoc returns plus a new API example, the CommandDoc description plus two new examples (text with output, and --json), build.doc.mjs, response-types.doc.mjs, and the regenerated README table.
  • Supporting, one small hunk: cli-self-docs.mjs now renders a command example's documented output field, which the doc type has always declared and no renderer showed. Without it, the new example's output would be invisible in astryx docs cli/commands/template. No existing command example sets output, so no other page changes. I can split this out on request.

Removed or split, not in this PR: agent-block wording, playbook wording, template edits, auto-install, a flag.

Representative before/after

The CLI output is the example. Scaffolding dashboard into a fresh Vite + Astryx project that lists @astryxdesign/core, @astryxdesign/theme-neutral, @stylexjs/stylex, react, and react-dom:

// Before (main)
const {data} = await template('dashboard', {targetPath: './src/pages/dashboard'});
// data -> {template: 'dashboard', outputDir: 'src/pages/dashboard', fileName: 'page.tsx', filesCopied: 1}
// $ vite build -> [vite]: Rollup failed to resolve import "recharts" from ".../src/pages/dashboard/page.tsx".  (exit 1)
// After (this PR)
const {data} = await template('dashboard', {targetPath: './src/pages/dashboard'});
// data -> {template: 'dashboard', outputDir: 'src/pages/dashboard', fileName: 'page.tsx', filesCopied: 1,
//          missingPackages: ['@heroicons/react', 'recharts'],
//          installCommand: 'npm install @heroicons/react@2 recharts@3'}
if (data.installCommand) run(data.installCommand); // then: vite build -> exit 0

Terminal, after:

$ astryx template dashboard src/pages/dashboard
Copied template to src/pages/dashboard/page.tsx

[warn] The template imports packages this project does not list. It will not build until they are installed:

missingPackages: @heroicons/react, recharts
installCommand:  npm install @heroicons/react@2 recharts@3

astryx build "analytics dashboard", after. The same two lines appear on each alternative:

TEMPLATE
Matches the idea. Scaffold it, then replace its content. Keep its layout and spacing.

name:            dashboard
description:     Three-band analytics: a row of headline tiles, then charts, then supporting tables, all re-reading from one global filter bar.
command:         npx astryx template dashboard --type page <path>
missingPackages: @heroicons/react, recharts
installCommand:  npm install @heroicons/react@2 recharts@3

Unchanged path: when the project already lists them, the output is Copied template to src/pages/again/page.tsx only, and the data carries missingPackages: [] and installCommand: null.

Evidence

  • Reproduction before the change: [repro.sh](https://github.com/thedjpetersen/astryx-pr-evidence/blob/main/cli-template-deps/repro.sh) <main checkout> <dir> --install creates a fresh Vite + React + StyleX project with the Astryx packages, scaffolds dashboard, and builds. On main the scaffold prints only Copied template…, and vite build exits 1 with Rollup failed to resolve import "recharts". The CLI gives no install command (before.txt).
  • Result after the change: the same script on this branch. The scaffold prints the [warn] line, missingPackages, and installCommand, and the --json data carries both. vite build still exits 1 until the printed command runs. After the script runs the exact installCommand from the JSON, vite build exits 0, and tsc -p . over the page exits 0 (after.txt).
  • Representative unchanged path: rescaffolding into the now-complete project prints only the copy line, with missingPackages: [] and installCommand: null (after-installed.txt). A test covers the same case: the template.copy data equals the old four fields plus the two empty ones, and the text contains no [warn] or field lines.
  • Regression test or other mutation-sensitive proof: packages/cli/api/template/template-packages.test.mjs. With the source changes reverted, it fails 7 of 8. The one that passes is the unchanged-path text test, which should pass on main. With the changes applied, it passes 8 of 8.

Measurements

Measure Before (main) After
dashboard scaffold → vite build, fresh Vite project exit 1, no hint exit 1, with missingPackages + installCommand printed; exit 0 after running it
Scaffold exit code 0 0 (unchanged)
template.copy fields 4 6 (4 unchanged + missingPackages, installCommand)
Page templates that import a package a fresh Vite + Astryx project lacks 46 / 55 (44 / 52 ready), reported: 0 46 / 55, reported: 46
Block templates, same 86 / 659, reported: 0 86 / 659, reported: 86
Missing packages across all templates – @heroicons/react ×127, recharts ×7, lucide-react ×5
astryx --json build "analytics dashboard" wall time (3 runs) 2.10–2.17 s 2.14–2.20 s
Blind benchmark, template-first workflow on main 18 / 36 builds hit this (not re-run; this PR removes the silent failure mode)

Evidence files (drag into the PR)

Preview story: none. This is CLI output, so there is no Storybook story. The scripted repro above replaces it.

Scope

  • One defect is restored: a scaffold that silently leaves the project unable to build.
  • Separable contradictory or unsettled tagalongs were removed or split: agent-block wording, playbook wording, template edits, auto-install.
  • No new public API, visual representation, default, or interaction model is hidden under the bug-fix label. The two additive response fields are the public delta, named here, and are required carriers under spec:AST-017 FR13. See owner decision 1.
  • Public text and artifacts contain no internal Meta context.

Compatibility declaration (spec:AST-017 FR42): tag [fix], classification compatible, affected surfaces: CLI machine-readable schema (template.copy, build.kit), CLI text output, CLI docs. No experimental, deprecation, correction, or cleanup ids. Changeset: .changeset/cli-template-missing-packages.md (@astryxdesign/cli: patch).

Owner or spec decisions needed

  1. Label. The restoration needs two additive response fields, because text must match JSON. If maintainers see that as a capability rather than a restoration, relabel the PR as new-feature. The code doesn't change either way.
  2. installCommand in build.kit is package-manager-specific (for example pnpm add …). The kit otherwise keeps its JSON package-manager-agnostic. spec:AST-048's platform note says commands appear without the run prefix in JSON, but that concerns Astryx invocations, and an install line without its package manager can't be run. The kit's header comment records this reasoning. If the AST-048 owner prefers, build can carry only missingPackages and leave the install line to astryx template. That would be a one-line removal plus a doc edit.
  3. Astryx packages count as imports too. The original proposal suggested checking only non-Astryx imports. Two Core templates import @astryxdesign/theme-neutral, and a project without it fails the same way, so this PR reports every undeclared package. In practice Core is always declared where templates are used. Restricting the check to non-Astryx packages would be a one-line filter.

Follow-ups (not in this PR)

  • Agent block and build playbook wording. The generated agent block says "start every page from a template". The build.help step for template <name> <path> could tell agents to run installCommand when the scaffold returns one. This is a separate policy discussion, deliberately left alone here.
  • Option (c). Whether templates should depend on icon and chart packages at all. The Icon component and the theme icon registry could replace most @heroicons/react imports. That is a template-content and design decision.
  • astryx template <name> (print source) and --skeleton don't report requirements. They write nothing, so nothing breaks, but template.show could carry missingPackages later.

Testing

Global-baseline review receipt (regenerated at this head; 15 matched claims)

Review receipt (node scripts/review-global-baselines.mjs --authority-commit 217f41d74ec41aee7f6895ea53e8b6035831f3b7 --review-head a9d4a9365a844159925b40df01a7daba29429414 --triggers behavior,public-api,compatibility,testing): 81 matched claims. The applicable ones and how this PR meets them:

Record / claim Trigger Match reason Disposition
spec:AST-017 FR3 Released contracts include behavior compatibility routed claim Command name, options, and exit codes are unchanged. The schema change is additive.
spec:AST-017 FR5 Additive and victim-free restorations are nonbreaking compatibility routed claim New fields only. Old consumers are unaffected.
spec:AST-017 FR14 No supported CLI behavior is hidden compatibility routed claim The automatic check is documented in the CommandDoc description, the example, the FunctionDoc, the typedefs, and the README.
spec:AST-017 FR29 Warnings fit the surface without changing success compatibility routed claim Not a deprecation warning. The [warn] line is the text projection of result data, and the exit status stays 0.
spec:AST-017 FR12 Supported inter-package ranges are contracts compatibility routed claim No dependency or peer range changes. The install specs come from ranges the package already declares.
spec:AST-017 FR42 Contributors declare compatibility intent once compatibility routed claim Declaration above (compatible).
spec:AST-002 DEC-3 / DEC-6 One canonical name, one responsibility public-api routed claims missingPackages (what) and installCommand (how) have one meaning each, and the same names on template.copy and build.kit.
architecture:component-test-sufficiency INV2 / INV5 / INV6 testing routed claims Regression test observes the JSON and text contract, fails before (7/8) and passes after (8/8). Edge cases: unchanged path, Astryx-only template, pnpm and nested package cd, workspace-root declarations, integration template version line, comments and strings, unparseable source.
spec:AST-030 FR11 Each surface owns one test lane testing routed claim Tests sit beside their code: the foundation unit tests, the template API/CLI tests, and one case in template-integration.test.mjs.
architecture:container-padding, architecture:public-component-api INV1–12, other AST-017 lifecycle claims (FR15–FR45) public-api / compatibility routed claims Not applicable: component props, layout, or release lifecycle. No component, flag, config, or experimental surface is touched.

The full receipt JSON is at review-receipt.json.

Commands run (every one bounded with timeout):

  • pnpm exec vitest run packages/cli/api/template/template-packages.test.mjs: with the source reverted (patch stashed to a file, then re-applied), 7 failed and 1 passed. After, 8 passed.
  • Focused lanes on the final head: vitest run packages/cli/api/build packages/cli/api/template packages/cli/clients/cli/commands/build* packages/cli/clients/cli/commands/template* packages/cli/foundation/discovery/cli-self-docs* packages/cli/foundation/discovery/template* packages/cli/foundation/env packages/cli/foundation/doc-compiler/doc-loads.test.mjs: 47 files, 553 passed.
  • Full package suite, pnpm -F @astryxdesign/cli test, run once. Under full parallel load on a shared machine it reported timeouts. Every file that failed was re-run at --maxWorkers=4. The only failures left were 17 in pack-check.test.mjs, integration-authoring.test.mjs, and integration-real-world.test.mjs (npm pack failed). Those same 17 fail identically on unmodified main in this environment, because npm packing is unavailable there. One real failure, doc-loads.test.mjs, which requires listing the new module's lazy @babel/parser load, is fixed in this PR.
  • pnpm run typecheck:strict, typecheck:json-api, typecheck:authoring, typecheck:template-docs in packages/cli: all clean. strict needs @astryxdesign/theme-neutral built locally.
  • eslint on every changed .mjs file: clean. prettier --write on the new files and on template.doc.mjs, which was prettier-clean on main.
  • node scripts/generate-cli-readme.mjs regenerated the README response table.
  • pnpm check:repo passed through the pre-commit hook.
  • repro.sh against unmodified main and against this branch, with --install. Plus tsc -p . in the after project: exit 0.
  • astryx docs cli/commands/template and astryx docs cli/api/functions/template render the new examples, including the sample output.

Note

Rebased onto main @ 217f41d with no conflicts. At this head, the focused tests, core typecheck, ESLint and check:repo were re-run and pass, and the global-baseline receipt was regenerated (same matched claims). Screenshots and measurements were captured against main @ eedc844; the regression tests that encode them pass at this head.

Need: most page templates import an icon or chart package
(`@heroicons/react`, `recharts`, `lucide-react`). `astryx template <name>
<path>` copied them into projects that did not list those packages and
reported plain success, so the first build after wiring the page in failed
on an unresolved import. `astryx build` recommends these templates as the
place to start, which made the break the common path rather than an edge.

Model: after writing the file, the copy leaf reads the written file's
imports (Babel parse, top-level import/export-from only), drops relative
paths, builtins and path aliases, and checks each package against every
package.json from the target directory up (so a workspace root counts).
Whatever is left is reported as `missingPackages`, with `installCommand`:
the project's own package manager (`npm install`, `pnpm add`, `yarn add`,
`bun add`), each package pinned to the major line the template's shipping
package declares, and `cd <dir> &&` when the project's package.json is not
in cwd. The text output prints both fields under a `[warn]` line. `astryx
build` adds the same two fields to its start and alternatives, computed for
the project where it runs. The file is still written; nothing is installed.

Compatibility: additive. `template.copy` and `build.kit` gain fields;
every existing field keeps its shape and meaning, and exit codes are
unchanged. The docs tree now renders a command example's documented
`output` field, so the template command's new example shows its output.
@vercel

vercel Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
astryx Ready Ready Preview Oct 1, 2026 2:38am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 1, 2026
@astracat-bot

astracat-bot Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

AI review status for this pull request.

Review status Updated
❓ Needs maintainer input (for maintainers only) Oct 11, 2026, 5:56 PM UTC

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR

🧪 Sandbox Preview

View Sandbox for this PR

No new or modified components detected.

Bundle Size Summary

No component packages changed.

Accessibility Audit

Status: No accessibility violations detected.

Visual Regression

14 of 420 shot(s) changed.

A change here is a question, not a failure: check whether the after is the
picture you intended. Record that review on the PR. Baseline maintenance is an
explicit dispatch of CI; this report never rewrites the baseline or adds a release gate.

component story theme mode pixels
Chat Full AI Chat probe light 155,733
Chat Full AI Chat probe dark 155,005
Chat Default neutral dark 33,205
Chat Default neutral light 32,876
Chat Empty State probe light 23,531
Chat Empty State probe dark 22,622
ChatAutoScroll Scroll Behavior Comparison neutral dark 15,378
ChatAutoScroll Scroll Behavior Comparison neutral light 14,107
Chat With Attachments probe light 13,229
Chat With Attachments probe dark 11,065
Markdown Default probe dark 897
Markdown Default probe light 897
Markdown Default neutral dark 882
Markdown Default neutral light 858

Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

@astracat-bot astracat-bot 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.

Thanks for the clear repro and the careful write-up. This is on hold for a maintainer decision before it can be approved.

The scaffold and astryx build changes add missingPackages and installCommand as new public behaviour. The current specs cover the additive shape of such fields, but no current record was identified that governs a scaffold or a build recommendation naming the packages a template needs and the install command for them. Approval therefore needs a maintainer to provide or identify that governing spec. That decision also needs to settle two points the PR itself raises: whether build's JSON may carry the package-manager-specific install command, and whether undeclared Astryx packages are counted alongside third-party packages such as the icon and chart libraries.

One smaller item to address once that direction is settled: in a project where the package manager cannot be determined because several lockfiles are present, the new install line falls back to npm install even though detection otherwise stays neutral rather than guessing. Please either omit the install command in that ambiguous state or make the ambiguity visible, so a builder is not pointed at the wrong package manager.

The contract, text-projection and unchanged-path behaviour otherwise look solid, with no change to exit codes or existing fields.

[Automated review]

@astracat-bot

astracat-bot Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded. #7183 shipped this same feature on main: template and build report missingPackages with an installCommand. Thank you for the careful reproduction and the import-reader design, which set the direction.

The maintainers approved the behavior with one condition from this review: when several lockfiles leave the package manager undetermined, the CLI names the missing packages but prints no install command. Main still guesses in that case, so a small follow-up on main applies that condition using the shared package-manager detection.

@cixzhang cixzhang closed this Oct 11, 2026
@github-actions
github-actions Bot deleted the fix/cli-template-deps branch October 12, 2026 06:35

This branch was successfully deployed

1 active deployment
Preview — a9d4a936 Deployed Oct 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants