Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions bin/ensure-bun.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,21 @@ if (-not $env:CLAUDE_PLUGIN_DATA) { [Console]::Error.WriteLine("ensure-bun: CLAU
$BunDir = Join-Path $env:CLAUDE_PLUGIN_DATA "bun"
$BunBin = Join-Path $BunDir "bun.exe"

# Probe the pinned bun's --version. MUST route through `cmd /c`, NOT the PS call
# operator `& $BunBin`: under the host's detached/no-console spawn (launch.mjs
# stdio:"ignore"/inherit with no attached console) PowerShell refuses to activate
# a native .exe in the pipeline (CantActivateDocumentInPipeline) and `& $BunBin`
# yields EMPTY — so the version compare fails even for a valid pinned bun, and
# every launch re-downloads ~110 MB, overrunning the 30 s MCP connect budget
# (Cowork Windows field finding, 2026-06-10). `cmd /c` invokes the exe via the
# command interpreter, which has no such restriction. POSIX ensure-bun.sh uses
# $(...) capture and is unaffected.
function Test-Ok {
if (-not (Test-Path $BunBin)) { return $false }
try { return ((& $BunBin --version 2>$null) -eq $Pin) } catch { return $false }
try {
$v = (cmd /c "`"$BunBin`" --version" 2>$null | Select-Object -First 1)
return ("$v".Trim() -eq $Pin)
} catch { return $false }
}

if (Test-Ok) { exit 0 }
Expand All @@ -43,7 +55,10 @@ try {
Expand-Archive -Path $Zip -DestinationPath $Tmp -Force
Move-Item -Force (Join-Path $Tmp "bun-windows-x64\bun.exe") $BunBin
Remove-Item -Recurse -Force $Tmp
[Console]::Error.WriteLine("ensure-bun: provisioned $(& $BunBin --version)")
# Same cmd /c routing as Test-Ok — a bare `& $BunBin` prints blank under the
# detached spawn, making this success line read "provisioned " with no version.
$ver = (cmd /c "`"$BunBin`" --version" 2>$null | Select-Object -First 1)
[Console]::Error.WriteLine("ensure-bun: provisioned $("$ver".Trim())")
} finally {
if ($haveLock) { Remove-Item -Recurse -Force $Lock -ErrorAction SilentlyContinue }
}
13 changes: 13 additions & 0 deletions bin/launch.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Type surface for bin/launch.mjs (a hand-written .mjs launcher that must stay
// runnable as `bun bin/launch.mjs`). Only the pure, exported resolveEntry is
// consumed by TS (tests/launch.test.ts, Guard 3b); the rest of launch.mjs is the
// side-effectful launch sequence gated by import.meta.main. Under
// moduleResolution:"bundler", an import of "../bin/launch.mjs" resolves this
// `.d.mts` for types while bun loads the real `.mjs` at runtime.

/**
* Resolve the server entrypoint for a plugin install rooted at `root`. Prefers
* the built bundle `dist/server.js` if present; otherwise falls through to the
* source-sync TS entrypoint `src/server/index.ts`.
*/
export function resolveEntry(root: string): string;
124 changes: 70 additions & 54 deletions bin/launch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
// Modes:
// bun launch.mjs provision bun, then run the server
// bun launch.mjs --provision-only pre-warm bun and exit (SessionStart hook)
//
// STRUCTURE: the side-effectful launch sequence (env reads, provision, spawn) is
// wrapped in `main()` and gated by `import.meta.main`, so launch.test.ts can
// `import { resolveEntry }` to assert entry resolution WITHOUT triggering the
// provisioner or a server spawn. When the host runs `bun bin/launch.mjs`,
// launch.mjs IS the entry → import.meta.main is true → main() runs unchanged.

import { spawn, spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
Expand All @@ -43,65 +49,75 @@ const die = (msg) => {
process.exit(1);
};

const root = process.env.CLAUDE_PLUGIN_ROOT;
const data = process.env.CLAUDE_PLUGIN_DATA;
if (!root) die("CLAUDE_PLUGIN_ROOT is unset");
if (!data) die("CLAUDE_PLUGIN_DATA is unset");
// Resolve the server entrypoint. The built bundle (dist/server.js) wins if
// present; source-sync has no dist/, so it falls through to the TS entrypoint
// bun runs directly (auto-installing the reached import graph into BUN_INSTALL's
// cache on first call). Pure (no env, no spawn, no exit) so it is unit-testable
// in isolation — the side-effectful sequence lives in main(), below.
export function resolveEntry(root) {
return existsSync(join(root, "dist", "server.js"))
? join(root, "dist", "server.js")
: join(root, "src", "server", "index.ts");
}

// ── 1. Provision the pinned bun runtime (synchronous correctness gate) ───────
// Delegates to the same ensure-bun.{sh,ps1} the built bundles use. ALL of the
// provisioner's output is mapped to OUR stderr (the stdio integer `2` shares the
// parent's fd 2): stdout (fd 1) stays clean for the JSON-RPC stream the child
// bun will own.
const provision = isWin
? spawnSync(
"powershell",
["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(root, "bin", "ensure-bun.ps1")],
{ stdio: ["ignore", 2, 2], windowsHide: true },
)
: spawnSync("sh", [join(root, "bin", "ensure-bun.sh")], { stdio: ["ignore", 2, 2] });
if (provision.error) die(`failed to launch provisioner: ${provision.error.message}`);
if (provision.status !== 0) die(`provisioner exited with status ${provision.status}`);
function main() {
const root = process.env.CLAUDE_PLUGIN_ROOT;
const data = process.env.CLAUDE_PLUGIN_DATA;
if (!root) die("CLAUDE_PLUGIN_ROOT is unset");
if (!data) die("CLAUDE_PLUGIN_DATA is unset");

if (process.argv.includes("--provision-only")) process.exit(0);
// ── 1. Provision the pinned bun runtime (synchronous correctness gate) ─────
// Delegates to the same ensure-bun.{sh,ps1} the built bundles use. ALL of the
// provisioner's output is mapped to OUR stderr (the stdio integer `2` shares
// the parent's fd 2): stdout (fd 1) stays clean for the JSON-RPC stream the
// child bun will own.
const provision = isWin
? spawnSync(
"powershell",
["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(root, "bin", "ensure-bun.ps1")],
{ stdio: ["ignore", 2, 2], windowsHide: true },
)
: spawnSync("sh", [join(root, "bin", "ensure-bun.sh")], { stdio: ["ignore", 2, 2] });
if (provision.error) die(`failed to launch provisioner: ${provision.error.message}`);
if (provision.status !== 0) die(`provisioner exited with status ${provision.status}`);

// ── 2. Resolve bun + the server entrypoint ───────────────────────────────────
const bun = join(data, "bun", isWin ? "bun.exe" : "bun");
if (!existsSync(bun)) die(`provisioned bun not found at ${bun}`);
// Built bundle (dist/server.js) wins if present; source-sync has no dist/, so it
// falls through to the TS entrypoint bun runs directly (auto-installing the
// reached import graph into BUN_INSTALL's cache on first call).
const entry = existsSync(join(root, "dist", "server.js"))
? join(root, "dist", "server.js")
: join(root, "src", "server", "index.ts");
if (process.argv.includes("--provision-only")) process.exit(0);

// ── 3. Cross-OS env defaults derived from the REAL env var ───────────────────
// CLAUDE_PLUGIN_DATA persists across plugin updates and is set on every host, so
// it is the correct cross-OS anchor for both the bun auto-install cache and
// runtime state. We derive these in JS (not via manifest ${...} interpolation)
// so the manifest needs no CLAUDE_PLUGIN_DATA expansion. An already-set value
// (manifest env or user shell) wins.
const env = { ...process.env };
if (!env.BUN_INSTALL) env.BUN_INSTALL = join(data, "bun-cache");
if (!env.SCHOLAR_RUNTIME_ROOT) env.SCHOLAR_RUNTIME_ROOT = join(data, "runtime");
// ── 2. Resolve bun + the server entrypoint ─────────────────────────────────
const bun = join(data, "bun", isWin ? "bun.exe" : "bun");
if (!existsSync(bun)) die(`provisioned bun not found at ${bun}`);
const entry = resolveEntry(root);

// ── 4. Spawn bun. stdio:"inherit" → client <-> bun own fd 0/1 directly. ──────
const passthrough = process.argv.slice(2).filter((a) => a !== "--provision-only");
const child = spawn(bun, [entry, ...passthrough], {
stdio: "inherit",
cwd: root,
env,
windowsHide: true,
});
// ── 3. Cross-OS env defaults derived from the REAL env var ─────────────────
// CLAUDE_PLUGIN_DATA persists across plugin updates and is set on every host,
// so it is the correct cross-OS anchor for both the bun auto-install cache and
// runtime state. We derive these in JS (not via manifest ${...} interpolation)
// so the manifest needs no CLAUDE_PLUGIN_DATA expansion. An already-set value
// (manifest env or user shell) wins.
const env = { ...process.env };
if (!env.BUN_INSTALL) env.BUN_INSTALL = join(data, "bun-cache");
if (!env.SCHOLAR_RUNTIME_ROOT) env.SCHOLAR_RUNTIME_ROOT = join(data, "runtime");

for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
process.on(sig, () => {
try {
child.kill(sig);
} catch {
/* child already gone */
}
// ── 4. Spawn bun. stdio:"inherit" → client <-> bun own fd 0/1 directly. ────
const passthrough = process.argv.slice(2).filter((a) => a !== "--provision-only");
const child = spawn(bun, [entry, ...passthrough], {
stdio: "inherit",
cwd: root,
env,
windowsHide: true,
});

for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
process.on(sig, () => {
try {
child.kill(sig);
} catch {
/* child already gone */
}
});
}
child.on("error", (err) => die(`failed to spawn bun: ${err.message}`));
child.on("exit", (code, signal) => process.exit(signal ? 1 : (code ?? 0)));
}
child.on("error", (err) => die(`failed to spawn bun: ${err.message}`));
child.on("exit", (code, signal) => process.exit(signal ? 1 : (code ?? 0)));

if (import.meta.main) main();
8 changes: 8 additions & 0 deletions docs/audits/2026-06-02-maintenance-readiness.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ been run** against a live server. Everything else is tidiness.
> `src/server/index.ts` path (cold pinned-bun provision + cold bun auto-install of
> the import graph into the `CLAUDE_PLUGIN_DATA` cache, leaving the shipped tree
> pristine → clean MCP `initialize`). vec0-ABI pin unchanged.
>
> **Refactor note (2026-06-10, `fix/windows-connect-timeout`).** That live run
> exercised the *pre-refactor* `launch.mjs`. `launch.mjs` was since refactored to
> extract a pure `resolveEntry(root)` and gate the side-effectful launch sequence
> behind `import.meta.main` — a **behaviour-preserving relocation** (provision /
> resolve / spawn logic byte-identical, only re-indented), now pinned by
> `tests/launch.test.ts` (entry resolution: `dist/server.js` when built, else
> `src/server/index.ts`). The live entry-path verification above still stands.

---

Expand Down
28 changes: 27 additions & 1 deletion docs/superpowers/specs/2026-06-01-slim-plugin-pivot.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,12 @@ enumerated with its failure symptom in **HUMAN.md §5**.
§5 leg 7 — confirm a Desktop restart recovers cleanly.
- **ensure-bun.ps1**: the PowerShell download/extract path is unexecuted on the
dev host. Validate `Invoke-WebRequest`/`Expand-Archive` + the lock-dir guard.
- **koffi.node (win32-x64) — KNOWN REGRESSION (decided: accept + document).**
- **koffi.node (win32-x64) — KNOWN REGRESSION (decided: accept + document).
FIELD-CONFIRMED 2026-06-10 (Cowork Windows):** the predicted `require("koffi")`
failure surfaced live as `Cannot find native Koffi module` on pdf-child spawn —
exactly the swallowed-throw path below, now observed rather than inferred. The
prediction held; no behaviour change is required (it remains best-effort, off by
default), only this status flip from "predicted" to "observed."
`attachJobObject` does a runtime `require("koffi")` inside `server.js`. `bun
build --target=bun` keeps native modules external, and the slim package ships
**no `node_modules`**, so on Windows that `require` throws and is swallowed by
Expand All @@ -268,6 +273,27 @@ enumerated with its failure symptom in **HUMAN.md §5**.
`node_modules/koffi`), *or* tree-kill the pdf child from the cmd-side launcher.
Not done blind here — koffi's native-binding resolution cannot be validated off
the target.
- **Pinned-bun SIGILL on pdf-child spawn — NEW, field-observed 2026-06-10
(intermittent; single occurrence).** On one Cowork Windows boot the **pinned**
`bun.exe` (`bun-windows-x64` `1.3.11`, the vec0-ABI-matched runtime ensure-bun
provisions) crashed with `Illegal instruction` as the pdf child was spawned, so
`spawnPdfChild` saw the child die immediately. It did not reproduce on the next
boot. **Mechanism — hypothesis, NOT confirmed:** the default `bun-windows-x64`
release is built for a modern x86-64 baseline (uses AVX2-class instructions); on
a CPU/VM that does not expose them, the process traps `SIGILL`. The intermittency
fits a host that sometimes schedules the MCP onto a constrained vCPU, or a flaky
download leaving a corrupt `bun.exe` (Expand-Archive over a partial zip) — both
are guesses pending a Windows repro. **Remediation hypotheses (unvalidated, do
NOT ship blind):** (a) if it is the instruction-set mismatch, provision bun's
**`-baseline`** Windows build (`bun-windows-x64-baseline.zip`) instead of / as a
SIGILL-triggered fallback — it targets older CPUs and is the canonical bun fix
for `Illegal instruction`, but it must still carry the **same vec0 ABI** as the
pin, so the swap has to be version-locked the way the current pin is; (b) if it
is download corruption, have ensure-bun verify the extracted `bun.exe`
(size/hash, or the very `cmd /c "<bun>" --version` probe the connect-timeout fix
added) before declaring provision success, and re-download on mismatch. Pick the
branch only after a Windows repro distinguishes them — a `--version` that itself
SIGILLs points at (a); a `--version` that mismatches the pin points at (b).
- **UI bundling** — *RESOLVED 2026-06-04 (`eda8026`+`306e3f8`).* This bullet predicted the
defect: `build:ui` emits a multi-file `ui/index.html` + `chunk-*.js`, and the
sandboxed MCP-App iframe (SEP-1865) cannot fetch sibling chunks — so the
Expand Down
Loading
Loading