Skip to content

feat(acp): add persistent harness delegation to the RSS Gateway - #16

Open
fffonion wants to merge 30 commits into
masterfrom
feat/rss-acp-harness-delegation
Open

fffonion wants to merge 30 commits into
masterfrom
feat/rss-acp-harness-delegation

Conversation

@fffonion

Copy link
Copy Markdown
Contributor

Summary

Add an opt-in delegate_acp tool to the bundled RSS Gateway. RustScript Agent remains responsible for the parent run, approval, workspace authority, and final answer. A configured local harness owns child inference and its external session state; the Agent communicates with it over ACP v1 stdio.

  • Reuse the Agent's config.yaml for local harness launch definitions. Publish the tool only when the Gateway has a valid nonempty harness table and durable storage. Keep the default RSS inventory, the six legacy MCP tools, and editor-driven acp proxy unchanged.
  • Require a human decision for each new call. Pin an external session to the authorized parent session and harness, and restore it without silently creating a replacement or resending an uncertain task. Retain process capacity until cleanup is confirmed.
  • Add bounded, current-call results and operator guidance. The configured harness runs as a trusted local process; the ACP callback policy does not provide OS or network isolation.

Verification

Local candidate: 8f9b6c3df935530863865a1d46ec4ff6fa7600ee, based on 588c9d47baabcdb2f03179531355508a7238f776.

  • Real Gateway HTTP admission, approval, bundled RSS execution, durable storage, and process restart: two runs before restart and one after. Three child processes recorded one session/new, two successful session/resume responses, and three session/prompt requests on the same external session. Each parent model response depended on the tool result for its current call. The model and ACP peer were synthetic fixtures; no live inference service was used.
  • End-to-end target: 6 passed, 1 child entry ignored. Controls cover denied approval, rejected extra arguments, load-only history exclusion, cancellation and cleanup, pin fencing, and bounded results. Workspace revocation also passed in the policy target.
  • Compatibility: ACP client 33, legacy ACP proxy 53, MCP catalog 8 (including the mixed-registry negative control), config 24, RSS tool contracts 116, tool registry 32, and docs 37. All 89 discovered RSS sources compiled. Scoped strict Clippy, format, and diff checks exited 0.
  • Packaging: 15 tests passed with a process-local hooks setting. The initial local packaging run recorded 14 passes and one failure: the developer machine's Git author hook rejected a disposable test repository's fixture commit. The isolated rerun exercised the exact inventory, modes, and packaged source bytes.
  • GitHub Actions on the exact pull-request head.

Review focus

Check that RSS dispatch and the native launch path share the admitted run and call identity; that new approvals cannot carry over from another call; that restored or interrupted sessions do not replay external work; and that public results exclude private session identifiers, launch definitions, raw frames, and internal replay state.

Expose explicit initialize, session setup, prompt and close phases over a bounded ACP v1 stdio child. The caller receives the peer session id before any prompt is sent, so the durable scope can persist the binding and send intent first.

Prefer session/resume when advertised, use session/load only when solely advertised, and reject restore failures without creating a new session. Discard load replay at the serialized ingress boundary, cancel permission requests, and keep prompt text bounded to 32 KiB.

The owned supervisor enforces the 1 MiB frame limit, 64-notification and 4 MiB notification budgets, absolute deadlines, and process-group cleanup on explicit close or drop.
Classify every inbound line before it reaches the SDK transport: only the
response carrying the exact prompt request ID is forwarded, so text after the
matching response and unrelated frames never affect the result. Validate
session updates with the locked SDK schema, answer peer requests inline, and
charge only frames that are actually unconsumed.

Keep the direct leader unreaped while terminating and confirming the owned
process group, then reap it; share one absolute cleanup budget with connection
draining and never signal a cached PID after reaping. Release capacity only
after cleanup is proven.

Extend the ACP fixture and client tests for decoy responses, non-v1
handshakes, malformed updates, inline request bursts, long ready streams,
terminal callbacks and leader-exit-first group cleanup.
Byte-parse /proc stat for live group membership so a non-UTF-8 name or an
unreadable/unparsable entry cannot look like an empty group; only a vanished
entry counts as absence and cleanup stays unconfirmed otherwise. Group tests
observe members by PID and kernel start time instead of reusing the same
/proc group scan as the oracle.

