Commit Graph

3192 Commits

Author SHA1 Message Date
Anthony Holten
8f12eb61fd fix(read_file): drop the SQLite extractor change; production never opens a live store
read_file fetches document bytes through the file backend (a `base64 <
path` subprocess) and extract_document_bytes runs _extract_sqlite on a
private temp copy, so the extractor never opens a live database. The
guarded header read cost more than it protected: it held _live_lock
across the open (a FIFO named *.db would stall every tracked open/close)
and folded missing-file, directory and permission errors into one
message. Restore tools/read_extract.py and drop its tests.

Also name DEFAULT_DB_PATH, _default_db_path() and session_db.db_path
among HX015's documented misses.
2026-11-11 17:20:00 +01:00
Anthony Holten
c50101e5f5 fix(state): route in-process state.db opens through connect_tracked
has_live_connection() and offline_file_access() decide when raw byte I/O
on a live database is safe (closing any raw fd cancels the process's
POSIX locks on the file; #100519). They only see connections opened
through connect_tracked, and several in-process readers used a bare
sqlite3.connect. The read_file SQLite extractor also open()/close()d the
file to check its magic bytes, which cancels the gateway writer's locks
when the agent reads its own state.db.

Route those opens through connect_tracked with tracking_path (same
URIs, timeouts and flags): gateway readiness, the lifecycle ledger's
integrity and journal-mode reads, the API server response store, the
spillover reference scan, install state, doctor, the repair damage
check, shared metrics, the worktree liveness reads cron's sweep runs in
the gateway, backup verification, the restore destination and epoch
reads, the downgrade guard, approvals suggest (whose hand-built URI also
skipped percent-encoding) and the journal-mode switch. The read_file
magic check goes through read_header_bytes_preopen. Offline opens
(snapshots, staging copies, the stdlib-only backup copier) take a
documented HX015 waiver.

Add HX015, "untracked sqlite3.connect on state.db", an advisory
heuristic rule until a replay shows it can block.

Fixes #149276
2026-11-11 17:20:00 +01:00
Ben Barclay
1bd13ebac8 feat(scope): the scope names the agent's owner and role; a turn carries its fence
A Scope now says who owns the agent and what the activity may do on it, and a TurnScope says
which claim the turn runs under:

- Scope gains keyword-only owner (Principal for a personal agent, Group for a shared one) and
  role ("owner" | "manager" | "member"). A personal agent is used only by its owner, so its only
  role is "owner"; a group agent's roles are "manager" and "member". can_administer is true for
  owners and managers. A hosted scope must name both; a local scope defaults to the local person
  as owner with role "owner", so every local caller is unchanged.
- TurnScope gains fence: Fence(epoch, generation), the owner epoch and runtime generation the
  admission claim stamped. bind_turn(session, turn, fence) requires it; claim_fence(row) reads it
  off a claimed session_admissions row. The authority's turn path, the owner-side cron run and
  the managed worker bind the real fence.
- Inside a hosted scope a bind must keep tenant, agent, actor, owner and role; changing any of
  them raises ScopeSwitchRefused.
- bind_profile_scope / scope_for_profile drop the unused turn= tuple: a turn is marked only with
  bind_turn, which has the fence.

Tests that executed a never-claimed admission row now claim it first, as the drain does
(tests/gateway/session_claims.py); hand-built cron rows carry the claim's columns.
2026-11-11 09:54:19 -05:00
Ben Barclay
b738747fe8 docs(code-health): HX016 grandfathers an existing setter call even when its function changes
The rule text promised migration when a function is next edited; the ratchet compares lines, so an
edit around an old call never required it. Say what it does, and pin it with a test.
2026-11-11 09:44:33 -05:00
Ben Barclay
ad90be9b08 fix(scope): terminal policies name their owner; binds copy what they keep
Round-2 review findings:

- A raw terminal mapping could still replace the bound profile's policy with
  another profile's. Raw policies now go through bind_terminal_policy(policy,
  profile_home=...): inside a bound scope only the bound agent's own policy is
  accepted. The four callers pass the session's owning profile.
- A partial bind (home_override=False) inherited the home override from an
  earlier change, so resetting that change took it away. A bind now copies the
  pieces it keeps, so it is whole on its own.
- bind_state switched directly between hosted agents and tenants. Inside a
  hosted scope only a bind of the same tenant and agent is allowed.
