From d2e3e05533d89d94ee1724f0c82e9ff489be4fc0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:34:16 -0600 Subject: [PATCH] =?UTF-8?q?feat(mcpx):=20stage=203=20(Prepare)=20=E2=80=94?= =?UTF-8?q?=20materialise=20the=20resolved=20dependency=20set=20into=20the?= =?UTF-8?q?=20cache=20(#1915)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prepare mode no longer ends at "materialising it is stage 3 and is not part of this build". prepareResolved now hands the resolved set to PrepareSet, which writes the exact recorded pins as a package.json in a content-addressed cache entry (#1908) keyed by the canonical set and populates its node_modules with an installer that runs no scripts (npm --ignore-scripts). The same set always keys the same entry — a warm cache is a hit and installs nothing again — and a failed fill leaves no entry behind, so the next prepare retries instead of serving a half-built environment. canonicalPins refuses a set that leaves a package unpinned or pins one name two ways: preparing from it would key two environments alike or install an unspecified version. Report gains Prepared *PreparedSet; ResolveOptions gains the PrepareCache / PrepareInstall seams. Deliberately not in this slice, and the report says so: cross-project subsets are resolved and counted but not materialised (their design writes node_modules beside a foreign project's files — a write into a user's project that needs its own opt-in), no consumer points a run at the prepared environment yet (runner wiring is the next slice), and the deno import-map form is likewise later. Tests: PrepareSet unit coverage (empty set no-op, unpinned/conflicting refusals, no-cache-root refusal, subset counting) plus an end-to-end CheckImportsResolved prepare-mode test over a stubbed deno graph. Work authored by Lane GX (sandbox fix lane), who ended without a final report; reviewed, verified, and landed by Lane HT. --- pkgs/mcpx/internal/preflight/imports.go | 17 +- pkgs/mcpx/internal/preflight/preflight.go | 3 + pkgs/mcpx/internal/preflight/prepare.go | 254 +++++++++++++++++ pkgs/mcpx/internal/preflight/prepare_test.go | 272 +++++++++++++++++++ pkgs/mcpx/internal/preflight/resolve.go | 6 + 5 files changed, 543 insertions(+), 9 deletions(-) create mode 100644 pkgs/mcpx/internal/preflight/prepare.go create mode 100644 pkgs/mcpx/internal/preflight/prepare_test.go diff --git a/pkgs/mcpx/internal/preflight/imports.go b/pkgs/mcpx/internal/preflight/imports.go index 3593fac659..bb73c7b587 100644 --- a/pkgs/mcpx/internal/preflight/imports.go +++ b/pkgs/mcpx/internal/preflight/imports.go @@ -14,8 +14,10 @@ // --node-modules-dir=none are appended after any forwarded resolution // options, so a project configured with nodeModulesDir "auto" or a stale // lockfile is neither installed into nor edited (Codex review, PR #2575). -// The prepare stage of #1915 stays out until the cache mechanism (#1908) -// and the resolved dependency set (#1913) exist to build on. +// Stage 3 builds on both -- the cache mechanism (#1908) and the resolved +// dependency set (#1913) -- in prepare.go. It runs only in prepare mode +// and never through this invocation: computing a graph still installs +// nothing by itself, whatever the mode. // // The two edges a static graph cannot decide are computed dynamic imports: // import("./" + name) and require(v). deno's graph simply omits them, so @@ -42,8 +44,8 @@ type ImportsMode string const ( ImportsOff ImportsMode = "off" ImportsReport ImportsMode = "report" - // ImportsPrepare requests resolution for a future materialisation step. - // Resolve can build the dependency set, but this stage never installs it. + // ImportsPrepare resolves the dependency set and materialises it + // into the content-addressed cache (stage 3, prepare.go). ImportsPrepare ImportsMode = "prepare" ) @@ -540,12 +542,9 @@ func CheckImportsResolved(ctx context.Context, denoBin, entry string, mode Impor dynamics = append(dynamics, ScanDynamicImports(f, string(b))...) } if len(resolve) > 0 { - _, report := ResolveGraph(cctx, g, resolve[0], dynamics, dynamicMode) + set, report := ResolveGraph(cctx, g, resolve[0], dynamics, dynamicMode) if mode == ImportsPrepare { - report.Add(Problem{ - What: "the dependency set was resolved, but materialising it is stage 3 and is not part of this build", - Where: "script.imports", - }) + prepareResolved(cctx, report, set, resolve[0]) } return report } diff --git a/pkgs/mcpx/internal/preflight/preflight.go b/pkgs/mcpx/internal/preflight/preflight.go index a13be91552..f83f853b91 100644 --- a/pkgs/mcpx/internal/preflight/preflight.go +++ b/pkgs/mcpx/internal/preflight/preflight.go @@ -47,6 +47,9 @@ func (p Problem) String() string { // Report is everything found. type Report struct { Problems []Problem + // Prepared is the dependency environment stage 3 materialised, + // set only by the import pipeline in prepare mode (#1915). + Prepared *PreparedSet } // Add records a problem. diff --git a/pkgs/mcpx/internal/preflight/prepare.go b/pkgs/mcpx/internal/preflight/prepare.go new file mode 100644 index 0000000000..95d262d461 --- /dev/null +++ b/pkgs/mcpx/internal/preflight/prepare.go @@ -0,0 +1,254 @@ +package preflight + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + + "github.com/developing-today/code/pkgs/mcpx/internal/cache" + "github.com/developing-today/code/pkgs/mcpx/internal/defaults" + "github.com/developing-today/code/pkgs/mcpx/internal/homeutil" +) + +// Stage 3 (Prepare) of #1915: materialise a resolved dependency set into +// a prepared environment in the content-addressed cache (#1908). +// +// Stages 1 and 2 compute the import graph and resolve it into a data-only +// set; until this stage, prepare mode ended at a report saying the set +// "was resolved, but materialising it is stage 3". PrepareSet is that +// materialisation for the entry project's set: the exact recorded pins +// become a package.json in a cache entry keyed by the canonical set, and +// an installer populates its node_modules. The same set always keys the +// same entry -- a warm cache is a hit and installs nothing again -- and a +// different set can never collide with it, the same discipline the +// runner already applies to its exec workdirs. +// +// The recorded version is installed as declared: an exact pin installs +// exactly, and a range a manifest declared is written as declared and +// resolved by the installer at install time; the install's lockfile is +// stored inside the entry, so what actually materialised stays auditable +// and a later entry for the same key is the cached one, never a +// re-resolution. +// +// Two parts of the stage-3 design are deliberately not here yet, and the +// report says so rather than implying coverage: cross-project subsets +// are resolved and counted but not materialised (their design puts a +// node_modules beside the foreign project's files, which is a write +// into a user's project and needs its own opt-in), and no consumer +// points a run at the prepared environment yet -- the runner wiring is +// the next slice. The prepared environment is in the node_modules form +// node and bun consume; the deno import-map form is likewise a later +// slice. + +// prepareKind is the cache kind prepared environments live under, so +// `mcpx cache` lists and prunes them with everything else. +const prepareKind = "imports" + +// Installer populates a prepared environment directory whose +// package.json already carries the resolved pins. +type Installer interface { + Install(ctx context.Context, dir string, pkgs []ResolvedPackage) error +} + +// NPMInstaller is the production Installer: npm installs the pinned +// manifest into the entry. Scripts stay off -- a prepared environment is +// dependency code mcpx fetched because a script imports it, and running +// its install scripts would be executing it before the run starts. +type NPMInstaller struct { + // Bin is the npm executable; empty means "npm" from PATH. + Bin string +} + +func (n NPMInstaller) Install(ctx context.Context, dir string, _ []ResolvedPackage) error { + bin := n.Bin + if bin == "" { + bin = "npm" + } + cmd := exec.CommandContext(ctx, bin, "install", + "--ignore-scripts", "--no-audit", "--no-fund", "--loglevel=error") + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("npm install in the prepared environment: %w: %s", + err, strings.TrimSpace(string(out))) + } + return nil +} + +// PreparedSet is the outcome of stage 3 for one resolved set. +type PreparedSet struct { + // Dir is the prepared environment's directory in the cache. It is + // empty when the resolved set had no entry-project packages: there + // was nothing to materialise and no entry was created. + Dir string + // Key is the cache key Dir lives under, derived from the canonical + // resolved set. + Key string + // Hit reports that the entry already existed and nothing installed. + Hit bool + // Packages are the canonical pins that were materialised, sorted by + // name. + Packages []ResolvedPackage + // Subsets counts the cross-project subsets the resolved set kept + // separate. They are not materialised by this stage. + Subsets int +} + +// PrepareSet materialises set's entry-project packages into the cache +// rooted at cacheRoot. An empty set is a successful no-op. A failure +// leaves no cache entry behind: the cache stores an entry only when its +// fill completes, so a failed install is retried by the next prepare +// rather than served half-built forever. +func PrepareSet(ctx context.Context, cacheRoot string, set ResolvedSet, inst Installer) (PreparedSet, error) { + pkgs, err := canonicalPins(set.Packages) + if err != nil { + return PreparedSet{}, err + } + out := PreparedSet{Packages: pkgs, Subsets: len(set.Subsets)} + if len(pkgs) == 0 { + return out, nil + } + if cacheRoot == "" { + return PreparedSet{}, errors.New("no cache directory is available for the prepared environment (MCPX_CACHE_DIR is unset and no home directory could be determined)") + } + if inst == nil { + inst = NPMInstaller{} + } + parts := make([]string, 0, len(pkgs)+1) + parts = append(parts, "mcpx-prepare-v1") + for _, p := range pkgs { + parts = append(parts, p.Name+"@"+p.Version) + } + key := cache.KeyString(parts...) + c := cache.Open(cacheRoot) + lim := cache.Limits{ + MaxBytes: defaults.CacheMaxBytes, + MaxAge: defaults.CacheMaxAge, + LeaseStaleAge: defaults.CacheLeaseStaleAge, + } + dir, hit, err := c.Put(prepareKind, key, lim, func(dir string) error { + if err := writePreparedManifest(dir, pkgs); err != nil { + return err + } + return inst.Install(ctx, dir, pkgs) + }) + if err != nil { + return PreparedSet{}, fmt.Errorf("materialise the resolved dependency set: %w", err) + } + out.Dir, out.Key, out.Hit = dir, key, hit + return out, nil +} + +// canonicalPins reduces a resolved set's packages to the sorted, +// name-unique pins a prepared environment is keyed and built by. Stage 2 +// already dedupes by name; a conflicting or unpinned entry here means +// the set was built some other way, and preparing from it would key two +// different environments alike or install an unspecified version, so it +// is refused rather than guessed at. +func canonicalPins(in []ResolvedPackage) ([]ResolvedPackage, error) { + byName := map[string]ResolvedPackage{} + for _, p := range in { + if p.Name == "" { + return nil, errors.New("the resolved dependency set contains a package with no name") + } + if p.Version == "" { + return nil, fmt.Errorf("the resolved dependency set leaves %s unpinned; there is no version to prepare", p.Name) + } + if cur, ok := byName[p.Name]; ok && cur.Version != p.Version { + return nil, fmt.Errorf("the resolved dependency set pins %s to both %s and %s", p.Name, cur.Version, p.Version) + } + byName[p.Name] = p + } + out := make([]ResolvedPackage, 0, len(byName)) + for _, p := range byName { + out = append(out, p) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +// writePreparedManifest writes the entry's package.json: the resolved +// pins, as declared, and nothing else -- no scripts, no metadata that +// could drift from the set the entry is keyed by. +func writePreparedManifest(dir string, pkgs []ResolvedPackage) error { + deps := make(map[string]string, len(pkgs)) + for _, p := range pkgs { + deps[p.Name] = p.Version + } + manifest := map[string]any{ + "name": "mcpx-prepared-imports", + "version": "0.0.0", + "private": true, + "dependencies": deps, + } + b, err := json.MarshalIndent(manifest, "", " ") + if err != nil { + return err + } + return os.WriteFile(filepath.Join(dir, "package.json"), append(b, '\n'), 0o644) +} + +// prepareResolved runs stage 3 for one resolved set and records the +// outcome on the report: the prepared environment structurally (for the +// consumers that come next) and as report lines (for the user reading +// this run's warnings today). A materialisation failure is fatal: the +// caller asked for prepare by name, and letting the run continue would +// surface the same missing packages later as a runtime module error -- +// the failure shape this pipeline exists to replace. +func prepareResolved(ctx context.Context, r *Report, set ResolvedSet, opts ResolveOptions) { + prepared, err := PrepareSet(ctx, opts.prepareCacheRoot(), set, opts.PrepareInstall) + if err != nil { + r.Add(Problem{ + What: "the dependency set was resolved, but materialising it failed: " + err.Error(), + Where: "script.imports", + Fix: "check the package installer and the cache directory, or set script.imports to report", + Fatal: true, + }) + return + } + r.Prepared = &prepared + if len(prepared.Packages) > 0 { + how := "installed" + if prepared.Hit { + how = "already in the cache" + } + r.Add(Problem{ + What: fmt.Sprintf("prepared dependency environment (%s): %s at %s", how, packageList(prepared.Packages), prepared.Dir), + Where: "script.imports", + }) + } + if prepared.Subsets > 0 { + r.Add(Problem{ + What: fmt.Sprintf("%d cross-project dependency subset(s) were resolved but are not materialised yet: prepare covers the entry project's set only", prepared.Subsets), + Where: "script.imports", + }) + } +} + +// prepareCacheRoot resolves the cache root stage 3 writes to: the +// explicit option first, then the same derivation daemon.ResolvePaths +// applies to its cache leg (MCPX_CACHE_DIR, then XDG_CACHE_HOME, then +// the home directory). The daemon package cannot be imported here -- it +// reaches preflight through execsvc and the runner -- so the derivation +// is mirrored, and the two must be kept in step. +func (o ResolveOptions) prepareCacheRoot() string { + if o.PrepareCache != "" { + return o.PrepareCache + } + if v := os.Getenv("MCPX_CACHE_DIR"); v != "" { + return v + } + if v := os.Getenv("XDG_CACHE_HOME"); v != "" { + return filepath.Join(v, "mcpx") + } + if home, err := homeutil.Home(); err == nil { + return filepath.Join(home, ".cache", "mcpx") + } + return "" +} diff --git a/pkgs/mcpx/internal/preflight/prepare_test.go b/pkgs/mcpx/internal/preflight/prepare_test.go new file mode 100644 index 0000000000..5db3cea7ca --- /dev/null +++ b/pkgs/mcpx/internal/preflight/prepare_test.go @@ -0,0 +1,272 @@ +package preflight_test + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/preflight" +) + +// fakeInstaller records what stage 3 asked it to install and stands in +// for npm: it creates the node_modules marker a real install would, so +// tests can tell a materialised entry from an empty directory. +type fakeInstaller struct { + calls int + dirs []string + pins [][]preflight.ResolvedPackage + err error +} + +func (f *fakeInstaller) Install(_ context.Context, dir string, pkgs []preflight.ResolvedPackage) error { + f.calls++ + f.dirs = append(f.dirs, dir) + f.pins = append(f.pins, append([]preflight.ResolvedPackage(nil), pkgs...)) + if f.err != nil { + return f.err + } + for _, p := range pkgs { + marker := filepath.Join(dir, "node_modules", p.Name, "package.json") + if err := os.MkdirAll(filepath.Dir(marker), 0o755); err != nil { + return err + } + if err := os.WriteFile(marker, []byte("{}\n"), 0o644); err != nil { + return err + } + } + return nil +} + +func TestPrepareSetMaterialisesThenServesTheCacheHit(t *testing.T) { + root := t.TempDir() + inst := &fakeInstaller{} + set := preflight.ResolvedSet{Packages: []preflight.ResolvedPackage{ + {Name: "zeta", Version: "2.0.0", Source: "explicit --package"}, + {Name: "alpha", Version: "1.2.3", Source: "explicit --package"}, + }} + first, err := preflight.PrepareSet(context.Background(), root, set, inst) + if err != nil { + t.Fatal(err) + } + if first.Hit { + t.Error("the first prepare of a set cannot be a cache hit") + } + if first.Dir == "" || first.Key == "" { + t.Fatalf("a materialised set names its entry: %+v", first) + } + if filepath.Dir(first.Dir) != filepath.Join(root, "imports") || filepath.Base(first.Dir) != first.Key { + t.Errorf("the entry lives under /imports/: %s", first.Dir) + } + manifest, err := os.ReadFile(filepath.Join(first.Dir, "package.json")) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{`"alpha": "1.2.3"`, `"zeta": "2.0.0"`} { + if !strings.Contains(string(manifest), want) { + t.Errorf("the prepared manifest pins %s: %s", want, manifest) + } + } + if _, err := os.Stat(filepath.Join(first.Dir, "node_modules", "alpha", "package.json")); err != nil { + t.Errorf("the installer populated the entry: %v", err) + } + if inst.calls != 1 { + t.Fatalf("one cold prepare installs once, got %d", inst.calls) + } + if got := inst.pins[0]; len(got) != 2 || got[0].Name != "alpha" || got[1].Name != "zeta" { + t.Errorf("the installer receives the canonical (sorted) pins: %+v", got) + } + + // The same set in a different order is the same environment: a hit, + // and no second install. + second, err := preflight.PrepareSet(context.Background(), root, preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{set.Packages[1], set.Packages[0]}, + }, inst) + if err != nil { + t.Fatal(err) + } + if !second.Hit || second.Dir != first.Dir || second.Key != first.Key { + t.Errorf("the same set must key the same entry: first %+v, second %+v", first, second) + } + if inst.calls != 1 { + t.Errorf("a cache hit installs nothing again, got %d installs", inst.calls) + } +} + +func TestPrepareSetKeyFollowsTheSet(t *testing.T) { + root := t.TempDir() + inst := &fakeInstaller{} + a, err := preflight.PrepareSet(context.Background(), root, preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha", Version: "1.2.3"}}, + }, inst) + if err != nil { + t.Fatal(err) + } + b, err := preflight.PrepareSet(context.Background(), root, preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha", Version: "1.2.4"}}, + }, inst) + if err != nil { + t.Fatal(err) + } + if a.Key == b.Key || a.Dir == b.Dir { + t.Errorf("a different version is a different environment: %s vs %s", a.Dir, b.Dir) + } + if inst.calls != 2 { + t.Errorf("each distinct set installs once, got %d", inst.calls) + } +} + +func TestPrepareSetInstallerFailureLeavesNoEntry(t *testing.T) { + root := t.TempDir() + inst := &fakeInstaller{err: errors.New("registry unreachable")} + _, err := preflight.PrepareSet(context.Background(), root, preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha", Version: "1.2.3"}}, + }, inst) + if err == nil || !strings.Contains(err.Error(), "registry unreachable") { + t.Fatalf("the installer's failure must surface: %v", err) + } + entries, rerr := os.ReadDir(filepath.Join(root, "imports")) + if rerr != nil && !os.IsNotExist(rerr) { + t.Fatal(rerr) + } + if len(entries) != 0 { + t.Errorf("a failed install leaves no entry to be served later: %v", entries) + } + // And the next prepare retries rather than hitting a phantom entry. + inst.err = nil + prepared, err := preflight.PrepareSet(context.Background(), root, preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha", Version: "1.2.3"}}, + }, inst) + if err != nil { + t.Fatal(err) + } + if prepared.Hit { + t.Error("nothing was ever stored, so the retry cannot be a hit") + } +} + +func TestPrepareSetEmptySetIsANoOp(t *testing.T) { + inst := &fakeInstaller{} + prepared, err := preflight.PrepareSet(context.Background(), t.TempDir(), preflight.ResolvedSet{}, inst) + if err != nil { + t.Fatal(err) + } + if prepared.Dir != "" || prepared.Key != "" || len(prepared.Packages) != 0 { + t.Errorf("an empty set materialises nothing: %+v", prepared) + } + if inst.calls != 0 { + t.Error("an empty set installs nothing") + } +} + +func TestPrepareSetRefusesUnpinnedAndConflictingSets(t *testing.T) { + inst := &fakeInstaller{} + if _, err := preflight.PrepareSet(context.Background(), t.TempDir(), preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha"}}, + }, inst); err == nil || !strings.Contains(err.Error(), "unpinned") { + t.Errorf("a package with no version cannot be prepared: %v", err) + } + if _, err := preflight.PrepareSet(context.Background(), t.TempDir(), preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{ + {Name: "alpha", Version: "1.0.0"}, + {Name: "alpha", Version: "2.0.0"}, + }, + }, inst); err == nil || !strings.Contains(err.Error(), "both") { + t.Errorf("one name pinned two ways cannot be prepared: %v", err) + } + if _, err := preflight.PrepareSet(context.Background(), "", preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha", Version: "1.0.0"}}, + }, inst); err == nil || !strings.Contains(err.Error(), "no cache directory") { + t.Errorf("preparing without a cache root must say so: %v", err) + } + if inst.calls != 0 { + t.Error("a refused set installs nothing") + } +} + +func TestPrepareSetCountsSubsetsWithoutMaterialisingThem(t *testing.T) { + inst := &fakeInstaller{} + set := preflight.ResolvedSet{ + Packages: []preflight.ResolvedPackage{{Name: "alpha", Version: "1.2.3"}}, + Subsets: []preflight.DependencySubset{{ + Manifest: preflight.PackageManifest{Path: "/foreign/package.json", Dir: "/foreign"}, + Packages: []preflight.ResolvedPackage{{Name: "foreign-only", Version: "2"}}, + }}, + } + prepared, err := preflight.PrepareSet(context.Background(), t.TempDir(), set, inst) + if err != nil { + t.Fatal(err) + } + if prepared.Subsets != 1 { + t.Errorf("the subset is counted for the report: %+v", prepared) + } + if len(inst.pins) != 1 || len(inst.pins[0]) != 1 || inst.pins[0][0].Name != "alpha" { + t.Errorf("only the entry project's set is installed: %+v", inst.pins) + } +} + +// The graph `deno info --json` emits for a script whose one bare import +// does not resolve: the root module's dependency joins to a module entry +// carrying the error. +const denoInfoMissingBareFixture = `{ + "version": 1, + "roots": ["file:///work/main.ts"], + "modules": [ + { + "kind": "esm", + "specifier": "file:///work/main.ts", + "dependencies": [ + {"specifier": "some-pkg", "code": {"specifier": "npm:some-pkg", "span": {"start": {"line": 0, "character": 16}, "end": {"line": 0, "character": 26}}}} + ] + }, + {"specifier": "npm:some-pkg", "error": "Module not found: some-pkg"} + ], + "redirects": {}, + "npmPackages": {} +}` + +func TestCheckImportsPrepareModeMaterialisesTheResolvedSet(t *testing.T) { + dir := t.TempDir() + entry := filepath.Join(dir, "main.ts") + if err := os.WriteFile(entry, []byte("import \"some-pkg\";\n"), 0o644); err != nil { + t.Fatal(err) + } + stub := filepath.Join(dir, "deno-stub") + script := "#!/bin/sh\ncat <<'JSON'\n" + denoInfoMissingBareFixture + "\nJSON\n" + if err := os.WriteFile(stub, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + cacheRoot := t.TempDir() + inst := &fakeInstaller{} + rep := preflight.CheckImportsResolved(context.Background(), stub, entry, + preflight.ImportsPrepare, preflight.DynamicWarn, 10*time.Second, nil, dir, + preflight.ResolveOptions{ + Explicit: []string{"some-pkg@1.2.3"}, + Missing: preflight.MissingInstall, + PrepareCache: cacheRoot, + PrepareInstall: inst, + }) + if err := rep.Err(); err != nil { + t.Fatalf("prepare mode with a resolvable set should not fail the run: %v", err) + } + if rep.Prepared == nil { + t.Fatalf("prepare mode records the prepared environment: %+v", rep.Problems) + } + if rep.Prepared.Dir == "" || rep.Prepared.Hit { + t.Errorf("a cold cache materialises a fresh entry: %+v", rep.Prepared) + } + if _, err := os.Stat(filepath.Join(rep.Prepared.Dir, "node_modules", "some-pkg", "package.json")); err != nil { + t.Errorf("the resolved package is in the prepared environment: %v", err) + } + for _, p := range rep.Problems { + if strings.Contains(p.What, "is not part of this build") { + t.Errorf("the stage-3 stub text must be gone in prepare mode: %q", p.What) + } + } + if inst.calls != 1 { + t.Errorf("prepare installs the set once, got %d", inst.calls) + } +} diff --git a/pkgs/mcpx/internal/preflight/resolve.go b/pkgs/mcpx/internal/preflight/resolve.go index 59dc6b3840..a206694e6f 100644 --- a/pkgs/mcpx/internal/preflight/resolve.go +++ b/pkgs/mcpx/internal/preflight/resolve.go @@ -79,6 +79,12 @@ type ResolveOptions struct { CrossProject CrossProjectMode Network bool LatestVersion func(context.Context, string) (string, error) + // PrepareCache is the cache root stage 3 (prepare.go) materialises + // the resolved set into in prepare mode. Empty resolves the root + // from the environment the way the daemon resolves its cache. + PrepareCache string + // PrepareInstall is the installer stage 3 uses; nil means npm. + PrepareInstall Installer } // DiscoverPackageManifests finds the nearest package.json/package.jsonc or