Close now interrupts pending initialize/new/restore requests inside the single
absolute cleanup budget, with only a small drain slice before process reaping,
and only a published prompt attempts session/cancel. The supervisor publishes
typed final cleanup evidence through a caller-held observer before releasing
its process slot, so a timed-out close or a drop cannot hand unverified
capacity to the next delegation.

Ingress quota is released by the actor branch that consumes the matching
response, so abandoning the caller's wait no longer leaks a forwarded frame.
…tion

Verify the procfs view before spawning a delegated harness: the single full
procfs mount at /proc must be unrestricted (no nonzero hidepid), the process
must not span nested PID namespaces, and the same mount identity plus the self
PID/PGID anchor are rechecked before every group measurement. An unavailable,
replaced or ambiguous view is an error, never an empty group, and delegation is
refused before spawn when the view is known inadequate.

Treat a Z/X thread-group leader as terminal only when the kernel reports a
single thread. A top-level /proc scan lists only leaders, so a zombie leader
with live siblings previously looked absent, leaving the group unkilled while
cleanup kept its slot. Preserve the PGID for dead entries and never count a
parsing or visibility ambiguity as nonmembership.

Make prompt publication an explicit gate. Decide shutdown, the absolute
deadline and a withdrawn caller wait before PreparedRequest::block_task, which
enqueues synchronously: a stop that wins before publication sends neither the
wire prompt nor session/cancel. After publication, claim_cancel atomically
checks the serialized ingress for the matching response, so a response already
claimed cannot be followed by a late cancel. Track the actual pipe writer and
report written, partial, failed and merely-enqueued states separately.

Align the cleanup observer contract with the supervisor: publish the confirmed
report, then release the slot before task exit, and have wait_for_cleanup fence
on exit. Add deterministic gates for a pre-publication stop and deadline, one
cancel for an outstanding published prompt, no cancel after a claimed response,
and an unconfirmed bounded close whose observer confirms later without changing
the production budget.
…the wire

Replace the procfs group census with a waitid(WNOWAIT) proof: signal the
owned group only while the direct leader is still our unreaped child,
reap exactly that child, and confirm absence only when signal 0 reports
ESRCH for the original group. A lagging member or a reused group number
keeps capacity retained, and a host with untrustworthy waitid/kill
semantics is rejected before spawn.

Move prompt publication to the bounded stdio writer. One arbitration
record orders shutdown, the deadline, caller withdrawal, the first
written byte, the completed frame and the matching ingress response.
A frame discarded before any byte sends neither cancellation method; a
complete outstanding prompt gets at most one session/cancel; a partial
line poisons the connection; and the SDK's deferred $/cancel_request
for the reserved prompt id is suppressed at the wire.
Wire the operator-owned `acp_harnesses` table through the existing
`config.yaml` loader and keep its argv host-private, so the public config
snapshot never projects a launch definition and an invalid table fails
startup before the listener binds.

Add the durable delegation policy: a user approval bound to the run, the
call, the admitted workspace, the launch definition and the pin version; a
private session pin created once and restored afterwards; a separate
durable prompt-send intent; and one settlement write that also releases
the pin lease. A pin whose remote state is unknown is never rebuilt or
continued automatically.

The policy is installed only when the table is non-empty, refuses every
call before the spawn point when approval, workspace, harness, binding or
capacity is missing, and reports `completed` only after `end_turn` and
confirmed process cleanup.
Re-check the recorded stop on every poll_write, so a frame parked before
its first byte stays revocable and a partial frame is never appended to or
followed by a cancel notification. Ingress only claims a response after
the writer proved a complete frame.

Take the child's stdin out of the shared wire and drop it after the
connection is discarded, so a benign harness observes a real EOF and can
exit before any group signal instead of being force-terminated.

Anchor one absolute cleanup budget at the first observed stop and bound
cancel-lock acquisition and cancel-line serialization to its drain slice,
so blocked IO cannot delay group termination or reaping.
Record caller withdrawal synchronously under the ingress lock when the
prompt future is dropped, and re-read shutdown, the absolute deadline and
that withdrawal after taking the same lock on every write attempt. A
parked first byte can no longer be published when the SDK polls its
transport before the actor; the guard is disarmed only after a completed
exchange, so a finished prompt is unaffected. Already-sent and partial
frames keep their existing transitions.