- Setters whose tokens are discarded grew the state chain without bound. Changes
  that can no longer be reset fold together on the next push.
- A cross-profile install_profile_terminal_scope dropped its env_overlay.
- HX016 flagged a bare 'from . import set_secret_scope', whose module it cannot
  know.
- The TUI heap-trim ordering test observes the whole-profile release.
2026-11-11 09:44:33 -05:00
Ben Barclay
f09f83088a fix(scope): hold scope, home, secrets and terminal policy as one value
Review found three ways around the guards in the first commit: set_terminal_scope
was unguarded (four production callers), set_secret_scope(None) cleared secrets
alone so get_secret fell back to the launch profile, and a stale or out-of-order
reset token moved one piece back while the others stayed. Guards around three
separate context variables leave every unguarded path able to split them.

The four pieces are now one immutable ScopeState in one context variable. Every
setter is a change to that value; a reset removes its own change and replays the
later ones, dropping those made inside a scope the result no longer has, so any
reset sequence lands on a state whole binds produce. Leaving a hosted agent by
any reset other than the bind that entered it refuses.

- set_terminal_scope narrows a bound local scope's own policy; clearing it, or
  setting it in a hosted scope, refuses. set_secret_scope(None) inside a scope
  refuses.
- bind_profile_scope and bind_state refuse a local bind inside a hosted scope.
- The TUI turn holds one token instead of four; housekeeping still runs under
  the session's whole profile scope and the release resets it at once.
- HX016 sees relative imports and no longer flags a local object named like a
  setter's module.
- The historical updater reads the override through get_hermes_home_override
  when hermes_constants no longer exposes the raw context variable.
2026-11-11 09:44:33 -05:00
Ben Barclay
151dc5fc3e feat(scope): one Scope value for home, secrets and terminal policy
Profile state lived in three independent globals (home override, secret
scope, terminal policy) that every entry point set separately, so they could
describe different profiles. 85 call sites set them by hand.

hermes_scope.Scope(tenant, agent, actor) is now the single value, in one
contextvar; actor is Principal(id) or System(reason), and TurnScope adds
session and turn. agent/runtime_scope.py is the one module that turns a scope
into profile state: bind_profile_scope binds and restores all of it together.
The process's own home keeps its launch semantics; any other home is hydrated
from that profile's sources and stamped as routed.

