Files
PaperClipAI/maps
DottaandPaperclip 16643a6e03 fix(runner): recover pending Stop cleanup after controller restart (#18682)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server owns execution, Stop delivery, and usage settlement.
> - A Stop can remain pending when the controller restarts.
> - Recovery must reach the existing session without starting more paid
work.
> - Startup and budget fences currently block that cleanup, and
interrupted runs leave the restart selection.
> - This pull request gives exact audited Stop cleanup a shared
authority check and records its real acknowledgement.
> - The benefit is safe cleanup while usage debt remains honest.

## Linked Issues or Issue Description

**What happened?**

A pending native run-only Stop can retain an unfinished execution owner
after controller loss. Its startup cancellation fence prevents recovery
admission. If teardown marks the run interrupted and clears its task
lock, restart selection also omits it. A recovered session can receive
cancellation without the durable acknowledgement that the normal Stop
request would save.

**Expected behavior**

Recover only the existing remote session for the audited pending Stop.
Keep fresh provider work blocked, including during budget pause. Keep
incomplete usage pending until a real complete receipt arrives.

**Steps to reproduce**

1. Start a native run with a held reservation and an authenticated
remote checkpoint.
2. Persist a run-only Stop and its startup and execution cancellation
fences before acknowledgement.
3. Lose the controller. Leave the coordinator unfinished, mark the run
interrupted, and clear its task lock.
4. Attempt restart recovery and observe the missing claim or
cancellation admission rejection.

Related work: #14733 binds caller Stop requests. #18658 handles plugin
startup cleanup obligations. #18035 proposes broader accounting changes.
This change repairs existing-session Stop recovery and preserves current
accounting guards.

## What Changed

- Add one shared check for the exact run, company, issue, pending Stop,
intent audit, live recovery lease, generation, and remote reattachment
disposition.
- Include eligible interrupted Stop owners in restart selection. Keep
generic interruptions and another task execution owner fenced.
- Reuse only the original held reservation for cleanup. Keep budget
pause effective for fresh, bootstrap, dead-runner, and unproven recovery
work.
- Apply the same cleanup authority at heartbeat runtime selection and
native entry. Skip attachment staging and warm-owner retirement only for
that exact cleanup. Revalidate at session publication and fail closed if
the proof changed.
- Send the existing Stop through the audited cancellation producer
before turn submission. Close the coordinator only after
acknowledgement, including system-owned run-only Stops.
- Give verified cleanup a transport purpose that retains pending
semantic inputs without replay, dispatch, or a semantic reply. Add an
explicit Core retain-only intake mode; preserve authenticated identity,
schema, digest, sequence and replay checks. Ordinary execution still
requires its dispatcher.
- Add PostgreSQL, native protocol, and startup-fence regressions. Update
the execution contract and recovery maps.

## Verification

- The combined Stop regression fails on unchanged production at the
cancellation reservation guard. Interrupted restart selection also fails
before the repair while its running sibling passes.
- An assembled `heartbeatService.recoverNativeRunsAfterRestart`
regression exposes the earlier runtime-selection fence with the rest of
the repair present. The fixed path reaches selector/claim, runtime
selection, original held-budget reuse during pause, dispatch, real
native protocol, audited cancellation, and heartbeat settlement. It
starts no provider turn, acquires no new sandbox, and does not reclaim
the task lock.
- Fail-if-called attachment staging and turn boundaries remain
untouched. A retained warm-owner regression prevents retirement.
Invalidation at session publication fails closed. Actual backend/driver
constructor tests verify cleanup-purpose forwarding, absent default
options, and denial under foreign ownership.
- Missing usage retains accounting debt and the hold. A later complete
receipt records one 25-cent charge and settles that same hold.
Concurrent duplicate cleanup is denied. Both user-owned and system-owned
Stops pass.
- Real transport tests: 9 pass on Node 24.22.1. They preserve ordinary
saved-tool and completion recovery, prove the authority-denial race
before cancellation, and qualify cleanup with pending
ordinary/completion inputs and either handler ordering.
- Real authenticated Core intake: 11 pass. Callback-present and
callback-absent retain-only cases persist and acknowledge unanswered
input without dispatch, recovery or result. Default missing-dispatcher
rejection and digest-integrity/suspension guards remain effective.
Omitting the callback alone first failed by disconnecting; the explicit
retain-only mode fixes that defect.
- Repository `pnpm -r typecheck`, the server/runner-vendor build, map
checks, and module boundary checks passed locally before integrating the
latest retained-startup change. That integration passes 11 native
startup/cleanup compatibility cases and 3 assembled recovery/accounting
cases. The final broad affected-suite attempt was stopped without a
verdict; it is incomplete. Full repository tests and build are delegated
to current-head GitHub CI.
- Review exposed an additional real-process close failure with
unanswered input. The corrected path requires a fresh exact
provider-stop receipt confirming exit, followed by durable event drain
and exact runner suspension. All 11 focused transport cases pass,
including missing/false exit-proof negatives and ordinary recovery
siblings. Runner TypeScript and map validation pass after this
correction.
- The assembled test controls provider, workspace-transfer and GitHub
bootstrap I/O. It does not qualify hosted credentials, physical provider
termination, workspace preservation, or historical receipt recovery.
Local socket-permission setup failures are separate from semantic
regression results. No hosted replay has run on this repair.

- CI exposed an ordinary factory-call compatibility regression and an
obsolete authority-read test fixture. The repair preserves
single-argument ordinary calls and updates the race fixture without
changing its Stop assertions. The complete native executor suite now
passes all 1,049 tests; the ordinary factory boundary and all five
Stop-accounting cases pass. A separate local environment-default case
twice exceeded its five-second wait while other work ran; its prior-head
CI case passed. The same unchanged case passed an isolated diagnostic
without changing its assertion or timeout; the precise contention source
remains unproven.

- The final fixture edit initially used the wrong overloaded promise
type. CI rejected it; the annotation-only correction passes the exact
`pnpm run typecheck:build-gaps` entry point locally, including server
service tests and remaining workspaces. No runtime assertion changed.

- Final exact head `007fd4d04a2d6338c6dc073e97ab470a277fc3d0`: required
`ci / verify` and `ci / e2e`, build, typecheck and test groups pass.
Greptile is 5/5 with both findings resolved. Three expected checks are
skipped; the optional native check is neutral, while its final
current-head comment gives 5/5 from source inspection without a checkout
or test execution. The first server-shard attempt lost its self-hosted
runner connection; one scoped rerun passed. Its original annotation and
unavailable-log evidence are retained.

## Risks

- This changes execution authority. Cleanup requires an audited, exactly
bound pending Stop, an unfinished coordinator, a live remote
reattachment claim, and the original held reservation. It never
authorizes a replacement provider turn.
- Missing checkpoint, original held reservation, termination, or usage
evidence can keep cleanup or accounting pending. The repair does not
manufacture acknowledgement, replies, receipts, or zero cost.
- Retain-only intake is an internal trusted constructor option. It
changes no agent tool permission. Ordinary callback requirements and
semantic dispatch remain unchanged.
- No schema, public API, provider profile, or deployment setting changes
are required.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, Extra High reasoning, with source
inspection, code execution, and regression testing. The context-window
capacity is not exposed in this session.

## 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 described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket ID
- [x] I have run affected 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 risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open findings
- [x] I will address all reviewer comments before merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-02 18:22:40 -06:00
..

Paperclip maps

The maps describe the same capabilities from two perspectives:

  • Feature map: what a person can do, where to reach it, and how to verify the user journey. Preserve its Poteto format.
  • Agent access map: the APIs and agent entry points for those capabilities, their permission boundaries, and access verification.

The chat scenario catalog adds natural-language requests, starting context and expected conversational outcomes for the same capability IDs. It lives with Product E2E as planning data; a scenario reference is neither a registered execution nor evidence that a journey passed.

These are sibling directories under maps/. Each feature file has a same-named agent access companion. Reuse the product map's sub-feature IDs, so tasks/create identifies the same capability in both maps. Product behavior remains governed by the implementation spec; a map cannot grant authority or redefine a permission denial as success.

Capability identifiers

The feature ID is the recipe filename without .md, such as onboarding. The full capability ID joins that feature ID and a Sub-features key with /: the company key in feature-map/onboarding.md is onboarding/company. Its agent-access-map/onboarding.md companion uses the same local company key. The feature-map index lists the existing feature and full capability IDs.

Each child page states Feature ID: `onboarding`. after its introduction or product-map link. In feature recipes, show the full ID beside the parsed local key: - `company`: `onboarding/company` — create a company. In access companions and Storybook verification guidance, keep the existing local heading and put Capability ID: `onboarding/company`. beneath it. These labels make the existing identifiers visible without changing keys, anchors, or ID generation.

Use full capability IDs in cross-feature references, Storybook annotations, tests, issues, PRs, and verification evidence. Both segments use lowercase letters, digits, and hyphens. Keep filenames and keys stable when display titles or navigation labels change; renaming either changes the capability ID.

Entry-point IDs describe a surface, such as web-wizard, and are scoped to their recipe. Reference them with a recipe link, such as onboarding.md#web-wizard, and record the capability exercised separately. Navigation section labels are not capability IDs. See IDs and references for examples.

Access contract

Every business operation needs both an API and a usable agent entry point for an actor authorized to perform it. A dedicated tool is optional when REST, the CLI, an assigned MCP client, or native search_api / call_api already provides the operation. Record which agent surfaces actually have that path; an installed CLI or optional MCP package cannot be assumed available to every native/remote run.

Track these independently:

Dimension Values and meaning
API present, missing, not-applicable, or unreviewed. Use exact methods/paths; distinguish protocols from REST.
Agent access available, partial, missing, restricted, operator-only, not-applicable, or unreviewed. Name the supported surface and actual entry point.
Policy Actor, action/grant, company/resource/ownership scope, responsible-user intersection, run requirements, work modes, and gates relevant to the operation.
Evidence source-only, verified, failed, blocked, or not-run. Source presence and successful board calls are not agent verification.
Review depth baseline records representative operations and known gaps; operation-reviewed enumerates the capability's meaningful operations and their individual access contracts.

Broad capabilities such as task properties must be split into operations before they count as operation-reviewed: renaming, metadata edits, assignment, dependencies, and lifecycle changes can use different tools and permission rules. An available read path cannot certify a write path. List/get/create/update/delete, execution/control, credential handling, and resolution are separate where their authority or transport differs. Do not duplicate request schemas from OpenAPI.

Exceptions and restrictions

Presentation-only state, static developer fixtures, and pre-start/local operator work may use not-applicable for a domain API, with a concrete reason and the existing local path. When a capability combines shared data with presentation, split the operations: browser recents do not exempt resource lookup from API coverage. Promoting local state to a shared feature requires revisiting the entry.

A board-only endpoint is restricted for agent identity, not an automatic exception or a missing API. Cite the enforced policy and record whether the agent can request the authorized human's action and observe its result. An unresolved delegation question remains in Gaps. Company access, a job title, a personal assistant's OAuth grant, or an accepted interaction does not grant board identity. Keep budget, approval, secret and execution authority intact.

Check actual route/service authorization and production tool admission. OpenAPI actor labels and scenario/evaluation tool declarations are supporting metadata; record disagreements rather than using them as proof of access. Native API fallback restrictions, tool field/scope limits, and rollout settings are part of the agent path, even when a legacy agent can call the REST endpoint directly.

Companion file format

Each agent-access-map/<area>.md has an H1, a relative link to its product file, and its feature ID, followed by one H2 backticked local key per product sub-feature. Each capability starts with its full capability ID and contains these fields:

  • Review: baseline or operation-reviewed.
  • API: presence state and exact operation IDs, or a reasoned exception.
  • Agent access: availability state and concrete entry points by surface.
  • Policy: relevant permission and runtime boundaries, with source references.
  • Evidence: evidence state, reviewed commit and sources or executed proof.
  • Verification: allowed/denied assertions and observable result; record what has actually run separately from the proposed recipe.
  • Gaps: missing APIs/paths, discovery drift, unreviewed operations or policy decisions; use none only for the enumerated scope that was reviewed.

For an operation-reviewed capability, use H3 backticked operation IDs and repeat API, Agent access, Policy, Evidence, Verification and Gaps for each operation. Use small operation names such as create, update, read, or run-now. The enclosing capability has Review: operation-reviewed only after its meaningful operations have been enumerated. The following excerpt shows one operation; include the others before using that review label:

## `definition`

Review: `operation-reviewed`.

### `create`

API: `present` — POST /api/companies/{companyId}/routines.
Agent access: `available` — agent REST, CLI routine create and native call_api
under the enabled rollout and active-run/mode gates.
Policy: same company; assigneeAgentId must be the calling agent; cite the
routine authorization and native API policy sources.
Evidence: `source-only` — reviewed commit and source links; no live proof.
Verification: `not-run` — create an owned routine; reject assignment to another
agent; inspect saved configuration, attribution and retry behavior.
Gaps: verify ownership and responsible-user resolution with a permitted agent
context; source presence alone does not qualify this operation.

Keeping the maps synchronized

When a change adds/removes a capability or changes its behavior, API, permission, tool binding, CLI support, or work mode, update the affected companion and product recipe as appropriate in the same change. Preserve IDs across renames where the capability is unchanged; update the affected cross-links together. Indexes discover recipes automatically. An API-only change may update the companion without rewriting unchanged user instructions. Update the corresponding chat scenarios when their request, assumptions or expected outcome changes; use multiple cases for meaningfully different starting conditions rather than treating an API path as conversational coverage.

maintain-verification-skill owns reconciliation of both maps. It follows changed source and authorization, checks real agent reachability, and records product gaps without implementing them during a maintenance pass. The creation skill uses this structure. verify-paperclip consumes the relevant recipes and reports evidence/drift; map editing belongs to maintenance.

Run the structural check after map changes:

node scripts/check-maps.mjs

It checks paired areas/IDs, navigation metadata, required fields, and local references. It does not certify endpoint authorization, production bindings, operation completeness, or live behavior. Source audits must check those against the existing API and tool contracts; avoid a second schema catalog or runtime.

For live access proof, use Paperclip's existing API/runner/MCP fixtures or an owned isolated instance. Use the actual agent identity, target and work mode. Assert the allowed result and relevant denial (another company/private resource, wrong owner, missing grant, invalid run, restricted mode or resolver). Mutations also need persisted state/attribution and retry behavior. Capture evidence using the existing artifact workflow; keep executed run results separate from generated maps/generated/coverage.json, which lists page references.

Local authorship and generated indexes

Change only the recipes, access contracts and stories whose behavior or intent changed. Feature recipes own navigation metadata; stories own small parameters.paperclip annotations. Keep the feature-map README's readable ID index aligned with those sources; it does not register entries for generation. Do not refresh counts in shared READMEs, inventories, fingerprints or review journals.

node scripts/storybook-catalog.mjs validates and generates aggregate navigation, Storybook data, verification routes and the page inventory. All outputs live in ignored maps/generated/, ui/storybook/generated/, and the ignored Storybook preview.tsx wrapper. Start/build and UI typechecking generate their own inputs. A clean merged checkout therefore assembles both branches' changes automatically.

Git provides history and diffs. PRs, issues and CI artifacts retain review/run evidence for the named revision. Capability associations do not create whole-file review dependencies. Keep durable scenario limits in the affected recipe or story.