Skip to content

The agent that grows with you

refactor(build): share product recipes across distributions

ethernet1bf588234c7c
diff --git a/.dockerignore b/.dockerignore
index 660964ab915..31bed2c49b4 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -12,6 +12,8 @@ __pycache__
*.egg-info/
dist/
build/
+!scripts/build/
+!scripts/build/**
# Virtual environments
venv/
@@ -27,6 +29,8 @@ node_modules
.notebooklm-playwright/
.pip-cache/
.uv-cache/
+.cache/
+.build/
# Built artifacts that are regenerated inside the image. Excluded so local
# rebuilds on the developer's machine don't invalidate the npm-install layer
@@ -58,6 +62,8 @@ htmlcov/
# Documentation
*.md
+!skills/**/*.md
+!optional-skills/**/*.md
# Runtime data (bind-mounted at /opt/data; must not leak into build context)
data/
@@ -108,6 +114,7 @@ packaging/
# Design and planning documents
plans/
.plans/
+.hermes/
# Repo-level dotfiles that are git-only or dev-tooling config
.envrc
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index 68be4377ae8..64d3a2f1117 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -1442,33 +1442,23 @@ jobs:
termux-build/payload/.work/build_set.txt
key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/termux-builder.Dockerfile') }}
- - name: Build the TUI bundle for the deb
- shell: bash
- # The deb ships the PREBUILT TUI (hermes --tui runs it directly via
- # the payload node; there is no npm on a phone). Same shape as the
- # desktop payload: git archive never carries built dists, so plant
- # the just-built entry.js into the staged app tree.
- run: |
- npm ci --workspace ui-tui --include=dev --no-fund --no-audit --silent
- npm run build --workspace ui-tui
- python3 scripts/bundles/payload.py surfaces termux-build/payload --repo-dir app --tui-only
-
- name: Assemble the .deb
shell: bash
env:
TERMUX_BUILDER_IMAGE: ${{ steps.builder_image.outputs.image }}
- # build_deb.sh always validates in a fresh pinned container (no
- # opt-out flag); the channel is derived from the tag inside the
- # script via deb_version.py.
+ # The driver prepares locked TUI dependencies and builds the shared
+ # TUI product before handing the staged bionic payload to build_deb.sh.
+ # Native dependency staging stays above; .deb validation still runs
+ # in a fresh pinned container with no opt-out.
run: |
if [ -n "$HERMES_BUILD_COMMIT" ]; then
- bash scripts/termux/build_deb.sh \
+ python3 scripts/termux/build.py \
--repo . \
--commit "$HERMES_BUILD_COMMIT" \
--payload termux-build/payload \
--out termux-build/deb
else
- bash scripts/termux/build_deb.sh \
+ python3 scripts/termux/build.py \
--repo . \
--tag "$HERMES_PAYLOAD_TAG" \
--payload termux-build/payload \
diff --git a/.gitignore b/.gitignore
index b2bd61c0317..f3f0e4495d0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -76,6 +76,7 @@
*.tsbuildinfo
*-snapshots/
.act-sandbox-agent.*
+.build/
.bytecode-fingerprint
.bytecode-fingerprint.tmp
.codex/
diff --git a/Dockerfile b/Dockerfile
index 1199106dae9..6e9ee6c846f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -48,7 +48,7 @@ RUN apt-get -o Acquire::Retries=3 update && \
# 2.41) runtime. Bumping to a new Node major is a one-line ARG change; see
# #4977.
FROM node:26-bookworm-slim@sha256:9e6f9357d371591e32ab6f2d8a26d63bdd0d17c29eee3f4f3e7e454d9634bf73 AS node_source
-FROM debian:13.4
+FROM debian:13.4 AS runtime_base
# Disable Python stdout buffering to ensure logs are printed immediately.
# Do not write .pyc files at runtime: /opt/hermes is immutable in the
@@ -231,36 +231,32 @@ ENV UV_PYTHON_DOWNLOADS=never
# native extensions must use the compiler installed in this image.
ENV CC=gcc CXX=g++
-# ---------- Layer-cached dependency install ----------
-# Copy only package manifests first so npm install is cached unless the
-# lockfiles themselves change.
-#
-# ui-tui/packages/hermes-ink/ is copied IN FULL (not just its manifests)
-# because it is referenced as a `file:` workspace dependency from
-# ui-tui/package.json. Copying the tree up front lets npm resolve the
-# workspace to real content instead of stopping at a bare package.json.
+# Frontend dependencies never enter the runtime layers.
+FROM runtime_base AS frontend_build
COPY package.json package-lock.json ./
COPY web/package.json web/
COPY ui-tui/package.json ui-tui/
COPY ui-tui/packages/hermes-ink/ ui-tui/packages/hermes-ink/
-# apps/shared/ is copied IN FULL because web/package.json references it as a
-# `file:` workspace dependency (same pattern as hermes-ink above).
COPY apps/shared/ apps/shared/
-
-# `npm_config_install_links=false` forces npm to install `file:` deps as
-# symlinks instead of copies. This is the default since npm 10+, which is
-# what the image ships now (via the node:22 source stage). We set it
-# explicitly anyway as defense-in-depth: the previous Debian-bundled npm
-# 9.x defaulted to install-as-copy, which produced a hidden
-# node_modules/.package-lock.json that permanently disagreed with the root
-# lock on the @hermes/ink entry, tripped the TUI launcher's
-# `_tui_need_npm_install()` check on every startup, and triggered a
-# runtime `npm install` that then failed with EACCES. Keeping the env
-# guards against a future regression if the source npm version changes.
+COPY scripts/build/node-deps.mjs scripts/build/node-deps.mjs
ENV npm_config_install_links=false
+RUN node scripts/build/node-deps.mjs --source /opt/hermes --workspace ui-tui --workspace web
-RUN npm install --prefer-offline --no-audit --fetch-retries=5 && \
- npm cache clean --force
+COPY pyproject.toml uv.lock ./
+COPY web/ web/
+COPY ui-tui/ ui-tui/
+COPY scripts/build/*.mjs scripts/build/
+COPY scripts/generate-icons.mjs scripts/generate_icons.py scripts/
+COPY assets/ assets/
+RUN node scripts/generate-icons.mjs --source /opt/hermes --out /tmp/hermes-icons && \
+ node scripts/build/tui.mjs --source /opt/hermes --out /opt/products/tui && \
+ node scripts/build/web.mjs --source /opt/hermes --icons /tmp/hermes-icons --out /opt/products/web
+
+FROM runtime_base AS runtime
+# Standalone TypeScript linting is a runtime feature; Vite/esbuild are not.
+COPY --from=frontend_build /opt/hermes/node_modules/typescript /opt/hermes/node_modules/typescript
+RUN mkdir -p /opt/hermes/node_modules/.bin && \
+ ln -s ../typescript/bin/tsc /opt/hermes/node_modules/.bin/tsc
# ---------- Photon iMessage sidecar deps (baked, NS-606) ----------
# The photon plugin's Node sidecar needs its own node_modules
@@ -320,22 +316,18 @@ RUN cd plugins/platforms/photon/sidecar && \
# avoids the cross-platform failures that kept [matrix] out of [all]
# while still making Matrix work in the published container. Fixes #30399.
#
-# The editable link is created after the source copy below.
+# Source binding is created after the source copy below.
COPY pyproject.toml uv.lock ./
RUN touch ./README.md
-RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra hindsight --extra matrix
+COPY scripts/build/python_env.py scripts/build/python_env.py
+RUN python3 -m scripts.build.python_env --source /opt/hermes --python /usr/local/bin/python3 \
+ --uv /usr/local/bin/uv --out /opt/hermes/.venv --no-install-project \
+ --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock \
+ --extra azure-identity --extra hindsight --extra matrix
-# ---------- Frontend build (cached independently from Python source) ----------
-# Copy only the frontend source trees first so that Python-only changes don't
-# invalidate the (relatively slow) web + ui-tui build layer.
-COPY web/ web/
-COPY ui-tui/ ui-tui/
-COPY apps/shared/ apps/shared/
-COPY scripts/generate-icons.mjs scripts/generate_icons.py scripts/
-COPY assets/ assets/
-RUN cd web && npm run build && \
- cd ../ui-tui && npm run build && \
- rm -rf /opt/hermes/.cache/icon-build
+# Shared product outputs are independent of application dependency assembly.
+COPY --from=frontend_build /opt/products/tui /opt/hermes/ui-tui
+COPY --from=frontend_build /opt/products/web /opt/hermes/hermes_cli/web_dist
# ---------- Source code ----------
# .dockerignore excludes node_modules, so the installs above survive.
@@ -347,11 +339,8 @@ RUN cd web && npm run build && \
# write so the build steps below don't need chmod u+w dances.
COPY --link --chmod=a+rX,go-w . .
-# ---------- Permissions ----------
-# Link hermes-agent itself (editable). Deps are already installed in the
-# cached layer above; `--no-deps` makes this a fast egg-link creation with no
-# resolution or downloads.
-RUN uv pip install --python /opt/hermes/.venv/bin/python --no-cache-dir --no-deps -e "."
+# The shared assembler binds the prepared environment and frontend products.
+RUN /opt/hermes/.venv/bin/python -m docker.build_agent
# Wire the exec shim and install-method stamp. Files under /opt/hermes are
# already root-owned (COPY, uv sync, npm install all run as root) and
diff --git a/apps/bootstrap-installer/package.json b/apps/bootstrap-installer/package.json
index d94bc17e41b..e851e237c83 100644
--- a/apps/bootstrap-installer/package.json
+++ b/apps/bootstrap-installer/package.json
@@ -6,7 +6,7 @@
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 5175",
- "prebuild": "node ../../scripts/generate-icons.mjs",
+ "prebuild": "node ../../scripts/generate-icons.mjs --source ../.. --out ../..",
"build": "tsc -b && vite build",
"preview": "vite preview",
"tauri": "tauri",
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index be81730bdf7..661813d33f0 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,8 +27,8 @@
"profile:main": "tsc --build tsconfig.electron.json && wait-on http://127.0.0.1:5174 && node scripts/bundle-electron-main.mjs --dev && cross-env XCURSOR_SIZE=24 HERMES_DESKTOP_DEV_SERVER=http://127.0.0.1:5174 electron --inspect=9229 .",
"profile:main:cpu": "tsc --build tsconfig.electron.json && wait-on http://127.0.0.1:5174 && node scripts/bundle-electron-main.mjs --dev && cross-env XCURSOR_SIZE=24 NODE_OPTIONS=--cpu-prof HERMES_DESKTOP_DEV_SERVER=http://127.0.0.1:5174 electron .",
"start": "npm run build && electron .",
- "prebuild": "node ../../scripts/generate-icons.mjs && node scripts/assert-root-install.mjs && npm run clean",
- "build": "node scripts/assert-root-install.mjs && node scripts/write-build-stamp.mjs && vite build && node scripts/bundle-electron-main.mjs && node scripts/stage-native-deps.mjs",
+ "prebuild": "node ../../scripts/generate-icons.mjs && node scripts/assert-root-install.mjs",
+ "build": "node scripts/assert-root-install.mjs && node scripts/write-build-stamp.mjs && node scripts/stage-native-deps.mjs && node ../../scripts/build/desktop.mjs --source ../.. --icons ../.. --stamp build/install-stamp.json --native-deps build/native-deps --out dist",
"postbuild": "node scripts/assert-dist-built.mjs",
"prebuilder": "node scripts/patch-electron-builder-mac-binary.mjs",
"builder": "cross-env NODE_OPTIONS=--max-old-space-size=16384 node scripts/run-electron-builder.mjs",
diff --git a/apps/desktop/scripts/after-pack-digests.test.mjs b/apps/desktop/scripts/after-pack-digests.test.mjs
index 7116164286e..f161a662ce6 100644
--- a/apps/desktop/scripts/after-pack-digests.test.mjs
+++ b/apps/desktop/scripts/after-pack-digests.test.mjs
@@ -36,8 +36,10 @@ function fixture() {
}
delete env.PYTHONHOME
delete env.PYTHONPATH
+ // The digest hook only needs the manifest to mark the payload as present.
+ fs.writeFileSync(path.join(payload, 'manifest.json'), '{}')
execFileSync(python, ['-c',
- 'from pathlib import Path; import sys; from scripts.bundles.payload import record_tools, write_manifest; from pm.store import current_target; root=Path(sys.argv[1]); write_manifest(root,target=current_target(),repo="repo"); record_tools(root,Path("pm/lock.json"),current_target(),{"uv":"uv"})',
+ 'from pathlib import Path; import sys; from scripts.bundles.payload import record_tools; from pm.store import current_target; root=Path(sys.argv[1]); record_tools(root,Path("pm/lock.json"),current_target(),{"uv":"uv"})',
payload], { cwd: repo, env, encoding: 'utf8' })
const facts = path.join(payload, 'tools', 'facts.json')
const before = JSON.parse(fs.readFileSync(facts, 'utf8'))
diff --git a/apps/desktop/scripts/bundle-electron-main.mjs b/apps/desktop/scripts/bundle-electron-main.mjs
index 940622115a4..cb8b17f25a6 100644
--- a/apps/desktop/scripts/bundle-electron-main.mjs
+++ b/apps/desktop/scripts/bundle-electron-main.mjs
@@ -1,90 +1,75 @@
#!/usr/bin/env node
-// bundle-electron-main.mjs — bundles electron/main.ts and electron/preload.ts
-// into self-contained js files in dist/ so the packaged app doesn't need
-// node_modules/ or tsx at runtime.
-//
-// Output:
-// dist/electron-main.mjs (MJS bundle — entry point for packaged app)
-// dist/electron-preload.js (CJS bundle — loaded via BrowserWindow preload)
-//
-// `electron` and `node-pty` are external (provided by the runtime / staged
-// separately via stage-native-deps).
-import { build } from 'esbuild'
-import { createRequire } from 'node:module'
-import { resolve, dirname } from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { parseArgs } from 'node:util'
+import { isMain, workspaceTool } from '../../../scripts/build/frontend-common.mjs'
-const require = createRequire(import.meta.url)
+const repoRoot = resolve(import.meta.dirname, '../../..')
-const here = dirname(fileURLToPath(import.meta.url))
-const root = resolve(here, '..')
-const distDir = resolve(root, 'dist')
-mkdirSync(distDir, { recursive: true })
-
-const mainEntry = resolve(root, 'electron/main.ts')
-const mainOut = resolve(distDir, 'electron-main.mjs')
-const preloadEntry = resolve(root, 'electron/preload.ts')
-const preloadOut = resolve(distDir, 'electron-preload.js')
-
-const external = ['electron', 'node-pty', 'get-windows', 'fs']
-// Production bundles bake packaged=true so unpackaged `electron .` still
-// behaves like a packaged build. Dev bundles (`--dev`) leave the env alone
-// so HERMES_DESKTOP_DEV_SERVER / source-tree resolution keep working.
-const isDev = process.argv.includes('--dev')
-
-// The install stamp is baked INTO the bundle: the define below sets the
-// __HERMES_INSTALL_STAMP__ global to the stamp OBJECT literal (the JSON
-// text is a valid JS expression, so no string round-trip). A baked
-// constant cannot be missing, stale, or edited after signing.
-// `npm run build` writes build/install-stamp.json immediately before this
-// script runs, so a missing file here is a broken build, not a thin one.
-// Dev bundles bake nothing — install-stamp.ts's typeof guard yields null,
-// because a dev run has no artifact to be truthful about (a stale stamp
-// from a previous build would lie about provenance).
-function bakedInstallStamp() {
- const raw = readFileSync(resolve(root, 'build/install-stamp.json'), 'utf8')
- JSON.parse(raw) // fail the build on malformed output, not first launch
- return raw
+// Evaluate the one identity module in a fresh process. Its CJS cache and the
+// caller's environment must not carry a previous variant into this artifact.
+function productIdentity(source, stamp) {
+ const variant = stamp.updateMechanism === 'microsoft-store' ? 'store'
+ : stamp.payload === 'bootstrap' ? '' : stamp.payload
+ if (!['', 'bundled', 'light', 'store'].includes(variant)) {
+ throw new Error(`Invalid desktop stamp payload: ${stamp.payload}`)
+ }
+ return execFileSync(process.execPath, ['-e', 'console.log(JSON.stringify(require(process.argv[1])))',
+ join(source, 'apps/desktop/product-identity.cjs')], {
+ env: { ...process.env, HERMES_DESKTOP_VARIANT: variant, HERMES_PAYLOAD_TAG: stamp.tag || '' },
+ encoding: 'utf8',
+ }).trim()
}
-const define = isDev
- ? {}
- : {
- 'process.env.HERMES_DESKTOP_IS_PACKAGED': JSON.stringify(true),
- '__HERMES_INSTALL_STAMP__': bakedInstallStamp(),
- // The product identity (name object, appId, deep-link scheme)
- // baked the same way electron-builder gets it
- '__HERMES_PRODUCT_IDENTITY__': JSON.stringify(require('../product-identity.cjs')),
- }
-
-// Bundle main.ts → dist/electron-main.mjs
-await build({
- entryPoints: [mainEntry],
- bundle: true,
- platform: 'node',
- format: 'esm',
- target: 'node20',
- outfile: mainOut,
- external,
- banner: {
- js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",
- },
- define,
- logLevel: 'info',
-})
-console.log(`bundled ${mainOut}${isDev ? ' (dev)' : ''}`)
+/** Bundle main/preload using only the prepared workspace's compiler. */
+export async function bundleElectronMain({ source, out, stamp, dev = false }) {
+ source = resolve(source)
+ out = resolve(out)
+ const { build } = await import(pathToFileURL(workspaceTool(source, 'apps/desktop', 'esbuild')).href)
+ const define = {}
+ if (!dev) {
+ if (!stamp) throw new Error('A prepared install stamp is required')
+ const raw = readFileSync(stamp, 'utf8')
+ const metadata = JSON.parse(raw)
+ define['process.env.HERMES_DESKTOP_IS_PACKAGED'] = JSON.stringify(true)
+ define.__HERMES_INSTALL_STAMP__ = raw
+ define.__HERMES_PRODUCT_IDENTITY__ = productIdentity(source, metadata)
+ }
+ mkdirSync(out, { recursive: true })
+ const common = {
+ absWorkingDir: join(source, 'apps/desktop'),
+ bundle: true,
+ platform: 'node',
+ target: 'node20',
+ external: ['electron', 'node-pty', 'get-windows', 'fs'],
+ define,
+ logLevel: 'info',
+ }
+ await build({
+ ...common,
+ entryPoints: [join(source, 'apps/desktop/electron/main.ts')],
+ format: 'esm',
+ outfile: join(out, 'electron-main.mjs'),
+ banner: { js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);" },
+ })
+ await build({
+ ...common,
+ entryPoints: [join(source, 'apps/desktop/electron/preload.ts')],
+ format: 'cjs',
+ outfile: join(out, 'electron-preload.js'),
+ })
+}
-// Bundle preload.ts → dist/electron-preload.js
-await build({
- entryPoints: [preloadEntry],
- bundle: true,
- platform: 'node',
- format: 'cjs',
- target: 'node20',
- outfile: preloadOut,
- external,
- define,
- logLevel: 'info',
-})
-console.log(`bundled ${preloadOut}${isDev ? ' (dev)' : ''}`)
+if (isMain(import.meta.url)) {
+ const { values } = parseArgs({ options: {
+ source: { type: 'string', default: repoRoot },
+ out: { type: 'string' }, stamp: { type: 'string' }, dev: { type: 'boolean' },
+ } })
+ await bundleElectronMain({
+ ...values,
+ out: values.out || join(values.source, 'apps/desktop/dist'),
+ stamp: values.stamp || join(values.source, 'apps/desktop/build/install-stamp.json'),
+ })
+}
diff --git a/apps/desktop/scripts/mac-sign.test.mjs b/apps/desktop/scripts/mac-sign.test.mjs
index 49c19191daa..7213f260f6a 100644
--- a/apps/desktop/scripts/mac-sign.test.mjs
+++ b/apps/desktop/scripts/mac-sign.test.mjs
@@ -23,7 +23,7 @@ function fixture() {
const nested = path.join(tools, 'chromium', 'Browser.app')
const binaries = [path.join(app, 'Contents', 'MacOS', 'Hermes'),
path.join(tools, 'python', 'bin', 'python3'),
- path.join(nested, 'Contents', 'MacOS', 'Browser')]
+ path.join(nested, 'Contents', 'MacOS', process.platform === 'win32' ? 'chrome.exe' : 'Chromium')]
for (const binary of binaries) {
fs.mkdirSync(path.dirname(binary), { recursive: true })
const bytes = Buffer.alloc(64)
@@ -41,7 +41,9 @@ function fixture() {
const py = code => childProcess.execFileSync(python, ['-c', code, payload], {
cwd: repo, env, encoding: 'utf8', timeout: 60000
}).trim()
- py('from pathlib import Path; import sys; from scripts.bundles.payload import record_tools,write_manifest; from pm.store import current_target; root=Path(sys.argv[1]); write_manifest(root,target=current_target(),repo="repo"); record_tools(root,Path("pm/lock.json"),current_target(),{"python":"python","chromium":"chromium"})')
+ // The digest hook only needs the manifest to mark the payload as present.
+ fs.writeFileSync(path.join(payload, 'manifest.json'), '{}')
+ py('from pathlib import Path; import sys; from scripts.bundles.payload import record_tools; from pm.store import current_target; root=Path(sys.argv[1]); record_tools(root,Path("pm/lock.json"),current_target(),{"python":"python","chromium":"chromium"})')
const facts = path.join(tools, 'facts.json')
const initial = JSON.parse(fs.readFileSync(facts, 'utf8'))
return { root, app, payload, tools, nested, binaries, ignored, env, py, facts, initial }
diff --git a/apps/desktop/scripts/stage-native-deps.mjs b/apps/desktop/scripts/stage-native-deps.mjs
index 385d031725b..3681325b42c 100644
--- a/apps/desktop/scripts/stage-native-deps.mjs
+++ b/apps/desktop/scripts/stage-native-deps.mjs
@@ -3,7 +3,8 @@
//
// Usage:
// node scripts/stage-native-deps.mjs # host platform/arch
-// node scripts/stage-native-deps.mjs win32 arm64 # explicit target
+// node scripts/stage-native-deps.mjs --platform win32 --arch arm64
+// node scripts/stage-native-deps.mjs --source REPO --out NATIVE_NODE_MODULES
//
// Also exported as `stageNodePty({ platform, arch })` for use from
// before-pack.mjs, where electron-builder gives you the real per-target
@@ -24,6 +25,8 @@ import {
} from 'node:fs'
import { spawnSync } from 'node:child_process'
import { isMain } from './utils.mjs'
+import { parseArgs } from 'node:util'
+import { productOutput, withProduct, workspaceTool } from '../../../scripts/build/frontend-common.mjs'
const here = dirname(fileURLToPath(import.meta.url))
const projectRoot = resolve(here, '..')
@@ -57,9 +60,9 @@ function patchUnixTerminalAsarPaths(destRoot) {
* Locate node-pty's package root via real module resolution, so this
* works whether it's hoisted to a workspace root or local to this app.
*/
-function resolveNodePtyRoot() {
+function resolveNodePtyRoot(appRoot = projectRoot) {
const pkgJsonPath = require.resolve('node-pty/package.json', {
- paths: [projectRoot]
+ paths: [appRoot]
})
return dirname(pkgJsonPath)
}
@@ -237,7 +240,7 @@ function validateStagedBinaries(destRoot, targetPlatform) {
* modules; build on the target platform or provide a prebuild).
* 4. Validate every staged `.node` file's binary platform matches the target.
*/
-export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platform, arch = process.arch } = {}) {
+export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platform, arch = process.arch, appRoot = projectRoot } = {}) {
const hostMatch = platform === process.platform && arch === process.arch
rmSync(destRoot, { recursive: true, force: true })
@@ -314,7 +317,7 @@ export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platfor
`running electron-rebuild (target arch: ${arch})...`
)
const rebuildArgs = [
- '../../node_modules/.bin/electron-rebuild',
+ join(dirname(workspaceTool(resolve(appRoot, '../..'), 'apps/desktop', '@electron/rebuild')), 'cli.js'),
'-f',
'-w',
'node-pty',
@@ -322,7 +325,7 @@ export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platfor
arch
]
const result = spawnSync(process.execPath, rebuildArgs, {
- cwd: projectRoot,
+ cwd: appRoot,
stdio: 'inherit'
})
if (result.status !== 0) {
@@ -343,10 +346,11 @@ export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platfor
return destRoot
}
-export function stageNodePty({ platform = process.platform, arch = process.arch } = {}) {
- const srcRoot = resolveNodePtyRoot()
- const destRoot = resolve(projectRoot, 'dist/node_modules/node-pty')
- return stageNodePtyInto(srcRoot, destRoot, { platform, arch })
+export function stageNodePty({ platform = process.platform, arch = process.arch, source = resolve(projectRoot, '../..'), out = join(source, 'apps/desktop/dist/node_modules') } = {}) {
+ const appRoot = join(source, 'apps/desktop')
+ const srcRoot = resolveNodePtyRoot(appRoot)
+ const destRoot = join(out, 'node-pty')
+ return stageNodePtyInto(srcRoot, destRoot, { platform, arch, appRoot })
}
// ─── get-windows (read_window_below tool) ────────────────────────────
@@ -406,7 +410,7 @@ export function openWindowsSync() {
}
`
-function resolveGetWindowsRoot() {
+function resolveGetWindowsRoot(appRoot = projectRoot) {
// get-windows is an optionalDependency (its node-pre-gyp install script has
// no Linux or Windows ARM64 prebuilt and its node-gyp fallback may fail, so
// `npm ci` can skip it entirely on those targets). Return null when it is
@@ -415,7 +419,7 @@ function resolveGetWindowsRoot() {
// get-windows' exports map doesn't expose ./package.json; resolve the entry
// (index.js sits at the package root) and take its directory.
const entryPath = require.resolve('get-windows', {
- paths: [projectRoot]
+ paths: [appRoot]
})
return dirname(entryPath)
} catch {
@@ -580,11 +584,13 @@ export function stageGetWindows(
{
platform = process.platform,
arch = process.arch,
- resolveRoot = resolveGetWindowsRoot
+ source = resolve(projectRoot, '../..'),
+ out = join(source, 'apps/desktop/dist/node_modules'),
+ resolveRoot = () => resolveGetWindowsRoot(join(source, 'apps/desktop'))
} = {}
) {
const srcRoot = resolveRoot()
- const destRoot = resolve(projectRoot, 'dist/node_modules/get-windows')
+ const destRoot = join(out, 'get-windows')
if (!srcRoot) {
// npm may omit an optional dependency whose install script fails. That is
@@ -615,9 +621,21 @@ export function stageGetWindows(
return stageGetWindowsInto(srcRoot, destRoot, { platform, arch, install })
}
-// Allow direct CLI invocation: node scripts/stage-native-deps.mjs [platform] [arch]
+// Preparation may rebuild/download native bindings. The compiler only consumes
+// the resulting tree, and must never call this preparation function.
+export async function prepareDesktopNativeDependencies({ source, out, platform = process.platform, arch = process.arch }) {
+ ;({ source, out } = productOutput(source, out, ['node_modules', 'apps/desktop/node_modules', 'apps/desktop/src', 'apps/desktop/electron']))
+ await withProduct(out, async product => {
+ stageNodePty({ source, out: product, platform, arch })
+ stageGetWindows({ source, out: product, platform, arch })
+ }, { source })
+ return { out }
+}
+
if (isMain(import.meta.url)) {
- const [platform, arch] = process.argv.slice(2)
- stageNodePty({ platform, arch })
- stageGetWindows({ platform, arch })
+ const { values } = parseArgs({ options: {
+ source: { type: 'string', default: resolve(projectRoot, '../..') },
+ out: { type: 'string' }, platform: { type: 'string', default: process.platform }, arch: { type: 'string', default: process.arch },
+ } })
+ await prepareDesktopNativeDependencies({ ...values, out: values.out || join(values.source, 'apps/desktop/build/native-deps') })
}
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index b6d895f348b..38c98a2668e 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -1,6 +1,6 @@
-import { defineConfig } from 'vite'
import babel from '@rolldown/plugin-babel'
import react, { reactCompilerPreset } from '@vitejs/plugin-react'
+import { defineConfig } from 'vite'
/** React Compiler preset scoped to modules that can actually contain
* components/hooks (JSX syntax or a react-ish import). The preset's default
@@ -10,12 +10,19 @@ import react, { reactCompilerPreset } from '@vitejs/plugin-react'
function compilerPreset() {
const preset = reactCompilerPreset()
preset.rolldown.filter.code = /\/>|<\/|from\s*['"][^'"]*react/
+
return preset
}
-import tailwindcss from '@tailwindcss/vite'
-import path from 'path'
+
import fs from 'fs'
import { createRequire } from 'module'
+import { fileURLToPath } from 'node:url'
+import path from 'path'
+
+import tailwindcss from '@tailwindcss/vite'
+
+// The runner loads this as ESM without the default bundler's CJS globals.
+const __dirname: string = path.dirname(fileURLToPath(import.meta.url))
// `hgui` symlinks a worktree's node_modules to the main checkout. Vite realpaths
// those before enforcing server.fs.allow, so codicon/font assets resolve outside
@@ -80,9 +87,10 @@ const emojibaseAssets = () => ({
}) {
server.middlewares.use('/emojibase', (req, res, next) => {
const rel = (req.url ?? '').split('?')[0].replace(/^\/+/, '')
- if (!emojibaseDir || !EMOJIBASE_PATH.test(rel)) return next()
+
+ if (!emojibaseDir || !EMOJIBASE_PATH.test(rel)) {return next()}
fs.readFile(path.join(emojibaseDir, rel), (err: unknown, buf: Buffer) => {
- if (err) return next()
+ if (err) {return next()}
res.setHeader('Content-Type', 'application/json')
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
res.end(buf)
@@ -90,7 +98,8 @@ const emojibaseAssets = () => ({
})
},
generateBundle(this: { emitFile: (asset: { type: 'asset'; fileName: string; source: Uint8Array }) => void }) {
- if (!emojibaseDir) return
+ if (!emojibaseDir) {return}
+
for (const rel of ['en/data.json', 'en/messages.json', 'en/shortcodes/emojibase.json']) {
this.emitFile({
type: 'asset',
diff --git a/docker/build_agent.py b/docker/build_agent.py
new file mode 100644
index 00000000000..3b0c2572b08
--- /dev/null
+++ b/docker/build_agent.py
@@ -0,0 +1,31 @@
+"""Supply the image's fixed runtime paths to the shared offline assembler."""
+from __future__ import annotations
+
+from pathlib import Path
+import sysconfig
+
+from scripts.build.agent import assemble
+from scripts.build.inputs import AgentInputs, RESOURCE_ENV
+from pm.store import current_target
+
+
+def assemble_image(root: Path) -> None:
+ environment = root / ".venv"
+ site = Path(sysconfig.get_path("purelib", vars={"base": str(environment), "platbase": str(environment)}))
+ manifest = assemble(AgentInputs(
+ project=root / "pyproject.toml", code=root, repo=".", placement="fixed",
+ target=current_target(), python=(environment / "bin/python").absolute(),
+ site_packages=site, environment=environment, tools=root / "tools",
+ pm_runtime=root / "pm-runtime", bin_dir="libexec",
+ resources={name: root / name for name in RESOURCE_ENV},
+ frontends={"tui": root / "ui-tui", "web": root / "hermes_cli/web_dist"},
+ ), root)
+ # Preserve the venv command paths used by s6 and the privilege-drop shim.
+ for name, command in manifest["runtime"]["commands"].items():
+ link = environment / "bin" / name
+ link.unlink(missing_ok=True)
+ link.symlink_to(f"../../{command}")
+
+
+if __name__ == "__main__":
+ assemble_image(Path("/opt/hermes"))
diff --git a/docs/shared-bundle-builds.md b/docs/shared-bundle-builds.md
index 40177b8f850..db2611e7ac0 100644
--- a/docs/shared-bundle-builds.md
+++ b/docs/shared-bundle-builds.md
@@ -1,95 +1,212 @@
# Shared bundle builds
-The build-only Python modules live in `scripts/bundles/`. They use PM for
-package installation and dependency resolution. They do not implement a
-second package manager.
+Hermes separates dependency preparation, product builds, and distribution
+packaging. The compiler and agent-assembly interfaces live in
+[`scripts/build/README.md`](../scripts/build/README.md). These are current
+interfaces, not proof that every distribution passed native acceptance.
-| Module | Responsibility | Consumers |
+## Providers, products, and distributions
+
+| Layer | Responsibility | Implementation |
+|---|---|---|
+| Dependency providers | Prepare tools, Python environments, JavaScript dependencies, and native bindings | PM/uv, `scripts/build/node-deps.mjs`, `scripts/build/python_env.py`, Nix, and Termux |
+| Product builders | Compile icons/TUI/web/desktop UI or assemble a runnable agent from prepared inputs | `scripts/generate_icons.py` and `scripts/build/` |
+| Distribution adapters | Select products and package them for their target | `scripts/bundles/`, `Dockerfile`, `nix/`, and `scripts/termux/` |
+
+Providers retain their package managers and locks. Product builders do not
+install missing dependencies or download inputs. The Node dependency provider
+uses one locked workspace union. Nix supplies its own npm and Python inputs.
+Termux supplies bionic tools and wheels. Shared recipes do not imply identical
+bytes, dependency selections, or Python environments across targets.
+
+| Product | Implementation | Inputs |
|---|---|---|
-| `payload.py` | Git snapshots, manifest/facts, JS output placement, relocation and launcher generation | Native desktop and Termux |
-| `native.py` | Native tool-store staging and dependency venv assembly | `hermes pm bundle`, desktop builder |
-| `desktop.py` | Build the JS surfaces, assemble the payload, invoke Electron packaging | Native release workflow, local builds |
-| `stage.py` | Stage a payload and its launchers without creating an Electron package | `npm run payload` |
-| `mint_launchers.py` | Mint Windows launchers with the payload interpreter's distlib | Shared launcher assembly |
-| `launcher_wrapper.py` | Runtime template for the minted executable | Shared launcher renderer |
+| Icons | `scripts/generate_icons.py` | Artwork and prepared `icon-build` environment |
+| TUI | `scripts/build/tui.mjs` | Prepared TUI workspace |
+| Dashboard | `scripts/build/web.mjs` | Prepared web workspace and generated icons |
+| Desktop UI | `scripts/build/desktop.mjs` | Prepared desktop workspace, icons, stamp, and native bindings |
+| Runnable agent | `scripts/build/agent.py` | Code, interpreter, dependencies, independent PM runtime, resources, and selected frontends |
+
+The desktop UI compiler does not depend on the dashboard. A bundled desktop
+selects an agent with TUI and dashboard products. A light desktop does not
+select an agent payload.
+
+## Build and packaging entrypoints
-Build a desktop bundle from a checkout at its release tag:
+Build a desktop distribution from a checkout at its release tag:
```sh
uv run --no-project --python 3.14 python scripts/bundles/desktop.py --tag=vX.Y.Z
```
-The builder derives console entrypoints from the archived `pyproject.toml`.
-It checks the interpreter, dependency tree, and generated launchers before
-publishing their relative paths in the payload manifest. The desktop build
-bakes this launch contract into its stamp. Electron uses the declared paths
-without payload probes, adoption, or repair. Non-bundled builds carry no
-placeholder payload. The stamp also declares the update mechanism. Store
-packages use `microsoft-store`, and sideload bundles use `app-installer`. The runtime
-has no separate Store probe or compatibility fallback.
-The MSIX hook reads the declared launcher names
-rather than carrying a second entrypoint list. POSIX launchers follow
-links to the installed payload and call each declared function directly.
-Windows launchers are minted by the payload's own Python, preserving native
-architecture and relocation behavior.
-
-Termux uses the same snapshot, manifest/fact writer, JS asset placement and
-POSIX launcher generator. Its package-manager hooks stay in `scripts/termux/`.
-Its bionic wheel compilation and offline installation remain target-specific:
-a glibc host cannot execute the shipped interpreter, and Termux has a fixed
-installation prefix. Native desktop staging instead resolves on the target OS.
-Neither path compiles dependencies on the user's machine.
-
-Electron-specific work stays with Electron: renderer/main-process bundling,
-Node native bindings, MSIX metadata, signing, notarization and app packaging.
-The after-pack hook invokes the shared Python relocation command instead of
-maintaining its own link rewrite algorithm.
-
-Ordinary bundle staging does not scan user plugin trees. Runtime plugin
-admission is a separate PM transaction. Build output cleanup is confined to
-its payload store; it must not prune the machine-wide downloader partials.
-
-## Target boundaries
-
-Desktop stages on the target OS and architecture. Its dependency step uses
-`uv sync --frozen --all-extras --active` on the staged interpreter.
-The complete desktop builder, not `pm bundle` alone, adds prebuilt JS surfaces
-and invokes Electron packaging.
-
-Termux's host scripts run on Linux ARM64. `build_cpython.sh` and `build_node.sh`
-stage pinned bionic packages; `stage_runtime_libs.py` supplies their native
-library closure. `termux_build.sh` exports the tag's core plus `acp` requirements,
-builds the required native wheels in the pinned bionic container, and records
-wheelhouse inputs. `build_deb.sh` assembles the environment offline, creates the
-APT package, and validates it in a fresh container without network access.
-Those container checks do not substitute for Android device acceptance.
-
-The installed Termux root is `$PREFIX/lib/hermes-agent/`. It contains `app`,
-`tools`, `runtime-libs`, `venv`, `bin`, and the PM manifest/facts. Maintainer
-hooks manage only the package's CLI symlinks under `$PREFIX/bin` and refuse
-foreign launcher conflicts. They do not compile dependencies on install.
+`desktop.py` requires exactly one of `--tag` or `--commit`. Commit builds
+require the full commit SHA and matching checkout HEAD. `--variant` accepts
+`bundled`, `store`, or `light`, with `bundled` as the default. `--repo` selects
+the checkout. Arguments after `--` go to Electron Builder.
+
+The driver prepares Node dependencies, builds the selected products, and runs
+Electron packaging. The desktop npm build prepares its stamp and native tree
+before the shared desktop compiler. Electron-specific dependency compilation,
+MSIX metadata, signing, notarization, and package formats remain adapter work.
+
+Stage a native agent with both frontend products, without Electron packaging:
+
+```sh
+python -m scripts.bundles.stage --out /work/agent-payload --ref HEAD
+```
+
+This command prepares and builds TUI/web products if none are supplied. It
+also accepts `--tui` and `--web` together as prepared product roots. It rejects
+a selection with only one of those arguments. The standalone products have
+explicit input/output contracts in the builder README.
+
+`--ref` selects the agent source snapshot. Automatic frontend compilation uses
+a temporary snapshot of that same revision. Explicit frontend products must
+come from the selected revision.
+
+`hermes pm bundle --out /work/agent-payload --ref HEAD` stages native tools,
+the application environment, and the agent. That PM command does not build
+frontends. `npm run payload --workspace apps/desktop` uses the stage driver
+that includes them. Neither command creates an Electron installer.
+
+For Termux, tools and the wheelhouse are prerequisites:
+
+```sh
+python scripts/termux/build.py --repo /work/source --payload /work/termux-payload \
+ --out /work/packages --tag vX.Y.Z
+```
+
+The Termux driver accepts exactly one of `--tag` or `--commit`. It prepares
+the TUI workspace, calls the shared TUI builder, and passes that product to
+`build_deb.sh`. It does not add the dashboard or replace bionic preparation.
+
+The CLI contracts are in `scripts/bundles/desktop.py:129–143`,
+`scripts/bundles/stage.py:17–46`, `pm/cli.py:442–444,488–491`, and
+`scripts/termux/build.py:21–62`.
+
+## Shared agent and launcher contract
+
+`AgentInputs` supplies explicit paths and a placement mode:
+
+- `contained` keeps runtime inputs inside the native payload.
+- `fixed` retains the Docker or Termux installation prefix.
+- `references` keeps installed code and dependencies in separate Nix store paths.
+
+The assembler derives console commands from `[project.scripts]`. It copies
+source-layout resources and selected frontends, or links explicit reference
+inputs. It writes the completion manifest after structural assembly. Nix also
+receives a command/environment map for its native wrappers.
+
+The launcher implementation lives in `scripts/build/launchers.py`.
+`launcher_wrapper.py` and `mint_launchers.py` live in that same directory.
+`scripts/bundles/payload.py` owns git snapshots, PM tool facts, PM runtime
+sealing, and portable link handling. It no longer owns frontend placement or
+launcher generation.
+
+The desktop stamp carries the declared launch paths. Electron consumes that
+contract without payload adoption or repair. Non-bundled builds carry no
+placeholder agent payload. Store packages declare `microsoft-store` as their
+update mechanism. Sideload bundles declare `app-installer`.
+
+Windows launcher minting runs the payload interpreter. POSIX launchers use
+explicit interpreter, source, and dependency paths. Structural assembly does
+not replace target-native launch tests. A manifest alone does not prove that
+a relocated or signed artifact runs.
+
+## Independent PM runtime
+
+PM dependencies come from `pm/pyproject.toml` and `pm/uv.lock`, not the
+application dependency graph. The application environment and `pm-runtime`
+are separate inputs to agent assembly.
+
+Native and Docker preparation use `pm.runtime_stage.stage_runtime`. Termux
+uses that function with its offline wheelhouse. Nix uses the independent
+`nix/pm-runtime.nix` derivation. Native sealing records the payload interpreter
+and PM-only site directory in `pm-runtime.json`.
+
+Resident PM workers run the declared interpreter with `-I -S -B`. They add
+only the declared PM dependency directory before the worker script. They do
+not borrow application dependencies or add PM packages to the caller's
+interpreter. Docker and Nix stamps point to their declared PM runtime.
+These contracts live in `pm/runtime.py:55–88,171–182` and
+`scripts/bundles/payload.py:58–90`.
+
+Ordinary native staging does not scan user plugin trees. It runs provisioning
+in a child with build-owned home, cache, and PM roots. Live PM retains plugin
+admission, generation selection, and transaction state. Both paths use
+`pm.environment.PythonEnvironment` for explicit uv environment construction.
+
+## Distribution boundaries and output paths
+
+| Distribution | Selected products | Current output layout |
+|---|---|---|
+| Desktop bundled/Store | Icons, TUI, web, agent, desktop UI | Products: `apps/desktop/build/products/`. Agent: `apps/desktop/build/agent-payload/`. UI: `apps/desktop/dist/`. Packages: `apps/desktop/release/` |
+| Desktop light | Icons and desktop UI | `apps/desktop/dist/` and `apps/desktop/release/`, without an agent payload |
+| Docker | Icons, TUI, web, agent | Agent at `/opt/hermes`, dependencies at `.venv`, PM at `pm-runtime`, generated commands at `libexec` |
+| Nix TUI | TUI | `$out/lib/hermes-tui/{dist/entry.js,package.json}` |
+| Nix web | Web | `$out/index.html` and assets |
+| Nix agent | Agent with TUI/web references | `$out/bin`, `$out/share/hermes-agent`, `$out/ui-tui`, `manifest.json`, and `command-map.json` |
+| Nix desktop | Icons and desktop UI, with the Nix agent | `$out/share/hermes-desktop` and `$out/bin/hermes-desktop` |
+| Termux | TUI and agent | `OUT/hermes-agent_<version>_aarch64.deb`, installed at `$PREFIX/lib/hermes-agent/` |
+
+Native payloads contain `hermes-agent`, `tools`, `venv`, `pm-runtime`, `bin`,
+`uv-cache`, and their manifests/facts. Copied frontend assets live at
+`hermes-agent/hermes_cli/tui_dist/` and `hermes-agent/hermes_cli/web_dist/`.
+The TUI asset directory contains `entry.js` and module-mode package metadata.
+
+Docker keeps its existing TUI product at `/opt/hermes/ui-tui` and web output
+at `/opt/hermes/hermes_cli/web_dist`. The assembler also plants its shared TUI
+asset layout beneath `hermes_cli/tui_dist`. Venv command symlinks preserve the
+paths used by s6 and the privilege-drop shim.
+
+The Docker frontend stage owns npm dependencies and compilation. The runtime
+stage copies only the frontend products and the locked TypeScript package for
+runtime linting. Node/npm and Photon's separately installed sidecar dependencies
+remain runtime inputs. Python dependency preparation precedes the application
+source copy. Actual cache-hit and layer-size claims require build evidence.
+
+Nix retains `importNpmLock`, uv2nix, platform overrides, and store references.
+Its builders run during derivation builds, not evaluation. Per-product source
+filters keep frontend, Python, and resource inputs separate. Nix wrappers
+consume the assembler's command map and retain their PATH and extra-Python
+collision policies.
+
+**Nix wheel policy:** `nix/python.nix:128–135` sets `HERMES_NIX_BUILD=1` only
+for the Hermes derivation. `setup.py:34–72` rejects general Hermes wheel/sdist
+builds. The shared assembler uses the installed Nix code without another copy.
+Other providers use source-layout code and metadata, not a public Hermes wheel.
+
+Termux retains bionic wheel compilation, offline installation, native library
+paths, and its fixed prefix. Its installed root contains `app`, `tools`,
+`runtime-libs`, `venv`, `pm-runtime`, `bin`, and manifests/facts. APT maintainer
+hooks manage the declared CLI symlinks under `$PREFIX/bin` and refuse foreign
+conflicts. They do not compile dependencies during installation.
`stage_apt_repo.py` owns repository metadata and signatures. Stable and canary
-suites are `hermes-stable` and `hermes-canary`; package files publish before
-signed metadata. Runtime and repository pins are distinct from the native
-build-toolchain packages used only inside CI.
-
-Docker and Nix consume PM pins but do not run this desktop payload assembly.
-Docker has its own curated extras and image lifecycle. Nix uses uv2nix and
-separate derivations. [Stable release admission](stable-releases.md) coordinates
-their acceptance and publication with desktop and Termux packages.
-
-PM and Docker ship full Chromium, without a separate headless shell. The same
-executable serves headed and headless sessions. Browser launchers use the
-selected PM executable; direct Playwright callers select the `chromium` channel.
-Native staging removes retired package facts and directories from its build
-cache. It does not remove browser files from the user's machine-wide store.
-
-PM retains completed download archives until the package is verified and
-published. Normal installs commit package facts before deleting their archives.
-Cross-target staging verifies the published entry before deleting its archives.
-Failed or paused installs keep downloads for retry. Cleanup leaves unrelated
-archives and resumable partials alone. A later repair may download again.
+suites are `hermes-stable` and `hermes-canary`. Package files publish before
+signed metadata. [Stable release admission](stable-releases.md) coordinates
+acceptance and publication across distributions.
+
+## Cache ownership
+
+PM binary download archives and the native uv wheel cache have different
+consumers. They are not interchangeable cleanup targets.
+
+- PM retains completed downloads until package verification and publication.
+ Successful installs remove their exact fetch archives. Failures retain
+ downloads for retry. Cleanup leaves unrelated partials alone.
+- Native staging prunes obsolete entries only in its build-owned tool store.
+ It does not prune the user's machine-wide store.
+- Native staging retains `uv-cache/` for offline mutable-environment rebuilds.
+ It keeps extracted wheel entries but removes wheel ZIPs beneath `sdists-v*`
+ so native signing can reach the extracted binaries.
+- Icon preparation uses its own `SOURCE/.cache/icon-build`. Its build-only
+ dependencies do not belong in the native application cache.
+- Frontend `node_modules` is a provider input, not a frontend product.
+ Docker's runtime TypeScript and Photon selections are separate exceptions.
+
+The native cache behavior is in `scripts/bundles/native.py:55–65,202–216`.
+Removing all caches from a payload can break offline environment reconstruction.
## Pinned binary inputs
@@ -127,8 +244,21 @@ Electron/SDK archives independently downloaded by their build tools.
## Verification boundary
-Tests execute shared snapshot/manifest helpers on real git fixtures, stage
-real subprocesses and venvs at controlled boundaries, and mint/run Windows
-launchers after relocation. POSIX launcher and symlink tests run on POSIX.
-A local helper test is not proof of a signed installer, bionic wheel build,
-or stable-release upgrade. The release workflows own those native receipts.
+The checks below distinguish product tests from distribution acceptance.
+Signed installers and Android device execution require their native runners.
+
+Focused helper tests cannot establish all of these requirements:
+
+- Offline frontend compilation from prepared immutable inputs.
+- Standalone TUI interaction and dashboard backend/assets behavior.
+- Native Electron bindings and final signed launchers on each target.
+- PM isolation after native payload relocation.
+- Retained-cache offline reconstruction of a mutable application environment.
+- Docker non-root CLI/TUI/web/browser behavior and every image layer's contents.
+- Actual Nix package execution through reference-based wrappers.
+- Fresh network-disabled Termux package installation and Android device behavior.
+
+Use the existing acceptance checks in `tests/install/BUNDLED_UPDATES.md`,
+`tests/docker/`, Nix checks, and `scripts/termux/check_deb.sh` plus
+`validate_installed.py`. Container acceptance does not substitute for Android
+device acceptance. No build-pass claim follows from this document.
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.py
index 66885a2e659..392ecaa85ac 100644
--- a/hermes_cli/main_tui_launch.py
+++ b/hermes_cli/main_tui_launch.py
@@ -278,7 +278,8 @@ _TUI_BUILD_INPUT_FILES = (
"tsconfig.json",
"tsconfig.build.json",
"babel.compiler.config.cjs",
- "scripts/build.mjs",
+ "../scripts/build/tui.mjs",
+ "../scripts/build/frontend-common.mjs",
"packages/hermes-ink/package.json",
"packages/hermes-ink/index.js",
"packages/hermes-ink/text-input.js",
diff --git a/nix/checks.nix b/nix/checks.nix
index a4d3c6d71fd..4478f912e3a 100644
--- a/nix/checks.nix
+++ b/nix/checks.nix
@@ -991,17 +991,12 @@ json.dump(sorted(leaf_paths(DEFAULT_CONFIG)), sys.stdout, indent=2)
echo "ok" > $out/result
'';
- # Verify every pyproject.toml [project.scripts] entry has a wrapped binary
+ # Exercise every declared command and the environment delivered by
+ # makeWrapper, plus the shared assembler's store-reference contract.
entry-points-sync = pkgs.runCommand "hermes-entry-points-sync" { } ''
- set -e
- echo "=== Checking entry points match pyproject.toml [project.scripts] ==="
- for bin in hermes hermes-agent hermes-acp; do
- test -x ${hermes-agent}/bin/$bin || (echo "FAIL: $bin binary missing from Nix package"; exit 1)
- echo "PASS: $bin present"
- done
-
+ ${hermes-agent.python}/bin/python3 ${./tests/agent-references.py} \
+ ${hermes-agent} ${../pyproject.toml} ${hermes-agent.agentInputsFile}
mkdir -p $out
- echo "ok" > $out/result
'';
# Verify CLI subcommands are accessible
diff --git a/nix/desktop.nix b/nix/desktop.nix
index 3353138ee4f..7ee1bd97ec3 100644
--- a/nix/desktop.nix
+++ b/nix/desktop.nix
@@ -70,6 +70,8 @@ let
dirs = [
"apps/desktop"
"apps/shared"
+ "scripts/build/desktop.mjs"
+ "scripts/build/frontend-common.mjs"
];
pname = "hermes-desktop-renderer";
@@ -78,44 +80,30 @@ let
buildPhase = ''
runHook preBuild
- mkdir -p apps/desktop/build
- cp ${installStampFile} apps/desktop/build/install-stamp.json
- cp -r ${generatedIcons}/apps/desktop/public/. apps/desktop/public/
-
patchShebangs .
- pushd apps/desktop
- # typecheck :3
- npm exec -- tsc -b
-
- # build the renderer bundle
- # vite's emptyOutDir wipes dist/ on every run
- # so it has to be first
- npm exec -- vite build
-
- # build the electron bundle
- node scripts/bundle-electron-main.mjs
-
- # Compile node-pty against Electron's actual ABI (the nixpkgs
- # `electron` we ship). Headers come from a pinned fetchurl input
- # since the sandbox has no network here, so node-gyp's
- # normal --disturl download path can't run.
- mkdir -p "$TMPDIR/electron-headers"
- tar -xzf ${electronHeaders} -C "$TMPDIR/electron-headers" --strip-components=1
-
- ${lib.getExe hermesNpmLib.node-gyp} rebuild \
- --directory=../../node_modules/node-pty \
- --build-from-source \
- --runtime=electron \
- --target=${electron.version} \
- --nodedir="$TMPDIR/electron-headers" \
- --disturl="" \
- --offline
-
- # Target platform/arch come from stdenv.hostPlatform, not the
- # build host's own process.platform/arch.
- node scripts/stage-native-deps.mjs ${targetPlatform} ${targetArch}
- popd
+ # The native provider runs before compilation. Use the headers for
+ # the exact Electron runtime shipped by this derivation, offline.
+ mkdir -p "$TMPDIR/electron-headers"
+ tar -xzf ${electronHeaders} -C "$TMPDIR/electron-headers" --strip-components=1
+ ${lib.getExe hermesNpmLib.node-gyp} rebuild \
+ --directory=node_modules/node-pty \
+ --build-from-source \
+ --runtime=electron \
+ --target=${electron.version} \
+ --arch=${targetArch} \
+ --nodedir="$TMPDIR/electron-headers" \
+ --disturl="" \
+ --offline
+
+ node apps/desktop/scripts/stage-native-deps.mjs \
+ --source "$PWD" --out "$TMPDIR/desktop-native-deps" \
+ --platform ${targetPlatform} --arch ${targetArch}
+ node scripts/build/desktop.mjs \
+ --source "$PWD" --out "$PWD/apps/desktop/dist" \
+ --icons ${generatedIcons} --stamp ${installStampFile} \
+ --native-deps "$TMPDIR/desktop-native-deps" \
+ --platform ${targetPlatform} --typecheck
runHook postBuild
'';
@@ -144,11 +132,7 @@ let
installPhase = ''
runHook preInstall
mkdir -p $out
- # vite writes to apps/desktop/dist/ (we cd'd there in buildPhase).
- # stage-native-deps.mjs stages node-pty into dist/node_modules/node-pty,
- # so copying dist/ wholesale carries the native dep along with the
- # esbuild bundle that require()s it. apps/desktop/build was created
- # before the cd.
+ # The shared product contains renderer, main/preload, and native deps.
cp -rn apps/desktop/dist $out/
cp ${installStampFile} $out/install-stamp.json
diff --git a/nix/hermes-agent.nix b/nix/hermes-agent.nix
index 032af002404..898e11fc064 100644
--- a/nix/hermes-agent.nix
+++ b/nix/hermes-agent.nix
@@ -171,6 +171,50 @@ let
sitePackagesPath = python.sitePackages;
+ # Only the offline assembler's import closure. A frontend or catalog edit
+ # must not change this source, and no build output is read during evaluation.
+ agentBuilderSrc = lib.fileset.toSource {
+ root = ./..;
+ fileset = lib.fileset.unions [
+ ../scripts/build/agent.py
+ ../scripts/build/inputs.py
+ ../scripts/build/launchers.py
+ ];
+ };
+
+ agentInputsFile = writeText "hermes-agent-inputs.json" (builtins.toJSON {
+ project = "${../pyproject.toml}";
+ code = "${hermesVenv}/${sitePackagesPath}";
+ repo = "share/hermes-agent";
+ placement = "references";
+ target = "${if stdenv.hostPlatform.isDarwin then "darwin" else "linux"}-${
+ if stdenv.hostPlatform.isAarch64 then "arm64" else "x64"
+ }";
+ python = "${hermesVenv}/bin/python3";
+ site_packages = "${hermesVenv}/${sitePackagesPath}";
+ environment = toString hermesVenv;
+ pm_runtime = toString pmRuntime;
+ command_dir = "${hermesVenv}/bin";
+ resources = {
+ skills = toString bundledSkills;
+ optional-skills = toString bundledOptionalSkills;
+ plugins = toString bundledPlugins;
+ locales = toString bundledLocales;
+ optional-mcps = toString bundledOptionalMcps;
+ };
+ frontends = {
+ tui = "${hermesTui}/lib/hermes-tui";
+ web = toString hermesWeb;
+ };
+ ref = if dirty then null else rev;
+ stamp = toString installStampFile;
+ env = {
+ HERMES_NODE = lib.getExe hermesNpmLib.nodejs;
+ } // lib.optionalAttrs (rev != null && !dirty) {
+ HERMES_REVISION = rev;
+ };
+ });
+
# Walk propagatedBuildInputs to include transitive Python deps in PYTHONPATH.
# Without this, a plugin listing e.g. requests as a dep would fail at runtime
# if requests isn't already in the sealed uv2nix venv.
@@ -229,56 +273,34 @@ stdenv.mkDerivation (finalAttrs: {
installPhase = ''
runHook preInstall
- # Symlinks, not copies: these are all store paths already, and the
- # wrapper env vars just hold paths. Symlinking keeps this derivation
- # near-instant when only the venv changed, with an identical closure.
- mkdir -p $out/share/hermes-agent $out/bin
- ln -s ${bundledSkills} $out/share/hermes-agent/skills
- ln -s ${bundledOptionalSkills} $out/share/hermes-agent/optional-skills
- ln -s ${bundledPlugins} $out/share/hermes-agent/plugins
- ln -s ${bundledLocales} $out/share/hermes-agent/locales
- ln -s ${bundledOptionalMcps} $out/share/hermes-agent/optional-mcps
- ln -s ${hermesWeb} $out/share/hermes-agent/web_dist
- ln -s ${hermesTui}/lib/hermes-tui $out/ui-tui
-
- cp ${installStampFile} $out/share/hermes-agent/install-stamp.json
-
- ${lib.concatMapStringsSep "\n"
- (name: ''
- makeWrapper ${hermesVenv}/bin/${name} $out/bin/${name} \
- --suffix PATH : "${runtimePath}" \
- --set HERMES_BUNDLED_SKILLS $out/share/hermes-agent/skills \
- --set HERMES_OPTIONAL_SKILLS $out/share/hermes-agent/optional-skills \
- --set HERMES_BUNDLED_PLUGINS $out/share/hermes-agent/plugins \
- --set HERMES_BUNDLED_LOCALES $out/share/hermes-agent/locales \
- --set HERMES_OPTIONAL_MCPS $out/share/hermes-agent/optional-mcps \
- --set HERMES_WEB_DIST $out/share/hermes-agent/web_dist \
- --set HERMES_TUI_DIR $out/ui-tui \
- --set-default HERMES_BIN $out/bin/hermes \
- --set HERMES_PYTHON ${hermesVenv}/bin/python3 \
- --set HERMES_NODE ${lib.getExe hermesNpmLib.nodejs} \
- --set HERMES_INSTALL_ROOT $out/share/hermes-agent${
- # Fold the line continuation INTO the optionalString: a bare
- # `\` on the line above an empty expansion would dangle onto a
- # blank line, ending the makeWrapper command early and running
- # the next flag as its own shell command (`--suffix: command
- # not found`). Only reproduces when rev == null (dirty trees).
- # Only embed clean revs — a dirtyRev-derived rev is the parent
- # of uncommitted work, and the banner's update check would
- # compare against upstream as if the tree were at that commit.
- lib.optionalString (rev != null && !dirty) " \\\n --set HERMES_REVISION ${rev}"
- }${
- lib.optionalString (
- extraPythonPackages != [ ]
- ) " \\\n --suffix PYTHONPATH : \"${pythonPath}\""
- }
- '')
- [
- "hermes"
- "hermes-agent"
- "hermes-acp"
- ]
+ # uv2nix owns Python code and dependencies. The shared assembler only
+ # links resources and emits the derived command/environment description.
+ PYTHONPATH=${agentBuilderSrc} ${python}/bin/python3 -m scripts.build.agent \
+ --inputs ${agentInputsFile} --out "$out"
+
+ # Native wrappers retain Nix's PATH/PYTHONPATH policies. Names, executable
+ # sources and resource bindings come from the builder, not another table.
+ makeAgentWrapper() {
+ local source="$1" destination="$2"
+ shift 2
+ makeWrapper "$source" "$out/$destination" "$@" \
+ --suffix PATH : "${runtimePath}" \
+ --set-default HERMES_BIN "$out/bin/hermes"${
+ lib.optionalString (extraPythonPackages != [ ])
+ " \\\n --suffix PYTHONPATH : \"${pythonPath}\""
+ }
}
+ ${python}/bin/python3 - "$out/command-map.json" > "$TMPDIR/agent-wrappers.sh" <<'PY'
+ import json, shlex, sys
+
+ with open(sys.argv[1]) as handle:
+ description = json.load(handle)
+ env = [arg for key, value in sorted(description["env"].items())
+ for arg in ("--set", key, value)]
+ for command in description["commands"].values():
+ print(shlex.join(["makeAgentWrapper", command["source"], command["destination"], *env]))
+ PY
+ source "$TMPDIR/agent-wrappers.sh"
${lib.optionalString (extraPythonPackages != [ ]) ''
echo "=== Checking for plugin/core package collisions ==="
@@ -299,6 +321,8 @@ stdenv.mkDerivation (finalAttrs: {
hermesWeb
hermesNpmLib
hermesVenv
+ agentBuilderSrc
+ agentInputsFile
installStampFile
pmRuntime
python
diff --git a/nix/icons.nix b/nix/icons.nix
index e57c203824e..90f9e5cfe20 100644
--- a/nix/icons.nix
+++ b/nix/icons.nix
@@ -10,11 +10,6 @@ let
};
in
runCommand "hermes-icons" { nativeBuildInputs = [ iconBuildVenv ]; } ''
- cp -r ${src} source
- chmod -R u+w source
- cd source
- python scripts/generate_icons.py
- python scripts/generate_icons.py --check
- mkdir -p $out
- cp -r apps web website $out/
+ python ${src}/scripts/generate_icons.py --source ${src} --out $out
+ python ${src}/scripts/generate_icons.py --source ${src} --out $out --check
''
diff --git a/nix/lib.nix b/nix/lib.nix
index 67ee92e8e0e..45f08a9bef1 100644
--- a/nix/lib.nix
+++ b/nix/lib.nix
@@ -174,6 +174,9 @@ let
in
if relPath == "" then
true
+ else if lib.hasPrefix "scripts/build/" relPath && lib.hasSuffix ".mjs" relPath then
+ # Frontend recipes belong to their product source filters, not Python.
+ false
else if builtins.elem relPath excludedFiles then
false
else if builtins.elem topComponent excludedDirs then
diff --git a/nix/tests/agent-references.py b/nix/tests/agent-references.py
new file mode 100644
index 00000000000..1e42993dae6
--- /dev/null
+++ b/nix/tests/agent-references.py
@@ -0,0 +1,74 @@
+"""Check the shipped Nix agent, not a reconstruction of its assembly recipe."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import tomllib
+
+
+package, project, inputs_file = map(Path, sys.argv[1:])
+inputs = json.loads(inputs_file.read_text())
+entries = tomllib.loads(project.read_text())["project"]["scripts"]
+command_map = json.loads((package / "command-map.json").read_text())
+assert command_map["commands"].keys() == entries.keys()
+assert {p.name for p in (package / "bin").iterdir()} == entries.keys()
+
+repo = package / inputs["repo"]
+for name, source in inputs["resources"].items():
+ resource = repo / name
+ assert resource.is_symlink(), resource
+ assert resource.samefile(source), (resource, source)
+for name, key in (("tui", "HERMES_TUI_DIR"), ("web", "HERMES_WEB_DIST")):
+ resource = Path(command_map["env"][key])
+ assert resource.is_symlink(), resource
+ assert resource.samefile(inputs["frontends"][name])
+assert not (repo / "run_agent.py").exists(), "installed Python code must not be copied"
+assert not list(repo.glob("*.dist-info")), "Nix keeps the uv2nix wheel's metadata"
+assert command_map["env"]["HERMES_PYTHON"] == inputs["python"]
+assert command_map["env"]["HERMES_INSTALL_ROOT"] == str(repo)
+stamp = json.loads((repo / "install-stamp.json").read_text())
+assert stamp["pmRuntime"] == inputs["pm_runtime"]
+assert (Path(inputs["pm_runtime"]) / "pm-runtime.json").is_file()
+
+# Observe the environment the *actual wrapper* hands Python and import its
+# declared entrypoint, without starting an LLM session. The legacy run_agent
+# entrypoint does not parse --help and swallows initialization errors, so its
+# exit status alone is not an import check. No parsing makeWrapper's shell text.
+with tempfile.TemporaryDirectory() as temporary:
+ home = Path(temporary)
+ probe = home / "probe"
+ probe.mkdir()
+ (probe / "sitecustomize.py").write_text(
+ "import importlib, json, os\n"
+ "observed = dict(os.environ)\n"
+ "module, function = os.environ['NIX_CHECK_ENTRY'].split(':')\n"
+ "assert callable(getattr(importlib.import_module(module), function))\n"
+ "print(json.dumps(observed), flush=True)\n"
+ "os._exit(0)\n"
+ )
+ env = {"HOME": str(home), "HERMES_HOME": str(home / ".hermes"),
+ "PATH": os.defpath, "LANG": "C.UTF-8", "TZ": "UTC"}
+ for name, entry in entries.items():
+ command = command_map["commands"][name]
+ assert command["entry"] == entry
+ assert Path(command["source"]).samefile(Path(inputs["command_dir"]) / name)
+ executable = package / command["destination"]
+ assert os.access(executable, os.X_OK), executable
+ result = subprocess.run([str(executable), "--help"], cwd=home,
+ env={**env, "PYTHONPATH": str(probe), "NIX_CHECK_ENTRY": entry},
+ text=True, capture_output=True, check=True, timeout=60)
+ observed = json.loads(result.stdout)
+ for key, value in command_map["env"].items():
+ assert observed[key] == value, (name, key, observed.get(key), value)
+ assert observed["HERMES_BIN"] == str(package / "bin/hermes")
+ print(f"PASS: {name} imports from a clean cwd and receives the shared environment")
+
+ # These public interfaces parse --help without starting an agent session.
+ for name in ("hermes", "hermes-acp"):
+ subprocess.run([str(package / "bin" / name), "--help"], cwd=home, env=env,
+ check=True, timeout=60, stdout=subprocess.DEVNULL)
+ print(f"PASS: {name} --help")
+
+print("PASS: referenced resources, independent PM runtime, and uv2nix code placement")
diff --git a/nix/tui.nix b/nix/tui.nix
index b94814228a3..4bb665c46ee 100644
--- a/nix/tui.nix
+++ b/nix/tui.nix
@@ -1,29 +1,25 @@
-# nix/tui.nix — Hermes TUI (Ink/React) compiled with tsc and bundled
+# Self-contained Hermes TUI, compiled by the same recipe as npm.
{ hermesNpmLib, ... }:
hermesNpmLib.buildNpmPackage {
dirs = [
"ui-tui"
"apps/shared"
+ "scripts/build/tui.mjs"
+ "scripts/build/frontend-common.mjs"
];
doCheck = false;
buildPhase = ''
- # esbuild bundles everything — no need for tsc or vite.
- # Run from the workspace root where node_modules/ lives.
- node ui-tui/scripts/build.mjs
+ runHook preBuild
+ node scripts/build/tui.mjs --source "$PWD" --out "$TMPDIR/tui-product"
+ runHook postBuild
'';
installPhase = ''
runHook preInstall
-
mkdir -p $out/lib/hermes-tui
- # esbuild writes to ui-tui/dist/ from the source root (no cd).
- cp -r ui-tui/dist $out/lib/hermes-tui/dist
-
- # package.json kept for "type": "module" resolution on `node dist/entry.js`.
- cp ui-tui/package.json $out/lib/hermes-tui/
-
+ cp -r "$TMPDIR/tui-product/." $out/lib/hermes-tui/
runHook postInstall
'';
}
diff --git a/nix/web.nix b/nix/web.nix
index 14520295b68..ec8ac0eda9f 100644
--- a/nix/web.nix
+++ b/nix/web.nix
@@ -1,34 +1,25 @@
-# nix/web.nix — Hermes Web Dashboard (Vite/React) frontend build
+# Dashboard compilation consumes prepared icons; no npm lifecycle preparation.
{ hermesNpmLib, generatedIcons, ... }:
hermesNpmLib.buildNpmPackage {
dirs = [
"web"
-
- # @hermes/shared ships as a file: workspace dep of web, so its source
- # must be in the filtered src tree too.
"apps/shared"
+ "scripts/build/web.mjs"
+ "scripts/build/frontend-common.mjs"
];
doCheck = false;
buildPhase = ''
- cp -r ${generatedIcons}/web/public/. web/public/
- # Build from web/ so vite.config.ts and tsconfig resolve correctly.
- # The workspace root's node_modules/ is at ../node_modules/.
- cd web
- node ../node_modules/typescript/bin/tsc -b
- # outDir in vite.config.ts points to ../hermes_cli/web_dist for the
- # monorepo layout. Override with --outDir dist for the nix build.
- node ../node_modules/vite/bin/vite.js build --outDir dist
-
- # Return to source root so installPhase paths are correct.
- cd ..
+ runHook preBuild
+ node scripts/build/web.mjs --source "$PWD" --icons ${generatedIcons} --out "$TMPDIR/web-product"
+ runHook postBuild
'';
installPhase = ''
runHook preInstall
- # vite writes to web/dist/ (we cd'd there, overrode outDir, then cd'd back).
- cp -r web/dist $out
+ mkdir -p $out
+ cp -r "$TMPDIR/web-product/." $out/
runHook postInstall
'';
}
diff --git a/pm/environment.py b/pm/environment.py
new file mode 100644
index 00000000000..5f0b38085b5
--- /dev/null
+++ b/pm/environment.py
@@ -0,0 +1,152 @@
+"""Explicit uv construction, independent of PM tool discovery and live selection.
+
+Callers own the destination, source/workspace, cache and publication lifecycle.
+This module neither discovers profiles nor modifies the process environment.
+"""
+from __future__ import annotations
+
+import codecs
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+import io
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+from typing import TextIO
+
+from pm.package import InstallError
+
+
+def _run_streaming(command: list[str], *, cwd: Path, env: dict[str, str],
+ timeout: int, output: TextIO) -> subprocess.CompletedProcess:
+ """Keep CI progress live, a bounded diagnostic tail, and a wall-clock timeout."""
+ deadline = time.monotonic() + timeout
+ proc = subprocess.Popen(command, cwd=str(cwd), env=env, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, text=True, errors="replace", bufsize=0)
+ pipe = proc.stdout
+ assert isinstance(pipe, io.TextIOWrapper) # Popen was given stdout=PIPE and text=True.
+ tail = ""
+ try:
+ # A descendant can keep stdout open after proc exits. Nonblocking reads
+ # bound that drain without leaving a thread stuck in readline()/close().
+ # PM's Python >=3.14 supports nonblocking pipes on Windows as well as POSIX.
+ os.set_blocking(pipe.fileno(), False)
+ decoder = io.IncrementalNewlineDecoder(
+ codecs.getincrementaldecoder(pipe.encoding)(errors="replace"), translate=True,
+ )
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise subprocess.TimeoutExpired(command, timeout, stderr=tail)
+ try:
+ data = os.read(pipe.fileno(), 65536)
+ except BlockingIOError:
+ time.sleep(min(.05, remaining))
+ continue
+ text = decoder.decode(data, final=not data)
+ if text:
+ tail = (tail + text)[-2000:]
+ output.write(text)
+ output.flush()
+ if not data:
+ break
+ # EOF can precede process exit; it does not grant another timeout budget.
+ try:
+ code = proc.wait(timeout=max(0, deadline - time.monotonic()))
+ except subprocess.TimeoutExpired:
+ raise subprocess.TimeoutExpired(command, timeout, stderr=tail) from None
+ except BaseException:
+ proc.kill()
+ proc.wait(timeout=5)
+ raise
+ finally:
+ pipe.close()
+ return subprocess.CompletedProcess(command, code, "", tail)
+
+
+@dataclass(frozen=True, kw_only=True)
+class PythonEnvironment:
+ uv: Path
+ python: Path
+ destination: Path
+ cache: Path
+ env: Mapping[str, str]
+ offline: bool = False
+ output: TextIO | None = None
+
+ @property
+ def executable(self) -> Path:
+ return self.destination / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+
+ def _run(self, args: list[str], *, cwd: Path, timeout: int) -> subprocess.CompletedProcess:
+ # The caller supplies policy (PM already sanitizes it via pm.ensure.uv).
+ # Preserve intentional index credentials/settings; only explicit routing
+ # inputs and project-config visibility override this child environment.
+ env = {key: value for key, value in self.env.items() if key not in (
+ "VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE",
+ "UV_WORKING_DIR", "UV_PROJECT", "UV_CONFIG_FILE", "UV_NO_CONFIG",
+ "UV_MANAGED_PYTHON", "UV_NO_MANAGED_PYTHON", "UV_SYSTEM_PYTHON",
+ )}
+ env.update(UV_PYTHON=str(self.python), UV_PROJECT_ENVIRONMENT=str(self.destination),
+ UV_CACHE_DIR=str(self.cache), UV_PYTHON_DOWNLOADS="never")
+ with tempfile.TemporaryDirectory(prefix="pm-uv-config-") as config:
+ env.update(XDG_CONFIG_HOME=config, XDG_CONFIG_DIRS=config)
+ command = [str(self.uv), *args]
+ if self.offline:
+ command.append("--offline")
+ if self.output is not None:
+ return _run_streaming(command, cwd=cwd, env=env, timeout=timeout, output=self.output)
+ return subprocess.run(command, cwd=str(cwd), env=env, capture_output=True,
+ text=True, timeout=timeout)
+
+ def create(self) -> None:
+ """Create at the final destination; callers must not move a live venv."""
+ self.destination.parent.mkdir(parents=True, exist_ok=True)
+ result = self._run(
+ ["venv", "--relocatable", "--no-project", "--no-config",
+ "--python", str(self.python), str(self.destination)],
+ cwd=self.destination.parent, timeout=120,
+ )
+ if result.returncode:
+ raise InstallError("venv", f"uv venv failed: {result.stderr[-600:]}")
+
+ def sync(self, source: Path, *, extras: Sequence[str] = (), frozen: bool = True,
+ all_extras: bool = False, no_install_project: bool = False) -> None:
+ """Install the root and every member; resolve only in a writable workspace.
+
+ ``frozen=False`` is reserved for the caller-owned generated workspace,
+ never the original project's lock. Seed/replay policy belongs to PM.
+ """
+ from pm.workspace import classify_uv_failure
+
+ if not frozen:
+ locked = self._run(["lock", "--python", str(self.python)], cwd=source, timeout=1800)
+ if locked.returncode:
+ raise classify_uv_failure("lock", locked.returncode, locked.stderr or locked.stdout)
+ # Locking members alone is insufficient: plain sync only installs root deps.
+ command = ["sync", "--frozen", "--all-packages", "--python", str(self.python)]
+ if all_extras:
+ command.append("--all-extras")
+ if no_install_project:
+ # --all-packages has no single selected project in uv, so
+ # --no-install-project alone does not exclude the root. Name it
+ # explicitly without dropping member dependencies or installations.
+ import tomllib
+
+ project = tomllib.loads((source / "pyproject.toml").read_text(encoding="utf-8-sig"))
+ command += ["--no-install-project", "--no-install-package", project["project"]["name"]]
+ for extra in sorted(set(extras)):
+ command += ["--extra", extra]
+ result = self._run(command, cwd=source, timeout=1800)
+ if result.returncode:
+ raise classify_uv_failure("sync", result.returncode, result.stderr or result.stdout)
+
+ def check(self) -> None:
+ result = self._run(
+ ["pip", "check", "--no-config", "--python", str(self.executable)],
+ cwd=self.destination.parent, timeout=60,
+ )
+ if result.returncode:
+ raise InstallError("venv", f"dependency validation failed: {result.stderr[-600:]}")
diff --git a/pm/packages.py b/pm/packages.py
index d1e9906bebc..1f9e39fe06d 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -443,6 +443,7 @@ class Venv(StatePackage):
import uuid
from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path
from pm.ensure import uv as pm_uv
+ from pm.environment import PythonEnvironment
from pm.lock import Facts
from pm.workspace import enabled_member_dirs, lock_and_sync
@@ -452,18 +453,16 @@ class Venv(StatePackage):
uv_bin, env = pm_uv(explicit=repair)
if uv_bin is None:
raise InstallError(self.name, "uv is not installed")
- env["UV_PROJECT_ENVIRONMENT"] = str(candidate)
- env.pop("UV_NO_CONFIG", None) # project indexes/sources belong to the project
+ environment = PythonEnvironment(
+ uv=Path(uv_bin), python=Path(env["UV_PYTHON"]), destination=candidate,
+ cache=Path(env["UV_CACHE_DIR"]), env=env,
+ offline=env.get("UV_OFFLINE") == "1",
+ )
members = [] if repair else (enabled_member_dirs() if plugin_dirs is None else plugin_dirs)
try:
generation.mkdir(parents=True)
(generation / ".lease-managed").touch()
- create = subprocess.run(
- [uv_bin, "venv", "--relocatable", str(candidate)],
- env=env, capture_output=True, text=True, timeout=120,
- )
- if create.returncode:
- raise InstallError(self.name, f"uv venv failed: {create.stderr[-600:]}")
+ environment.create()
prior = Facts(runtime_facts_path(project), strict=repair).get("venv") or {}
replay = None
if repair and ("environment" in prior or "resolved_lock" in prior):
@@ -479,18 +478,13 @@ class Venv(StatePackage):
seed = (Path(prior["resolved_lock"]) if members and prior.get("resolved_lock")
else project / "uv.lock")
lock_and_sync(members, extras, venv_dir=candidate, root=generation / "workspace",
- seed_lock=seed, frozen=repair or not members, env=env, replay=replay)
+ seed_lock=seed, frozen=repair or not members, replay=replay,
+ source=project, environment=environment)
resolved_lock = generation / "workspace" / "uv.lock"
- python = candidate / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
- checked = subprocess.run(
- [uv_bin, "pip", "check", "--python", str(python)],
- env=env, capture_output=True, text=True, timeout=60,
- )
- if checked.returncode:
- raise InstallError(self.name, f"dependency validation failed: {checked.stderr[-600:]}")
+ environment.check()
if repair:
from pm.recovery import validate_environment
- validate_environment(python, env=env, cwd=resolved_lock.parent)
+ validate_environment(environment.executable, env=env, cwd=resolved_lock.parent)
except BaseException:
shutil.rmtree(generation, ignore_errors=True)
raise
diff --git a/pm/workspace.py b/pm/workspace.py
index 1f0f321592a..1eea62221ee 100644
--- a/pm/workspace.py
+++ b/pm/workspace.py
@@ -11,7 +11,10 @@ import os
import subprocess
from collections.abc import Mapping
from pathlib import Path
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
+
+if TYPE_CHECKING:
+ from pm.environment import PythonEnvironment
from pm import paths
from pm.package import InstallError
@@ -141,7 +144,8 @@ def _copy_core_inputs(source: Path, destination: Path) -> None:
shutil.copy2(entry, target)
-def _generate_pyproject(plugin_dirs: list[Path], root: Optional[Path] = None) -> tuple[Path, bool]:
+def _generate_pyproject(plugin_dirs: list[Path], root: Optional[Path] = None, *,
+ source: Optional[Path] = None) -> tuple[Path, bool]:
"""(Re)generate the workspace root's pyproject.toml from core's
pyproject + the enabled plugin members. Idempotent — same inputs,
same bytes. Returns (root, changed): changed is True when the member
@@ -149,12 +153,12 @@ def _generate_pyproject(plugin_dirs: list[Path], root: Optional[Path] = None) ->
the signal to re-seed the resolution from the committed lock."""
if root is None:
root = workspace_root()
- source = paths.repo_root().resolve()
+ source = (paths.repo_root() if source is None else source).resolve()
if root.resolve() == source or source.is_relative_to(root.resolve()):
raise InstallError("venv", "workspace must not replace the core source")
root.mkdir(parents=True, exist_ok=True)
- core_pyproject = paths.repo_root() / "pyproject.toml"
+ core_pyproject = source / "pyproject.toml"
core_text = core_pyproject.read_text(encoding="utf-8-sig")
members = [_member_rel(root, _workspace_member(source, root, identity=identity))
@@ -172,7 +176,7 @@ def _generate_pyproject(plugin_dirs: list[Path], root: Optional[Path] = None) ->
changed = target.read_text(encoding="utf-8") != text
except OSError:
changed = True
- _copy_core_inputs(paths.repo_root(), root)
+ _copy_core_inputs(source, root)
target.write_text(text, encoding="utf-8")
return root, changed
@@ -185,7 +189,7 @@ def build_root(plugin_dirs: list[Path], root: Optional[Path] = None) -> Path:
return generated
-def _seed_lock(root: Path, seed_lock: Optional[Path] = None) -> None:
+def _seed_lock(root: Path, seed_lock: Optional[Path] = None, *, source: Optional[Path] = None) -> None:
"""Seed the generated root's uv.lock with the CURRENT resolution.
Seed precedence: the parent-supplied ``seed_lock`` path first, then
@@ -206,7 +210,7 @@ def _seed_lock(root: Path, seed_lock: Optional[Path] = None) -> None:
if existing.is_file():
seed_lock = existing
else:
- seed_lock = paths.repo_root() / "uv.lock"
+ seed_lock = (paths.repo_root() if source is None else source) / "uv.lock"
if not seed_lock.is_file():
return # nothing committed to seed from; uv resolves from scratch
(root / "uv.lock").write_bytes(seed_lock.read_bytes())
@@ -424,6 +428,8 @@ def lock_and_sync(
seed_lock: Optional[Path] = None,
frozen: bool = False,
replay: Optional[Path] = None,
+ source: Optional[Path] = None,
+ environment: PythonEnvironment | None = None,
) -> None:
"""Build the root, then `uv lock` + `uv sync --frozen --extra ...`.
@@ -436,18 +442,21 @@ def lock_and_sync(
gets a COPY — the live process environment is never mutated. ``replay``
copies a recorded sibling workspace and uses its lock without resolution
or plugin discovery; it is reserved for restoring an existing selection.
+ ``source`` and ``environment`` bypass live source/tool discovery when supplied;
+ the environment owns the child process policy, cache and interpreter.
Raises a CLASSIFIED InstallError on failure: ResolutionConflict only
for a confirmed resolver conflict; network, build and tool failures
stay generic InstallError — they are not evidence of a dependency
conflict and must not disable plugins.
"""
- from pm.ensure import uv as pm_uv
+ if environment is not None and environment.destination != venv_dir:
+ raise ValueError("workspace and environment destinations differ")
if replay is None:
- generated, changed = _generate_pyproject(plugin_dirs, root)
+ generated, changed = _generate_pyproject(plugin_dirs, root, source=source)
if changed:
- _seed_lock(generated, seed_lock)
+ _seed_lock(generated, seed_lock, source=source)
else:
import shutil
@@ -459,35 +468,16 @@ def lock_and_sync(
generated = root
frozen = True
- uv_bin, run_env = pm_uv(base_env=env)
- if uv_bin is None:
- raise InstallError("venv", "PM's uv and Python are required; run `hermes pm install`")
- run_env.pop("UV_NO_CONFIG", None)
- run_env["UV_PROJECT_ENVIRONMENT"] = str(venv_dir)
-
- import subprocess
-
- if not frozen:
- lock = subprocess.run(
- [uv_bin, "lock"], cwd=str(generated), env=run_env, capture_output=True, text=True, timeout=1800
- )
- if lock.returncode != 0:
- raise classify_uv_failure("lock", lock.returncode, lock.stderr or lock.stdout)
-
- # --all-packages is REQUIRED: plain `uv sync --frozen` installs only the
- # ROOT project's deps — workspace-member deps are locked by `uv lock`
- # but silently never reach site-packages (probed live 2026-09-03: a
- # member's pyfiglet stayed absent from site-packages under plain
- # --frozen, present under --all-packages). The union's whole contract
- # is that plugin deps ride the venv; without this flag every member
- # install is a silent no-op.
- cmd = [uv_bin, "sync", "--frozen", "--all-packages"]
- for extra in sorted(set(extras or [])):
- cmd += ["--extra", extra]
- sync = subprocess.run(cmd, cwd=str(generated), env=run_env, capture_output=True, text=True, timeout=1800)
- if sync.returncode != 0:
- # --frozen means the lock already resolved; a sync failure here is
- # install/download/tooling, never a NEW resolution conflict.
- raise classify_uv_failure(
- "sync", sync.returncode, sync.stderr or sync.stdout
+ if environment is None:
+ from pm.ensure import uv as pm_uv
+ from pm.environment import PythonEnvironment
+
+ uv_bin, run_env = pm_uv(base_env=env)
+ if uv_bin is None:
+ raise InstallError("venv", "PM's uv and Python are required; run `hermes pm install`")
+ environment = PythonEnvironment(
+ uv=Path(uv_bin), python=Path(run_env["UV_PYTHON"]), destination=venv_dir,
+ cache=Path(run_env["UV_CACHE_DIR"]), env=run_env,
+ offline=run_env.get("UV_OFFLINE") == "1",
)
+ environment.sync(generated, extras=extras or (), frozen=frozen)
diff --git a/pyproject.toml b/pyproject.toml
index e64e5cb002b..74ce74344d8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -655,7 +655,7 @@ youtube-transcript-api = false
# and the drift broke installed wheels. Do not add the list back.
[tool.setuptools.packages.find]
-include = ["agent", "agent.*", "tools", "tools.*", "hermes_cli", "hermes_cli.*", "gateway", "gateway.*", "tui_gateway", "tui_gateway.*", "cron", "cron.*", "acp_adapter", "plugins", "plugins.*", "providers", "providers.*", "pm", "pm.*"]
+include = ["agent", "agent.*", "tools", "tools.*", "hermes_cli", "hermes_cli.*", "hermes_wisdom", "hermes_wisdom.*", "gateway", "gateway.*", "tui_gateway", "tui_gateway.*", "cron", "cron.*", "acp_adapter", "plugins", "plugins.*", "providers", "providers.*", "pm", "pm.*"]
[tool.setuptools.package-data]
hermes_cli = ["observability/schemas/*.json", "data/*.json", "local_runtime/*.json"]
diff --git a/scripts/build/README.md b/scripts/build/README.md
new file mode 100644
index 00000000000..4cbf9b8fd09
--- /dev/null
+++ b/scripts/build/README.md
@@ -0,0 +1,296 @@
+# Shared product builders
+
+These modules compile frontends and assemble a runnable agent from prepared
+inputs. They do not replace npm, uv, PM, or Nix.
+[Shared bundle builds](../../docs/shared-bundle-builds.md) describes the
+providers and distribution adapters.
+
+This reference describes the current interfaces, not completed artifact
+acceptance. A successful parser or helper test does not prove a distribution
+build or a target-native runtime.
+
+## Ownership
+
+| Layer | Owns | Examples |
+|---|---|---|
+| Dependency provider | Tools, locked dependencies, native libraries and build environments | `node-deps.mjs`, `python_env.py`, PM, Nix `importNpmLock`/uv2nix, Termux wheelhouse |
+| Product builder | Compilation or application assembly from prepared inputs | `tui.mjs`, `web.mjs`, `desktop.mjs`, `agent.py`, `../generate_icons.py` |
+| Distribution adapter | Product selection, target preparation, package layout, signing and publication | `../bundles/`, `../../Dockerfile`, `../../nix/`, `../termux/` |
+
+`node-deps.mjs` and `python_env.py` prepare dependencies. Unlike the product
+builders, they can access package registries. There is no universal installer,
+all-products dispatcher, or cross-platform Python environment.
+
+## Prepared JavaScript workspace
+
+Run commands from the repository root. Replace the absolute example paths with
+build-owned paths.
+
+```sh
+node scripts/build/node-deps.mjs --source /work/source \
+ --workspace ui-tui --workspace web
+```
+
+`--source` and at least one `--workspace` are required. A workspace can be its
+locked path or package name. The provider deduplicates the selection and runs
+one root `npm ci` operation. It includes root dependencies, development
+dependencies, and optional dependencies. It checks Node/npm against the root
+`engines` declarations. npm lifecycle scripts remain enabled.
+
+The prepared source needs these inputs:
+
+- Root `package.json` and `package-lock.json`.
+- Selected workspace manifests and their required `file:` dependency sources.
+- Source files and configuration for the selected product.
+- Resolved dependencies in workspace-local or root `node_modules`.
+
+Request the complete workspace union once. A later, narrower `npm ci` can
+remove dependencies that another product needs. This provider modifies the
+prepared workspace. It does not build a frontend or publish a completion stamp.
+Nix supplies dependencies through `importNpmLock` instead of this command.
+
+## Frontend products
+
+```sh
+node scripts/build/tui.mjs --source /work/source --out /work/products/tui
+node scripts/build/web.mjs --source /work/source \
+ --icons /work/products/icons --out /work/products/web
+node scripts/build/desktop.mjs --source /work/source \
+ --icons /work/products/icons --stamp /work/install-stamp.json \
+ --native-deps /work/native-deps --out /work/products/desktop
+```
+
+| Builder | Required CLI arguments | Additional CLI arguments | Product contents |
+|---|---|---|---|
+| `tui.mjs` | `--source`, `--out` | None | `dist/entry.js` and `package.json` with `type: module` |
+| `web.mjs` | `--source`, `--out`, `--icons` | None | `index.html`, Vite assets, and public assets |
+| `desktop.mjs` | `--source`, `--out`, `--icons`, `--stamp`, `--native-deps` | `--typecheck`, `--platform` | Renderer assets, `electron-main.mjs`, `electron-preload.js`, and native `node_modules` |
+
+Each output is the product directory itself. The desktop output is a `dist`
+directory, not an application package. The exported functions are `buildTui`,
+`buildWeb`, and `buildDesktop`. They return output paths, not a new provenance
+manifest.
+
+The compilers resolve modules from the supplied workspace. They do not run
+npm, uv, PM installation, or icon preparation. TypeScript/Vite scratch files
+stay outside source inputs. Compilation uses a private output directory next
+to the destination. A successful compile replaces the destination. A failed
+compile leaves the previous product in place and reports failure. Its presence
+alone does not prove that the latest build succeeded.
+
+Existing arbitrary output directories require the builder's `.hermes-product`
+marker. Files, symlinks, and source directories are rejected. The exact npm
+destinations (`ui-tui/dist`, `hermes_cli/web_dist`, `apps/desktop/dist`, and
+`apps/desktop/build/native-deps`) remain rebuildable without a prior marker.
+Other in-tree products live beneath `.build/` or `apps/desktop/build/products/`.
+
+### Icons and native inputs
+
+`--icons` names the generator's output root, not a directory of loose icons.
+The web builder reads `web/public/` beneath it and requires `favicon.ico`.
+The desktop builder reads `apps/desktop/public/` beneath it and requires
+`apple-touch-icon.png`.
+
+Run the generator with a prepared `icon-build` Python environment:
+
+```sh
+python scripts/generate_icons.py --source /work/source --out /work/products/icons
+python scripts/generate_icons.py --source /work/source --out /work/products/icons --check
+```
+
+The generator reads artwork from `SOURCE/assets` and writes its declared paths
+beneath `OUT`. These paths also include desktop packaging, website, and
+bootstrap-installer assets. `--check` regenerates targets in memory and checks
+output image properties. It does not compare output bytes with regenerated bytes.
+The generator writes targets directly, not through the frontend
+publication helper.
+
+The convenience wrapper prepares the locked environment and can access the
+network:
+
+```sh
+node scripts/generate-icons.mjs --source /work/source --out /work/products/icons
+```
+
+It uses the isolated `icon-build` dependency group and
+`SOURCE/.cache/icon-build`. Both icon commands accept `--check`. Without
+explicit paths, they use the source checkout as the output root.
+
+The desktop native tree contains prepared packages, including `node-pty` with
+its compiled binding. macOS also requires `get-windows/main`. The provider owns
+the architecture and Electron ABI match. `--platform` defaults to the running
+Node platform and controls native-file checks. It does not cross-compile a
+binding. `--typecheck` enables the desktop renderer TypeScript check and defaults
+to false. The web builder always runs its TypeScript project check.
+
+The supplied install stamp controls the desktop main/preload build identity.
+The compiler does not create an install stamp, build the dashboard, package
+Electron, or sign native files.
+
+### Source-development entrypoints
+
+Existing npm commands use these recipes:
+
+```sh
+npm run build --workspace ui-tui
+npm run build --workspace web
+npm run build --workspace apps/desktop
+```
+
+| Command | Output | Preparation outside the product compiler |
+|---|---|---|
+| TUI build | `ui-tui/dist/entry.js` | Existing installed workspace dependencies |
+| Web build | `hermes_cli/web_dist/` | npm `prebuild` prepares icons |
+| Desktop build | `apps/desktop/dist/` | Icons, root-install assertion, install stamp, and native-dependency staging |
+
+TUI and web scripts support a no-argument development mode. Explicit product
+mode requires the arguments in the earlier table. The desktop product script
+has no no-argument mode. The Node product parsers expose no `--help` flag.
+
+## Python dependency provider
+
+```sh
+python -m scripts.build.python_env --source /work/source \
+ --python /work/tools/python --uv /work/tools/uv --out /work/venv \
+ --extra all --extra messaging
+```
+
+| Argument | Contract |
+|---|---|
+| `--source`, `--python`, `--uv`, `--out` | Required prepared source, interpreter, uv executable, and fresh environment destination |
+| `--cache` | Optional cache directory. Default: `OUT.parent/.uv-cache` |
+| `--extra` | Repeatable extra selection |
+| `--all-extras` | Select all extras instead of `--extra` |
+| `--no-install-project` | Exclude the root application install, but retain workspace-member installation |
+| `--offline` | Prohibit uv network access. Required artifacts must already be available |
+
+`OUT` must not exist. Failure removes this invocation's environment, not a
+pre-existing environment. Success prints its Python executable. The Python
+function `build_python_environment` additionally requires an explicit `env`
+mapping. It returns the same executable as a `Path`.
+
+The provider uses `pm.environment.PythonEnvironment` for environment creation,
+frozen workspace sync, and dependency checks. It preserves project uv policy,
+uses the supplied interpreter, and disables interpreter downloads. It does not
+discover user plugins or publish a live PM selection. Nix and Termux retain
+separate dependency providers. The uv cache remains available after this call.
+
+## Runnable agent assembly
+
+```sh
+python -m scripts.build.agent --inputs /work/agent-inputs.json --out /work/agent
+```
+
+The only builder arguments are `--inputs` and `--out`. Python entrypoints also
+accept argparse's `-h`/`--help`. The library interface is
+`assemble(AgentInputs(...), out)`. The input JSON rejects unknown fields.
+
+### Input fields
+
+All supplied filesystem input paths must be absolute and exist. `repo` and
+`bin_dir` are output-relative names, not filesystem inputs.
+
+| Field | Required | Meaning |
+|---|---|---|
+| `project` | Yes | `pyproject.toml` with static project metadata and `[project.scripts]` |
+| `code` | Yes | Prepared source tree, or installed code root for reference placement |
+| `repo` | Yes | Code/resource location beneath `OUT`, such as `hermes-agent`, `.`, or `share/hermes-agent` |
+| `placement` | Yes | `contained`, `fixed`, or `references` |
+| `target` | Yes | `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `win32-x64`, `win32-arm64`, or `linux-arm64-bionic` |
+| `python` | Yes | Prepared target interpreter file |
+| `site_packages` | Yes | Prepared application dependency directory |
+| `environment` | Yes | Prepared application environment root |
+| `pm_runtime` | Yes | Independent PM runtime directory with `pm-runtime.json` |
+| `bin_dir` | No | One output-relative directory name. Default: `bin` |
+| `tools` | No | Prepared runtime tool directory. The manifest defaults to `tools` if omitted |
+| `command_dir` | For `references` | Directory of prepared commands declared by the project |
+| `resources` | No | Resource-name to directory mapping |
+| `frontends` | No | `tui` and/or `web` product paths |
+| `ref` | No | Source identity copied to the completion manifest |
+| `stamp` | No | Prepared install stamp copied to `OUT/repo/install-stamp.json` |
+| `features` | No | Prepared feature inventory copied to `OUT/enabled-features.json` |
+| `env` | No | Additional environment values in the reference-placement command map |
+
+Recognized resource names are `skills`, `optional-skills`, `plugins`, `locales`,
+and `optional-mcps`. Distribution adapters supply the required resources.
+The generic assembler does not infer a missing resource mapping. TUI inputs
+require `dist/entry.js` and `package.json`. Web inputs require `index.html`.
+
+The PM marker supplies `python` and `sitePackages` paths relative to its runtime
+directory, or absolute store references. These paths must resolve to real
+inputs. If a supplied stamp declares `nix` or `docker`, its `pmRuntime` must
+match the supplied PM runtime. The assembler does not create that environment.
+
+### Placement and output
+
+- **`contained`:** The provider prepares the interpreter, dependencies, PM
+ runtime, and tools inside `OUT`. Assembly copies source/resources, plants
+ frontends, and calls the portable link helper.
+- **`fixed`:** The provider owns final-prefix preparation. Assembly copies or
+ reuses source/resources and generates launchers without portable relocation.
+ Docker and Termux use this placement.
+- **`references`:** Assembly references installed code and commands without
+ copying Python code or replacing wheel metadata. It links explicit resources
+ and frontends, then emits `command-map.json`. Nix creates its native wrappers
+ from this map.
+
+Source-layout placement writes project distribution metadata without building
+a Hermes wheel. It also writes `site_packages/hermes-agent.pth` with a relative
+code path. Source-layout placement therefore requires an output-owned dependency
+directory, including in `fixed` mode. Reference placement does not write this file.
+
+Commands derive from `[project.scripts]`, not a second command
+list. POSIX launchers use the supplied runtime paths. Windows launcher minting
+runs the target interpreter and therefore needs a runnable native environment.
+A target label alone does not prove ABI compatibility.
+
+For copied frontends, the assembler places TUI files at
+`OUT/repo/hermes_cli/tui_dist/` and web files at
+`OUT/repo/hermes_cli/web_dist/`. Reference placement links TUI at `OUT/ui-tui`
+and web at `OUT/repo/web_dist` and records their environment bindings.
+
+After structural assembly, `manifest.json` records `schema`, `target`, `repo`,
+`venv`, `store`, `launchers`, and `runtime`, plus `ref` when supplied. Its
+`runtime` contains `repoDir`, `toolsDir`, `storePython`, `sitePackages`, and
+`commands`. Reference placement also emits command sources, destinations,
+entrypoints, and environment values in `command-map.json`.
+
+Agent assembly modifies its output in place. It removes old completion records
+before work and writes the manifest last. This is not the frontend builder's
+atomic-directory publication contract. A failed assembly can leave partial
+files. The manifest is not evidence of a target-native launch or signed-package
+acceptance.
+
+## Implementation references
+
+These locations define the interfaces described here:
+
+| Contract | Source |
+|---|---|
+| Frontend arguments and publication | `frontend-common.mjs:31–79` |
+| TUI product and development output | `tui.mjs:25–103` |
+| Web inputs and TypeScript check | `web.mjs:8–71` |
+| Desktop inputs and native checks | `desktop.mjs:11–69` |
+| Locked workspace union | `node-deps.mjs:31–68` |
+| Python provider | `python_env.py:21–76`, `../../pm/environment.py:50–133` |
+| Agent input fields and checks | `inputs.py:30–115` |
+| Agent assembly and outputs | `agent.py:76–168` |
+| Launcher implementation | `launchers.py`, `launcher_wrapper.py`, `mint_launchers.py` |
+
+## Verification still required
+
+Parser checks and source inspection establish the documented call shapes.
+They do not establish offline compilation, cache reuse, or runtime success.
+Artifact acceptance still needs these checks:
+
+- Real frontend builds from immutable prepared inputs without network access.
+- Standalone TUI interaction and dashboard assets/backend behavior.
+- Native Electron bindings under the packaged Electron version.
+- Agent CLI, ACP, plugins, and catalogs from an unrelated working directory.
+- Native payload relocation and offline mutable-environment reconstruction.
+- Docker runtime probes as its non-root user and layer-content inspection.
+- Actual Nix builds and commands through store-reference wrappers.
+- Fresh network-disabled bionic installation and Android device acceptance.
+
+Docker/Nix build execution belongs to the distribution verification work, not
+this documentation pass. No build-pass claim follows from this reference.
diff --git a/scripts/build/agent.py b/scripts/build/agent.py
new file mode 100644
index 00000000000..427dfff6ff4
--- /dev/null
+++ b/scripts/build/agent.py
@@ -0,0 +1,168 @@
+"""Assemble a runnable agent from prepared inputs, without downloads or live state."""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import tomllib
+
+from scripts.build.inputs import AgentInputs, RESOURCE_ENV, project_entries, validate_frontends
+from scripts.build.launchers import write_launchers
+
+
+def _copy(source: Path, destination: Path, *, replace: bool = False) -> None:
+ if source.resolve() == destination.resolve():
+ return
+ if destination.resolve().is_relative_to(source.resolve()) or source.resolve().is_relative_to(destination.resolve()):
+ raise ValueError(f"output must not be inside copied input: {source}")
+ if replace and destination.exists():
+ shutil.rmtree(destination)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ if source.is_dir():
+ shutil.copytree(source, destination, symlinks=True, dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns("__pycache__", ".git"))
+ else:
+ shutil.copy2(source, destination)
+
+
+def plant_surfaces(repo: Path, frontends: dict[str, Path]) -> None:
+ """Only explicit built products are accepted; no hunting in the source tree."""
+ validate_frontends(frontends)
+ if "tui" in frontends:
+ tui = frontends["tui"]
+ destination = repo / "hermes_cli/tui_dist"
+ _copy(tui / "dist", destination, replace=True)
+ _copy(tui / "package.json", destination / "package.json")
+ if "web" in frontends:
+ _copy(frontends["web"], repo / "hermes_cli/web_dist", replace=True)
+
+
+def write_metadata(project_path: Path, repo: Path) -> None:
+ """Source-layout installs have no wheel; preserve PEP 621 dependency metadata.
+
+ This attaches the project's static declarations, not installed-environment
+ guesses. Nix keeps the real wheel's dist-info untouched.
+ """
+ project = tomllib.loads(project_path.read_text(encoding="utf-8-sig"))["project"]
+ if project.get("dynamic"):
+ raise ValueError("agent assembly requires static project metadata")
+ dist = re.sub(r"[-_.]+", "_", project["name"])
+ info = repo / f"{dist}-{project['version']}.dist-info"
+ info.mkdir(parents=True, exist_ok=True)
+ lines = ["Metadata-Version: 2.3", f"Name: {project['name']}", f"Version: {project['version']}"]
+ for key, header in (("description", "Summary"), ("requires-python", "Requires-Python")):
+ if key in project:
+ lines.append(f"{header}: {project[key]}")
+ lines.extend(f"Requires-Dist: {req}" for req in project.get("dependencies", []))
+ for extra, requirements in project.get("optional-dependencies", {}).items():
+ extra = re.sub(r"[-_.]+", "-", extra).lower()
+ lines.append(f"Provides-Extra: {extra}")
+ for req in requirements:
+ requirement, _, marker = req.partition(";")
+ condition = f"({marker.strip()}) and " if marker else ""
+ lines.append(f"Requires-Dist: {requirement.strip()}; {condition}extra == '{extra}'")
+ (info / "METADATA").write_text("\n".join(lines) + "\n", encoding="utf-8")
+ groups = {**project.get("entry-points", {}), "console_scripts": project_entries(project_path)}
+ if project.get("gui-scripts"):
+ groups["gui_scripts"] = project["gui-scripts"]
+ text = "\n".join(f"[{group}]\n" + "\n".join(f"{name} = {entry}" for name, entry in values.items())
+ for group, values in groups.items())
+ (info / "entry_points.txt").write_text(text + "\n", encoding="utf-8")
+
+
+def assemble(inputs: AgentInputs, out: Path) -> dict:
+ out = out.absolute()
+ out.mkdir(parents=True, exist_ok=True)
+ # An interrupted rebuild must not leave an old completion claim behind.
+ manifest_path = out / "manifest.json"
+ previous = json.loads(manifest_path.read_text(encoding="utf-8-sig")) if manifest_path.is_file() else {}
+ manifest_path.unlink(missing_ok=True)
+ (out / "command-map.json").unlink(missing_ok=True)
+ inputs.validate(out)
+ entries = project_entries(inputs.project)
+ repo = out / inputs.repo
+ referenced = inputs.placement == "references"
+ repo.mkdir(parents=True, exist_ok=True)
+ if not referenced:
+ if inputs.code.resolve() != repo.resolve():
+ if repo == out:
+ raise ValueError("root-level code must be prepared in place")
+ _copy(inputs.code, repo, replace=True)
+ for name, source in inputs.resources.items():
+ _copy(source, repo / name, replace=True)
+ plant_surfaces(repo, inputs.frontends)
+ write_metadata(inputs.project, repo)
+ # Arbitrary scripts run with the prepared environment's Python too
+ # (Docker's config migration, plugins), not only generated launchers.
+ if not inputs.site_packages.resolve().is_relative_to(out):
+ raise ValueError("source binding requires an output-owned dependency directory")
+ relative_code = Path(os.path.relpath(repo, inputs.site_packages)).as_posix()
+ (inputs.site_packages / "hermes-agent.pth").write_text(relative_code + "\n", encoding="utf-8")
+ for source, destination in ((inputs.stamp, repo / "install-stamp.json"),
+ (inputs.features, out / "enabled-features.json")):
+ if source is not None:
+ _copy(source, destination)
+ if inputs.placement == "contained":
+ from scripts.bundles.payload import relativize_links
+ relativize_links(out)
+ def location(path: Path) -> str:
+ return path.relative_to(out).as_posix() if path.is_relative_to(out) and not referenced else str(path)
+
+ python, site = location(inputs.python), location(inputs.site_packages)
+ tools = location(inputs.tools) if inputs.tools else "tools"
+ if referenced:
+ commands = {name: str(inputs.command_dir / name) for name in entries}
+ for command in commands.values():
+ if not Path(command).is_file():
+ raise FileNotFoundError(f"prepared command missing: {command}")
+ env = {**inputs.env, "HERMES_PYTHON": str(inputs.python), "HERMES_INSTALL_ROOT": str(repo)}
+ links = {RESOURCE_ENV[name]: (path, repo / name) for name, path in inputs.resources.items()}
+ for name, path in inputs.frontends.items():
+ key, destination = {"tui": ("HERMES_TUI_DIR", out / "ui-tui"),
+ "web": ("HERMES_WEB_DIST", repo / "web_dist")}[name]
+ links[key] = (path, destination)
+ for key, (source, destination) in links.items():
+ destination.unlink(missing_ok=True)
+ destination.symlink_to(source, target_is_directory=True)
+ env[key] = str(destination)
+ mapping = {"commands": {name: {"source": commands[name], "destination": f"{inputs.bin_dir}/{name}",
+ "entry": entry} for name, entry in entries.items()}, "env": env}
+ (out / "command-map.json").write_text(json.dumps(mapping, indent=2) + "\n", encoding="utf-8")
+ else:
+ for name, command in previous.get("runtime", {}).get("commands", {}).items():
+ if name not in entries and command == f"{inputs.bin_dir}/{name}{'.exe' if inputs.target.startswith('win32') else ''}":
+ (out / command).unlink(missing_ok=True)
+ launch_python = f"{location(inputs.environment)}/bin/python" if inputs.target.endswith("-bionic") else python
+ commands = write_launchers(out, entries, python=launch_python, repo=inputs.repo, site=site,
+ target=inputs.target, bin_dir=inputs.bin_dir)
+ manifest = {"schema": 1, "target": inputs.target, "repo": inputs.repo,
+ "venv": location(inputs.environment), "store": tools,
+ "launchers": list(entries), "runtime": {
+ "repoDir": str(inputs.code) if referenced else inputs.repo,
+ "toolsDir": tools, "storePython": python,
+ "sitePackages": site, "commands": commands}}
+ if inputs.ref is not None:
+ manifest["ref"] = inputs.ref
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ return manifest
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--inputs", type=Path, required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ args = parser.parse_args()
+ try:
+ inputs = AgentInputs.from_dict(json.loads(args.inputs.read_text(encoding="utf-8-sig")))
+ assemble(inputs, args.out)
+ except Exception:
+ (args.out / "manifest.json").unlink(missing_ok=True)
+ (args.out / "command-map.json").unlink(missing_ok=True)
+ raise
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/build/desktop.mjs b/scripts/build/desktop.mjs
new file mode 100644
index 00000000000..e9f015384d3
--- /dev/null
+++ b/scripts/build/desktop.mjs
@@ -0,0 +1,70 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process'
+import { cpSync, existsSync, readdirSync } from 'node:fs'
+import { dirname, join, relative, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { bundleElectronMain } from '../../apps/desktop/scripts/bundle-electron-main.mjs'
+import { checkDistBuilt } from '../../apps/desktop/scripts/assert-dist-built.mjs'
+import { classifyNativeBinary } from '../../apps/desktop/scripts/stage-native-deps.mjs'
+import { frontendArgs, isMain, productOutput, withProduct, workspaceTool } from './frontend-common.mjs'
+
+function validateNativeTree(nativeDeps, platform) {
+ const pty = join(nativeDeps, 'node-pty')
+ if (!existsSync(join(pty, 'package.json'))) throw new Error(`Missing prepared node-pty: ${pty}`)
+ const bindings = readdirSync(pty, { recursive: true }).filter(name => name.endsWith('.node'))
+ if (!bindings.length) throw new Error(`Prepared node-pty has no native binding: ${pty}`)
+ for (const binding of bindings) {
+ if (classifyNativeBinary(join(pty, binding)) !== platform) {
+ throw new Error(`Prepared node-pty binding does not match ${platform}: ${binding}`)
+ }
+ }
+ if (platform === 'darwin' && !existsSync(join(nativeDeps, 'get-windows/main'))) {
+ throw new Error('Prepared get-windows is missing its macOS helper')
+ }
+}
+
+/** Pure desktop compilation. out is the dist directory, not the source app. */
+export async function buildDesktop({ source, out, icons, stamp, nativeDeps, typecheck = false, platform = process.platform }) {
+ if (!icons || !stamp || !nativeDeps) throw new Error('icons, stamp and nativeDeps are required prepared inputs')
+ const app = 'apps/desktop'
+ ;({ source, out } = productOutput(source, out, [
+ ...readdirSync(join(resolve(source), app)).filter(name => name !== 'dist').map(name => `${app}/${name}`),
+ `${app}/scripts`, 'scripts/build', 'package.json', 'package-lock.json',
+ 'apps/shared', 'node_modules', ...[join(resolve(icons), app, 'public'), stamp, nativeDeps].map(input => relative(resolve(source), resolve(input))),
+ ]))
+ const publicIcons = join(resolve(icons), app, 'public')
+ if (!existsSync(join(publicIcons, 'apple-touch-icon.png'))) throw new Error(`Missing desktop icon: ${join(publicIcons, 'apple-touch-icon.png')}`)
+ validateNativeTree(resolve(nativeDeps), platform)
+ await withProduct(out, async (product, scratch) => {
+ const publicDir = join(scratch, 'public')
+ const sourcePublic = join(source, app, 'public')
+ if (existsSync(sourcePublic)) cpSync(sourcePublic, publicDir, { recursive: true })
+ cpSync(publicIcons, publicDir, { recursive: true })
+ if (typecheck) {
+ const ts = workspaceTool(source, app, 'typescript')
+ execFileSync(process.execPath, [join(dirname(ts), 'tsc.js'), '-p', join(source, app, 'tsconfig.json'),
+ '--noEmit', '--incremental', '--tsBuildInfoFile', join(scratch, 'renderer.tsbuildinfo')], { cwd: join(source, app), stdio: 'inherit' })
+ }
+ const { build } = await import(pathToFileURL(workspaceTool(source, app, 'vite')).href)
+ await build({
+ root: join(source, app),
+ configLoader: 'runner',
+ publicDir,
+ cacheDir: join(scratch, 'vite-cache'),
+ build: { outDir: product, emptyOutDir: true },
+ })
+ await bundleElectronMain({ source, out: product, stamp })
+ cpSync(resolve(nativeDeps), join(product, 'node_modules'), { recursive: true, dereference: true })
+ const result = checkDistBuilt(product)
+ if (!result.ok) throw new Error(result.error)
+ }, { source })
+ return { out }
+}
+
+if (isMain(import.meta.url)) {
+ const args = frontendArgs(process.argv.slice(2), {
+ icons: { type: 'string' }, stamp: { type: 'string' }, 'native-deps': { type: 'string' },
+ typecheck: { type: 'boolean' }, platform: { type: 'string' },
+ })
+ await buildDesktop({ ...args, nativeDeps: args['native-deps'] })
+}
diff --git a/scripts/build/frontend-common.mjs b/scripts/build/frontend-common.mjs
new file mode 100644
index 00000000000..2b2088f9ce1
--- /dev/null
+++ b/scripts/build/frontend-common.mjs
@@ -0,0 +1,113 @@
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { parseArgs } from 'node:util'
+
+export const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+
+// Look only in the prepared workspace, not a parent checkout's dependency tree.
+// Package symlinks themselves are valid inputs (including Nix store references).
+export function workspaceTool(source, workspace, name) {
+ for (const root of [path.join(source, workspace), source]) {
+ const manifest = path.join(root, 'node_modules', name, 'package.json')
+ if (existsSync(manifest)) {
+ return createRequire(path.join(root, 'package.json')).resolve(name)
+ }
+ }
+ throw new Error(`Missing prepared ${name} dependency in ${workspace} or ${source}/node_modules`)
+}
+
+function canonical(file) {
+ if (existsSync(file)) return realpathSync(file)
+ return path.join(canonical(path.dirname(file)), path.basename(file))
+}
+
+function contains(parent, child) {
+ const relative = path.relative(parent, child)
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
+}
+
+const productMarker = '.hermes-product'
+const productOwner = 'hermes-frontend-product-v1\n'
+const developerOutputs = ['ui-tui/dist', 'hermes_cli/web_dist', 'apps/desktop/dist', 'apps/desktop/build/native-deps']
+
+function developerOutput(source, out) {
+ return source && developerOutputs.some(name => path.resolve(out) === path.join(path.resolve(source), name))
+}
+
+// A destination name alone does not confer ownership of its existing contents.
+function requireOwnedOutput(out, source) {
+ const stat = lstatSync(out, { throwIfNoEntry: false })
+ if (!stat) return
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`Output must be a directory, not a file or symlink: ${out}`)
+ // These exact npm destinations belong to their compiler. Other paths require
+ // explicit ownership before an existing directory can be replaced.
+ if (developerOutput(source, out)) return
+ const marker = path.join(out, productMarker)
+ if (!lstatSync(marker, { throwIfNoEntry: false })?.isFile() || readFileSync(marker, 'utf8') !== productOwner) {
+ throw new Error(`Output already exists and is not builder-owned; choose a fresh output directory: ${out}`)
+ }
+}
+
+export function productOutput(source, out, inputs) {
+ if (!source || !out) throw new Error('source and output paths are required')
+ const src = realpathSync(path.resolve(source))
+ const dest = canonical(path.resolve(out))
+ if (contains(dest, src) || inputs.some(input => {
+ const protectedPath = canonical(path.join(src, input))
+ return contains(dest, protectedPath) || contains(protectedPath, dest)
+ })) throw new Error(`Output must not overlap build inputs: ${out}`)
+ // In-tree products have explicit homes; everything else under source is an
+ // input, even when this particular compiler does not read it.
+ const generated = developerOutput(src, dest)
+ || ['.build', 'apps/desktop/build/products'].some(name => {
+ const root = path.join(src, name)
+ return dest !== root && contains(root, dest)
+ })
+ if (contains(src, dest) && !generated) throw new Error(`Output must be outside source or in a supported generated destination: ${out}`)
+ requireOwnedOutput(out, src)
+ return { source: src, out: dest }
+}
+
+// Never delete the last successful product before a compiler succeeds. The
+// staging and backup directories are siblings so publication stays on one FS.
+export function publishDirectory(staged, out, { source } = {}) {
+ // The destination may have been occupied while the compiler was running.
+ requireOwnedOutput(out, source)
+ writeFileSync(path.join(staged, productMarker), productOwner)
+ const backup = `${staged}.previous`
+ const previous = existsSync(out)
+ if (previous) renameSync(out, backup)
+ try {
+ renameSync(staged, out)
+ } catch (error) {
+ if (previous) renameSync(backup, out)
+ throw error
+ }
+ if (previous) rmSync(backup, { recursive: true, force: true })
+}
+
+export async function withProduct(out, compile, { source } = {}) {
+ requireOwnedOutput(out, source)
+ mkdirSync(path.dirname(out), { recursive: true })
+ const scratch = mkdtempSync(path.join(path.dirname(out), `.${path.basename(out)}-build-`))
+ const product = path.join(scratch, 'product')
+ mkdirSync(product)
+ try {
+ await compile(product, scratch)
+ publishDirectory(product, out, { source })
+ } finally {
+ rmSync(scratch, { recursive: true, force: true })
+ }
+}
+
+export function isMain(url) {
+ return process.argv[1] && url === pathToFileURL(path.resolve(process.argv[1])).href
+}
+
+export function frontendArgs(args, extra = {}) {
+ const { values } = parseArgs({ args, options: { source: { type: 'string' }, out: { type: 'string' }, ...extra } })
+ if (!values.source || !values.out) throw new Error('--source and --out are required for product builds')
+ return values
+}
diff --git a/scripts/build/inputs.py b/scripts/build/inputs.py
new file mode 100644
index 00000000000..c9ebad218ac
--- /dev/null
+++ b/scripts/build/inputs.py
@@ -0,0 +1,122 @@
+"""Build-time paths, not a second runtime configuration or dependency resolver."""
+from __future__ import annotations
+
+from dataclasses import dataclass, field, fields
+from pathlib import Path
+import json
+import re
+import tomllib
+
+
+RESOURCE_ENV = {
+ "skills": "HERMES_BUNDLED_SKILLS",
+ "optional-skills": "HERMES_OPTIONAL_SKILLS",
+ "plugins": "HERMES_BUNDLED_PLUGINS",
+ "locales": "HERMES_BUNDLED_LOCALES",
+ "optional-mcps": "HERMES_OPTIONAL_MCPS",
+}
+
+
+def dependency_site(environment: Path, python_version: str, target: str) -> Path:
+ """Providers know the target pin; the builder's interpreter is irrelevant."""
+ minor = python_version.split("+")[0].rsplit(".", 1)[0]
+ return environment / ("Lib/site-packages" if target.startswith("win32") else
+ f"lib/python{minor}/site-packages")
+
+
+def project_entries(project: Path) -> dict[str, str]:
+ entries = tomllib.loads(project.read_text(encoding="utf-8-sig"))["project"]["scripts"]
+ for name, entry in entries.items():
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", name):
+ raise ValueError(f"invalid command name: {name}")
+ if not re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*", entry):
+ raise ValueError(f"invalid script entry: {entry}")
+ return entries
+
+
+@dataclass(frozen=True)
+class AgentInputs:
+ project: Path
+ code: Path
+ repo: str
+ placement: str
+ target: str
+ python: Path
+ site_packages: Path
+ environment: Path
+ pm_runtime: Path
+ bin_dir: str = "bin"
+ tools: Path | None = None
+ command_dir: Path | None = None
+ resources: dict[str, Path] = field(default_factory=dict)
+ frontends: dict[str, Path] = field(default_factory=dict)
+ ref: str | None = None
+ stamp: Path | None = None
+ features: Path | None = None
+ env: dict[str, str] = field(default_factory=dict)
+
+ @classmethod
+ def from_dict(cls, data: dict) -> AgentInputs:
+ unknown = data.keys() - {f.name for f in fields(cls)}
+ if unknown:
+ raise ValueError(f"unknown agent inputs: {', '.join(sorted(unknown))}")
+ values = dict(data)
+ for key in ("project", "code", "python", "site_packages", "environment", "tools",
+ "pm_runtime", "command_dir", "stamp", "features"):
+ if values.get(key) is not None:
+ values[key] = Path(values[key])
+ for key in ("resources", "frontends"):
+ values[key] = {name: Path(path) for name, path in values.get(key, {}).items()}
+ return cls(**values)
+
+ def validate(self, out: Path) -> None:
+ if not re.fullmatch(r"(?:(?:linux|darwin|win32)-(?:x64|arm64)|linux-arm64-bionic)", self.target):
+ raise ValueError(f"unsupported target: {self.target}")
+ if self.placement not in ("contained", "fixed", "references"):
+ raise ValueError(f"unknown placement: {self.placement}")
+ if Path(self.repo).is_absolute() or ".." in Path(self.repo).parts:
+ raise ValueError("repo must be an output-relative path")
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", self.bin_dir):
+ raise ValueError("bin_dir must be one output-relative directory")
+ if self.resources.keys() - RESOURCE_ENV.keys():
+ raise ValueError("unknown resource names")
+ if self.frontends.keys() - {"tui", "web"}:
+ raise ValueError("unknown frontend names")
+ paths = [self.project, self.code, self.python, self.site_packages, self.environment,
+ self.pm_runtime, *self.resources.values(), *self.frontends.values()]
+ paths += [p for p in (self.tools, self.command_dir, self.stamp, self.features) if p is not None]
+ for path in paths:
+ if not path.is_absolute():
+ raise ValueError(f"input path must be absolute: {path}")
+ if not path.exists():
+ raise FileNotFoundError(f"required agent input missing: {path}")
+ for path in (self.project, self.python):
+ if not path.is_file():
+ raise ValueError(f"expected a file: {path}")
+ for path in (self.code, self.site_packages, self.environment, self.pm_runtime):
+ if not path.is_dir():
+ raise ValueError(f"expected a directory: {path}")
+ marker = json.loads((self.pm_runtime / "pm-runtime.json").read_text(encoding="utf-8-sig"))
+ pm_python = (self.pm_runtime / marker["python"]).resolve()
+ pm_site = (self.pm_runtime / marker["sitePackages"]).resolve()
+ if not pm_python.is_file() or not pm_site.is_dir():
+ raise ValueError("prepared PM runtime is incomplete")
+ if self.stamp is not None:
+ stamp = json.loads(self.stamp.read_text(encoding="utf-8-sig"))
+ if stamp.get("distribution") in ("nix", "docker") and stamp.get("pmRuntime") != str(self.pm_runtime):
+ raise ValueError("install stamp must reference the supplied independent PM runtime")
+ if self.placement == "contained":
+ for path in (self.python, self.site_packages, self.environment, self.pm_runtime, self.tools):
+ if path is not None and not path.resolve().is_relative_to(out):
+ raise ValueError(f"contained input must be prepared inside output: {path}")
+ if self.placement == "references" and self.command_dir is None:
+ raise ValueError("referenced placement requires command_dir")
+ validate_frontends(self.frontends)
+
+
+def validate_frontends(frontends: dict[str, Path]) -> None:
+ for name, path in frontends.items():
+ required = ("dist/entry.js", "package.json") if name == "tui" else ("index.html",)
+ for entry in required:
+ if not (path / entry).is_file():
+ raise FileNotFoundError(path / entry)
diff --git a/scripts/build/launcher_wrapper.py b/scripts/build/launcher_wrapper.py
new file mode 100644
index 00000000000..9b5c3399bf2
--- /dev/null
+++ b/scripts/build/launcher_wrapper.py
@@ -0,0 +1,107 @@
+"""Bundled-payload CLI entry wrapper — the distlib launcher's zip overlay.
+
+scripts/build/launchers.py reads this file, substitutes the four
+HERMES_* placeholders (see the constants below), and hands the result to
+a distlib ScriptMaker as
+the script text. On win32 the minted artifact is a real PE: the distlib
+launcher stub + a shebang whose interpreter is the ``<launcher_dir>``
+placeholder form (resolved at runtime relative to the launcher's own
+directory) + this script packed as __main__.py in a zip overlay. The
+The wrapper replaces everything the old rust shim + its sidecar did
+(plan: pm-clean):
+
+ * resolve the launcher's own directory from sys.argv[0] (the distlib
+ launcher puts its exe path there — the shebang's ``<launcher_dir>``
+ placeholder resolves the interpreter the same way),
+ * put the payload repo snapshot FIRST and the venv site-packages second
+ on sys.path (same order, same reason as the old shim: the repo's
+ hermes_cli wins over anything stale in site-packages — the sealed
+ payload's venv has no working editable install, its pointer names the
+ BUILD machine),
+ * drop inherited PYTHONPATH / PYTHONHOME so foreign installs can never
+ shadow the bundle,
+ * default sys.pycache_prefix to the user-level cache (%LOCALAPPDATA%
+ \\hermes\\pycache on win32, ~/.cache/hermes-pycache elsewhere) when the
+ user has not set one — the sealed payload must never see __pycache__
+ writes (signature-breaking on mac, read-only mount on AppImage/MSIX).
+
+The whole file is import-safe so tests can drive configure()/main()
+directly (tests/scripts/test_desktop_cli_wrapper.py).
+"""
+
+import importlib
+import os
+import sys
+
+HERMES_ENTRY_MODULE = "__HERMES_ENTRY_MODULE__"
+HERMES_ENTRY_FUNC = "__HERMES_ENTRY_FUNC__"
+HERMES_REPO_REL = "__HERMES_REPO_REL__"
+HERMES_SITE_REL = "__HERMES_SITE_REL__"
+
+
+def _join_rel(here, rel):
+ """Join a forward-slash relative path (the minted-in convention, same
+ as the payload manifest) onto a host dir without os.sep assumptions."""
+ return os.path.join(here, *rel.split("/"))
+
+
+def launcher_dir(argv0):
+ """The directory of the launcher itself, from sys.argv[0]. abspath
+ because cwd is meaningless for a GUI/alias launch."""
+ return os.path.dirname(os.path.abspath(argv0))
+
+
+def payload_sys_paths(here):
+ """Import roots for the sealed payload: repo first (wins), then the
+ venv's dependency tree — mirroring the old shim's PYTHONPATH order."""
+ return [_join_rel(here, HERMES_REPO_REL), _join_rel(here, HERMES_SITE_REL)]
+
+
+def default_pycache_dir(environ):
+ """User-level bytecode cache. The sealed payload is read-only at
+ runtime (or signature-sealed, on mac), so __pycache__ writes must
+ land outside it. Only consulted when the user has not set their own
+ PYTHONPYCACHEPREFIX."""
+ if sys.platform == "win32":
+ base = environ.get("LOCALAPPDATA")
+ return os.path.join(base, "hermes", "pycache") if base else None
+ base = environ.get("HOME")
+ return os.path.join(base, ".cache", "hermes-pycache") if base else None
+
+
+def configure(here, environ=None):
+ """Point THIS process (the minted launcher's python) at the payload.
+ Returns the sys.path entries prepended, for tests."""
+ environ = os.environ if environ is None else environ
+ # Same hygiene as the old rust shim: an inherited PYTHONPATH could
+ # shadow bundled modules with foreign ones; PYTHONHOME would repoint
+ # the stdlib entirely.
+ environ.pop("PYTHONPATH", None)
+ environ.pop("PYTHONHOME", None)
+ entries = payload_sys_paths(here)
+ sys.path[0:0] = entries
+ if not environ.get("PYTHONPYCACHEPREFIX"):
+ default = default_pycache_dir(environ)
+ if default:
+ environ["PYTHONPYCACHEPREFIX"] = default
+ # The env var is only read at interpreter startup; we ARE at
+ # startup, but setting it in os.environ cannot retro-activate
+ # it — sys.pycache_prefix is the live switch.
+ sys.pycache_prefix = default
+ return entries
+
+
+def main(argv=None):
+ argv = list(sys.argv if argv is None else argv)
+ here = launcher_dir(argv[0] if argv else sys.argv[0])
+ configure(here)
+ importlib.import_module("hermes_bootstrap")
+ module = importlib.import_module(HERMES_ENTRY_MODULE)
+ target = getattr(module, HERMES_ENTRY_FUNC)
+ # main() reads sys.argv; hand it the real argv (argv[0] stays the
+ # launcher path, exactly like a console-script entry point).
+ return target()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/build/launchers.py b/scripts/build/launchers.py
new file mode 100644
index 00000000000..99135bc85c5
--- /dev/null
+++ b/scripts/build/launchers.py
@@ -0,0 +1,95 @@
+"""Shared payload launcher rendering; all paths are supplied by the assembler."""
+from __future__ import annotations
+
+import json
+import os
+import re
+from pathlib import Path
+import subprocess
+import tempfile
+
+
+def render_wrapper(entry: str, repo: str, site: str) -> str:
+ module, func = entry.split(":", 1)
+ text = (Path(__file__).with_name("launcher_wrapper.py")).read_text(encoding="utf-8-sig")
+ for key, value in {"ENTRY_MODULE": module, "ENTRY_FUNC": func, "REPO_REL": repo, "SITE_REL": site}.items():
+ if '"' in value or "\n" in value or "__" in value:
+ raise ValueError(f"invalid launcher value: {key}")
+ text = text.replace(f"__HERMES_{key}__", value)
+ unresolved = re.search(r"__HERMES_\w+?__", text)
+ if unresolved:
+ raise ValueError(f"unresolved launcher placeholder: {unresolved.group()}")
+ return text
+
+
+def posix_launcher(name: str, entry: str, *, python: str, repo: str, site: str, target: str) -> str:
+ import shlex
+
+ def shell_path(value: str) -> str:
+ return shlex.quote(value) if Path(value).is_absolute() else '"$root"/' + shlex.quote(value)
+
+ module, func = entry.split(":", 1)
+ bionic = target.endswith("-bionic")
+ header = "#!/data/data/com.termux/files/usr/bin/sh" if bionic else "#!/usr/bin/env bash"
+ extra = ""
+ if bionic:
+ extra = '''PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"
+export PREFIX
+export LD_LIBRARY_PATH="$root/tools/python/data/data/com.termux/files/usr/lib:$root/tools/node/data/data/com.termux/files/usr/lib:$root/tools/ffmpeg/data/data/com.termux/files/usr/lib:$root/runtime-libs/lib:$PREFIX/lib"
+export HERMES_PYTHON_SRC_ROOT="$REPO"
+export HERMES_PYTHON="$PYTHON"
+export HERMES_NODE="$root/tools/node/data/data/com.termux/files/usr/bin/node"
+export HERMES_RUNTIME_DIR="$root/tools"
+export PATH="$root/tools/npm/bin:$root/tools/node/data/data/com.termux/files/usr/bin:$root/tools/ffmpeg/data/data/com.termux/files/usr/bin:$root/tools/ripgrep:$PATH"
+'''
+ code = f"import sys; sys.argv[0]={name!r}; from {module} import {func}; sys.exit({func}())"
+ return f'''{header}
+set -eu
+self="$0"
+while [ -L "$self" ]; do
+ target="$(readlink "$self")"
+ case "$target" in
+ /*) self="$target" ;;
+ *) self="$(dirname "$self")/$target" ;;
+ esac
+done
+root="$(cd "$(dirname "$self")/.." && pwd)"
+PYTHON={shell_path(python)}
+REPO={shell_path(repo)}
+SITE={shell_path(site)}
+[ -x "$PYTHON" ] || {{ printf '%s\\n' 'Bundled interpreter missing; reinstall Hermes.' >&2; exit 2; }}
+unset PYTHONPATH PYTHONHOME
+export PYTHONPATH="$REPO:$SITE"
+export PYTHONPYCACHEPREFIX="${{PYTHONPYCACHEPREFIX:-${{XDG_CACHE_HOME:-$HOME/.cache}}/hermes-pycache}}"
+{extra}exec "$PYTHON" -P -c {shlex.quote(code)} "$@"
+'''
+
+
+def write_launchers(root: Path, entries: dict[str, str], *, python: str,
+ repo: str, site: str, target: str, bin_dir: str = "bin",
+ run=subprocess.run) -> dict[str, str]:
+ """Mint only declared commands; the caller owns completion publication."""
+ bindir = root / bin_dir
+ bindir.mkdir(parents=True, exist_ok=True)
+ windows = target.startswith("win32")
+ for name, entry in entries.items():
+ if windows:
+ with tempfile.TemporaryDirectory(prefix="hermes-mint-") as temp:
+ wrapper = Path(temp) / "wrapper.py"
+ wrapper.write_text(render_wrapper(entry, f"../{repo}", f"../{site}"), encoding="utf-8")
+ module, func = entry.split(":", 1)
+ env = {**os.environ, "HERMES_MINT_BIN_DIR": str(bindir),
+ "HERMES_MINT_SPECS": json.dumps([{"name": name, "module": module, "func": func}]),
+ "HERMES_MINT_WRAPPER": str(wrapper),
+ "HERMES_MINT_PYTHON": "<launcher_dir>\\..\\" + python.replace("/", "\\")}
+ run([str(root / python), str(Path(__file__).with_name("mint_launchers.py"))], env=env, check=True)
+ else:
+ script = posix_launcher(name, entry, python=python, repo=repo, site=site, target=target)
+ output = bindir / name
+ output.write_text(script, encoding="utf-8")
+ output.chmod(0o755)
+ commands = {name: f"{bin_dir}/{name}{'.exe' if windows else ''}" for name in entries}
+ for command in commands.values():
+ if not (root / command).is_file():
+ raise FileNotFoundError(f"payload launcher missing: {command}")
+ return commands
diff --git a/scripts/build/mint_launchers.py b/scripts/build/mint_launchers.py
new file mode 100644
index 00000000000..c195b53f547
--- /dev/null
+++ b/scripts/build/mint_launchers.py
@@ -0,0 +1,111 @@
+"""Mint the bundled payload's win32 CLI launchers with distlib.
+
+Run by scripts/bundles/desktop.py (step 5b) with the payload's OWN
+store python as the minting interpreter — the store python is the same
+distribution the launchers will execute, and its architecture is by
+construction the target architecture, which is exactly what distlib's
+_get_launcher needs (it picks a 32/64-bit, -arm-suffixed launcher stub by
+the MINTING interpreter's platform; cross-arch minting with a mismatched
+host python produces launchers that cannot run).
+
+distlib availability: the payload python ships pip (python-build-standalone
+includes it), and pip vendors distlib at pip._vendor.distlib — so the mint
+works with NO extra dependency. A top-level distlib install is preferred
+when present. (Self-contained .\_pth interpreters were REJECTED as an
+alternative approach: they break uv venv materialization.)
+
+Layout facts arrive via environment from scripts/build/launchers.py:
+
+ HERMES_MINT_BIN_DIR absolute output dir (agent-payload/bin)
+ HERMES_MINT_SPECS JSON list of {"name": exe stem, "module": dotted
+ module, "func": entry function} — mirrors
+ [project.scripts] in pyproject.toml
+ HERMES_MINT_WRAPPER path of the RENDERED launcher-wrapper.py for THIS
+ entry (substitution is scripts/build/launchers.py's job,
+ one implementation, one test)
+ HERMES_MINT_PYTHON bin-relative path of the store python, BACKslashes,
+ e.g. <launcher_dir>\..\tools\<entry>\python.exe —
+ baked into the shebang; the literal <launcher_dir>
+ prefix is resolved by the launcher at run time
+ relative to its own directory (relocatability is
+ live-proved: the placeholder survives minting)
+
+Testable standalone: tests/scripts/test_mint_launchers.py drives main()
+against a temp tree with a stub module and RUNS the minted exe.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+
+try: # a real distlib install when available
+ from distlib.scripts import ScriptMaker
+except ImportError: # the payload python's guaranteed fallback: pip's vendor
+ from pip._vendor.distlib.scripts import ScriptMaker
+
+
+def make_maker(bin_dir, shebang_python, wrapper_text):
+ class MintScriptMaker(ScriptMaker):
+ # The wrapper text is fully pre-rendered, so ignore the entry the
+ # spec carried — the name is all we need from it.
+ def __init__(self, wrapper, **kwargs):
+ target_dir = kwargs.pop("target_dir")
+ super().__init__(None, target_dir, **kwargs)
+ self._wrapper_text = wrapper
+
+ def _get_script_text(self, entry):
+ return self._wrapper_text
+
+ # The shebang the launcher stub parses: #! + this string. The
+ # <launcher_dir> literal is replaced by the launcher with its own
+ # directory at run time — that IS the self-relative mechanism.
+ maker = MintScriptMaker(
+ wrapper_text,
+ target_dir=bin_dir,
+ add_launchers=True,
+ dry_run=False,
+ )
+ maker.executable = shebang_python
+ return maker
+
+
+def mint_one(bin_dir, shebang_python, wrapper_text, spec):
+ """Mint one launcher exe; returns its absolute path. distlib also
+ writes a python-versioned twin (hermes-3.14.exe) — the payload ships
+ exactly one name per entry, so the twin is removed."""
+ maker = make_maker(bin_dir, shebang_python, wrapper_text)
+ filenames = maker.make(f"{spec['name']} = {spec['module']}:{spec['func']}")
+ plain = os.path.join(bin_dir, f"{spec['name']}.exe")
+ if os.path.abspath(plain) not in (os.path.abspath(f) for f in filenames):
+ raise SystemExit(f"distlib did not write {plain}: {filenames}")
+ for extra in filenames:
+ if os.path.abspath(extra) != os.path.abspath(plain):
+ os.remove(extra)
+ return plain
+
+
+def main(environ=None):
+ environ = os.environ if environ is None else environ
+ bin_dir = environ["HERMES_MINT_BIN_DIR"]
+ specs = json.loads(environ["HERMES_MINT_SPECS"])
+ shebang_python = environ["HERMES_MINT_PYTHON"]
+ if not os.path.isabs(bin_dir):
+ raise SystemExit("HERMES_MINT_BIN_DIR must be absolute")
+ if not shebang_python.startswith("<launcher_dir>\\..\\"):
+ raise SystemExit(
+ "HERMES_MINT_PYTHON must be <launcher_dir>\\..\\payload-relative "
+ f"(backslashes), got: {shebang_python}"
+ )
+ os.makedirs(bin_dir, exist_ok=True)
+ minted = []
+ for spec in specs:
+ # utf-8-sig: tolerate a BOM the JS renderer might prepend.
+ with open(environ["HERMES_MINT_WRAPPER"], encoding="utf-8-sig") as f:
+ wrapper_text = f.read()
+ minted.append(mint_one(bin_dir, shebang_python, wrapper_text, spec))
+ return minted
+
+
+if __name__ == "__main__":
+ print("\n".join(main()))
diff --git a/scripts/build/node-deps.mjs b/scripts/build/node-deps.mjs
new file mode 100644
index 00000000000..ad9be189369
--- /dev/null
+++ b/scripts/build/node-deps.mjs
@@ -0,0 +1,69 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process'
+import { existsSync, readFileSync, realpathSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { delimiter, dirname, join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { parseArgs } from 'node:util'
+
+// npm.cmd needs a shell. Use npm's JS entrypoint so paths remain argv on Windows.
+export function npmCommand({ env = process.env } = {}) {
+ const names = process.platform === 'win32' ? ['npm.cmd', 'npm'] : ['npm']
+ const candidates = [env.npm_execpath]
+ for (const dir of (env.PATH || env.Path || '').split(delimiter)) {
+ for (const name of names) {
+ const bin = join(dir, name)
+ if (!existsSync(bin)) continue
+ const prefix = dirname(realpathSync(bin))
+ candidates.push(
+ join(prefix, 'node_modules/npm/bin/npm-cli.js'),
+ join(prefix, '../lib/node_modules/npm/bin/npm-cli.js'),
+ join(prefix, '../lib/npm/bin/npm-cli.js'),
+ realpathSync(bin),
+ )
+ }
+ }
+ const cli = candidates.find(path => path && path.endsWith('.js') && existsSync(path))
+ if (!cli) throw new Error('npm CLI is required on PATH')
+ return [process.execPath, cli]
+}
+
+/** Install the full requested workspace union in one strict, locked operation. */
+export function prepareNodeDependencies({ source, workspaces, env = process.env }) {
+ source = resolve(source)
+ if (!Array.isArray(workspaces) || workspaces.length === 0) {
+ throw new Error('Select at least one workspace; implicit all-workspace installation is not allowed')
+ }
+ const manifest = JSON.parse(readFileSync(join(source, 'package.json'), 'utf8'))
+ const lock = JSON.parse(readFileSync(join(source, 'package-lock.json'), 'utf8'))
+ const workspacePaths = Object.values(lock.packages || {})
+ .filter(entry => entry.link)
+ .map(entry => entry.resolved)
+ const selected = [...new Set(workspaces.map(workspace => {
+ const path = workspacePaths.find(path => path === workspace || lock.packages[path]?.name === workspace)
+ if (!path || !existsSync(join(source, path, 'package.json'))) {
+ throw new Error(`Unknown or missing locked workspace: ${workspace}`)
+ }
+ return path
+ }))]
+ const [node, npm] = npmCommand({ env })
+ const npmVersion = execFileSync(node, [npm, '--version'], { cwd: source, env, encoding: 'utf8' }).trim()
+ const { satisfies } = createRequire(npm)('semver')
+ for (const [name, version] of [['node', process.versions.node], ['npm', npmVersion]]) {
+ const range = manifest.engines?.[name]
+ if (range && !satisfies(version, range)) throw new Error(`${name} ${version} violates ${range}`)
+ }
+ execFileSync(node, [npm, 'ci', '--no-audit', '--no-fund', '--engine-strict', '--include=dev',
+ '--include=optional', '--include-workspace-root=true',
+ ...selected.flatMap(workspace => ['--workspace', workspace]),
+ ], { cwd: source, env, stdio: 'inherit' })
+ return { source, workspaces: selected }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const { values } = parseArgs({ options: {
+ source: { type: 'string' }, workspace: { type: 'string', multiple: true },
+ } })
+ if (!values.source) throw new Error('--source is required')
+ prepareNodeDependencies({ source: values.source, workspaces: values.workspace })
+}
diff --git a/scripts/build/python_env.py b/scripts/build/python_env.py
new file mode 100644
index 00000000000..b45cdb89727
--- /dev/null
+++ b/scripts/build/python_env.py
@@ -0,0 +1,76 @@
+"""Native/Docker dependency preparation over PM's explicit uv mechanics.
+
+Unlike live PM, a build never discovers plugins or publishes a selection.
+The source is the prepared application tree; editable installs keep pointing
+at that tree. Nix and Termux retain their own dependency providers.
+"""
+from __future__ import annotations
+
+import argparse
+from collections.abc import Mapping, Sequence
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+from pm.environment import PythonEnvironment
+from pm.package import InstallError
+
+
+def build_python_environment(
+ *, source: Path, python: Path, uv: Path, out: Path,
+ env: Mapping[str, str], cache: Path | None = None,
+ extras: Sequence[str] = (), all_extras: bool = False,
+ no_install_project: bool = False, offline: bool = False,
+) -> Path:
+ """Build a fresh environment and return its Python executable after validation.
+
+ ``out`` must not exist. Failure removes only this invocation's destination;
+ a pre-existing environment is never deleted or used as a successful result.
+ The cache (default: ``out.parent / ".uv-cache"``) remains available to the
+ native offline-cache packager. ``no_install_project`` prepares only the
+ locked dependencies, before an application source layer is available.
+ """
+ source, out = source.absolute(), out.absolute()
+ cache = out.parent / ".uv-cache" if cache is None else cache.absolute()
+ environment = PythonEnvironment(
+ uv=uv.absolute(), python=python.absolute(), destination=out,
+ cache=cache.absolute(), env=env, offline=offline, output=sys.stderr,
+ )
+ out.mkdir(parents=True)
+ try:
+ environment.create()
+ environment.sync(source, extras=extras, all_extras=all_extras,
+ no_install_project=no_install_project)
+ environment.check()
+ except BaseException:
+ shutil.rmtree(out, ignore_errors=True)
+ raise
+ return environment.executable
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", required=True, type=Path)
+ parser.add_argument("--python", required=True, type=Path)
+ parser.add_argument("--uv", required=True, type=Path)
+ parser.add_argument("--out", required=True, type=Path)
+ parser.add_argument("--cache", type=Path, help="uv cache; defaults to OUT's sibling .uv-cache")
+ selection = parser.add_mutually_exclusive_group()
+ selection.add_argument("--extra", dest="extras", action="append", default=[])
+ selection.add_argument("--all-extras", action="store_true")
+ parser.add_argument("--no-install-project", action="store_true")
+ parser.add_argument("--offline", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ executable = build_python_environment(**vars(args), env=dict(os.environ))
+ except (InstallError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
+ print(f"python environment: {exc}", file=sys.stderr)
+ return 1
+ print(executable)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/build/tui.mjs b/scripts/build/tui.mjs
new file mode 100644
index 00000000000..d87965261c0
--- /dev/null
+++ b/scripts/build/tui.mjs
@@ -0,0 +1,103 @@
+#!/usr/bin/env node
+// Self-contained TUI compiler. Dependencies must already be prepared.
+import { cpSync, readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { resolve, join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { frontendArgs, isMain, productOutput, publishDirectory, repoRoot, withProduct, workspaceTool } from './frontend-common.mjs'
+
+// `react-devtools-core` is only imported when DEV=true at runtime (Ink dev
+// mode). Stub it out so the bundle doesn't carry the dep.
+const stubDevtools = {
+ name: 'stub-react-devtools-core',
+ setup(b) {
+ b.onResolve({ filter: /^react-devtools-core$/ }, args => ({
+ path: args.path,
+ namespace: 'stub-devtools'
+ }))
+ b.onLoad({ filter: /.*/, namespace: 'stub-devtools' }, () => ({
+ contents: 'export default { initialize() {}, connectToDevTools() {} }',
+ loader: 'js'
+ }))
+ }
+}
+
+export async function buildTui(options) {
+ const { source, out: destination } = productOutput(options.source, options.out, ['ui-tui', 'apps/shared', 'node_modules'])
+ const { build } = await import(pathToFileURL(workspaceTool(source, 'ui-tui', 'esbuild')).href)
+ const root = join(source, 'ui-tui')
+ await withProduct(destination, async product => {
+ const out = join(product, 'dist/entry.js')
+ await build({
+ absWorkingDir: root,
+ entryPoints: [resolve(root, 'src/entry.tsx')],
+ bundle: true,
+ platform: 'node',
+ format: 'esm',
+ target: 'node20',
+ outfile: out,
+ jsx: 'automatic',
+ jsxImportSource: 'react',
+ // Skip the prebuilt @hermes/ink bundle and inline the source instead:
+ // (1) esbuild's `__esm` helper does not await nested async init, so the
+ // prebuilt bundle's lazy `render` would never resolve when nested in
+ // this top-level Promise.all; (2) bundling from source also lets us
+ // keep `ink-text-input` and the upstream `ink` graph OUT of the
+ // bundle entirely — re-exporting them from entry-exports created a
+ // circular async chain that hung the TUI at startup with only ANSI
+ // reset bytes on screen (#31227).
+ alias: { '@hermes/ink': resolve(root, 'packages/hermes-ink/src/entry-exports.ts') },
+ plugins: [stubDevtools],
+ // Some transitive deps use CommonJS `require(...)` at runtime. ESM bundles
+ // don't get a `require` binding automatically, so we inject one.
+ banner: {
+ js: "import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);"
+ },
+ logLevel: 'info'
+ })
+
+ // esbuild preserves the shebang from src/entry.tsx into the bundle, but Nix's
+ // patchShebangs phase mangles `/usr/bin/env -S node --foo --bar` (it strips
+ // the `node` token, leaving a broken interpreter). The hermes_cli launcher
+ // always invokes this file as `node dist/entry.js` anyway, so the shebang is
+ // redundant — strip it.
+ const body = readFileSync(out, 'utf8')
+ if (body.startsWith('#!')) {
+ writeFileSync(out, body.slice(body.indexOf('\n') + 1))
+ }
+ writeFileSync(join(product, 'package.json'), JSON.stringify({ type: 'module' }) + '\n')
+ })
+ return { out: destination, entry: join(destination, 'dist/entry.js') }
+}
+
+// npm's existing developer entrypoint retains ui-tui/dist without replacing
+// the source workspace (a product includes its own package.json).
+async function buildDeveloperTui() {
+ const scratch = mkdtempSync(join(tmpdir(), 'hermes-tui-'))
+ try {
+ const result = await buildTui({ source: repoRoot, out: join(scratch, 'tui') })
+ // TMPDIR and the source checkout need not share a filesystem.
+ const staged = mkdtempSync(join(repoRoot, 'ui-tui/.dist-'))
+ try {
+ cpSync(join(result.out, 'dist'), staged, { recursive: true })
+ publishDirectory(staged, join(repoRoot, 'ui-tui/dist'), { source: repoRoot })
+ } finally {
+ rmSync(staged, { recursive: true, force: true })
+ }
+ return { out: join(repoRoot, 'ui-tui'), entry: join(repoRoot, 'ui-tui/dist/entry.js') }
+ } finally {
+ rmSync(scratch, { recursive: true, force: true })
+ }
+}
+
+if (isMain(import.meta.url)) {
+ try {
+ const result = process.argv.length === 2
+ ? await buildDeveloperTui()
+ : await buildTui(frontendArgs(process.argv.slice(2)))
+ console.log(`built ${result.entry}`)
+ } catch (error) {
+ console.error(error)
+ process.exitCode = 1
+ }
+}
diff --git a/scripts/build/web.mjs b/scripts/build/web.mjs
new file mode 100644
index 00000000000..de63b12c427
--- /dev/null
+++ b/scripts/build/web.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+// Pure dashboard compilation; icon/dependency preparation belongs to callers.
+import { cpSync, existsSync, mkdirSync, statSync } from 'node:fs'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { frontendArgs, isMain, productOutput, repoRoot, withProduct, workspaceTool } from './frontend-common.mjs'
+
+function typecheck(ts, root, scratch) {
+ const diagnostics = []
+ const host = ts.createSolutionBuilderHost(ts.sys, undefined, diagnostic => diagnostics.push(diagnostic))
+ // Use the existing tsc -b project graph, with build state isolated from the
+ // prepared source. force also prevents stale source buildinfo skipping checks.
+ const buildInfo = new Map()
+ host.writeFile = (file, data) => {
+ if (!file.endsWith('.tsbuildinfo')) throw new Error(`Unexpected TypeScript emit: ${file}`)
+ if (!buildInfo.has(file)) buildInfo.set(file, path.join(scratch, `ts-${buildInfo.size}.tsbuildinfo`))
+ ts.sys.writeFile(buildInfo.get(file), data)
+ }
+ const status = ts.createSolutionBuilder(host, [path.join(root, 'tsconfig.json')], { force: true }).build()
+ if (status !== 0) {
+ const message = ts.formatDiagnosticsWithColorAndContext(diagnostics, {
+ getCurrentDirectory: () => root,
+ getCanonicalFileName: file => file,
+ getNewLine: () => '\n'
+ })
+ throw new Error(`TypeScript build failed (${status})\n${message}`)
+ }
+}
+
+export async function buildWeb(options) {
+ const { source, out } = productOutput(options.source, options.out, ['web', 'apps/shared', 'node_modules'])
+ if (!options.icons) throw new Error('Prepared icons are required (--icons)')
+ const publicIcons = path.resolve(options.icons, 'web/public')
+ const favicon = path.join(publicIcons, 'favicon.ico')
+ if (!existsSync(favicon) || !statSync(favicon).isFile()) throw new Error(`Missing prepared icon: ${favicon}`)
+ // Icon inputs can be outside source but are still read-only build inputs.
+ productOutput(options.icons, out, ['web/public'])
+ const root = path.join(source, 'web')
+ const tsModule = await import(pathToFileURL(workspaceTool(source, 'web', 'typescript')).href)
+ const { build } = await import(pathToFileURL(workspaceTool(source, 'web', 'vite')).href)
+ await withProduct(out, async (product, scratch) => {
+ typecheck(tsModule.default ?? tsModule, root, scratch)
+ const publicDir = path.join(scratch, 'public')
+ mkdirSync(publicDir)
+ if (existsSync(path.join(root, 'public'))) cpSync(path.join(root, 'public'), publicDir, { recursive: true })
+ cpSync(publicIcons, publicDir, { recursive: true })
+ await build({
+ root,
+ configFile: path.join(root, 'vite.config.ts'),
+ // Vite's default config bundler writes into source node_modules/.vite-temp.
+ configLoader: 'runner',
+ cacheDir: path.join(scratch, 'vite-cache'),
+ publicDir,
+ build: { outDir: product, emptyOutDir: true }
+ })
+ if (!existsSync(path.join(product, 'index.html'))) throw new Error('Web build did not produce index.html')
+ }, { source })
+ return { out, index: path.join(out, 'index.html') }
+}
+
+if (isMain(import.meta.url)) {
+ try {
+ const options = process.argv.length === 2
+ ? { source: repoRoot, icons: repoRoot, out: path.join(repoRoot, 'hermes_cli/web_dist') }
+ : frontendArgs(process.argv.slice(2), { icons: { type: 'string' } })
+ const result = await buildWeb(options)
+ console.log(`built ${result.index}`)
+ } catch (error) {
+ console.error(error)
+ process.exitCode = 1
+ }
+}
diff --git a/scripts/bundles/desktop.py b/scripts/bundles/desktop.py
index 31868318f88..37e7f06cee3 100644
--- a/scripts/bundles/desktop.py
+++ b/scripts/bundles/desktop.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import argparse
-import hashlib
import json
import os
import re
@@ -16,8 +15,6 @@ ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
-from scripts.bundles.payload import plant_surfaces, relativize_links, stage_launchers
-
def run(argv: list[str], *, cwd: Path, env: dict[str, str]) -> None:
print("bundle: " + subprocess.list2cmdline(argv), flush=True)
@@ -94,27 +91,20 @@ def build(repo: Path, tag: str | None, variant: str, builder_args: list[str],
node_arch = capture([node, "-p", "process.arch"], repo)
if node_arch != target.split("-")[1]:
raise ValueError(f"Node {node_arch} does not match build target {target}")
- stamp = json.dumps({"lock": hashlib.sha256((repo / "package-lock.json").read_bytes()).hexdigest(),
- "node": capture([node, "--version"], repo),
- "npm": capture([*npm, "--version"], repo), "target": target}, sort_keys=True)
- stamp_path = repo / "node_modules/.install-stamp"
- if not stamp_path.is_file() or stamp_path.read_text(encoding="utf-8-sig") != stamp:
- stamp_path.unlink(missing_ok=True)
- run([*npm, "ci", "--no-audit", "--no-fund", "--fetch-retries=5", "--prefer-offline"], cwd=repo, env=env)
- stamp_path.write_text(stamp, encoding="utf-8")
- # Use the installed semver implementation for package.json's actual grammar.
- run([node, "-e", "const s=require('semver'),p=require('./package.json'); for(const [n,v] of [['node',process.versions.node],['npm',process.argv[1]]]) if(!s.satisfies(v,p.engines[n])) throw Error(n+' violates '+p.engines[n])", capture([*npm, "--version"], repo)], cwd=repo, env=env)
+ workspaces = ["apps/desktop"] + ([] if variant == "light" else ["ui-tui", "web"])
+ run([node, "scripts/build/node-deps.mjs", "--source", str(repo),
+ *[arg for workspace in workspaces for arg in ("--workspace", workspace)]], cwd=repo, env=env)
payload = repo / "apps/desktop/build/agent-payload"
if variant == "light":
shutil.rmtree(payload, ignore_errors=True)
else:
- run([*npm, "run", "build", "--workspace", "ui-tui"], cwd=repo, env=env)
- run([*npm, "run", "build", "--workspace", "web"], cwd=repo, env=env)
- run([sys.executable, "-m", "pm.cli", "bundle", "--out", str(payload), "--ref", commit], cwd=repo, env=env)
- manifest = json.loads((payload / "manifest.json").read_text(encoding="utf-8-sig"))
- plant_surfaces(payload / manifest["repo"], repo)
- relativize_links(payload)
- stage_launchers(payload, manifest)
+ products = repo / "apps/desktop/build/products"
+ run([node, "scripts/generate-icons.mjs", "--source", str(repo), "--out", str(products / "icons")], cwd=repo, env=env)
+ run([node, "scripts/build/tui.mjs", "--source", str(repo), "--out", str(products / "tui")], cwd=repo, env=env)
+ run([node, "scripts/build/web.mjs", "--source", str(repo), "--icons", str(products / "icons"),
+ "--out", str(products / "web")], cwd=repo, env=env)
+ run([sys.executable, "-m", "scripts.bundles.stage", "--out", str(payload), "--ref", commit,
+ "--tui", str(products / "tui"), "--web", str(products / "web")], cwd=repo, env=env)
desktop = repo / "apps/desktop"
# Windows file-version and MSIX build-number policy remains with its packager.
version_args = []
diff --git a/scripts/bundles/native.py b/scripts/bundles/native.py
index 0053f407277..88aac8d95d7 100644
--- a/scripts/bundles/native.py
+++ b/scripts/bundles/native.py
@@ -3,9 +3,13 @@ from __future__ import annotations
import os
import shutil
+import subprocess
+import sys
+import tempfile
+import argparse
from pathlib import Path
-from pm.cli import _install_names, _run_live
+from pm.cli import _install_names
from pm.ensure import _store, _facts, _lockfile, uv as pm_uv
from pm.lock import Facts
from pm.registry import get_package, walk
@@ -74,14 +78,25 @@ def stage_pm_runtime(root: Path, uv: Path, python: Path, repo: Path, *, offline:
def stage_native(args) -> int:
- previous = os.environ.get("HERMES_RUNTIME_DIR")
- try:
- return _stage_native(args)
- finally:
- if previous is None:
- os.environ.pop("HERMES_RUNTIME_DIR", None)
- else:
- os.environ["HERMES_RUNTIME_DIR"] = previous
+ """Provision in a child with build-owned HOME/cache/PM roots."""
+ out = Path(args.out).resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "manifest.json").unlink(missing_ok=True)
+ root = Path(__file__).resolve().parents[2]
+ with tempfile.TemporaryDirectory(prefix=".build-", dir=out) as work:
+ env = {**os.environ, "HOME": work, "USERPROFILE": work,
+ "HERMES_HOME": str(Path(work) / ".hermes"),
+ "HERMES_RUNTIME_DIR": str(out / "tools"),
+ "HERMES_PYTHON_SRC_ROOT": str(root),
+ "XDG_CACHE_HOME": str(Path(work) / "cache"),
+ "XDG_CONFIG_HOME": str(Path(work) / "config"),
+ "UV_CACHE_DIR": str(Path(work) / "uv-cache"),
+ "PYTHONPATH": os.pathsep.join([str(root), *filter(None, sys.path)])}
+ command = [sys.executable, "-B", "-m", "scripts.bundles.native", "--out", str(out),
+ "--ref", args.ref or "HEAD", "--source", str(root)]
+ for name, product in getattr(args, "frontends", {}).items():
+ command += [f"--{name}", str(product)]
+ return subprocess.run(command, cwd=root, env=env).returncode
def _stage_native(args) -> int:
@@ -103,11 +118,13 @@ def _stage_native(args) -> int:
repo_dir = out / "hermes-agent"
ref = args.ref or "HEAD"
- from scripts.bundles.payload import snapshot, write_manifest, relativize_links
+ from scripts.bundles.payload import snapshot
print(f"staging repo snapshot ({ref})…", flush=True)
- snapshot(paths.repo_root(), ref, repo_dir)
-
- os.environ["HERMES_RUNTIME_DIR"] = str(store_dir)
+ snapshot(getattr(args, "source", None) or paths.repo_root(), ref, repo_dir)
+ # PM's provider code reads its adjacent lock. Never combine that tool graph
+ # with a revision selecting different pins.
+ if (repo_dir / "pm/lock.json").read_bytes() != paths.lockfile_path().read_bytes():
+ raise ValueError("selected revision's PM lock differs from the builder; use a checkout at that revision")
names = [
n for n in _bundle_package_names()
@@ -146,6 +163,8 @@ def _stage_native(args) -> int:
_store().entry(python_fact["entry"]), current_target()
)
+ if python_bin is None:
+ raise FileNotFoundError("staged Python executable is missing")
stage_pm_runtime(out, Path(uv_bin), python_bin, repo_dir)
print("✓ pm-runtime (independent locked dependencies)", flush=True)
@@ -163,16 +182,17 @@ def _stage_native(args) -> int:
# sdist builds at the machine's real toolchain.
env.setdefault("AR", "/usr/bin/ar")
env.setdefault("CC", "clang")
- for cmd in (
- [uv_bin, "venv", "--relocatable", "--python", str(python_bin), str(venv_dir)],
- [uv_bin, "sync", "--frozen", "--all-extras", "--active"],
- ):
- print(f" venv: $ {' '.join(cmd)}", flush=True)
- code, tail = _run_live(cmd, cwd=repo_dir, env=env)
- if code != 0:
- print(f"✗ venv: {' '.join(cmd[1:3])} failed:\n{tail}")
- return 1
- print("✓ venv (relocatable, all extras, on the staged interpreter)")
+ from scripts.build.python_env import build_python_environment
+ from pm.package import InstallError
+
+ cache = Path(os.environ["UV_CACHE_DIR"])
+ try:
+ build_python_environment(source=repo_dir, python=python_bin, uv=Path(uv_bin),
+ out=venv_dir, env=env, cache=cache, all_extras=True)
+ except InstallError as exc:
+ print(f"✗ venv: {exc}")
+ return 1
+ print("✓ venv (all extras, on the staged interpreter)")
# Inventory the staged interpreter before publishing the bundle contract.
from pm.features import FeatureProbeError, installed_extras, write_features
@@ -190,12 +210,10 @@ def _stage_native(args) -> int:
# mutable-venv rebuild from the bundle near-free (`uv sync --offline`
# from a warm cache probed at 0.4s vs 1.2s cold) — the blow-away-on-
# update contract depends on it.
- from pm.packages import uv_cache_dir as bundle_uv_cache_dir
-
payload_cache = out / "uv-cache"
if payload_cache.exists():
shutil.rmtree(payload_cache, ignore_errors=True)
- src_cache = bundle_uv_cache_dir()
+ src_cache = cache
if src_cache.is_dir():
print(f" uv-cache: copying {src_cache} → payload...", flush=True)
stage_uv_cache(src_cache, payload_cache)
@@ -210,12 +228,37 @@ def _stage_native(args) -> int:
if failed:
return 1
- relativize_links(out)
from scripts.bundles.payload import record_tools
recorded = {name: fact["entry"] for name in names if (fact := _facts().get(name)) and "entry" in fact}
record_tools(out, paths.lockfile_path(), current_target(), recorded)
- write_manifest(out, target=current_target(), repo="hermes-agent", ref=ref)
+ from scripts.build.agent import assemble
+ from scripts.build.inputs import AgentInputs, RESOURCE_ENV, dependency_site
+
+ assemble(AgentInputs(
+ project=repo_dir / "pyproject.toml", code=repo_dir, repo="hermes-agent",
+ placement="contained", target=current_target(), python=python_bin,
+ site_packages=dependency_site(venv_dir, python_fact["version"], current_target()), environment=venv_dir,
+ tools=store_dir, pm_runtime=out / "pm-runtime", ref=ref,
+ resources={name: repo_dir / name for name in RESOURCE_ENV},
+ frontends=getattr(args, "frontends", {}), features=out / "enabled-features.json",
+ ), out)
print(f"✓ manifest ({out / 'manifest.json'})")
return 1 if failed else 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--ref", default="HEAD")
+ parser.add_argument("--source", type=Path, required=True)
+ parser.add_argument("--tui", type=Path)
+ parser.add_argument("--web", type=Path)
+ args = parser.parse_args()
+ args.frontends = {name: path for name in ("tui", "web") if (path := getattr(args, name)) is not None}
+ return _stage_native(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/bundles/payload.py b/scripts/bundles/payload.py
index 1f0812aa22e..cfc3ccdb5bb 100644
--- a/scripts/bundles/payload.py
+++ b/scripts/bundles/payload.py
@@ -1,16 +1,14 @@
-"""Shared payload layout, source snapshots and generated launchers."""
+"""Distribution snapshots, PM facts and portable link sealing."""
from __future__ import annotations
import argparse
import json
import os
-import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
-import tomllib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
@@ -18,14 +16,6 @@ if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
-def write_manifest(root: Path, *, target: str, repo: str, ref: str | None = None) -> dict:
- manifest = {"schema": 1, "target": target, "repo": repo, "venv": "venv", "store": "tools"}
- if ref is not None:
- manifest["ref"] = ref
- (root / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
- return manifest
-
-
def snapshot(repo: Path, ref: str, destination: Path) -> None:
"""Archive a resolved git revision without carrying checkout metadata."""
repo, destination = repo.resolve(), destination.resolve()
@@ -41,10 +31,6 @@ def snapshot(repo: Path, ref: str, destination: Path) -> None:
source.extractall(destination, filter="data")
-def project_entries(repo: Path) -> dict[str, str]:
- return tomllib.loads((repo / "pyproject.toml").read_text(encoding="utf-8-sig"))["project"]["scripts"]
-
-
def record_tools(root: Path, lock_path: Path, target: str, entries: dict[str, str]) -> None:
from pm.lock import Facts, Lockfile
from pm.registry import get_package
@@ -69,21 +55,6 @@ def rehash_tools(root: Path) -> int:
return Facts(store / "facts.json", strict=True).refresh_digests(store)
-def plant_surfaces(repo: Path, source: Path, *, dashboard: bool = True) -> None:
- tui = source / "ui-tui/dist/entry.js"
- if not tui.is_file():
- raise FileNotFoundError(tui)
- destination = repo / "hermes_cli/tui_dist"
- destination.mkdir(parents=True, exist_ok=True)
- shutil.copy2(tui, destination / "entry.js")
- if dashboard:
- web = source / "hermes_cli/web_dist"
- if not (web / "index.html").is_file():
- raise FileNotFoundError(web / "index.html")
- shutil.rmtree(repo / "hermes_cli/web_dist", ignore_errors=True)
- shutil.copytree(web, repo / "hermes_cli/web_dist")
-
-
def seal_pm_runtime(root: Path, python: Path) -> dict:
"""Record a resident PM runtime without Windows' CWD-bound redirector.
@@ -157,137 +128,15 @@ def _relativize_bin_links(root: Path, directory: Path) -> int:
return count
-def render_wrapper(entry: str, repo: str, site: str) -> str:
- module, func = entry.split(":", 1)
- text = (Path(__file__).with_name("launcher_wrapper.py")).read_text(encoding="utf-8-sig")
- for key, value in {"ENTRY_MODULE": module, "ENTRY_FUNC": func, "REPO_REL": repo, "SITE_REL": site}.items():
- if '"' in value or "\n" in value or "__" in value:
- raise ValueError(f"invalid launcher value: {key}")
- text = text.replace(f"__HERMES_{key}__", value)
- unresolved = re.search(r"__HERMES_\w+?__", text)
- if unresolved:
- raise ValueError(f"unresolved launcher placeholder: {unresolved.group()}")
- return text
-
-
-def posix_launcher(name: str, entry: str, *, python: str, repo: str, site: str, target: str) -> str:
- import shlex
-
- module, func = entry.split(":", 1)
- bionic = target.endswith("-bionic")
- header = "#!/data/data/com.termux/files/usr/bin/sh" if bionic else "#!/usr/bin/env bash"
- extra = ""
- if bionic:
- extra = '''PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"
-export PREFIX
-export LD_LIBRARY_PATH="$root/tools/python/data/data/com.termux/files/usr/lib:$root/tools/node/data/data/com.termux/files/usr/lib:$root/tools/ffmpeg/data/data/com.termux/files/usr/lib:$root/runtime-libs/lib:$PREFIX/lib"
-export HERMES_PYTHON_SRC_ROOT="$REPO"
-export HERMES_PYTHON="$PYTHON"
-export HERMES_NODE="$root/tools/node/data/data/com.termux/files/usr/bin/node"
-export HERMES_RUNTIME_DIR="$root/tools"
-export PATH="$root/tools/npm/bin:$root/tools/node/data/data/com.termux/files/usr/bin:$root/tools/ffmpeg/data/data/com.termux/files/usr/bin:$root/tools/ripgrep:$PATH"
-'''
- code = f"import sys; sys.argv[0]={name!r}; from {module} import {func}; sys.exit({func}())"
- return f'''{header}
-set -eu
-self="$0"
-while [ -L "$self" ]; do
- target="$(readlink "$self")"
- case "$target" in
- /*) self="$target" ;;
- *) self="$(dirname "$self")/$target" ;;
- esac
-done
-root="$(cd "$(dirname "$self")/.." && pwd)"
-PYTHON="$root/{python}"
-REPO="$root/{repo}"
-SITE="$root/{site}"
-[ -x "$PYTHON" ] || {{ printf '%s\\n' 'Bundled interpreter missing; reinstall Hermes.' >&2; exit 2; }}
-unset PYTHONPATH PYTHONHOME
-export PYTHONPATH="$REPO:$SITE"
-export PYTHONPYCACHEPREFIX="${{PYTHONPYCACHEPREFIX:-${{XDG_CACHE_HOME:-$HOME/.cache}}/hermes-pycache}}"
-{extra}exec "$PYTHON" -P -c {shlex.quote(code)} "$@"
-'''
-
-
-def stage_launchers(root: Path, manifest: dict, *, run=subprocess.run) -> list[str]:
- from pm.lock import Facts
- from pm.registry import get_package
-
- target = manifest["target"]
- repo = root / manifest["repo"]
- entries = project_entries(repo)
- facts = Facts(root / manifest["store"] / "facts.json")
- python_fact = facts.get("python")
- if not python_fact:
- raise ValueError("payload has no Python fact")
- python = get_package("python").binary(root / manifest["store"] / python_fact["entry"], target)
- if python is None or not python.is_file():
- raise FileNotFoundError("payload interpreter missing")
- windows = target.startswith("win32")
- minor = python_fact["version"].split("+")[0].rsplit(".", 1)[0]
- site = f'{manifest["venv"]}/' + ("Lib/site-packages" if windows else f"lib/python{minor}/site-packages")
- bindir = root / "bin"
- if bindir.exists():
- shutil.rmtree(bindir)
- bindir.mkdir(parents=True, exist_ok=True)
- relative_python = python.relative_to(root).as_posix()
- for name, entry in entries.items():
- if windows:
- with tempfile.TemporaryDirectory(prefix="hermes-mint-") as temp:
- wrapper = Path(temp) / "wrapper.py"
- wrapper.write_text(render_wrapper(entry, f'../{manifest["repo"]}', f"../{site}"), encoding="utf-8")
- module, func = entry.split(":", 1)
- env = {**os.environ, "HERMES_MINT_BIN_DIR": str(bindir),
- "HERMES_MINT_SPECS": json.dumps([{"name": name, "module": module, "func": func}]),
- "HERMES_MINT_WRAPPER": str(wrapper),
- "HERMES_MINT_PYTHON": "<launcher_dir>\\..\\" + relative_python.replace("/", "\\")}
- run([str(python), str(Path(__file__).with_name("mint_launchers.py"))], env=env, check=True)
- else:
- # Termux's prefix is contractual; its venv interpreter is built at that prefix.
- launch_python = f'{manifest["venv"]}/bin/python' if target.endswith("-bionic") else relative_python
- script = posix_launcher(name, entry, python=launch_python, repo=manifest["repo"], site=site, target=target)
- output = bindir / name
- output.write_text(script, encoding="utf-8")
- output.chmod(0o755)
- # Consumers receive a completed launch contract, not a Python-layout puzzle.
- if not (root / site).is_dir():
- raise FileNotFoundError(f"payload dependency tree missing: {site}")
- commands = {name: f"bin/{name}{'.exe' if windows else ''}" for name in entries}
- for command in commands.values():
- if not (root / command).is_file():
- raise FileNotFoundError(f"payload launcher missing: {command}")
- manifest["launchers"] = list(entries)
- manifest["runtime"] = {
- "repoDir": manifest["repo"], "toolsDir": manifest["store"],
- "storePython": relative_python, "sitePackages": site, "commands": commands,
- }
- (root / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
- return list(entries)
-
-
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("action", choices=["launchers", "relocate", "surfaces", "rehash"])
+ parser.add_argument("action", choices=["relocate", "rehash"])
parser.add_argument("payload", type=Path)
- parser.add_argument("--source", type=Path, default=ROOT)
- parser.add_argument("--tui-only", action="store_true")
- parser.add_argument("--repo-dir", help="staged repository directory when no manifest exists yet")
args = parser.parse_args()
if args.action == "rehash":
print(f"rehashed {rehash_tools(args.payload)} payload tools")
- return
- if args.action == "relocate":
- relativize_links(args.payload)
- return
- if args.action == "surfaces" and args.repo_dir:
- plant_surfaces(args.payload / args.repo_dir, args.source, dashboard=not args.tui_only)
- return
- manifest = json.loads((args.payload / "manifest.json").read_text(encoding="utf-8-sig"))
- if args.action == "launchers":
- stage_launchers(args.payload.resolve(), manifest)
else:
- plant_surfaces(args.payload / manifest["repo"], args.source, dashboard=not args.tui_only)
+ relativize_links(args.payload)
if __name__ == "__main__":
diff --git a/scripts/bundles/stage.py b/scripts/bundles/stage.py
index e530e15383b..be8e478b684 100644
--- a/scripts/bundles/stage.py
+++ b/scripts/bundles/stage.py
@@ -1,29 +1,52 @@
-"""Stage the shared native payload and launchers without an Electron package."""
+"""Select complete frontend products and stage the runnable native agent."""
from __future__ import annotations
import argparse
-import json
+import shutil
+import subprocess
import sys
+import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT))
+if str(ROOT) not in sys.path:
+ sys.path.insert(0, str(ROOT))
from scripts.bundles.native import stage_native
-from scripts.bundles.payload import stage_launchers
-def main() -> int:
+def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", required=True)
parser.add_argument("--ref", default="HEAD")
- args = parser.parse_args()
- code = stage_native(args)
- if code:
- return code
- root = Path(args.out).resolve()
- manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8-sig"))
- stage_launchers(root, manifest)
- return 0
+ parser.add_argument("--tui", type=Path)
+ parser.add_argument("--web", type=Path)
+ args = parser.parse_args(argv)
+ if bool(args.tui) != bool(args.web):
+ parser.error("supply both --tui and --web products, or neither to build them")
+ out = Path(args.out).resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "manifest.json").unlink(missing_ok=True)
+ if args.tui is not None:
+ args.frontends = {"tui": args.tui.resolve(), "web": args.web.resolve()}
+ return stage_native(args)
+ node = shutil.which("node")
+ if node is None:
+ raise FileNotFoundError("Node is required to build frontend products")
+ with tempfile.TemporaryDirectory(prefix="hermes-products-") as temp:
+ products = Path(temp)
+ source = products / "source"
+ from scripts.bundles.payload import snapshot
+ snapshot(ROOT, args.ref, source)
+ commands = [
+ ["scripts/build/node-deps.mjs", "--source", str(source), "--workspace", "ui-tui", "--workspace", "web"],
+ ["scripts/generate-icons.mjs", "--source", str(source), "--out", str(products / "icons")],
+ ["scripts/build/tui.mjs", "--source", str(source), "--out", str(products / "tui")],
+ ["scripts/build/web.mjs", "--source", str(source), "--icons", str(products / "icons"), "--out", str(products / "web")],
+ ]
+ for command in commands:
+ subprocess.run([node, *command], cwd=ROOT, check=True)
+ args.frontends = {"tui": products / "tui", "web": products / "web"}
+ return stage_native(args)
if __name__ == "__main__":
diff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.py
index 84bf12a6bf4..1d1d4f27818 100644
--- a/scripts/ci/classify_changes.py
+++ b/scripts/ci/classify_changes.py
@@ -226,6 +226,8 @@ def classify(files: list[str]) -> dict[str, bool]:
python_prod = any(not _py_irrelevant(f) and not _py_test_only(f) for f in files)
frontend = any(
f.startswith(_FRONTEND) or f in _ROOT_NPM or f in _FRONTEND_FILES
+ or f.startswith("tests-js/")
+ or (f.startswith("scripts/build/") and f.endswith((".mjs", ".js", ".ts")))
for f in files
)
deps = any(f == "pyproject.toml" for f in files)
diff --git a/scripts/generate-icons.mjs b/scripts/generate-icons.mjs
index 77becb17acf..8029a890e36 100644
--- a/scripts/generate-icons.mjs
+++ b/scripts/generate-icons.mjs
@@ -14,11 +14,17 @@
*/
import { spawnSync } from 'node:child_process'
import path from 'node:path'
+import { parseArgs } from 'node:util'
import { fileURLToPath, pathToFileURL } from 'node:url'
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
export function generateIcons(args = [], { root = repoRoot, run = spawnSync, env = process.env } = {}) {
+ const { values } = parseArgs({ args, options: {
+ source: { type: 'string' }, out: { type: 'string' }, check: { type: 'boolean' }
+ } })
+ const source = path.resolve(values.source ?? root)
+ const out = path.resolve(values.out ?? source)
const childEnv = { ...env }
// Parent payload paths must not shadow the isolated build dependencies.
delete childEnv.PYTHONPATH
@@ -26,9 +32,10 @@ export function generateIcons(args = [], { root = repoRoot, run = spawnSync, env
const result = run('uv', [
'run', '--isolated', '--locked', '--only-group', 'icon-build',
// PM copies its wheel cache into payloads. Keep build wheels outside it.
- '--cache-dir', path.join(root, '.cache', 'icon-build'),
- 'python', path.join(root, 'scripts', 'generate_icons.py'), ...args
- ], { cwd: root, stdio: 'inherit', windowsHide: true, env: childEnv })
+ '--cache-dir', path.join(source, '.cache', 'icon-build'),
+ 'python', path.join(root, 'scripts', 'generate_icons.py'), '--source', source, '--out', out,
+ ...(values.check ? ['--check'] : [])
+ ], { cwd: source, stdio: 'inherit', windowsHide: true, env: childEnv })
if (result.error) {
console.error('[generate-icons] failed to launch icon generator:', result.error.message)
console.error('[generate-icons] uv is required to run the isolated icon-build group')
diff --git a/scripts/generate_icons.py b/scripts/generate_icons.py
index c65397418d8..cceb850e37f 100644
--- a/scripts/generate_icons.py
+++ b/scripts/generate_icons.py
@@ -77,6 +77,7 @@ Outputs (30 files):
from __future__ import annotations
+import argparse
import io
import re
import sys
@@ -92,17 +93,6 @@ except ImportError:
" node scripts/generate-icons.mjs"
)
-ROOT = Path(__file__).resolve().parent.parent
-ASSETS = ROOT / "assets"
-BACKGROUNDS = ASSETS / "backgrounds"
-GIRL_BLACK = ASSETS / "nous-girl-black.svg"
-GIRL_WHITE = ASSETS / "nous-girl-white.svg"
-GIRLS = {"black": GIRL_BLACK, "white": GIRL_WHITE}
-MASTER = ASSETS / "icon-master.svg"
-MASTER_DARK = ASSETS / "icon-master-dark.svg"
-
-# The squircle corner radius measured on the real 1024 icon (~245px).
-SQUIRCLE_RADIUS = 245
# The nous dark background (#0d1117) — fixed dark tile/background everywhere.
DARK_HEX = "#0d1117"
DARK_RGB = (13, 17, 23)
@@ -186,49 +176,58 @@ TARGETS: list[tuple[str, str, object]] = [
# ─── girl art extraction ────────────────────────────────────────────────────
-_path_cache: dict[str, str] = {}
-_bbox_cache: dict[str, tuple[float, float, float, float]] = {}
+class IconArt:
+ """One generation's rendering inputs and caches; never writes to source."""
+ def __init__(self, source: Path):
+ assets = source / "assets"
+ self.girls = {color: assets / f"nous-girl-{color}.svg" for color in ("black", "white")}
+ self.backgrounds = assets / "backgrounds"
+ self.paths: dict[str, str] = {}
+ self.bboxes: dict[str, tuple[float, float, float, float]] = {}
+ self.master = compose_svg(self, "black", "squircle-light.svg")
+ self.master_dark = compose_svg(self, "white", "squircle-dark.svg")
-def girl_path(girl: str) -> str:
+
+def girl_path(art: IconArt, girl: str) -> str:
"""The girl `<path>` element with editor metadata stripped (resvg rejects
undeclared inkscape/sodipodi prefixes)."""
- if girl not in _path_cache:
- src = GIRLS[girl].read_text(encoding="utf-8")
+ if girl not in art.paths:
+ src = art.girls[girl].read_text(encoding="utf-8")
m = re.search(r"<path\b.*?/>", src, re.S)
- assert m, f"no <path> found in {GIRLS[girl].name}"
+ assert m, f"no <path> found in {art.girls[girl].name}"
path = re.sub(r'\s+(inkscape|sodipodi):[a-zA-Z-]+="[^"]*"', "", m.group(0))
- _path_cache[girl] = path
- return _path_cache[girl]
+ art.paths[girl] = path
+ return art.paths[girl]
-def girl_bbox(girl: str) -> tuple[float, float, float, float]:
+def girl_bbox(art: IconArt, girl: str) -> tuple[float, float, float, float]:
"""Art bounding box in the girl SVG's coordinate space, measured by
rendering once and taking the alpha bbox (robust to art changes)."""
- if girl not in _bbox_cache:
- data = resvg_py.svg_to_bytes(svg_path=str(GIRLS[girl]), width=512, height=512)
+ if girl not in art.bboxes:
+ data = resvg_py.svg_to_bytes(svg_path=str(art.girls[girl]), width=512, height=512)
im = Image.open(io.BytesIO(data))
bx, by, bx2, by2 = im.getchannel("A").point(lambda v: 255 if v > 0 else 0).getbbox()
s = GIRL_VIEWBOX / 512.0
- _bbox_cache[girl] = (bx * s, by * s, (bx2 - bx) * s, (by2 - by) * s)
- return _bbox_cache[girl]
+ art.bboxes[girl] = (bx * s, by * s, (bx2 - bx) * s, (by2 - by) * s)
+ return art.bboxes[girl]
-def girl_layer(girl: str, box: tuple[float, float, float, float]) -> str:
+def girl_layer(art: IconArt, girl: str, box: tuple[float, float, float, float]) -> str:
"""Nested-svg layer: girl art (bbox as viewBox) placed into `box` — the
box's aspect is preserved via 'meet', so the girl never distorts."""
- bx, by, bw, bh = girl_bbox(girl)
+ bx, by, bw, bh = girl_bbox(art, girl)
x, y, w, h = box
return (
f'<svg x="{x}" y="{y}" width="{w}" height="{h}" viewBox="{bx} {by} {bw} {bh}">\n'
- f" {girl_path(girl)}\n"
+ f" {girl_path(art, girl)}\n"
" </svg>"
)
-def background_inner(name: str) -> tuple[str, int, int]:
+def background_inner(art: IconArt, name: str) -> tuple[str, int, int]:
"""Inner content + (width, height) of a background SVG asset."""
- text = (BACKGROUNDS / name).read_text(encoding="utf-8")
+ text = (art.backgrounds / name).read_text(encoding="utf-8")
m = re.search(r'<svg\b[^>]*viewBox="0 0 (\d+(?:\.\d+)?) (\d+(?:\.\d+)?)"[^>]*>', text)
assert m, f"cannot parse viewBox of {name}"
w, h = float(m.group(1)), float(m.group(2))
@@ -237,45 +236,25 @@ def background_inner(name: str) -> tuple[str, int, int]:
return inner, int(w), int(h)
-def compose_svg(girl: str, bg: str) -> str:
+def compose_svg(art: IconArt, girl: str, bg: str) -> str:
"""Full svg text: background + girl layer, in the background's native
coordinate space (resvg scales to whatever output size is requested, so
the composition is size-agnostic — no manual box scaling)."""
- inner, w, h = background_inner(bg)
+ inner, w, h = background_inner(art, bg)
return (
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}">\n'
f" {inner.strip()}\n"
- f" {girl_layer(girl, GIRL_BOXES[bg])}\n"
+ f" {girl_layer(art, girl, GIRL_BOXES[bg])}\n"
"</svg>\n"
)
-def ensure_masters(check: bool = False) -> None:
- """Write the generated light/dark masters; placeholder fallback if the
- girl art is missing."""
- missing = [p for p in (GIRL_BLACK, GIRL_WHITE) if not p.exists()]
- if missing:
- if check:
- sys.exit(f"[check] girl art missing: {[p.name for p in missing]}")
- placeholder = f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
- <rect x="0" y="0" width="1024" height="1024" rx="{SQUIRCLE_RADIUS}" fill="#ffffff"/>
- <circle cx="512" cy="512" r="420" fill="#e34c4c"/>
-</svg>
-'''
- for path in (MASTER, MASTER_DARK):
- path.write_text(placeholder, encoding="utf-8")
- print(f"[master] wrote placeholder masters ({[p.name for p in missing]})")
- return
- MASTER.write_text(compose_svg("black", "squircle-light.svg"), encoding="utf-8")
- MASTER_DARK.write_text(compose_svg("white", "squircle-dark.svg"), encoding="utf-8")
-
-
# ─── rendering ──────────────────────────────────────────────────────────────
-def render(master: Path, size: int, *, background: str | None = None) -> Image.Image:
+def render(master: str, size: int, *, background: str | None = None) -> Image.Image:
"""Render a master to an RGBA PNG of `size`x`size`."""
data = resvg_py.svg_to_bytes(
- svg_path=str(master), width=size, height=size, background=background
+ svg_string=master, width=size, height=size, background=background
)
return Image.open(io.BytesIO(data)).convert("RGBA")
@@ -309,7 +288,7 @@ def save_png(img: Image.Image, buf: io.BytesIO) -> None:
img.save(buf, "PNG", optimize=True)
-def girl_mark(kind: str, size: int) -> Image.Image:
+def girl_mark(art: IconArt, kind: str, size: int) -> Image.Image:
"""The girl in the app-icon squircle (BrandMark asset) — the mark IS the
icon shape. girl_light: black girl on white squircle. girl_dark: white
girl on #0d1117 squircle."""
@@ -317,84 +296,81 @@ def girl_mark(kind: str, size: int) -> Image.Image:
girl, bg = "black", "squircle-light.svg"
else:
girl, bg = "white", "squircle-dark.svg"
- if not GIRLS[girl].exists():
- print(f" [girl] {GIRLS[girl].name} missing — placeholder fallback")
- return render(MASTER if kind == "girl_light" else MASTER_DARK, size)
- return render_svg(compose_svg(girl, bg), size)
+ return render_svg(compose_svg(art, girl, bg), size)
-def build_logo_image(master: Path, dark: bool = False) -> Image.Image:
+def build_logo_image(art: IconArt, dark: bool = False) -> Image.Image:
"""1772x1799 wordmark: the girl alone on transparency (no frame), centered.
Light = black girl, dark = white girl — the consuming surface's background
(navbar light/dark) shows through."""
W, H = 1772, 1799
- svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">\n {girl_layer("white" if dark else "black", (0, 0, W, H))}\n</svg>\n'
+ svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">\n {girl_layer(art, "white" if dark else "black", (0, 0, W, H))}\n</svg>\n'
return render_svg(svg, (W, H))
-def target_bytes(kind: str, arg: object) -> bytes:
+def target_bytes(art: IconArt, kind: str, arg: object) -> bytes:
"""Produce the exact bytes for one target. Shared by write + check."""
if kind == "svg":
- return MASTER.read_bytes()
+ return art.master.encode("utf-8")
if kind == "svg_dark":
- return MASTER_DARK.read_bytes()
+ return art.master_dark.encode("utf-8")
if kind == "svg_copy":
- return MASTER.read_bytes()
+ return art.master.encode("utf-8")
buf = io.BytesIO()
if kind == "png":
- save_png(render(MASTER, arg), buf)
+ save_png(render(art.master, arg), buf)
elif kind == "png_dark":
- save_png(render(MASTER_DARK, arg), buf)
+ save_png(render(art.master_dark, arg), buf)
elif kind == "png_white":
- render(MASTER, arg, background="#ffffff").convert("RGB").save(buf, "PNG", optimize=True)
+ render(art.master, arg, background="#ffffff").convert("RGB").save(buf, "PNG", optimize=True)
elif kind == "png_dark_white":
- render(MASTER_DARK, arg, background=DARK_HEX).convert("RGB").save(buf, "PNG", optimize=True)
+ render(art.master_dark, arg, background=DARK_HEX).convert("RGB").save(buf, "PNG", optimize=True)
elif kind in ("girl_light", "girl_dark"):
- save_png(girl_mark(kind, arg), buf)
+ save_png(girl_mark(art, kind, arg), buf)
elif kind == "ico":
- img = render(MASTER, max(arg))
+ img = render(art.master, max(arg))
img.save(buf, format="ICO", sizes=[(s, s) for s in arg])
elif kind == "ico_dark":
- img = render(MASTER_DARK, max(arg))
+ img = render(art.master_dark, max(arg))
img.save(buf, format="ICO", sizes=[(s, s) for s in arg])
elif kind == "icns":
- img = render(MASTER, 1024)
+ img = render(art.master, 1024)
frames = [img.resize((s, s), Image.LANCZOS) for s in (16, 32, 64, 128, 256, 512, 1024)]
img.save(buf, format="ICNS", append_images=frames[1:])
elif kind == "icns_dark":
- img = render(MASTER_DARK, 1024)
+ img = render(art.master_dark, 1024)
frames = [img.resize((s, s), Image.LANCZOS) for s in (16, 32, 64, 128, 256, 512, 1024)]
img.save(buf, format="ICNS", append_images=frames[1:])
elif kind == "wide":
w, h = arg
canvas = Image.new("RGBA", (w, h), (0, 0, 0, 0))
- paste_centered(canvas, render(MASTER, 100))
+ paste_centered(canvas, render(art.master, 100))
canvas.save(buf, "PNG")
elif kind == "wide_dark":
w, h = arg
canvas = Image.new("RGBA", (w, h), (0, 0, 0, 0))
- paste_centered(canvas, render(MASTER_DARK, 100))
+ paste_centered(canvas, render(art.master_dark, 100))
canvas.save(buf, "PNG")
elif kind == "logo":
- build_logo_image(MASTER, dark=False).save(buf, "PNG")
+ build_logo_image(art, dark=False).save(buf, "PNG")
elif kind == "logo_dark":
- build_logo_image(MASTER_DARK, dark=True).save(buf, "PNG")
+ build_logo_image(art, dark=True).save(buf, "PNG")
else:
raise ValueError(f"unknown kind {kind!r}")
return buf.getvalue()
-def cmd_write() -> int:
+def cmd_write(source: Path, out: Path) -> int:
"""Return failure when any target cannot be generated or verified."""
- ensure_masters()
+ art = IconArt(source)
written = 0
failures = 0
for rel, kind, arg in TARGETS:
- path = ROOT / rel
+ path = out / rel
try:
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(target_bytes(kind, arg))
+ path.write_bytes(target_bytes(art, kind, arg))
written += 1
except Exception as exc: # noqa: BLE001 - report all, then fail
failures += 1
@@ -403,7 +379,7 @@ def cmd_write() -> int:
print("\n[verify]")
for rel, kind, arg in TARGETS:
- path = ROOT / rel
+ path = out / rel
try:
if kind in ("svg", "svg_dark", "svg_copy"):
print(f" {rel}: {path.stat().st_size} bytes SVG")
@@ -429,23 +405,23 @@ def cmd_write() -> int:
return int(failures > 0)
-def cmd_check() -> int:
+def cmd_check(source: Path, out: Path) -> int:
"""Structural verification: regenerate every target in memory and assert
the invariants that actually matter (there are no committed bytes to
byte-compare — outputs are generated on demand)."""
- ensure_masters(check=True)
+ art = IconArt(source)
problems: list[str] = []
# every target must generate without error
for rel, kind, arg in TARGETS:
try:
- target_bytes(kind, arg)
+ target_bytes(art, kind, arg)
except Exception as exc: # noqa: BLE001
problems.append(f"{rel}: REGENERATE FAILED ({exc})")
# PNG targets must have the expected format + size
for rel, (fmt, size) in CHECK_SIZES.items():
- path = ROOT / rel
+ path = out / rel
if not path.exists():
problems.append(f"{rel}: MISSING (expected generated file)")
continue
@@ -464,7 +440,7 @@ def cmd_check() -> int:
"apps/desktop/public/nous-girl-dark.png",
"apps/desktop/public/apple-touch-icon.png",
):
- path = ROOT / rel
+ path = out / rel
if not path.exists():
continue
alpha = Image.open(path).convert("RGBA").getchannel("A")
@@ -490,7 +466,7 @@ def cmd_check() -> int:
("apps/desktop/assets/icon-dark.ico", [16, 24, 32, 48, 64, 128, 256]),
("apps/bootstrap-installer/src-tauri/icons/icon.ico", [16, 32, 64, 128, 256]),
):
- path = ROOT / rel
+ path = out / rel
if not path.exists():
problems.append(f"{rel}: MISSING")
continue
@@ -512,9 +488,15 @@ def cmd_check() -> int:
def main() -> None:
- if "--check" in sys.argv:
- sys.exit(cmd_check())
- sys.exit(cmd_write())
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", type=Path, default=Path(__file__).resolve().parent.parent)
+ parser.add_argument("--out", type=Path, help="Output root (defaults to source for developer builds)")
+ parser.add_argument("--check", action="store_true")
+ args = parser.parse_args()
+ source = args.source.resolve()
+ out = (args.out or source).resolve()
+ command = cmd_check if args.check else cmd_write
+ sys.exit(command(source, out))
if __name__ == "__main__":
diff --git a/scripts/termux/build.py b/scripts/termux/build.py
new file mode 100644
index 00000000000..1d0e085f0f9
--- /dev/null
+++ b/scripts/termux/build.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+"""Build the TUI and package a prepared bionic payload as a Termux .deb.
+
+Tool staging and wheelhouse preparation remain separate prerequisites. This
+sequence owns only the shared frontend build and the native .deb handoff.
+"""
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+import subprocess
+import sys
+
+if __package__ in (None, ""):
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+from scripts.releases.commit_build import require_commit
+from scripts.termux.deb_version import deb_version_for_tag
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
+ parser.add_argument("--repo", type=Path, required=True)
+ parser.add_argument("--payload", type=Path, required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ identity = parser.add_mutually_exclusive_group(required=True)
+ identity.add_argument("--tag")
+ identity.add_argument("--commit")
+ args = parser.parse_args(argv)
+
+ try:
+ if args.tag is not None:
+ deb_version_for_tag(args.tag)
+ else:
+ require_commit(args.commit)
+ except ValueError as exc:
+ parser.error(str(exc))
+
+ repo, payload, out = (path.resolve() for path in (args.repo, args.payload, args.out))
+ for option, path in (("--repo", repo), ("--payload", payload)):
+ if not path.is_dir():
+ parser.error(f"{option} must name an existing directory: {path}")
+ product = repo / ".build/termux/tui"
+ revision = ["--tag", args.tag] if args.tag is not None else ["--commit", args.commit]
+ commands = [
+ ["node", str(repo / "scripts/build/node-deps.mjs"),
+ "--source", str(repo), "--workspace", "ui-tui"],
+ ["node", str(repo / "scripts/build/tui.mjs"),
+ "--source", str(repo), "--out", str(product)],
+ ["bash", str(repo / "scripts/termux/build_deb.sh"),
+ "--repo", str(repo), "--payload", str(payload), "--out", str(out),
+ "--tui-product", str(product), *revision],
+ ]
+ try:
+ for command in commands:
+ subprocess.run(command, cwd=repo, check=True)
+ except subprocess.CalledProcessError as exc:
+ return exc.returncode
+ except OSError as exc:
+ print(f"termux build: {exc}", file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/termux/build_deb.sh b/scripts/termux/build_deb.sh
index fdbef23a5c4..f17a26a5548 100644
--- a/scripts/termux/build_deb.sh
+++ b/scripts/termux/build_deb.sh
@@ -34,8 +34,9 @@ TAG=""
COMMIT_MODE=""
PAYLOAD=""
OUT=""
+TUI_PRODUCT=""
-usage() { printf 'usage: build_deb.sh --repo <dir> (--tag <tag> | --commit <full-sha>) --payload <dir> --out <dir>\n' >&2; exit 2; }
+usage() { printf 'usage: build_deb.sh --repo <dir> (--tag <tag> | --commit <full-sha>) --payload <dir> --tui-product <dir> --out <dir>\n' >&2; exit 2; }
log() { printf '\n==> %s\n' "$*"; }
fail() { printf 'build_deb: FAILED: %s\n' "$*" >&2; exit 1; }
@@ -45,6 +46,7 @@ while [ "$#" -gt 0 ]; do
--tag) TAG="${2:?}"; shift 2 ;;
--commit) COMMIT_MODE="${2:?}"; shift 2 ;;
--payload) PAYLOAD="${2:?}"; shift 2 ;;
+ --tui-product) TUI_PRODUCT="${2:?}"; shift 2 ;;
--out) OUT="${2:?}"; shift 2 ;;
*) usage ;;
esac
@@ -89,6 +91,9 @@ else
COMMIT="$(git -C "$REPO_ABS" rev-parse --verify "refs/tags/$TAG^{commit}")" \
|| fail "tag $TAG not found in $REPO_ABS"
fi
+[ -n "$TUI_PRODUCT" ] || fail "--tui-product is required (run scripts/termux/build.py)"
+TUI_PRODUCT="$(cd "$TUI_PRODUCT" && pwd)"
+[ -f "$TUI_PRODUCT/dist/entry.js" ] && [ -f "$TUI_PRODUCT/package.json" ] || fail "incomplete TUI product"
for d in python node uv npm ffmpeg ripgrep runtime-libs app wheelhouse; do
[ -d "$PAYLOAD_ABS/$d" ] || fail "payload missing $d/ -- run termux_build.sh + build_cpython.sh + build_node.sh first"
done
@@ -198,10 +203,6 @@ seal_pm_runtime(root, python)
# to route hermes update -> pkg upgrade remediation.
printf 'apt\n' > "$PAYLOAD_ABS/app/.install_method"
-# [3] Entry functions come from the archived project's script declarations.
-log "Writing trampolines"
-python3 "$HERE/launchers.py" --payload "$PAYLOAD_ABS"
-
# The shared stamp writer records the apt-termux update owner.
# Commit mode exports HERMES_BUILD_COMMIT and leaves the tag empty.
log "Writing app/install-stamp.json"
@@ -229,8 +230,8 @@ mkdir -p "$STAGE/DEBIAN" "$DEST/tools"
for tool in python node uv npm ffmpeg ripgrep; do
cp -a "$PAYLOAD_ABS/$tool" "$DEST/tools/"
done
-cp -a "$PAYLOAD_ABS/runtime-libs" "$PAYLOAD_ABS/app" "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/pm-runtime" "$PAYLOAD_ABS/bin" "$DEST/"
-python3 "$HERE/payload_facts.py" "$DEST" "$PAYLOAD_ABS/.work/build_set.txt"
+cp -a "$PAYLOAD_ABS/runtime-libs" "$PAYLOAD_ABS/app" "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/pm-runtime" "$DEST/"
+python3 "$HERE/payload_facts.py" "$DEST" "$PAYLOAD_ABS/.work/build_set.txt" --tui-product "$TUI_PRODUCT"
python3 "$HERE/launchers.py" --payload "$DEST" --control "$STAGE/DEBIAN"
diff --git a/scripts/termux/launchers.py b/scripts/termux/launchers.py
index d6d77024998..7c4b4b90df1 100644
--- a/scripts/termux/launchers.py
+++ b/scripts/termux/launchers.py
@@ -1,35 +1,14 @@
-"""Emit Termux entrypoints and package-manager hooks from declared scripts."""
+"""APT maintainer hooks; agent entrypoints belong to scripts.build.launchers."""
from __future__ import annotations
import argparse
from pathlib import Path
import shlex
-import tomllib
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
-def write_launchers(payload: Path, entries: dict[str, str]) -> None:
- from scripts.bundles.payload import posix_launcher
-
- lock = payload / "app/pm/lock.json"
- if lock.is_file():
- import json
- version = json.loads(lock.read_text(encoding="utf-8-sig"))["packages"]["python"]["version"]
- minor = version.split("+")[0].rsplit(".", 1)[0]
- else:
- minor = f"{sys.version_info.major}.{sys.version_info.minor}"
- bindir = payload / "bin"
- bindir.mkdir(parents=True, exist_ok=True)
- for name, entry in entries.items():
- text = posix_launcher(name, entry, python="venv/bin/python", repo="app",
- site=f"venv/lib/python{minor}/site-packages", target="linux-arm64-bionic")
- path = bindir / name
- path.write_text(text, encoding="utf-8")
- path.chmod(0o755)
-
-
def write_maintainer_scripts(control: Path, names: list[str]) -> None:
names_text = " ".join(shlex.quote(name) for name in names)
postinst = '''#!/data/data/com.termux/files/usr/bin/sh
@@ -72,12 +51,11 @@ done
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--payload", type=Path, required=True)
- parser.add_argument("--control", type=Path)
+ parser.add_argument("--control", type=Path, required=True)
args = parser.parse_args()
- entries = tomllib.loads((args.payload / "app/pyproject.toml").read_text(encoding="utf-8"))["project"]["scripts"]
- write_launchers(args.payload, entries)
- if args.control is not None:
- write_maintainer_scripts(args.control, list(entries))
+ from scripts.build.inputs import project_entries
+ entries = project_entries(args.payload / "app/pyproject.toml")
+ write_maintainer_scripts(args.control, list(entries))
if __name__ == "__main__":
diff --git a/scripts/termux/payload_facts.py b/scripts/termux/payload_facts.py
index 17612db6c0e..5f419335ef5 100644
--- a/scripts/termux/payload_facts.py
+++ b/scripts/termux/payload_facts.py
@@ -1,4 +1,4 @@
-"""Record the staged bionic tools through pm's existing facts contract."""
+"""Record bionic tools and assemble the prepared fixed-prefix agent."""
from __future__ import annotations
import argparse
@@ -9,21 +9,38 @@ import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+def write_facts(payload: Path, lock_path: Path, build_set: Path, tui: Path) -> None:
+ from pm.lock import Lockfile
+ from pm.registry import get_package
+ from scripts.bundles.payload import record_tools
+ from scripts.build.agent import assemble
+ from scripts.build.inputs import AgentInputs, RESOURCE_ENV, dependency_site
-
-def write_facts(payload: Path, lock_path: Path, build_set: Path) -> None:
+ payload = payload.resolve()
target = "linux-arm64-bionic"
- from scripts.bundles.payload import record_tools
record_tools(payload, lock_path, target, {name: name for name in ("python", "node", "uv", "npm", "ffmpeg", "ripgrep")})
natives = [line.strip() for line in build_set.read_text(encoding="utf-8").splitlines() if line.strip()]
(payload / "native-wheels.json").write_text(json.dumps(natives) + "\n", encoding="utf-8")
- from scripts.bundles.payload import write_manifest
- write_manifest(payload, target=target, repo="app")
+ # This is the target pin, never the host's sys.version_info or sysconfig.
+ version = Lockfile(lock_path).version("python")
+ python = get_package("python").binary(payload / "tools/python", target)
+ if version is None or python is None:
+ raise ValueError("bionic Python pin/executable missing")
+ repo = payload / "app"
+ assemble(AgentInputs(
+ project=repo / "pyproject.toml", code=repo, repo="app", placement="fixed", target=target,
+ python=python,
+ site_packages=dependency_site(payload / "venv", version, target),
+ environment=payload / "venv", tools=payload / "tools", pm_runtime=payload / "pm-runtime",
+ resources={name: repo / name for name in RESOURCE_ENV}, frontends={"tui": tui.resolve()},
+ stamp=repo / "install-stamp.json",
+ ), payload)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("payload", type=Path)
parser.add_argument("build_set", type=Path)
+ parser.add_argument("--tui-product", type=Path, required=True)
args = parser.parse_args()
- write_facts(args.payload, args.payload / "app/pm/lock.json", args.build_set)
+ write_facts(args.payload, args.payload / "app/pm/lock.json", args.build_set, args.tui_product)
diff --git a/tests-js/desktop-builder.test.mjs b/tests-js/desktop-builder.test.mjs
new file mode 100644
index 00000000000..cc421abc386
--- /dev/null
+++ b/tests-js/desktop-builder.test.mjs
@@ -0,0 +1,102 @@
+import { execFileSync } from 'node:child_process'
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterEach, expect, test } from 'vitest'
+import { stageGetWindows, stageNodePtyInto } from '../apps/desktop/scripts/stage-native-deps.mjs'
+
+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const roots = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+function put(path, text) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text) }
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), 'desktop build with spaces-'))
+ roots.push(root)
+ const source = join(root, 'source')
+ const app = join(source, 'apps/desktop')
+ put(join(app, 'package.json'), '{"type":"module"}')
+ put(join(app, 'vite.config.mjs'), 'export default { base: "./", build: { minify: false } }')
+ put(join(app, 'index.html'), '<html><div id="app"></div><script type="module" src="/src/index.js"></script></html>')
+ put(join(app, 'src/index.js'), 'document.getElementById("app").textContent = "built renderer"')
+ put(join(app, 'electron/main.ts'), 'console.log(JSON.stringify({ stamp: __HERMES_INSTALL_STAMP__, identity: __HERMES_PRODUCT_IDENTITY__ }))')
+ put(join(app, 'electron/preload.ts'), 'globalThis.fixturePreload = "compiled preload"')
+ cpSync(join(repo, 'apps/desktop/product-identity.cjs'), join(app, 'product-identity.cjs'))
+ symlinkSync(join(repo, 'node_modules'), join(app, 'node_modules'), 'junction')
+ const icons = join(root, 'icons')
+ put(join(icons, 'apps/desktop/public/apple-touch-icon.png'), 'fresh icon')
+ put(join(app, 'public/apple-touch-icon.png'), 'stale icon')
+ const nativeDeps = join(root, 'native')
+ // The native input is the real host binding, not a fake compiler/dependency.
+ stageNodePtyInto(join(repo, 'node_modules/node-pty'), join(nativeDeps, 'node-pty'))
+ stageGetWindows({ source: repo, out: nativeDeps })
+ const stamp = join(root, 'install-stamp.json')
+ put(stamp, JSON.stringify({ schemaVersion: 1, payload: 'light', updateMechanism: 'external', commit: 'a'.repeat(40), tag: 'v1.2.3' }))
+ return { source, out: join(root, 'result'), icons, nativeDeps, stamp }
+}
+function files(root, dir = root) {
+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
+ const path = join(dir, entry.name)
+ if (entry.isDirectory()) return files(root, path)
+ return entry.isFile() ? [[path.slice(root.length), readFileSync(path).toString('base64')]] : []
+ })
+}
+
+test('desktop compiler consumes explicit immutable inputs, replaces variants, and preserves the last product on failure', async () => {
+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')
+ const input = fixture()
+ const before = files(input.source)
+ await buildDesktop(input)
+ expect(files(input.source)).toEqual(before)
+ expect(readFileSync(join(input.out, 'apple-touch-icon.png'), 'utf8')).toBe('fresh icon')
+ expect(existsSync(join(input.out, 'assets'))).toBe(true)
+ expect(existsSync(join(input.out, 'electron-preload.js'))).toBe(true)
+ expect(files(join(input.out, 'node_modules/node-pty')).some(([name]) => name.endsWith('.node'))).toBe(true)
+ const run = () => JSON.parse(execFileSync(process.execPath, [join(input.out, 'electron-main.mjs')], { cwd: tmpdir(), encoding: 'utf8' }))
+ expect(run().identity.light).toBe(true)
+ put(input.stamp, JSON.stringify({ schemaVersion: 1, payload: 'bundled', updateMechanism: 'microsoft-store', commit: 'b'.repeat(40), tag: null }))
+ // Ambient variant/tag must not override explicit stamp inputs or cached CJS identity.
+ execFileSync(process.execPath, [join(repo, 'scripts/build/desktop.mjs'), ...Object.entries(input).flatMap(([key, value]) => [`--${key === 'nativeDeps' ? 'native-deps' : key}`, value])], {
+ cwd: tmpdir(), env: { ...process.env, PATH: '', HERMES_DESKTOP_VARIANT: 'light', HERMES_PAYLOAD_TAG: 'v1.0.0-canary.20260911' }, stdio: 'pipe',
+ })
+ expect(run().identity.store).toBe(true)
+ expect(run().identity.light).toBe(false)
+ expect(run().stamp.commit).toBe('b'.repeat(40))
+ const built = files(input.out)
+ put(join(input.source, 'apps/desktop/electron/main.ts'), 'THIS IS NOT TYPESCRIPT !!!')
+ await expect(buildDesktop(input)).rejects.toThrow()
+ expect(files(input.out)).toEqual(built)
+ expect(files(input.source).some(([name]) => name.includes('.vite') || name.endsWith('tsbuildinfo'))).toBe(false)
+}, 60000)
+
+test('native preparation stages the selected source into an explicit tree before compilation', async () => {
+ const { prepareDesktopNativeDependencies } = await import('../apps/desktop/scripts/stage-native-deps.mjs')
+ const input = fixture()
+ const nativeOut = join(dirname(input.out), 'prepared-native')
+ await prepareDesktopNativeDependencies({ source: input.source, out: nativeOut })
+ expect(existsSync(join(nativeOut, 'node-pty/package.json'))).toBe(true)
+ expect(files(join(nativeOut, 'node-pty')).some(([name]) => name.endsWith('.node'))).toBe(true)
+ expect(existsSync(join(input.source, 'apps/desktop/dist'))).toBe(false)
+})
+
+test('typecheck uses scratch state and incomplete prepared inputs fail before publication', async () => {
+ const { buildDesktop } = await import('../scripts/build/desktop.mjs')
+ const input = fixture()
+ put(join(input.source, 'apps/desktop/tsconfig.json'), JSON.stringify({ compilerOptions: { composite: true, skipLibCheck: true, types: [] }, include: ['src/*.ts'] }))
+ put(join(input.source, 'apps/desktop/src/typed.ts'), 'export const value: string = "valid"')
+ await buildDesktop({ ...input, typecheck: true })
+ const built = files(input.out)
+ expect(files(input.source).some(([name]) => name.endsWith('.tsbuildinfo') || name.endsWith('typed.js'))).toBe(false)
+ put(join(input.source, 'apps/desktop/src/typed.ts'), 'export const value: string = 123')
+ await expect(buildDesktop({ ...input, typecheck: true })).rejects.toThrow()
+ expect(files(input.out)).toEqual(built)
+ rmSync(join(input.icons, 'apps/desktop/public/apple-touch-icon.png'))
+ await expect(buildDesktop(input)).rejects.toThrow(/icon/i)
+ expect(files(input.out)).toEqual(built)
+ await expect(buildDesktop({ ...input, out: join(input.source, 'apps/desktop/scripts') })).rejects.toThrow(/overlap/)
+ put(join(input.icons, 'apps/desktop/public/apple-touch-icon.png'), 'fresh icon')
+ rmSync(join(input.nativeDeps, 'node-pty/build'), { recursive: true, force: true })
+ rmSync(join(input.nativeDeps, 'node-pty/prebuilds'), { recursive: true, force: true })
+ await expect(buildDesktop(input)).rejects.toThrow(/native binding/)
+ expect(files(input.out)).toEqual(built)
+}, 30000)
diff --git a/tests-js/generate-icons.test.mjs b/tests-js/generate-icons.test.mjs
index 90a49056371..59d796a13e9 100644
--- a/tests-js/generate-icons.test.mjs
+++ b/tests-js/generate-icons.test.mjs
@@ -10,11 +10,21 @@ test('icon builds use only the locked build group outside every application venv
expect(run).toHaveBeenCalledExactlyOnceWith('uv', [
'run', '--isolated', '--locked', '--only-group', 'icon-build',
'--cache-dir', path.join(root, '.cache', 'icon-build'),
- 'python', path.join(root, 'scripts', 'generate_icons.py'), '--check'
+ 'python', path.join(root, 'scripts', 'generate_icons.py'), '--source', root, '--out', root, '--check'
], { cwd: root, stdio: 'inherit', windowsHide: true, env: { PATH: 'tools', UV_PYTHON: env.UV_PYTHON, VIRTUAL_ENV: 'runtime-venv' } })
expect(env.PYTHONPATH).toBe('payload-libraries')
})
+test('icon preparation passes explicit source and independent output roots', () => {
+ const run = vi.fn(() => ({ status: 0 }))
+ const source = path.resolve('source with spaces')
+ const out = path.resolve('icon outputs')
+ expect(generateIcons(['--source', source, '--out', out], { run })).toBe(0)
+ const [, args, options] = run.mock.calls[0]
+ expect(args.slice(-4)).toEqual(['--source', source, '--out', out])
+ expect(options.cwd).toBe(source)
+})
+
test('failed icon processes cannot report a successful build', () => {
expect(generateIcons([], { run: () => ({ status: 7 }), env: {} })).toBe(7)
expect(generateIcons([], { run: () => ({ status: null, signal: 'SIGTERM' }), env: {} })).toBe(1)
diff --git a/tests-js/node-deps.test.mjs b/tests-js/node-deps.test.mjs
new file mode 100644
index 00000000000..cd1f017de15
--- /dev/null
+++ b/tests-js/node-deps.test.mjs
@@ -0,0 +1,65 @@
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterEach, expect, test } from 'vitest'
+import { npmCommand } from '../scripts/build/node-deps.mjs'
+
+const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const roots = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+function json(path, value) {
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, JSON.stringify(value))
+}
+
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), 'node union with spaces-'))
+ roots.push(root)
+ json(join(root, 'package.json'), { name: 'fixture', private: true, dependencies: { 'root-only': 'file:vendor/root-only' }, workspaces: ['ui-tui', 'web', 'apps/desktop'], engines: { node: '>=22', npm: '>=10' } })
+ for (const name of ['tui-only', 'web-only', 'root-only']) {
+ json(join(root, 'vendor', name, 'package.json'), { name, version: '1.0.0', main: 'index.cjs' })
+ writeFileSync(join(root, 'vendor', name, 'index.cjs'), `module.exports = '${name}'`)
+ }
+ json(join(root, 'ui-tui/package.json'), { name: 'tui', version: '1.0.0', dependencies: { 'tui-only': 'file:../vendor/tui-only' } })
+ json(join(root, 'web/package.json'), { name: 'web', version: '1.0.0', dependencies: { 'web-only': 'file:../vendor/web-only' } })
+ json(join(root, 'apps/desktop/package.json'), { name: 'desktop', version: '1.0.0', scripts: { postinstall: 'node -e "require(\'fs\').writeFileSync(\'electron-provisioned\',\'yes\')"' } })
+ const [node, npm] = npmCommand()
+ execFileSync(node, [npm, 'install', '--package-lock-only', '--ignore-scripts', '--no-audit', '--no-fund', '--offline'], { cwd: root, env: { ...process.env, npm_config_cache: join(root, '.npm-cache') }, stdio: 'pipe' })
+ return root
+}
+
+test('one locked preparation retains the requested union without provisioning desktop', async () => {
+ const { prepareNodeDependencies } = await import('../scripts/build/node-deps.mjs')
+ const source = fixture()
+ const lock = readFileSync(join(source, 'package-lock.json'))
+ await prepareNodeDependencies({ source, workspaces: ['ui-tui', 'web', 'ui-tui'], env: { ...process.env, npm_config_offline: 'true', npm_config_cache: join(source, '.npm-cache') } })
+ for (const [workspace, name] of [['ui-tui', 'tui-only'], ['web', 'web-only']]) {
+ expect(createRequire(join(source, workspace, 'package.json'))(name)).toBe(name)
+ }
+ expect(createRequire(join(source, 'package.json'))('root-only')).toBe('root-only')
+ expect(existsSync(join(source, 'node_modules/desktop'))).toBe(false)
+ expect(existsSync(join(source, 'apps/desktop/electron-provisioned'))).toBe(false)
+ expect(readFileSync(join(source, 'package-lock.json'))).toEqual(lock)
+ execFileSync(process.execPath, [join(repo, 'scripts/build/node-deps.mjs'), '--source', source, '--workspace', 'ui-tui', '--workspace', 'web'], { cwd: tmpdir(), env: { ...process.env, npm_config_offline: 'true', npm_config_cache: join(source, '.npm-cache') }, stdio: 'pipe' })
+ expect(createRequire(join(source, 'web/package.json'))('web-only')).toBe('web-only')
+}, 30000)
+
+test('web-only selection excludes siblings and rejects stale locks without rewriting them', async () => {
+ const { prepareNodeDependencies } = await import('../scripts/build/node-deps.mjs')
+ const source = fixture()
+ const env = { ...process.env, npm_config_offline: 'true', npm_config_cache: join(source, '.npm-cache') }
+ rmSync(join(source, 'apps/desktop'), { recursive: true })
+ prepareNodeDependencies({ source, workspaces: ['web'], env })
+ expect(existsSync(join(source, 'node_modules/tui-only'))).toBe(false)
+ expect(existsSync(join(source, 'apps/desktop/electron-provisioned'))).toBe(false)
+ const lock = readFileSync(join(source, 'package-lock.json'))
+ json(join(source, 'web/package.json'), { name: 'web', version: '1.0.0', dependencies: { 'web-only': '9.0.0' } })
+ expect(() => prepareNodeDependencies({ source, workspaces: ['web'], env })).toThrow()
+ expect(readFileSync(join(source, 'package-lock.json'))).toEqual(lock)
+ expect(() => prepareNodeDependencies({ source, workspaces: [], env })).toThrow(/workspace/)
+ expect(() => prepareNodeDependencies({ source, workspaces: ['missing'], env })).toThrow(/workspace/)
+}, 30000)
diff --git a/tests-js/product-builders.test.mjs b/tests-js/product-builders.test.mjs
new file mode 100644
index 00000000000..d7589130ef3
--- /dev/null
+++ b/tests-js/product-builders.test.mjs
@@ -0,0 +1,219 @@
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, symlinkSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { createRequire } from 'node:module'
+import { fileURLToPath } from 'node:url'
+import { afterEach, expect, test } from 'vitest'
+import { buildTui } from '../scripts/build/tui.mjs'
+import { buildWeb } from '../scripts/build/web.mjs'
+import { productOutput, publishDirectory, withProduct } from '../scripts/build/frontend-common.mjs'
+
+const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const require = createRequire(import.meta.url)
+const temporary = []
+afterEach(() => { for (const dir of temporary.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+function fixture() {
+ const dir = mkdtempSync(path.join(tmpdir(), 'product builders '))
+ temporary.push(dir)
+ return dir
+}
+function put(root, name, content) {
+ const file = path.join(root, name)
+ mkdirSync(path.dirname(file), { recursive: true })
+ writeFileSync(file, content)
+}
+function dependency(root, workspace, name) {
+ const target = path.dirname(require.resolve(`${name}/package.json`))
+ const link = path.join(root, workspace, 'node_modules', name)
+ mkdirSync(path.dirname(link), { recursive: true })
+ symlinkSync(target, link, 'junction')
+}
+function webSource(source) {
+ put(source, 'package.json', '{"private":true,"type":"module"}')
+ put(source, 'web/package.json', '{"type":"module"}')
+ put(source, 'web/index.html', '<html><head><link rel="icon" href="/favicon.ico"></head><body><script type="module" src="/src/main.ts"></script></body></html>')
+ put(source, 'web/src/main.ts', 'import { answer } from "./value"; document.body.textContent = answer;')
+ put(source, 'web/src/value.ts', 'export const answer: string = "prepared web";')
+ put(source, 'web/tsconfig.json', JSON.stringify({ files: [], references: [{ path: './tsconfig.app.json' }] }))
+ put(source, 'web/tsconfig.app.json', JSON.stringify({ compilerOptions: { target: 'ES2022', module: 'ESNext', types: [], noEmit: true, tsBuildInfoFile: './node_modules/.tmp/app.tsbuildinfo' }, include: ['src'] }))
+ put(source, 'web/vite.config.ts', 'import { defineConfig } from "vite"; export default defineConfig({base: "/dashboard/", build: {outDir: "should-not-be-used"}});')
+ put(source, 'web/public/retained.txt', 'retained public asset')
+ put(source, 'web/public/favicon.ico', 'stale source icon')
+}
+
+test('product outputs exclude the source tree except supported generated destinations', async () => {
+ const inputs = ['ui-tui', 'apps/shared', 'node_modules']
+ // Only call the read-only validator on real source paths: never publish here.
+ for (const name of ['pm', 'hermes_cli', 'scripts', 'pyproject.toml', '.git', 'tools', '.build', 'apps/desktop/build/products']) {
+ expect(() => productOutput(repo, path.join(repo, name), inputs), name).toThrow(/output/i)
+ }
+ const base = fixture()
+ const source = path.join(base, 'source')
+ mkdirSync(source)
+ for (const name of ['new-source-file', 'pm/generated', 'hermes_cli/web_dist-copy', 'apps/desktop/dist-copy', 'apps/desktop/build/native-deps-copy', 'hermes_cli/web_dist/assets']) {
+ expect(() => productOutput(source, path.join(source, name), inputs), name).toThrow(/output/i)
+ }
+ for (const name of ['hermes_cli/web_dist', 'apps/desktop/dist', 'apps/desktop/build/native-deps', 'apps/desktop/build/products/tui', 'apps/desktop/build/products/web', '.build/web', '.build/termux/tui']) {
+ const out = path.join(source, name)
+ expect(productOutput(source, out, inputs).out).toBe(out)
+ expect(existsSync(out)).toBe(false)
+ await withProduct(out, product => put(product, 'built.txt', 'product'))
+ expect(productOutput(source, out, inputs).out).toBe(out)
+ }
+ const adjacent = path.join(base, 'web-product')
+ expect(productOutput(source, adjacent, inputs).out).toBe(adjacent)
+ // Ownership never exempts a directory from source/input protection.
+ const sourceDir = path.join(source, 'pm')
+ await withProduct(sourceDir, product => put(product, 'keep.txt', 'source'))
+ expect(() => productOutput(source, sourceDir, inputs)).toThrow(/output/i)
+ const generatedInput = path.join(source, '.build/web')
+ expect(() => productOutput(source, generatedInput, ['.build/web'])).toThrow(/overlap/)
+ symlinkSync(sourceDir, path.join(source, '.build/redirect'), 'junction')
+ symlinkSync(sourceDir, path.join(base, 'source-alias'), 'junction')
+ for (const alias of [path.join(source, '.build/redirect'), path.join(base, 'source-alias')]) {
+ expect(() => productOutput(source, path.join(alias, 'output'), inputs)).toThrow(/output/i)
+ }
+})
+
+test('publication replaces only builder-owned directories and rechecks ownership after compilation', async () => {
+ const base = fixture()
+ const source = path.join(base, 'source')
+ mkdirSync(source)
+ const unowned = path.join(base, 'unowned')
+ put(unowned, 'keep.txt', 'not a product')
+ mkdirSync(path.join(base, 'empty'))
+ put(base, 'file', 'not a directory')
+ symlinkSync(unowned, path.join(base, 'link'), 'junction')
+ symlinkSync(path.join(base, 'absent'), path.join(base, 'dangling'), 'junction')
+ const inTree = path.join(source, '.build/unowned')
+ put(inTree, 'keep.txt', 'not a product either')
+ for (const out of [unowned, path.join(base, 'empty'), path.join(base, 'file'), path.join(base, 'link'), path.join(base, 'dangling'), inTree]) {
+ expect(() => productOutput(source, out, []), out).toThrow(/output/i)
+ let compiled = false
+ await expect(withProduct(out, () => { compiled = true })).rejects.toThrow(/output/i)
+ expect(compiled).toBe(false)
+ }
+ const staged = path.join(base, 'staged')
+ put(staged, 'new.txt', 'new product')
+ expect(() => publishDirectory(staged, unowned)).toThrow(/output/i)
+ expect(readFileSync(path.join(unowned, 'keep.txt'), 'utf8')).toBe('not a product')
+ expect(readFileSync(path.join(staged, 'new.txt'), 'utf8')).toBe('new product')
+
+ const out = path.join(base, 'product')
+ await withProduct(out, product => put(product, 'old.txt', 'old product'))
+ expect(productOutput(source, out, []).out).toBe(out)
+ await withProduct(out, product => put(product, 'new.txt', 'new product'))
+ expect(existsSync(path.join(out, 'old.txt'))).toBe(false)
+ await expect(withProduct(out, () => { throw new Error('compile failed') })).rejects.toThrow('compile failed')
+ expect(readFileSync(path.join(out, 'new.txt'), 'utf8')).toBe('new product')
+
+ const occupied = path.join(base, 'occupied-during-build')
+ await expect(withProduct(occupied, product => {
+ put(product, 'new.txt', 'new product')
+ put(occupied, 'keep.txt', 'created by someone else')
+ })).rejects.toThrow(/output/i)
+ expect(readFileSync(path.join(occupied, 'keep.txt'), 'utf8')).toBe('created by someone else')
+})
+
+test('existing npm build directories can be rebuilt without adopting arbitrary outputs', async () => {
+ const source = fixture()
+ for (const name of ['ui-tui/dist', 'hermes_cli/web_dist', 'apps/desktop/dist', 'apps/desktop/build/native-deps']) {
+ const out = path.join(source, name)
+ put(out, 'old-output', 'previous compiler output')
+ await withProduct(out, product => put(product, 'new-output', 'rebuilt'), { source })
+ expect(existsSync(path.join(out, 'old-output'))).toBe(false)
+ expect(readFileSync(path.join(out, 'new-output'), 'utf8')).toBe('rebuilt')
+ }
+ const unrelated = path.join(source, 'pm')
+ put(unrelated, 'keep', 'source')
+ await expect(withProduct(unrelated, () => {}, { source })).rejects.toThrow(/output/i)
+})
+
+test('web compiles with prepared icons and workspace-local tools without writing source or tsbuildinfo', async () => {
+ const { readdirSync, lstatSync } = await import('node:fs')
+ function snapshot(dir) {
+ return Object.fromEntries(readdirSync(dir, { recursive: true }).sort().map(name => {
+ const file = path.join(dir, name)
+ const stat = lstatSync(file)
+ return [name, stat.isFile() ? readFileSync(file).toString('base64') : 'directory or link']
+ }))
+ }
+ const base = fixture()
+ const source = path.join(base, 'source with spaces')
+ const icons = path.join(base, 'prepared icons')
+ webSource(source)
+ dependency(source, 'web', 'typescript')
+ dependency(source, 'web', 'vite')
+ put(icons, 'web/public/favicon.ico', 'prepared icon bytes')
+ const before = snapshot(source)
+ const out = path.join(base, 'web output')
+ execFileSync(process.execPath, [path.join(repo, 'scripts/build/web.mjs'), '--source', source, '--icons', icons, '--out', out], { cwd: base })
+ expect(readFileSync(path.join(out, 'favicon.ico'), 'utf8')).toBe('prepared icon bytes')
+ expect(readFileSync(path.join(out, 'retained.txt'), 'utf8')).toBe('retained public asset')
+ expect(readFileSync(path.join(out, 'index.html'), 'utf8')).toContain('/dashboard/assets/')
+ expect(snapshot(source)).toEqual(before)
+ const second = path.join(base, 'second output')
+ await buildWeb({ source, icons, out: second })
+ expect(readFileSync(path.join(second, 'index.html'))).toEqual(readFileSync(path.join(out, 'index.html')))
+}, 30_000)
+
+test('web rejects missing icons and compiler failures without publishing stale success', async () => {
+ const base = fixture()
+ const source = path.join(base, 'source')
+ const icons = path.join(base, 'icons')
+ const out = path.join(base, 'web')
+ webSource(source)
+ dependency(source, '', 'typescript')
+ dependency(source, '', 'vite')
+ await expect(buildWeb({ source, icons, out })).rejects.toThrow(/icon/i)
+ expect(existsSync(out)).toBe(false)
+ put(icons, 'web/public/favicon.ico', 'prepared icon')
+ await buildWeb({ source, icons, out })
+ const previous = readFileSync(path.join(out, 'index.html'))
+ put(source, 'web/src/value.ts', 'export const answer: string = 42;')
+ await expect(buildWeb({ source, icons, out })).rejects.toThrow(/TypeScript/)
+ expect(readFileSync(path.join(out, 'index.html'))).toEqual(previous)
+ put(source, 'web/src/value.ts', 'export const answer: string = "valid";')
+ put(source, 'web/index.html', '<script type="module" src="/missing-entry.js"></script>')
+ await expect(buildWeb({ source, icons, out })).rejects.toThrow()
+ expect(readFileSync(path.join(out, 'index.html'))).toEqual(previous)
+}, 30_000)
+
+function tuiSource(source) {
+ put(source, 'package.json', '{"private":true}')
+ put(source, 'ui-tui/package.json', '{"type":"module"}')
+ put(source, 'ui-tui/src/entry.tsx', '#!/usr/bin/env node\nimport { answer } from "@hermes/ink"; console.log(answer);')
+ put(source, 'ui-tui/packages/hermes-ink/src/entry-exports.ts', 'import devtools from "react-devtools-core"; devtools.initialize(); export const answer: string = "prepared source";')
+}
+
+test('TUI uses prepared workspace-local tools from an unrelated cwd and publishes a relocatable module product', () => {
+ const base = fixture()
+ const source = path.join(base, 'source with spaces')
+ tuiSource(source)
+ dependency(source, 'ui-tui', 'esbuild')
+ const out = path.join(base, 'product one')
+ execFileSync(process.execPath, [path.join(repo, 'scripts/build/tui.mjs'), '--source', source, '--out', out], { cwd: base })
+ expect(JSON.parse(readFileSync(path.join(out, 'package.json'), 'utf8')).type).toBe('module')
+ const entry = path.join(out, 'dist/entry.js')
+ expect(readFileSync(entry, 'utf8').startsWith('#!')).toBe(false)
+ rmSync(source, { recursive: true })
+ expect(execFileSync(process.execPath, [entry], { cwd: base, encoding: 'utf8' }).trim()).toBe('prepared source')
+})
+
+test('TUI failure does not publish or disturb a previous product, and missing prepared tools fail clearly', async () => {
+ const base = fixture()
+ const source = path.join(base, 'source')
+ tuiSource(source)
+ const out = path.join(base, 'out')
+ await expect(buildTui({ source, out })).rejects.toThrow(/esbuild.*prepared|prepared.*esbuild/i)
+ expect(existsSync(out)).toBe(false)
+ dependency(source, '', 'esbuild')
+ await buildTui({ source, out })
+ const previous = readFileSync(path.join(out, 'dist/entry.js'))
+ put(source, 'ui-tui/src/entry.tsx', 'const broken = ;')
+ await expect(buildTui({ source, out })).rejects.toThrow()
+ expect(readFileSync(path.join(out, 'dist/entry.js'))).toEqual(previous)
+ await expect(buildTui({ source, out: source })).rejects.toThrow(/output/i)
+ expect(existsSync(path.join(source, 'ui-tui/src/entry.tsx'))).toBe(true)
+})
diff --git a/tests/ci/test_classify_changes.py b/tests/ci/test_classify_changes.py
index 7a6a89b2976..02bcfeb40c0 100644
--- a/tests/ci/test_classify_changes.py
+++ b/tests/ci/test_classify_changes.py
@@ -80,6 +80,8 @@ def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_
CASES = {
+ "shared JS builder → frontend": (["scripts/build/web.mjs"], _lanes(python=True, frontend=True)),
+ "root JS tests → frontend": (["tests-js/product-builders.test.mjs"], _lanes(python=True, frontend=True)),
"docs-only → nothing heavy": (["README.md", "docs/guide.md"], _lanes()),
"python source → python": (["run_agent.py"], _lanes(python=True, scan=True)),
# pyproject.toml declares the pytest markers the OS lanes select on, so it
diff --git a/tests/ci/test_desktop_release_commit_admission.py b/tests/ci/test_desktop_release_commit_admission.py
index a16d1ca5b2f..feef73e3d10 100644
--- a/tests/ci/test_desktop_release_commit_admission.py
+++ b/tests/ci/test_desktop_release_commit_admission.py
@@ -73,7 +73,7 @@ def test_trusted_dispatch_admits_a_pushed_feature_without_switching_checkout(tmp
'stream.write(json.dumps(sys.argv[1:])+"\\n")\nprint("write")\n'
)
if os.name == 'nt':
- from scripts.bundles.mint_launchers import mint_one
+ from scripts.build.mint_launchers import mint_one
mint_one(str(helper), sys.executable, code, {'name': 'gh', 'module': 'fixture', 'func': 'main'})
else:
module = helper / 'gh.py'
diff --git a/tests/docker/test_image_payload.py b/tests/docker/test_image_payload.py
index 17753741544..24cf846f59c 100644
--- a/tests/docker/test_image_payload.py
+++ b/tests/docker/test_image_payload.py
@@ -39,6 +39,9 @@ with Image.open('/opt/hermes/hermes_cli/web_dist/favicon.ico') as image:
assert image.width > 0 and image.height > 0
assert importlib.util.find_spec('resvg_py') is None
assert not Path('/opt/hermes/.cache/icon-build').exists()
+assert not Path('/opt/hermes/node_modules/vite').exists()
+assert not Path('/opt/hermes/node_modules/esbuild').exists()
+assert Path('/opt/hermes/node_modules/typescript/bin/tsc').is_file()
"""
result = subprocess.run(
["docker", "run", "--rm", "--network", "none", "--user", "hermes",
diff --git a/tests/pm/test_environment_build.py b/tests/pm/test_environment_build.py
new file mode 100644
index 00000000000..809aecdf4dd
--- /dev/null
+++ b/tests/pm/test_environment_build.py
@@ -0,0 +1,427 @@
+"""Real, offline uv construction below PM selection and distribution packaging."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import zipfile
+
+import pytest
+
+
+def _wheel(directory: Path, name: str, version: str = "1.0", requirements=()) -> Path:
+ metadata = f"{name}-{version}.dist-info"
+ entries = {
+ f"{name}/__init__.py": f"__version__ = {version!r}\n",
+ f"{metadata}/METADATA": f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"
+ + "".join(f"Requires-Dist: {requirement}\n" for requirement in requirements),
+ f"{metadata}/WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
+ }
+ entries[f"{metadata}/RECORD"] = "".join(f"{path},,\n" for path in entries)
+ wheel = directory / f"{name}-{version}-py3-none-any.whl"
+ with zipfile.ZipFile(wheel, "w") as archive:
+ for path, body in entries.items():
+ archive.writestr(path, body)
+ return wheel
+
+
+def _run(command, *, cwd: Path, env: dict) -> str:
+ result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True, timeout=60)
+ assert result.returncode == 0, result.stderr
+ return result.stdout.strip()
+
+
+def locked_project(tmp_path):
+ uv = shutil.which("uv")
+ assert uv, "environment construction tests require uv on PATH"
+ source = tmp_path / "source with spaces"
+ source.mkdir()
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ for name in ("base_dep", "member_dep", "chosen_dep", "other_dep"):
+ _wheel(wheels, name)
+ (source / "pyproject.toml").write_text(
+ '[project]\nname="construction-root"\nversion="1"\nrequires-python=">=3.11"\n'
+ 'dependencies=["base-dep==1.0"]\n'
+ '[project.optional-dependencies]\nchosen=["chosen-dep==1.0"]\nother=["other-dep==1.0"]\n'
+ '[tool.uv]\npackage=false\nno-index=true\n'
+ f'find-links=[{json.dumps(wheels.as_posix())}]\n'
+ '[tool.uv.workspace]\nmembers=["member"]\n', encoding="utf-8",
+ )
+ member = source / "member"
+ member.mkdir()
+ (member / "pyproject.toml").write_text(
+ '[project]\nname="plugin-member"\nversion="1"\nrequires-python=">=3.11"\n'
+ 'dependencies=["member-dep==1.0"]\n[tool.uv]\npackage=false\n', encoding="utf-8",
+ )
+ home = tmp_path / "isolated-home"
+ home.mkdir()
+ config = tmp_path / "config"
+ config.mkdir()
+ env = {key: value for key, value in os.environ.items()
+ if not key.startswith(("UV_", "PYTHON")) and key != "VIRTUAL_ENV"}
+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(home / ".hermes"),
+ XDG_CONFIG_HOME=str(config), XDG_CONFIG_DIRS=str(config),
+ UV_CACHE_DIR=str(tmp_path / "cache"), UV_PYTHON=sys.executable, UV_OFFLINE="1")
+ _run([uv, "lock", "--python", sys.executable], cwd=source, env=env)
+ return source, Path(uv), env
+
+
+def installable_project(locked_project):
+ source, uv, env = locked_project
+ metadata = source / "pyproject.toml"
+ metadata.write_text(metadata.read_text().replace("package=false", "package=true") +
+ '\n[build-system]\nrequires=[]\nbuild-backend="local_backend"\nbackend-path=["."]\n')
+ (source / "root_app.py").write_text("VALUE = 'installed from the explicit source'\n")
+ # A local PEP 517/660 backend: no registry or build-tool downloads in this fixture.
+ (source / "local_backend.py").write_text('''
+from pathlib import Path
+from zipfile import ZipFile
+
+def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
+ Path("root_app.py").read_text() # Full builds require the application source layer.
+ name = "construction_root-1-py3-none-any.whl"
+ dist = "construction_root-1.dist-info"
+ entries = {
+ "construction_root.pth": str(Path.cwd()) + "\\n",
+ dist + "/METADATA": "Metadata-Version: 2.1\\nName: construction-root\\nVersion: 1\\nRequires-Dist: base-dep==1.0\\n",
+ dist + "/WHEEL": "Wheel-Version: 1.0\\nRoot-Is-Purelib: true\\nTag: py3-none-any\\n",
+ }
+ entries[dist + "/RECORD"] = "".join(path + ",,\\n" for path in entries)
+ with ZipFile(Path(wheel_directory) / name, "w") as wheel:
+ for path, body in entries.items():
+ wheel.writestr(path, body)
+ return name
+
+build_editable = build_wheel
+''')
+ _run([str(uv), "lock", "--python", sys.executable], cwd=source, env=env)
+ return source, uv, env
+
+
+def test_native_provider_builds_all_extras_at_explicit_destination(installable_project, tmp_path, monkeypatch):
+ from scripts.build.python_env import build_python_environment
+ import pm.paths
+ import pm.workspace
+
+ source, uv, env = installable_project
+ monkeypatch.setattr(pm.paths, "repo_root", lambda: pytest.fail("implicit source"))
+ monkeypatch.setattr(pm.workspace, "enabled_member_dirs", lambda: pytest.fail("user plugins"))
+ before = dict(os.environ)
+ locked = (source / "uv.lock").read_bytes()
+ executable = build_python_environment(
+ source=source, python=Path(sys.executable), uv=uv, out=tmp_path / "native environment",
+ cache=tmp_path / "cache", env=env, all_extras=True, offline=True,
+ )
+ assert _run([str(executable), "-I", "-c",
+ "import root_app, member_dep, chosen_dep, other_dep; print(root_app.VALUE)"],
+ cwd=tmp_path, env=env) == "installed from the explicit source"
+ assert executable.parent.parent == tmp_path / "native environment"
+ assert (source / "uv.lock").read_bytes() == locked
+ assert dict(os.environ) == before
+ assert not Path(env["HERMES_HOME"]).exists()
+
+
[email protected]("extra_flags, expected", [
+ (["--extra", "chosen", "--extra", "chosen"], [True, False]),
+ (["--all-extras"], [True, True]),
+ ([], [False, False]),
+])
+def test_cli_dependency_only_needs_no_application_source(installable_project, tmp_path, extra_flags, expected):
+ source, uv, env = installable_project
+ (source / "root_app.py").unlink()
+ (source / "local_backend.py").unlink()
+ locked = (source / "uv.lock").read_bytes()
+ repo = Path(__file__).resolve().parents[2]
+ executable = _run(
+ [sys.executable, "-m", "scripts.build.python_env", "--source", str(source),
+ "--python", sys.executable, "--uv", str(uv), "--out", str(tmp_path / "docker env"),
+ "--no-install-project", "--offline", *extra_flags],
+ cwd=tmp_path, env={**env, "PYTHONPATH": str(repo)},
+ )
+ assert executable, "CLI must return the verified environment executable"
+ result = json.loads(_run(
+ [executable, "-I", "-c", "import json, importlib.util, importlib.metadata, base_dep; "
+ "print(json.dumps([importlib.util.find_spec('chosen_dep') is not None, "
+ "importlib.util.find_spec('other_dep') is not None, "
+ "'construction-root' in [d.metadata['Name'] for d in importlib.metadata.distributions()]]))"],
+ cwd=tmp_path, env=env,
+ ))
+ assert result == [*expected, False]
+ assert (source / "uv.lock").read_bytes() == locked
+ assert not Path(env["HERMES_HOME"]).exists()
+
+
+def test_child_output_is_live_and_keeps_explicit_index_credentials(tmp_path):
+ import io
+ from pm.environment import PythonEnvironment
+
+ released = tmp_path / "release-child"
+
+ class AcknowledgingLog(io.StringIO):
+ def write(self, text):
+ if "child-started" in text:
+ released.touch()
+ return super().write(text)
+
+ output = AcknowledgingLog()
+ child_env = dict(os.environ, UV_INDEX_PRIVATE_USERNAME="fixture-user",
+ UV_INDEX_PRIVATE_PASSWORD="fixture-secret",
+ UV_DEFAULT_INDEX="https://fixture.invalid/simple")
+ environment = PythonEnvironment(
+ uv=Path(sys.executable), python=Path(sys.executable), destination=tmp_path / "venv",
+ cache=tmp_path / "cache", env=child_env, output=output,
+ )
+ script = (
+ "import os, time; from pathlib import Path; "
+ "print('child-started', flush=True); "
+ f"release = Path({str(released)!r}); deadline = time.monotonic() + 5\n"
+ "while not release.exists() and time.monotonic() < deadline: time.sleep(.01)\n"
+ "assert release.exists(), 'log was hidden until process exit'\n"
+ "assert os.environ['UV_INDEX_PRIVATE_USERNAME'] == 'fixture-user'\n"
+ "assert os.environ['UV_INDEX_PRIVATE_PASSWORD'] == 'fixture-secret'\n"
+ "assert os.environ['UV_DEFAULT_INDEX'] == 'https://fixture.invalid/simple'\n"
+ "print('child-complete', flush=True)\n"
+ )
+ result = environment._run(["-c", script], cwd=tmp_path, timeout=10)
+ assert result.returncode == 0, result.stderr
+ assert "child-started" in output.getvalue()
+ assert "child-complete" in output.getvalue()
+ assert "child-complete" in result.stderr, "failure diagnostics must retain a bounded output tail"
+
+
[email protected]("parent_exits", [True, False])
+def test_streaming_deadline_includes_inherited_stdout(tmp_path, parent_exits):
+ import io
+ import threading
+ import time
+ from pm.environment import PythonEnvironment
+
+ release = tmp_path / "release-descendant"
+ finished = tmp_path / "descendant-finished"
+ output = io.StringIO()
+ environment = PythonEnvironment(
+ uv=Path(sys.executable), python=Path(sys.executable), destination=tmp_path / "venv",
+ cache=tmp_path / "cache", env=dict(os.environ), output=output,
+ )
+ # The descendant inherits stdout even when the direct child has already exited.
+ # Its finite lifetime also bounds this regression on the broken implementation.
+ descendant = (
+ "import time; from pathlib import Path; "
+ "print('inherited-output', flush=True); "
+ f"release = Path({str(release)!r}); deadline = time.monotonic() + 10\n"
+ "while not release.exists() and time.monotonic() < deadline: time.sleep(.01)\n"
+ f"Path({str(finished)!r}).touch()\n"
+ )
+ parent = (
+ "import subprocess, sys; "
+ f"child = subprocess.Popen([sys.executable, '-c', {descendant!r}]); "
+ + ("sys.exit(0)" if parent_exits else "child.wait()")
+ )
+ threads_before = set(threading.enumerate())
+ timeout = 2
+ started = time.monotonic()
+ try:
+ with pytest.raises(subprocess.TimeoutExpired):
+ environment._run(["-c", parent], cwd=tmp_path, timeout=timeout)
+ assert time.monotonic() - started < timeout + 2, "draining stdout restarted the timeout"
+ assert "inherited-output" in output.getvalue()
+ assert set(threading.enumerate()) <= threads_before, "timeout leaked an output reader"
+ finally:
+ # Cooperatively stop the orphan: its parent is no longer in the test subtree.
+ release.touch()
+ deadline = time.monotonic() + 5
+ while not finished.exists() and time.monotonic() < deadline:
+ time.sleep(.01)
+ assert finished.exists(), "descendant did not acknowledge cleanup"
+ # Clean up even a broken implementation's reader after closing its writer.
+ for thread in set(threading.enumerate()) - threads_before:
+ thread.join(timeout=5)
+
+
+def test_streaming_eof_does_not_restart_process_wait_timeout(tmp_path):
+ import io
+ import time
+ from pm.environment import PythonEnvironment
+
+ output = io.StringIO()
+ environment = PythonEnvironment(
+ uv=Path(sys.executable), python=Path(sys.executable), destination=tmp_path / "venv",
+ cache=tmp_path / "cache", env=dict(os.environ), output=output,
+ )
+ # Spend most of the budget before EOF, then leave the process alive without
+ # any pipe writers. Waiting for exit must use only the remaining budget.
+ script = (
+ "import os, time; print('before-eof', flush=True); time.sleep(3); "
+ "os.close(1); os.close(2); time.sleep(10)"
+ )
+ timeout = 4
+ started = time.monotonic()
+ with pytest.raises(subprocess.TimeoutExpired) as error:
+ environment._run(["-c", script], cwd=tmp_path, timeout=timeout)
+ assert time.monotonic() - started < timeout + 2, "EOF restarted the process wait budget"
+ assert error.value.timeout == timeout
+ assert "before-eof" in output.getvalue()
+
+
[email protected]("damage", ["source", "check", "lock"])
+def test_failed_build_removes_only_its_candidate(installable_project, tmp_path, damage):
+ from scripts.build.python_env import build_python_environment
+ from pm.package import InstallError
+
+ source, uv, env = installable_project
+ previous = tmp_path / "previous"
+ executable = build_python_environment(source=source, python=Path(sys.executable), uv=uv,
+ out=previous, env=env, offline=True)
+ cfg = (previous / "pyvenv.cfg").read_bytes()
+ source_lock = (source / "uv.lock").read_bytes()
+ if damage == "source":
+ (source / "root_app.py").unlink()
+ elif damage == "check":
+ backend = source / "local_backend.py"
+ backend.write_text(backend.read_text().replace("base-dep==1.0", "base-dep==2.0"))
+ # Same-size edits within one timestamp tick otherwise reuse the backend's .pyc.
+ shutil.rmtree(source / "__pycache__", ignore_errors=True)
+ else:
+ (source / "uv.lock").unlink()
+ candidate = tmp_path / "candidate"
+ with pytest.raises(InstallError, match="dependency validation" if damage == "check" else "uv sync"):
+ build_python_environment(source=source, python=Path(sys.executable), uv=uv,
+ out=candidate, env=env, cache=tmp_path / "cold-cache", offline=True)
+ assert not candidate.exists()
+ with pytest.raises(FileExistsError):
+ build_python_environment(source=source, python=Path(sys.executable), uv=uv,
+ out=previous, env=env, offline=True)
+ assert (previous / "pyvenv.cfg").read_bytes() == cfg
+ assert _run([str(executable), "-I", "-c", "import base_dep; print(base_dep.__version__)"],
+ cwd=tmp_path, env=env) == "1.0"
+ if damage != "lock":
+ assert (source / "uv.lock").read_bytes() == source_lock
+ else:
+ assert not (source / "uv.lock").exists(), "frozen builds must not manufacture a lock"
+
+
+def test_explicit_environment_installs_locked_members_without_live_selection(locked_project, tmp_path, monkeypatch):
+ from pm.environment import PythonEnvironment
+ import pm.paths
+ import pm.workspace
+
+ source, uv, env = locked_project
+ before_lock = (source / "uv.lock").read_bytes()
+ before_process = dict(os.environ)
+ before_env = dict(env)
+ # Supplying a prepared workspace must bypass live roots and plugin discovery.
+ monkeypatch.setattr(pm.paths, "repo_root", lambda: pytest.fail("implicit source lookup"))
+ monkeypatch.setattr(pm.workspace, "enabled_member_dirs", lambda: pytest.fail("profile discovery"))
+ environment = PythonEnvironment(
+ uv=uv, python=Path(sys.executable), destination=tmp_path / "candidate",
+ cache=tmp_path / "cache", env=env,
+ )
+ environment.create()
+ environment.sync(source, extras=["chosen"])
+ environment.check()
+ result = json.loads(_run(
+ [str(environment.executable), "-I", "-c",
+ "import sys, json, base_dep, member_dep, chosen_dep, importlib.util; "
+ "print(json.dumps([sys.base_prefix, member_dep.__version__, "
+ "importlib.util.find_spec('other_dep') is None]))"], cwd=tmp_path, env=env,
+ ))
+ assert result == [sys.base_prefix, "1.0", True]
+ assert (source / "uv.lock").read_bytes() == before_lock
+ assert not (source / ".venv").exists()
+ assert not (Path(env["HERMES_HOME"])).exists()
+ assert env == before_env
+ assert dict(os.environ) == before_process
+
+
+def test_explicit_workspace_preserves_seed_and_replays_copied_members(locked_project, tmp_path, monkeypatch):
+ from pm.environment import PythonEnvironment
+ import pm.workspace as workspace
+
+ source, uv, env = locked_project
+ project = source / "pyproject.toml"
+ project.write_text(project.read_text().replace(
+ '[tool.uv.workspace]\nmembers=["member"]\n', "",
+ ).replace('base-dep==1.0', 'base-dep>=1,<2'))
+ _run([str(uv), "lock", "--python", sys.executable], cwd=source, env=env)
+ seed_bytes = (source / "uv.lock").read_bytes()
+ _wheel(tmp_path / "wheels", "base_dep", "1.1")
+ original_member = source / "member"
+ before_member = (original_member / "pyproject.toml").read_bytes()
+ monkeypatch.setattr(workspace.paths, "repo_root", lambda: pytest.fail("implicit source discovery"))
+ monkeypatch.setattr(workspace, "enabled_member_dirs", lambda: pytest.fail("profile discovery"))
+
+ first = PythonEnvironment(uv=uv, python=Path(sys.executable), destination=tmp_path / "first" / "venv",
+ cache=tmp_path / "cache", env=env, offline=True)
+ first.create()
+ workspace.lock_and_sync(
+ [original_member], ["chosen"], source=source, root=tmp_path / "first" / "workspace",
+ venv_dir=first.destination, environment=first, seed_lock=source / "uv.lock",
+ )
+ first.check()
+ assert _run([str(first.executable), "-I", "-c", "import base_dep, member_dep; print(base_dep.__version__)"],
+ cwd=tmp_path, env=env) == "1.0", "compatible seed must not be upgraded"
+ assert (source / "uv.lock").read_bytes() == seed_bytes
+ assert (original_member / "pyproject.toml").read_bytes() == before_member
+ recorded = tmp_path / "first" / "workspace"
+ recorded_lock = (recorded / "uv.lock").read_bytes()
+
+ # Repair replays recorded inputs, not today's edited source/plugins.
+ (original_member / "pyproject.toml").write_text("broken plugin TOML")
+ project.write_text("broken source TOML")
+ second = PythonEnvironment(uv=uv, python=Path(sys.executable), destination=tmp_path / "second" / "venv",
+ cache=tmp_path / "cache", env=env, offline=True)
+ second.create()
+ workspace.lock_and_sync(
+ [], ["chosen"], source=source, root=tmp_path / "second" / "workspace",
+ venv_dir=second.destination, environment=second, replay=recorded,
+ )
+ second.check()
+ assert _run([str(second.executable), "-I", "-c", "import member_dep, chosen_dep; print(member_dep.__version__)"],
+ cwd=tmp_path, env=env) == "1.0"
+ assert (tmp_path / "second" / "workspace" / "uv.lock").read_bytes() == recorded_lock
+ assert (recorded / "uv.lock").read_bytes() == recorded_lock
+
+
+def test_live_apply_keeps_selection_on_failed_union(locked_project, tmp_path, monkeypatch):
+ import importlib
+ from hermes_cli.runtime_paths import runtime_facts_path, selected_venv
+ from pm.lock import Facts
+ from pm.packages import Venv
+ import pm.paths
+ from pm.workspace import ResolutionConflict
+
+ source, uv, env = locked_project
+ metadata = source / "pyproject.toml"
+ metadata.write_text(metadata.read_text().replace('[tool.uv.workspace]\nmembers=["member"]\n', ""))
+ _run([str(uv), "lock", "--python", sys.executable], cwd=source, env=env)
+ source_lock = (source / "uv.lock").read_bytes()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "isolated-home")
+ monkeypatch.setenv("HERMES_HOME", env["HERMES_HOME"])
+ monkeypatch.setattr(pm.paths, "repo_root", lambda: source)
+ # Tool acquisition is the adapter's job; the same prepared env is not mutated.
+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv", lambda **kwargs: (str(uv), env))
+ original_env = dict(env)
+ prepared = Venv().apply(["chosen"], plugin_dirs=[source / "member"])
+ assert env == original_env
+ assert selected_venv(source) == source / "venv", "preparation must not select the candidate"
+ assert (prepared["environment"].parent / ".lease-managed").is_file()
+ facts = Facts(runtime_facts_path(source))
+ facts.record_state("venv", "fixture-stamp", ["chosen"], **prepared)
+ prior_facts = facts.path.read_bytes()
+ generations = prepared["environment"].parent.parent
+ prior_generations = set(generations.iterdir())
+ plugin = source / "member" / "pyproject.toml"
+ plugin.write_text(plugin.read_text().replace('member-dep==1.0', 'member-dep==2.0'))
+ with pytest.raises(ResolutionConflict):
+ Venv().apply(["chosen"], plugin_dirs=[source / "member"])
+ assert selected_venv(source) == prepared["environment"]
+ assert facts.path.read_bytes() == prior_facts
+ assert set(generations.iterdir()) == prior_generations
+ assert (source / "uv.lock").read_bytes() == source_lock
+ assert env == original_env
diff --git a/tests/pm/test_recovery.py b/tests/pm/test_recovery.py
index a2f0ec301e7..5997b5f52e1 100644
--- a/tests/pm/test_recovery.py
+++ b/tests/pm/test_recovery.py
@@ -15,6 +15,12 @@ from pm.lock import Facts
from pm.packages import uv_env
from tests.pm.test_workspace_build_inputs import _wheel
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
@pytest.mark.parametrize("failure", [None, "missing_distribution", "broken_module"])
def test_startup_validation_checks_real_ruamel_dependency(tmp_path, failure):
diff --git a/tests/pm/test_recovery_validation.py b/tests/pm/test_recovery_validation.py
index f56e47d5240..e172aec5490 100644
--- a/tests/pm/test_recovery_validation.py
+++ b/tests/pm/test_recovery_validation.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import importlib
import importlib.metadata
import os
+from pathlib import Path
import shutil
import sys
@@ -13,6 +14,12 @@ from pm.package import InstallError
from pm.packages import uv_env
from pm.recovery import validate_environment
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
@pytest.mark.parametrize("damage", ["module", "distribution"])
def test_validation_rejects_a_missing_required_import(tmp_path, monkeypatch, damage):
diff --git a/tests/pm/test_runtime_transaction.py b/tests/pm/test_runtime_transaction.py
index c745de289db..a8e36b92091 100644
--- a/tests/pm/test_runtime_transaction.py
+++ b/tests/pm/test_runtime_transaction.py
@@ -7,6 +7,12 @@ import pytest
from pm.lock import Facts
from pm.package import InstallError
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
@pytest.mark.parametrize("failure", ["build", "record", "missing", None])
def test_sync_commits_only_a_successful_candidate(tmp_path, monkeypatch, failure):
diff --git a/tests/pm/test_startup_recovery.py b/tests/pm/test_startup_recovery.py
index 7fd81708764..2027b75defd 100644
--- a/tests/pm/test_startup_recovery.py
+++ b/tests/pm/test_startup_recovery.py
@@ -16,6 +16,12 @@ from pm.packages import uv_env
from pm.store import current_target, sha256_file, tree_digest
from tests.pm.test_workspace_build_inputs import _wheel
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
@pytest.mark.parametrize("marker_name", [".update-incomplete", ".lazy-refresh-incomplete", None, "manual", "baseline"])
def test_bootstrap_repairs_before_dependency_activation(tmp_path, monkeypatch, marker_name):
diff --git a/tests/pm/test_union_installs_members.py b/tests/pm/test_union_installs_members.py
index 155c4166293..a0c04ad8868 100644
--- a/tests/pm/test_union_installs_members.py
+++ b/tests/pm/test_union_installs_members.py
@@ -18,6 +18,12 @@ import pytest
import pm.workspace as ws
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
def _site_packages(venv: Path) -> Path:
"""The fixture supplies this interpreter as the PM toolchain."""
diff --git a/tests/pm/test_uv_cache.py b/tests/pm/test_uv_cache.py
index 4322619b525..d5d102ad092 100644
--- a/tests/pm/test_uv_cache.py
+++ b/tests/pm/test_uv_cache.py
@@ -8,6 +8,12 @@ import pytest
import pm.packages as pkgs
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
def test_uv_env_pins_cache_dir(monkeypatch, tmp_path):
monkeypatch.setattr(pkgs, "uv_cache_dir", lambda: tmp_path / "c")
diff --git a/tests/pm/test_uv_python.py b/tests/pm/test_uv_python.py
index 6b8566d722b..44679a06b73 100644
--- a/tests/pm/test_uv_python.py
+++ b/tests/pm/test_uv_python.py
@@ -15,6 +15,12 @@ from pm.package import InstallError
from pm.packages import Python, Uv
from pm.store import current_target
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
@pytest.fixture
def installed_uv(tmp_path, monkeypatch):
diff --git a/tests/pm/test_venv_sync_ambient_config.py b/tests/pm/test_venv_sync_ambient_config.py
index 6e97c821151..f2aac6a6a94 100644
--- a/tests/pm/test_venv_sync_ambient_config.py
+++ b/tests/pm/test_venv_sync_ambient_config.py
@@ -23,6 +23,12 @@ from pathlib import Path
import pytest
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
def _write_project(root: Path) -> None:
"""A project whose [tool.uv] the lock depends on: hide it and uv
rejects the lock (the #82446 shape)."""
diff --git a/tests/pm/test_workspace.py b/tests/pm/test_workspace.py
index 6a361b7f02a..321bc30f372 100644
--- a/tests/pm/test_workspace.py
+++ b/tests/pm/test_workspace.py
@@ -20,6 +20,12 @@ import pytest
import pm.workspace as ws
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
@pytest.fixture
def layout(tmp_path, monkeypatch):
"""A fake install: core repo with pyproject, plugin dirs, store."""
@@ -343,7 +349,7 @@ def test_changed_root_seeds_from_committed_lock_unchanged_keeps_extended(
stdout = ""
monkeypatch.setattr(importlib.import_module("pm.ensure"), "uv",
- lambda **kwargs: ("uv", {"UV_PYTHON": "pm-python"}))
+ lambda **kwargs: ("uv", {"UV_PYTHON": "pm-python", "UV_CACHE_DIR": str(tmp_path / "cache")}))
monkeypatch.setattr(ws.subprocess, "run", lambda cmd, **k: FakeProc())
root = ws.workspace_root()
diff --git a/tests/pm/test_workspace_build_inputs.py b/tests/pm/test_workspace_build_inputs.py
index e89304024c2..fc5700340bc 100644
--- a/tests/pm/test_workspace_build_inputs.py
+++ b/tests/pm/test_workspace_build_inputs.py
@@ -12,6 +12,12 @@ from pm import workspace
from pm.packages import uv_env
[email protected](autouse=True)
+def isolated_machine_home(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+
+
def test_real_build_inputs_stay_in_generated_root(tmp_path, monkeypatch):
core = tmp_path / "core"
core.mkdir()
diff --git a/tests/scripts/test_agent_build.py b/tests/scripts/test_agent_build.py
new file mode 100644
index 00000000000..33192d1355c
--- /dev/null
+++ b/tests/scripts/test_agent_build.py
@@ -0,0 +1,306 @@
+"""Prepared inputs become runnable products without acquiring dependencies."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def inputs_fixture(tmp_path):
+ source = tmp_path / "prepared source"
+ source.mkdir()
+ (source / "pyproject.toml").write_text(
+ '[project]\nname="assembly-fixture"\nversion="1.2.3"\n'
+ '[project.scripts]\nprobe="entry:main"\n', encoding="utf-8")
+ (source / "entry.py").write_text(
+ "import json, os, sys\nfrom pathlib import Path\nimport dependency\n"
+ "from importlib.metadata import version\n"
+ "def main():\n print(json.dumps([sys.argv[1:], dependency.VALUE, "
+ "version('assembly-fixture'), (Path(__file__).parent/'skills/data').read_text()]))\n"
+ " return 7\n", encoding="utf-8")
+ (source / "skills").mkdir()
+ (source / "skills/data").write_text("resource", encoding="utf-8")
+ out = tmp_path / "payload"
+ python = out / "tools/python/bin/python3"
+ python.parent.mkdir(parents=True)
+ shutil.copy2(Path(sys._base_executable).resolve(), python)
+ site = out / "venv/lib/python3.14/site-packages"
+ site.mkdir(parents=True)
+ (site / "dependency.py").write_text("VALUE = 'prepared'\n", encoding="utf-8")
+ (site / "entry.py").write_text("raise RuntimeError('dependency shadowed source')\n", encoding="utf-8")
+ pm = out / "pm-runtime"
+ (pm / "lib/site-packages").mkdir(parents=True)
+ (pm / "pm-runtime.json").write_text(json.dumps({
+ "python": "../tools/python/bin/python3", "sitePackages": "lib/site-packages"}), encoding="utf-8")
+ tui, web = tmp_path / "tui", tmp_path / "web"
+ (tui / "dist").mkdir(parents=True)
+ web.mkdir()
+ (tui / "dist/entry.js").write_text("export const built = true;", encoding="utf-8")
+ (tui / "package.json").write_text('{"type":"module"}', encoding="utf-8")
+ (web / "index.html").write_text("built web", encoding="utf-8")
+ return out, {
+ "project": str(source / "pyproject.toml"), "code": str(source),
+ "repo": "app", "target": "linux-x64", "placement": "contained",
+ "python": str(python), "site_packages": str(site),
+ "environment": str(out / "venv"), "tools": str(out / "tools"),
+ "pm_runtime": str(pm), "resources": {"skills": str(source / "skills")},
+ "frontends": {"tui": str(tui), "web": str(web)}, "ref": "fixture-revision",
+ }
+
+
+def build_cli(data, out, tmp_path):
+ document = tmp_path / "inputs.json"
+ document.write_text(json.dumps(data), encoding="utf-8")
+ home = tmp_path / "home"
+ home.mkdir(exist_ok=True)
+ return subprocess.run(
+ [sys.executable, "-B", "-m", "scripts.build.agent", "--inputs", str(document), "--out", str(out)],
+ cwd=tmp_path, env={"PATH": os.environ["PATH"], "HOME": str(home),
+ "HERMES_HOME": str(home / ".hermes"), "PYTHONPATH": str(ROOT)},
+ capture_output=True, text=True, timeout=30,
+ )
+
+
+def test_contained_cli_assembly_runs_after_move_and_preserves_prepared_state(tmp_path):
+ out, data = inputs_fixture(tmp_path)
+ (out / "provider-state").write_text("retain", encoding="utf-8")
+ before = {p.relative_to(data["code"]): p.read_bytes() for p in Path(data["code"]).rglob("*") if p.is_file()}
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode == 0, result.stderr
+ assert (out / "provider-state").read_text() == "retain"
+ manifest = json.loads((out / "manifest.json").read_text())
+ assert manifest["ref"] == data["ref"]
+ assert manifest["runtime"] == {
+ "repoDir": "app", "toolsDir": "tools", "storePython": "tools/python/bin/python3",
+ "sitePackages": "venv/lib/python3.14/site-packages", "commands": {"probe": "bin/probe"}}
+ assert (out / "app/hermes_cli/tui_dist/entry.js").is_file()
+ assert json.loads((out / "app/hermes_cli/tui_dist/package.json").read_text())["type"] == "module"
+ assert (out / "app/hermes_cli/web_dist/index.html").is_file()
+ assert not (tmp_path / "home/.hermes").exists()
+ moved = tmp_path / "relocated payload"
+ out.rename(moved)
+ (tmp_path / "entry.py").write_text("raise RuntimeError('cwd shadowed source')", encoding="utf-8")
+ run = subprocess.run([str(moved / manifest["runtime"]["commands"]["probe"]), "two words", "$(no)", ""],
+ cwd=tmp_path, env={"PATH": os.environ["PATH"], "HOME": str(tmp_path / "home"),
+ "PYTHONPATH": "/foreign", "PYTHONHOME": "/foreign"},
+ text=True, capture_output=True, timeout=30)
+ assert run.returncode == 7, run.stderr
+ assert json.loads(run.stdout) == [["two words", "$(no)", ""], "prepared", "1.2.3", "resource"]
+ assert before == {p.relative_to(data["code"]): p.read_bytes() for p in Path(data["code"]).rglob("*") if p.is_file()}
+ assert not list(moved.rglob("__pycache__"))
+ assert (moved / "pm-runtime/pm-runtime.json").is_file()
+
+
+def test_referenced_installed_code_uses_derived_command_map_without_copying(tmp_path):
+ _, data = inputs_fixture(tmp_path)
+ out = tmp_path / "nix output"
+ source = Path(data["code"])
+ (source / "entry.py").write_text(
+ "import json, os\nfrom pathlib import Path\n"
+ "def main():\n print(json.dumps([Path(os.environ['HERMES_BUNDLED_SKILLS'],'data').read_text(),"
+ "os.environ['HERMES_NODE']]))\n", encoding="utf-8")
+ bindir = tmp_path / "installed env/bin"
+ bindir.mkdir(parents=True)
+ command = bindir / "probe"
+ command.write_text(f"#!{sys.executable}\nimport sys\nsys.path.insert(0, {str(source)!r})\nfrom entry import main\nmain()\n", encoding="utf-8")
+ command.chmod(0o755)
+ data.update(placement="references", repo="share/hermes-agent", command_dir=str(bindir),
+ env={"HERMES_NODE": "/prepared/node"})
+ before = {p: p.read_bytes() for p in source.rglob("*") if p.is_file()}
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode == 0, result.stderr
+ mapping = json.loads((out / "command-map.json").read_text())
+ assert mapping["commands"] == {"probe": {
+ "source": str(command), "destination": "bin/probe", "entry": "entry:main"}}
+ assert Path(mapping["env"]["HERMES_TUI_DIR"]).resolve() == Path(data["frontends"]["tui"])
+ assert Path(mapping["env"]["HERMES_WEB_DIST"]).resolve() == Path(data["frontends"]["web"])
+ assert mapping["env"]["HERMES_INSTALL_ROOT"] == str(out / "share/hermes-agent")
+ assert not list(out.rglob("entry.py"))
+ assert (out / "share/hermes-agent/skills").is_symlink()
+ assert (out / "ui-tui").is_symlink()
+ assert (out / "share/hermes-agent/web_dist").is_symlink()
+ assert not (out / "bin/probe").exists(), "Nix owns native makeWrapper"
+ run = subprocess.run([mapping["commands"]["probe"]["source"]], cwd=tmp_path,
+ env={"PATH": os.environ["PATH"], "HOME": str(tmp_path / "home"),
+ "PYTHONDONTWRITEBYTECODE": "1", **mapping["env"]},
+ text=True, capture_output=True, check=True)
+ assert json.loads(run.stdout) == ["resource", "/prepared/node"]
+ assert before == {p: p.read_bytes() for p in source.rglob("*") if p.is_file()}
+
+
+def test_fixed_root_keeps_privilege_shim_and_resolves_venv_command_symlink(tmp_path):
+ out, data = inputs_fixture(tmp_path)
+ # Docker source already occupies /opt/hermes; its bin/hermes belongs to s6.
+ shutil.copytree(data["code"], out, dirs_exist_ok=True)
+ data.update(placement="fixed", repo=".", code=str(out), project=str(out / "pyproject.toml"), bin_dir="libexec")
+ bindir = out / "bin"
+ bindir.mkdir()
+ (bindir / "probe").write_text("privilege shim", encoding="utf-8")
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode == 0, result.stderr
+ assert (bindir / "probe").read_text() == "privilege shim"
+ link = out / "venv/bin/probe"
+ link.parent.mkdir()
+ link.symlink_to("../../libexec/probe")
+ run = subprocess.run([str(link), "ok"], cwd=tmp_path,
+ env={"PATH": os.environ["PATH"], "HOME": str(tmp_path / "home")},
+ text=True, capture_output=True)
+ assert run.returncode == 7, run.stderr
+ assert json.loads(run.stdout)[0] == ["ok"]
+
+
+def test_source_metadata_keeps_declared_requirements_extras_and_entrypoints(tmp_path):
+ from importlib.metadata import distributions
+ from packaging.requirements import Requirement
+
+ out, data = inputs_fixture(tmp_path)
+ project = Path(data["project"])
+ project.write_text(
+ '[project]\nname="assembly-fixture"\nversion="1.2.3"\nrequires-python=">=3.11"\n'
+ 'dependencies=["dependency>=1,<2; python_version >= \'3.11\'"]\n'
+ '[project.optional-dependencies]\nextra=["optional>=2; sys_platform == \'linux\'"]\n'
+ '[project.scripts]\nprobe="entry:main"\n', encoding="utf-8")
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode == 0, result.stderr
+ metadata = next(distributions(path=[str(out / "app")]))
+ assert metadata.metadata["Requires-Python"] == ">=3.11"
+ reqs = {Requirement(r).name: Requirement(r) for r in metadata.requires}
+ assert str(reqs["dependency"].specifier) == "<2,>=1"
+ optional = reqs["optional"]
+ assert optional.marker.evaluate({"extra": "extra", "sys_platform": "linux"})
+ assert not optional.marker.evaluate({"extra": "", "sys_platform": "linux"})
+ assert not optional.marker.evaluate({"extra": "extra", "sys_platform": "win32"})
+ assert [(e.name, e.value) for e in metadata.entry_points] == [("probe", "entry:main")]
+
+
[email protected]("fault", ["missing-pm", "missing-resource", "missing-tui", "unknown-field", "bad-repo", "bad-target"])
+def test_failed_inputs_cannot_leave_a_completion_claim(tmp_path, fault):
+ out, data = inputs_fixture(tmp_path)
+ (out / "manifest.json").write_text('{"runtime": {"commands": {}}}', encoding="utf-8")
+ if fault == "missing-pm":
+ (Path(data["pm_runtime"]) / "pm-runtime.json").unlink()
+ elif fault == "missing-resource":
+ data["resources"]["skills"] = str(tmp_path / "missing skills")
+ elif fault == "missing-tui":
+ (Path(data["frontends"]["tui"]) / "dist/entry.js").unlink()
+ elif fault == "unknown-field":
+ data["typo"] = True
+ elif fault == "bad-repo":
+ data["repo"] = "../escape"
+ else:
+ data["target"] = "linux-typo"
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode != 0
+ assert not (out / "manifest.json").exists()
+ assert not (out / "bin/probe").exists()
+
+
+def test_incremental_copy_drops_removed_source_without_deleting_provider_files(tmp_path):
+ out, data = inputs_fixture(tmp_path)
+ source = Path(data["code"])
+ (source / "obsolete.py").write_text("old", encoding="utf-8")
+ assert build_cli(data, out, tmp_path).returncode == 0
+ sentinel = out / "provider-file"
+ sentinel.write_text("retain", encoding="utf-8")
+ (source / "obsolete.py").unlink()
+ assert build_cli(data, out, tmp_path).returncode == 0
+ assert not (out / "app/obsolete.py").exists()
+ assert sentinel.read_text() == "retain"
+
+
+def test_fixed_launcher_accepts_explicit_external_python_without_path_guessing(tmp_path):
+ out, data = inputs_fixture(tmp_path)
+ data.update(placement="fixed", python=sys.executable)
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode == 0, result.stderr
+ run = subprocess.run([str(out / "bin/probe")], cwd=tmp_path,
+ env={"PATH": os.environ["PATH"], "HOME": str(tmp_path / "home")},
+ capture_output=True, text=True)
+ assert run.returncode == 7, run.stderr
+
+
+def test_stage_passes_explicit_products_to_the_single_assembler(tmp_path, monkeypatch):
+ from scripts.bundles import stage
+ from scripts.build.agent import assemble
+ from scripts.build.inputs import AgentInputs
+
+ out, data = inputs_fixture(tmp_path)
+ calls = []
+ def native(args):
+ calls.append(args.frontends)
+ assemble(AgentInputs.from_dict({**data, "frontends": args.frontends}), out)
+ return 0
+ monkeypatch.setattr(stage, "stage_native", native)
+ assert stage.main(["--out", str(out), "--ref", "fixture", "--tui", data["frontends"]["tui"],
+ "--web", data["frontends"]["web"]]) == 0
+ assert calls == [{k: Path(v) for k, v in data["frontends"].items()}]
+ assert json.loads((out / "manifest.json").read_text())["runtime"]["commands"] == {"probe": "bin/probe"}
+
+
+def test_prepared_environment_python_imports_app_from_unrelated_script(tmp_path):
+ out, data = inputs_fixture(tmp_path)
+ environment = out / ".venv"
+ subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(environment)], check=True)
+ python = environment / "bin/python"
+ site = subprocess.check_output([str(python), "-I", "-c", "import sysconfig; print(sysconfig.get_paths()['purelib'])"], text=True).strip()
+ Path(site, "dependency.py").write_text("VALUE='prepared'", encoding="utf-8")
+ data.update(placement="fixed", environment=str(environment), python=str(python), site_packages=site)
+ result = build_cli(data, out, tmp_path)
+ assert result.returncode == 0, result.stderr
+ script = tmp_path / "external-probe.py"
+ script.write_text("import entry\nfrom importlib.metadata import version\nprint(version('assembly-fixture'))\n", encoding="utf-8")
+ run = subprocess.run([str(python), "-I", str(script)], cwd=tmp_path,
+ env={"PATH": os.environ["PATH"], "HOME": str(tmp_path / "home"), "PYTHONDONTWRITEBYTECODE": "1"},
+ capture_output=True, text=True)
+ assert run.returncode == 0, run.stderr
+ assert run.stdout.strip() == "1.2.3"
+
+
+def test_site_layout_uses_explicit_target_version_not_builder_python(tmp_path):
+ from scripts.build.inputs import dependency_site
+ assert dependency_site(tmp_path, "3.99.1+vendor", "linux-x64") == tmp_path / "lib/python3.99/site-packages"
+ assert dependency_site(tmp_path, "3.99.1", "win32-arm64") == tmp_path / "Lib/site-packages"
+
+
+def test_automatic_frontends_use_requested_snapshot_not_current_checkout(tmp_path, monkeypatch):
+ from scripts.bundles import stage
+ repo = tmp_path / "checkout"
+ repo.mkdir()
+ subprocess.run(["git", "init", str(repo)], check=True, capture_output=True)
+ project = repo / "pyproject.toml"
+ project.write_text('[project]\nversion="1"\n', encoding="utf-8")
+ subprocess.run(["git", "add", "."], cwd=repo, check=True)
+ subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-m", "selected"], cwd=repo, check=True, capture_output=True)
+ revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
+ project.write_text('[project]\nversion="dirty-current"\n', encoding="utf-8")
+ monkeypatch.setattr(stage, "ROOT", repo)
+ monkeypatch.setattr(stage.shutil, "which", lambda name: "/prepared/node")
+ real_run = subprocess.run
+ built_sources = []
+ def run(command, **kwargs):
+ if command[0] != "/prepared/node":
+ return real_run(command, **kwargs)
+ source = Path(command[command.index("--source") + 1])
+ built_sources.append(source)
+ assert source != repo
+ assert 'version="1"' in (source / "pyproject.toml").read_text()
+ monkeypatch.setattr(stage.subprocess, "run", run)
+ monkeypatch.setattr(stage, "stage_native", lambda args: 0)
+ assert stage.main(["--out", str(tmp_path / "out"), "--ref", revision]) == 0
+ assert len(built_sources) == 4
diff --git a/tests/scripts/test_bundle_native.py b/tests/scripts/test_bundle_native.py
index f72c570ab83..c4362ef0913 100644
--- a/tests/scripts/test_bundle_native.py
+++ b/tests/scripts/test_bundle_native.py
@@ -19,6 +19,7 @@ from scripts.bundles import native
def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_path, monkeypatch):
from hermes_cli.runtime_paths import site_packages
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
output = tmp_path / "payload"
target_python = output / "staged-python" / ("python.exe" if os.name == "nt" else "bin/python")
target_python.parent.mkdir(parents=True)
@@ -32,9 +33,14 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_pat
repo.mkdir()
pm_project = Path(__file__).resolve().parents[2] / "pm"
(repo / "pm").mkdir()
- for name in ("pyproject.toml", "uv.lock"):
+ for name in ("pyproject.toml", "uv.lock", "lock.json"):
shutil.copy2(pm_project / name, repo / "pm" / name)
- (repo / "pyproject.toml").write_text('[project]\nname="fixture"\nversion="1.0.0"\nrequires-python=">=3.11"\n[project.optional-dependencies]\npayloadtest=[]\n[tool.uv]\npackage=false\n', encoding="utf-8")
+ (repo / "pyproject.toml").write_text('[project]\nname="fixture"\nversion="1.0.0"\nrequires-python=">=3.11"\n[project.scripts]\nprobe="entry:main"\n[project.optional-dependencies]\npayloadtest=[]\n[tool.uv]\npackage=false\n', encoding="utf-8")
+ from scripts.build.inputs import RESOURCE_ENV
+ for name in RESOURCE_ENV:
+ (repo / name).mkdir()
+ (repo / name / "asset").write_text("required", encoding="utf-8")
+ (repo / "entry.py").write_text("def main(): return 0\n", encoding="utf-8")
uv = shutil.which("uv")
assert uv, "native bundle test requires uv"
env = {**os.environ, "UV_OFFLINE": "1", "UV_PYTHON_DOWNLOADS": "never", "UV_CACHE_DIR": str(tmp_path / "cache")}
@@ -46,46 +52,49 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_pat
monkeypatch.setattr(native, "_bundle_package_names", lambda: [])
monkeypatch.setattr(native, "_install_names", lambda names: 0)
monkeypatch.setattr(native, "_store", lambda: SimpleNamespace(root=output / "tools", entry=lambda _: target_python.parent))
- monkeypatch.setattr(native, "_facts", lambda: SimpleNamespace(get=lambda _: {"entry": "python"}, entries_in_use=lambda: []))
+ monkeypatch.setattr(native, "_facts", lambda: SimpleNamespace(get=lambda _: {"entry": "python", "version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"}, entries_in_use=lambda: []))
monkeypatch.setattr(native, "get_package", lambda _: SimpleNamespace(binary=lambda *args: target_python))
monkeypatch.setattr(native, "pm_uv", lambda: (uv, dict(env)))
monkeypatch.setattr(native, "_arch_guard", lambda store: [])
monkeypatch.setattr("scripts.bundles.payload.relativize_links", lambda root: 0)
monkeypatch.setattr("pm.extras.ANCHORS", {"payloadtest": "bundle_probe.present"})
- monkeypatch.setattr("pm.packages.uv_cache_dir", lambda: tmp_path / "cache")
- real_run = native._run_live
+ from scripts.build import python_env
+ real_build = python_env.build_python_environment
calls = []
witness = tmp_path / "inventory-python.json"
fail_inventory = False
- def child(argv, *, cwd, env):
- calls.append(argv[1])
+ def build(**kwargs):
+ calls.append(kwargs)
assert not (output / "manifest.json").exists()
marker = json.loads((output / "pm-runtime/pm-runtime.json").read_text())
assert (output / "pm-runtime" / marker["python"]).resolve() == target_python
assert (output / "pm-runtime" / marker["sitePackages"]).is_dir()
- result = real_run(argv, cwd=cwd, env=env)
- if argv[1] == "sync" and result[0] == 0:
- site = site_packages(output / "venv")
- if fail_inventory:
- shutil.rmtree(site)
- else:
- package = site / "bundle_probe"
- package.mkdir()
- (package / "__init__.py").write_text(
- "import json, pathlib, sys\n"
- f"pathlib.Path({str(witness)!r}).write_text(json.dumps(sys.executable), encoding='utf-8')\n",
- encoding="utf-8",
- )
- (package / "present.py").write_text("", encoding="utf-8")
+ result = real_build(**kwargs)
+ site = site_packages(output / "venv")
+ if fail_inventory:
+ shutil.rmtree(site)
+ else:
+ package = site / "bundle_probe"
+ package.mkdir()
+ (package / "__init__.py").write_text(
+ "import json, pathlib, sys\n"
+ f"pathlib.Path({str(witness)!r}).write_text(json.dumps(sys.executable), encoding='utf-8')\n",
+ encoding="utf-8",
+ )
+ (package / "present.py").write_text("", encoding="utf-8")
return result
- monkeypatch.setattr(native, "_run_live", child)
+ monkeypatch.setattr(python_env, "build_python_environment", build)
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "original"))
- assert native.stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 0
- assert calls == ["venv", "sync"]
+ monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "cache"))
+ assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 0
+ assert calls[0]["all_extras"] is True
assert (output / "hermes-agent/pyproject.toml").is_file()
- assert json.loads((output / "manifest.json").read_text())["repo"] == "hermes-agent"
+ manifest = json.loads((output / "manifest.json").read_text())
+ assert manifest["repo"] == "hermes-agent"
+ command = "bin/probe.exe" if os.name == "nt" else "bin/probe"
+ assert manifest["runtime"]["commands"] == {"probe": command}
feature_file = output / "enabled-features.json"
assert json.loads(feature_file.read_text(encoding="utf-8"))["extras"] == ["payloadtest"]
assert Path(json.loads(witness.read_text(encoding="utf-8"))) == target_python
@@ -93,16 +102,27 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_pat
before = feature_file.read_bytes()
fail_inventory = True
- assert native.stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
+ assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
assert not (output / "manifest.json").exists()
assert feature_file.read_bytes() == before
assert os.environ["HERMES_RUNTIME_DIR"] == str(tmp_path / "original")
- monkeypatch.setattr(native, "_run_live", lambda *a, **kw: (1, "injected failure"))
- assert native.stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
+ from pm.package import InstallError
+ def fail_build(**kwargs):
+ raise InstallError("venv", "injected failure")
+ monkeypatch.setattr(python_env, "build_python_environment", fail_build)
+ assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
assert not (output / "manifest.json").exists()
assert os.environ["HERMES_RUNTIME_DIR"] == str(tmp_path / "original")
+ import pytest
+ (repo / "pm/lock.json").write_text("{}", encoding="utf-8")
+ subprocess.run(["git", "add", "pm/lock.json"], cwd=repo, check=True)
+ subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-m", "different pins"], cwd=repo, check=True, capture_output=True)
+ monkeypatch.setattr(native, "_install_names", lambda names: pytest.fail("mismatched pins reached provisioning"))
+ with pytest.raises(ValueError, match="PM lock differs"):
+ native._stage_native(SimpleNamespace(out=str(output), ref="HEAD"))
+
def test_staged_cache_installs_built_wheel_without_unsigned_zip(tmp_path):
uv = shutil.which("uv")
@@ -163,3 +183,16 @@ def test_staged_cache_installs_built_wheel_without_unsigned_zip(tmp_path):
capture_output=True, text=True, check=True, timeout=30,
)
assert probe.stdout.strip() == "installed from cached wheel"
+
+
+def test_native_dispatch_isolates_process_state_on_real_child_failure(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "user-home"))
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "user-tools"))
+ before = dict(os.environ)
+ out = tmp_path / "output"
+ assert native.stage_native(SimpleNamespace(out=str(out), ref="missing-build-test-ref")) != 0
+ assert dict(os.environ) == before
+ assert not (tmp_path / "user-home").exists()
+ assert not (tmp_path / "user-tools").exists()
+ assert not (out / "manifest.json").exists()
+ assert not list(out.glob(".build-*"))
diff --git a/tests/scripts/test_bundle_payload.py b/tests/scripts/test_bundle_payload.py
index bf817114335..f6626850a04 100644
--- a/tests/scripts/test_bundle_payload.py
+++ b/tests/scripts/test_bundle_payload.py
@@ -9,11 +9,14 @@ import sys
import pytest
-from scripts.bundles.payload import plant_surfaces, posix_launcher, project_entries, relativize_links, snapshot, write_manifest, stage_launchers
+from scripts.bundles.payload import relativize_links, snapshot
+from scripts.build.inputs import project_entries
+from scripts.build.agent import plant_surfaces
+from scripts.build.launchers import posix_launcher
from scripts.bundles.desktop import release_version
-def test_snapshot_and_manifest_are_shared_by_both_layouts(tmp_path):
+def test_snapshot_preserves_declared_entries_in_both_layouts(tmp_path):
source = tmp_path / "source"
source.mkdir()
subprocess.run(["git", "init", str(source)], check=True, capture_output=True)
@@ -26,11 +29,9 @@ def test_snapshot_and_manifest_are_shared_by_both_layouts(tmp_path):
root = tmp_path / repo_name
root.mkdir()
snapshot(source, "HEAD", root / repo_name)
- manifest = write_manifest(root, target=target, repo=repo_name)
- assert project_entries(root / manifest["repo"]) == {"custom": "entry:run"}
+ assert project_entries(root / repo_name / "pyproject.toml") == {"custom": "entry:run"}
assert not (root / repo_name / "untracked").exists()
assert not (root / repo_name / ".git").exists()
- assert json.loads((root / "manifest.json").read_text(encoding="utf-8-sig")) == manifest
assert release_version(source, "v1.2.3") == "1.2.3"
with pytest.raises(ValueError):
release_version(source, "v1.2.4")
@@ -38,73 +39,31 @@ def test_snapshot_and_manifest_are_shared_by_both_layouts(tmp_path):
def test_surfaces_require_complete_outputs_and_replace_stale_files(tmp_path):
source, repo = tmp_path / "build", tmp_path / "payload"
- tui = source / "ui-tui/dist"
+ tui = source / "tui/dist"
web = source / "hermes_cli/web_dist"
tui.mkdir(parents=True)
web.mkdir(parents=True)
(tui / "entry.js").write_text("built tui", encoding="utf-8")
+ (tui.parent / "package.json").write_text('{"type":"module"}', encoding="utf-8")
(web / "index.html").write_text("built web", encoding="utf-8")
- plant_surfaces(repo, source)
+ plant_surfaces(repo, {"tui": tui.parent, "web": web})
(repo / "hermes_cli/web_dist/stale").write_text("old", encoding="utf-8")
- plant_surfaces(repo, source)
+ plant_surfaces(repo, {"tui": tui.parent, "web": web})
assert not (repo / "hermes_cli/web_dist/stale").exists()
assert (repo / "hermes_cli/tui_dist/entry.js").read_text(encoding="utf-8-sig") == "built tui"
(web / "index.html").unlink()
with pytest.raises(FileNotFoundError):
- plant_surfaces(repo, source)
+ plant_surfaces(repo, {"tui": tui.parent, "web": web})
def test_wrapper_rejects_unresolved_template_fields(tmp_path, monkeypatch):
- from scripts.bundles import payload
+ from scripts.build import launchers
template = tmp_path / "launcher_wrapper.py"
template.write_text('entry = "__HERMES_ENTRY_MODULE__"\nmissing = "__HERMES_NEW__"\n', encoding="utf-8")
- monkeypatch.setattr(payload, "__file__", str(tmp_path / "payload.py"))
+ monkeypatch.setattr(launchers, "__file__", str(tmp_path / "payload.py"))
with pytest.raises(ValueError, match="__HERMES_NEW__"):
- payload.render_wrapper("entry:run", "../app", "../venv/Lib/site-packages")
-
-
-def test_launcher_stage_reads_declared_entries_and_drops_stale_names(tmp_path, monkeypatch):
- from pathlib import Path
- from types import SimpleNamespace
- from pm.lock import Facts
- from pm.store import current_target
-
- root = tmp_path / "payload"
- repo, tools = root / "app", root / "tools"
- repo.mkdir(parents=True)
- tools.mkdir()
- interpreter = tools / "python/python.exe"
- interpreter.parent.mkdir()
- interpreter.write_bytes(b"fixture interpreter")
- (repo / "pyproject.toml").write_text('[project.scripts]\ncustom="entry:run"\n', encoding="utf-8")
- Facts(tools / "facts.json").record("python", "3.11.16", "python", {}, tools)
- manifest = write_manifest(root, target=current_target(), repo="app")
- site = "venv/Lib/site-packages" if current_target().startswith("win32") else "venv/lib/python3.11/site-packages"
- (root / site).mkdir(parents=True)
- (root / "bin").mkdir()
- (root / "bin/removed-entry").write_text("old", encoding="utf-8")
- monkeypatch.setattr("pm.registry.get_package", lambda _: SimpleNamespace(binary=lambda *args: interpreter))
- calls = []
-
- def mint(argv, *, env, check):
- calls.append(json.loads(env["HERMES_MINT_SPECS"]))
- compile(Path(env["HERMES_MINT_WRAPPER"]).read_text(encoding="utf-8-sig"), "wrapper", "exec")
- (root / "bin/custom.exe").write_bytes(b"mint fixture")
-
- assert stage_launchers(root, manifest, run=mint) == ["custom"]
- assert not (root / "bin/removed-entry").exists()
- if current_target().startswith("win32"):
- assert calls == [[{"name": "custom", "module": "entry", "func": "run"}]]
- else:
- assert (root / "bin/custom").is_file()
- published = json.loads((root / "manifest.json").read_text(encoding="utf-8-sig"))
- assert published["launchers"] == ["custom"]
- assert published["runtime"] == {
- "repoDir": "app", "toolsDir": "tools", "storePython": "tools/python/python.exe",
- "sitePackages": site,
- "commands": {"custom": "bin/custom.exe" if current_target().startswith("win32") else "bin/custom"},
- }
+ launchers.render_wrapper("entry:run", "../app", "../venv/Lib/site-packages")
@pytest.mark.platforms("posix")
diff --git a/tests/scripts/test_bundle_store_cleanup.py b/tests/scripts/test_bundle_store_cleanup.py
index 543f9a49b49..76331b0d943 100644
--- a/tests/scripts/test_bundle_store_cleanup.py
+++ b/tests/scripts/test_bundle_store_cleanup.py
@@ -31,13 +31,18 @@ def test_cached_bundle_prunes_unselected_facts_and_entries(tmp_path, monkeypatch
lock.set_pin(name, "fixture", {})
lock.save()
monkeypatch.setattr(native, "_lockfile", lambda: lock)
+ from pathlib import Path
+ import shutil
+ staged_lock = output / "hermes-agent/pm/lock.json"
+ staged_lock.parent.mkdir(parents=True)
+ shutil.copy2(Path(__file__).resolve().parents[2] / "pm/lock.json", staged_lock)
monkeypatch.setattr("scripts.bundles.payload.snapshot", lambda *args: None)
monkeypatch.setattr(native, "_install_names", lambda names: 0)
# Stop after cleanup, before invoking any venv/build subprocesses.
monkeypatch.setattr(native, "pm_uv", lambda: (None, {}))
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(user_store))
- assert native.stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
+ assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
remaining = Facts(staged_store / "facts.json")
for name in stale:
diff --git a/tests/scripts/test_commit_bundle_entrypoints.py b/tests/scripts/test_commit_bundle_entrypoints.py
index 5b95cea9b5b..62ffbad20b8 100644
--- a/tests/scripts/test_commit_bundle_entrypoints.py
+++ b/tests/scripts/test_commit_bundle_entrypoints.py
@@ -51,17 +51,15 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, mon
assert env["HERMES_BUILD_COMMIT"] == sha
assert env["GITHUB_SHA"] == sha
assert env["HERMES_PAYLOAD_VERSION"] == "0.1.2"
- if "pm.cli" in argv:
- assert argv[-2:] == ["--ref", sha]
+ if "scripts.bundles.stage" in argv:
+ assert argv[argv.index("--ref") + 1] == sha
+ assert "--tui" in argv and "--web" in argv
payload = repo / 'apps/desktop/build/agent-payload'
(payload / 'hermes-agent').mkdir(parents=True)
(payload / 'manifest.json').write_text(json.dumps({'repo': 'hermes-agent', 'target': current_target()}), encoding='utf-8')
- launcher_calls = []
- monkeypatch.setattr(desktop, 'stage_launchers', lambda payload, manifest: launcher_calls.append((payload, manifest)))
monkeypatch.setattr(desktop, "run", run)
desktop.build(repo, None, variant, ['--publish=never'], commit_build=sha)
- assert any('pm.cli' in argv for argv, _, _ in calls) == (variant != 'light')
- assert bool(launcher_calls) == (variant != 'light')
+ assert any('scripts.bundles.stage' in argv for argv, _, _ in calls) == (variant != 'light')
argv, cwd, env = calls[-1]
assert argv[:5] == ['node', 'npm-cli.js', 'run', 'builder', '--']
assert '-c.extraMetadata.version=0.1.2' in argv
diff --git a/tests/scripts/test_desktop_cli_wrapper.py b/tests/scripts/test_desktop_cli_wrapper.py
index e3c789200be..aa60bc693fa 100644
--- a/tests/scripts/test_desktop_cli_wrapper.py
+++ b/tests/scripts/test_desktop_cli_wrapper.py
@@ -1,6 +1,6 @@
"""Unit tests for the bundled payload's win32 launcher wrapper.
-scripts/bundles/launcher_wrapper.py is the zip overlay a distlib
+scripts/build/launcher_wrapper.py is the zip overlay a distlib
ScriptMaker packs into every minted CLI launcher exe (the rust shim's
replacement). The wrapper is import-safe on purpose, so these tests drive
its real logic — path resolution, sys.path order, the pycache_prefix
@@ -21,7 +21,7 @@ from pathlib import Path
import pytest
_REPO = Path(__file__).resolve().parents[2]
-_WRAPPER = _REPO / "scripts" / "bundles" / "launcher_wrapper.py"
+_WRAPPER = _REPO / "scripts" / "build" / "launcher_wrapper.py"
def _load(env=None):
diff --git a/tests/scripts/test_icon_generation_exit.py b/tests/scripts/test_icon_generation_exit.py
index 8f287e7c8b1..2f63b0b425e 100644
--- a/tests/scripts/test_icon_generation_exit.py
+++ b/tests/scripts/test_icon_generation_exit.py
@@ -17,9 +17,10 @@ def test_write_status_includes_every_target(tmp_path, monkeypatch, capsys, failu
spec = importlib.util.spec_from_file_location("icon_generator_under_test", script)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
- monkeypatch.setattr(module, "ROOT", tmp_path)
- monkeypatch.setattr(module, "ensure_masters", lambda: None)
- monkeypatch.setattr(sys, "argv", [str(script)])
+ source = tmp_path / "immutable source"
+ source.mkdir()
+ monkeypatch.setattr(module, "IconArt", lambda root: root)
+ monkeypatch.setattr(sys, "argv", [str(script), "--source", str(source), "--out", str(tmp_path)])
image = io.BytesIO()
Image.new("RGBA", (2, 2), (0, 0, 0, 0)).save(image, "PNG")
@@ -29,7 +30,9 @@ def test_write_status_includes_every_target(tmp_path, monkeypatch, capsys, failu
(tmp_path / "blocked").write_text("not a directory", encoding="utf-8")
monkeypatch.setattr(module, "TARGETS", [(first, "png", "first"), ("last.png", "png", "last")])
- def target_bytes(kind, target):
+ def target_bytes(art, kind, target):
+ assert art == source
+ assert not list(source.iterdir())
if target == "first":
if failure == "render":
raise RuntimeError("injected render failure")
diff --git a/tests/scripts/test_mint_launchers.py b/tests/scripts/test_mint_launchers.py
index 346920b84d5..802fd2f80a3 100644
--- a/tests/scripts/test_mint_launchers.py
+++ b/tests/scripts/test_mint_launchers.py
@@ -1,4 +1,4 @@
-"""Live tests for the win32 launcher mint (scripts/bundles/mint_launchers.py).
+"""Live tests for the win32 launcher mint (scripts/build/mint_launchers.py).
These RUN the real mint on the current interpreter and then execute the
minted launcher — the strongest proof the mechanism is intact (the research
@@ -27,7 +27,7 @@ from pathlib import Path
import pytest
_REPO = Path(__file__).resolve().parents[2]
-_MINT = _REPO / "scripts" / "bundles" / "mint_launchers.py"
+_MINT = _REPO / "scripts" / "build" / "mint_launchers.py"
pytestmark = [
pytest.mark.platforms("windows"),
@@ -99,7 +99,7 @@ def _mint(bin_dir: Path, wrapper: Path, specs) -> list[str]:
def _render_wrapper(tmp_path: Path) -> Path:
- from scripts.bundles.payload import render_wrapper
+ from scripts.build.launchers import render_wrapper
text = render_wrapper("hermes_cli.main:main", "../repo", "../venv/Lib/site-packages")
out = tmp_path / "wrapper.py"
out.write_text(text, encoding="utf-8")
diff --git a/tests/scripts/test_pm_runtime_bundle.py b/tests/scripts/test_pm_runtime_bundle.py
index 4e6dbe1e69f..32ce253cb5c 100644
--- a/tests/scripts/test_pm_runtime_bundle.py
+++ b/tests/scripts/test_pm_runtime_bundle.py
@@ -124,6 +124,9 @@ def test_native_stage_builds_pm_before_application_environment(tmp_path, monkeyp
return {"entry": "python"}
calls = []
+ lock = tmp_path / "hermes-agent/pm/lock.json"
+ lock.parent.mkdir(parents=True)
+ shutil.copy2(Path(__file__).resolve().parents[2] / "pm/lock.json", lock)
monkeypatch.setattr(payload, "snapshot", lambda *args: None)
monkeypatch.setattr(native, "_bundle_package_names", lambda: [])
monkeypatch.setattr(native, "_install_names", lambda names: 0)
@@ -138,7 +141,6 @@ def test_native_stage_builds_pm_before_application_environment(tmp_path, monkeyp
raise StopAfterPM
monkeypatch.setattr(native, "stage_pm_runtime", staged)
- monkeypatch.setattr(native, "_run_live", lambda *args, **kwargs: pytest.fail("app sync ran before PM stage"))
with pytest.raises(StopAfterPM):
- native.stage_native(SimpleNamespace(out=str(tmp_path), ref="HEAD"))
+ native._stage_native(SimpleNamespace(out=str(tmp_path), ref="HEAD"))
assert calls == [(tmp_path, Path("uv"), tmp_path / "tools/python/python", tmp_path / "hermes-agent")]
diff --git a/tests/scripts/test_termux_agent_assembly.py b/tests/scripts/test_termux_agent_assembly.py
new file mode 100644
index 00000000000..cf60829f826
--- /dev/null
+++ b/tests/scripts/test_termux_agent_assembly.py
@@ -0,0 +1,50 @@
+"""Bionic assembly consumes prepared bytes without running foreign binaries."""
+import json
+from pathlib import Path
+import shutil
+
+from scripts.build.inputs import RESOURCE_ENV, dependency_site
+from scripts.termux.payload_facts import write_facts
+
+
+def test_bionic_facts_and_agent_keep_fixed_prefix_and_tui_only(tmp_path):
+ from pm.lock import Lockfile, Facts
+ from pm.registry import get_package
+
+ payload = tmp_path / "payload"
+ repo = payload / "app"
+ (repo / "pm").mkdir(parents=True)
+ lock = repo / "pm/lock.json"
+ shutil.copy2(Path(__file__).resolve().parents[2] / "pm/lock.json", lock)
+ (repo / "pyproject.toml").write_text('[project]\nname="fixture"\nversion="1"\n[project.scripts]\nprobe="entry:main"\n', encoding="utf-8")
+ (repo / "install-stamp.json").write_text('{"distribution":"apt-termux","payload":"bundled"}', encoding="utf-8")
+ for name in RESOURCE_ENV:
+ (repo / name).mkdir()
+ target = "linux-arm64-bionic"
+ tools = ("python", "node", "uv", "npm", "ffmpeg", "ripgrep")
+ for name in tools:
+ executable = get_package(name).binary(payload / "tools" / name, target)
+ executable.parent.mkdir(parents=True, exist_ok=True)
+ executable.write_bytes(b"foreign binary must not be executed")
+ executable.chmod(0o755)
+ python = get_package("python").binary(payload / "tools/python", target)
+ site = dependency_site(payload / "venv", Lockfile(lock).version("python"), target)
+ site.mkdir(parents=True)
+ pm = payload / "pm-runtime"
+ (pm / "deps").mkdir(parents=True)
+ (pm / "pm-runtime.json").write_text(json.dumps({"python": "../" + python.relative_to(payload).as_posix(), "sitePackages": "deps"}), encoding="utf-8")
+ tui = tmp_path / "tui-product"
+ (tui / "dist").mkdir(parents=True)
+ (tui / "dist/entry.js").write_text("built", encoding="utf-8")
+ (tui / "package.json").write_text('{"type":"module"}', encoding="utf-8")
+ build_set = tmp_path / "build-set.txt"
+ build_set.write_text("native-fixture\n", encoding="utf-8")
+ write_facts(payload, lock, build_set, tui)
+ manifest = json.loads((payload / "manifest.json").read_text())
+ assert manifest["runtime"]["commands"] == {"probe": "bin/probe"}
+ assert manifest["runtime"]["sitePackages"] == site.relative_to(payload).as_posix()
+ assert (repo / "hermes_cli/tui_dist/entry.js").read_text() == "built"
+ assert not (repo / "hermes_cli/web_dist").exists()
+ assert json.loads((payload / "native-wheels.json").read_text()) == ["native-fixture"]
+ facts = Facts(payload / "tools/facts.json", strict=True)
+ assert all(facts.get(name)["target"] == target for name in tools)
diff --git a/tests/scripts/test_termux_build_driver.py b/tests/scripts/test_termux_build_driver.py
new file mode 100644
index 00000000000..68be12c351e
--- /dev/null
+++ b/tests/scripts/test_termux_build_driver.py
@@ -0,0 +1,183 @@
+"""Exercise the Termux sequencing boundary with real child executables."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+import pytest
+from ruamel.yaml import YAML
+
+
+ROOT = Path(__file__).resolve().parents[2]
+DRIVER = ROOT / "scripts/termux/build.py"
+pytestmark = pytest.mark.platforms("posix")
+
+
+def build_fixture(tmp_path):
+ repo = tmp_path / "source with spaces"
+ payload = tmp_path / "prepared payload"
+ out = tmp_path / "deb output"
+ tools = tmp_path / "tools"
+ tools.mkdir()
+ payload.mkdir()
+ for name in ("scripts/build/node-deps.mjs", "scripts/build/tui.mjs", "scripts/termux/build_deb.sh"):
+ script = repo / name
+ script.parent.mkdir(parents=True, exist_ok=True)
+ script.touch()
+ log = tmp_path / "calls.jsonl"
+ recorder = f"""#!{sys.executable}
+import json
+import os
+from pathlib import Path
+import sys
+
+args = sys.argv[1:]
+assert Path(args[0]).is_file(), args
+stage = Path(args[0]).name
+with Path(os.environ['CALL_LOG']).open('a') as stream:
+ stream.write(json.dumps({{'tool': Path(sys.argv[0]).name, 'args': args,
+ 'cwd': os.getcwd(), 'image': os.environ.get('TERMUX_BUILDER_IMAGE')}}) + '\\n')
+if stage == os.environ.get('FAIL_STAGE'):
+ sys.exit(37)
+if stage == 'tui.mjs':
+ product = Path(args[args.index('--out') + 1])
+ (product / 'dist').mkdir(parents=True, exist_ok=True)
+ (product / 'dist/entry.js').write_text('fixture TUI product')
+ (product / 'package.json').write_text('{{"type":"module"}}')
+if stage == 'build_deb.sh':
+ product = Path(args[args.index('--tui-product') + 1])
+ assert (product / 'dist/entry.js').read_text() == 'fixture TUI product'
+ destination = Path(args[args.index('--out') + 1])
+ destination.mkdir(parents=True)
+ (destination / 'assembly-received-product').write_text(str(product))
+"""
+ for name in ("node", "bash"):
+ tool = tools / name
+ tool.write_text(recorder, encoding="utf-8")
+ tool.chmod(0o755)
+ env = dict(os.environ, PATH=f"{tools}{os.pathsep}{os.environ['PATH']}",
+ CALL_LOG=str(log), TERMUX_BUILDER_IMAGE="fixture-pinned-image")
+ return repo, payload, out, log, env
+
+
+def invoke(build_fixture, *identity, extra=()):
+ repo, payload, out, _, env = build_fixture
+ return subprocess.run(
+ [sys.executable, str(DRIVER), "--repo", str(repo), "--payload", str(payload),
+ "--out", str(out), *identity, *extra],
+ cwd=repo.parent, env=env, capture_output=True, text=True, timeout=30,
+ )
+
+
+def recorded_calls(log):
+ return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
+
+
[email protected]("identity", [("--tag", "v1.2.3"), ("--commit", "a" * 40)])
+def test_driver_prepares_only_tui_then_passes_product_to_deb(build_fixture, identity):
+ repo, payload, out, log, _ = build_fixture
+ result = invoke(build_fixture, *identity)
+ assert result.returncode == 0, result.stdout + result.stderr
+ product = repo / ".build/termux/tui"
+ assert recorded_calls(log) == [
+ {"tool": "node", "args": [str(repo / "scripts/build/node-deps.mjs"),
+ "--source", str(repo), "--workspace", "ui-tui"],
+ "cwd": str(repo), "image": "fixture-pinned-image"},
+ {"tool": "node", "args": [str(repo / "scripts/build/tui.mjs"),
+ "--source", str(repo), "--out", str(product)],
+ "cwd": str(repo), "image": "fixture-pinned-image"},
+ {"tool": "bash", "args": [str(repo / "scripts/termux/build_deb.sh"),
+ "--repo", str(repo), "--payload", str(payload), "--out", str(out),
+ "--tui-product", str(product), *identity],
+ "cwd": str(repo), "image": "fixture-pinned-image"},
+ ]
+ assert (out / "assembly-received-product").read_text() == str(product)
+
+
[email protected]("identity", [
+ (), ("--tag", "v1.2.3", "--commit", "a" * 40),
+ ("--ta", "v1.2.3"), ("--commit", "short"),
+ ("--commit", "A" * 40), ("--tag", ""), ("--tag", "latest"),
+ ("--tag", "v1.2.3", "--skip-build"),
+])
+def test_invalid_cli_never_starts_a_build(build_fixture, identity):
+ _, payload, out, log, _ = build_fixture
+ result = invoke(build_fixture, *identity)
+ assert result.returncode == 2, result.stdout + result.stderr
+ assert "error:" in result.stderr
+ assert recorded_calls(log) == []
+ assert not (payload / ".work").exists()
+ assert not out.exists()
+
+
[email protected]("missing", ["--repo", "--payload", "--out"])
+def test_all_paths_are_explicit(build_fixture, missing):
+ repo, payload, out, log, env = build_fixture
+ paths = {"--repo": repo, "--payload": payload, "--out": out}
+ args = [value for option, path in paths.items() if option != missing
+ for value in (option, str(path))]
+ result = subprocess.run([sys.executable, str(DRIVER), *args, "--tag", "v1.2.3"],
+ cwd=repo.parent, env=env, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 2
+ assert missing in result.stderr
+ assert recorded_calls(log) == []
+
+
+def test_missing_prepared_payload_is_rejected_before_frontend_work(build_fixture):
+ _, payload, out, log, _ = build_fixture
+ payload.rmdir()
+ result = invoke(build_fixture, "--tag", "v1.2.3")
+ assert result.returncode == 2, result.stdout + result.stderr
+ assert "--payload" in result.stderr
+ assert recorded_calls(log) == []
+ assert not payload.exists()
+ assert not out.exists()
+
+
[email protected]("stage, reached", [
+ ("node-deps.mjs", ["node-deps.mjs"]),
+ ("tui.mjs", ["node-deps.mjs", "tui.mjs"]),
+ ("build_deb.sh", ["node-deps.mjs", "tui.mjs", "build_deb.sh"]),
+])
+def test_child_failure_stops_sequence_even_with_stale_product(build_fixture, stage, reached):
+ repo, payload, out, log, env = build_fixture
+ stale = repo / ".build/termux/tui/dist/entry.js"
+ stale.parent.mkdir(parents=True)
+ stale.write_text("stale product")
+ env["FAIL_STAGE"] = stage
+ result = invoke(build_fixture, "--tag", "v1.2.3")
+ assert result.returncode == 37, result.stdout + result.stderr
+ assert [Path(call["args"][0]).name for call in recorded_calls(log)] == reached
+ assert not out.exists()
+
+
[email protected]("identity", [("--tag", "v1.2.3"), ("--commit", "a" * 40)])
+def test_release_workflow_runs_the_shared_sequence(build_fixture, identity):
+ repo, payload, _, log, env = build_fixture
+ (repo / "scripts/termux/build.py").symlink_to(DRIVER)
+ (repo / "termux-build").mkdir()
+ (repo / "termux-build/payload").symlink_to(payload, target_is_directory=True)
+ tools = log.parent / "tools"
+ (tools / "python3").symlink_to(sys.executable)
+ env.update(HERMES_BUILD_COMMIT=identity[1] if identity[0] == "--commit" else "",
+ HERMES_PAYLOAD_TAG=identity[1] if identity[0] == "--tag" else "")
+ workflow = YAML(typ="safe").load((ROOT / ".github/workflows/desktop-bundled-release.yml").read_text())
+ step = next(step for step in workflow["jobs"]["termux-deb"]["steps"]
+ if step.get("name") == "Assemble the .deb")
+ bash = shutil.which("bash")
+ assert bash is not None
+ result = subprocess.run([bash, "-euo", "pipefail", "-c", step["run"]],
+ cwd=repo, env=env, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stdout + result.stderr
+ calls = recorded_calls(log)
+ assert [Path(call["args"][0]).name for call in calls] == [
+ "node-deps.mjs", "tui.mjs", "build_deb.sh",
+ ]
+ assert calls[-1]["args"][-2:] == list(identity)
+ assert (repo / "termux-build/deb/assembly-received-product").read_text() == str(
+ repo / ".build/termux/tui")
diff --git a/tests/scripts/test_termux_commit_identity.py b/tests/scripts/test_termux_commit_identity.py
index eecb7496800..2334eb78ee3 100644
--- a/tests/scripts/test_termux_commit_identity.py
+++ b/tests/scripts/test_termux_commit_identity.py
@@ -58,4 +58,4 @@ def test_deb_identity_refusal_leaves_payload_and_output_untouched(tmp_path):
(payload / 'app/pyproject.toml').write_text('[project]\nversion="9.9.9"\n', encoding='utf-8')
assert 'version' in invoke(['--commit', commit]).lower()
(payload / 'app/pyproject.toml').write_bytes((repo / 'pyproject.toml').read_bytes())
- assert 'payload missing python/' in invoke(['--commit', commit])
+ assert '--tui-product is required' in invoke(['--commit', commit])
diff --git a/tests/test_managed_runtime_resolution.py b/tests/test_managed_runtime_resolution.py
index 99e0ac5f9c0..597c0cbc3cb 100644
--- a/tests/test_managed_runtime_resolution.py
+++ b/tests/test_managed_runtime_resolution.py
@@ -11,8 +11,8 @@ from pm.package import InstallError
def test_workspace_uv_preserves_managed_tool_and_interpreter(monkeypatch, tmp_path):
ensure = importlib.import_module("pm.ensure")
- monkeypatch.setattr(ensure, "uv", lambda **kwargs: ("managed/uv", {"UV_PYTHON": "managed/python"}))
- monkeypatch.setattr(workspace, "_generate_pyproject", lambda *args: (tmp_path, False))
+ monkeypatch.setattr(ensure, "uv", lambda **kwargs: ("managed/uv", {"UV_PYTHON": "managed/python", "UV_CACHE_DIR": str(tmp_path / "cache")}))
+ monkeypatch.setattr(workspace, "_generate_pyproject", lambda *args, **kwargs: (tmp_path, False))
def reject_path(*args, **kwargs):
raise AssertionError("workspace commands must not resolve tools from PATH")
monkeypatch.setattr(shutil, "which", reject_path)
@@ -29,7 +29,7 @@ def test_workspace_uv_preserves_managed_tool_and_interpreter(monkeypatch, tmp_pa
def test_workspace_uv_missing_toolchain_never_falls_back(monkeypatch, tmp_path):
ensure = importlib.import_module("pm.ensure")
monkeypatch.setattr(ensure, "uv", lambda **kwargs: (None, {}))
- monkeypatch.setattr(workspace, "_generate_pyproject", lambda *args: (tmp_path, False))
+ monkeypatch.setattr(workspace, "_generate_pyproject", lambda *args, **kwargs: (tmp_path, False))
monkeypatch.setattr(shutil, "which", lambda name: "developer/uv")
with pytest.raises(InstallError, match="PM's uv and Python"):
workspace.lock_and_sync([], venv_dir=tmp_path / "venv", root=tmp_path)
diff --git a/tests/test_termux_launchers.py b/tests/test_termux_launchers.py
index 8259d88cdbc..ec1338e1f03 100644
--- a/tests/test_termux_launchers.py
+++ b/tests/test_termux_launchers.py
@@ -10,7 +10,7 @@ import sys
import pytest
-from scripts.termux.launchers import write_launchers
+from scripts.build.launchers import write_launchers
@pytest.mark.platforms("posix")
@@ -28,7 +28,8 @@ def test_launchers_forward_arguments_and_export_payload_environment(tmp_path):
)
(tmp_path / "json.py").write_text("raise RuntimeError('cwd shadowed stdlib')\n", encoding="utf-8")
entries = {name: "capture_entry:main" for name in ("hermes", "hermes-agent", "hermes-acp")}
- write_launchers(payload, entries)
+ write_launchers(payload, entries, python="venv/bin/python", repo="app",
+ site="venv/lib/python3.14/site-packages", target="linux-arm64-bionic")
bin_dir = tmp_path / "prefix/bin"
bin_dir.mkdir(parents=True)
for name in entries:
diff --git a/ui-tui/package.json b/ui-tui/package.json
index 977dbe4c355..b00b09a15f6 100644
--- a/ui-tui/package.json
+++ b/ui-tui/package.json
@@ -6,7 +6,7 @@
"scripts": {
"dev": "npm run build:ink && tsx --watch src/entry.tsx",
"start": "tsx src/entry.tsx",
- "build": "node scripts/build.mjs",
+ "build": "node ../scripts/build/tui.mjs",
"build:ink": "npm run build --prefix packages/hermes-ink",
"visual": "node scripts/visual/run.mjs",
"typecheck": "tsc --noEmit -p tsconfig.json",
diff --git a/ui-tui/scripts/build.mjs b/ui-tui/scripts/build.mjs
deleted file mode 100644
index f9494ca4301..00000000000
--- a/ui-tui/scripts/build.mjs
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env node
-// Bundles src/entry.tsx into a single self-contained dist/entry.js.
-// No runtime node_modules needed.
-import { build } from 'esbuild'
-import { readFileSync, writeFileSync } from 'node:fs'
-import { fileURLToPath } from 'node:url'
-import { dirname, resolve } from 'node:path'
-
-const here = dirname(fileURLToPath(import.meta.url))
-const root = resolve(here, '..')
-const out = resolve(root, 'dist/entry.js')
-
-// `react-devtools-core` is only imported when DEV=true at runtime (Ink dev
-// mode). Stub it out so the bundle doesn't carry the dep.
-const stubDevtools = {
- name: 'stub-react-devtools-core',
- setup(b) {
- b.onResolve({ filter: /^react-devtools-core$/ }, args => ({
- path: args.path,
- namespace: 'stub-devtools'
- }))
- b.onLoad({ filter: /.*/, namespace: 'stub-devtools' }, () => ({
- contents: 'export default { initialize() {}, connectToDevTools() {} }',
- loader: 'js'
- }))
- }
-}
-
-await build({
- entryPoints: [resolve(root, 'src/entry.tsx')],
- bundle: true,
- platform: 'node',
- format: 'esm',
- target: 'node20',
- outfile: out,
- jsx: 'automatic',
- jsxImportSource: 'react',
- // Skip the prebuilt @hermes/ink bundle and inline the source instead:
- // (1) esbuild's `__esm` helper does not await nested async init, so the
- // prebuilt bundle's lazy `render` would never resolve when nested in
- // this top-level Promise.all; (2) bundling from source also lets us
- // keep `ink-text-input` and the upstream `ink` graph OUT of the
- // bundle entirely — re-exporting them from entry-exports created a
- // circular async chain that hung the TUI at startup with only ANSI
- // reset bytes on screen (#31227).
- alias: { '@hermes/ink': resolve(root, 'packages/hermes-ink/src/entry-exports.ts') },
- plugins: [stubDevtools],
- // Some transitive deps use CommonJS `require(...)` at runtime. ESM bundles
- // don't get a `require` binding automatically, so we inject one.
- banner: {
- js: "import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);"
- },
- logLevel: 'info'
-})
-
-// esbuild preserves the shebang from src/entry.tsx into the bundle, but Nix's
-// patchShebangs phase mangles `/usr/bin/env -S node --foo --bar` (it strips
-// the `node` token, leaving a broken interpreter). The hermes_cli launcher
-// always invokes this file as `node dist/entry.js` anyway, so the shebang is
-// redundant — strip it.
-const body = readFileSync(out, 'utf8')
-if (body.startsWith('#!')) {
- writeFileSync(out, body.slice(body.indexOf('\n') + 1))
-}
-
-console.log(`built ${out}`)
diff --git a/ui-tui/src/__tests__/bundleNoAsyncEsmDeadlock.test.ts b/ui-tui/src/__tests__/bundleNoAsyncEsmDeadlock.test.ts
index 783c47df99b..f9e7bf614ed 100644
--- a/ui-tui/src/__tests__/bundleNoAsyncEsmDeadlock.test.ts
+++ b/ui-tui/src/__tests__/bundleNoAsyncEsmDeadlock.test.ts
@@ -60,7 +60,7 @@ beforeAll(() => {
if (!bundleIsFresh()) {
// Refresh the bundle so the regression test runs against current
// sources, not whatever was last committed by hand.
- execFileSync(process.execPath, [resolve(uiTuiRoot, 'scripts/build.mjs')], {
+ execFileSync(process.execPath, [resolve(uiTuiRoot, '../scripts/build/tui.mjs')], {
cwd: uiTuiRoot,
stdio: ['ignore', 'ignore', 'inherit'],
timeout: 120_000
diff --git a/web/package.json b/web/package.json
index 444e81dbd3e..eac7d35e501 100644
--- a/web/package.json
+++ b/web/package.json
@@ -5,8 +5,8 @@
"type": "module",
"scripts": {
"dev": "vite",
- "prebuild": "node ../scripts/generate-icons.mjs",
- "build": "tsc -b && vite build",
+ "prebuild": "node ../scripts/generate-icons.mjs --source .. --out ..",
+ "build": "node ../scripts/build/web.mjs",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"fix": "npm run lint:fix",
diff --git a/web/vite.config.ts b/web/vite.config.ts
index b23b716d063..00d5abbf30b 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -13,6 +13,9 @@ function compilerPreset() {
}
import tailwindcss from "@tailwindcss/vite";
import path from "path";
+import { fileURLToPath } from "node:url";
+
+const configDir: string = fileURLToPath(new URL(".", import.meta.url));
const BACKEND = process.env.HERMES_DASHBOARD_URL ?? "http://127.0.0.1:9119";
@@ -77,8 +80,8 @@ export default defineConfig({
],
resolve: {
alias: {
- "@": path.resolve(__dirname, "./src"),
- "@hermes/shared": path.resolve(__dirname, "../apps/shared/src"),
+ "@": path.resolve(configDir, "./src"),
+ "@hermes/shared": path.resolve(configDir, "../apps/shared/src"),
},
// When @nous-research/ui is symlinked via `file:../../design-language`,
// Node's module resolution would pick up shared deps from
diff --git a/website/scripts/prebuild.mjs b/website/scripts/prebuild.mjs
index 7e699c1781e..445f8a3b708 100644
--- a/website/scripts/prebuild.mjs
+++ b/website/scripts/prebuild.mjs
@@ -129,7 +129,7 @@ async function ensureUnifiedIndex() {
// logo ships a broken navbar.
console.log("[prebuild] generating icon assets…");
{
- const r = spawnSync("node", [iconGenScript], { stdio: "inherit", cwd: repoRoot });
+ const r = spawnSync("node", [iconGenScript, "--source", repoRoot, "--out", repoRoot], { stdio: "inherit", cwd: repoRoot });
if (r.status !== 0) {
console.error("[prebuild] icon generation failed — see the isolated icon-build runner output above");
process.exit(1);