The legacy setters keep their signatures. Inside a bound scope, a call naming
another profile moves the whole scope (local) or raises ScopeSwitchRefused
(hosted). Gateway turns, cron, the TUI, model switch, kanban spawn and the
managed worker bind once at entry. HX016 blocks new direct setter calls;
existing ones migrate when their function is next edited.
2026-11-11 09:44:33 -05:00
Siddharth Balyan
3bcd071226 fix(ci): the supply-chain scan no longer counts a moved line as new (#153398)
* fix(ci): the supply-chain scan judges a moved file by what changed in it

The supply-chain pattern scan failed on a pull request that moves hermes_cli/_launchers.py to hermes_agent/hermes_cli/_launchers.py and leaves a small forwarding file at the old path. Git showed the old path as modified and the new path as an added file, so all 1,177 unchanged lines counted as added. Line 334, which builds a Windows launcher with exec and base64.b64decode and has been on main for a long time, was then reported as a critical finding.

The scan now runs git diff with --find-copies -l0. Git pairs the new file with its old path and shows only the lines that changed as added. -l0 removes git's file limit: on a diff of about 5,000 files git otherwise skips copy detection and also drops rename detection.

Copy detection alone would also hide a payload-shaped line that a pull request copies into a new file while the original file keeps it. The scan therefore still judges every line of a copied file that its source file still contains after the pull request. A line is treated as moved only when it left its old place.

It still reports a payload line added anywhere: new lines in a moved file, a new file, a copy of an existing file with a line inserted, and a copied line whose source still has it. Renamed files without a forwarding file were already judged by their changed lines and are unchanged. On the 5,230-file move range the scan takes about 8 seconds instead of 1.3.

* fix(ci): the supply-chain scan judges a moved line by whether the diff also removes it

The scan paired a moved file with its old path through git's copy detection and then re-read both files. That missed a payload line when one file was copied to two new paths, and it split lines at characters git does not treat as line ends.
The scan now diffs without rename detection and leaves out an added line only when the same diff removes a line with the same text, once per removed line. A second copy of a moved file and a copy whose source keeps the line are judged.
The copy detection, the name-status parser and the cat-file reader are removed, so the scan no longer needs git 2.38.

* fix(ci): the supply-chain scan treats a line as moved only between files of the same name

An added line was left out whenever the diff removed the same text anywhere, so a payload-shaped line deleted from a test fixture and added to another module produced no finding.
The removed line must now come from a file with the same file name, which is what a move to a new folder keeps. Text taken from a file of another name is judged.
2026-11-11 18:10:04 +05:30
Teknium
1fef533064 docs(config): drop documented keys nothing reads (agent.verbose, display.copy_shortcut, slack.reply_prefix)
- agent.verbose: the example config seeded it, but verbosity comes from
  --verbose / display.tool_progress (de5a88bd97 dropped the read).
- display.copy_shortcut: default added in 645a2f482d with no reader; the
  Ctrl+Shift+C binding never consulted it.
- slack.reply_prefix: the Slack docs promised a prefix on every message, but
  only the WhatsApp adapters read reply_prefix.

Part of #126448
2026-11-10 15:32:44 -08:00
John Paul Soliva
b80bb675a8 fix(gateway): cap image-URL downloads in agent replies at max_inbound_media_bytes
Image URLs in an agent reply are downloaded by Slack / Telegram / Feishu /
Mattermost / Weixin before upload, and those paths read the whole body into
memory with no cap, so a streamed unbounded body could OOM the gateway.
They now stream through the same capped reader the inbound path uses and
take the adapter's existing fallback when the cap is exceeded.

Rebased onto current main (adapters moved under plugins/platforms/, the
SSRF redirect guard went public as ssrf_redirect_guard). The capped reader
is made public too (read_httpx_body_with_limit) so the plugins do not add
new private-core imports; the Teams baseline entry for the old private
name is dropped.

Fixes #122667
2026-11-10 14:17:55 -08:00
unsupportedpastels
fbe9216c11 feat(gemini): Interactions API transport in the gemini provider plugin
Google's Interactions API is now the recommended Gemini interface and where
new Gemini capabilities launch. The gemini plugin now
supplies its own client (ProviderProfile.create_client), which sends each
call to Interactions or to generateContent per model:

- providers.gemini.gemini_api / providers.gemini.models.<m>.gemini_api:
  interactions | generate_content | auto (default). auto keeps
  generateContent except for INTERACTIONS_MODELS (empty for now, so
  default behavior is unchanged). Only the AI Studio host has Interactions,
  so Vertex express and proxy bases stay on generateContent.
- Stateless (store: false): the full history goes as typed steps, so
  compaction, branching and model switches behave as on generateContent.
  Thought signatures ride extra_content.google.thought_signature (the
  existing slot) and replay as thought steps.
- Streaming (step.start/delta/stop, arguments_delta, thought summaries and
  signatures), usage (thoughts folded into completion tokens), status to
  finish_reason, in-band errors mapped to HTTP-equivalent codes.
- Long decode continues requires_continuation hops with
  previous_interaction_id + continuation_token, which needs a stored
  interaction, so only those requests set store: true.
- A long-decode stream that drops resumes from its last mid-stream
  checkpoint token (same request, continued), as the generateContent path
  does. Output past the checkpoint voids it: resuming would repeat that
  output, so the turn is retried instead. The dropped hop is counted up to
  its checkpoint.

One core line: gemini_api joins the known providers.<name> keys, so setting
it no longer logs "unknown config keys ignored". Otherwise core is
untouched: the generateContent path is the existing GeminiNativeClient,
and the plugin rebuilds the same keepalive client and provider TLS settings
the core gives it.
2026-11-10 11:37:47 -05:00
kshitijk4poor
463044ae93 refactor(profiles): reuse the dashboard's config mutation lock; drop slop comments
config_mutation_lock.py duplicated web_server._CONFIG_MUTATION_LOCK (965a548788). The lock now lives
in web_server_profiles beside _SKILLS_PROFILE_LOCK; web_server re-exports it for the routers' LateState
lookups and profile_provision imports it with the scope helpers it already uses.

Comment pass: narration, move history and section banners removed from the
added code; long docstrings trimmed to their contract. The two now-identical create_profile name
checks in check_profile_create_entry.py merge into one branch, and _mirror_voice_sections runs
through _try (logged) instead of its own silent catch-all.
2026-11-10 14:09:08 +05:30
kshitijk4poor
96d816a10f refactor(profiles): one entry point for profile create
`hermes profile create`, `POST /api/profiles` and the Desktop/TUI
`profiles.create` RPC each called `create_profile()` and then ran their own
post-create steps (skills, alias, credentials, model, MCP servers, skill
selection). The same "new profile" therefore came out different
depending on where it was started, and a fix to one surface missed the
other two.

Add `hermes_cli/profile_provision.py` with
`provision_profile(ProfileCreateRequest) -> ProvisionResult`. Every surface
now builds a request and renders the result. `create_profile()` keeps the
folder work (validate, copy, strip channels, stage, publish, notify);
`provision_profile` runs every later step in one fixed order. A failing
later step never undoes the create: it is a warning in the result, as the
dashboard and RPC already treated it.

- The dashboard's model / MCP / skill-selection writers and the RPC's
  launch-credential mirroring moved into the module; the routers import
  them. Every config read-modify-write during create now holds the
  dashboard's `_CONFIG_MUTATION_LOCK` (MCP servers, voice sections,
  endpoint seed and base_url restore were unlocked on main).
