diff --git a/.agents/skills/host-platform-context/SKILL.md b/.agents/skills/host-platform-context/SKILL.md index 8543fed3..0c677ca5 100644 --- a/.agents/skills/host-platform-context/SKILL.md +++ b/.agents/skills/host-platform-context/SKILL.md @@ -1,6 +1,6 @@ --- name: host-platform-context -description: "Use when modifying cli/src/engine-native/exec.ts spawnHost, spawnProcess, capture, captureWithin, which; os/*.ts HostOs facts (invoke, executableSuffixes, installHint, bunInstaller) or os/targets.ts HOST_TARGETS; deps.ts DEPENDENCIES, findBun, resolveVersionReading; services.ts makeDependencyManager or the cli/src/services.ts Effect layers; atomicWrite.ts replaceFile, replaceTextIfChanged, or removeStaleTemporaries; processes.ts processExited; or logger.ts terminal lease. Covers Windows cmd-shim encoding, pathless-spawn refusal, bounded process-group kills, version-probe time limits, symlink-preserving atomic writes and the cleanup of their killed-write leftovers, and the host support matrix. Not for golden harness rules (use engine-native-context) or toolchain pins and the doctor table (use toolchain-context)." +description: "Use when modifying cli/src/engine-native/exec.ts spawnHost, spawnProcess, capture, captureWithin, which; os/*.ts HostOs facts (invoke, executableSuffixes, installHint, bunInstaller) or os/targets.ts HOST_TARGETS; deps.ts DEPENDENCIES, findBun, resolveVersion; services.ts makeDependencyManager or the cli/src/services.ts Effect layers; atomicWrite.ts replaceFile, replaceTextIfChanged, or removeStaleTemporaries; processes.ts processExited; or logger.ts terminal lease. Covers Windows cmd-shim encoding, pathless-spawn refusal, bounded process-group kills, version-probe time limits, symlink-preserving atomic writes and the cleanup of their killed-write leftovers, and the host support matrix. Not for golden harness rules (use engine-native-context) or toolchain pins and the doctor table (use toolchain-context)." user-invocable: false metadata: pattern: tool-wrapper @@ -8,7 +8,7 @@ metadata: - path: cli/src/engine-native/exec.ts lines: "1-351" - path: cli/src/engine-native/deps.ts - lines: "1-224" + lines: "1-247" - path: cli/src/engine-native/os/types.ts lines: "1-40" - path: cli/src/engine-native/os/index.ts @@ -30,10 +30,10 @@ metadata: - path: cli/src/engine-native/logger.ts lines: "1-275" - path: cli/src/engine-native/services.ts - lines: "1-88" + lines: "1-92" - path: cli/src/services.ts lines: "1-42" - updated: "2026-12-01" + updated: "2026-12-02" --- # Host Platform Layer @@ -68,8 +68,8 @@ Output channels, change detection, the missing-dependency warn shape, and the li | Sync child | `spawnHost(cmd, args, overrides, host)` | `cli/src/engine-native/exec.ts` — `spawnHost` — resolves suffixes, applies `host.invoke`, and passes that invocation's `windowsVerbatimArguments`. Only a `.cmd`/`.bat` shim sets the flag (verify: `bunx vitest run cli/test/unit/os/windows.test.ts -t "normalizes and escapes the Windows command shim path"`; verify: `bunx vitest run cli/test/unit/os/windows.test.ts -t "invokes an executable directly with its arguments untouched"`). Unprobed: no unit test reads the options that `spawnHost` gives `spawnSync` (verify: `grep -n "windowsVerbatimArguments: invocation" cli/src/engine-native/exec.ts`) | | Async child | `spawnProcess(cmd, args, { stdio, cwd, env, host, timeoutMs })` | `exec.ts` — `spawnProcess` — default stdio discards stderr; pass `["ignore","pipe","pipe"]` when the caller prints `processFailureSummary`; `env` replaces the child environment, else the child gets the environment of the process | | Bounded probe | `captureWithin(cmd, args, ms)` → `output`/`failed`/`timed-out` | `exec.ts` — `captureWithin`, `killProcessTree` — POSIX children lead their own group (`detached`) and die by negative pid; Windows runs `taskkill /T /F` from `SystemRoot\System32` (`C:\Windows` when unset; unlike `commandInterpreter`, the value is not checked for an absolute path) | -| Version read | `deps.resolveVersionReading` | `cli/src/engine-native/deps.ts` — `VERSION_PROBE_LIMIT_MS` — keeps "no answer in time" apart from "no version" (verify: `grep -n VERSION_PROBE_LIMIT_MS cli/src/engine-native/deps.ts`) | -| Presence | `ctx.services.deps.probe(id)` | `deps.ts` — `pathProbe`, `findBun` — Bun must resolve to an absolute path because callers run it outside the sync working directory | +| Version read | `deps.resolveVersion` (an Effect) | `cli/src/engine-native/deps.ts` — `VERSION_PROBE_LIMIT_MS` — the default bounded reader (` --version` through `captureWithin`) reads a failed command and a probe that does not answer in time as no version (""). A spec with its own `version` reader (Bun, omp) has no time limit. A throw or a rejection of an executor call is not a version: it fails the Effect with `LegacyStepFailed` (verify: `bunx vitest run cli/test/unit/deps.test.ts -t "does not answer within the limit"`) | +| Presence | `ctx.services.deps.probe(id)` (an Effect) | `deps.ts` — `pathProbe`, `findBun` — Bun must resolve to an absolute path because callers run it outside the sync working directory. `probe`, `version`, and `path` are Effects; their calls into the executor (`exec.ts`) and `home.ts engineHome` go through `bridge.ts bridgeSync` or `bridgePromise` until #297, so a throw or a rejection there is `LegacyStepFailed`. The `ProbeExecutor` test doubles keep the shapes of the `exec.ts` functions | | Missing tool warning | `ctx.services.deps.warnMissing(id, logger, context)` | `cli/src/engine-native/services.ts` — `makeDependencyManager` — one warning per tool per manager | | Host fact | `hostOs(ctx.services.platform.name())` | `cli/src/engine-native/os/types.ts` — `HostOs` — facts that cannot be probed only | | Supported host | `HOST_TARGETS` | `cli/src/engine-native/os/targets.ts` — `HOST_TARGETS` — adding a row adds a host. `hostTargets.test.ts` checks the table against the host checks of the Bash and PowerShell launchers (verify: `bunx vitest run cli/test/unit/hostTargets.test.ts -t "keeps the Bash launcher aligned with every POSIX host target"`; verify: `bunx vitest run cli/test/unit/hostTargets.test.ts -t "keeps the PowerShell launcher aligned with every Windows host target"`) | diff --git a/.agents/skills/omp-sync-context/SKILL.md b/.agents/skills/omp-sync-context/SKILL.md index 2fec0128..64db5741 100644 --- a/.agents/skills/omp-sync-context/SKILL.md +++ b/.agents/skills/omp-sync-context/SKILL.md @@ -10,7 +10,7 @@ metadata: - path: cli/src/engine-native/ompFileDeploy.ts lines: "1-131" - path: cli/src/engine-native/ompPlugins.ts - lines: "1-436" + lines: "1-434" - path: cli/src/engine-native/ompKitPlugin.ts lines: "1-164" - path: cli/src/engine-native/ompRemovals.ts @@ -87,9 +87,10 @@ the run with `PluginFileRemoveFailed`, and a failed folder removal with `FileSystem.remove` adapter of Bun 1.4.5 reports `EPERM` as `EFAULT`. The calls of the passes into `atomicWrite.ts`, `exec.ts` (through -`ompChild.ts spawnOmp`), the dependency probes, and the logger (also through -`recordFailure` and `deps.warnMissing`) stay behind `bridge.ts bridgeSync` or -`bridgePromise` until #297 and #298. +`ompChild.ts spawnOmp`), and the logger (also through `recordFailure` and +`deps.warnMissing`) stay behind `bridge.ts bridgeSync` or `bridgePromise` +until #297. The dependency probes are Effects since #298, so the plugin pass +calls them directly. Every text read that a comparison or a parser uses goes through `fileText.ts readTextKeepingBom`, which keeps a leading byte order mark, as `readFileSync(path, "utf8")` did; `FileSystem.readFileString` drops it. diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md index db832744..0c55dc55 100644 --- a/.agents/skills/sync-orchestration-context/SKILL.md +++ b/.agents/skills/sync-orchestration-context/SKILL.md @@ -50,11 +50,11 @@ metadata: - path: cli/src/engine-native/parseHelp.ts lines: "1-31" - path: cli/src/engine-native/modes.ts - lines: "1-69" + lines: "1-66" - path: cli/src/engine-native/ompSync.ts lines: "1-151" - path: cli/src/engine-native/ompPlugins.ts - lines: "1-436" + lines: "1-434" - path: cli/src/engine-native/bun.ts lines: "1-120" - path: cli/src/engine-native/toolchain.ts @@ -222,18 +222,20 @@ writing sync runs `lockedSync` in one lock scope (see § Sync Lock): Each call into a module that a later child of plan #290 moves runs through `bridge.ts bridgeSync` or `bridgePromise`, so an interrupt waits until that step settles (`references/dispatch-flow.md`). The omp passes are Effect code -(#296): only their calls into the logger, `atomicWrite.ts`, `exec.ts`, and -the dependency probes are bridged. The bridge text of a failure is -`bridge.ts failureText`, which never coerces the thrown value. `kitHome()` -(`cli/src/kitHome.ts`, #297) is bridged the same way, and `makeCtx` maps its -`LegacyStepFailed` to `KitHomeInvalid` with the original message and cause. -A failed `FileSystem` operation of a pass fails the run with its -`PlatformError`, a YAML merge or prune with `OmpYamlInvalid`, and a removal of -the kit plugin prune with `PluginFileRemoveFailed` or -`PluginFolderRemoveFailed`; `engine.ts engineFailureDetail` prints the -message of the Node error or of the YAML failure, as the bridge did. An -existence probe, the marketplace registry read, and the removal of the retired -upgrade log do not fail the run (`omp-sync-context`). +(#296): only their calls into the logger, `atomicWrite.ts`, and `exec.ts` are +bridged. The toolchain passes and the dependency probes are Effect code too +(#298), and the Bun bootstrap runs as one uninterruptible region. The bridge +text of a failure is `bridge.ts failureText`, which never coerces the thrown +value. `kitHome()` (`cli/src/kitHome.ts`, #297) is bridged the same way, and +`makeCtx` maps its `LegacyStepFailed` to `KitHomeInvalid` with the original +message and cause. A failed `FileSystem` operation of a pass fails the run +with its `PlatformError`, a YAML merge or prune with `OmpYamlInvalid`, a +removal of the kit plugin prune with `PluginFileRemoveFailed` or +`PluginFolderRemoveFailed`, and the temporary installer folder of the Bun +bootstrap with `BunInstallFolderFailed`; `engine.ts engineFailureDetail` +prints the message of the Node error or of the YAML failure, as the bridge +did. An existence probe, the marketplace registry read, and the removal of +the retired upgrade log do not fail the run (`omp-sync-context`). While an engine run is active, a SIGINT or SIGTERM ends the process at once, as before the Effect seam, because a bridged pass cannot stop its `omp` or @@ -242,10 +244,16 @@ exitOnSignal(PUBLIC_SIGNAL_EXIT_CODES)` in `engine.ts`, installed only for the run) and 130 or 143 on the raw channel (`exitOnSignal(RAW_SIGNAL_EXIT_CODES)` in `main.ts`). The exception is a started mutation of a pass (a write or copy with its chmod, a directory creation with its chmod, a removal, or a -`replaceFile` call): it runs in `signalGuard.ts mutationRegion`, which is -uninterruptible and inside `deferSignalExit`, so a signal during it is -recorded and the process exits with that code once the mutation settled. The -OS releases the locks with the process. +`replaceFile` call) that runs in `signalGuard.ts mutationRegion`, which is +uninterruptible and inside `deferSignalExit`: a signal during it is recorded +and the process exits with that code once the mutation settled. Only +`mutationRegion` defers a signal. The Bun bootstrap runs under a fiber +interruption mask, not in `mutationRegion`, and that mask does not defer the +signal handler: the handler ends the process as soon as it runs, also during +the installer or the folder creation. A synchronous call blocks the handler +until it returns: a signal during the `rmSync` removal of the installer folder +runs the handler only after the removal ends. The OS releases the locks with +the process. (verify: `bunx vitest run cli/test/unit/syncSignals.test.ts`) The omp pipeline reads SoT from the embedded payload. @@ -282,12 +290,15 @@ lock module). returns 1 before the pipeline. - Every lock of a sync is an `Effect.acquireRelease` in one scope, so it goes when the scope closes: after the run, a failure, or an interrupt. An - in-process interrupt during a bridged pass or a started mutation waits until - it settles, and the locks stay held until then. A SIGINT or SIGTERM ends the - process at once, except inside a started mutation, which `deferSignalExit` - lets settle first (see § Dispatch Order), and the OS releases the locks with - it. - (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted bridged pass settles"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "finishes a started deploy write with its chmod"`, and `bunx vitest run cli/test/unit/syncLock.test.ts -t "lock wait deadline"`) + in-process interrupt during a bridged pass, the Bun bootstrap, or a started + mutation waits until it settles, and the locks stay held until then. A + SIGINT or SIGTERM ends the process at once, except inside a started mutation + in `mutationRegion`, which `deferSignalExit` lets settle first (see + § Dispatch Order), and the OS releases the locks with it. The interruption + mask of the Bun bootstrap does not defer the signal handler, but a + synchronous call, such as the removal of the installer folder, delays the + handler until that call returns. + (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted Bun bootstrap settles"`, `bunx vitest run cli/test/unit/bridge.test.ts -t "ends an interrupted run only after the bridged Promise settles"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "finishes a started deploy write with its chmod"`, and `bunx vitest run cli/test/unit/syncLock.test.ts -t "lock wait deadline"`) (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "exits 1 with the held line and leaves HOME unchanged"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "takes no lock in a dry run"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "rejects an unknown argument with exit 2 before it takes the lock"`, `bunx vitest run cli/test/unit/engine-di.test.ts -t "with exit 2 before it takes a lock or writes an omp file"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "exits 2 when the lock wait is not a non-negative safe integer"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "DRY_RUN env global"`, and `bunx vitest run cli/test/unit/syncLock.test.ts -t "prints the help with -h and --help while another sync holds the lock"`) diff --git a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md index 1ee2c99e..f60cb329 100644 --- a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md +++ b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md @@ -93,9 +93,8 @@ runEngineNative(argv, options?) index.ts; an Effect ``` Each call from this Effect code into a module that a later child of plan -#290 moves (`bun.ts`, `toolchain.ts`, `home.ts`, `../kitHome.ts`, and the -logger, the atomic writer, the `exec.ts` spawns, and the dependency probes -that the omp passes call) goes through `bridge.ts bridgeSync` or +#290 moves (`home.ts`, `../kitHome.ts`, the logger, the atomic writer, and +the `exec.ts` spawns) goes through `bridge.ts bridgeSync` or `bridgePromise`. A bridged step runs without interruption, so an interrupt of a sync waits until it settles, and the scope keeps the sync lock and the folder locks until then; a throw or a rejection is `LegacyStepFailed`. @@ -110,14 +109,25 @@ and `ompFileDeploy.ts syncMergedYaml` converts that result with `deferSignalExit`. The ledger stays a plain append (`failures.ts recordFailure`); the plugin pass and `ompSync` call it through `bridgeSync` until #297, because its warning goes through the logger. -(verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted bridged pass settles"`) +The toolchain passes are Effect code since #298 and are not bridged: +`toolchain.ts`, `deps.ts` (the dependency probes), and `bun.ts` (not bridged). +The Bun bootstrap runs as one uninterruptible region, so an in-process +interrupt of a sync also waits until it ends. That region is a fiber +interruption mask only, not a `mutationRegion`, and it does not defer the +signal handler: a SIGINT or SIGTERM during the bootstrap ends the process as +soon as the handler runs. A synchronous call blocks the handler until it +returns, so a signal during the `rmSync` removal of the installer folder ends +the process only after the removal ends. +(verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted Bun bootstrap settles"` +for the Bun bootstrap, and `bunx vitest run cli/test/unit/bridge.test.ts -t "ends an interrupted run only after the bridged Promise settles"` +for a bridged step) `ompSync` owns its step order. Read the function body, not a copy here (verify: `sed -n '/^export const ompSync/,/^});/p' cli/src/engine-native/ompSync.ts`). The order rules that matter: -- `ompSync` starts with `bun.ts bunBootstrap`, which is memoized on - `ctx.bunRuntime` for the engine run. +- `ompSync` starts with `bun.ts bunBootstrap`. The run-owned `Deferred` + `ctx.bunRuntime` keeps its outcome, so the engine run bootstraps Bun once. - A writing sync runs under the sync lock and the folder locks, so two syncs never run the read-modify-write of one file at the same time. `SKILL.md` § Sync Lock owns the lock rules. diff --git a/.agents/skills/toolchain-context/SKILL.md b/.agents/skills/toolchain-context/SKILL.md index 1dcd75e9..e837bcf8 100644 --- a/.agents/skills/toolchain-context/SKILL.md +++ b/.agents/skills/toolchain-context/SKILL.md @@ -8,22 +8,22 @@ metadata: - path: cli/src/commands/toolchain.ts lines: "1-72" - path: cli/src/engine-native/modes.ts - lines: "1-67" + lines: "1-66" - path: cli/src/engine-native/toolchain.ts - lines: "1-237" + lines: "1-295" - path: cli/src/engine-native/bun.ts - lines: "1-120" + lines: "1-221" - path: cli/src/engine-native/deps.ts - lines: "1-224" + lines: "1-247" - path: cli/src/engine-native/kitDb.ts lines: "1-177" - path: cli/src/engine-native/ompSync.ts - lines: "1-122" + lines: "1-152" - path: cli/src/engine-native/sharedTypes.d.ts lines: "1-12" - path: SoT/toolchain.json lines: "1-15" - updated: "2026-11-27" + updated: "2026-12-02" --- # Toolchain Verified-Version Floors @@ -32,6 +32,14 @@ metadata: probes and comparison, and the doctor report table. `bun.ts bunBootstrap` owns the only managed install. +The toolchain passes are Effects (#298): `present`, `installedVersion`, +`report`, `latestUpstream`, `outdatedReport`, and `bunBootstrap`, and also the +dependency methods `probe`, `version`, and `path` of `services.ts +DependencyManager`. Their calls into `exec.ts`, `home.ts`, `kitDb.ts`, and the +logger go through `bridge.ts bridgeSync` or `bridgePromise` until #297, so a +throw or a rejection there is `LegacyStepFailed`. `field`, `isNewer`, and +`belowFloor` stay plain functions. + Pointers here name concepts, not coordinates — if a path or symbol moved, trust the stated purpose and re-locate it (grep the symbol) before acting. @@ -88,14 +96,17 @@ verify: `bunx vitest run cli/test/unit/toolchain.test.ts -t "engine toolchain ve `toolchain outdated [--refresh]` runs `modeToolchain` -> `outdatedReport`. 1. `outdatedReport` selects the manifest tools that have both `verified` and - `upstream`, in manifest order. + `upstream`, in manifest order. The lookups run at the same time + (`Effect.all`, unbounded concurrency). Each lookup recovers its own lookup + failure, so a failed lookup does not stop another lookup. 2. `latestUpstream` reads the kit cache (`kitDb.ts readCache`, key `upstream:`, max age `toolchain.ts UPSTREAM_CACHE_MS`) unless `--refresh` is set. 3. On a miss it reads the GitHub latest release tag of `upstream.github` with `tagPrefix` stripped (a tag without that prefix fails the lookup). GitHub is the only upstream source. `GITHUB_TOKEN` or `GH_TOKEN` adds a bearer - token. + token. The request and the body read run in one `Effect.tryPromise` under + one 8 s deadline (`AbortSignal.timeout`). 4. Only a successful lookup is cached. A failure prints `lookup failed: ` in the row, and the command still exits 0. 5. `isNewer(latest, verified)` sets `newer`; anything else is `current`. @@ -103,13 +114,15 @@ verify: `bunx vitest run cli/test/unit/toolchain.test.ts -t "engine toolchain ve The report never installs anything and never edits a pin. `toolchain check` stays offline. verify: `bunx vitest run cli/test/unit/toolchainOutdated.test.ts -t "toolchain outdated"` -(failed lookup still exits 0; a transport failure is retried, not cached). +(failed lookup still exits 0; a transport failure is retried, not cached; the +`spawned CLI` case runs `toolchain outdated` with every proxy variable set to a +local listener and proves that a fresh cache answers without a connection). ## Managed Install | Tool | Owner | Notes | |------|-------|-------| -| `bun` | `bun.ts bunBootstrap, per-engine-run memo` | Resolves an existing Bun or download-then-runs the pinned installer once per EngineNative invocation; every caller shares the memoized result: `modes.ts modeToolchain` (`toolchain ensure bun`) and `ompSync.ts ompSync` (Bun bootstrap before the omp file deploys). | +| `bun` | `bun.ts bunBootstrap, per-engine-run memo` | Resolves an existing Bun or download-then-runs the pinned installer once per EngineNative invocation. The first call keeps the outcome in a run-owned `Deferred` (`Ctx.bunRuntime`). Each later or concurrent call of the same run waits for that outcome without interruption; each engine run has its own. The bootstrap runs as one uninterruptible region: it makes the temporary folder, runs the installer, and deletes the folder. When it cannot make or delete the folder, the run fails with `BunInstallFolderFailed` and the message of the file system error, in place of the installer outcome. Callers: `modes.ts modeToolchain` (`toolchain ensure bun`) and `ompSync.ts ompSync` (Bun bootstrap before the omp file deploys). | verify: `grep -rn 'bunBootstrap(' cli/src/engine-native` lists the callers; `bunx vitest run cli/test/unit/bun.test.ts -t "per-run Bun bootstrap"`. diff --git a/cli/src/engine-native/bun.ts b/cli/src/engine-native/bun.ts index 584c64cc..16794f6a 100644 --- a/cli/src/engine-native/bun.ts +++ b/cli/src/engine-native/bun.ts @@ -1,6 +1,14 @@ -import { mkdtempSync, rmSync } from "node:fs"; +/** + * The one managed install: Bun. `bunBootstrap` resolves an existing Bun or + * runs the pinned installer once per engine run. Its calls into the process + * layer (`exec.ts spawnProcess`) and the logger, which a later child of plan + * #290 moves, run through the bridge. + */ +import { mkdtemp, rmSync } from "node:fs"; import { tmpdir } from "node:os"; +import { Deferred, Effect, Schema } from "effect"; +import { bridgePromise, bridgeSync, failureText, type LegacyStepFailed } from "./bridge"; import { p, spawnProcess, type AsyncProcessOptions, type AsyncProcessResult } from "./exec"; import type { Ctx } from "./index"; import type { EngineServices } from "./services"; @@ -14,6 +22,34 @@ export type BunRuntimeState = readonly reason: "missing-curl" | "download-failed" | "installer-failed" | "install-failed"; }; +const ready = (executable: string): BunRuntimeState => ({ kind: "ready", executable }); + +const deferred = ( + reason: Extract["reason"], +): BunRuntimeState => ({ kind: "deferred", reason }); + +/** + * The bootstrap could not make or remove its temporary installer folder; + * `message` is the message of the file system error, which `cause` keeps. + */ +export class BunInstallFolderFailed extends Schema.TaggedError< + BunInstallFolderFailed, + { readonly brand: unique symbol } +>()("BunInstallFolderFailed", { + path: Schema.String, + message: Schema.String, + cause: Schema.Defect(), +}) {} + +/** A failed bootstrap: a bridged call threw or rejected, or the installer folder failed. */ +export type BunBootstrapFailure = LegacyStepFailed | BunInstallFolderFailed; + +const INSTALL_FOLDER_PREFIX = "docks-kit-bun-"; + +/** The installer folder at `path` failed; `cause` is the Node error. */ +const installFolderFailed = (path: string, cause: unknown): BunInstallFolderFailed => + new BunInstallFolderFailed({ path, message: failureText(cause), cause }); + function predictedExecutable(ctx: Ctx, host: HostOs = hostOs()): string { const root = process.env["BUN_INSTALL"] !== undefined && process.env["BUN_INSTALL"] !== "" @@ -42,79 +78,144 @@ function processFailure(result: AsyncProcessResult): string { ); } -async function installBun( +const installBun = ( pin: string, directory: string, - host: HostOs = hostOs(), -): Promise { - const options: AsyncProcessOptions = { stdio: ["ignore", "ignore", "pipe"] }; - const installer = host.bunInstaller(pin, directory); - const download = await spawnProcess(installer.download.command, installer.download.args, options); - if (download.error !== undefined || download.exitCode !== 0) { - return { ok: false, reason: "download-failed", detail: processFailure(download) }; - } - const install = await spawnProcess(installer.run.command, installer.run.args, options); - if (install.error !== undefined || install.exitCode !== 0) { - return { ok: false, reason: "installer-failed", detail: processFailure(install) }; - } - return { ok: true }; -} + host: HostOs, +): Effect.Effect => + Effect.gen(function* () { + const options: AsyncProcessOptions = { stdio: ["ignore", "ignore", "pipe"] }; + const installer = host.bunInstaller(pin, directory); + const download = yield* bridgePromise("spawnProcess", () => + spawnProcess(installer.download.command, installer.download.args, options), + ); + if (download.error !== undefined || download.exitCode !== 0) { + const failed: BunInstallResult = { + ok: false, + reason: "download-failed", + detail: processFailure(download), + }; + return failed; + } + const install = yield* bridgePromise("spawnProcess", () => + spawnProcess(installer.run.command, installer.run.args, options), + ); + if (install.error !== undefined || install.exitCode !== 0) { + const failed: BunInstallResult = { + ok: false, + reason: "installer-failed", + detail: processFailure(install), + }; + return failed; + } + const installed: BunInstallResult = { ok: true }; + return installed; + }); -export function bunBootstrap(ctx: Ctx, services: EngineServices): Promise { - if (ctx.bunRuntime !== undefined) return ctx.bunRuntime; - const pending = runBunBootstrap(ctx, services); - ctx.bunRuntime = pending; - return pending; -} +/** + * The Bun runtime of this engine run. The first call runs the bootstrap and + * keeps its outcome in the run context (`Ctx.bunRuntime`); every later or + * concurrent call of the same run waits for that outcome, so one run installs + * Bun at most once. The bootstrap runs without interruption, as the bridged + * Promise did, and a waiter waits without interruption until it settles. + */ +export const bunBootstrap = ( + ctx: Ctx, + services: EngineServices, +): Effect.Effect => + Effect.uninterruptible( + Effect.suspend(() => { + const shared = ctx.bunRuntime; + if (shared !== undefined) return Deferred.await(shared); + // The check and the claim run in one synchronous step, so a second caller sees the claim. + const outcome = Deferred.makeUnsafe(); + ctx.bunRuntime = outcome; + return Effect.exit(runBunBootstrap(ctx, services)).pipe( + Effect.flatMap((exit) => Effect.andThen(Deferred.done(outcome, exit), exit)), + ); + }), + ); -async function runBunBootstrap(ctx: Ctx, services: EngineServices): Promise { - const host = hostOs(services.platform.name()); - - const existing = await services.deps.path("bun"); - if (existing !== "") return { kind: "ready", executable: existing }; - - const pin = field("bun", "verified"); - if (pin === "") { - services.logger.warn("Bun bootstrap aborted — SoT/toolchain.json has no verified Bun pin"); - return { kind: "deferred", reason: "install-failed" }; - } - if (services.deps.probe("curl").state === "missing") { - services.deps.warnMissing( - "curl", - services.logger, - "cannot bootstrap Bun; install Bun manually, then re-run sync", - ); - return { kind: "deferred", reason: "missing-curl" }; - } - if (ctx.dryRun) { - const executable = predictedExecutable(ctx, host); - services.logger.echo(`[dry-run] install Bun ${pin} (kit-verified) -> ${executable}`); - return { kind: "ready", executable }; - } - services.logger.warn(`Bun not found — installing Bun ${pin} (kit-verified)...`); - const temporaryDir = mkdtempSync(p(tmpdir(), "docks-kit-bun-")); - let result: BunInstallResult; - try { - result = await installBun(pin, temporaryDir, host); - } finally { - rmSync(temporaryDir, { recursive: true, force: true }); - } - if (!result.ok) { - const stage = result.reason === "download-failed" ? "installer download" : "installer"; - services.logger.warn( - `Bun ${stage} failed (${result.detail}). Install Bun manually from https://bun.sh/docs/installation, then re-run sync.`, +const runBunBootstrap = ( + ctx: Ctx, + services: EngineServices, +): Effect.Effect => + Effect.gen(function* () { + const host = hostOs(services.platform.name()); + const { logger } = services; + + const existing = yield* services.deps.path("bun"); + if (existing !== "") return ready(existing); + + const pin = field("bun", "verified"); + if (pin === "") { + yield* bridgeSync("logger", () => + logger.warn("Bun bootstrap aborted — SoT/toolchain.json has no verified Bun pin"), + ); + return deferred("install-failed"); + } + if ((yield* services.deps.probe("curl")).state === "missing") { + yield* bridgeSync("logger", () => + services.deps.warnMissing( + "curl", + logger, + "cannot bootstrap Bun; install Bun manually, then re-run sync", + ), + ); + return deferred("missing-curl"); + } + if (ctx.dryRun) { + const executable = predictedExecutable(ctx, host); + yield* bridgeSync("logger", () => + logger.echo(`[dry-run] install Bun ${pin} (kit-verified) -> ${executable}`), + ); + return ready(executable); + } + yield* bridgeSync("logger", () => + logger.warn(`Bun not found — installing Bun ${pin} (kit-verified)...`), ); - return { kind: "deferred", reason: result.reason }; - } + // The prefix goes to the OS as written, as `mkdtempSync` got it before: the OS + // resolves a symlink in TMPDIR before a following `..`, and a path join would not. + const folderPrefix = p(tmpdir(), INSTALL_FOLDER_PREFIX); + const temporaryDir = yield* Effect.callback((resume) => { + mkdtemp(folderPrefix, (error, folder) => + resume( + error === null + ? Effect.succeed(folder) + : Effect.fail(installFolderFailed(folderPrefix, error)), + ), + ); + }); + const installed = yield* Effect.exit(installBun(pin, temporaryDir, host)); + // A failed removal replaces the installer outcome, as the former `finally` block did. + // `rmSync` keeps the Node error: the `FileSystem.remove` adapter of Bun 1.4.5 reports `EPERM` as `EFAULT`. + yield* Effect.try({ + try: () => rmSync(temporaryDir, { recursive: true, force: true }), + catch: (cause) => installFolderFailed(temporaryDir, cause), + }); + const result = yield* installed; + if (!result.ok) { + const stage = result.reason === "download-failed" ? "installer download" : "installer"; + yield* bridgeSync("logger", () => + logger.warn( + `Bun ${stage} failed (${result.detail}). Install Bun manually from https://bun.sh/docs/installation, then re-run sync.`, + ), + ); + return deferred(result.reason); + } - const installed = await services.deps.path("bun"); - if (installed === "") { - services.logger.warn( - "Bun install failed. Install manually from https://bun.sh/docs/installation, then re-run sync.", + const executable = yield* services.deps.path("bun"); + if (executable === "") { + yield* bridgeSync("logger", () => + logger.warn( + "Bun install failed. Install manually from https://bun.sh/docs/installation, then re-run sync.", + ), + ); + return deferred("install-failed"); + } + const version = yield* services.deps.version("bun"); + yield* bridgeSync("logger", () => + logger.change(`Bun installed (${version !== "" ? version : "version unknown"})`), ); - return { kind: "deferred", reason: "install-failed" }; - } - const version = await services.deps.version("bun"); - services.logger.change(`Bun installed (${version !== "" ? version : "version unknown"})`); - return { kind: "ready", executable: installed }; -} + return ready(executable); + }); diff --git a/cli/src/engine-native/deps.ts b/cli/src/engine-native/deps.ts index 9153f42a..f5a22bdf 100644 --- a/cli/src/engine-native/deps.ts +++ b/cli/src/engine-native/deps.ts @@ -6,10 +6,17 @@ * policy, and the doctor report, while bun.ts bunBootstrap owns the one managed * install; this registry owns WHICH external tools exist and the one-line * command that installs a missing one. + * + * The probes are Effects. Their calls into the executor (`exec.ts`) and into + * `home.ts engineHome`, which a later child of plan #290 moves, run through + * the bridge, so a probe fails with `LegacyStepFailed` when such a call throws + * or rejects. */ import { isAbsolute } from "node:path"; +import { Effect } from "effect"; -import { capture, captureWithin, commandExists, p, which, type CaptureOutcome } from "./exec"; +import { bridgePromise, bridgeSync, type LegacyStepFailed } from "./bridge"; +import { capture, captureWithin, commandExists, p, which } from "./exec"; import { engineHome } from "./home"; import { hostOs, platformName, rawPlatform } from "./os"; import type { HostOs, Invocation } from "./os/types"; @@ -21,23 +28,15 @@ export type ProbeResult = | { readonly state: "present"; readonly path?: string } | { readonly state: "missing" }; +/** The calls of a probe into the process layer, with the shapes of the `exec.ts` functions. */ export interface ProbeExecutor { readonly commandExists: (name: string) => boolean; - readonly capture: (cmd: string, args: ReadonlyArray) => Promise; + readonly capture: typeof capture; /** `capture` with a time limit. Without it, a version probe has no limit. */ - readonly captureWithin?: ( - cmd: string, - args: ReadonlyArray, - timeoutMs: number, - ) => Promise; + readonly captureWithin?: typeof captureWithin; readonly which: (name: string) => string; } -/** The version text ("" when the tool is absent or prints none), or no answer in time. */ -export type VersionReading = - | { readonly kind: "version"; readonly value: string } - | { readonly kind: "timed-out" }; - /** * The longest wait for a ` --version` answer. A cold rust-analyzer start * once took 20 s on a macOS runner (#114), so the limit leaves room for slow @@ -45,22 +44,34 @@ export type VersionReading = */ export const VERSION_PROBE_LIMIT_MS = 60_000; +/** How a spec finds its tool, for the host of `platform`. */ +type Resolver = ( + exec: ProbeExecutor, + platform: NodeJS.Platform, +) => Effect.Effect; + +/** How a spec reads its version, for the host of `platform`. */ +type VersionReader = ( + exec: ProbeExecutor, + platform: NodeJS.Platform, +) => Effect.Effect; + export interface DependencySpec { readonly id: ToolId; readonly versionArgs: ReadonlyArray; /** Platform-correct one-line install command (param injectable for tests). */ readonly installHint: (platform?: NodeJS.Platform) => string; - readonly resolve?: (exec: ProbeExecutor, platform: NodeJS.Platform) => ProbeResult; + readonly resolve?: Resolver; /** * Reads the version in a different way than ` `, for the host of `platform`. * This reader has no time limit. */ - readonly version?: (exec: ProbeExecutor, platform: NodeJS.Platform) => Promise; + readonly version?: VersionReader; } interface SpecOptions { - readonly resolve?: (exec: ProbeExecutor, platform: NodeJS.Platform) => ProbeResult; - readonly version?: (exec: ProbeExecutor, platform: NodeJS.Platform) => Promise; + readonly resolve?: Resolver; + readonly version?: VersionReader; } const spec = ( @@ -102,15 +113,29 @@ function bunInstallHint(pf: NodeJS.Platform = rawPlatform()): string { return `tmp=$(mktemp -d) && ${commandLine(download)} && ${commandLine(run)}`; } +const MISSING: ProbeResult = { state: "missing" }; + +const whichOf = (exec: ProbeExecutor, name: string) => bridgeSync("which", () => exec.which(name)); + +const captureOf = (exec: ProbeExecutor, cmd: string, args: ReadonlyArray) => + bridgePromise("capture", () => exec.capture(cmd, args)); + // Presence is the injected executor's verdict; `which` only resolves WHERE the // tool is, which on Windows is the `.cmd`/`.exe` candidate rather than the name. const pathProbe = - (id: string): ((exec: ProbeExecutor) => ProbeResult) => - (exec) => { - if (!exec.commandExists(id)) return { state: "missing" }; - const path = exec.which(id); - return path === "" ? { state: "present" } : { state: "present", path }; - }; + (id: string) => + (exec: ProbeExecutor): Effect.Effect => + Effect.gen(function* () { + if (!(yield* bridgeSync("commandExists", () => exec.commandExists(id)))) return MISSING; + const path = yield* whichOf(exec, id); + const found: ProbeResult = path === "" ? { state: "present" } : { state: "present", path }; + return found; + }); + +interface FoundBun { + readonly command: string; + readonly path: string; +} /** * Bun on PATH, else the first folder of the host's Bun search (`HostOs.bunSearch`), the list that @@ -121,25 +146,31 @@ const pathProbe = const findBun = ( exec: ProbeExecutor, host: HostOs, -): { command: string; path: string } | undefined => { - const onPath = exec.which("bun"); - if (onPath !== "" && isAbsolute(onPath)) { - return { command: "bun", path: onPath }; - } - const home = engineHome(); - const bunInstall = process.env["BUN_INSTALL"]; - const bunRoot = bunInstall !== undefined && bunInstall !== "" ? bunInstall : p(home, ".bun"); - for (const entry of host.bunSearch) { - const found = exec.which(p(entry.base === "bunRoot" ? bunRoot : home, ...entry.rest)); - if (found !== "" && isAbsolute(found)) return { command: found, path: found }; - } - return undefined; -}; - -const resolveBun = (exec: ProbeExecutor, platform: NodeJS.Platform): ProbeResult => { - const bun = findBun(exec, hostOs(platformName(platform))); - return bun === undefined ? { state: "missing" } : { state: "present", path: bun.path }; -}; +): Effect.Effect => + Effect.gen(function* () { + const onPath = yield* whichOf(exec, "bun"); + if (onPath !== "" && isAbsolute(onPath)) { + return { command: "bun", path: onPath }; + } + const home = yield* bridgeSync("engineHome", () => engineHome()); + const bunInstall = process.env["BUN_INSTALL"]; + const bunRoot = bunInstall !== undefined && bunInstall !== "" ? bunInstall : p(home, ".bun"); + for (const entry of host.bunSearch) { + const found = yield* whichOf( + exec, + p(entry.base === "bunRoot" ? bunRoot : home, ...entry.rest), + ); + if (found !== "" && isAbsolute(found)) return { command: found, path: found }; + } + return undefined; + }); + +const resolveBun: Resolver = (exec, platform) => + findBun(exec, hostOs(platformName(platform))).pipe( + Effect.map((bun): ProbeResult => + bun === undefined ? MISSING : { state: "present", path: bun.path }, + ), + ); export const defaultProbeExecutor: ProbeExecutor = { commandExists, capture, captureWithin, which }; @@ -156,74 +187,61 @@ export const DEPENDENCIES: Record = { () => "install omp from https://github.com/can1357/oh-my-pi (an existing install updates with `omp update`, or through the tool that manages it, such as Tern)", { - version: async (exec) => - (await exec.capture("omp", ["--version"])).trim().replace(/^omp[/v]/, ""), + version: (exec) => + captureOf(exec, "omp", ["--version"]).pipe( + Effect.map((out) => out.trim().replace(/^omp[/v]/, "")), + ), }, ), bun: spec("bun", bunInstallHint, { resolve: resolveBun, - version: async (exec, platform) => { - const bun = findBun(exec, hostOs(platformName(platform))); - if (bun === undefined) return ""; - return await exec.capture(bun.command, ["--version"]); - }, + version: (exec, platform) => + findBun(exec, hostOs(platformName(platform))).pipe( + Effect.flatMap((bun) => + bun === undefined ? Effect.succeed("") : captureOf(exec, bun.command, ["--version"]), + ), + ), }), }; -export function resolveDependency( +export const resolveDependency = Effect.fn("resolveDependency")(function* ( specification: DependencySpec, exec: ProbeExecutor, platform: NodeJS.Platform = rawPlatform(), -): ProbeResult { - return (specification.resolve ?? pathProbe(specification.id))(exec, platform); -} +) { + return yield* (specification.resolve ?? pathProbe(specification.id))(exec, platform); +}); /** * Reads the version with ` ` under `VERSION_PROBE_LIMIT_MS`, - * or with the spec's own `version` reader. An executor without - * `captureWithin` reads without a limit and never reports `timed-out`. + * or with the spec's own `version` reader. An absent tool, a failed probe, + * and a probe that does not answer in time read as no version (""). An + * executor without `captureWithin` reads without a limit. */ -export async function resolveVersionReading( +export const resolveVersion = Effect.fn("resolveVersion")(function* ( specification: DependencySpec, exec: ProbeExecutor, platform: NodeJS.Platform = rawPlatform(), -): Promise { - if (resolveDependency(specification, exec, platform).state !== "present") { - return { kind: "version", value: "" }; +) { + if ((yield* resolveDependency(specification, exec, platform)).state !== "present") return ""; + if (specification.version !== undefined) return yield* specification.version(exec, platform); + const bounded = exec.captureWithin; + if (bounded === undefined) { + return yield* captureOf(exec, specification.id, specification.versionArgs); } - if (specification.version !== undefined) { - return { kind: "version", value: await specification.version(exec, platform) }; - } - if (exec.captureWithin === undefined) { - return { - kind: "version", - value: await exec.capture(specification.id, specification.versionArgs), - }; - } - const outcome = await exec.captureWithin( - specification.id, - specification.versionArgs, - VERSION_PROBE_LIMIT_MS, + // The executor stays the receiver, as a method call of `exec` would keep it. + const outcome = yield* bridgePromise("captureWithin", () => + bounded.call(exec, specification.id, specification.versionArgs, VERSION_PROBE_LIMIT_MS), ); - if (outcome.kind === "timed-out") return outcome; - return { kind: "version", value: outcome.kind === "output" ? outcome.stdout : "" }; -} - -/** `resolveVersionReading` as text: a probe that timed out reads as no version. */ -export async function resolveVersion( - specification: DependencySpec, - exec: ProbeExecutor, - platform: NodeJS.Platform = rawPlatform(), -): Promise { - const reading = await resolveVersionReading(specification, exec, platform); - return reading.kind === "version" ? reading.value : ""; -} + return outcome.kind === "output" ? outcome.stdout : ""; +}); -export async function resolvePath( +export const resolvePath = Effect.fn("resolvePath")(function* ( specification: DependencySpec, exec: ProbeExecutor, platform: NodeJS.Platform = rawPlatform(), -): Promise { - const result = resolveDependency(specification, exec, platform); - return result.state === "present" ? (result.path ?? exec.which(specification.id)) : ""; -} +) { + const result = yield* resolveDependency(specification, exec, platform); + if (result.state !== "present") return ""; + return result.path ?? (yield* whichOf(exec, specification.id)); +}); diff --git a/cli/src/engine-native/engineCtx.ts b/cli/src/engine-native/engineCtx.ts index 77dcbdb5..c35d27be 100644 --- a/cli/src/engine-native/engineCtx.ts +++ b/cli/src/engine-native/engineCtx.ts @@ -4,11 +4,11 @@ * the environment. Code that is not Effect code yet reads and writes the same * plain `Ctx`, which the Effect code passes on. */ -import { Context, Effect, Schema } from "effect"; +import { Context, type Deferred, Effect, Schema } from "effect"; import { kitHome } from "../kitHome"; import { bridgeSync } from "./bridge"; -import type { BunRuntimeState } from "./bun"; +import type { BunBootstrapFailure, BunRuntimeState } from "./bun"; import { engineHome } from "./home"; import type { TerminalLease } from "./logger"; import type { EngineServices } from "./services"; @@ -21,7 +21,8 @@ export interface Ctx { /** Injected capability seam (logger/deps/platform) — see services.ts. */ readonly services: EngineServices; terminalLease?: TerminalLease; - bunRuntime?: Promise; + /** The Bun bootstrap outcome of this run; the first `bun.ts bunBootstrap` call creates it. */ + bunRuntime?: Deferred.Deferred; /** Per-run next-step triggers (Output Policy): advice prints only when its trigger changed or --verbose. */ readonly nextStepTriggers: { ompRestart: boolean; diff --git a/cli/src/engine-native/index.ts b/cli/src/engine-native/index.ts index 2dbe19ba..2ee7c7c5 100644 --- a/cli/src/engine-native/index.ts +++ b/cli/src/engine-native/index.ts @@ -15,6 +15,7 @@ import type { PlatformError } from "effect/PlatformError"; import { DependencyManagerService, LoggerService, PlatformService } from "../services"; import type { LegacyStepFailed } from "./bridge"; +import type { BunInstallFolderFailed } from "./bun"; import { EngineContext, makeCtx, type KitHomeInvalid } from "./engineCtx"; import type { LeaseHeld } from "./logger"; import { modeToolchain } from "./modes"; @@ -31,8 +32,9 @@ export type { SyncConcurrency, SyncTask } from "./syncConcurrency"; * A run that failed: each failure keeps the original value that the seam * prints. An unrecovered file operation of an omp pass fails with its * `PlatformError` (a failed upgrade-log removal only warns), a YAML merge or - * prune with `OmpYamlInvalid`, and a kit plugin prune removal with - * `PluginFolderRemoveFailed` or `PluginFileRemoveFailed`. + * prune with `OmpYamlInvalid`, a kit plugin prune removal with + * `PluginFolderRemoveFailed` or `PluginFileRemoveFailed`, and the temporary + * installer folder of the Bun bootstrap with `BunInstallFolderFailed`. */ export type EngineFailure = | LegacyStepFailed @@ -42,7 +44,8 @@ export type EngineFailure = | PlatformError | OmpYamlInvalid | PluginFolderRemoveFailed - | PluginFileRemoveFailed; + | PluginFileRemoveFailed + | BunInstallFolderFailed; /** * Run one engine operation and succeed with its exit code. Help, a refused diff --git a/cli/src/engine-native/modes.ts b/cli/src/engine-native/modes.ts index 3a8f019a..84e250e3 100644 --- a/cli/src/engine-native/modes.ts +++ b/cli/src/engine-native/modes.ts @@ -1,11 +1,10 @@ /** * Direct mode for `toolchain`. Same public argv vocabulary, golden-tested - * messages, same exit codes. Each call into `toolchain.ts` and `bun.ts`, which - * a later child of plan #290 moves, runs through the bridge. + * messages, same exit codes. It calls the Effect passes of `toolchain.ts` and + * `bun.ts` directly. */ import { Effect } from "effect"; -import { bridgePromise, bridgeSync } from "./bridge"; import { bunBootstrap } from "./bun"; import { EngineContext } from "./engineCtx"; import { UsageRefused } from "./parseHelp"; @@ -28,13 +27,11 @@ export const modeToolchain = Effect.fn("modeToolchain")(function* (args: Readonl } if (op === "check") { - yield* bridgePromise("report", () => report(ctx)); + yield* report(ctx); return 0; } if (op === "outdated") { - yield* bridgePromise("outdatedReport", () => - outdatedReport(ctx, { refresh: args.includes("--refresh") }), - ); + yield* outdatedReport(ctx, { refresh: args.includes("--refresh") }); return 0; } if (op !== "ensure") return yield* new UsageRefused({ message: TOOLCHAIN_USAGE }); @@ -47,17 +44,17 @@ export const modeToolchain = Effect.fn("modeToolchain")(function* (args: Readonl // `bun` is the one managed tool, and its bootstrap is silent when Bun is // already installed. Probe first so the no-op confirmation the `--verbose` // contract promises is not mistaken for a fresh install. - const alreadyInstalled = yield* bridgeSync("present", () => present(ctx, "bun")); - const runtime = yield* bridgePromise("bunBootstrap", () => bunBootstrap(ctx, ctx.services)); + const alreadyInstalled = yield* present(ctx, "bun"); + const runtime = yield* bunBootstrap(ctx, ctx.services); if (runtime.kind !== "ready") return 1; if (alreadyInstalled) { // A present tool whose --version cannot be read reports `unknown` in the // doctor table; keep the same vocabulary rather than an empty pair of // parentheses. `ensure` never upgrades (policy `present`), but a Bun // below the kit floor is a real problem, so it warns on every run. - const probed = yield* bridgePromise("installedVersion", () => installedVersion(ctx, "bun")); - const floor = yield* bridgeSync("field", () => field("bun", "floor")); - const below = yield* bridgeSync("belowFloor", () => belowFloor(probed, floor)); + const probed = yield* installedVersion(ctx, "bun"); + const floor = field("bun", "floor"); + const below = belowFloor(probed, floor); const label = probed === "" ? "version unknown" : probed; yield* Effect.sync(() => { if (below) warn(`bun ${probed} is below the kit floor ${floor}; run bun upgrade`); diff --git a/cli/src/engine-native/ompPlugins.ts b/cli/src/engine-native/ompPlugins.ts index a1debd88..7e7c6742 100644 --- a/cli/src/engine-native/ompPlugins.ts +++ b/cli/src/engine-native/ompPlugins.ts @@ -338,9 +338,8 @@ export const syncPlugins = Effect.fn("syncPlugins")(function* (ctx: Ctx, paths: if (!ctx.dryRun) yield* removeUpgradeLog(ctx); - // The dependency probes move with #298; until then they are bridged. - if ((yield* bridgeSync("deps.probe omp", () => deps.probe("omp"))).state === "missing") { - yield* bridgeSync("deps.warnMissing omp", () => + if ((yield* deps.probe("omp")).state === "missing") { + yield* bridgeSync("logger", () => deps.warnMissing( "omp", ctx.services.logger, @@ -349,10 +348,9 @@ export const syncPlugins = Effect.fn("syncPlugins")(function* (ctx: Ctx, paths: ); return undefined; } - const gitMissing = - (yield* bridgeSync("deps.probe git", () => deps.probe("git"))).state === "missing"; + const gitMissing = (yield* deps.probe("git")).state === "missing"; if (gitMissing) { - yield* bridgeSync("deps.warnMissing git", () => + yield* bridgeSync("logger", () => deps.warnMissing( "git", ctx.services.logger, diff --git a/cli/src/engine-native/ompSync.ts b/cli/src/engine-native/ompSync.ts index cf9b723e..67a2f61d 100644 --- a/cli/src/engine-native/ompSync.ts +++ b/cli/src/engine-native/ompSync.ts @@ -17,7 +17,7 @@ import { Effect } from "effect"; -import { bridgePromise, bridgeSync } from "./bridge"; +import { bridgeSync } from "./bridge"; import { bunBootstrap } from "./bun"; import { EngineContext, type Ctx } from "./engineCtx"; import { p } from "./exec"; @@ -60,13 +60,14 @@ export const ompWriteFolders = Effect.fn("ompWriteFolders")(function* () { /** * Run the omp pipeline in `folders`, the folders that `engineSync` resolved * and locked. The passes are Effect code; only their calls into code that a - * later child of plan #290 moves run through the bridge (`bunBootstrap` here, - * the logger, the atomic writer, the dependency probes, and the omp - * children inside the passes), so an interrupt waits until that call settles. + * later child of plan #290 moves run through the bridge (the logger, the + * atomic writer, and the omp children inside the passes), so an interrupt + * waits until that call settles. The Bun bootstrap runs without + * interruption. */ export const ompSync = Effect.fn("ompSync")(function* (folders: OmpWriteFolders) { const ctx = yield* EngineContext; - yield* bridgePromise("bunBootstrap", () => bunBootstrap(ctx, ctx.services)); + yield* bunBootstrap(ctx, ctx.services); const { paths } = folders; const agentDir = paths.agentDir; diff --git a/cli/src/engine-native/services.ts b/cli/src/engine-native/services.ts index 9906135b..4b1fc294 100644 --- a/cli/src/engine-native/services.ts +++ b/cli/src/engine-native/services.ts @@ -5,31 +5,35 @@ * provides to the public CLI and to the harness-private native-raw entry, so * every execution path shares one implementation. */ +import type { Effect } from "effect"; + +import type { LegacyStepFailed } from "./bridge"; import { DEPENDENCIES, defaultProbeExecutor, resolveDependency, resolvePath, resolveVersion, - resolveVersionReading, type DependencySpec, type ProbeExecutor, type ProbeResult, type ToolId, - type VersionReading, } from "./deps"; import { makeLogger, type Logger, type LoggerSinks } from "./logger"; import { platformName, rawPlatform, type PlatformName } from "./os"; export type { Logger } from "./logger"; +/** + * The dependency methods. `probe`, `version`, and `path` are Effects that + * fail with `LegacyStepFailed` when a bridged call into the process layer or + * the home lookup throws or rejects. + */ export interface DependencyManager { readonly spec: (id: ToolId) => DependencySpec; - readonly probe: (id: ToolId) => ProbeResult; - readonly version: (id: ToolId) => Promise; - /** Like `version`, but keeps a probe that did not answer in time apart from no version. */ - readonly versionReading: (id: ToolId) => Promise; - readonly path: (id: ToolId) => Promise; + readonly probe: (id: ToolId) => Effect.Effect; + readonly version: (id: ToolId) => Effect.Effect; + readonly path: (id: ToolId) => Effect.Effect; readonly warnMissing: (id: ToolId, logger: Logger, context?: string) => void; } @@ -67,7 +71,6 @@ export const makeDependencyManager = ( }, probe: (id) => resolveDependency(DEPENDENCIES[id], exec, platform.raw()), version: (id) => resolveVersion(DEPENDENCIES[id], exec, platform.raw()), - versionReading: (id) => resolveVersionReading(DEPENDENCIES[id], exec, platform.raw()), path: (id) => resolvePath(DEPENDENCIES[id], exec, platform.raw()), warnMissing: (id, logger, context) => { if (warned.has(id)) return; diff --git a/cli/src/engine-native/toolchain.ts b/cli/src/engine-native/toolchain.ts index b93f707c..2737c467 100644 --- a/cli/src/engine-native/toolchain.ts +++ b/cli/src/engine-native/toolchain.ts @@ -1,7 +1,14 @@ /** * Verified-version-floor layer over SoT/toolchain.json. Probe commands spawn * deterministic argv arrays and are covered by golden regression cases. + * + * The passes are Effects. Their calls into the logger and the kit store + * (`kitDb.ts`), which a later child of plan #290 moves, run through the + * bridge; the upstream request runs in one `Effect.tryPromise`. */ +import { Clock, Effect, Schema } from "effect"; + +import { bridgeSync } from "./bridge"; import type { ToolId } from "./deps"; import type { Ctx } from "./index"; import { compareCodepoints, isObject, parseJson } from "./jq"; @@ -45,41 +52,43 @@ export function belowFloor(installed: string, floor: string): boolean { return installed !== "" && floor !== "" && isNewer(floor, installed); } -export function present(ctx: Ctx, tool: ToolId): boolean { - return ctx.services.deps.probe(tool).state === "present"; -} +export const present = Effect.fn("present")(function* (ctx: Ctx, tool: ToolId) { + return (yield* ctx.services.deps.probe(tool)).state === "present"; +}); function firstLineField(out: string, index: number): string { const fields = (out.split("\n")[0] ?? "").trim().split(/[ \t]+/); return fields[index === -1 ? fields.length - 1 : index] ?? ""; } -export async function installedVersion(ctx: Ctx, tool: ToolId): Promise { +export const installedVersion = Effect.fn("installedVersion")(function* (ctx: Ctx, tool: ToolId) { const version = () => ctx.services.deps.version(tool); switch (tool) { case "git": - return firstLineField(await version(), 2); + return firstLineField(yield* version(), 2); case "jq": - return (await version()).replace(/^jq-/, ""); + return (yield* version()).replace(/^jq-/, ""); case "curl": - return firstLineField(await version(), 1); + return firstLineField(yield* version(), 1); case "bun": case "omp": case "npm": - return await version(); + return yield* version(); default: return ""; } -} +}); function row(cells: [string, string, string, string, string, string]): string { const widths = [28, 9, 14, 9, 9]; return cells.map((c, i) => (i < widths.length ? c.padEnd(widths[i]!) : c)).join(" "); } -export async function report(ctx: Ctx): Promise { +export const report = Effect.fn("report")(function* (ctx: Ctx) { const { echo } = ctx.services.logger; - echo(row(["TOOL", "KIND", "INSTALLED", "FLOOR", "VERIFIED", "STATUS"])); + yield* bridgeSync("logger", () => + echo(row(["TOOL", "KIND", "INSTALLED", "FLOOR", "VERIFIED", "STATUS"])), + ); const pn = ctx.services.platform.name(); const platformOs = hostOs(pn).toolchainOs; for (const tool of Object.keys(manifest()).sort(compareCodepoints)) { @@ -92,8 +101,8 @@ export async function report(ctx: Ctx): Promise { let installed: string; let status: string; const toolId = tool as ToolId; - if (present(ctx, toolId)) { - installed = await installedVersion(ctx, toolId); + if (yield* present(ctx, toolId)) { + installed = yield* installedVersion(ctx, toolId); status = installed === "" ? "unknown" : "ok"; if (belowFloor(installed, floor)) { status = "below-floor"; @@ -105,9 +114,10 @@ export async function report(ctx: Ctx): Promise { installed = "-"; status = "missing"; } - echo(row([tool, dash(kind), installed, dash(floor), dash(verified), status])); + const cells = row([tool, dash(kind), installed, dash(floor), dash(verified), status]); + yield* bridgeSync("logger", () => echo(cells)); } -} +}); export type UpstreamResult = { ok: true; version: string } | { ok: false; reason: string }; @@ -121,6 +131,17 @@ export interface UpstreamInputs { const UPSTREAM_CACHE_MS = 24 * 3600_000; +/** The one deadline of an upstream request: it covers the response and the body read. */ +const UPSTREAM_TIMEOUT_MS = 8000; + +/** The upstream request or its body read failed; `reason` is the text of the row. */ +class UpstreamLookupFailed extends Schema.TaggedError< + UpstreamLookupFailed, + { readonly brand: unique symbol } +>()("UpstreamLookupFailed", { reason: Schema.String }) {} + +const lookupFailed = (reason: string): UpstreamResult => ({ ok: false, reason }); + function upstreamSpec(tool: string): JsonObject | undefined { const entry = manifest()[tool]; const upstream = entry !== undefined && isObject(entry) ? entry["upstream"] : undefined; @@ -132,82 +153,117 @@ function upstreamLabel(spec: JsonObject): string { return typeof github === "string" ? `github ${github}` : "-"; } -async function fetchJson( +type FetchedJson = { ok: true; body: JsonObject } | { ok: false; reason: string }; + +/** + * The JSON body of `url`. The request and the body read run under one + * deadline; a rejection of either, such as the timeout, fails with the + * message of the error. + */ +const fetchJson = ( fetchImpl: FetchLike, url: string, headers: Record, -): Promise<{ ok: true; body: JsonObject } | { ok: false; reason: string }> { - const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(8000) }); - if (response.status !== 200) return { ok: false, reason: `HTTP ${response.status}` }; - const body = parseJson(await response.text()); - return body !== undefined && isObject(body) - ? { ok: true, body } - : { ok: false, reason: "invalid response" }; -} +): Effect.Effect => + Effect.tryPromise({ + try: () => + fetchImpl(url, { + headers, + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }).then((response) => + response.status !== 200 + ? { ok: false, reason: `HTTP ${response.status}` } + : response.text().then((text) => { + const body = parseJson(text); + return body !== undefined && isObject(body) + ? { ok: true, body } + : { ok: false, reason: "invalid response" }; + }), + ), + catch: (error) => + new UpstreamLookupFailed({ + reason: error instanceof Error ? error.message : String(error), + }), + }); -async function lookupUpstream( +function lookupUpstream( spec: JsonObject, fetchImpl: FetchLike, env: NodeJS.ProcessEnv, -): Promise { +): Effect.Effect { const { github, tagPrefix } = spec; - if (typeof github === "string") { - const headers: Record = { - Accept: "application/vnd.github+json", - "User-Agent": "docks-kit", - }; - const token = env["GITHUB_TOKEN"] || env["GH_TOKEN"]; - if (token !== undefined && token !== "") headers["Authorization"] = `Bearer ${token}`; - const result = await fetchJson( - fetchImpl, - `https://api.github.com/repos/${github}/releases/latest`, - headers, - ); - if (!result.ok) return result; - const tag = result.body["tag_name"]; - if (typeof tag !== "string") return { ok: false, reason: "invalid response" }; - const prefix = typeof tagPrefix === "string" ? tagPrefix : ""; - return tag.startsWith(prefix) - ? { ok: true, version: tag.slice(prefix.length) } - : { ok: false, reason: `unexpected tag ${tag}` }; + if (typeof github !== "string") { + return Effect.succeed(lookupFailed("no upstream in SoT/toolchain.json")); } - return { ok: false, reason: "no upstream in SoT/toolchain.json" }; + const headers: Record = { + Accept: "application/vnd.github+json", + "User-Agent": "docks-kit", + }; + const token = env["GITHUB_TOKEN"] || env["GH_TOKEN"]; + if (token !== undefined && token !== "") headers["Authorization"] = `Bearer ${token}`; + return fetchJson( + fetchImpl, + `https://api.github.com/repos/${github}/releases/latest`, + headers, + ).pipe( + Effect.map((result): UpstreamResult => { + if (!result.ok) return result; + const tag = result.body["tag_name"]; + if (typeof tag !== "string") return lookupFailed("invalid response"); + const prefix = typeof tagPrefix === "string" ? tagPrefix : ""; + return tag.startsWith(prefix) + ? { ok: true, version: tag.slice(prefix.length) } + : lookupFailed(`unexpected tag ${tag}`); + }), + ); } -/** Newest upstream release for one manifest tool; successes cache 24 h in kit.db. */ -export async function latestUpstream( +/** + * Newest upstream release for one manifest tool; successes cache 24 h in + * kit.db. A failed lookup is a result with its reason, so it never fails the + * Effect. + */ +export const latestUpstream = Effect.fn("latestUpstream")(function* ( tool: string, inputs: UpstreamInputs, -): Promise { +) { const { home, refresh, now, fetchImpl = globalThis.fetch, env = process.env } = inputs; const key = `upstream:${tool}`; if (!refresh) { - const cached = readCache(home, key, UPSTREAM_CACHE_MS, now); - if (cached !== undefined) return { ok: true, version: cached }; + const cached = yield* bridgeSync("readCache", () => + readCache(home, key, UPSTREAM_CACHE_MS, now), + ); + if (cached !== undefined) { + const hit: UpstreamResult = { ok: true, version: cached }; + return hit; + } } const spec = upstreamSpec(tool); - if (spec === undefined) return { ok: false, reason: "no upstream in SoT/toolchain.json" }; - let result: UpstreamResult; - try { - result = await lookupUpstream(spec, fetchImpl, env); - } catch (error) { - result = { ok: false, reason: error instanceof Error ? error.message : String(error) }; - } - if (result.ok) writeCache(home, key, result.version, now); + if (spec === undefined) return lookupFailed("no upstream in SoT/toolchain.json"); + const result = yield* lookupUpstream(spec, fetchImpl, env).pipe( + Effect.catchTag("UpstreamLookupFailed", (failed) => + Effect.succeed(lookupFailed(failed.reason)), + ), + ); + if (result.ok) yield* bridgeSync("writeCache", () => writeCache(home, key, result.version, now)); return result; -} +}); -/** Compare each verified pin with the newest upstream release. Report only. */ -export async function outdatedReport( +/** + * Compare each verified pin with the newest upstream release. Report only. + * The lookups run at the same time; each one recovers its own lookup + * failure, so one failed lookup does not stop another. + */ +export const outdatedReport = Effect.fn("outdatedReport")(function* ( ctx: Ctx, options: { readonly refresh: boolean; readonly fetchImpl?: FetchLike }, -): Promise { +) { const { echo } = ctx.services.logger; const tools = Object.keys(manifest()).filter( (tool) => field(tool, "verified") !== "" && upstreamSpec(tool) !== undefined, ); - const now = Date.now(); - const results = await Promise.all( + const now = yield* Clock.currentTimeMillis; + const results = yield* Effect.all( tools.map((tool) => latestUpstream(tool, { home: ctx.home, @@ -216,8 +272,9 @@ export async function outdatedReport( ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}), }), ), + { concurrency: "unbounded" }, ); - echo(row(["TOOL", "KIND", "VERIFIED", "LATEST", "STATUS", "UPSTREAM"])); + const lines = [row(["TOOL", "KIND", "VERIFIED", "LATEST", "STATUS", "UPSTREAM"])]; tools.forEach((tool, index) => { const verified = field(tool, "verified"); const result = results[index]!; @@ -230,8 +287,9 @@ export async function outdatedReport( status = `lookup failed: ${result.reason}`; } const label = upstreamLabel(upstreamSpec(tool) ?? {}); - echo(row([tool, field(tool, "kind"), verified, latest, status, label])); + lines.push(row([tool, field(tool, "kind"), verified, latest, status, label])); }); - echo("Report only: update a verified pin after testing that release (SoT/toolchain.json)."); + lines.push("Report only: update a verified pin after testing that release (SoT/toolchain.json)."); + for (const line of lines) yield* bridgeSync("logger", () => echo(line)); return 0; -} +}); diff --git a/cli/src/engine.ts b/cli/src/engine.ts index 59102a98..cddaa17b 100644 --- a/cli/src/engine.ts +++ b/cli/src/engine.ts @@ -24,10 +24,11 @@ const requireSupportedHost = () => { }; /** - * The text of a failed run. A bridged step, the kit home, a YAML failure, and - * a removal of the kit plugin prune keep the message that they captured when - * they failed, so the cause is not read again; a lock failure and a file - * operation give the message of their Node error, and a held lease its own. + * The text of a failed run. A bridged step, the kit home, a YAML failure, a + * removal of the kit plugin prune, and the Bun installer folder keep the + * message that they captured when they failed, so the cause is not read + * again; a lock failure and a file operation give the message of their Node + * error, and a held lease its own. */ const failureDetail = (error: EngineFailure): string => { switch (error._tag) { @@ -36,6 +37,7 @@ const failureDetail = (error: EngineFailure): string => { case "OmpYamlInvalid": case "PluginFolderRemoveFailed": case "PluginFileRemoveFailed": + case "BunInstallFolderFailed": return error.message; case "LockAcquireError": return failureText(error.cause); diff --git a/cli/test/unit/bun.test.ts b/cli/test/unit/bun.test.ts index 23d41be3..83006f93 100644 --- a/cli/test/unit/bun.test.ts +++ b/cli/test/unit/bun.test.ts @@ -4,8 +4,14 @@ import type * as OsModule from "node:os"; import { basename, join, sep } from "node:path"; import type * as ExecModule from "../../src/engine-native/exec"; +/** The callback form of `node:fs mkdtemp`, which the bootstrap calls. */ +type Mkdtemp = ( + prefix: string, + callback: (error: NodeJS.ErrnoException | null, folder: string) => void, +) => void; + const mocks = vi.hoisted(() => ({ - mkdtempSync: vi.fn((_prefix: string) => "docks-kit-bun-private"), + mkdtemp: vi.fn(), rmSync: vi.fn(), spawnProcess: vi.fn(), tmpdir: vi.fn(() => ""), @@ -17,13 +23,15 @@ vi.mock("../../src/engine-native/exec", async () => { }); vi.mock("node:fs", async () => { const actual = await vi.importActual("node:fs"); - return { ...actual, mkdtempSync: mocks.mkdtempSync, rmSync: mocks.rmSync }; + return { ...actual, mkdtemp: mocks.mkdtemp, rmSync: mocks.rmSync }; }); vi.mock("node:os", async () => { const actual = await vi.importActual("node:os"); return { ...actual, tmpdir: mocks.tmpdir }; }); +import { Cause, Effect } from "effect"; +import { engineFailureDetail } from "../../src/engine"; import { bunBootstrap, type BunRuntimeState } from "../../src/engine-native/bun"; import type { Ctx } from "../../src/engine-native"; import type { ProbeExecutor } from "../../src/engine-native/deps"; @@ -34,8 +42,12 @@ import { makePlatform, type EngineServices, } from "../../src/engine-native/services"; +import { runEngine } from "../lib/engineRun"; import { verifiedVersion } from "../lib/toolchainManifest"; +/** Run the bootstrap Effect `effect`. */ +const run = (effect: Effect.Effect): Promise => Effect.runPromise(effect); + const VERIFIED_BUN = verifiedVersion("bun"); interface ProbeState { @@ -116,7 +128,7 @@ function expectReady(state: BunRuntimeState): string { beforeEach(async () => { const os = await vi.importActual("node:os"); const privateDir = join(os.tmpdir(), "docks-kit-bun-private"); - mocks.mkdtempSync.mockReset().mockReturnValue(privateDir); + mocks.mkdtemp.mockReset().mockImplementation((_prefix, callback) => callback(null, privateDir)); mocks.rmSync.mockReset(); mocks.spawnProcess .mockReset() @@ -135,9 +147,13 @@ afterEach(() => { describe("per-run Bun bootstrap", () => { it("returns and memoizes an existing resolved executable", async () => { const test = rig("linux", { curl: true, installed: false, pathBun: "/usr/local/bin/bun" }); - expect(expectReady(await bunBootstrap(test.ctx, test.services))).toBe("/usr/local/bin/bun"); + expect(expectReady(await run(bunBootstrap(test.ctx, test.services)))).toBe( + "/usr/local/bin/bun", + ); test.state.pathBun = undefined; - expect(expectReady(await bunBootstrap(test.ctx, test.services))).toBe("/usr/local/bin/bun"); + expect(expectReady(await run(bunBootstrap(test.ctx, test.services)))).toBe( + "/usr/local/bin/bun", + ); expect(mocks.spawnProcess).not.toHaveBeenCalled(); }); @@ -145,8 +161,7 @@ describe("per-run Bun bootstrap", () => { const test = rig("linux", { curl: false, installed: false }); const first = bunBootstrap(test.ctx, test.services); const second = bunBootstrap(test.ctx, test.services); - expect(first).toBe(second); - await expect(Promise.all([first, second])).resolves.toEqual([ + await expect(run(Effect.all([first, second], { concurrency: "unbounded" }))).resolves.toEqual([ { kind: "deferred", reason: "missing-curl" }, { kind: "deferred", reason: "missing-curl" }, ]); @@ -160,7 +175,9 @@ describe("per-run Bun bootstrap", () => { it("predicts the pinned POSIX path in dry-run without spawning or removing", async () => { process.env["BUN_INSTALL"] = "/custom bun"; const test = rig("linux", { curl: true, installed: false }, true); - expect(expectReady(await bunBootstrap(test.ctx, test.services))).toBe("/custom bun/bin/bun"); + expect(expectReady(await run(bunBootstrap(test.ctx, test.services)))).toBe( + "/custom bun/bin/bun", + ); expect(test.lines.join("")).toContain( `[dry-run] install Bun ${VERIFIED_BUN} (kit-verified) -> /custom bun/bin/bun`, ); @@ -171,7 +188,7 @@ describe("per-run Bun bootstrap", () => { it("predicts the pinned Windows path in dry-run without spawning or removing", async () => { process.env["BUN_INSTALL"] = "C:/custom bun"; const test = rig("win32", { curl: true, installed: false }, true); - expect(expectReady(await bunBootstrap(test.ctx, test.services))).toBe( + expect(expectReady(await run(bunBootstrap(test.ctx, test.services)))).toBe( "C:/custom bun/bin/bun.exe", ); expect(test.lines.join("")).toContain( @@ -183,7 +200,7 @@ describe("per-run Bun bootstrap", () => { it("defers a POSIX dry-run when curl cannot satisfy the planned bootstrap", async () => { const test = rig("linux", { curl: false, installed: false }, true); - expect(await bunBootstrap(test.ctx, test.services)).toEqual({ + expect(await run(bunBootstrap(test.ctx, test.services))).toEqual({ kind: "deferred", reason: "missing-curl", }); @@ -228,9 +245,9 @@ describe("per-run Bun bootstrap", () => { } mocks.tmpdir.mockReturnValue(testRoot); let privateDirectory = ""; - mocks.mkdtempSync.mockImplementation((prefix: string) => { + mocks.mkdtemp.mockImplementation((prefix, callback) => { privateDirectory = fs.mkdtempSync(prefix); - return privateDirectory; + callback(null, privateDirectory); }); const test = rig(platformId, { curl: true, installed: false }); let downloadedTo = ""; @@ -259,9 +276,14 @@ describe("per-run Bun bootstrap", () => { }); try { - expect(expectReady(await bunBootstrap(test.ctx, test.services))).toBe(expectedExecutable); + expect(expectReady(await run(bunBootstrap(test.ctx, test.services)))).toBe( + expectedExecutable, + ); const scriptPath = `${privateDirectory}/${installerName}`; - expect(mocks.mkdtempSync).toHaveBeenCalledWith(`${testRoot}/docks-kit-bun-`); + expect(mocks.mkdtemp).toHaveBeenCalledWith( + `${testRoot}/docks-kit-bun-`, + expect.any(Function), + ); expect( privateDirectory.startsWith(`${testRoot}/`) || privateDirectory.startsWith(`${testRoot}${sep}`), @@ -344,7 +366,7 @@ describe("per-run Bun bootstrap", () => { stderr: "curl: (22) server returned 503", }); - expect(await bunBootstrap(test.ctx, test.services)).toEqual({ + expect(await run(bunBootstrap(test.ctx, test.services))).toEqual({ kind: "deferred", reason: "download-failed", }); @@ -365,7 +387,7 @@ describe("per-run Bun bootstrap", () => { stderr: "install: unsupported platform", }); - expect(await bunBootstrap(test.ctx, test.services)).toEqual({ + expect(await run(bunBootstrap(test.ctx, test.services))).toEqual({ kind: "deferred", reason: "installer-failed", }); @@ -374,11 +396,95 @@ describe("per-run Bun bootstrap", () => { it("returns install-failed after a successful download that produces no Bun", async () => { const test = rig("linux", { curl: true, installed: false }); - expect(await bunBootstrap(test.ctx, test.services)).toEqual({ + expect(await run(bunBootstrap(test.ctx, test.services))).toEqual({ kind: "deferred", reason: "install-failed", }); expect(mocks.rmSync).toHaveBeenCalledTimes(1); expect(test.lines.join("")).toContain("Bun install failed"); }); + + it("fails with the installer folder error in place of the installer outcome when the folder cannot be deleted", async () => { + const test = rig("linux", { curl: true, installed: false }); + mocks.spawnProcess.mockResolvedValueOnce({ + error: undefined, + exitCode: 22, + stdout: "", + stderr: "curl: (22) server returned 503", + }); + const nodeError = Object.assign( + new Error("EACCES: permission denied, rmdir '/tmp/docks-kit-bun-private'"), + { code: "EACCES" }, + ); + mocks.rmSync.mockImplementationOnce(() => { + throw nodeError; + }); + + const failed = await run(Effect.flip(bunBootstrap(test.ctx, test.services))); + expect(failed._tag).toBe("BunInstallFolderFailed"); + expect(failed.message).toBe(nodeError.message); + expect(engineFailureDetail(Cause.fail(failed))).toBe(nodeError.message); + expect(test.lines.join("")).not.toContain("Bun installer download failed"); + // A later call of the same run gets the same failure and installs nothing. + expect(await run(Effect.flip(bunBootstrap(test.ctx, test.services)))).toBe(failed); + expect(mocks.spawnProcess).toHaveBeenCalledTimes(1); + }); + + it("fails with the installer folder error when the folder cannot be made, and starts no installer", async () => { + const test = rig("linux", { curl: true, installed: false }); + const nodeError = Object.assign( + new Error("ENOENT: no such file or directory, mkdtemp '/missing-tmp/docks-kit-bun-XXXXXX'"), + { code: "ENOENT" }, + ); + mocks.mkdtemp.mockImplementationOnce((_prefix, callback) => callback(nodeError, "")); + + const failed = await run(Effect.flip(bunBootstrap(test.ctx, test.services))); + expect(failed._tag).toBe("BunInstallFolderFailed"); + expect(failed.message).toBe(nodeError.message); + expect(engineFailureDetail(Cause.fail(failed))).toBe(nodeError.message); + expect(mocks.spawnProcess).not.toHaveBeenCalled(); + expect(mocks.rmSync).not.toHaveBeenCalled(); + }); + + it("shares one bootstrap among repeated and concurrent calls of one engine run, and none between two runs", async () => { + const test = rig("linux", { curl: true, installed: false, pathBun: "/usr/local/bin/bun" }); + const base = test.services.deps; + const gate = Promise.withResolvers(); + let started = 0; + const services: EngineServices = { + ...test.services, + deps: { + ...base, + // Each bootstrap starts with this lookup. It waits at the gate, so the first two calls overlap. + path: (id) => { + if (id === "bun") started += 1; + return Effect.andThen( + Effect.promise(() => gate.promise), + base.path(id), + ); + }, + }, + }; + const ready = { kind: "ready", executable: "/usr/local/bin/bun" }; + + // The third task opens the gate after the first two started. + const overlapping = await run( + Effect.all( + [ + bunBootstrap(test.ctx, services), + bunBootstrap(test.ctx, services), + Effect.sync(() => gate.resolve()), + ], + { concurrency: "unbounded" }, + ), + ); + expect(overlapping.slice(0, 2)).toEqual([ready, ready]); + expect(await run(bunBootstrap(test.ctx, services))).toEqual(ready); + expect(started).toBe(1); + + // Each engine run has its own run context, so each one bootstraps once. + expect(await runEngine(["toolchain", "ensure", "bun"], services)).toBe(0); + expect(await runEngine(["toolchain", "ensure", "bun"], services)).toBe(0); + expect(started).toBe(3); + }); }); diff --git a/cli/test/unit/deps.test.ts b/cli/test/unit/deps.test.ts index 1c833841..e98b2ff1 100644 --- a/cli/test/unit/deps.test.ts +++ b/cli/test/unit/deps.test.ts @@ -2,12 +2,12 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import { delimiter, join, resolve } from "node:path"; import { stripVTControlCharacters } from "node:util"; +import { Effect } from "effect"; import { describe, expect, it, vi } from "vitest"; import { DEPENDENCIES, resolvePath, resolveVersion, - resolveVersionReading, VERSION_PROBE_LIMIT_MS, type ProbeExecutor, } from "../../src/engine-native/deps"; @@ -105,7 +105,7 @@ describe("DependencyManager registry", () => { which: (name) => (name === "npm" ? executable : ""), }; - await expect(resolvePath(DEPENDENCIES.npm, exec, "win32")).resolves.toBe(executable); + expect(await Effect.runPromise(resolvePath(DEPENDENCIES.npm, exec, "win32"))).toBe(executable); }); it("gives an executable Linux git hint", () => { @@ -163,7 +163,7 @@ describe("DependencyManager registry", () => { const version = DEPENDENCIES.bun.version; if (version === undefined) throw new Error("Bun version probe is not registered"); - await expect(version(exec, "linux")).resolves.toBe(""); + expect(await Effect.runPromise(version(exec, "linux"))).toBe(""); expect(captureFn).not.toHaveBeenCalled(); }); @@ -183,7 +183,7 @@ describe("DependencyManager registry", () => { which: (name) => (name === "/custom-bun/bin/bun" ? name : ""), }); - await expect(manager.version("bun")).resolves.toBe("1.4.0"); + expect(await Effect.runPromise(manager.version("bun"))).toBe("1.4.0"); expect(calls).toEqual([["/custom-bun/bin/bun", ["--version"]]]); } finally { if (previousHome === undefined) delete process.env["HOME"]; @@ -210,8 +210,8 @@ describe("DependencyManager registry", () => { which: (name) => (name === linked ? name : ""), }); - expect(manager.probe("bun")).toEqual({ state: "present", path: linked }); - await expect(manager.version("bun")).resolves.toBe("1.4.5"); + expect(Effect.runSync(manager.probe("bun"))).toEqual({ state: "present", path: linked }); + expect(await Effect.runPromise(manager.version("bun"))).toBe("1.4.5"); expect(calls).toEqual([linked]); } finally { vi.unstubAllEnvs(); @@ -231,8 +231,8 @@ describe("DependencyManager registry", () => { which: (name) => (name === windowsBun ? name : ""), }); - expect(manager.probe("bun")).toEqual({ state: "present", path: windowsBun }); - await expect(manager.version("bun")).resolves.toBe("1.4.5"); + expect(Effect.runSync(manager.probe("bun"))).toEqual({ state: "present", path: windowsBun }); + expect(await Effect.runPromise(manager.version("bun"))).toBe("1.4.5"); } finally { vi.unstubAllEnvs(); } @@ -258,14 +258,17 @@ describe("DependencyManager registry", () => { ? name : "", }); - expect(withFallback.probe("bun")).toEqual({ state: "present", path: fallback }); + expect(Effect.runSync(withFallback.probe("bun"))).toEqual({ + state: "present", + path: fallback, + }); const onlyRelative = makeDependencyManager(makePlatform("linux"), { commandExists: () => true, capture: async () => "", which: (name) => (name === "bun" ? "relative/bin/bun" : ""), }); - expect(onlyRelative.probe("bun")).toEqual({ state: "missing" }); + expect(Effect.runSync(onlyRelative.probe("bun"))).toEqual({ state: "missing" }); } finally { if (previousHome === undefined) delete process.env["HOME"]; else process.env["HOME"] = previousHome; @@ -283,8 +286,8 @@ describe("DependencyManager registry", () => { which: () => "/host/git", }); - expect(manager.probe("git")).toEqual({ state: "missing" }); - await expect(manager.path("git")).resolves.toBe(""); + expect(Effect.runSync(manager.probe("git"))).toEqual({ state: "missing" }); + expect(await Effect.runPromise(manager.path("git"))).toBe(""); }); it("probes presence without running the version command", () => { @@ -294,11 +297,11 @@ describe("DependencyManager registry", () => { capture: captureVersion, which: (name) => `/stub/${name}`, }); - expect(manager.probe("git")).toEqual({ state: "present", path: "/stub/git" }); + expect(Effect.runSync(manager.probe("git"))).toEqual({ state: "present", path: "/stub/git" }); expect(captureVersion).not.toHaveBeenCalled(); }); - it("reports a version probe that does not answer within the limit as timed out", async () => { + it("reads a version probe that does not answer within the limit as no version", async () => { const bounded: Array<[string, ReadonlyArray, number]> = []; const exec: ProbeExecutor = { commandExists: () => true, @@ -310,14 +313,8 @@ describe("DependencyManager registry", () => { which: (name) => `/stub/${name}`, }; - await expect(resolveVersionReading(DEPENDENCIES.git, exec)).resolves.toEqual({ - kind: "timed-out", - }); - await expect(resolveVersion(DEPENDENCIES.git, exec)).resolves.toBe(""); - expect(bounded).toEqual([ - ["git", ["--version"], VERSION_PROBE_LIMIT_MS], - ["git", ["--version"], VERSION_PROBE_LIMIT_MS], - ]); + expect(await Effect.runPromise(resolveVersion(DEPENDENCIES.git, exec))).toBe(""); + expect(bounded).toEqual([["git", ["--version"], VERSION_PROBE_LIMIT_MS]]); }); it("reads the version from the bounded probe output, and an empty one from a failed probe", async () => { @@ -328,14 +325,16 @@ describe("DependencyManager registry", () => { which: (name) => `/stub/${name}`, }); - await expect( - resolveVersionReading( - DEPENDENCIES.git, - answering({ kind: "output", stdout: "git version 2.53.0" }), + expect( + await Effect.runPromise( + resolveVersion( + DEPENDENCIES.git, + answering({ kind: "output", stdout: "git version 2.53.0" }), + ), ), - ).resolves.toEqual({ kind: "version", value: "git version 2.53.0" }); - await expect( - resolveVersionReading(DEPENDENCIES.git, answering({ kind: "failed" })), - ).resolves.toEqual({ kind: "version", value: "" }); + ).toBe("git version 2.53.0"); + expect( + await Effect.runPromise(resolveVersion(DEPENDENCIES.git, answering({ kind: "failed" }))), + ).toBe(""); }); }); diff --git a/cli/test/unit/envGlobals.test.ts b/cli/test/unit/envGlobals.test.ts index 28969176..be2d9d22 100644 --- a/cli/test/unit/envGlobals.test.ts +++ b/cli/test/unit/envGlobals.test.ts @@ -43,10 +43,9 @@ function stubServices(records: Array): EngineServices { installHint: (value = platform.raw()) => specification.installHint(value), }; }, - probe: (id) => ({ state: "present", path: `/stub-bin/${id}` }), - version: async (id) => (id === "bun" ? "1.4.0" : "0.5.3"), - versionReading: async (id) => ({ kind: "version", value: id === "bun" ? "1.4.0" : "0.5.3" }), - path: async (id) => `/stub-bin/${id}`, + probe: (id) => Effect.succeed({ state: "present", path: `/stub-bin/${id}` }), + version: (id) => Effect.succeed(id === "bun" ? "1.4.0" : "0.5.3"), + path: (id) => Effect.succeed(`/stub-bin/${id}`), warnMissing: () => {}, }; return { logger, deps, platform }; diff --git a/cli/test/unit/ompKitPlugin.test.ts b/cli/test/unit/ompKitPlugin.test.ts index 176a1666..bdd594f6 100644 --- a/cli/test/unit/ompKitPlugin.test.ts +++ b/cli/test/unit/ompKitPlugin.test.ts @@ -40,10 +40,9 @@ function testCtx(dryRun = false, stdout: Array = [], stderr: Array DEPENDENCIES[id], - probe: vi.fn(() => ({ state: "missing" as const })), - version: async () => "", - versionReading: async () => ({ kind: "version" as const, value: "" }), - path: async () => "", + probe: vi.fn(() => Effect.succeed({ state: "missing" as const })), + version: () => Effect.succeed(""), + path: () => Effect.succeed(""), warnMissing: () => {}, }, }; diff --git a/cli/test/unit/ompPluginInventory.test.ts b/cli/test/unit/ompPluginInventory.test.ts index 8f7c8156..cf782920 100644 --- a/cli/test/unit/ompPluginInventory.test.ts +++ b/cli/test/unit/ompPluginInventory.test.ts @@ -41,9 +41,11 @@ vi.mock("../../src/engine-native/exec", async () => { const actual = await vi.importActual("../../src/engine-native/exec"); return { ...actual, spawnProcess: mocks.spawnProcess }; }); -vi.mock("../../src/engine-native/bun", () => ({ - bunBootstrap: async () => ({ kind: "ready", executable: "bun" }), -})); +vi.mock("../../src/engine-native/bun", async () => { + // The hoisted factory runs before the static imports of this file. + const { Effect } = await import("effect"); + return { bunBootstrap: () => Effect.succeed({ kind: "ready", executable: "bun" }) }; +}); import { BunServices } from "@effect/platform-bun"; import { Effect } from "effect"; diff --git a/cli/test/unit/ompRemovals.test.ts b/cli/test/unit/ompRemovals.test.ts index 0b470218..6679f4e5 100644 --- a/cli/test/unit/ompRemovals.test.ts +++ b/cli/test/unit/ompRemovals.test.ts @@ -31,9 +31,11 @@ vi.mock("../../src/engine-native/exec", async () => { const actual = await vi.importActual("../../src/engine-native/exec"); return { ...actual, spawnProcess: mocks.spawnProcess }; }); -vi.mock("../../src/engine-native/bun", () => ({ - bunBootstrap: async () => ({ kind: "ready", executable: "bun" }), -})); +vi.mock("../../src/engine-native/bun", async () => { + // The hoisted factory runs before the static imports of this file. + const { Effect } = await import("effect"); + return { bunBootstrap: () => Effect.succeed({ kind: "ready", executable: "bun" }) }; +}); import { BunServices } from "@effect/platform-bun"; import { Effect } from "effect"; @@ -60,10 +62,9 @@ function testCtx(root: string, dryRun = false, stdout: Array = []): Ctx platform: makePlatform("linux"), deps: { spec: (id) => DEPENDENCIES[id], - probe: vi.fn(() => ({ state: "missing" as const })), - version: async () => "", - versionReading: async () => ({ kind: "version" as const, value: "" }), - path: async () => "", + probe: vi.fn(() => Effect.succeed({ state: "missing" as const })), + version: () => Effect.succeed(""), + path: () => Effect.succeed(""), warnMissing: () => {}, }, }; diff --git a/cli/test/unit/syncLock.test.ts b/cli/test/unit/syncLock.test.ts index cc0ba8e6..a6ce124e 100644 --- a/cli/test/unit/syncLock.test.ts +++ b/cli/test/unit/syncLock.test.ts @@ -610,7 +610,7 @@ async function reachCheckpoint( } describe("interrupt of a sync", () => { - it("keeps the sync lock and the omp folder locks until an interrupted bridged pass settles", async () => { + it("keeps the sync lock and the omp folder locks until an interrupted Bun bootstrap settles", async () => { await withHome(async (home) => { await withSharedFolder(async (shared) => { process.env["PI_CODING_AGENT_DIR"] = shared; @@ -621,12 +621,14 @@ describe("interrupt of a sync", () => { ...base, deps: { ...base.deps, - // The Bun bootstrap, the first bridged pass of the pipeline, waits here. - path: (id) => { - if (id !== "bun") return base.deps.path(id); - entered.resolve(); - return bunPath.promise; - }, + // The Bun bootstrap, the first uninterruptible pass of the pipeline, waits here. + path: (id) => + id !== "bun" + ? base.deps.path(id) + : Effect.promise(() => { + entered.resolve(); + return bunPath.promise; + }), }, }; const fiber = Effect.runFork( diff --git a/cli/test/unit/syncPipelineFailure.test.ts b/cli/test/unit/syncPipelineFailure.test.ts index ac452794..e1abd499 100644 --- a/cli/test/unit/syncPipelineFailure.test.ts +++ b/cli/test/unit/syncPipelineFailure.test.ts @@ -24,9 +24,11 @@ vi.mock("../../src/engine-native/ompPlugins", async (importOriginal) => ({ ...(await importOriginal()), syncPlugins: mocks.syncPlugins, })); -vi.mock("../../src/engine-native/bun", () => ({ - bunBootstrap: async () => ({ kind: "ready", executable: "bun" }), -})); +vi.mock("../../src/engine-native/bun", async () => { + // The hoisted factory runs before the static imports of this file. + const effect = await import("effect"); + return { bunBootstrap: () => effect.Effect.succeed({ kind: "ready", executable: "bun" }) }; +}); import { engineFailureDetail } from "../../src/engine"; import { runEngineNative } from "../../src/engine-native"; diff --git a/cli/test/unit/toolchain.test.ts b/cli/test/unit/toolchain.test.ts index 5619f2ee..18d14f83 100644 --- a/cli/test/unit/toolchain.test.ts +++ b/cli/test/unit/toolchain.test.ts @@ -1,23 +1,40 @@ -import { mkdirSync, readFileSync, rmSync, symlinkSync } from "node:fs"; -import { join } from "node:path"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { + chmodSync, + mkdirSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { basename, dirname, join } from "node:path"; import { stripVTControlCharacters } from "node:util"; +import { BunServices } from "@effect/platform-bun"; import { Effect } from "effect"; import { afterAll, describe, expect, it } from "vitest"; import type { Ctx } from "../../src/engine-native"; +import type { ProbeResult } from "../../src/engine-native/deps"; import { EngineContext } from "../../src/engine-native/engineCtx"; import { modeToolchain } from "../../src/engine-native/modes"; import { makeEngineServices } from "../../src/engine-native/services"; import { report } from "../../src/engine-native/toolchain"; -import { BUN_RUNTIME } from "../lib/cliEntry"; +import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; import { runEngine } from "../lib/engineRun"; import { runPublicCli } from "../lib/goldenExecution"; -import { cleanupTemporaryDirs, makeStubDir, temporaryDir } from "../lib/goldenResources"; +import { cleanupTemporaryDirs, makeStubDir, REPO_DIR, temporaryDir } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; import { floorVersion, verifiedVersion } from "../lib/toolchainManifest"; -/** Run the toolchain mode `args` in the run context `ctx`. */ +/** Run the toolchain mode `args` in the run context `ctx`, on the real file system. */ const runMode = (ctx: Ctx, args: ReadonlyArray): Promise => - Effect.runPromise(modeToolchain(args).pipe(Effect.provideService(EngineContext, ctx))); + Effect.runPromise( + modeToolchain(args).pipe( + Effect.provideService(EngineContext, ctx), + Effect.provide(BunServices.layer), + ), + ); afterAll(cleanupTemporaryDirs); @@ -107,21 +124,27 @@ describe("engine toolchain version report", () => { ])("classifies installed Bun version %j as %s", async (version, status) => { const stdout: Array = []; const services = makeEngineServices({ sinks: { stdout: (chunk) => void stdout.push(chunk) } }); - const ctx = { + const ctx: Ctx = { + repoDir: "/fixture-kit", + home: "/fixture-home", + dryRun: false, + verbose: false, services: { ...services, deps: { ...services.deps, - probe: (tool: string) => - tool === "bun" - ? { state: "present" as const, path: "/stub/bun" } - : { state: "missing" as const }, - version: async (tool: string) => (tool === "bun" ? version : ""), + probe: (tool) => + Effect.succeed( + tool === "bun" ? { state: "present", path: "/stub/bun" } : { state: "missing" }, + ), + version: (tool) => Effect.succeed(tool === "bun" ? version : ""), }, }, - } as Ctx; + nextStepTriggers: { ompRestart: false }, + failures: [], + }; - await report(ctx); + await Effect.runPromise(report(ctx)); const bun = stdout .join("") @@ -199,9 +222,9 @@ describe("public toolchain ensure", () => { ...services, deps: { ...services.deps, - probe: () => ({ state: "present" as const, path: "/stub/bun" }), - path: async () => "/stub/bun", - version: async () => version, + probe: () => Effect.succeed({ state: "present" as const, path: "/stub/bun" }), + path: () => Effect.succeed("/stub/bun"), + version: () => Effect.succeed(version), }, }, } as unknown as Ctx; @@ -223,9 +246,9 @@ describe("public toolchain ensure", () => { ...services, deps: { ...services.deps, - probe: () => ({ state: "present" as const, path: "/stub/bun" }), - path: async () => "/stub/bun", - version: async () => "1.4.0", + probe: () => Effect.succeed({ state: "present" as const, path: "/stub/bun" }), + path: () => Effect.succeed("/stub/bun"), + version: () => Effect.succeed("1.4.0"), }, }, } as unknown as Ctx; @@ -274,3 +297,101 @@ describe("engine toolchain argument errors", () => { expect(stderr).toEqual([expect.stringContaining(diagnostic)]); }); }); + +/** The deadline of a spawned CLI child: it ends before the case deadline, so the case can still report and clean up. */ +const CHILD_DEADLINE_MS = SPAWN_TIMEOUT_MS - 15_000; + +// Linux and macOS only: Bun ignores TMPDIR on Windows, so the case cannot set +// the temporary parent there. The POSIX installer also runs `curl` and then +// `bash`, which these POSIX shell stubs stand in for. +const POSIX_INSTALLER_HOST = process.platform === "linux" || process.platform === "darwin"; + +describe.runIf(POSIX_INSTALLER_HOST)("public toolchain ensure installer folder", () => { + it( + "stages the Bun installer under the TMPDIR parent that the OS resolves", + async () => { + const root = temporaryDir("toolchain-bun-tmpdir-"); + // `/lexical/link` points to `/real/leaf`, so the OS reads + // `/lexical/link/..` as `/real`, and a path join reads it as `/lexical`. + mkdirSync(join(root, "real", "leaf"), { recursive: true }); + mkdirSync(join(root, "lexical")); + symlinkSync(join(root, "real", "leaf"), join(root, "lexical", "link")); + const home = join(root, "home"); + mkdirSync(home); + // The child PATH holds only the stub folder, and the stubs use only shell + // builtins, so no installer command can resolve to a program outside the + // fixture. Each stub writes the physical folder of the installer script, with + // no line delimiter, to its own file under the fixture home. The `curl` stub + // does not write its `-o` destination. + const stubs = join(root, "stubs"); + mkdirSync(stubs); + const stub = (name: string, body: string): void => { + writeFileSync(join(stubs, name), `#!/bin/sh\n${body}\n`); + chmodSync(join(stubs, name), 0o755); + }; + stub( + "curl", + [ + 'target=""', + 'while [ "$#" -gt 0 ]; do', + ' if [ "$1" = "-o" ]; then target="$2"; fi', + " shift", + "done", + `cd -P -- "\${target%/*}" && printf '%s' "$(pwd -P)" > "$HOME/curl-folder"`, + ].join("\n"), + ); + stub("bash", `cd -P -- "\${1%/*}" && printf '%s' "$(pwd -P)" > "$HOME/bash-folder"`); + + // BUN_RUNTIME is an absolute path, so the CLI starts without a PATH lookup. + // Bun is absent for the CLI: no PATH folder holds it, BUN_INSTALL is unset, + // and the home is empty. The CLI leads its own process group, so the + // watchdog can stop the stubs with it. + const child = spawn( + BUN_RUNTIME, + ["--no-env-file", cliEntry(), "toolchain", "ensure", "bun"], + { + cwd: REPO_DIR, + detached: true, + env: { + HOME: home, + USERPROFILE: home, + PATH: stubs, + TMPDIR: `${root}/lexical/link/..`, + LC_ALL: "C", + TERM: "dumb", + }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk)); + child.stdout.resume(); + // A real-time watchdog, not a wait: the child gets its own deadline before + // the case deadline. On expiry the test kills the process group of the + // child and waits for the child to exit, so no process of the fixture + // outlives the case. + let expired = false; + const deadline = setTimeout(() => { + expired = true; + if (child.pid !== undefined) process.kill(-child.pid, "SIGKILL"); + }, CHILD_DEADLINE_MS); + let code: number | null; + try { + [code] = (await once(child, "close")) as [number | null]; + } finally { + clearTimeout(deadline); + } + + expect(expired, `the child did not exit within ${CHILD_DEADLINE_MS} ms`).toBe(false); + // The stubs install no Bun, so the bootstrap ends with install-failed and exit 1. + expect(stderr).toContain(`installing Bun ${verifiedVersion("bun")} (kit-verified)`); + expect(stderr).toContain("Bun install failed"); + expect(code).toBe(1); + const folder = readFileSync(join(home, "curl-folder"), "utf8"); + expect(readFileSync(join(home, "bash-folder"), "utf8")).toBe(folder); + expect(basename(folder)).toMatch(/^docks-kit-bun-.+$/); + expect(dirname(folder)).toBe(realpathSync(join(root, "real"))); + }, + SPAWN_TIMEOUT_MS, + ); +}); diff --git a/cli/test/unit/toolchainOutdated.test.ts b/cli/test/unit/toolchainOutdated.test.ts index e2600191..35b11a40 100644 --- a/cli/test/unit/toolchainOutdated.test.ts +++ b/cli/test/unit/toolchainOutdated.test.ts @@ -1,15 +1,30 @@ -import { mkdtempSync, rmSync } from "node:fs"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { createServer, type AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { Effect } from "effect"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Ctx } from "../../src/engine-native"; +import { writeCache } from "../../src/engine-native/kitDb"; import { makeEngineServices } from "../../src/engine-native/services"; -import { latestUpstream, outdatedReport } from "../../src/engine-native/toolchain"; +import { + latestUpstream, + outdatedReport, + type UpstreamInputs, +} from "../../src/engine-native/toolchain"; +import type { FetchLike } from "../../src/engine-native/sharedTypes"; +import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; +import { REPO_DIR } from "../lib/goldenResources"; +import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; import { verifiedVersion } from "../lib/toolchainManifest"; let home = ""; const NOW = 1_800_000_000_000; +/** The deadline of a spawned CLI child: it ends before the case deadline, so the case can still report and clean up. */ +const CHILD_DEADLINE_MS = SPAWN_TIMEOUT_MS - 15_000; function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status }); @@ -24,6 +39,32 @@ function makeCtx(stdout: Array): Ctx { } as Ctx; } +const lookup = (tool: string, inputs: UpstreamInputs) => + Effect.runPromise(latestUpstream(tool, inputs)); + +const runReport = ( + ctx: Ctx, + options: { readonly refresh: boolean; readonly fetchImpl?: FetchLike }, +) => Effect.runPromise(outdatedReport(ctx, options)); + +/** The manifest tools that `toolchain outdated` looks up: a verified pin and an upstream. */ +function upstreamTools(): Array<{ readonly tool: string; readonly verified: string }> { + const manifest = JSON.parse(readFileSync(join(REPO_DIR, "SoT", "toolchain.json"), "utf8")) as { + readonly tools: Record< + string, + { readonly verified?: string | null; readonly upstream?: unknown } + >; + }; + return Object.entries(manifest.tools).flatMap(([tool, entry]) => + typeof entry.verified === "string" && + entry.verified !== "" && + typeof entry.upstream === "object" && + entry.upstream !== null + ? [{ tool, verified: entry.verified }] + : [], + ); +} + describe("toolchain outdated", () => { beforeEach(() => { home = mkdtempSync(join(tmpdir(), "docks-outdated-")); @@ -36,7 +77,7 @@ describe("toolchain outdated", () => { it("strips the GitHub tag prefix", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ tag_name: "bun-v1.4.3" })); - const result = await latestUpstream("bun", { + const result = await lookup("bun", { home, refresh: false, now: NOW, @@ -48,7 +89,7 @@ describe("toolchain outdated", () => { }); it("rejects a GitHub release tag without the manifest prefix", async () => { - const result = await latestUpstream("bun", { + const result = await lookup("bun", { home, refresh: false, now: NOW, @@ -65,7 +106,7 @@ describe("toolchain outdated", () => { ); const stdout: Array = []; - const code = await outdatedReport(makeCtx(stdout), { refresh: false, fetchImpl }); + const code = await runReport(makeCtx(stdout), { refresh: false, fetchImpl }); const output = stdout.join(""); expect(code).toBe(0); @@ -99,7 +140,7 @@ describe("toolchain outdated", () => { }; const stdout: Array = []; - expect(await outdatedReport(makeCtx(stdout), { refresh: false, fetchImpl })).toBe(0); + expect(await runReport(makeCtx(stdout), { refresh: false, fetchImpl })).toBe(0); const output = stdout.join(""); const bunRow = `^bun\\s+managed\\s+${bunPin.replaceAll(".", "\\.")}\\s+${bunNewer.replaceAll(".", "\\.")}`; expect(output).toMatch(new RegExp(`${bunRow}\\s+newer\\s+github oven-sh/bun$`, "m")); @@ -119,13 +160,13 @@ describe("toolchain outdated", () => { .mockResolvedValueOnce(jsonResponse({ tag_name: "v1.7.0" })) .mockResolvedValueOnce(jsonResponse({ tag_name: "v1.8.0" })); - const first = await latestUpstream("omp", { + const first = await lookup("omp", { home, refresh: false, now: NOW, fetchImpl, }); - const cached = await latestUpstream("omp", { + const cached = await lookup("omp", { home, refresh: false, now: NOW + 23 * 3600_000, @@ -135,7 +176,7 @@ describe("toolchain outdated", () => { expect(cached).toEqual(first); expect(fetchImpl).toHaveBeenCalledTimes(1); - const refreshed = await latestUpstream("omp", { + const refreshed = await lookup("omp", { home, refresh: true, now: NOW + 23 * 3600_000, @@ -150,13 +191,13 @@ describe("toolchain outdated", () => { .fn(async () => jsonResponse({ tag_name: "v1.7.0" })) .mockRejectedValueOnce(new Error("network unavailable")); - const failed = await latestUpstream("omp", { + const failed = await lookup("omp", { home, refresh: false, now: NOW, fetchImpl, }); - const recovered = await latestUpstream("omp", { + const recovered = await lookup("omp", { home, refresh: false, now: NOW, @@ -167,4 +208,85 @@ describe("toolchain outdated", () => { expect(recovered).toEqual({ ok: true, version: "1.7.0" }); expect(fetchImpl).toHaveBeenCalledTimes(2); }); + + describe("spawned CLI", () => { + it( + "prints the seeded upstream versions from a fresh cache without a network request", + async () => { + // Every proxy variable points at this listener, so a request that the cache + // should answer reaches it instead of the network. + const connections: Array = []; + const listener = createServer((socket) => { + connections.push(`${socket.remoteAddress}:${socket.remotePort}`); + socket.destroy(); + }); + try { + listener.listen(0, "127.0.0.1"); + await once(listener, "listening"); + const proxy = `http://127.0.0.1:${(listener.address() as AddressInfo).port}`; + const tools = upstreamTools(); + expect(tools.length).toBeGreaterThan(0); + for (const { tool } of tools) writeCache(home, `upstream:${tool}`, "999.0.0", Date.now()); + + // The environment starts empty and Bun reads no `.env` file, so no + // proxy, token, engine, or NO_PROXY value of the runner leaks in. + const child = spawn(BUN_RUNTIME, ["--no-env-file", cliEntry(), "toolchain", "outdated"], { + cwd: REPO_DIR, + env: { + HOME: home, + USERPROFILE: home, + PATH: process.env["PATH"] ?? "", + LC_ALL: "C", + TERM: "dumb", + HTTP_PROXY: proxy, + HTTPS_PROXY: proxy, + ALL_PROXY: proxy, + http_proxy: proxy, + https_proxy: proxy, + all_proxy: proxy, + NO_PROXY: "", + no_proxy: "", + }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk)); + child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk)); + // A real-time watchdog, not a wait: the child gets its own deadline before + // the case deadline. On expiry the test kills the child and waits for its + // exit, so no child outlives the case. + let expired = false; + const deadline = setTimeout(() => { + expired = true; + child.kill("SIGKILL"); + }, CHILD_DEADLINE_MS); + let code: number | null; + try { + [code] = (await once(child, "close")) as [number | null]; + } finally { + clearTimeout(deadline); + } + + expect(expired, `the child did not exit within ${CHILD_DEADLINE_MS} ms`).toBe(false); + expect(stderr).toBe(""); + expect(code).toBe(0); + expect(stdout).not.toContain("lookup failed"); + for (const { tool, verified } of tools) { + const pin = verified.replaceAll(".", "\\."); + expect(stdout).toMatch( + new RegExp(`^${tool}\\s+\\S+\\s+${pin}\\s+999\\.0\\.0\\s+newer\\s`, "m"), + ); + } + expect(connections).toEqual([]); + } finally { + if (listener.listening) { + listener.close(); + await once(listener, "close"); + } + } + }, + SPAWN_TIMEOUT_MS, + ); + }); });