Let the supervisor anchor cleanup from the original run deadline and the
first cleanup-start notification instead of waiting for the SDK connection
to finish. Every path into cleanup shares the existing 500 ms drain slice
of the one absolute 5 s budget, so a connection stuck in an inline reply
or a physical writer drain cannot hold the process slot or delay reaping.
Publish the idempotent cleanup anchor at the actor's single common exit
instead of scattering the notification across individual stop branches.
The ACP SDK keeps the physical transport draining after the foreground
task returns, so the connection future is a late termination signal that
the supervisor may otherwise only observe at the run deadline. Clean
prompt completion, early setup errors, caller withdrawal before the
prompt is armed and command EOF now all notify the supervisor, while the
earliest stop still anchors first before any cancellable IO.

Add regressions over the real SDK and a real child harness. One holds the
transport close so the connection future cannot resolve and proves the
anchor is published while it is still pending. The other withdraws the
prompt before arming, never closes or requests shutdown, and requires
confirmed cleanup, an exact reap and an empty post-handshake wire within
the bounded drain.
Route delegate_acp approvals through the gateway's real manual approval
surface, bind the private launch definition, workspace, pin version, task
and expiry durably, and refuse automatic reviewers or previews that cannot
show the complete task.

Replace the unconditional session metadata merge with a database-enforced
compare-and-swap on owner, durable session identity, document version and
the exact lease call. Settlement and lease release share one write,
prepared/creating calls are indeterminate, and settled replays require the
identical request and authenticated approval identity.

Wake setup and prompt cancellation from the run cancellation watch, recheck
the run, approval and same absolute deadline at the last pre-spawn boundary,
and confine every post-spawn early return to confirmed cleanup or an
explicit quarantine. Bound the serialized result envelope to the run output
budget with UTF-8 truncation.
Add docs/acp-delegation.md and update docs/acp-mode.md,
docs/configuration.md and docs/status.md to describe the acp_harnesses
startup entry, the delegate_acp tool contract, durable session pin
binding and resume across gateway restarts, and the failure table for
approvals, cancellation, timeouts and lost external sessions.

Documentation only: no code, schema or configuration changes, and no
new test coverage.
Spawn the integration-test executable as a real Gateway child process
with the production router, durable store, and bundled RSS loop; then
stop and reap it and start a second OS process on the same private home
and database. The control admits a plain run over HTTP in each process
and proves the second process's actual model input contains the first
turn's durable session record.
… run

- Route automatic and guardian-sealed runs through a real durable
  human_pending approval row instead of refusing the tool outright; only
  an authenticated manual resolver can authorize the external process.
- Read workspace authority, cancellation root, sealed reviewer and the
  admitted deadline from the live run, and revalidate them in a
  synchronous barrier immediately before spawn. A stop, revocation,
  elapsed clock, inactive run or stale approval fails with zero spawns.
- Pin CAS retries to the original session row identity, so a recreated
  session never inherits an approval, lease or outcome. A stale lease is
  reclaimed only when the store proves its owning run terminal, and the
  takeover settles the interrupted call in the same durable write.
- Keep pin ownership and the process slot charged until a real terminal
  cleanup report exists; an interrupted restore before the prompt send
  intent stays recoverable and is never replayed as a prompt.
- Refuse a run output budget below the minimal result envelope before any
  approval or process exists, and drop the diagnostic code before falling
  back to a bounded refusal so a legal budget always carries a complete
  or explicitly truncated envelope.
- Boot each child through the production with_agent_selection_and_compaction
  path with the gateway's default home selection request, and assert that both
  real health responses report source.kind == bundled.
- Hand the spawned Child to an owning guard immediately so every startup
  failure kills and reaps the exact process instead of orphaning it.
- Add a startup-failure control covering live-but-unready children and invalid
  readiness, plus a distinct run_id assertion on restart.
…p path

- Replace the unbounded kill/wait (which dropped the kill error and marked
  the child reaped even when wait failed) with one absolute 5 s reclamation
  window: finite try_wait observation of the exact owned child, EINTR treated
  as retryable, and the guard marked reaped only after a real terminal state
  was observed and the process reaped. Failures keep the handle and report
  the signal/poll reason instead of pretending success.
- Share that single window between the startup timeout and the normal stop
  timeout, and share one per-guard deadline between explicit calls and Drop so
  reclamation windows never stack.
