Files
orca/config/scripts/check-runtime-electron-ratchet.mjs
T
Neil 03fcfdfb92 feat(orcad): boot the Orca runtime on plain Node (#15968)
* refactor(host): resolve the app root through the port in fork-reachable modules

`parcel-watcher-entry-path.ts` and `session-scanner-service-entry-path.ts` read the
app root via `require('electron').app` inside a try/catch that already returns null
when Electron is absent. They were therefore correct under plain Node at runtime and
only failed the *static* text check — which is real, not pedantic: the comment in
`ports/port-scan-command-client.ts:19` records that the plain-node-entry-guard fails
on that literal text, try/catch or not.

`hasAppEnvironment() ? getAppEnvironment() : null` gives the identical "no app root
here" answer without the text. That restores `hasAppEnvironment`, which an earlier
commit in this stack deleted as unused — it now has the caller it was waiting for.

Ratchet baseline 27 → 25.

Verified: 74 files / 458 tests; `pnpm typecheck` clean; `oxlint` clean.

* feat(orcad): boot the Orca runtime on plain Node

Closes the last two Electron couplings and makes `orcad` a working artifact:
a 4.43 MB Node bundle that boots, pairs, registers a repo, creates a real git
worktree and round-trips a PTY — with zero `require("electron")`.

Ratchet 2 -> 0, so `config/runtime-electron-baseline.txt` is now empty and its
test asserts exactly that: any reachable electron import is a regression.

- speech: inject the service factories, so importing ModelManager for its type
  no longer drags Electron's streaming net.request into the graph
- filesystem-watcher: add a WorktreeWatcherRemoval port. Every entry in those
  maps arrives through an ipcMain handler carrying a renderer sender, so a host
  with no renderer has nothing to close, restore or forget — the inert default
  is what the desktop code does against empty maps, not a stub hiding work
- user-data-path / profile-storage-paths: resolve userData through
  AppEnvironment. These surfaced only once orcad pulled the store in

Both host ports now anchor to a realm-global symbol. `vi.resetModules()` gives
the re-imported graph a fresh module copy, so a binding installed before the
reset silently read back as uninstalled.

The acceptance smoke drives both hosts through one code path (`--target
orcad|electron`) and seeds its own git repo, so it is hermetic and asserts the
same contract of each. Wired into PR CI.

* test(smoke): remove the seeded workspace container, not just the worktree

* test(smoke): surface the server's stderr when it dies before ready

* fix(smoke): build node-pty for Node before booting orcad in CI

* fix(smoke): drive the CLI built from this checkout, not one on PATH

* docs(ratchet): say the baseline must stay empty, not merely shrink

* build(orcad): externalize only the native modules actually in the graph
2026-08-22 21:47:46 -07:00

171 lines
6.3 KiB
JavaScript

#!/usr/bin/env node
/**
* Ratchet gate for Electron imports reachable from the Orca runtime.
*
* The runtime is meant to become host-agnostic so it can also run on plain Node
* (see docs/design/node-only-runtime-backend.html). Nothing enforces that today:
* `orca-runtime.ts` reaches ~50 modules that import `electron`, and the number
* silently grows whenever someone adds an import several hops away, because no
* single reviewer sees the transitive edge.
*
* This bundles the runtime with esbuild, reads the metafile for every module that
* imports `electron`, and compares that set to a checked-in baseline. A NEW module
* fails the build; a removed one must be dropped from the baseline. The baseline
* may only shrink, so the migration is measurable and cannot regress.
*
* This is a reachability check, not a lint rule: the point is precisely the edges
* that no per-file rule can see.
*
* Usage: node config/scripts/check-runtime-electron-ratchet.mjs [--write]
*/
import { build } from 'esbuild'
import { readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import process from 'node:process'
// Why absolute, not cwd-relative: `pnpm lint` runs from the repo root but CI steps and
// editors do not always, and a cwd-relative miss surfaced as an unhandled ENOENT stack
// instead of a usable message.
const ROOT = path.join(import.meta.dirname, '..', '..')
const BASELINE_PATH = path.join(ROOT, 'config', 'runtime-electron-baseline.txt')
// The two module graphs a Node backend would have to boot: the runtime service
// itself and the RPC server that fronts it.
const ENTRY_POINTS = [
path.join(ROOT, 'src', 'main', 'runtime', 'orca-runtime.ts'),
path.join(ROOT, 'src', 'main', 'runtime', 'runtime-rpc.ts')
]
// Native addons and electron cannot be bundled; externalising them is what the
// relay build already does (config/scripts/build-relay.mjs).
const EXTERNAL = [
'electron',
'node-pty',
'@parcel/watcher',
'better-sqlite3',
'keytar',
'fsevents',
'cpu-features'
]
/**
* Why: some optional native deps (ssh2's cpu-features) reference a prebuilt `.node`
* that only exists where a build toolchain has run. Resolving them made this gate
* pass on a developer machine and hard-fail on CI. Nothing here needs the addon —
* only the import graph — so mark every `.node` external instead.
*/
const externalNativeAddons = {
name: 'external-native-addons',
setup(pluginBuild) {
pluginBuild.onResolve({ filter: /\.node$/ }, (args) => ({ path: args.path, external: true }))
}
}
export async function collectElectronImporters(entryPoints = ENTRY_POINTS) {
const result = await build({
entryPoints,
bundle: true,
write: false,
// Why outdir with write:false: esbuild refuses multiple entry points without one,
// even though nothing is emitted — the metafile is all this reads.
outdir: path.join(ROOT, 'runtime-electron-ratchet-metafile-only'),
platform: 'node',
target: 'node20',
format: 'cjs',
external: EXTERNAL,
metafile: true,
absWorkingDir: ROOT,
logLevel: 'silent',
plugins: [externalNativeAddons]
})
const importers = new Set()
for (const [file, info] of Object.entries(result.metafile.inputs)) {
for (const imported of info.imports ?? []) {
// Subpaths (electron/main) are as unavailable under plain Node as the bare module.
if (imported.path === 'electron' || imported.path.startsWith('electron/')) {
importers.add(path.relative(ROOT, path.resolve(ROOT, file)).split(path.sep).join('/'))
}
}
}
return [...importers].sort()
}
export function readBaseline(text) {
return text
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith('#'))
.sort()
}
export function diffAgainstBaseline(current, baseline) {
const baselineSet = new Set(baseline)
const currentSet = new Set(current)
return {
added: current.filter((file) => !baselineSet.has(file)),
removed: baseline.filter((file) => !currentSet.has(file))
}
}
function renderBaseline(files) {
return [
'# Modules reachable from the Orca runtime that import `electron`.',
'# Generated by config/scripts/check-runtime-electron-ratchet.mjs.',
'# This list is EMPTY and must stay that way: the runtime boots on plain Node',
'# (see `pnpm run build:orcad`). Any entry means the runtime got less portable;',
'# migrate the module behind a host port instead (src/main/host/).',
'',
...files
].join('\n')
}
async function main() {
const write = process.argv.includes('--write')
const current = await collectElectronImporters()
if (write) {
writeFileSync(BASELINE_PATH, `${renderBaseline(current)}\n`)
console.log(`[runtime-electron-ratchet] wrote ${current.length} entries to ${BASELINE_PATH}`)
return
}
const baseline = readBaseline(readFileSync(BASELINE_PATH, 'utf8'))
const { added, removed } = diffAgainstBaseline(current, baseline)
if (added.length > 0) {
console.error(
`[runtime-electron-ratchet] ${added.length} new module(s) reachable from the Orca runtime now import electron:
${added.map((file) => ` + ${file}`).join('\n')}
The runtime must stay bootable on plain Node. Put the Electron facility behind a port in
src/main/host/ and depend on the port, or move the code out of the runtime's import graph.
See docs/design/node-only-runtime-backend.html.`
)
process.exitCode = 1
return
}
if (removed.length > 0) {
console.error(
`[runtime-electron-ratchet] ${removed.length} module(s) no longer import electron — nice.
Refresh the baseline so the gate keeps its new, tighter floor:
${removed.map((file) => ` - ${file}`).join('\n')}
node config/scripts/check-runtime-electron-ratchet.mjs --write`
)
process.exitCode = 1
return
}
console.log(`[runtime-electron-ratchet] ok — ${current.length} entries, unchanged.`)
}
// Why pathToFileURL and not a `file://` template: on Windows process.argv[1] is a
// native path (C:\repo\...) while import.meta.url is file:///C:/repo/..., so the
// template never matches and the gate would exit 0 without checking anything — a
// lint gate that fails open. Same idiom as check-max-lines-ratchet.mjs:225.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
await main()
}