- Plugins get no step here: since main's 6933155eaf the core create calls
  the selected memory provider's on_profile_created hook, so every surface
  already gets the provider's per-profile files.
- `scripts/check_profile_create_entry.py` (scripts/check, lint.yml) scans
  every production Python file and fails on any use of `create_profile`
  outside its definition and the new module: calls, imports, aliases, the
  function passed as a value, getattr by name, and files that do not parse.

Behaviour is unchanged on purpose: each surface passes the options it used
before (only the RPC mirrors launch credentials). Two small differences,
both on failure paths: a failing post-create step in the CLI prints a
warning instead of a traceback, and the RPC writes SOUL.md during the core
create (as the dashboard already did), so a failed write fails the create
instead of returning soul_written=false.
2026-11-10 14:09:08 +05:30
unsupportedpastels
bf4d330db0 fix(ci): only delegate to a twin from the same head branch and repository
A cancelled gate could pass on a live run of another PR that shares its head
SHA. Fork runs carry an empty pull_requests list, so the PR cannot be matched
without refusing every fork duplicate; require the twin's head_branch and
head_repository.id to match instead (both duplicates of one push share them).
Also soften the README: the last run to start never passes by delegation,
and a run cancelled while still pending never runs its gate.

Suggested by Greptile; narrowing from @BearHuddleston's review.
2026-11-09 22:16:54 -05:00
unsupportedpastels
d85c6f3974 fix(ci): fail closed with the report when a runs page is not an object
Catch AttributeError in the superseding-run lookup so a JSON list page keeps
the gate failing with its job report instead of a traceback.

Suggested by @BearHuddleston's review.
2026-11-09 22:16:54 -05:00
unsupportedpastels
6d84737945 fix(ci): delegate from approved fork duplicates by run start order
Order superseding runs by (run_started_at, id) so the later entrant to the
concurrency group, which is the one that cancels, carries the verdict. Let
attempt 2 delegate only when attempt 1 concluded action_required (a fork
run held for approval). Adds tests for a pending twin and the client-side
workflow/SHA/event check.