- Exercise the real negative control through the ordinary GatewayProcess::start
  failure wrapper: the child is alive and unready when the short observation
  clock expires, only ChildGuard::drop reclaims it during unwinding, and a
  spawn identity witness plus /proc proves the exact pid was reaped inside the
  total budget. An identity-checked outer reclaimer only acts if the owner
  regression leaked the child. The finite-deadline and EINTR error paths use a
  test double; both real-child cases remain.
Keep the guard's single absolute reclamation window and record its one forced signal attempt, so an explicit stop that runs out of budget cannot be followed by a second SIGKILL from Drop. A repeated entry only observes what is left of the original deadline.

Drop implementations no longer write diagnostics while unwinding. The outer safety net re-reads the exact child identity and reaps an already-exited child without signalling it; every WNOHANG/EINTR path shares one bounded deadline.

Add the failing-window test double and the real killed-child reap case, and keep the existing real startup-failure controls unchanged.
The outer safety net read a live /proc stat and only then the command
line. A child that exited in between had an empty cmdline while the stat
snapshot still looked alive, so the net refused the identity and skipped
waitpid, leaving a zombie behind.

After an empty cmdline, re-read the same stat a bounded number of times,
re-validating parent and spawn start time, and accept only the terminal
zombie state so the existing bounded waitpid reaps that exact child
without a signal. The observation is injectable through a test-only hook:
the regression makes the exact child exit exactly between the two reads
and proves it is waited for without a signal, while a mismatched witness
control proves the net still refuses.
…dline

The fixture fallback abandoned an exact child whose /proc command line had
already gone once eight stat re-reads were spent. Linux clears the argument
vector in exit_mm and only later publishes Z in exit_notify, so that fixed
count can run out while the child is still alive, and the unreaped zombie was
left behind.

Observe once and keep one boundary for everything after it:

- A lost identity still returns with zero operations.
- A matching Z, or a matching child with no command-line text, goes straight
  into the bounded waitpid(WNOHANG) loop and is never signalled.
- Only a matching child that still shows the harness command line in its
  command line may make the one existing signal attempt.
- Every wait iteration re-proves parent and spawn start time first, and the
  loop sleeps only the remaining time of the same absolute RECLAIM_BUDGET
  deadline, so EINTR and a never-terminating child both end at the original
  window instead of opening a second one.

The regression holds the transient open deterministically: a real child
replaces itself with a program that has an empty argument vector and then
blocks on its stdin pipe, so /proc reports a live non-Z child with no
command-line text for as long as the test keeps the pipe open. The fallback
must keep waiting past the removed eight-read budget, signal nothing, reap
that exact child once the pipe closes, and return at the original deadline
for a matching child that never terminates.
Check the single reclamation deadline after the identity observation and
again immediately before the kill, and before every waitpid after an
observation. Once the window is spent, no signal, identity re-read, poll,
or wait may start; sleep and EINTR still consume the original remainder.

Two deterministic controls advance a test-only clock to exactly the entry
deadline: a real /bin/sleep child carrying the harness entry in argv[0]
must stay alive and owned instead of being signalled, and a real zombie
must stay unreaped under /proc until its exact owner collects it.
- Route automatic, guardian and unset reviewer runs through a real durable
  human_pending row; the production Telegram picker and /approve /deny
  paths accept a delegation id as syntax only and authorize strictly from
  the bound run, session, owner, picker, pending state and expiry.
- Freeze one absolute delegation deadline, then perform the only process
  creation under a single synchronous fence shared with the real writers:
  the persistence session fence used by CAS/delete/approval resolve, the
  RunCancellation mutex used by request, and the workspace authority
  revoke mutex. A stop, revoke, replacement or expired approval observed
  there is zero spawn; one that loses the race is cancelled normally.
- Carry the original session identity through every phase write, abort and
  asynchronous settlement, and re-check the original pin lease in each
  mutation. A replacement row is never inherited, even with the same owner.
- Give one cleanup owner the call identity, observer, service permit and
  per-run admission. Only confirmed cleanup settles and releases; unknown or
  lost cleanup stays charged in quarantine. A stale lease is reclaimable
  only after a durable terminal run and recorded confirmed cleanup.
- Measure the result budget at the public JSON boundary, add the typed
  refusal minimum, and drop the unvalidated code-dropping fallback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant