Files
hermes-agent/tools/delegate_tool_resumable.py
Jeffrey Quesnelle fe9a4b58ec feat(profiles): never run a profile on the host while a plugin runs it elsewhere (#156725)
* feat(profiles): never run a profile on the host while a plugin runs it elsewhere

One host gateway serves every profile by default and runs each profile's
cron, messaging platforms, Kanban dispatch and Webapp; the CLI, TUI and
desktop build agents on the host too. A plugin that runs a profile's whole
backend somewhere else (for example in a sandbox, through its own host
launcher) had no way to stop the host from also running that profile outside
it, reading config the sandbox can write.

A host-side plugin now marks such a profile in host-only storage under the
Hermes root, never in a profile home:

  <hermes root>/profiles_run_elsewhere/<profile>.json
  {"plugin": "<plugin name>", "since": "<ISO 8601 UTC>"}

The file's presence is the marker, and an unreadable marker still marks the
profile. Writers write a dot-prefixed temp file in the folder and rename it
over <profile>.json. hermes_cli.profiles_run_elsewhere reads it and gives
host-side plugin code mark_profile_run_elsewhere() and
clear_profile_run_elsewhere().

For a marked profile:

- profiles_to_serve() leaves it out, the default profile included, unless
  the caller passes include_run_elsewhere=True. The host gateway stops
  serving it at its next rescan, and the desktop cron ticker, /p/<profile>/
  routing and the dashboard's cron and session fan-outs skip it. Callers
  that only look for live gateways, count installed homes or read which
  worktrees a resumable subagent pins opt in (host attach, the launch
  profile policy, the multiplex counts, the worktree sweep's pin view).
- AIAgent refuses to build an agent for it (ProfileRunsElsewhere), whichever
  frontend asks, including a multi-profile host building a sibling's agent.
- CLI commands that run a turn exit 1 before any banner, TUI or gateway
  contact; `hermes serve` and `hermes dashboard` exit 78 before attaching or
  binding; the gateway process exits 78 before reading config.
- ensure_gateway_runtime() answers inaccessible / profile_runs_elsewhere
  before discovery, so nothing starts or attaches to it on the host.
- The dashboard's cron, session, file and Webapp requests for it answer 409,
  the desktop cron ticker's gate refuses it, and the Kanban dispatcher
  leaves its cards in ready (skipped_nonspawnable).

A process that cannot list the marker folder (permission denied) is the
backend the plugin runs, not the host: it refuses nothing. Any other error
reading the folder fails closed. A profiles folder the process cannot list
shows only the process's own profile instead of raising PermissionError.

_seed_file_if_missing moves to profiles_initialization.py, its only caller,
to keep profiles.py under its size cap.

* fix(profiles): close review gaps in the run-elsewhere marker

Follow-up to "feat(profiles): never run a profile on the host while a
plugin runs it elsewhere", from the first review of #156725.

Checks added where a host process could still run a marked profile:

- cron.scheduler_tick.tick() returns before the tick lock, the due scan or
  any job for a marked profile, so every in-process ticker skips it: the
  gateway's (its launch profile included), the desktop's, and the built-in
  fallback an external provider starts. CronScheduler.claim_fire() claims
  nothing for it, for a provider's inbound fires and the misfire sweep.
- AIAgent.run_conversation() makes the check AIAgent.__init__ makes, so an
  agent built before the profile was marked (a gateway's cached agent, an
  open dashboard or TUI session) runs no further turn.
- The dashboard's deferred agent build refuses first, before it binds the
  profile's scope or starts its MCP servers.
- `hermes gateway run` exits 78 in _prepare_agent_startup, with or without
  --force: before plugin discovery, shell-hook registration and the
  host-gateway attach guards.

The marker module:

- run_elsewhere_for_home() reads the home as written and as resolved, and
  refuses when either reading is marked. A symlink or junction to a profile
  home, a relative or `..` path, or the profile id in another letter case
  now reaches that profile's marker.
- mark_profile_run_elsewhere() publishes a new marker with a hard link,
  which never replaces a file: of two plugins that both found no marker,
  one claims the profile and the other gets the ValueError. Where the
  filesystem has no hard links it renames as before.
  clear_profile_run_elsewhere() returns False without unlinking when it
  finds no marker, so it cannot remove one published after it looked. No
  lock is taken.
- Only a missing marker folder means nothing is marked. A regular file in
  its place refuses every profile, like any other read error.
- The folder reader returns one shape, _MarkerFolder(names, error).
- mark_profile_run_elsewhere, clear_profile_run_elsewhere and run_elsewhere
  are listed in plugin_api.json and public-api.md is regenerated, so
  `hermes plugins validate` accepts a plugin that imports them by name.

Corrections to that commit's message:

- "A profiles folder the process cannot list shows only the process's own
  profile instead of raising PermissionError" now holds only for a process
  whose own home is a named profile under that folder (the backend a
  plugin runs elsewhere). Any other process gets the PermissionError, as on
  main, so activate_multi_profile_hosting_eagerly() fails closed again for
  a default-profile host that cannot list the folder.
- "Any other error reading the folder fails closed" did not hold for a
  regular file at the folder's path, which read as "nothing marked". It
  holds now.
- "Writers write a dot-prefixed temp file in the folder and rename it over
  <profile>.json": the Python API's first write of a marker is the hard
  link above. Its rewrite of an existing marker, and other writers, still
  rename.

Not changed: a gateway or a serve/dashboard backend already running as the
marked profile is not stopped. It runs no further turn and no cron job for
the profile, and stays up until it is stopped.

* fix(profiles): load no env file or secret source from a marked home

Second follow-up to "feat(profiles): never run a profile on the host while
a plugin runs it elsewhere", for the review finding "CLI runs code before
refusing" on #156725.

While a plugin runs a profile elsewhere, the backend it runs writes the
profile's home. Every `hermes` start loads that home when hermes_cli.main
is imported (load_hermes_dotenv), before argparse and before any refusal,
and so does the plugin's own host process. A `secrets:` source that
backend wrote into its own config.yaml therefore ran on the host as the
user: `secrets.command` through /bin/sh on Linux and macOS,
`secrets.onepassword.binary_path` as a program on every OS. A .env it
wrote reached the environment of every such start, overriding what the
process already had.

Now a dotenv load whose home is marked takes nothing from that home:

- load_hermes_dotenv() does not read, rewrite or publish the home's .env,
  does not load .op.env and resolves no `secrets:` source. It asks once
  per load (run_elsewhere_for_home: a path resolve and a listing of a
  folder that is normally not there) and treats the two files as absent,
  so the project .env takes the precedence it has for a home without a
  .env. The project .env, the administrator-managed .env, the
  config-backend boot and the terminal bridge are unchanged.
- The config-backend bootstrap (_bootstrap_env) takes no selector or plane
  credential from a marked home's .env or .op.env, also when it runs
  before the first load. bootstrap_deployment() passes the load's answer
  on, so one load asks once.
- hydrate_profile_secret_sources() resolves nothing for a marked home, so
  a host gateway or dashboard that serves the profile runs none of its
  sources either.

A process that is denied the marker folder is the backend the plugin runs:
its home reads as not marked and it loads its own files as before. A
marker folder that cannot be read for any other reason already refuses
every profile; no profile's env files or secret sources are loaded either
until it can be read, and the log line says so.

What this changes for a marked profile: a host process started under its
home has none of its .env values in the process environment and none of
the keys its secret sources supply. The marking plugin supplies what its
own host process needs.

Not covered: hermes_cli.config.load_env() and the readers built on it
(get_env_value, reload_env) still open the .env file when asked, and the
secret scope a multi-profile host builds for a profile it serves still
reads it. Neither runs anything.

* fix(profiles): start no command and read no env value from a marked home

Third follow-up to "feat(profiles): never run a profile on the host
while a plugin runs it elsewhere" (#156725), on top of "load no env file
or secret source from a marked home".

While a plugin runs a profile elsewhere, the backend it runs writes the
profile's home. Two kinds of host process still acted on what that
backend wrote there (measured under a marked profile with stand-ins that
only append a line to a file):

- Commands that start a command the profile's own files name, without
  building an agent. `hermes hooks test` ran a shell hook from
  config.yaml. `hermes mcp test` started an `mcp_servers` stdio command,
  and sent an HTTP server's request to the address in its entry.
  `hermes secrets onepassword status` and `sync` ran the program
  `secrets.onepassword.binary_path` names. `hermes send` loaded the
  home's .env into the process with a loader of its own.
- Code that reads one env value on demand. The previous commit stopped
  the dotenv load; load_env() and get_env_value() still opened the
  home's .env. So `hermes status` listed keys that backend wrote as
  configured, `status --all` sent a request with a bearer from the file
  to a URL from the file, `status`, `dump` and `auth list` copied its
  keys into the profile's auth.json, and HERMES_REDACT_SECRETS was taken
  from it.

Now, for a home that is marked:

- tools.hosted_tool_policy: the four host features that start a process
  from the profile's files (RUNS_PROFILE_COMMANDS: shell_hooks,
  mcp_stdio, cron_scripts, skill_inline_shell) are off, at the place
  each already asks whether it may run in a hosted scope, and
  host_feature_refusal() answers with the run-elsewhere message. The
  one subprocess site of shell hooks starts nothing (`hooks test`,
  `hooks doctor`, a hook registered before the profile was marked), and
  the MCP stdio transport starts nothing, whoever asks.
- The MCP probe (_probe_single_server: `mcp test`, `mcp add`,
  `mcp configure`, `doctor`, the dashboard and TUI routes) raises
  ProfileRunsElsewhere before it validates, resolves, starts or calls a
  server, stdio or HTTP. `mcp login` and `mcp reauth` refuse first,
  before they drop the stored tokens or the device flow calls the
  entry's server.
- `hermes secrets <source> <verb>` exits 1 with the message of the
  commands that run a turn (one wrapper where the verbs are registered).
- `hermes send` exits 1 the same way, before its own loader reads the
  home's .env and config.yaml credentials into the process.
- agent.secret_scope.load_env_file(), the one .env tokenizer, reads a
  file in a marked home as empty and does not open it. That covers
  hermes_cli.config.load_env(), get_env_value(),
  get_env_value_prefer_dotenv(), reload_env(), the credential pool's
  seeding from .env, and the secret scope a multi-profile host builds
  for a profile. Hermes's own .env writers (save_env_value,
  remove_env_value) do not read through it and still write the file, so
  a key the user saves through the marking plugin's host process lands
  there. A file in any other folder (a plugin's host-only copy) reads as
  before.
- `hermes status --all` does not probe LM Studio at model.base_url: with
  the .env values out of reach, the address in config.yaml still sent a
  request from the host.
- `hermes status` and `hermes config` print one line saying that the
  profile's .env keys are not read on this host, because they now show
  as not set.

The check behind the tokenizer and the features is
profiles_run_elsewhere.home_runs_elsewhere(home): the answer of
run_elsewhere_for_home, kept per process and home. Each call stats the
marker folder and the home's marker file, and asks again when that
differs from the stat taken before the last asking, so a marker written
or removed by any process is seen at the next call. A marker folder that
cannot be read marks every home, as it does for running a profile, and
is asked about again every time. A process that is denied the folder is
the backend the plugin runs: it reads its own .env and runs its own
hooks and MCP servers as before.

This corrects the previous commit's message, which said "Not covered:
hermes_cli.config.load_env() and the readers built on it (get_env_value,
reload_env) still open the .env file when asked, and the secret scope a
multi-profile host builds for a profile it serves still reads it". Both
are covered now.

Not covered: config.yaml of a marked home is still read (`hermes status`
and `hermes config` show it). `quick_commands` of type exec still run in
a chat client, gateway or TUI backend that was already running when the
profile was marked. resolve_home_dotenv() (two config migrations) still
parses the home's .env. Plugins in the home are still discovered.

* fix(profiles): no quick command runs for a profile that runs elsewhere

A quick_commands entry of type exec is a shell command in the profile's
config.yaml, a file the backend the plugin runs writes. The refusals so
far keep a hermes command from starting, on a marked home, a process
that dispatches one. Three cases still reached the three places that
start the command (the classic CLI, the gateway, the TUI / dashboard
backend):

- a chat client, gateway or backend that was already running as the
  profile when it was marked: its turns are refused, its slash commands
  were not;
- a dashboard or `hermes serve` backend on another profile's home, whose
  command.dispatch takes the profile with the request (the `profile`
  parameter, or a session of that profile);
- a multiplexing gateway: its own quick commands are the default
  profile's whichever profile's process started it
  (load_gateway_config_for_runner), so a gateway started from a named
  profile while `default` is marked had them.

Each of the three places now asks run_elsewhere_refusal() before it
starts the command and answers with the run-elsewhere message instead.
The home asked is the one whose config.yaml names the command: the home
bound for the request in the TUI / dashboard backend and for a local
session of the gateway, the process's own in the classic CLI, and for a
gateway's messaging commands the home its config was loaded from
(_hm_quick_commands_home: the default profile's when it multiplexes).

Alias quick commands are unchanged, and so is the backend the plugin
runs, which does not see the marker.

* test(profiles): fire the marker race helper after the module's own look

`_between_look_and_change` runs an action right after the marker module's
next look at a profile's marker, to play the writer that gets in between a
look and a change. It patched `os.listdir`, `os.lstat` and `_read_entry`,
and fired as soon as a call for the marker returned.

The suite's home guard (`tests/home_io_guard.py`) wraps `os.lstat` too, and
resolves the path before it calls the real function. On POSIX
`os.path.realpath` lstats every component of the path through `os.lstat`,
so the helper saw the guard's own lstat of `<profile>.json` first and fired
inside the guard, before the module's lstat had run. In
`test_a_clear_that_found_no_marker_never_removes_one_published_after_it_looked`
the other plugin's marker was therefore already in place when
`clear_profile_run_elsewhere` looked, and the call raised `ValueError`
instead of returning False. On Windows `realpath` does not call `os.lstat`,
so the test passed there and failed on Linux only.

The three wrappers now share a depth counter and fire only when the
outermost patched call returns: a look made inside a look is part of it.
The action runs at the same point on both systems, after the module's own
look and before its change. No product code changes.

* fix(mcp): refuse "mcp add" first for a profile a plugin runs elsewhere

`hermes mcp add` reached the run-elsewhere refusal only inside its probe,
and treated it like any failed connection: it printed "Failed to connect"
and offered "Save config anyway", which wrote the server entry (disabled)
into the marked profile's config.yaml. For an HTTP server it had by then
asked for a bearer token and saved it to the profile's `.env`.

`cmd_mcp_add` now refuses before its first question, the way `send` and
the `secrets` verbs do: the message on stderr, exit 1, nothing asked and
no file of the profile changed.

The probe's other callers leave nothing written when the probe refuses
(`mcp test`, `mcp configure`, the dashboard and TUI test routes, the
connector install, the OAuth flows) and are unchanged.

* test(profiles): gate the Windows letter-case test with the platforms marker

`test_a_profiles_folder_spelled_in_another_letter_case_reads_the_marker_on_windows`
was gated with a bare `skipif(os.name != "nt")`. The Windows lane imports
only files that carry a `platforms(...)` spec covering Windows and selects
with `-m platforms`, so the test ran on no CI host (tests/AGENTS.md: "Use
the marker, never a bare `skipif`"). It now carries
`@pytest.mark.platforms("windows")`. No other test this branch adds gates
on the host with a `skipif`.

* docs(dashboard): say which requests _cron_profile_home() refuses

The helper's docstring said that the host "neither reads nor runs" a marked
profile's "jobs, sessions or files". The helper answers 409 only to the
requests that resolve their profile through it: every cron request (an omitted
profile resolves to the backend's own), and the session and file requests that
name the profile. A session or file request with no profile uses the backend's
own home without asking the helper, as the description's "Not covered" section
says. The docstring now says that. No code change.

Found in review.

* fix(profiles): ask again when a home's link leads to another profile

home_runs_elsewhere() keeps its answer per process and home path, and held it
valid while a stat of the marker files it had worked out was unchanged. Those
files belong to the directory the path led to at the first asking. When the
home is a symlink or junction and the link is pointed at another profile, no
marker is written or removed, so the kept answer stayed: pointed at a marked
profile, run_elsewhere_for_home() refused the home while load_env_file() still
read the marked profile's .env; pointed away from one, the unmarked home's
.env read as empty. Reproduced with a symlink on Linux and with a symlink and
a junction on Windows. A link above the home (the root itself) was already
seen, because the marker paths are read through it.

The kept answer is now also for the directory the path leads to: each call
stats the home and compares device and file id with the stat taken before the
home was resolved. That is one more stat per call. Measured for a plain home,
the cached check goes from 2.5 to 5.4 us on Linux and from 7.0 to 12.3 us on
Windows, and load_env_file() from 17 to 20 us and from 104 to 112 us; through
a link on Windows the check goes from 27 to 71 us. Resolving the home at every
call instead would add 23 us on Linux and 87 us on Windows, more than the
whole check.

Found in review.

* fix(profiles): a second name for a marked profile's home is not served either

Found in review. With profiles/alias a link to profiles/ops (a symlink, or a
junction on Windows), marking ops took only the name ops out of
profiles_to_serve(): the list was filtered by name, so the host gateway kept
alias in its served set, although every check that asks by home refused it.
Two more checks asked by name and let the link through: the Kanban
dispatcher's profile_exists_here(), and the dashboard's profile resolution
_cron_profile_home(), behind the cron, session, history and file requests
that name a profile.

All three now ask by home. The served list and the dispatcher use the kept
answer of home_runs_elsewhere(), which costs stats per profile instead of a
resolve and a folder listing; the dashboard asks run_elsewhere_for_home()
and answers 409 with the marked profile's name. The kept answers hold 4096
homes instead of 256, so a host with several hundred profiles still answers
its list from stats.

* fix(profiles): a clone made under a marked name keeps the keys it was cloned with

Found in review. Creating a profile mirrors the launch profile's .env into
it, but only over the seeded comment-only stub, never over the keys a clone
brought. That check asked the .env tokenizer what the new file holds, and
the tokenizer answers with nothing for a home a plugin runs elsewhere. A
profile cloned under a name whose marker was already there (left behind
when an earlier profile of that name was deleted) therefore looked empty,
and the launch profile's .env was copied over the cloned keys.

The check now reads the destination as the file it is
(load_env_file(..., for_overwrite_check=True)). Nothing else reads a marked
home's .env: every value reader still gets nothing from it. A new profile
whose .env is the stub still receives the launch keys, marked name or not,
as every new profile does.

* fix(profiles): a marker covers its profile's directory under every name

Found in review, as the mirror of the link case fixed before: with
profiles/ops a symlink or junction to profiles/real and ops marked, the
directory's own name real was still listed, served, built and run on this
host, and its .env was read. A home was followed to the profile its path
leads to, but not to the other names that lead to its directory, while the
backend elsewhere runs in that one directory whatever it is called.

run_elsewhere_for_home() and home_runs_elsewhere() are the two functions
every refusal asks. Both now also compare the home's directory (device and
file id) with the home of each profile the root's marker folder marks, so a
marked name that is itself a link marks the directory it leads to, under
that directory's own name too. An error or a filesystem without file ids is
never a match.

The kept answer of home_runs_elsewhere() adds one stat per other marked
profile, which also sees a marked link pointed at another directory. It
learns of a new marker under another name from the marker folder's time, so
a listing taken less than two seconds after the folder changed is not
relied on and is taken again at the next call, without resolving the home
again: two changes can share one tick of a filesystem's clock.

* fix(profiles): home maintenance waits while a plugin runs the profile elsewhere

After an installed revision changes, the first start of each profile runs
home maintenance for its own home (boot_bootstrap): the config migration,
which first copies config.yaml and .env beside themselves as
<name>.bak-<stamp>, the plugin-catalog cache drop, launcher publication and
the default-plugin check. Every hermes command and the gateway process make
that call before any command can refuse. A host start under a marked
profile, the marking plugin's own status and switch-off commands included,
therefore rewrote config.yaml under the backend the plugin runs and left a
byte copy of the keys file in a home that backend reads and writes.

run_boot_bootstrap now asks run_elsewhere_for_home() for this process's
home when maintenance is due (a new revision, or a step still owed), before
it takes the record lock. For a marked home it runs no step and writes no
record, so the maintenance stays owed and the first start after the marker
is gone does it. The question is asked by home: a marked home reached
through a link, and the directory behind a marked link, are covered. The
backend the plugin runs (it is denied the marker folder) and every unmarked
profile, the default one included, are maintained as before. A marker
folder that cannot be read holds maintenance back, as it refuses every
profile.

A start whose record says this revision is done reads its record and
returns as before; nothing is asked on that path.

One log line says why: "home maintenance: the '<plugin>' plugin runs
profile '<name>' elsewhere, so this host leaves its home alone; it is owed
until the profile runs here".

* fix(profiles): the backend migration does not move a profile a plugin runs elsewhere

`hermes gateway migrate --backends --apply` and the dashboard's "move to the
gateway" request (`POST /api/gateway/migrate/backends/apply?profile=`) went
ahead for a profile a plugin runs elsewhere. The move wrote `.env` and
`config.yaml` in that profile's home, installed and started a gateway service
for it and stopped its old backend. The gateway then refused to run the profile
and exited, so the run could only end in its rollback, which put the saved
`.env` and `config.yaml` back over whatever the backend the plugin runs had
written in the meantime.

The refusal a marked profile gets everywhere else is now one of the blockers
the apply path adds before anything changes. The command exits 3 with it, the
dry run and `GET /api/gateway/migrate/backends/plan` list it, and the
dashboard's request answers 409 and starts no run.

* fix(profiles): the config.yaml of a profile a plugin runs elsewhere sets no host environment variable

Importing `gateway.run` copies settings of the launch home's `config.yaml` into
the process environment. Among them is every top-level scalar of the file,
under the scalar's own name when that name is not set yet. `hermes -p <profile>
gateway status` imports the module, and so does the gateway process before it
refuses a marked profile. While a plugin runs the profile elsewhere, the
backend it runs writes that file, so it could choose `LD_PRELOAD`,
`NODE_OPTIONS`, `PYTHONPATH` or a proxy for that host process and for every
program the process starts afterwards. The home's `.env` was already closed for
this reason; `config.yaml` was a second way in.

`load_launch_home_dotenv()` in `env_loader.py` asks once whether a plugin runs
the launch profile elsewhere, runs the dotenv load with that answer
(`load_hermes_dotenv(home_elsewhere=...)`, the keyword the bootstraps already
take) and returns it. `gateway.run` calls it where it called
`load_hermes_dotenv`, and for a marked home it does not read the file for its
bridge. A home without a marker is asked about as often as before, and its
bridge is unchanged.

* fix(profiles): reading an env file under a folder named like ~user no longer raises

`load_env_file()` asks whether the file's folder is the home of a profile a
plugin runs elsewhere. That question expanded a leading `~name` with
`Path.expanduser()`, which raises `RuntimeError` when no user has that name.
So on Linux and macOS, with no marker anywhere, a relative path whose first
folder is named like `~someone` made the tokenizer raise ("Could not determine
home directory."), where it had always read the file as written or returned
`{}`. Windows guesses a folder for any `~name` and did not raise.

The marker question now expands with `os.path.expanduser()`, as its stat of the
home already did: a `~name` that is no user's stays as written, which is the
path the read opens.

* fix(profiles): the refusal says how to get a profile back when its plugin is gone

A marker can outlive the plugin that wrote it: the plugin was removed or
disabled, it no longer loads, or the Hermes root came back from a backup taken
while the profile ran elsewhere. The owner then meets the refusal at every
command that runs the profile, and its advice was to turn this off in a plugin
he no longer has. Core has no command that clears a marker, and the refusal
named neither the file nor another way.

The refusal for a marker that names its plugin keeps its sentences and ends
with one more: if that plugin is no longer installed or no longer loads,
deleting the marker file (named by its path) lets Hermes run the profile on
this computer again, and the file is not to be deleted while the plugin still
runs the profile. The user guide says the same.

* test(profiles): marking a profile leaves the marker folder listable by other local users

On Linux and macOS `mark_profile_run_elsewhere()` sets the marker folder to
0755. A host service that runs as another local user must be able to list the
folder: a listing that is denied reads as "this process is the backend the
plugin runs", and such a process refuses nothing. No test noticed when that
`chmod` was removed. This one marks under umask 077, and marks again after the
folder was made 0700, and expects 0755 both times.

* test(profiles): the quiet-folder test no longer depends on how fast it runs

`test_a_marker_folder_that_has_been_quiet_is_not_listed_again` expects 150
listings of the marker folder "a moment after the marker was written". The
module stops listing once the folder's time is two seconds old, so a test run
that stalls for two seconds between writing the marker and the end of that loop
counts fewer listings and fails. It did once on a loaded machine.

The test now stands the module's clock at the folder's own time before it asks
for the first time, as it already moved that clock forward for its second half.

* test(profiles): the marker question by home does not raise for a folder named like ~user

The dotenv load asks whether a plugin runs a home's profile elsewhere through
`run_elsewhere_for_home()`, which expanded a leading `~name` the way the
tokenizer's question did. The test of a folder named like a user that does not
exist now asks through both, so each of the two expansions has a test that
fails when it raises again.

* fix(profiles): the backend migration plans no step against a profile a plugin runs elsewhere

The block for a marked profile sat among the blockers of the apply path, which
a plan that can only be done by hand never reaches. On Windows every plan is of
that kind, and there the backend a plugin runs is a process of this host
(`hermes serve --isolated` under the profile's home). So `hermes gateway
migrate --backends --apply`, with or without `--dry-run`, found that process as
an old backend of the marked home, exited 6 and printed the steps of a move by
hand: `taskkill /PID <its pid> /T /F`, then installing a gateway for the
profile.

The refusal is now the first answer of the plan's own owner check, which every
form of the plan passes before a step is chosen. A marked home gets a blocked
plan (exit 3) with the run-elsewhere message and no step, on every platform;
the dashboard's plan and apply routes read the same plan.

* test(profiles): the public marker functions are pinned by what the validator does

`test_the_user_guides_marker_example_validates_clean` read the user guide from
the repository, cut its Python example out, parsed it and compared the names
it imports with a list. That is a test of a file's text. What it guarded is
that `hermes plugins validate` calls the three documented marker functions
public, and `test_the_documented_marker_functions_are_public_plugin_api`
already pins that by running the validator on a plugin that imports them:
with one of the three taken out of the public list, that test fails.

The guide-reading test is removed. The other tests of this branch read only
files under their own temporary homes.

* fix(profiles): no form of the backend migration acts on a profile a plugin runs elsewhere

The block for a marked profile sat in the migration's plan, and several
forms of `hermes gateway migrate --backends` never reach the plan or act
before it:

- `--apply --detach` started the run in the background and reported it as
  started; only that run then refused.
- `--restore` undid a move that was made before the profile was marked: it
  stopped and removed the gateway service, wrote `config.yaml` and `.env`
  back from the move's backups and started the old backend.
- A move that did not finish was rolled back the same way by the next
  `--apply` or `--restore`, and the dry run named the command that does it.
- A second `--apply` on a moved home named `--restore`.
- Every form but the dry run made the run lock in the marked home first.

The command now refuses where every form enters: for a marked profile
`--apply` and `--restore`, with any other flag, exit 3 with the
run-elsewhere message before the home's record is read or its lock is made.
Nothing is written, started or stopped, and the record of an earlier move
stays for when the profile runs on this host again. `--status` still reads.

The dashboard's `POST /api/gateway/migrate/backends/apply` and
`.../restore` answer 409 `blocked` with the same message for a marked
profile, start no run and name no command.

* fix(profiles): the lists of old backends say when a plugin runs the profile elsewhere

The backend a plugin runs for a profile can be a `hermes serve` process of
this machine, which the backend migration's scan finds like any other old
backend of that home:

- `hermes gateway migrate --backends` listed it without a word about the
  plugin and ended with the line that offers the dry run of its move.
- After `hermes update`, the notice called it "an old Hermes backend for
  this profile" and offered the same dry run.
- The rows the dashboard's plan route returns said nothing about it either.

A listed backend whose home's profile a plugin runs elsewhere now carries
one more note, in the report's text and JSON and in the dashboard's rows:
"Profile 'ops' runs elsewhere (the 'x' plugin runs its backend): Hermes
does not move this backend to the gateway on this host." The report offers
no dry run when its own profile is marked, and the update prints no notice
for such a profile. The move itself is already refused for it.

* fix(profiles): the blocked plan of a profile a plugin runs elsewhere lists no backend to move by hand

Where a backend can only be moved by hand (on Windows every one), the plan
of a marked profile printed no step but kept the entry above the blocker:
"manual cannot be migrated automatically ... Run the steps below in
PowerShell or Command Prompt ... Steps, in this order", with nothing under
it. The dashboard's card prints "This server cannot be moved from here" and
those instructions for every such entry.

The marker's check is now its own step of the plan, before the checks of
which gateway serves the home, and the plan it blocks lists no backend at
all: the text is the home and the blocker, and the JSON has an empty
`unsupported`. The other reasons a plan is blocked print as before.

* fix(profiles): the refusal's last sentence says "on this host" like the sentences before it

The sentence the refusal gained for a plugin that is gone said that deleting
the marker file "lets Hermes run the profile on this computer again", two
sentences after "Hermes does not run it on this host". The message and the
user guide say "host" everywhere else, so this sentence does too.

* test(profiles): the line for a listed backend says what the marker tells

The line a listed backend of a marked home carries has three forms: the
plugin by name, "a plugin" when the marker file cannot be read, and "Hermes
cannot read <folder>" when the marker folder cannot be read. The tests of
the report covered the first. This one reads all three from real markers.

* fix(ci): a change to the run-elsewhere marker module starts the update suite

The notice `hermes update` prints about an old backend
(hermes_cli/update_backend_notice.py) now asks whether a plugin runs the
profile elsewhere, so it imports hermes_cli/profiles_run_elsewhere.py. The
change classifier did not route that module to the upgrade E2E lane, and
tests/ci/test_update_ci_routing.py failed for it:

    e2e_upgrade: imported by the update path but not routed to it:
    {'hermes_cli/profiles_run_elsewhere.py': ['hermes_cli/update_backend_notice.py']}

The module joins the lane's owner list, beside the backend-migration marker
the same notice reads.

* fix(profiles): a marked profile's key_cmd is not run on this host

`providers.<id>.key_cmd`, and a custom provider's `key_cmd`, is a shell
command line in the profile's own `config.yaml`. Hermes runs it to get the
provider's key, with the profile's environment and credentials. For a
profile a plugin runs elsewhere, the backend there writes that file, and
nothing on this path asked the marker: the dashboard's
`GET /api/model/options?profile=<name>` ran a marked profile's command once,
as it does for any profile.

`_mint`, the one place every `key_cmd` runs, now raises `CommandTokenError`
with the run-elsewhere message for a marked profile. The model picker turns
that error into a probe without a key, so it still answers; the same request
now runs the command zero times.

The fix and its test are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a dashboard file request never dials a marked profile's SSH workspace

A file request that names a profile is answered 409 when a plugin runs that
profile elsewhere. For a profile whose workspace is on an SSH host the
request went another way first: `_fs_backend` read `terminal` from the
profile's `config.yaml` and dialed the host named there before the route
reached the refusal. `GET /api/fs/list?profile=<name>` and
`GET /api/fs/default-cwd?profile=<name>` dialed the host a marked profile's
config names.

`_fs_backend` now resolves the profile first, which answers 409 for a marked
one before its config is read. Every file route that can go to an SSH host
passes through it. A request that names no profile behaves as before. Two
existing tests call the real `_fs_backend` with a profile that is not on
disk; they now stand in for the lookup.

The fix and its tests are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): gateway ensure and attach refuse a marked profile whose directory is a link out of the root

A marker covers the profile's directory whatever path leads to it. But
`ensure_gateway_runtime` made the home canonical before it asked the marker.
When `profiles/ops` is a link to a directory outside the Hermes root, the
canonical path has no Hermes root above it and so no marker: `gateway ensure`
went on to discovery for a marked profile and did not answer
`profile_runs_elsewhere`. `attach_gateway` resolves the home before it calls
`ensure`, so it went the same way.

Both now ask about the home as it was given too. In `ensure` the check sits
inside the existing assignment, which keeps the function at the complexity
cap; `attach_gateway` checks before it resolves. The answer for a marked
profile is the one `ensure` already gave: `inaccessible`,
`profile_runs_elsewhere`, the refusal in `detail`.

The fix and its test are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): marked profiles still count when an external cron registry may be shared

An external cron provider keeps one remote registry that is not scoped to a
profile, so Hermes uses it only on a host with a single profile. Two callers
decide that by counting the served profiles, and a profile a plugin runs
elsewhere is no longer in that list:

- The gateway chose its scheduler with the number of profiles it ticks. On a
  host with `default` and a marked `ops` that number is 1, so the gateway
  kept the external provider, which reconciles the registry toward
  `default`'s jobs when it starts.
- The dashboard skips an external reconcile when it counts more than one
  profile. With the other profiles marked, the reconcile ran.

On main both counts included `ops`. If the backend elsewhere arms that
profile's jobs through the same provider account, such a reconcile can
cancel them.

Both callers now count the marked profiles where the question is who may
share the registry. The profiles the gateway ticks and the dashboard lists
are unchanged. Three existing stand-ins for `_cron_profile_dicts` accept the
new keyword.

The fix and its tests are the reviewer's patch from the review of
6a60a75a669, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a marked profile's speech command is not run on this host

`tts.providers.<name>.command` and `stt.providers.<name>.command` are shell
command lines in the profile's own `config.yaml`, and one runner starts
both. The dashboard reaches it for a named profile without building an
agent: `POST /api/audio/speak?profile=<name>` ran a marked profile's TTS
command, and `POST /api/audio/transcribe?profile=<name>` ran its STT command
and returned what it printed. The backend a plugin runs elsewhere writes
that file, so this is the host starting a command line that backend wrote,
as with a provider's `key_cmd`.

`run_command_provider`, the one place both kinds run, now raises
`RuntimeError` with the run-elsewhere message for a marked profile. The
callers already turn a `RuntimeError` of the runner into their own failure
answer, so the speak request answers 400 with the message and the
transcribe request answers that the transcription failed.

* fix(profiles): the gateway's clients ask about a linked profile's home before they resolve it

`gateway ensure` and `gateway attach` now ask the marker about the home as
it was given. Two callers resolve the home before those functions see it,
so a marked profile whose directory is a link out of the Hermes root still
got past them:

- `connect_gateway`, which `hermes sessions discard` and `adopt` and the
  cron and Kanban clients call. None of them passes the command line's own
  refusal first, and for such a profile it went on to discovery and could
  start a gateway.
- The TUI's bootstrap script, which an open TUI runs again whenever its
  gateway is gone. A TUI that was open before a plugin took the profile
  over started a gateway for it again.

`connect_gateway` asks about this process's home before it resolves it and
raises the error it already raises for a gateway it may not attach to
(`inaccessible`, `profile_runs_elsewhere`). The bootstrap script passes the
home to `attach_gateway` as the environment names it; `attach_gateway`
resolves it after its own check.

* fix(profiles): the plugin host takes no launcher and no package from a marked profile's home

With `plugins.isolation: host` every plugin of the profile loads in a child
process. Its command line began with `plugins.host.launcher` from the
profile's own `config.yaml`, and the child started in the profile home with
that folder first on its import path. For a profile a plugin runs elsewhere
the backend there writes both: `hermes -p <name> status` started the launcher
that file named, and a `hermes_cli` package placed in the home ran in the
child instead of Hermes's own.

For a marked profile `host_launcher()` now reads the launcher from the
managed overlay only, which that backend cannot write; with none set there,
the child starts without a launcher. The child is started with `-P`, as the
profile extraction already was, so the folder it starts in is no longer on
its import path. That part applies to every profile: a module that sits in
the profile home can no longer be imported by name from a hosted plugin.
Hermes's own packages still come from `PYTHONPATH`, and a plugin's own
package is loaded by its path as before.

The fix and its tests are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a marked profile's password manager binary is not run on this host

`vault.bitwarden.binary_path` and `vault.onepassword.binary_path` name a
password manager's command line program in the profile's own `config.yaml`.
The Settings dialog's `vault.unlock` request hands that program the master
password the person typed, without building an agent. For a profile a plugin
runs elsewhere the backend there writes that file, and nothing on this path
asked the marker: the request ran a marked profile's program and gave it the
password.

`_bw` and `_op`, the one place each manager's program is looked up for
unlock, list and fill, now raise `RuntimeError` with the run-elsewhere
message for a marked profile. `vault.unlock` answers with its usual error
5095 carrying that message. The local vault does not pass either function.

The fix and its test are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a marked profile's browser executable is not started on this host

`browser.executable_path` names the Chromium a local browser session starts,
in the profile's own `config.yaml`. `hermes doctor --live` launches it to
check that a browser can start, without building an agent. For a profile a
plugin runs elsewhere the backend there writes that file, and nothing on this
path asked the marker: `hermes -p <name> doctor --live` started the program a
marked profile named.

`launch_chromium`, the one place a local Chromium is started, now returns its
usual `(None, error)` with the run-elsewhere message for a marked profile.
`doctor --live` reports the browser probe as failed with that message.

The fix and its test are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): the cron registry count sees a marked default beside a standalone gateway

Whether an external cron provider's registry may be shared was decided from
the larger of two counts: the profiles the gateway ticks and the installed
ones. A gateway that runs as a standalone profile ticks only itself, and the
installed list leaves a standalone profile out. With `default` marked and the
gateway running as a standalone `ops`, both counts were 1, so the gateway
took the external provider and reconciled its registry toward `ops`'s jobs
alone, although the marked `default`'s backend may arm jobs there too.

The count is now the number of different profile names in the two lists
together. With no marker every profile in the installed list is one the
gateway ticks, so the count is the number of profiles it ticks, as before.

The fix and its test case are the reviewer's patch from the review of
cd58d712aa6, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a managed launcher expands its env refs for a marked profile too

For a profile a plugin runs elsewhere the plugin host's launcher is read
from the managed overlay alone. That read took the overlay's file as
parsed, so a ${VAR} in plugins.host.launcher reached the child's command
line unexpanded, while every other profile got the expanded value.
host_launcher() now asks apply_managed_overlay({}), which expands refs
against the process env the way the config loader does.

* fix(profiles): a marked profile linked out of the root does not get its own launcher

`hermes -p ops` names the home `<root>/profiles/ops`. When that is a link
to a directory outside the Hermes root, the plugin manager is keyed by the
directory the link leads to, and the plugin host asked the marker about
that directory, which has no marker folder above it. So the host child of
such a profile still started under the `plugins.host.launcher` its own
`config.yaml` names.

The manager now keeps the home as it was named (`owner_home`), and the
host passes it to `host_launcher()`, which asks the marker about that
home. Other callers of `host_launcher()` are unchanged.

The fix and its test are the reviewer's patch from the review of
b3d3693bb6a, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): an empty PYTHONPATH entry does not put the profile home on the host's path

The plugin host's child starts in the profile home, with `-P` so that
folder is not on its import path. `-P` drops only Python's own first
entry: an empty entry in `PYTHONPATH` (`PYTHONPATH=:/x`, or a trailing
separator) still means the current directory, and the child inherited
such entries as they were. A module placed in the profile home then ran
in the host child again, ahead of the standard library.

The inherited entries are now made absolute against the parent's working
directory before the child gets them, so an empty or relative entry means
for the child what it means for the parent. This applies to every
profile, like `-P` itself.

The fix and its test are the reviewer's patch from the review of
b3d3693bb6a, taken as posted.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

---------

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-23 21:37:40 -05:00

782 lines
43 KiB
Python

"""Durable subagent records in ``state.db`` (``resumable_subagents``): what ``delegate_task(action='continue')``
rebuilds a child from after a restart or crash, how a stopped child may resume, and which worktrees the startup
sweep must keep for it.
One row per subagent_id, written by the run itself (``record_start`` when its workspace is seeded, ``checkpoint`` on
each heartbeat while its terminal cwd moves, ``record_stop`` after its cleanup ran) and by boot recovery for a run
whose owner process died (``recover_abandoned``). The row's ``pinned`` flag is the worktree pin: set for a child that
did not complete and was not stopped by a person, for ``delegation.resumable_ttl_hours`` (newest
``delegation.max_resumable`` per profile; the oldest beyond the cap loses its pin, the row stays). Automatic
resumption is ``delegate_tool_auto_resume`` (gated on ``delegation.auto_resume``), which reads ``resume_mode`` /
``next_attempt_at`` and marks a record ``superseded`` when its parent moved on.
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import subprocess
import threading
import time
from pathlib import Path
from typing import Any, Iterable, Optional
logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module
AUTO_AT, AUTO_ON_BOOT, ON_FIX = "AUTO_AT", "AUTO_ON_BOOT", "ON_FIX"
REPAIR_THEN_CONTINUE, HANDOFF = "REPAIR_THEN_CONTINUE", "HANDOFF"
GATEWAY_SHUTDOWN = "gateway_shutdown"
# A record ``action='continue'`` can rebuild from (``claimed`` while a continue is starting, ``running`` live).
_FINISHED = ("resumable", "completed", "stopped", "superseded")
_DEFAULT_TTL_HOURS, _DEFAULT_MAX_RESUMABLE = 48.0, 32
# DESIGN.md per-reason table (agent/error_classifier.py::FailoverReason): mode, and the default delay before an
# AUTO_AT attempt when the failure carried no reset time.
_MODE_BY_REASON: dict[str, tuple[str, Optional[float]]] = {
"rate_limit": (AUTO_AT, 15 * 60.0), "upstream_rate_limit": (AUTO_AT, 15 * 60.0),
"timeout": (AUTO_AT, 5 * 60.0), "overloaded": (AUTO_AT, 5 * 60.0), "server_error": (AUTO_AT, 5 * 60.0),
"session_busy": (AUTO_AT, 30.0), "interpreter_shutdown": (AUTO_ON_BOOT, None),
"content_policy_blocked": (HANDOFF, None),
**dict.fromkeys(("context_overflow", "payload_too_large", "image_too_large", "image_corrupt",
"thinking_signature", "invalid_encrypted_content"), (REPAIR_THEN_CONTINUE, None)),
}
def _settings() -> tuple[float, int]:
from tools.delegate_tool_config import _load_config
cfg = _load_config()
try:
ttl = max(0.0, float(cfg.get("resumable_ttl_hours", _DEFAULT_TTL_HOURS)))
cap = max(0, int(cfg.get("max_resumable", _DEFAULT_MAX_RESUMABLE)))
except (TypeError, ValueError):
ttl, cap = _DEFAULT_TTL_HOURS, _DEFAULT_MAX_RESUMABLE
return ttl, cap
def classify(entry: dict[str, Any], stop_cause: Optional[str]) -> tuple[str, Optional[str], Optional[float]]:
"""``(state, resume_mode, next_attempt_at)`` for a stopped child's result entry. ``state`` is ``resumable``
(pinned), ``completed`` or ``stopped`` (a person or the parent stopped it: no pin)."""
status, exit_reason = entry.get("status"), entry.get("exit_reason")
if status == "completed" and exit_reason == "completed":
return "completed", None, None
if status == "interrupted":
return ("resumable", AUTO_ON_BOOT, None) if stop_cause == GATEWAY_SHUTDOWN else ("stopped", None, None)
if status == "unknown":
return "resumable", AUTO_ON_BOOT, None
reason = str(entry.get("failure_reason") or "")
resets_at = entry.get("failure_resets_at")
if isinstance(resets_at, (int, float)) and not isinstance(resets_at, bool) and reason in (
"billing", "rate_limit", "upstream_rate_limit"):
return "resumable", AUTO_AT, float(resets_at)
mode, delay = _MODE_BY_REASON.get(reason, (ON_FIX, None))
return "resumable", mode, (time.time() + delay if delay else None)
# ── storage ────────────────────────────────────────────────────────────────
# A write computed from a record it read lands only while the row is unchanged; a row that moved is read again.
_CAS_TRIES = 8
def _db_path_for(parent_agent: Any = None) -> Any:
"""The profile store the parent's children write their transcripts to (its ``state.db`` path, or the scope of a
storage handle), else this scope's profile; None in a managed worker, which owns no ledger."""
from agent.runtime_session_store import is_worker_process
if is_worker_process():
return None
from persistence_assembly import Persistence, profile_scope
db = getattr(parent_agent, "_session_db", None)
if isinstance(db, Persistence):
return db.scope
path = getattr(db, "db_path", None)
if isinstance(path, (str, Path)):
return Path(path)
return profile_scope()
def _write(target: Any, fn) -> Any:
"""``fn(ledger)`` on the subagent records of *target*'s profile store (a ``state.db`` path or a profile scope);
None when there is no store to write or the write failed."""
if target is None:
return None
from persistence import ProfileScope
from persistence_assembly import open_persistence, profile_scope
scope = target if isinstance(target, ProfileScope) else profile_scope(home=Path(target).parent)
try:
with open_persistence(scope, eager=True) as store:
return fn(store.coordination)
except FileNotFoundError: # its profile was removed: a late write must not recreate it
logger.debug("resumable subagent record skipped: %s is gone", scope.profile_dir)
return None
except Exception:
logger.warning("resumable subagent record write failed (%s)", target, exc_info=True)
return None
def _as_record(got: Any) -> Optional[dict[str, Any]]:
"""The run record of a stored row, with the columns a claim moves without rewriting the record (state, owner)."""
if got is None:
return None
return {**got.document, "state": got.state.value, "stop_cause": got.stop_cause, "owner_pid": got.owner_pid,
"owner_started_at": got.owner_started_at}
def _row(ledger, sid: str) -> Optional[dict[str, Any]]:
"""The record, with the columns a claim moves without rewriting the JSON (state, owner) taken from the row."""
return _as_record(ledger.get_subagent(subagent_id=sid))
def _limits():
from persistence.authority.subagents import SubagentLimits
ttl, cap = _settings()
return SubagentLimits(ttl_hours=ttl, max_resumable=cap)
def _subagent_write(record: dict[str, Any], *, state: str, pinned: bool, expires_at: Optional[float],
stop_cause: Optional[str] = None):
from persistence.authority.subagents import SubagentState, SubagentWrite
# ``auto_claim`` / ``auto_cancel`` mark only a claim no run has started yet: a written run record never carries them.
record = {k: v for k, v in record.items() if k not in ("state", "stop_cause", "auto_claim", "auto_cancel")}
document = json.loads(json.dumps(record, ensure_ascii=False, default=str))
return SubagentWrite(state=SubagentState(state), pinned=pinned, stop_cause=stop_cause,
owner_pid=record.get("owner_pid"), owner_started_at=record.get("owner_started_at"),
document=document, expires_at=expires_at)
def _upsert(ledger, sid: str, record: dict[str, Any], *, state: str, pinned: bool, expires_at: Optional[float],
stop_cause: Optional[str] = None, expected: Any, limits: Any = None) -> bool:
"""Write the whole row while the stored one is still *expected* (None: no row yet); False when it moved."""
return ledger.put_subagent(subagent_id=sid, write=_subagent_write(
record, state=state, pinned=pinned, expires_at=expires_at, stop_cause=stop_cause), expected=expected,
limits=limits)
def _apply_limits(ledger) -> None:
"""TTL un-pins and retires a record; beyond the cap the oldest pins drop (the row stays continuable)."""
ledger.apply_subagent_limits(limits=_limits())
# ── worktrees ──────────────────────────────────────────────────────────────
def _git_lines(args: list[str], cwd: str) -> list[str]:
from hermes_cli._subprocess_compat import noninteractive_repo_git_env
env = noninteractive_repo_git_env(cwd)
if env is None:
return []
try:
res = subprocess.run(["git", *args], cwd=cwd, env=env, capture_output=True, text=True, encoding="utf-8",
errors="replace", timeout=10, stdin=subprocess.DEVNULL, check=False)
except (OSError, subprocess.SubprocessError):
return []
return res.stdout.splitlines() if res.returncode == 0 else []
def _worktrees_of(cwd: Optional[str]) -> list[str]:
"""Every worktree of the repository *cwd* is in (``git worktree list``), or ``[]``."""
if not cwd or not os.path.isdir(cwd):
return []
return [os.path.realpath(line[9:]) for line in _git_lines(["worktree", "list", "--porcelain"], cwd)
if line.startswith("worktree ")]
def _toplevel(cwd: Optional[str]) -> Optional[str]:
if not cwd or not os.path.isdir(cwd):
return None
lines = _git_lines(["rev-parse", "--show-toplevel"], cwd)
return os.path.realpath(lines[0]) if lines else None
def _new_worktrees(cwd: Optional[str], baseline: Iterable[str]) -> list[str]:
known = set(baseline)
return [p for p in _worktrees_of(cwd) if p not in known] if known else []
def _pin_paths(record: dict[str, Any]) -> list[str]:
"""Where the child was when it STOPPED: its last terminal cwd's worktree, its isolation worktree, and every
worktree a repository it worked in gained since it first entered it (a ``git worktree add`` it ran without
cd-ing into it), wherever its cwd went afterwards. Each repository is compared with its own baseline."""
cwd = record.get("cwd")
paths = [p for p in (_toplevel(cwd), (record.get("worktree") or {}).get("path")) if p]
paths += _new_worktrees(record.get("start_cwd") or cwd, record.get("worktrees_at_start") or ())
for main, baseline in (record.get("repo_baselines") or {}).items():
paths += _new_worktrees(main, baseline)
return sorted({os.path.realpath(p) for p in paths})
_LIVE_PIN_TTL_S = 30.0
_live_pin_cache: dict[str, tuple[float, list[str]]] = {}
_live_pin_lock = threading.Lock()
def _live_pins(record: dict[str, Any], *, memo: bool = True) -> list[str]:
"""Pins of a ``running``/``claimed`` record: where the child is NOW, plus where its previous run stopped (a
continue's stored ``pin_paths``); a cached set never hides the live location.
The sweep asks again right before each tree it touches, so the git discovery behind the live part is memoized
for a few seconds, keyed on every record field that drives it: a checkpointed move changes the key and is
discovered at once, while the record itself is always read fresh. The only thing a cached answer can miss is a
worktree created within the TTL, and a tree that new is never past the sweep's idle tier. Recovery and reclaim
store their answer as the stopped record's pins, so they pass ``memo=False``."""
if not memo:
return sorted({*(record.get("pin_paths") or ()), *_pin_paths(record)})
key = json.dumps([record.get(k) for k in ("cwd", "start_cwd", "worktrees_at_start", "repo_baselines")]
+ [(record.get("worktree") or {}).get("path")], sort_keys=True, default=str)
now = time.monotonic()
with _live_pin_lock:
hit = _live_pin_cache.get(key)
if hit is None or now - hit[0] > _LIVE_PIN_TTL_S:
hit = (now, _pin_paths(record)) # git runs outside the lock
with _live_pin_lock:
for stale in [k for k, (at, _p) in _live_pin_cache.items() if now - at > _LIVE_PIN_TTL_S]:
del _live_pin_cache[stale]
_live_pin_cache[key] = hit
return sorted({*(record.get("pin_paths") or ()), *hit[1]})
def _note_repo(baselines: dict[str, list[str]], start_main: Optional[str], cwd: Optional[str]) -> None:
"""Record the baseline of the repository *cwd* is in when the child first enters it (the start repository's
is ``worktrees_at_start``)."""
trees = _worktrees_of(cwd)
if trees and trees[0] != start_main and trees[0] not in baselines: # the main worktree is always listed first
baselines[trees[0]] = trees
# ── run lifecycle ──────────────────────────────────────────────────────────
def endpoint_identity(provider: Any, base_url: Any) -> tuple[Any, Optional[str]]:
"""``(provider, sha256 of the exact base_url)``: what a continue compares to refuse a changed backend. The URL
itself is never stored (it can carry a key in its query or userinfo); the real one is re-resolved from the
task's route at continue. Exact bytes, so any change to the URL still refuses."""
return provider, (hashlib.sha256(str(base_url).encode("utf-8")).hexdigest() if base_url is not None else None)
def _owner_identity() -> dict[str, Any]:
from gateway.status import get_process_start_time
started = get_process_start_time(os.getpid())
return {"owner_pid": os.getpid(), "owner_started_at": started}
def _spec(child: Any) -> Optional[dict[str, Any]]:
"""The rebuild spec without live objects or secrets: the route is kept as the request that re-routes it."""
build = getattr(child, "_delegate_resume", None)
session_id = getattr(child, "session_id", None)
if not isinstance(build, dict) or not isinstance(session_id, str) or not session_id:
return None
route = build.get("route")
return {"goal": build.get("goal"), "context": build.get("context"), "toolsets": build.get("toolsets"),
"endpoint": list(build.get("endpoint") or ()), "model": getattr(child, "model", None),
"session_id": session_id, "route_request": getattr(route, "request", None)}
def record_start(run: Any) -> None:
"""A child began (or resumed) running: durable identity, rebuild spec, owner and starting workspace. A write
that fails stays pending on the run (``_flush``) and is retried, whole, at the next checkpoint and at the stop."""
child = run.child
spec = _spec(child)
sid = run.subagent_id
if spec is None or not sid:
return
path = _db_path_for(run.parent_agent)
cwd = _child_cwd(run)
from tools.delegate_tool_registry import _recent_subagents, _active_subagents_lock
owners = {str(getattr(child, "_parent_session_id", "") or "") or str(getattr(run.parent_agent, "session_id", "")
or "")}
# The git probes run before the write transaction (seconds on a slow repo; no state.db lock held through them).
earlier = _write(path, lambda ledger: _row(ledger, sid)) or {}
start_cwd = earlier.get("start_cwd") or cwd
start_trees = _worktrees_of(start_cwd)
# ``lock`` serializes the start-record retries (heartbeat thread vs the stop path) with the terminal write, so a
# retry still waiting on the busy timeout can never land after ``record_stop`` and flip the row back to running.
# Who started this run: a parent's spawn, a parent's continue (no automatic resume after it), the scheduler.
origin = getattr(child, "_delegate_run_origin", None)
origin = origin if origin in ("continue", "auto") else "spawn"
auto = {"auto_attempts": int(earlier.get("auto_attempts") or 0), "auto_off": earlier.get("auto_off")
or ("the parent continued it itself" if origin == "continue" else None),
# The automatic-resume deadline counts from the FIRST stop, across every resumed run.
"auto_first_stopped_at": earlier.get("auto_first_stopped_at")}
durable: dict[str, Any] = {"db": path, "cwd": cwd, "start_main": start_trees[0] if start_trees else None,
"baselines": dict(earlier.get("repo_baselines") or {}), "lock": threading.RLock(),
"auto": auto}
_note_repo(durable["baselines"], durable["start_main"], cwd)
def _do(ledger):
for _ in range(_CAS_TRIES):
stored = ledger.get_subagent(subagent_id=sid)
prev = _as_record(stored) or {}
with _active_subagents_lock:
owners.update((_recent_subagents.get(sid) or {}).get("ancestor_owner_session_ids") or ())
owners.update(prev.get("owners") or ())
owners.update(_ancestor_sessions(child))
owners.discard("")
record = {**prev, **spec, **_owner_identity(), "subagent_id": sid,
"delegation_id": getattr(child, "_delegation_id", None), "owners": sorted(owners),
# The async unit whose ledger row reports this run (``<call>-k`` with independent completions).
"unit_id": getattr(child, "_delegation_unit_id", None),
"start_cwd": start_cwd, "cwd": durable["cwd"], "worktree": prev.get("worktree")
or run.worktree_info, "outcome": "running", "resume_mode": None,
# Kept across continues: a tree the child made in an earlier run is still its own.
"worktrees_at_start": prev.get("worktrees_at_start") or start_trees,
# A promise belongs to one stop: this run's own stop (or boot recovery) makes it afresh.
"run_origin": origin, "run_started_at": time.time(), "auto_promised": False, **auto}
record["repo_baselines"] = durable["baselines"]
# A running record pins too (its paths are resolved at sweep time): a crash before boot recovery ran
# must not hand its tree to the sweep. Bounded by the same TTL.
columns: dict[str, Any] = dict(state="running", pinned=True,
expires_at=time.time() + _settings()[0] * 3600)
if origin == "auto": # the parent's last word: a stop, /stop or replacement since the claim cancels it
from tools.delegate_tool_auto_resume import CANCELLED
if stored is None:
return f"{CANCELLED}: the record moved (gone)"
started = ledger.start_auto_resumed_run(subagent_id=sid, write=_subagent_write(record, **columns),
expected=stored, owner_pid=os.getpid())
if started.cancelled:
return started.cancelled
if started.written:
return True
elif _upsert(ledger, sid, record, **columns, expected=stored):
return True
return None
outcome = _write(path, _do)
if isinstance(outcome, str): # cancelled by the parent before it ran: no run record, the child does not start
child._delegate_auto_cancelled = outcome
child._delegate_claim = None # the row is the parent's now: cleanup must not hand any claim back
return
if origin == "auto" and not outcome:
# Fail closed: without its run record the parent's last word could not be checked, and a later retry would
# check it while the child already runs. It does not start; cleanup hands the claim back to ``resumable``.
child._delegate_auto_cancelled = "Not continued: its run record could not be written"
return
durable["pending"] = None if outcome else _do
child._delegate_durable = durable
def _flush(durable: dict[str, Any]) -> bool:
"""Retry the run's pending start record in its own transaction; True once it is persisted. Cleared only after
that transaction committed, so a later write failing never leaves "persisted" set over a rolled-back row."""
with durable["lock"]:
pending = durable.get("pending")
if pending is not None and not durable.get("stopped") and _write(durable.get("db"), pending):
durable["pending"] = pending = None
return pending is None
def _ancestor_sessions(child: Any) -> set[str]:
owners, cur = set(), child
for _ in range(8):
ref = getattr(cur, "_delegate_parent_ref", None)
cur = ref() if callable(ref) else None
if cur is None:
break
sid = getattr(cur, "session_id", None)
if isinstance(sid, str) and sid:
owners.add(sid)
return owners
def _child_cwd(run: Any) -> Optional[str]:
from tools.delegate_tool_routes import child_profile_scope
from tools.terminal_tool import get_session_cwd
with child_profile_scope(run.child):
cwd = get_session_cwd(run.child_task_id)
return os.path.realpath(cwd) if isinstance(cwd, str) and cwd else None
def checkpoint(run: Any) -> None:
"""Heartbeat: persist the child's terminal cwd when it moved, so a hard kill still knows where it was."""
durable = getattr(run.child, "_delegate_durable", None)
if not isinstance(durable, dict) or not run.subagent_id:
return
cwd = _child_cwd(run)
if not cwd or cwd == durable.get("cwd"):
_flush(durable)
return
durable["cwd"] = cwd
baselines = durable["baselines"]
_note_repo(baselines, durable["start_main"], cwd)
if not _flush(durable):
return # the full start record goes first; this cwd rides on its next retry or on the stop record
def _do(ledger):
ledger.checkpoint_subagent(subagent_id=run.subagent_id, cwd=cwd, repo_baselines=baselines)
_write(durable.get("db"), _do)
def stop_cause_live(run: Any) -> Optional[str]:
"""``gateway_shutdown`` when the gateway's shutdown stopped this child (``note_gateway_shutdown`` marked it, or
its own turn recorded the shutdown interrupt), else None."""
if getattr(run.child, "_delegate_stop_cause", None) == GATEWAY_SHUTDOWN or GATEWAY_SHUTDOWN in str(
getattr(run, "turn_exit_reason", "") or ""):
return GATEWAY_SHUTDOWN
return None
def keeps_worktree(run: Any, entry: dict[str, Any]) -> bool:
"""Whether the stopped child is resumable, so its isolation worktree must survive the stop: only with its
record persisted (a pending one is retried first); without one nothing pins the tree, so it is finalized as
before (archived when it holds work)."""
durable = getattr(run.child, "_delegate_durable", None)
if not run.subagent_id or not isinstance(durable, dict) or not _flush(durable):
return False
return classify(entry, stop_cause_live(run))[0] == "resumable"
def stamp_entry(run: Any, entry: dict[str, Any]) -> None:
"""The result entry says how this stopped child may resume (absent when it completed or a person stopped it)."""
durable = getattr(run.child, "_delegate_durable", None)
if not run.subagent_id or not isinstance(durable, dict):
return
durable["cwd"] = _child_cwd(run) or durable.get("cwd") # before cleanup drops the child's cwd record
if not _flush(durable):
return # no record to continue from: the entry must not offer a resume
state, mode, next_at = classify(entry, stop_cause_live(run))
if state == "resumable":
entry["resume_mode"] = mode
if getattr(run.child, "_delegation_unit_id", None) and not durable["auto"]["auto_off"]:
from tools.delegate_tool_auto_resume import promise
from tools.delegate_tool_auto_resume import gave_up, gave_up_line
candidate = {**durable["auto"], "resume_mode": mode, "next_attempt_at": next_at}
if auto := promise(candidate):
entry["auto_resume"] = auto
durable["promised"] = True # only a stop that promised a resume may be resumed automatically
elif reason := gave_up(candidate): # this stop's own completion is the one terminal failure
entry["auto_gave_up"] = reason
entry["error"] = f"{entry.get('error') or entry.get('status')}; {gave_up_line(run.subagent_id, reason)}"
durable["gave_up"] = reason
def record_stop(run: Any, entry: Optional[dict[str, Any]]) -> None:
"""The child's run ended and its resources are closed: its outcome, resume mode, last cwd and pins."""
durable = getattr(run.child, "_delegate_durable", None)
sid = run.subagent_id
if not isinstance(durable, dict) or not sid:
return
entry = entry or {"status": "unknown"}
cwd = durable.get("cwd") or _child_cwd(run)
live_cause = stop_cause_live(run)
# The segment it stopped in: with ``compression.in_place: false`` each rotation moved it to a new session.
session_id = getattr(run.child, "session_id", None)
def _do(ledger):
for _ in range(_CAS_TRIES):
stored = ledger.get_subagent(subagent_id=sid)
record = _as_record(stored) or {}
if isinstance(session_id, str) and session_id:
record["session_id"] = session_id
record["auto_promised"] = bool(durable.get("promised"))
if durable.get("gave_up"):
record["auto_gave_up"] = record["auto_note"] = durable["gave_up"]
if _finish(ledger, sid, record, entry, live_cause or record.get("stop_cause"), cwd=cwd, expected=stored):
return True
return None
with durable["lock"]:
flushed = _flush(durable)
durable["stopped"] = True # no start retry may run after the stop, landed or not
if flushed: # never a partial row (no goal, route or owners) the parent cannot claim
_write(durable.get("db"), _do)
def _finish(ledger, sid: str, record: dict[str, Any], entry: dict[str, Any], cause: Optional[str], *,
cwd: Optional[str], expected: Any, pins: Optional[list[str]] = None) -> bool:
"""Write the stopped record while the row is still *expected*, with the limits in the same write; False when it
moved. *pins*: its pin paths computed before the write (git probes take seconds; no write may wait on them)."""
document, columns = _stopped(record, entry, cause, cwd=cwd, pins=pins)
return _upsert(ledger, sid, document, **columns, expected=expected, limits=_limits())
def _stopped(record: dict[str, Any], entry: dict[str, Any], cause: Optional[str], *, cwd: Optional[str],
pins: Optional[list[str]] = None) -> tuple[dict[str, Any], dict[str, Any]]:
"""``(record, columns)`` of the stopped record ``_upsert`` writes."""
ttl, _cap = _settings()
state, mode, next_at = classify(entry, cause)
record = {**record, "cwd": cwd or record.get("cwd"), "outcome": entry.get("status"), "resume_mode": mode,
"next_attempt_at": next_at, "failure_reason": entry.get("failure_reason"),
"failure_resets_at": entry.get("failure_resets_at"), "usage_limit": entry.get("usage_limit"),
"stopped_at": time.time()}
if state == "resumable" and not record.get("auto_first_stopped_at"):
record["auto_first_stopped_at"] = record["stopped_at"]
if isinstance(entry.get("worktree"), dict):
record["worktree"] = {**(record.get("worktree") or {}), **entry["worktree"]}
record["pin_paths"] = (_pin_paths(record) if pins is None else pins) if state == "resumable" else []
return record, {"state": state, "pinned": state == "resumable" and bool(record["pin_paths"]),
"expires_at": time.time() + ttl * 3600, "stop_cause": cause}
def note_gateway_shutdown() -> int:
"""Gateway shutdown is about to stop this process's children: mark them first (in memory and on every profile's
running records), so each reads as a restart (resumable) rather than a user stop however its run ends, a
SIGKILL mid-unwind included. Returns how many records were marked."""
from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock
with _active_subagents_lock:
live = [r.get("agent") for r in _active_subagents.values()]
for agent in live:
if agent is not None:
agent._delegate_stop_cause = GATEWAY_SHUTDOWN
marked = 0
for db in _profile_dbs():
marked += _write(db, lambda ledger: ledger.mark_subagents_gateway_shutdown(owner_pid=os.getpid())) or 0
return marked
def _abandoned_entry(record: dict[str, Any]) -> tuple[dict[str, Any], Optional[str]]:
"""``(entry, cause)`` for a run whose owner died: a gateway shutdown when that was marked, else unknown."""
cause = record.get("stop_cause")
return {"status": "interrupted" if cause == GATEWAY_SHUTDOWN else "unknown"}, cause
def plan_recovery(path: Any, alive) -> dict[str, tuple[Any, Any, list[str], Any]]:
"""Boot, before the recovery write: ``{subagent_id: (owner_pid, owner_started_at, pin_paths, stored row)}`` for
every ``running``/``claimed`` record of *path*'s store whose owner is gone."""
return recovery_plan(_write(path, lambda ledger: ledger.list_inflight_subagents()) or (), alive)
def recovery_plan(rows: Iterable[Any], alive) -> dict[str, tuple[Any, Any, list[str], Any]]:
"""``plan_recovery`` over stored ``running``/``claimed`` rows. The git probes behind the pins run here, before
any write."""
return {row.subagent_id: (row.owner_pid, row.owner_started_at, _live_pins(dict(row.document), memo=False), row)
for row in rows if not alive(row.owner_pid, row.owner_started_at)}
def _still_abandoned(stored: Any, pid: Any, started: Any) -> Optional[dict[str, Any]]:
"""The record, when *stored* is still the same dead owner's ``running``/``claimed`` row."""
if stored is None or stored.state.value not in ("running", "claimed") or (
stored.owner_pid, stored.owner_started_at) != (pid, started):
return None
return _as_record(stored)
def recovered_records(plan: dict[str, tuple[Any, Any, list[str], Any]]) -> dict[str, tuple[dict[str, Any], Any]]:
"""Boot: each planned record (``plan_recovery``) still held by its dead owner, ``{subagent_id: (record, write)}``:
the record as stored and the resumable record it becomes (outcome ``unknown``, or a gateway shutdown when that
was marked), pinned on where it last was. The recovery write lands it only while its dead owner still holds the
row; a row that died after the plan was made is reclaimed by ``claim``."""
out = {}
for sid, (pid, started, pins, stored) in plan.items():
record = _still_abandoned(stored, pid, started)
if record is None:
continue
entry, cause = _abandoned_entry(record)
document, columns = _stopped(record, entry, cause, cwd=record.get("cwd"), pins=pins)
out[sid] = (record, (document, columns))
return out
def subagent_recoveries(recovered: dict[str, tuple[dict[str, Any], Any]], promised: Iterable[str] = ()) -> list[Any]:
"""The recovery write of each ``recovered_records`` entry, ``auto_promised`` set on the *promised* ids (the
scheduler then resumes each of them, or delivers its one give-up)."""
from persistence.authority.subagents import SubagentRecovery
promised = set(promised)
out = []
for sid, (record, (document, columns)) in recovered.items():
document = {**document, "auto_promised": True} if sid in promised else document
out.append(SubagentRecovery(subagent_id=sid, owner_pid=record.get("owner_pid"),
owner_started_at=record.get("owner_started_at"),
write=_subagent_write(document, **columns)))
return out
def continuable_of(ledger, unit_id: str, recovered: dict[str, tuple[dict[str, Any], Any]]) -> list[str]:
"""Every child of the async unit *unit_id* its parent can continue once the boot recovery lands: the ones it
finishes (*recovered*), and the ones that recorded their own resumable stop before the owner exited (a gateway
restart stops each child cleanly, while the unit's ledger row is left running); oldest first."""
now, rows = time.time(), {}
for sid in ledger.list_continuable_subagents(unit_id=unit_id):
if sid not in recovered and (got := ledger.get_subagent(subagent_id=sid)) is not None:
rows[sid] = (got.created_at, got.expires_at)
for sid, (record, (document, columns)) in recovered.items():
unit = document.get("unit_id") if document.get("unit_id") is not None else document.get("delegation_id")
if columns["state"] == "resumable" and unit == unit_id:
stored = ledger.get_subagent(subagent_id=sid)
rows[sid] = (stored.created_at if stored is not None else now, columns["expires_at"])
# The recovery's limits pass retires a record whose TTL already passed.
live = [(created, sid) for sid, (created, expires) in rows.items() if expires is None or expires > now]
return [sid for _created, sid in sorted(live)]
def _reclaim_dead_owner(path: Any, sid: str, record: dict[str, Any]) -> Optional[dict[str, Any]]:
"""A ``running``/``claimed`` row whose owner process died (after this process's boot recovery ran): finish it
the way boot recovery would and return the finished record; None while its owner is alive."""
from tools.async_delegation import _owner_liveness
alive = _owner_liveness()
pid, started = record.get("owner_pid"), record.get("owner_started_at")
if alive is None or alive(pid, started):
return None
pins = _live_pins(record, memo=False)
def _do(ledger):
for _ in range(_CAS_TRIES):
stored = ledger.get_subagent(subagent_id=sid)
current = _still_abandoned(stored, pid, started)
if current is None:
return None
entry, cause = _abandoned_entry(current)
if _finish(ledger, sid, current, entry, cause, cwd=current.get("cwd"), pins=pins, expected=stored):
return _row(ledger, sid)
return None
return _write(path, _do)
# ── continue ───────────────────────────────────────────────────────────────
def claim(parent_agent: Any, sid: str) -> tuple[Optional[dict[str, Any]], Optional[str]]:
"""Take a finished child's durable record for ``continue`` (``(record, None)``, or ``(None, error)``). The
state flip to ``claimed`` is one guarded UPDATE, so two continues never run one conversation twice."""
from tools.delegate_tool_registry import _owns_subagent_record
path = _db_path_for(parent_agent)
record = _write(path, lambda ledger: _as_record(ledger.apply_subagent_limits(limits=_limits(), subagent_id=sid)))
if record is None:
return None, None
owned = {"owner_agent_session_id": None, "ancestor_owner_session_ids": record.get("owners") or ()}
if not _owns_subagent_record(owned, parent_agent):
return None, None
if record.get("state") in ("running", "claimed"):
record = _reclaim_dead_owner(path, sid, record) or record
if record.get("state") not in _FINISHED:
return None, (f"Subagent '{sid}' is still running or being continued. Try again shortly; if this persists, "
"spawn a new task.") if record.get("state") in ("running", "claimed") else None
owner = _owner_identity() # boot recovery must not reclaim a continue this live process is starting
from persistence.authority.subagents import SubagentState # the parent took it over: no automatic report owed
claimed = _write(path, lambda ledger: ledger.claim_subagent(
subagent_id=sid, expected_state=SubagentState(record["state"]), owner_pid=owner["owner_pid"],
owner_started_at=owner["owner_started_at"]))
return (record, None) if claimed is True else (None, f"Subagent '{sid}' is already being continued.")
def _hand_back(ledger, sid: str, state: str, *, promised: Optional[bool] = None, owner_pid: Optional[int] = None) -> None:
"""Return a claimed record no run started to *state* (with *promised* as its debt when given), in one write:
a stop that landed during the claim (``$.auto_cancel``) wins over handing a promise back."""
from persistence.authority.subagents import SubagentState
ledger.hand_back_subagent(subagent_id=sid, state=SubagentState(state), promised=promised, owner_pid=owner_pid)
def release(parent_agent: Any, sid: str, record: dict[str, Any]) -> None:
"""Hand a claimed record back (the continue was refused before anything ran), with the debt it had."""
_write(_db_path_for(parent_agent), lambda ledger: _hand_back(ledger, sid, record["state"],
promised=bool(record.get("auto_promised"))))
def hold_claim(child: Any, parent_agent: Any, sid: str, record: dict[str, Any]) -> None:
"""The continued child carries its claim until its run records itself (``record_start``), so a run that fails
before that hands the row back (``release_unstarted``) instead of leaving it ``claimed`` by a live process."""
child._delegate_claim = (_db_path_for(parent_agent), sid, record["state"])
def release_unstarted(child: Any) -> bool:
"""Hand back the claim of a continued child whose run ended before ``record_start`` (idempotent). True when
the hand-back committed (or there was none); a failed one is queued for ``retry_hand_backs``."""
claim = getattr(child, "_delegate_claim", None)
durable = getattr(child, "_delegate_durable", None)
if not isinstance(claim, tuple) or (isinstance(durable, dict) and durable.get("pending") is None):
return True
path, sid, state = claim
# A stop that reached this registered child before it ran (an automatic run failing closed) is the parent's
# decision: the row ends ``stopped``, never handed back for the scheduler to resume.
stopped = (getattr(child, "_delegate_run_origin", None) == "auto"
and getattr(child, "_delegate_stop_requested", False) is True)
pending = (path, sid, "stopped" if stopped else state, False if stopped else None)
committed = _hand_back_pending(pending)
if not committed: # the store is busy: the queue owns the claim now, and the scheduler's tick retries it
with _PENDING_HAND_BACKS_LOCK:
_PENDING_HAND_BACKS.append(pending)
child._delegate_claim = None
return committed
# Hand-backs whose write failed (``release_unstarted``): a row left ``claimed`` by this live process is invisible to
# the scheduler and to boot recovery, so a promised child would never report while the process lives.
_PENDING_HAND_BACKS: list[tuple[Optional[Path], str, str, Optional[bool]]] = []
_PENDING_HAND_BACKS_LOCK = threading.Lock()
def _hand_back_pending(pending: tuple[Optional[Path], str, str, Optional[bool]]) -> bool:
"""One hand-back attempt; True once it committed (a row no longer ``claimed`` by this process counts)."""
path, sid, state, promised = pending
return _write(path, lambda ledger: (_hand_back(ledger, sid, state, promised=promised, owner_pid=os.getpid()),
True)[1]) is True
def retry_hand_backs() -> None:
"""Scheduler tick: retry each queued hand-back once, keeping only the ones that still failed."""
with _PENDING_HAND_BACKS_LOCK:
queued = list(_PENDING_HAND_BACKS)
_PENDING_HAND_BACKS.clear()
failed = [p for p in queued if not _hand_back_pending(p)]
if failed:
with _PENDING_HAND_BACKS_LOCK:
_PENDING_HAND_BACKS.extend(failed)
def last_workspace(parent_agent: Any, sid: str) -> Optional[dict[str, Any]]:
"""``{cwd, worktree}`` the child stopped in, for a continue to start there instead of the parent's cwd."""
record = _write(_db_path_for(parent_agent), lambda ledger: _row(ledger, sid)) or {}
cwd = record.get("cwd")
if not (isinstance(cwd, str) and os.path.isdir(cwd)):
return None
worktree = record.get("worktree") if isinstance(record.get("worktree"), dict) else None
return {"cwd": cwd, "worktree": worktree if worktree and os.path.isdir(worktree.get("path") or "") else None}
# ── worktree sweep pin ─────────────────────────────────────────────────────
def _profile_dbs(*, include_run_elsewhere: bool = False) -> list[Any]:
"""The scope of every served profile that has a store (with *include_run_elsewhere*, also of the profiles a
plugin runs elsewhere)."""
from hermes_cli.profiles import profiles_to_serve
from persistence_assembly import profile_scope, store_exists
homes = [home for _name, home in profiles_to_serve(multiplex=True, include_standalone=True, include_parked=True,
include_run_elsewhere=include_run_elsewhere)]
return [scope for scope in (profile_scope(home=Path(home)) for home in homes) if store_exists(scope)]
def _settings_of(home: Path) -> tuple[float, int]:
"""*home*'s own ``delegation`` limits, read under its scope (the sweep runs under whichever profile started it)."""
from agent.runtime_scope import bind_profile_scope
try:
with bind_profile_scope(home, hydrate_secrets=False):
return _settings()
except Exception: # health: allow BLE001 -- an unreadable profile keeps the default cap, never loses its pins
logger.debug("delegation settings of %s unreadable", home, exc_info=True)
return _DEFAULT_TTL_HOURS, _DEFAULT_MAX_RESUMABLE
def _read_pins(scope: Any, now: float) -> Iterable[tuple[str, dict[str, Any]]]:
"""The pinned records of *scope*'s store, read without opening it for writing."""
from persistence import PersistenceError
from persistence_assembly import open_persistence_reader
_ttl, cap = _settings_of(scope.profile_dir)
try:
with open_persistence_reader(scope.profile_dir) as store:
rows = store.coordination.list_pinned_subagents(max_resumable=cap, now=now)
except PersistenceError: # unreadable here: nothing pinned
return []
out = []
for row in rows:
record = {**row.document, "expires_at": row.expires_at}
if row.state.value in ("running", "claimed"):
record["pin_paths"] = _live_pins(record)
out.append((row.subagent_id, record))
return out
def pinned_worktrees(now: Optional[float] = None) -> dict[str, str]:
"""``{realpath: reason}`` for every worktree a live resumable record pins, across this install's profiles.
The startup sweep's only view of the records."""
now = now or time.time()
pins: dict[str, str] = {}
# A profile a plugin runs elsewhere still pins its trees; this only reads its records.
for db in _profile_dbs(include_run_elsewhere=True):
for sid, record in _read_pins(db, now):
until = time.strftime("%Y-%m-%d %H:%M", time.localtime(record["expires_at"])) if record.get(
"expires_at") else "?"
for path in record.get("pin_paths") or ():
pins.setdefault(os.path.realpath(path), f"resumable subagent {sid} (pinned until {until})")
return pins
def pin_reason(path: str, pins: dict[str, str]) -> Optional[str]:
"""Why the tree at *path* is pinned (a pin on the tree or any directory inside it), else None."""
root = os.path.realpath(path)
for pinned, reason in pins.items():
if pinned == root or pinned.startswith(root + os.sep):
return reason
return None