Patch from @BearHuddleston's review.
2026-11-09 22:16:54 -05:00
unsupportedpastels
3105eb1f6a fix(ci): page through event-filtered runs when looking for a superseding twin 2026-11-09 22:16:54 -05:00
unsupportedpastels
3bdbc97063 fix(ci): only let a cancelled duplicate run delegate forward to a newer twin
A cancelled run's gate may now pass only when a strictly newer run (higher id) of the same workflow, event and head SHA is live or succeeded, and only on the run's first attempt. Delegation is acyclic, so two cancelled duplicates can no longer vouch for each other and the newest cancelled run always fails.
2026-11-09 22:16:54 -05:00
unsupportedpastels
8c891f2d51 fix(ci): pass the gate of a cancelled duplicate PR run when its twin is live 2026-11-09 22:16:54 -05:00
Maciej Lisiewski
4e9ae2136b Merge pull request #151577 from NousResearch/fix/node-deps-fetch-before-delete
fix(build): keep the previous node_modules until the pnpm install succeeds
2026-11-09 22:32:14 +01:00
Maciej Lisiewski
38d4cbdf93 Merge pull request #152151 from NousResearch/just-ci-local
ci: more CI checks run locally as just recipes
2026-11-09 22:28:33 +01:00
Maciej Lisiewski
e60ab54588 fix(dev): just lint-docker selects every file CI's shellcheck action does
ludeeus/action-shellcheck (00cae500) also selects *.bash, *.ksh, *.zsh,
*.shlib and the shell rc/profile names. The local selector took only *.sh
plus shebang files, so a future docker/foo.bash would be checked in CI and
skipped locally. Both selections give the same 8 files under docker/ today.
2026-11-09 20:37:26 +01:00
Maciej Lisiewski
49a851b0ec fix(dev): just check-icons drops the CR Windows Python prints
On native Windows print() ends in CRLF and $(...) strips only the LF, so
HERMES_PYTHON kept a trailing CR and generate-icons.mjs could not spawn it.
The path is now printed without a newline.
2026-11-09 20:37:25 +01:00
Maciej Lisiewski
407ab834f1 fix(dev): just check-icons renders on the checkout's runtime environment
Locally the script left the interpreter to generate-icons.mjs, which takes
HERMES_PYTHON, else `python` on PATH. In an unactivated shell that is the
PM toolchain Python, and the renderer runs it isolated (-I), so Pillow and
resvg-py are missing. Outside Actions the script now selects the checkout's
runtime venv (pm.environments.project_python) through scripts/hermes-python.
On a runner it still uses setup-pm's HERMES_PYTHON unchanged.
2026-11-09 20:10:55 +01:00
kshitijk4poor
6933155eaf refactor(memory): take the Honcho-specific code out of core
Honcho left core on 2026-10-01 (7e53b3ef82) and ships from plastic-labs/honcho, but core kept
four places that know its file layout: profile create and rename edited Honcho's host blocks,
`hermes update` called the plugin's `sync_honcho_profiles_quiet()`, and the dashboard config
panel had a Honcho-only storage kind that imported the plugin's private `client` and `oauth`
modules (including its lock internals).

Replace them with seams any memory provider can use:

- MemoryProvider.on_profile_created / on_profile_renamed: called for the provider the profile's
  config selects, with that profile's home and its own .env secrets bound, from create_profile
  (CLI, dashboard, Desktop/TUI) and rename_profile. A failing hook, or an unreadable config, is
  logged and never fails the create or rename.
- STORAGE_PROVIDER for config_schema.py, with read_config_fields / write_config_fields on the
  provider: the provider owns its file layout; core keeps coercion, the memory.provider switch,
  the 400 on a refused write, and saves secrets to .env only after the provider accepted them.

Delete: hermes_cli/profiles_honcho.py, the CLI create's Honcho step, the update-time sync,
STORAGE_HONCHO_HOST_BLOCK and the host-block reader/writer, the empty `honcho: {}` config
root and its template block, HONCHO_API_KEY in _ENV_CONFIG_KEYS (the *_API_KEY rule covers
it), the dead check_config_yaml_readers exemption, and "honcho" as a hardcoded reserved
profile/subcommand name (alias collision now checks installed memory-provider names).
_record_profile_rename moves to profile_identity.py (profiles.py line budget).

Kept: honcho in the left-core migration (moves existing users onto the catalog plugin), its
env-var metadata, and comments that use it as an example.

Until the Honcho plugin implements these methods (catalog pin 7dd3702 does not), its dashboard
panel is empty, --clone creates no host block for the new profile and rename does not re-key
it; `hermes honcho sync` still creates missing host blocks by hand.
2026-11-10 00:16:18 +05:30
Maciej Lisiewski
f4bbeab788 ci(guards): hadolint runs from scripts/ci/lint_docker.sh, which just lint-docker also runs
The pinned hadolint digest moves from the workflow into the script, which CI calls as
`lint_docker.sh hadolint`. Locally the script also runs shellcheck on the files
ludeeus/action-shellcheck selects under docker/. Editing the script alone now starts the
docker_meta lane that runs it, without building an image.
2026-11-09 19:43:47 +01:00
Maciej Lisiewski
fa23d69165 feat(dev): just check-repo-guards and check-uv-lock run the guard scripts outside Actions
The repo-guards step scripts publish through RUNNER_TEMP, GITHUB_OUTPUT and
GITHUB_STEP_SUMMARY, and the supply-chain scan reads the PR's base and head, so run
locally they died on a KeyError. scripts/ci/local_step.sh gives each step throwaway
runner files and the merge base with origin/main as the PR base. It fails a step on a
non-zero exit or found=true, runs every step, and runs them on the bootstrap Python, as
the pre-setup-pm steps run. CI is unchanged.
2026-11-09 19:43:46 +01:00
Maciej Lisiewski
a11cecb2d8 ci(guards): check-icons runs the icon freshness step locally and in CI
The repo-guards icon step moves into scripts/ci/check_icons.sh, and CI now calls it
through `just check-icons` (setup-pm already precedes the step). On a runner the script
keeps the old whole-tree check, so it still catches files an earlier step left behind.
Anywhere else it diffs against a scratch-index snapshot, so uncommitted work is not
reported as icon drift and the real index is untouched.
2026-11-09 19:43:46 +01:00
Maciej Lisiewski
6750c484c3 refactor(build): move the node-deps lock and its programs into modules
The checkout lock, the child supervision and the heartbeat, watcher and
relay programs embedded as strings move out of node-deps.mjs:
node-deps-lock.mjs owns who may touch the trees, and the three programs are
real .mjs files (node-deps-heartbeat/-watcher/-relay.mjs) that lint and
navigation can see. node-deps.mjs keeps recovery, install and commit.
No behaviour change; the watcher's empty catches now say why.

