Files
PaperClipAI/packages/adapter-utils/src/acpx-engine/run-coordinator.ts
T
Nicky LeachandPaperclip b446ff59bf refactor(acpx-engine): coordinator-owned ACP run lifecycle with a typed resource ledger (#11576)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent adapters run agent sessions through the ACPX engine
> - The ACPX engine handled one run attempt as a long implicit procedure
> - That shape made resource ownership, cleanup order, and failure
behavior hard to verify
> - This pull request gives the attempt a coordinator, a typed resource
ledger, separate run sites, and explicit turn and settlement sequences
> - The benefit is clear ownership, one cleanup path, safer session
reuse, and testable failure behavior

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The ACPX engine manages startup, turn execution, session reuse, and
cleanup inside one large run procedure.

**Current behavior**

The run procedure owns several resources through implicit control flow.
Cleanup and session reuse behavior depend on lane-specific branches and
error paths.

**Proposed behavior**

The coordinator owns the run attempt. A typed ledger records six
resources and their states. Host and sandbox run sites own lane-specific
acquisition. Turn and settlement sequences expose typed outcomes. The
engine emits allowlisted phase telemetry.

**Reason and benefit**

Explicit ownership makes cleanup and failure behavior easier to inspect.
The fault matrix and characterization tests protect the external result
while the refactor reduces hidden control flow.

**Breaking changes**

None to the public adapter contract. The host warm-save path now closes
and relaunches the runtime because a transferred runtime could retain a
run-scoped credential. A cold session-handshake failure now closes the
created runtime.

**Additional context**

This pull request contains the ACPX engine lifecycle refactor, its
tests, and the lifecycle document.

## What Changed

- Add a run coordinator for startup, turn execution, settlement, and
result reproduction.
- Add a typed resource ledger with open, sealed, and consumed states.
- Add host and sandbox run sites for lane-specific resource acquisition.
- Replace separate runtime maps with a generic session reuse store.
- Split session fingerprint identity from the outer session key.
- Add typed turn and settlement sequences with one cleanup owner.
- Add a closed allowlist for phase telemetry.
- Add characterization tests and a 17-case fault matrix.
- Add `doc/acp-run-lifecycle.md`.

## Verification

- `npx vitest run packages/adapter-utils/src/acpx-engine/` passes 18
files and 286 tests at the submitted commit.
- `pnpm --filter @paperclipai/adapter-utils typecheck` reports 0 errors
at the submitted commit.
- Run the full pull request checks after GitHub starts CI.
- Run Greptile review after the pull request opens.

## Risks

- The refactor changes internal control flow across the ACPX engine.
- Host warm-save behavior now closes and relaunches the runtime.
- Settlement changes the handling of a cold session-handshake failure
from a leak to a close.
- The characterization baselines and fault matrix reduce the risk of an
external behavior change.

> Paperclip is the open source app people use to manage AI agents for
work
> The adapter layer runs agent sessions through the ACPX engine
> The engine needs explicit lifecycle ownership for reliable cleanup
> This pull request adds coordinator-owned phases and a typed resource
ledger
> The result makes lifecycle behavior easier to test and review

## Model Used

OpenAI GPT-5 Codex. Exact model ID: GPT-5. The model used tool
execution, repository inspection, and code review support. The
implementation author supplied the submitted code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-17 22:02:16 -07:00

126 lines
5.2 KiB
TypeScript

// The run coordinator.
//
// One `run()` coordinator owns the attempt. It sequences four steps: startup,
// turn, settlement, and result reproduction. It holds the routing table as
// data:
//
// * A build failure or a partial-bridge failure throws from startup. The
// coordinator's one catch replays the `startup_rollback` entries through the
// partial ledger, records the disposition report, and rethrows.
// * A runtime-create, handshake, missing-handle, or configuration failure
// produces a `settle` result. The coordinator settles the resources, then
// reproduces the error result.
// * Every other startup outcome produces a `ready` result. The coordinator
// runs the turn, settles the resources, then reproduces the turn result.
//
// The coordinator has no catch around the turn: the turn never rejects and
// returns a typed `TurnCompletion` (Phase 21). The external result is reproduced
// AFTER settlement, so a caller never observes a result before the run releases
// its resources.
import type {
AcquiredRunResources,
ConsumedRunResources,
PreTurnFailedCause,
ResourceDisposition,
ResourceId,
StartupReady,
StartupResult,
TurnCompletion,
} from "./run-contracts.js";
/** One resource's final disposition, as the coordinator or settlement records it. */
export interface ResourceDispositionRecord {
readonly id: ResourceId;
readonly disposition: ResourceDisposition;
}
/** The per-resource disposition report the coordinator records at each end. */
export interface SettlementDispositionReport {
readonly records: readonly ResourceDispositionRecord[];
}
/** The cause the coordinator hands to settlement. A clean turn carries no cause. */
export type SettlementReason =
| { readonly kind: "pre_turn"; readonly cause: PreTurnFailedCause }
| { readonly kind: "turn"; readonly completion: TurnCompletion };
/** The outcome the coordinator hands to result reproduction. */
export type ReproducibleOutcome = SettlementReason;
/**
* The four steps the coordinator sequences, plus the run ledger. The engine
* supplies each step; the coordinator owns only the order and the startup
* rollback. This keeps the coordinator free of the engine's private run state.
*/
export interface RunPlan<TResult> {
/** The one run ledger for the attempt. The coordinator creates it (see `runAttempt`). */
readonly ledger: AcquiredRunResources;
/**
* Run the startup sequence. It returns a `ready` or a `settle` result, or it
* throws on a build failure or a partial-bridge failure.
*/
startup(): Promise<StartupResult>;
/**
* Replay the `startup_rollback` entries the partial ledger carries. The
* coordinator calls it only on a startup throw, with the claimed entries.
*/
rollbackStartup(consumed: ConsumedRunResources): Promise<void> | void;
/** Record the per-resource disposition report at the end of the run. */
recordDisposition(report: SettlementDispositionReport): void;
/** Run the turn against the ready resources. It never rejects. */
runTurn(ready: StartupReady): Promise<TurnCompletion>;
/**
* Settle the run's resources for the given reason. The one cleanup owner. A
* synchronous return adds no awaited boundary, so a step that already settled
* inline keeps the caller's timing unchanged.
*/
settle(reason: SettlementReason): void | Promise<void>;
/** Reproduce the external result after settlement. */
reproduceResult(outcome: ReproducibleOutcome): TResult | Promise<TResult>;
}
/**
* Run the attempt through the routing table. The coordinator is the one owner of
* the startup-to-settlement order.
*/
export async function runAttempt<TResult>(plan: RunPlan<TResult>): Promise<TResult> {
let startupResult: StartupResult;
try {
startupResult = await plan.startup();
} catch (startupError) {
// The coordinator's only catch wraps startup. A build failure and a
// partial-bridge failure reach here. Claim the partial ledger, replay its
// `startup_rollback` entries, record the disposition report (each entry the
// rollback released is `finalized`), and rethrow the original error.
const consumed = plan.ledger.takeForSettlement();
await plan.rollbackStartup(consumed);
plan.recordDisposition(finalizedReport(consumed));
throw startupError;
}
if (startupResult.kind === "settle") {
// A pre-turn failure after the ledger acquired resources. Settle the
// resources, then reproduce the error result AFTER settlement.
const reason: SettlementReason = { kind: "pre_turn", cause: startupResult.cause };
const settled = plan.settle(reason);
if (settled) await settled;
return plan.reproduceResult(reason);
}
// The ready path: run the turn, settle, then reproduce the result. There is no
// catch around the turn — `runTurn` never rejects.
const completion = await plan.runTurn(startupResult);
const reason: SettlementReason = { kind: "turn", completion };
const settled = plan.settle(reason);
if (settled) await settled;
return plan.reproduceResult(reason);
}
/** Build a disposition report that marks every claimed entry `finalized`. */
function finalizedReport(consumed: ConsumedRunResources): SettlementDispositionReport {
return {
records: consumed.entries().map((entry) => ({ id: entry.id, disposition: "finalized" as const })),
};
}