The new files ship wherever node-deps.mjs did: the Dockerfile's
dependency layer, nix/webapp.nix, the webapp freshness inputs, the desktop
input-cache key, and the source-build test fixture.
2026-11-09 19:13:41 +01:00
Maciej Lisiewski
dc2c16efdb fix(build): read node-deps inputs once the checkout lock is held
The lockfile, projects and receipt key were read before lockCheckout,
which can wait 10 minutes. A run that waited out an update compared the
new trees with the old files: it reused a stale receipt or rejected a good
install. They are now read and validated after the lock is taken.
2026-11-09 19:13:41 +01:00
Maciej Lisiewski
16236f2166 fix(build): start the node-deps lock watcher before the installer
The relay started pnpm first and the watcher after it, with no error
handler: a watcher spawn failure (a process or descriptor limit) exited the
relay while pnpm went on writing the trees the failed run then restored.
The relay now starts pnpm only once the watcher has spawned, and hands it
the pid on stdin; a watcher that cannot start fails the run before
anything touches the trees.
2026-11-09 19:13:41 +01:00
Maciej Lisiewski
9bd3241914 fix(build): restore the trees and release the lock on Ctrl-C during install
node-deps had no SIGINT/SIGHUP listener, so a Ctrl-C or closed terminal
during pnpm killed it before the restore and the release: the next run
waited out the 30 s stale limit on a dead owner. The run now outlives the
job signals while its child runs (the child gets them too and exits), and
the CLI exits with the child's 128 + n so Ctrl-C still reports 130.
SIGTERM is left out: one aimed at node-deps alone still kills it and the
relay passes it on.
2026-11-09 19:13:41 +01:00
Maciej Lisiewski
70947e2f74 fix(build): end the node-deps lock wait when a dead lock cannot be replaced
A takeover rename that kept failing (EPERM/EBUSY/EACCES) skipped both the
deadline check and the sleep, so the wait spun past its limit. A failed
rename now waits like a live owner.
2026-11-09 19:13:41 +01:00
Maciej Lisiewski
aafb19ff96 docs(build): name the node-deps lock gaps a whole-tree SIGKILL and Windows leave 2026-11-09 19:13:40 +01:00
Maciej Lisiewski
91ad3787bf fix(build): count only retry settings pnpm 12 reads on a source launch
pnpm 12 reads neither npm_config_fetch_retries nor fetch-retries from an npmrc,
so treating them as the user's choice left pnpm's default of 2 retries (~70 s
offline) instead of the user's count or the launch's 1.
2026-11-09 19:13:40 +01:00
Maciej Lisiewski
2a42a58110 fix(build): keep node-deps failures from being masked by the lock
A run that lost its lock during the reuse check failed with a raw ENOENT from
the tree the new owner had moved; it now reports the lost lock. A release that
throws (a leaked guard past the wait bound) no longer replaces the error that
failed the run.
2026-11-09 19:13:40 +01:00
Maciej Lisiewski
d2a041890d fix(build): kill a stopped node-deps run's pnpm once it loses the lock
Ctrl-Z stops the whole job, pnpm included. A run stopped past the stale limit
lost its lock, but no check could run while it blocked in execFileSync, so on
`fg` its pnpm finished writing into the trees the next owner had installed and
certified.

pnpm and Electron's installer now run under a watcher outside the job (its own
session; taskkill /T on Windows) that re-reads the lock every 250 ms and kills
the child's process tree, stopped first so nothing forks meanwhile, once the
lock is no longer its run's. pnpm stays in the job, so Ctrl-C and Ctrl-Z reach
it as before, and a SIGTERM aimed at node-deps alone is now passed on to it.
A run that breaks a lock replaces it in one rename and waits 2 s before it
touches the trees, so the old owner's watcher acts first.
2026-11-09 19:13:40 +01:00
Maciej Lisiewski
3de0089f86 fix(build): keep the user's download retries on a source launch
A launch forced pnpm_config_fetch_retries=1 whenever the env did not set it,
overriding a count in pnpm's config.yaml or pnpm-workspace.yaml, or the user
npmrc's fetch-retries. Lower it only when none of them sets one.
2026-11-09 19:13:40 +01:00
Maciej Lisiewski
57c5f92abd fix(build): bound the node-deps lock guard wait
A leaked guard dated in the future (a network filesystem's clock ahead, or a
clock stepped back) never aged out by its mtime, so underGuard spun forever.
It is now judged like the lock, by staying unchanged on this process's
monotonic clock, and the wait stops at the lock's wait limit.
2026-11-09 19:13:39 +01:00
Maciej Lisiewski
482f48329b fix(build): keep the node-deps heartbeat through transient errors
One EBUSY/ESTALE/EMFILE from utimes stopped the heartbeat for good, so a
waiter broke the lock of an install that was still running and both pnpm
installs ran in one checkout. The heartbeat now stops only on release, when
the lock is gone, or when it holds another run's token.
2026-11-09 19:13:39 +01:00
Maciej Lisiewski
c1a408dba8 fix(build): a node-deps run that lost its lock touches nothing
The heartbeat worker's flag lagged a resumed process by up to a beat, and
restore, discard and the Electron step never consulted it. An owner stopped
past the stale limit could restore its old trees over the new owner's fresh
ones, or write a receipt for a tree another run built. Every recover, move,
restore, discard, receipt write and pnpm start now re-reads the lock file and
compares the token; a run that lost it exits without touching the trees or
the set aside.
2026-11-09 19:13:39 +01:00
Maciej Lisiewski
73ac5478fb fix(build): give up on an unreachable registry sooner when launching
A source launch (`hermes --tui`, the dashboard) that has to install waited ~70 s on
pnpm's default retries before failing offline and falling back to the previous build,
holding the checkout lock the whole time. Launches now retry a download once (~10 s).
Updates and explicit builds keep the defaults. The retry settings are left out of the
reuse receipt, which covers what is installed, not how it was downloaded.
2026-11-09 19:13:39 +01:00
Maciej Lisiewski
74e8848fd9 fix(build): judge the node-deps lock by a heartbeat, and bound the wait
The pid/host/start-time owner check kept a dead run's lock forever when its pid was
reused by another user's process (EPERM), on Windows and macOS (no start time), after a
hostname change, and it took over a live lock from a sibling PID namespace. The wait had
no limit, so `hermes update` and `hermes --tui` could hang with the remedy cut off a
narrow progress line.

The owner now refreshes the lock's mtime from a worker thread; a lock a waiter sees
unchanged for 30 s of its own monotonic clock is broken, whatever it names. Removals run
under a short guard and re-check the content, which also closes the three-way takeover
race. The wait gives up after 10 minutes, with the remedy at the start of the line. A
run suspended past the stale limit certifies nothing.

The moved-set record is written to a temporary file and renamed, so a kill or ENOSPC
mid-write cannot leave a record that breaks every later run, and a previous set that
cannot be deleted after a successful install no longer fails the run: the next run's
recovery removes it.
2026-11-09 19:13:39 +01:00
Maciej Lisiewski
992ecc841f fix(build): delete a node_modules in place when it cannot be moved aside
A node_modules that is a mount point (a container volume) cannot be
renamed (EBUSY), nor moved to a .cache on another filesystem (EXDEV).
moveAside then restored and threw, so no install ran. Such a tree is
emptied in place, as before the move-aside, and only it cannot be
restored. On Windows EBUSY means an open file, and it stays a failure.
2026-11-09 19:13:39 +01:00
Maciej Lisiewski
ba63979246 fix(build): serialise node-deps runs and make the move-aside crash-safe
Every run, --no-install and reuse checks included, restored a set left
in .cache/node-deps-previous without a lock. A launch beside an
install put the old trees back under it, and that install then wrote a
receipt for the new inputs over the old tree. A kill while the set was
being deleted left a partial copy, which the next run restored over
the fresh trees.

node-deps now takes .cache/node-deps.lock (owner pid, host and Linux
start time; a dead owner's lock is taken over) around recovery, the
reuse check, the install and the receipt. The set records its trees
before the first move and is marked complete after the last. A run
after a kill keeps a finished pnpm install (one that wrote
.pnpm-workspace-state-v1.json after the move) instead of restoring
over it, and finishes an interrupted move or restore. The set is
renamed away before it is deleted, and the receipt is written first.
The receipt also requires pnpm's installed lock to hold this
lockfile's importers.
2026-11-09 19:13:38 +01:00
Maciej Lisiewski
14accd54f1 fix(build): keep the previous node_modules until the pnpm install succeeds
node-deps.mjs deleted every installed tree before pnpm fetched anything.
The first pnpm install runs on an empty store, so an unreachable registry
left no node_modules and every later `hermes --tui` failed.

Move the trees under .cache/node-deps-previous instead, put them back if
pnpm or the Electron step fails, and drop them once the install succeeds.
A run killed mid-install gets them back on the next run. Installs still
start from empty trees, because pnpm won't restore gutted packages.

`pnpm fetch` cannot fill the store first in pnpm 12: it takes no filter,
and it rewrites node_modules/.pnpm itself, even when it fails.

Fixes #150031
2026-11-09 19:13:38 +01:00
teknium1
8719a66ef8 ci: limit the ajv declaration separator to ':' (drop '=>')
BearHuddleston: '(?::|=>)' also matched an arrow function returning ajv's id
(const f = $id => '<ajv id>'; fetch(new URL('/evil', f()))), stripping the id
and letting a fetch-base self-updater pass. No JS object declaration uses '=>',
so restrict the separator to ':'. Add arrow_fn_base and other_url_declared as
red cases (the latter pins that only ajv's exact id -- not any
raw.githubusercontent URL in a $id -- is exempt).
2026-11-09 08:36:59 -08:00
teknium1
267ab847fd ci: read the candidate file as utf-8-sig (BOM-tolerant)
The new _file_fetches_github read tripped the windows-footguns gate: a plugin
file BOM'd by Windows tooling must still be read, so use utf-8-sig.
2026-11-09 08:36:59 -08:00
teknium1
aa711165dd ci: exempt the ajv meta-schema by declaration in Python, not a grep lookbehind
Two review findings on the regex approach:
- Greptile: the fixed `$id: "` / `$ref: "` lookbehinds rejected harmless ajv
  bundles with quoted keys ("$id":) or minified spacing ($id:"...") -- the very
  false rejection this change removes.
- BearHuddleston: the lookahead left a `.../data.json/../../evil` traversal (Node
  normalizes it to a real GitHub path) and a real fetch sharing a minified line
  with the inert id.

Replace the overloaded grep pattern with a plain grep -E first cut plus a Python
refinement (_file_fetches_github): strip the inert ajv $id/$ref DECLARATION in
any quoting/spacing, then a real raw.githubusercontent / release URL remaining is
a true fetch. "#" is the only id terminator, so a traversal out of data.json is a
different, non-exempt URL; the literal reused as a fetch base is not a declaration
and stays flagged. Tests parametrize four legit declaration forms and four
adversarial forms (two traversals, beside-id, fetch-base).
2026-11-09 08:36:59 -08:00
teknium1
ae6a219527 ci: pin the ajv exemption to the schema-declaration prefix
Greptile (P1): exempting the ajv meta-schema URL by value let the same literal
be abused as an executable fetch base --
`new URL('/evil/repo/main/plugin.js', ajvUrl); fetch(u)...writeFileSync(__filename, body)`
-- whose only raw.githubusercontent occurrence is the exempt id, so the fetch
scan skipped the file and the write scan never saw it.

Pin the exemption to the `$id: "`/`$ref: "` schema-declaration prefix with
fixed-length negative lookbehinds, so the URL is inert only where ajv declares
its meta-schema. The executable-base form, a sibling refs path, and a traversal
all still trip the gate. Adds the new-URL-base exploit as an invariant test.
2026-11-09 08:36:59 -08:00