Integrate current master into sleep-13-grok-dispatch

Preserve upstream fixes and append stack migrations after master history. Keep SQL bytes unchanged and generate snapshots from the integrated schema. Validate the target-branch migration ordering.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-27 01:36:17 -05:00
commit 23f09becf6
356 files changed
+15261 -1111

No files matched your search

+10
View File
@@ -580,6 +580,16 @@ PostgreSQL backends and checks rejection, pool recovery, and transaction isolati
Remove the patch when an upstream release passes these tests. Installs of the
unmodified `postgres` package outside this workspace do not include the patch.
The patch also preserves transaction connection reservation when pipelining is
disabled with `PGMAX_PIPELINE=0`. Without this fix, the driver's pipeline capacity
check skips the transaction reservation callback and `BEGIN` fails with
`UNSAFE_TRANSACTION`. Disabling pipelining makes a queued query wait for the next
available pool connection instead of sending it behind unrelated work on a busy
connection. This can help interactive requests that share a prepared-query pool
with slow background work. It does not make the SQL itself faster. The default
pipeline limit remains unchanged. Test transaction behavior before using this
setting with a driver build that does not include the patch.
Trusted-header actor synchronization retries transient connection failures,
including `CONNECT_TIMEOUT`, at most twice. This retry applies only to the
idempotent actor synchronization operations, not arbitrary transactions. A
+40
View File
@@ -2002,6 +2002,18 @@ extra arguments, model variants, and inherited permission rules require the
Legacy runner; incompatible settings return remediation instead of being ignored.
Saved OpenCode agents keep their runner and runtime policies.
Plugin environment drivers can declare `requiresAgent: true` when their leases
need an agent-owned resource. Setup saves the draft and environment, runs its
existing lifecycle preparation, and waits in `verifying` with the `setup` hold.
The worker becomes idle there until the user finishes hiring. Connection tests
use that draft's identity and a bounded Core-issued probe; ordinary tasks remain
blocked. Environment changes save immediately, preserve the selected account,
and invalidate the previous test. Tests without an agent report that prerequisite
without allocating a lease. Finishing setup still verifies the saved configuration.
Companies that require hire approval keep drafts paused and defer allocation and
verification until that approval. The wizard saves the account with a pending
verification warning instead of requiring a pre-approval computer.
Pi also requires an explicit `provider/model` before testing or hiring; inactive
setup drafts may precede model selection. Install its pinned runtime on the
execution host with `paperclipai runtime setup pi` before testing the connection.
@@ -2363,6 +2375,34 @@ identity mismatches.
## App-Shipped Skills Catalog
Plugin environment drivers can declare `skillKeys` that reference their own
manifest-managed skills. Selecting that environment adds those skills to the
normal authorized skill selection, including an explicitly empty optional
selection. Core installs a missing managed skill in the current company's
library during lifecycle reconciliation or new-run admission and preserves existing
skill edits and explicit version pins. New managed skills use
`plugin-<short-plugin-id>-<skill-slug>` for both the library slug and SKILL.md name.
The short ID is the final dot-separated plugin ID component, without a leading
`plugin-`. An unrelated skill can keep the same slug in a separate canonical
record. The required environment skill wins during delivery: a selected company
skill with the same slug or name is omitted and reported as shadowed. Stored agent
assignments and both library records remain unchanged. Run warnings and snapshots,
and the plugin runtime response, identify the omitted key and the winning key. Existing company copies keep their edits and names
until reset. Lifecycle callers request installation with
`agents.getRuntime(agentId, companyId, undefined, true)`; ordinary runtime reads and
recovery do not install newly declared skills. Run
preparation captures the same immutable versions as ordinary assignments;
recovery uses the saved selection. The lifecycle runtime reader includes the
effective default environment's skills before synchronizing the persistent home.
A task provider can pass its selected environment ID to `agents.getRuntime` when
a task overrides that default. This
contract currently applies to `driver: "plugin"` environments. Other drivers
and plugin drivers without `skillKeys` keep their existing behavior. No agent
configuration is rewritten, and no background scan is added. Changes to implicitly
selected skills, the effective default environment, or plugin requirements enqueue
normal durable runtime events, so an idle ready computer receives updates without
a new run. Failed synchronization retains the event for the existing retry path.
The Paperclip app ships a curated catalog of company skills out of the box. The
catalog is a workspace package at `packages/skills-catalog`:
+1 -1
View File
@@ -84,7 +84,7 @@ Paperclip runs a watchdog reconciliation tick at server startup, at the end of e
For each active watchdog the tick:
1. **Walks the watched subtree.** Starts at the configured issue and follows `parent_id` downward, excluding every issue whose `originKind = 'task_watchdog'` and everything below it. This excludes the watchdog's own review tasks so it cannot trigger itself.
1. **Walks the watched subtree.** Starts at the configured issue and follows `parent_id` downward, excluding every issue whose `originKind = 'task_watchdog'` and everything below it. This excludes the watchdog's own review tasks so it cannot trigger itself. The scan includes at most 100 levels, with the watched issue at level 1. If an eligible child remains beyond that limit, the result is **incomplete**. Paperclip skips review dispatch and rejects watchdog mutation revalidation until it can read the full subtree. A leaf at level 100 does not by itself make the scan incomplete. Reconciliation reports these cases separately through `incomplete` and `incompleteIssueIds`. Startup and periodic reconciliation warn when a watched issue first becomes incomplete. The warning contains the newly affected issue IDs. An unchanged incomplete issue does not produce repeated warnings. Once a successful scan no longer reports that issue as incomplete, a later incomplete scan can warn again.
2. **Checks for live paths.** If any included issue has a live run (`queued`, `running`, `scheduled_retry`), a queued wake request, or a scheduled retry, the subtree is **live** and the watchdog does not fire.
3. **Computes a stop fingerprint.** A SHA-256 hash over the stopped leaves' identifiers, statuses, blockers, pending interactions, and the current watchdog configuration. The configuration is part of the fingerprint, so changing the agent or instructions invalidates the previously reviewed state.
4. **Compares against `lastReviewedFingerprint`.** Match → suppress (the watchdog already saw this exact stopped state). New → proceed.
+126
View File
@@ -0,0 +1,126 @@
# Adapter model and harness audit: October 23, 2026
This audit follows the [October 2, 2026 audit](adapter-model-audit-2026-10-02.md).
It covers model selection in the coding-agent adapters and the CLI pins in the
evaluation sandbox image. Catalog entries identify models; provider accounts
and installed CLIs determine access. No agent defaults or saved model
selections are migrated.
## Model changes
| Adapter | Changes from the audit |
| --- | --- |
| Codex | No new selectable model IDs. Codex 0.160.0 through 0.164.0 ship the same bundled model set, which the picker already lists (including GPT-6 Astra, GPT-5.6 Terra, and GPT-5.6 Luna). OpenAI retired `gpt-5.5` (October 14, 2026) and `gpt-5.4` / `gpt-5.4-mini` (August 31, 2026) from Codex with ChatGPT sign-in. The API and API-key Codex sessions still serve them, so they stay in the picker. When the backend rejects one of them for a ChatGPT account, the environment Test (legacy CLI and Paperclip Runner) now names the retirement and the documented replacement instead of suggesting a stale CLI, a plan restriction, or generic account checks. |
| OpenCode | Add `anthropic/claude-haiku-5-5` and `google/gemini-4-argon` to the static fallback used by remote environments and the Paperclip Runner picker. Both IDs are in the OpenCode model registry (models.dev). |
| Claude Code (direct and Bedrock) | Claude Haiku 5.5 is covered by [#16708](https://github.com/paperclipai/paperclip/pull/16708); this audit does not duplicate it. Haiku 5.5 needs Claude Code 2.1.293 or later and supports all five effort levels. |
| Gemini CLI | Gemini 4 Argon (`gemini-4-argon`) is generally available on the Gemini API, but Gemini CLI 0.65.0 does not register it. Deferred. |
| Grok Build, Kimi Code, Cursor | No new verified model IDs. Grok 4.7 and Kimi K3 remain the newest documented models. |
## Harness changes
| Harness | Before | After |
| --- | --- | --- |
| Grok CLI (`@xai-official/grok`) | 1.0.46 | 1.0.70 |
| Gemini CLI | 0.62.0 | 0.65.0 |
| Kimi Code CLI | 2.1.1 | 2.3.3 |
| Cursor CLI (sandbox layer) | 2026.10.01-e373342 | 2026.10.22-27dcf5f |
| GitHub CLI | 2.102.0 | 2.103.3 |
| Codex CLI (shared provider pack) | 0.160.0 | Unchanged here; [#17245](https://github.com/paperclipai/paperclip/pull/17245) moves it to 0.163.0 |
| Claude Agent SDK / Claude Code | 0.3.286 / 2.1.286 | Unchanged; see "Deferred items" |
| OpenCode (shared provider pack) | 1.18.34 | Unchanged; see "Deferred items" |
| Hermes | 0.19.0 | 0.19.0 (newest on PyPI) |
These pins change only the evaluation image's sandbox layer. They must stay
aligned with the fleet sandbox image definition.
## Sources and verification
Research date: October 23, 2026. Harness pins rechecked October 26, 2026.
- [Codex models](https://learn.chatgpt.com/docs/models) states the GPT-5.5
retirement ("Effective October 14, 2026 ... GPT-5.5 retires from Codex for
users signed in with ChatGPT"), its replacements (GPT-6.1 Sol on paid plans,
GPT-6 Luna on Free and Go), the GPT-5.4 retirement and its replacements
(`gpt-6-sol`, `gpt-6-luna`), and that API-key sessions are not affected.
- The bundled `codex-rs/models-manager/models.json` is unchanged in model set
from [rust-v0.160.0](https://github.com/openai/codex/releases/tag/rust-v0.160.0)
to [rust-v0.164.0](https://github.com/openai/codex/releases/tag/rust-v0.164.0),
the npm `latest` release on October 26, 2026.
- [Claude Haiku 5.5](https://platform.claude.com/docs/en/models/haiku-5-5/overview)
was released October 7, 2026. The
[Claude Code changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md)
entry for 2.1.293 adds `claude-haiku-5-5`.
- [models.dev](https://models.dev/api.json) lists `anthropic/claude-haiku-5-5`
and `google/gemini-4-argon`. The OpenCode 1.18.34 executable's bundled
snapshot predates both. Paperclip Runner binds the selected model into the
OpenCode provider configuration, so the snapshot does not limit it.
- [Gemini 4 Argon](https://ai.google.dev/gemini-api/docs/models/gemini-4-argon)
is generally available since October 13, 2026. Gemini CLI 0.65.0
(`packages/core/src/config/models.ts`) has no entry for it, and pull requests
adding it to the CLI are still open.
- Grok CLI 1.0.70, Gemini CLI 0.65.0, and Kimi Code 2.3.3 are the npm `latest`
tags on October 26, 2026. xAI publishes no Grok CLI changelog; `-m`,
`--effort`, and `grok models` are unchanged in the
[CLI reference](https://docs.x.ai/build/cli/reference.md) and in
`grok --help` from 1.0.70.
[Kimi Code 2.2.0 and 2.3.0](https://github.com/MoonshotAI/kimi-code/releases)
remove the `kaos` MCP executor and require qualified plugin skill names;
Paperclip uses neither. Kimi Code 2.3.2 stops the agent from launching
swarms by itself, so `kimi -p` and ACP sessions no longer start swarms;
2.3.1 and 2.3.3 are fixes and prompt changes. `-m`, `-p`,
`--output-format`, and `acp` are unchanged in `kimi --help` from 2.3.3.
Gemini CLI 0.65.0 makes workspace settings read-only in untrusted folders;
Paperclip writes only home settings and sets `GEMINI_CLI_TRUST_WORKSPACE`
for remote runs.
- Cursor CLI 2026.10.22-27dcf5f is the version `https://cursor.com/install`
resolves. The archive SHA-256 was computed from the versioned Linux x64
tarball, and the extracted executable reports that version.
- [GitHub CLI 2.103.3](https://github.com/cli/cli/releases/tag/v2.103.3): the
pinned digest matches the release `checksums.txt`. 2.103.1 through 2.103.3
are fixes on top of 2.103.0.
- [Hermes on PyPI](https://pypi.org/project/hermes-agent/) remains at 0.19.0.
Newer Hermes releases (v0.22.4) are published only through GitHub, the
installer, and Docker.
## Deferred items
- **Claude runtime 2.1.286 → 2.1.308.** Claude Code's `stable` channel is
2.1.308 (`latest` is 2.1.309), with Agent SDK 0.3.308. The range changes
headless defaults that Paperclip runs depend on: fork subagents are on by
default in `-p` and the Agent SDK (2.1.302), sessions with no permission
mode start in `default` mode on third-party providers (2.1.302), and MCP
allow rules match whole server names (2.1.299). This needs a separate runner
qualification together with the patched `claude-agent-acp` bridge. Until then,
Haiku 5.5 on the CLI lane needs a 2.1.293+ CLI. Once #16708 records that
minimum, sandbox runs on an older image prepare a private CLI at the model
minimum before launch.
- **OpenCode 1.19.x and 2.x.** OpenCode 1.19.3 generates reasoning variants
from model options instead of catalog variants, which affects the variants
Paperclip Runner binds. OpenCode 2 changes the SDK, event, and plugin
contracts. Both need qualification.
- **ACP bridges.** ACPX 0.20.0, `claude-agent-acp` 0.94.0 (ACP SDK 2.0), and
`codex-acp` 2.2.2 (breaking tool-call contract in 2.0.0) need a
qualification campaign rather than a pin bump.
- **GitHub Copilot CLI 1.0.103.** The qualified Copilot profile binds
Copilot 1.0.88 by immutable identity; a new profile version needs its own
qualification. Copilot discovers models from the ACP session, so new Copilot
models need no catalog change.
- **Pi 1.4.0** and **Hermes 0.22.x** need runtime qualification; Hermes no
longer publishes to PyPI.
- **Gemini 4 Argon** in the Gemini CLI and Cursor catalogs: the CLI does not
register it yet, and Cursor documents display names only.
- **Codex default model.** Codex 0.161.0 makes `gpt-6.1-sol` its default.
Paperclip keeps `gpt-5.6-sol` so saved agents and spending do not change.
- **Hidden Codex aliases** (`gpt-daybreak-*`) are restricted to eligible
accounts.
- **Claude Sonnet 4.5** is deprecated and retires November 30, 2026. It stays
in the picker until then.
- **Claude Mythos 5.1** remains restricted to verified organizations.
## Host-environment baseline failures
Recorded once for this audit on the unchanged base (`c5ca29d`), Node 25.9.0:
- `server/src/__tests__/agent-hire-ai-connections.test.ts` fails at import
with `AI_InvalidArgumentError: baseURL must be a non-empty string.` because
the host injects an empty AI provider URL. Unrelated to this change.
+22 -3
View File
@@ -169,6 +169,19 @@ permissions. Ordinary discussion does not change a review score. Repeat review
mentions and pushes continue the existing task; inline replies return to the
task owning that thread.
A successful native execution can still be resolving its visible response.
Without a confirmed reply for that run, maintenance waits for its committed
presentation decision before choosing a completion fallback. It then uses the same saved request to settle the wait,
publish a genuine missing-response notice, or report a failed turn.
A queued or running follow-up acknowledgement preserves an existing App-owned
final PR summary. A new validated assessment can replace it through the review
publication path. When an authorized native turn commits a passive response
wait with no new comment, maintenance settles that request's acknowledgement
without replacing the assessment with a generic completion notice. This does
not count the old summary as a reply from the new run. Missing or failed
responses still receive their normal fallback; uncertain writes remain held.
Event prompts supplement the agent's instructions. Repository content and PR
prose are untrusted input and cannot change tool authority or publication policy.
The execution records the configuration revision and event context used.
@@ -249,9 +262,15 @@ the receipt.
Receipt recovery compares the complete saved publication request, including long
text and nested coverage entries. Shortened audit previews do not establish
request identity. Changed content or a missing durable publication returns a
conflict without dispatching another write. Exact retries read the current
receipt; the durable worker owns pending publication retries.
request identity. Changed content or a missing completed durable publication
returns a conflict without dispatching another write. Exact retries read the
current receipt; the durable worker owns pending publication retries.
A timeout during metadata or file reads can occur before publication staging.
The same request can repeat this preflight with its complete request identity.
The saved assessment, unique publication key, and provider lease still prevent
repeat external writes. `begin_review` retries return the run's current review
result. They do not return a shortened audit preview.
For a call that required human approval, the durable publication keeps that
verified approval for its exact operation. An exact caller retry only reads the
+30
View File
@@ -329,6 +329,36 @@ another recipient is named. The routing rule does not change automatic issue or
event policies. Archived bots and identities from other companies or providers
are excluded from the routing lookup.
## Retrying a saved request
A normal task Retry can continue a newer saved GitHub message after an earlier
attempt failed. Execution revalidates the exact admitted successor, its current
linked principal and repository access, and the durable continuation receipt;
it does not repeat the admission that already consumed the recovery hold.
A failed native predecessor still requires its committed failed result and
exact executor termination proof. Successful results and uncertain delivery do
not grant a replay. A certified failed-chat Retry retains the exact accepted
message identity when its predecessor stopped before identity initialization,
so a published review can expose its authorized passive response wait.
If an inherited task-resume attempt already recorded a result, ordinary Retry
explains that exact replay is unavailable and directs the user to send a new
message to continue from saved work. That new turn still passes normal current
requester, access and executor-containment checks.
If that successor failed at Retry authorization before runtime or provider
startup, the next normal Retry follows its canonical source receipt. The exact
system diagnostic, settlement events, empty execution evidence and absence of
allocated resources establish that narrow recovery path. A generic setup
failure or a claimed `providerWorkStarted: false` does not establish it.
The canonical task Retry also recognizes an isolated-directory binding failure
at the workspace preparation boundary before allocation. Its structured reason
and task binding, trusted failed settlement, dispatch-only profile and absence
of execution resources must all agree. Other workspace validation failures do
not inherit this permission. Current request authorization still runs at both
admission and execution; a failed unadmitted Retry intent does not replace the
saved request or prevent a later deliberate Retry.
## Run projection
The resolved token is leased at run start as an audited class-3 secret and is
+12
View File
@@ -1,5 +1,11 @@
# Paperclip evaluation guide
The explicit-only [chat feature evals](../tests/runner-e2e/CHAT-FEATURES.md) promote
two natural-language task scenarios into local native Product E2E cells. They
verify saving an unstarted task and delegating a saved announcement back to chat,
using ordinary production instructions, real browser messages and independent
state/provenance checks. The broader YAML catalog remains planning inventory.
The explicit-only [Daytona restart continuity journey](../tests/runner-e2e/README.md)
extends the existing native restart oracle to a 125-second controller outage,
using the recorded Claude and Codex models in disposable development fixtures.
@@ -84,6 +90,12 @@ behavior.
grading oracle. See [`tests/runner-e2e`](../tests/runner-e2e/README.md) and
[Everyday Workflows](../tests/runner-e2e/EVERYDAY-WORKFLOWS.md).
The [chat scenario catalog](../tests/runner-e2e/chat-scenarios/README.md) is a
planning inventory within Product E2E: natural user requests, assumed context and
expected outcomes linked to the feature and agent-access maps. It includes
conditional setup, permission, approval and recovery journeys. Its YAML files
are not registered runnable cells and contribute no passing coverage or scores.
Runner Evals answer whether a real runner/provider can perform a bounded
protocol operation against the expected control-plane contract. Product E2E
Evals answer whether a person can complete a product workflow through the real
+52
View File
@@ -160,3 +160,55 @@ these company-scoped records when their company is deleted. Run-scoped adapters
Native warm sessions retain their token-free launchers and inactive broker until
session retirement; environment deletion and orderly controller shutdown close
idle owners first. Cleanup failures are logged and do not change the run result.
## Project authorization for background repository work
Background provisioning and workspace maintenance have no responsible task user.
They must not retain a task's identity. A signed-in project workspace writer can
select their own active, company-installed GitHub Connector grant in project
settings and explicitly authorize the project. The binding stores the exact grant
ID and consenting user, never a credential. Revocation records a project lifecycle
event so subscribed providers can reconcile the change.
`GET /api/projects/:id/git-authorization` returns the current binding and only the
viewer's eligible personal grants. `PUT` accepts `{ grantId }` or `{ grantId: null }`.
Agents cannot create this standing consent. Project workspace writers can remove it.
Core rechecks membership, Connector installation/enablement, grant status, and
repository metadata on each background use. Public repositories never require
a connection or credential. Private repositories wait for authorization before
provisioning starts, so missing consent cannot leave a failed anonymous clone.
Repository selections retain the same visibility metadata used by the UI lock.
Legacy workspaces use existing Connector catalog metadata, with anonymous
GitHub discovery only when visibility is unknown. Unknown visibility defers
provisioning; it is never assumed public. It never substitutes another grant
when the selected one fails. Replacing a grant requires explicit reauthorization.
Project consent follows the selected connection's current GitHub repository access,
including repositories added to the project later. It does not create a second
repository approval list. Project repository editors may add sources within that
connection's access; manage permitted repositories in the GitHub connection.
Background export also rechecks the consenting user's project read access and the
project's existing trust policy. Low-trust or unverified projects cannot export a
raw credential through standing consent.
Cloud owner access is rechecked through current Cloud authority and the managed
owner-elevation setting on every private background export; saved local admin
roles cannot replace that authority. An unavailable authority check cannot confer
owner access, though explicit project membership still applies.
The trusted plugin capability `projects.git-credentials` enables
`ctx.projects.resolveGitCredential(projectId, workspaceId, companyId)`. The host
binds requests to the active project lifecycle or workspace operation; data, UI,
tool, and proactive calls do not carry this authority. Repository URLs come from
stored project workspaces. Foreground preparation uses the live run's accepted
identity and standard trust checks, even when background project consent exists.
Maintenance ignores originating run/agent context and uses project consent only.
After archival, existing consent remains usable only for host-issued workspace
inspection and removal. New provisioning and new consent remain blocked.
The provider receives a transient GitHub token with its existing provider
permissions. This is not a repository-scoped or read-only token minting API.
Only grant-listed repositories can trigger background export. Plugins must never
save tokens in entities, state, configuration, operation receipts, or logs, and
must send them only to trusted execution infrastructure over HTTPS. Revocation
prevents subsequent credential acquisition; it cannot recall a token already
sent to an in-flight operation. Existing tasks and Git credential fallback rules
outside this plugin API are unchanged.
+146 -5
View File
@@ -521,13 +521,25 @@ of the invalid call. Unauthorized tools still receive a generic rejection, and
corrected calls retain the same permission and approval checks.
A native provider may omit `continuation` (or send `null`) when it reports
`yielded` after saving a monitor or requesting repository preparation. The controller reads current authorized task
`yielded` after saving a monitor, requesting repository preparation, or publishing
an authorized current-head GitHub review. The controller reads current authorized task
context and fills the canonical continuation only if that same task,
run, assignee, and work mode remain eligible. An eligible monitor takes precedence.
A pending repository requested by that task in its current workspace offers
`same_agent`; the existing status arbiter and wake queue own the next admission.
Prepared repositories and requests belonging to another task cannot offer it.
An explicit `done` result does not acquire a continuation. Completion admission
A completed GitHub review with its processed publication may offer `response_wake`
for that exact head and accepted requester under current conversation and
connection authority. A normal tree resume may inherit the published review
through its accepted parent identity. An ordinary GitHub follow-up may inherit it
only after this run has a processed useful reply bound to its exact current
inbound comment; acknowledgements, pending or ambiguous writes and partial
assessment receipts do not suffice. Completion admission, finalization and
status commit recheck the server-issued run/review/head binding; a pending
publication, newer unreviewed head or revoked access cannot fall through to an
immediate continuation. An explicit malformed continuation remains invalid.
An explicit `done` result does not acquire a continuation or change its completion
policy; review scores are not interpreted as task-completion instructions. Completion admission
checks that persisted monitor again. This default does not create or renew a
schedule. A consumed, cleared, exhausted, or ineligible monitor cannot authorize
a passive wait. An explicit `response_wake` still identifies a real response
@@ -749,7 +761,7 @@ The handshake failure code is distinct from a session-identity mismatch. A timeo
An explicit recovery action is a typed liveness repair path for a source issue. It is the recovery primitive; the action can be rendered directly on the source issue or backed by a separate recovery issue when the repair needs its own work item.
A terminal native failure can retain a result accepted before checkpoint or cleanup failed. That result is historical evidence, not a live controller. New user input may start a fresh turn after the controller and execution environment have stopped and ordinary admission checks pass. Preserve the failed run, its result, and its recovery budget. Do not commit the old result, infer action outcomes, or replay the failed turn. A message saved while cleanup is pending must be reconsidered after verified cleanup and delivered once. Admission must consume its deferred receipt in the same transaction that creates the new run, including in agent chat, where later messages keep their separate turns. Completing that run must not promote the consumed receipt again. Workspace-export repair retains its separate saved-result recovery path.
A terminal native failure can retain a result accepted before checkpoint or cleanup failed. That result is historical evidence, not a live controller. New user input may start a fresh turn after the controller and execution environment have stopped and ordinary admission checks pass. Preserve the failed run, its result, and its recovery budget. Do not commit the old result, infer action outcomes, or replay the failed turn. A message saved while cleanup is pending must be reconsidered after verified cleanup and delivered once. External chat messages retain their original inbound action, wake receipt and actor. Cleanup delegates reconsideration to the live inbound owner, which revalidates the endpoint, conversation generation, principal and exact saved source before normal admission. The existing stranded-queue sweep uses the same owner after a lost callback or restart; it cannot substitute a generic assignment wake. A rejected source must not prevent other saved messages from being reconsidered. Admission must consume its deferred receipt in the same transaction that creates the new run, including in agent chat, where later messages keep their separate turns. Completing that run must not promote the consumed receipt again. Workspace-export repair retains its separate saved-result recovery path.
When a legacy turn admitted by an explicit user message fails or times out, a bounded transient retry needs its own durable continuation authorization. Initial admission binds the message's exact body digest and revision. Scheduling requires that original binding and revalidates the human author, source task, assignee, and execution ownership, then records the successor's receipt in the same transaction as its run. Historical receipts without a message binding cannot authorize automatic retries and are not backfilled. The parent receipt remains intact. Dispatch checks the exact successor, retry parent, and unchanged message binding again. Deleted or edited input, changed actors or ownership, superseded work, and duplicate successors cannot renew authority. One-run Retry and Interrupt intents retain their separate admission contracts; they are not renewable user-message authority. Other retry policies cannot borrow this receipt: their scheduling fails closed. Successful explicit turns do not create a prose-only missing-comment follow-up with spent authority.
@@ -757,7 +769,7 @@ Explicit retry admission checks the local parent adapter controller and verified
A new user message can continue a terminal native run whose process fields were cleared before local stop receipts existed. Admission must verify the exact run, runner, workspace, and provider session in the retained suspended state, with no active provider turn, pending tool call, or undelivered output. Missing or mismatched state keeps the hold. A later recorded process launch also keeps the hold until its stop is verified. Normal assignment, decision, controller, environment cleanup, and active-run gates still apply. The message starts one fresh conversation turn; it does not replay the failed run, reset its recovery budget, or certify unknown action outcomes.
The task thread exposes the guarded Retry action for failed or timed-out conversation runs and native preparation cancelled before provider startup when the never-started proof is verified. The server projects this eligibility on the recovery notice and rechecks it on Retry. Cleanup quarantine retains its inspection path, and non-conversation reconciliation gates remain enforced. Pending decisions, active execution, pause, budget, dependency, and ownership gates remain in force. A refused Retry reports its reason inline and remains available for another attempt.
The task thread exposes the guarded Retry action for failed or timed-out conversation runs and native preparation cancelled before provider startup when the never-started proof is verified. The server projects this eligibility on the recovery notice and rechecks it on Retry. Cleanup quarantine retains its inspection path, and non-conversation reconciliation gates remain enforced. Pending decisions, active execution, pause, budget, dependency, and ownership gates remain in force. A refused Retry reports its reason inline and remains available for another attempt. When a newer linked-human GitHub message was saved but its admission was skipped by a budget or agent-availability gate, ordinary task Retry selects that unstarted message before considering the older failed run. The existing chat task-Retry owner snapshots the complete pending batch, including eligible skipped input, into a new admission generation bound to the canonical processed deliveries, comments, principal, session generation, admitted instruction snapshots, and task Retry intent. It retains the original skipped receipt and failed result unchanged. A terminal failed publication of that old result also remains history for a distinct selected request; pending or uncertain publication still holds work, and the old output is never replayed. Board Retry refusals expose only stable allowlisted authority categories, never source payloads, identifiers, or credential fingerprints. Admission rechecks source integrity and current access, then uses the normal new-user-turn continuation proof: a committed failed result can remain history only after controller, successor, process, workspace, and exact remote-termination guards pass. Unknown ownership stays deferred; Retry cannot certify it. The existing chat retry queue owns delivery and bounded infrastructure retries; a committed receipt settles a lost acknowledgment without another execution. An accepted saved-input receipt discharges only its matching unadmitted-input gate, allowing later genuine conversation or tree-resume wakes without replaying the skipped request.
A continuation cancelled by the queued-run gate while waiting for review did not start a provider. Its matching dispatch-gate receipt and unclaimed execution fields keep this deliberate wait out of unknown-action reconciliation. Pending review and decision gates still apply. If an older server already created a recovery hold for this exact state, Retry or a new user message can request one fresh turn after the server verifies there is no provider, coordinator, or unfinished cleanup. Saved user input is reconsidered through the same admission path; the cancelled turn is not replayed.
@@ -838,6 +850,7 @@ A healthy `in_review` issue has at least one valid action path:
- a human owner via `assigneeUserId`
- an active run or queued wake that is expected to process the review state
- an active one-shot monitor for an external service or async review loop that the assignee owns
- an authorized GitHub conversation waiting for its next provider event after a published review; a tree resume or same-agent continuation retains this path only through its accepted requester lineage and the latest saved review publication
- an open explicit recovery action for an ambiguous review handoff
Agent-assigned `in_review` with no typed participant is only healthy when one of the other paths exists. Assignment to the same agent that produced the handoff is not, by itself, a review path.
@@ -1245,6 +1258,22 @@ apply. Stream closure without a turn terminal is not proof of success. Event
replay uses the existing source receipts and never repeats provider work merely
to recover recorded output.
Native execution success can precede its durable presentation decision. GitHub
response maintenance without a confirmed current-run reply holds that request
until the native phase is committed and a valid presentation decision exists.
A confirmed current-run receipt can retire its placeholder. The same maintenance owner
then rechecks the settled outcome; elapsed time cannot turn undecided output
into a generic failure notice. Failed execution retains normal error fallback.
GitHub main-PR response maintenance honors a committed native passive response wait
whose server presentation decision intentionally selects no comment. It settles
the current source's acknowledgement without a provider write or a fabricated
current-run reply receipt. Queued/running acknowledgements preserve an App-owned
final shared PR summary; a new canonical assessment may replace it. A generic
completion fallback must not overwrite that summary after an intentional wait.
Failure, genuinely missing response, and uncertain-publication handling retain
their existing independent checks.
If runnerd synthesizes a result when the provider stops, it publishes that result
before the provider-turn terminal and publishes the run terminal last. The
adapter can therefore retain the result while the matching turn still has
@@ -1293,6 +1322,13 @@ future execution until Resume, and missing stop proof still blocks continuation.
A permanently unusable native runner session may be replaced only with evidence that its predecessor is stopped and fenced, completed results and workspace state are preserved, required task history is available, and pending effects have been reconciled. A provider-native shell command or external write without a reliable outcome receipt is unknown. Unknown effects, integrity failures, and unverified process ownership never authorize speculative replay. Once automatic recovery is ruled out, Paperclip selects a conservative default: preserve recorded work, stop the affected task, and retain a durable no-replay hold. Unknown action outcomes remain unknown. No reconciliation form or user diagnosis is required.
An ACPX sidecar transport failure carries its redacted cause and code in the
terminal event's structured `error` field. The session facade must retain that
cause instead of reporting a failed turn with `error: null`. A transport failure
does not prove that the provider stopped or that a retry is safe; it remains
non-recoverable until the existing ownership and recovery checks establish the
next permitted action.
Local Codex crash replacement can use a complete interrupted-turn inventory,
authenticated process-stop evidence, and unchanged retained-state fingerprints.
Only text and an exactly receipted task-completion call qualify for this path;
@@ -1302,6 +1338,14 @@ recording the proof and successor lineage. Retained provider files are not edite
Bootstrap retries, exact-checkpoint resumes, and fresh replacement sessions share three total provider attempts, including the original attempt. Linked run IDs, controller restarts, and duplicate wakes do not reset this budget. Automatic attempts retain the 30-second delay. Replacement scheduling and predecessor lineage commit together, with one successor per predecessor and admission through the normal task locks, authorization, pause, approval, and budget gates.
When a same-run retry acquires a replacement plugin task lease, the executor
reloads the prior task's durable Runner checkpoint before checking local
lifecycle evidence. This includes retries after a provider turn omitted its
completion result. The existing lease-transfer policy must verify the company,
agent, workspace, retained session, and termination of prior execution. The
checkpoint must match the exact Runner, lease, run, session, turn, and item.
A missing restart claim does not remove these checks or authorize a fresh session.
A prepared remote workspace interrupted before the executor's first durable
claim may resume its untouched bootstrap on the same run. This requires attempt
and controller generation zero, no prior owner, and no process, provider session,
@@ -1315,6 +1359,13 @@ fresh native run identities. Unmarked preparations from older servers remain
held during rolling upgrades, because those servers cannot safely yield to a
recovery owner. Revisiting an existing preparation cannot add that marker.
Restart recovery checks the heartbeat process's live execution registry before
claiming an observed run. Native input can exist before workspace synchronization
has saved its descriptor or the executor has claimed its lease. A live preparation
keeps ownership throughout that interval. Recovery leaves its coordinator unchanged
and does not dispatch a second executor. An inactive run still requires the normal
ownership, workspace integrity, and provider evidence checks.
A preparation that resumes after another execution acquired the coordinator
lease yields through the controller-detachment path. It does not fail the shared
run, release its environment, or start another provider. Lease expiry alone does
@@ -1343,6 +1394,14 @@ ordinary Retry can continue. Finalized workspaces, mismatched sources and
accepted results keep their existing settlement paths. Reassignment does not
discard the stopped run's files or grant authority over the new assignee.
For older failed native runs that lack this bookkeeping, a deliberate Retry
registers preservation from the exact prepared workspace descriptor and assigns
the existing bounded maintenance owner. A live finalization owner or mismatched
source cannot be adopted. Registration does not prove termination or authorize
replay: the provider stop receipt, saved-file receipt, current execution authority
and effect fences still control successor admission. Repeated clicks retain the
same recovery generation and request.
Every continuation carries the triggering request, ordered user direction, interaction outcomes, completed work, and explicit history coverage. A delivered message remains part of the task's request after its connection or approval resolves. The original title is background; a completed Notion read does not satisfy a later Gmail request. Author and source-trust boundaries survive rendering into both native and legacy prompts. Missing required history must be fetched before dispatch rather than described as complete.
### Interrupted conversation continuation
@@ -1428,7 +1487,7 @@ Real gates still apply: company and task ownership, active provider ownership, b
A source that already stopped and was released remains fenced until its export settles; restart reconciliation scans these released sources too. Both provider reuse and destruction check the physical allocation for a shutdown fence or file-repair pin, including historical lease rows.
An operator Stop waits for provider termination. Remote sandbox providers may return a stopped/deleted receipt after their control-plane operation completes. Paperclip binds that receipt to the company, run, and exact lease; successful file cleanup, a terminal run row, or an in-sandbox shutdown event is not sufficient. Legacy conversational runs receive their cancellation acknowledgement after all remote leases have confirmed termination. Stop alone never creates a continuation. A user message queued during remote cleanup is reconsidered when the provider confirms termination; it still passes normal admission and adopts pending comment IDs in order. Once stopped, the next explicit wake uses the same queue. A compatible saved ACP session can resume, and an unavailable or incompatible session can start fresh with the full task context. Run credentials and scratch paths remain scoped to the new run. A subtree pause requires Resume; a message does not bypass it.
An operator Stop waits for provider termination. Remote sandbox providers may return a stopped/deleted receipt after their control-plane operation completes. Paperclip binds that receipt to the company, run, and exact lease; successful file cleanup, a terminal run row, or an in-sandbox shutdown event is not sufficient. Legacy conversational runs and native runs with an audited run-only Stop receive their shared cancellation acknowledgement after all remote leases have confirmed termination. A native interrupt acknowledgement alone does not establish containment. Workspace preservation remains a separate obligation and its recovery hold survives this acknowledgement. Stop alone never creates a continuation. A user message queued during remote cleanup is reconsidered when the provider confirms termination; it still passes normal admission and adopts pending comment IDs in order. Once stopped, the next explicit wake uses the same queue. A compatible saved ACP session can resume, and an unavailable or incompatible session can start fresh with the full task context. Run credentials and scratch paths remain scoped to the new run. A subtree pause requires Resume; a message does not bypass it.
Cancelled runs and runs with a recorded pending stop lose run-scoped API write authority, while reads remain available for diagnostics. This applies to ordinary tasks as well as conversations. Task and interaction mutations recheck that authority in the write transaction, so a cancelled run cannot overwrite a recovery disposition with a late Done or resolve an interaction after revocation. A task handoff that intentionally stops its own run can commit only with a server receipt tied to that exact request. Direct sandbox CLI adapters such as Grok register cancellation before preparation and keep ownership until host-owned termination is verified, including a sandbox acquired before adapter registration. A failed stop does not acknowledge cancellation or abandon an outstanding remote command. Interrupted workspace restore failures remain recorded for recovery; a stop receipt proves termination, not successful file restoration.
@@ -1464,6 +1523,13 @@ delta when attaching a new run. Other stale-event and authority checks remain.
### Explicit user continuation after execution failure
When a user's comment also assigns the task back to its agent, the assignment
wake retains that comment's continuation intent. Admission validates the saved
comment, its author, task, timing and delivery receipt through the same checks as
an ordinary comment wake. A bare assignment, agent/system input or mention wake
does not authorize continuation. Already deferred assignment-with-comment
receipts use this same path after recovery; they do not require another comment.
An execution recovery hold blocks automatic replay. A new authenticated user
comment or exact failed-run Retry can authorize a fresh native or legacy
conversation turn after the predecessor's
@@ -1651,6 +1717,23 @@ Delivery still requires the provider's verified stop receipt. Periodic queue
retries do not gain extra cleanup attempts, and the queue displays the server's
waiting reason while cleanup remains unresolved.
A connected task can also fail while preparing an accepted board-authored
message, before the provider starts. Its Retry belongs to the canonical task
intent rather than the external inbound-message ledger. The server certifies
its unchanged, undeleted comment, original user wake and accepted identity in
the same company, task, agent and user scope. A settled bootstrap diagnostic
must agree with the absence of a native result, coordinator, environment lease,
controller, process or provider output. A previous session display hint does
not establish that the failed attempt started a provider.
That intent pins the saved comment and accepted identity. Queue admission
rechecks the source; dispatch rechecks the coalesced intent and its exact claimed
successor receipt before inheriting the accepted identity. Current permissions,
assignment, pauses, budgets and containment remain normal queue requirements.
This path neither fabricates external inbound provenance nor replays a recorded
terminal result. If this source cannot be certified, Retry directs the user to
send a new task message to continue from saved work.
The legacy task recovery notice shows “Automatic recovery of this task stopped.” in
a bordered container with Retry for a failed or timed-out run. A failed Retry
shows its error in the same container. New user messages and saved undelivered
@@ -1824,6 +1907,24 @@ replacement. Missing or conflicting identity evidence, failed reads, and an
exhausted probe budget retain the existing ownership and recovery safeguards.
They must not launch a competing listener or overwrite the original marker.
Remote process verification uses one Node probe for liveness, command identity,
and the saved Linux boot identity and start ticks. If metadata disappears during
the probe, only a fresh `ESRCH` response confirms exit. A zombie also confirms
exit when its generation matches the saved marker. Permission errors, unreadable
metadata, and changed generations remain uncertain. Adopted-runner checks reject
that uncertainty rather than returning the same `false` value as a confirmed
exit. Launch checks that Node can run the probe before creating launch state or
detaching the process. These receipts do not release historical recovery holds
or prove that workspace files and provider state have been saved.
The transport propagates rejected adopted-process checks through close and
command waits. It must not turn a rejected check into a positive exit observation.
When a process check rejects close, the transport retires its local controller,
timers and notification queue without signalling the remote Runner or replacing
its checkpoint. Repeated close retains the same failed ownership result.
Copilot profile 62 binds this shared transport implementation. Profile 61 remains
decodable for recovery, but exact launch admission uses the current profile and
digest. Earlier live qualification results keep their original profile identity.
Healthy native warm turns retain their runner and provider processes. After a
controller crash, continuation can recover a completed remote session from its
saved checkpoint and exact sandbox process identity. The prior controller must
@@ -1902,6 +2003,16 @@ re-read dependency readiness, since new dependencies need not change the
displayed task status. Old blocked rows without a receipt remain held; no
historical status backfill is performed.
For legacy GitHub input without a saved App ID or its own response receipt,
Task Retry may prove the endpoint's earlier non-null App claim from a processed
response ledger created before that input. The proof stays within the same
company, endpoint, conversation and agent, with a processed prior delivery and
its inbound source link. Supported setup and reconnect writers preserve an
existing non-null App claim. This historical identity proof grants no publication
replay or access: the saved input and current principal, repository, conversation,
runtime fence and execution containment still pass normal admission. Explicit
conflicting App bindings remain denials.
### Queued input after a native Stop
A run-only Stop ends the current response. It does not discard queued user
@@ -2185,3 +2296,33 @@ use the same activity projection. Board-owned repairs stay actionable until a
verified native retry actually starts. Once an explicit board retry is running,
its live activity takes precedence over the prior owner and exhausted budget.
Resolved and cancelled actions remain resolved.
### Task directories after a fresh retry
A fresh repository-free retry receives its own private attempt directory. Once
that attempt succeeds, later ordinary input reuses the task's currently bound
directory, including an attempt directory, and preserves its saved files. The
binding is re-read before preparation. Only the exact company's task namespace
is eligible; closed or changed bindings, foreign paths, symlinks and missing
retained directories fail validation. A later explicitly fresh retry still
receives a separate clean sibling and does not copy or replay the old turn.
### Stopped execution workspace recovery instructions
A stopped run can retain a historical workspace repair instruction after machine
recovery has saved the files. Its execution projection uses the workspace
recovery state bound to that exact run for the next instruction, as the task
blocker does. Recovery in progress, a failed repair, and recovered files must
remain distinct. This read-only instruction does not release the replay hold,
change the stopped run, or authorize another provider turn. A recorded explicit
successor still takes precedence over the old recovery instruction.
A terminal native run can leave an older exact-session retry action behind when
workspace recovery takes ownership. The existing execution disposition worker
retires that action only after the exact run and coordinator are terminal, no
controller lease, result, successor or retry remains, and a separate source-bound
workspace hold records that uncertain actions cannot replay. The worker keeps
that hold and all saved work. It does not change the task or start a provider.
The same bounded reconciliation pass handles historical actions after restart.
+17 -9
View File
@@ -107,16 +107,16 @@ The grouped startup inventory remains unchanged. Existing company signals,
authority checks, expiry settlement, paging, backoff, and sleep gates remain
owned by their existing services.
The additive company-expiry index is migration `0380_tool_review_company_expiry`.
The additive company-expiry index is migration `0382_tool_review_company_expiry`.
It builds the index concurrently and idempotently through the existing top-level
migration executor. It was initially numbered 0402 to avoid existing allocations.
That passed per-branch numbering and schema checks, but CI correctly rejected
later PRs whose migrations then preceded their target branch's 0402. The fix
renumbers this unmerged index migration to 0380 and shifts the stack's former
0380 through 0401 migrations forward by one, preserving their SQL bytes. It
updates filename references, journal tags and indices, and generates snapshots
in the corrected dependency order. The moved journal timestamp is placed after
0379 and before the next migration; other timestamps remain unchanged.
migration executor. Initially reserving number 0402 passed per-branch checks but
caused CI to reject descendants whose migrations preceded their target branch.
A local 0380 correction fixed that ordering, but master had meanwhile added its
own 0378 and 0379 migrations. The integrated stack preserves master's history,
renumbers its unmerged migrations after 0379 in PR dependency order, and preserves
every migration's SQL bytes. Exact filename references and journal tags/indices
follow the new names. Stack journal timestamps remain ordered after master's
latest entry. Each generated snapshot includes both master and that PR's schema.
Each PR must pass the exact target-branch migration-order gate, in addition to
the existing numbering, safety, five-snapshot retention, and schema-drift checks.
@@ -145,3 +145,11 @@ Server typechecking passes. Combined-stack migration upgrades, full build, and
fresh remote checks remain required. Full local test:run is still unverified
because of embedded PostgreSQL startup/capacity limits; real gateway suites used
isolated, migrated test databases in the task-owned PostgreSQL instance.
A later review found an unbound `query` name in the SQL-capture assertion.
The due-row predicate short-circuited before that expression in the passing
fixture, and server typechecking excludes test sources. The assertion now
independently requires both the due expiry scan and the non-null deadline lookup
through each captured `read.query`. The earlier passing run did not detect this
name error; acceptance must include the service suite with both assertions.
+4
View File
@@ -137,5 +137,9 @@ the wiring is covered by tests.
the default path unchanged, and the V1 path gets its own tests.
- Pictures without known dimensions render at 4:3 until they load; the fitted print then
resizes once. The stack frame's height is fixed, so nothing below it moves.
- A picture whose file cannot be loaded (an attachment that returns 404, a file that is not
a picture after all) falls back to the icon sheet on the Artifacts page and to the document
icon in the panel and thread rows, from the element's own `error` event; nothing is
fetched to find out, and a front that moves on to another picture gets a fresh chance.
- Token count grows by about thirty `--artifact-*` entries; they are namespaced and
documented in the token block.
+14 -6
View File
@@ -23,7 +23,7 @@ bounded `read_file` operation for attachments and deliverables.
Core supports per-turn workspace sessions with Codex, OpenCode, and ACPX.
OpenCode and ACPX require the existing qualified provider profiles.
Workspace-free providers are not supported here. Codex warm retention is opt-in through `warmTaskVersion: 1`; ACPX and OpenCode remain per-turn.
Workspace-free providers are not supported here. Drivers opt into warm retention through `warmTaskVersion: 1`. Core prefers warm execution for new task runs on capable drivers, including ACPX; existing provider admission still determines which harnesses the driver supports.
The plugin owns project workspace preparation. Core does not prepare or reuse
a Core Git worktree for a task-only environment.
Selecting a plain task directory does not add redundant default configuration.
@@ -164,13 +164,20 @@ The existing agent-independent `inspect` and `remove` operations continue to
protect storage maintenance. Providers that do not declare finalization version 1
retain the inspection-based completion path. No stored binding migration is required.
## Codex warm task retention
## Warm task retention
A driver declares `warmTaskVersion: 1`, implements `onEnvironmentResumeLease`,
and returns `warmTaskVersion: 1` from `describe` only when its execution host
supports authorized run attachment. Select the agent's warm lifecycle or set
`runnerLifecycleMode: "warm"` and `runnerIdleTimeoutMs` on its plugin environment.
Core requires an explicitly selected account. Setup probes remain ephemeral.
supports authorized run attachment. Newly hired agents targeting such a driver
are configured for warm execution. Existing agents keep their explicit policy;
plugin runs without an explicit policy prefer warm execution. There is no
provider-specific warm gate or additional setting. Existing runs retain their
admitted lifecycle policy during restart recovery. The existing
`runnerIdleTimeoutMs` controls bounded retention. Fresh warm admission requires
a Core-managed credential identity before lease acquisition. Plugin-owned installed
accounts continue per-turn until such an identity is available; the saved warm
preference does not bypass account ownership checks. Drivers without warm
capability and setup probes remain ephemeral.
Plugin task execution does not create a Core-managed GitHub broker. Warm reuse
and restart recovery use the same broker-ownership rule as initial startup.
@@ -208,4 +215,5 @@ Changes to account, credential generation, workspace, runtime or process policy
retire the old owner before recovery. A new authority epoch archives the stopped
checkpoint under its stable archive key and preserves provider session files.
Warm status monitoring relies on PRP after startup and does not poll an idle
Launcher. General ACPX warm support is deliberately excluded.
Launcher. ACPX uses this task-provider contract; other execution transports retain
their provider-specific lifecycle policies.
+4
View File
@@ -373,6 +373,10 @@ export interface PaperclipPluginManifestV1 {
exportName: string;
/** For detailTab: which entity types this tab appears on */
entityTypes?: Array<"project" | "issue" | "agent" | "goal" | "run">;
/** Optional agent detail tab mirrored beside a running task.
* Declared board GET route scoped to agent :entityId returns { available: boolean }.
*/
taskSidePanel?: { availabilityPath: string };
/** For page and companySettingsPage: single route segment */
routePath?: string;
}>;
+6
View File
@@ -28,6 +28,12 @@ comment receipt, then checks current sender, repository, conversation and task
access. The retry records the current runtime generation and credential-reference
fingerprint. Another reconnect invalidates that admission. Historical deliveries,
stale webhook callbacks and the exact-run retry contract retain their fences.
Legacy input that predates saved App IDs can also use an earlier processed
response ledger from the same company, endpoint, conversation and agent. Its
server-owned App binding must predate that input and retain a processed delivery
and inbound source link. The endpoint's non-null App claim cannot be replaced;
this proves historical identity without replaying the earlier response. Missing
proof or an explicit conflicting App binding still rejects Retry.
Task Retry keeps the complete saved-input batch, including batches larger than
the exact-run endpoint's limit. Source rows, receipts and invalidations are read
+14
View File
@@ -16,6 +16,20 @@ Each recovery case includes another healthy turn after the recovered turn and
asserts that it does not start another runner or provider process.
It does not qualify a live model or a sandbox provider API.
Per-turn plugin continuation uses a stopped checkpoint on a replacement lease.
The executor tests cover Claude and Codex, including reopening blocked work.
The lease-authority integration test uses PostgreSQL to check that checkpoint
discovery cannot launch work or bypass a termination receipt. A stale negative
availability flag requires a fresh provider status before the checkpoint can
be read for continuation.
The executor can restore one quarantined journal in the same session scope.
It requires a terminal prior run, completed commands, a terminal event, and an
identity-matched suspended plugin checkpoint with no pending delivery or cleanup.
Multiple candidates, contradictory direct state, and unfinished work still fail
closed. Recovery preserves the journal and the provider's existing state owner.
Do not delete a quarantine or change database ownership to force continuation.
Use a disposable Linux container with Node.js, `sh`, `tar`, `base64`, `ps`, and
`setsid`. Build `paperclip-runnerd` and `fake-codex-app-server` from the checkout's
`packages/paperclip-runner/runner/Cargo.toml` for that container's architecture.
+7 -7
View File
@@ -65,9 +65,9 @@ ENV PATH=${PAPERCLIP_RUNNER_PROVIDER_PACK_ROOT}/node_modules/.bin:/usr/local/sha
# Never add a second CLI version to work around a runner compatibility pin.
RUN npm uninstall -g @anthropic-ai/claude-code @openai/codex opencode-ai \
&& npm install -g \
@xai-official/grok@1.0.46 \
@google/gemini-cli@0.62.0 \
@moonshot-ai/kimi-code@2.1.1 \
@xai-official/grok@1.0.70 \
@google/gemini-cli@0.65.0 \
@moonshot-ai/kimi-code@2.3.3 \
&& npm cache clean --force
# Hermes requires Python >=3.11,<3.14; the image's default Python is newer.
@@ -78,8 +78,8 @@ RUN /usr/bin/python3 -m venv /opt/hermes \
&& /opt/hermes/bin/pip install --no-cache-dir hermes-agent==0.19.0 \
&& ln -sf /opt/hermes/bin/hermes /usr/local/bin/hermes
ARG CURSOR_VERSION=2026.10.01-e373342
ARG CURSOR_SHA256_AMD64=a79726c6e644520e993970be4c45775a6889802b67abe461a677a53219ae28e8
ARG CURSOR_VERSION=2026.10.22-27dcf5f
ARG CURSOR_SHA256_AMD64=85296944e4600a83c4b764f578d1502bf9c416db200d33a593e8f3ecabfdc294
RUN set -eu; \
arch="$(dpkg --print-architecture)"; \
[ "$arch" = "amd64" ] || { echo "FATAL: cursor pin only covers amd64, not $arch" >&2; exit 1; }; \
@@ -93,8 +93,8 @@ RUN set -eu; \
ln -sf /usr/local/bin/cursor-agent /usr/local/bin/agent; \
chmod -R a+rX /opt/cursor
ARG GH_VERSION=2.102.0
ARG GH_SHA256_AMD64=bb766f710eef8ede859c18578c72c327597cd4c8a85b06001b1f3843c6019386
ARG GH_VERSION=2.103.3
ARG GH_SHA256_AMD64=4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d
RUN set -eu; \
arch="$(dpkg --print-architecture)"; \
[ "$arch" = "amd64" ] || { echo "FATAL: gh pin only covers amd64, not $arch" >&2; exit 1; }; \
+5 -5
View File
@@ -27,11 +27,11 @@ pack. Claude Code 2.1.280 is the minimum for
minimum for Sonnet 5.5; the pinned runtime also supports Fable 5.1. Codex
0.160.0 ships bundled metadata for the current
[GPT-6.1 Sol, GPT-6 Sol, and GPT-6 Luna model IDs](https://learn.chatgpt.com/docs/models).
The same refresh pins Grok CLI 1.0.46, Gemini CLI 0.62.0, Kimi Code 2.1.1,
Cursor CLI 2026.10.01-e373342, and GitHub CLI 2.102.0 in the sandbox layer.
The native Cursor provider uses its separately verified distribution, pinned to
2026.09.26-dd393fe; it does not use the sandbox layer’s global Cursor executable.
Grok CLI 1.0.46 supports the current
The sandbox layer pins Grok CLI 1.0.70, Gemini CLI 0.65.0, Kimi Code 2.3.3,
Cursor CLI 2026.10.22-27dcf5f, and GitHub CLI 2.103.3 (October 2026
refresh). The native Cursor provider uses its separately verified distribution,
pinned to 2026.09.26-dd393fe; it does not use the sandbox layer’s global Cursor
executable. Grok CLI 1.0.70 supports the current
[Grok 4.7](https://docs.x.ai/developers/grok-4-7) model family. Hermes stays
at 0.19.0, the newest release on PyPI.
+8
View File
@@ -7,6 +7,11 @@ The maps describe the same capabilities from two perspectives:
- [Agent access map](agent-access-map/README.md): the APIs and agent entry points
for those capabilities, their permission boundaries, and access verification.
The [chat scenario catalog](../tests/runner-e2e/chat-scenarios/README.md) 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
@@ -136,6 +141,9 @@ tool binding, CLI support, or work mode, update the affected companion and produ
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](../.agents/skills/maintain-verification-skill/SKILL.md)
owns reconciliation of both maps. It follows changed source and authorization,
+5
View File
@@ -4,6 +4,11 @@ This map accompanies the [feature map](../feature-map/README.md). It records API
agent entry points, permission boundaries and verification for the same capability IDs.
The [shared contract](../README.md) defines the format and maintenance rules.
The [chat scenario catalog](../../tests/runner-e2e/chat-scenarios/README.md) uses
these same IDs for human requests and expected outcomes. Its scenarios retain
the access boundaries here; neither a CEO role nor a planned scenario grants
board authority or establishes a working production tool binding.
Use full capability IDs when referring to access contracts outside their file:
`onboarding/company` means the `company` capability in `onboarding.md` in both maps.
The [feature index](../feature-map/README.md#browse-features) lists feature and
+6
View File
@@ -94,6 +94,12 @@ remaining operations before qualifying the whole capability.
Gaps: Agent handoff is implemented; execution readiness, assignment permission, and
repository access still apply.
Additional coverage: the explicit [chat feature evals](../../tests/runner-e2e/CHAT-FEATURES.md)
exercise native task creation and completion delivery through the real chat UI.
The [chat directive](../../server/src/services/agent-conversations.ts) tells agents
to use company-prefixed relative task links or platform-supplied absolute origins.
This adds no permission and does not qualify the whole capability or its denied cases.
## `conference-room`
Capability ID: `agent-chat/conference-room`.
+18 -3
View File
@@ -50,12 +50,23 @@ permission. Its creator can finish their own inactive setup with that permission
changing another person's setup requires configuration permission.
Creation retries reuse only records owned by the caller. Returning a completed
record also requires the normal agent-read and configuration-read checks.
An unfinished record stays paused with a
An unfinished record keeps compatibility status `paused` with a
`setup` hold and cannot receive API keys or authenticate with keys or JWTs.
Its standard grants apply at hire. Authorized completion retries recover the
same record and approval without changing the submitted configuration.
Normal agent-authored hiring keeps its existing approval policy.
An agent-owned plugin may prepare the draft and leave its lifecycle in
`verifying` while that setup hold remains. Only bounded Core-issued setup probes
can run there. The creator's company creation permission also covers configuring
and retrying their draft during preparation or stopping; other actors still require the
ordinary configuration permission. This is a board wizard path, not new agent
execution or probe authority. Lifecycle and component regressions cover these
transitions; no permitted-agent or live-provider journey is claimed here.
Companies requiring hire approval keep drafts paused and allocate no agent-owned
resource before approval. Selecting an account there is pending verification,
not approval or execution authority.
The creation boundary resolves the request-level runner before adapter validation
and credential normalization. Omitted/automatic new Codex selection uses the
qualified target's default; explicit Legacy is retained. Disabled adapters and
@@ -112,7 +123,7 @@ API: `present` — representative operation IDs:
receives `canManage: false`. Saving never creates a run or wakeup.
- `PUT /api/agents/{id}/instructions-bundle/file`.
- `PATCH /api/agents/{id}` with an explicit `runner: "paperclip"` upgrade.
- `POST /api/agents/{id}/qualify-runner` to qualify the saved effective sandbox before upgrading.
- `POST /api/agents/{id}/qualify-runner` to qualify the saved effective sandbox before upgrading or testing an existing native runner.
- `PATCH /api/agents/{id}` with `runtimeSettings: { harness, model?, aiConnection?, expected: { model, aiConnection } }` for a narrow roster edit. Each request handles one agent; the UI batches at most four writes and collects per-agent outcomes.
Agent access: `available` — Native read/update/history/restore instruction tools; REST /
@@ -138,7 +149,11 @@ authorization as saving the upgrade. The server resolves the saved computer;
`expectedEnvironmentId` rejects stale state and cannot select another computer.
Qualification checks company binding, returns only its receipt, and audits within
the agent's company. General instance environment probes still require instance
admin. No probe runs merely on page load. Operator browser evidence does not
admin. An existing native agent's clean configuration Test uses the same
saved-computer qualification before its runtime test. A current proof is reused;
a missing or stale proof requires a real successful probe and verified cleanup.
Draft settings and target changes do not qualify another computer. No probe runs
merely on page load. Operator browser evidence does not
qualify the agent permission paths for this operation.
Evidence: `source-only` — [implementation](../../server/src/routes/agents.ts#L1395) at
+38 -2
View File
@@ -115,8 +115,13 @@ GitHub publication recovery (2026-10-14): assigned-agent `submit_review`, `comme
and `update_comment` calls reuse their run-, task-, endpoint-, and argument-bound
publication on an exact retry. Identity uses the complete durable request rather
than the shortened audit preview. A changed suffix, changed nested entry, or
missing publication cannot authorize another write. Exact retries only read the
receipt; the worker owns pending provider retries. Fresh gateway policy and provider authority remain
missing completed publication cannot authorize another write. Exact retries read an
existing receipt; the worker owns pending provider retries. A request interrupted
during metadata or file reads before staging can repeat that preflight with the
same full request identity. The immutable assessment, unique publication and
provider lease still serialize its external write. `begin_review` exact retries
resolve the run's current review and return a typed result instead of an audit
preview. Fresh gateway policy and provider authority remain
required. The durable worker resumes transient failures after restart and stops
at its retry cap, revoked authority, or a superseded head. A pending receipt is
not task completion. Source:
@@ -134,6 +139,15 @@ follow normal access checks. Provider-fixture coverage is not live GitHub proof.
Native terminal reconciliation resolves the accepted run identity through the
existing chat provenance resolver; an older run's reply cannot complete a newer
request merely because both requests share the same PR comment.
A terminal native success does not authorize missing-response publication while
its native phase or durable presentation decision remains pending. Maintenance
rechecks the same request after authoritative settlement; failures keep their
separate fallback path.
Maintenance projects the bounded server-committed native passive-wait decision
only after current request ownership. It settles a no-comment acknowledgement
without authorizing a new send or counting an old shared receipt as a current-run
reply. Existing final App/marker-owned PR content survives progress acknowledgements;
new canonical review publication remains the writer for replacement assessments.
Speko browser sessions use `POST /api/companies/{companyId}/voice-sessions`,
with GET inspection/notification and POST `/{sessionId}/end` operations below
@@ -283,6 +297,20 @@ real human dependencies retain the ordinary attention-request path. A timed
wait requires a confirmed `set_task_monitor` schedule. Database coverage lives
in `external-chat-wait.integration.test.ts`; this is not live model evidence.
Inherited GitHub review waits (2026-10-26): an explicit native `response_wake`
after tree resume or same-agent continuation may retain the provider-event path
through accepted requester identity lineage and the latest processed review
publication for that task/conversation. This does not grant monitor management
or publication authority. Current task/agent/company binding, repository,
principal and endpoint checks remain effective. PostgreSQL regressions cover
quiet repeated finalization, historical publication reuse, newer unreviewed
heads and revoked access; live GitHub delivery remains separate acceptance.
Omitted/null yielded reports may use the current run's server-projected published
review wait. The same proof is rechecked at feedback, finalization and commit;
older/different-run review, pending publication and revoked connection cannot
supply it. This grants no new publication/monitor authority and leaves Done policy
unchanged; explicit malformed input is not coerced.
## `outbound-email`
Capability ID: `chat-channels/outbound-email`.
@@ -300,3 +328,11 @@ Evidence: `source-only` — reviewed at `9ef434fe79c57d976b8b03b14c5242db270b832
Verification: `not-run` — Use the actual permitted writer and run to create one child/publication, confirm recipient delivery and an exact-message reply, and repeat idempotent requests without duplicate sends. Assert run/owner/mode/budget/company/credential/attachment denials and separate read access. Inspect the provider before resolving an unknown write outcome; a 202 or queued publication alone is not proof of delivery.
Gaps: Real AgentMail transport, recipient delivery, and each native tool binding still need live proof. Controlled provider receipts and inbound-reply recipes do not establish a newly initiated external email journey.
Ordinary task Retry can select newer linked-human GitHub input whose original
admission was skipped by a budget or agent-availability gate. The chat owner
revalidates its exact processed delivery, company/task/agent/principal, unchanged
comment, session generation, and admitted instruction snapshot. A separate retry
receipt preserves the original skipped receipt and older failed native result.
Current access and normal native stop/cleanup guards still govern execution;
board wake metadata alone cannot manufacture chat authority or replay old work.
@@ -176,6 +176,15 @@ The task API does not transfer files or reveal guest filesystem paths.
This source update does not qualify live agent access, warm retention, or a provider.
See the [execution contract](../../doc/plugins/PLUGIN_RUNNER_EXECUTION.md).
Same-run checkpoint recovery also uses the saved lease path after a turn omits
its completion result. It requires verified prior termination, retained session
state, and matching company, agent, workspace, and complete Runner identity.
The [executor regression](../../server/src/services/native-runtime/native-session-executor.test.ts)
checks checkpoint retrieval and identity/termination denials. The
[lease authority fixture](../../server/src/__tests__/environment-task-authority.integration.test.ts)
checks the same-run read through the database-backed task API. These are
controlled regressions; live provider acceptance remains separate.
## `images`
Capability ID: `execution-environments/images`.
+22
View File
@@ -123,3 +123,25 @@ own policy and access review.
Gaps: Disable/remove and development reload are management workflows with no default
company agent access.
## Project Git authorization
Project workspace writers can use `PUT /api/projects/{id}/git-authorization` to
consent to their own eligible personal GitHub Connector grant. This route is
board-only; agent requests cannot establish standing consent. `GET` requires
project read access and returns no token. SDK `projects.resolveGitCredential`
requires `projects.git-credentials` and a matching host-issued project operation.
Background work uses the selected project grant. Foreground preparation uses the
active run identity and trust boundary. UI/data/tool invocations have no export
authority. No task identity is retained for maintenance.
Background export rechecks the consenting user's project read access and project
trust policy. Repository access follows the selected connection, including later
project additions; no separate project repository approval list is stored.
Archived projects allow only host-issued workspace inspection and removal using
existing consent; they cannot acquire credentials for provisioning.
Evidence: owned embedded-database grant/route fixtures in
`server/src/__tests__/project-git-authorization.test.ts`, worker invocation
fixtures in `server/src/__tests__/plugin-worker-manager.test.ts`, and capability
and scope denials in `packages/plugins/sdk/tests/host-client-factory.test.ts`.
These are automated fixture checks, not live provider qualification.
+44 -1
View File
@@ -8,12 +8,25 @@ Native finalization deadline reconciliation records unfinished workspace
preservation through the existing server-owned recovery path. It grants no
additional agent API, provider-stop authority or permission to replay work.
Remote process probes remain server-owned. Confirmed exit requires `ESRCH` or a
zombie with the saved generation. Unknown adopted-process ownership rejects the
probe and grants no permission to replace a runner, signal a different process,
or replay work. Launch requires a working Node probe before detachment.
Ordinary board Retry can reauthorize saved GitHub input for the same App after
reconnect. It pins current runtime authority and preserves sender, repository,
conversation and task checks. Pending input takes precedence over the older
failed request and transfers once to the retry owner. This grants no new agent
Retry API or stale webhook authority. Local PostgreSQL and HTTP-route regressions
Retry API or stale webhook authority. Legacy input can use a server-owned,
processed earlier response ledger to prove the same endpoint's App claim before
that input. Company, conversation, agent and prior delivery/source linkage remain
required. Explicit conflicting App IDs cannot use that fallback. Local PostgreSQL and HTTP-route regressions
cover these transitions; hosted execution and delivery remain separate acceptance.
Dispatch validates the exact claimed wake and resolved user-continuation receipt
for the current successor. A later board Retry can follow that successor only
when exact durable diagnostics and absent execution/resources prove it never
started. This preserves the original sender/source and grants no agent Retry
permission or accepted-result replay.
Source revision: `3bbc2104b65caf9f7763938a01260a5673e12f7a`.
@@ -243,6 +256,31 @@ replace the owner's generation or revision. Resolved files-only recovery retains
its no-replay restriction. The local PostgreSQL regression checks the producer,
worker, and physical source receipt; it is not deployed provider acceptance.
Connected board-message preparation failures use the canonical board Retry
owner only after the exact unchanged comment, original user wake, accepted
same-user identity and pre-provider settlement are certified. Admission and
execution recheck the pinned source and claimed successor receipts. Repeated
pre-provider failures retain the source only through each canonical intent,
failed dispatch and accepted parent identity; cycles and chains beyond twenty
links fail closed. This grants
no external inbound authority or permission to replay a terminal result; an
uncertifiable source directs the user to send a new task message. The real
HTTP/queue regression proves this boundary locally, not hosted provider recovery.
For external chat, the same canonical Retry owner may certify the structured
isolated-directory binding failure that occurs before environment allocation.
It requires exact task/source authority and trusted settlement with no process,
lease, native result or unknown execution evidence. Other validation reasons and
the older direct chat-retry entry point remain denied. Local HTTP/dispatch proof
does not establish hosted provider completion.
An authorized deliberate Retry also registers missing historical native
preservation from an exact prepared descriptor and an unowned terminal
finalization. It adopts only the existing bounded maintenance capability. A live
owner or mismatched allocation cannot supply this proof. No termination receipt
or execution authority is created by registration; connected Retry still waits
behind recovery and rechecks its existing external identity.
The internal preservation resume path grants no board or agent execution API.
It requires the exact source action, company, run, lease and environment, a
held physical workspace owner, and its current stop-only cleanup claim. The
@@ -453,6 +491,11 @@ Agent access: `partial` — eligible admitted agent/native bound wake receives s
Policy: Exact prior run/lease/workspace stop proof, no competing execution, current owner/responsible user, normal subtree/project pause/budget/review gates. Durable ordered message/wake receipts avoid duplicates; never borrow authority from stale callback/other routine. Unused hold-denied admission needs no-execution/dispatch evidence before automatic reconsideration.
A human-authored comment attached to an assignment wake can authorize the same
fresh continuation as an ordinary comment. The server validates the persisted
comment and its task/author/timing; the assignment label alone grants no
authority. Agents and system wakes cannot inherit this human-input path.
Evidence: `source-only` — [legacy gates](../../server/src/services/recovery/legacy-continuation.ts), [native ownership](../../server/src/services/native-runtime/native-restart-recovery.ts), [queued Stop](../../server/src/modules/wake-queue/adapters/postgres.ts); reviewed at `3bbc2104b65caf9f7763938a01260a5673e12f7a`. No live provider proof.
Verification: `not-run` — After confirmed cleanup one useful continuation consumes saved order; repeat sweep/reload no duplicate. Pause/budget/approval/unknown external outcome and reassignment prevent stale admission. Queued Stop leaves another routine cycle intact.
+6
View File
@@ -49,6 +49,12 @@ those APIs with their admitted run token. These paths do not require a project.
Policy: Company/project/workspace visibility and runtime authority; active run, trust
preset and task ownership where required.
Ordinary input may reuse the exact currently bound private task directory after
an explicitly fresh retry. Preparation rechecks company, source task, current
binding and canonical path; missing directories, symlinks and foreign roots are
rejected. This preserves files without granting new access or replaying the
previous turn. An explicitly fresh retry still creates a clean sibling.
Task workspace writes require `issue:mutate`, an active owned task/run for agents,
and current source visibility. Shared physical roots also require source-project
workspace write authority. Accepting a new pending choice advances its binding
+5
View File
@@ -9,6 +9,11 @@ The sibling [agent access map](../agent-access-map/README.md) records APIs,
agent entry points and permission boundaries for the same capability IDs.
Follow the [shared map contract](../README.md) when maintaining either map.
The [chat scenario catalog](../../tests/runner-e2e/chat-scenarios/README.md)
describes how people might request these capabilities in conversation, including
setup and permission branches. These are planned Product E2E journeys, not live
coverage results.
## IDs and references
Use the existing IDs in issues, PRs, Storybook annotations, tests, and verification
+7
View File
@@ -61,6 +61,13 @@ inaccessible saved conversation; verify no cross-user or cross-company history a
Automated: [chat project tools](../../server/src/__tests__/chat-project-tools.test.ts) checks tool contracts; live model choice and UI handoff require a manual run.
Explicit live evals: [chat feature journeys](../../tests/runner-e2e/CHAT-FEATURES.md)
send natural requests to save a backlog task or delegate an announcement. They
check project/assignee, execution or non-execution, saved output, return to chat,
and click the actual same-instance task link after reload. Registration alone
does not establish a pass. Production chat guidance uses company-prefixed relative
task links unless the platform supplied a verified absolute origin.
Manual: Ask the configured agent to create bounded project work, inspect the proposed/created target, and open the resulting task. Verify the request context and intended project survived and the task produces a useful output.
### `conference-room`
+26
View File
@@ -37,6 +37,14 @@ Save & exit keeps its configuration; Finish setup on the agent returns to the
same record. Final submission requests approval when required, then follows the
existing preparation and verification lifecycle.
Agent-owned plugin environments prepare the saved draft in the background when
their driver declares `requiresAgent`. The draft waits in `verifying` with its
setup hold until hiring finishes. Changing environments keeps the selected
account and Configure step, saves the selection, and invalidates its test.
Preparation and failed-save retries remain visible without reconnecting.
Companies requiring hire approval save the account with pending verification;
resource allocation waits for approval.
### `agent-configuration`
Open `/agents/:agentId` and the configuration/instruction surfaces it exposes.
@@ -87,6 +95,14 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use
Automated: [new agent page](../../ui/src/pages/NewAgent.test.tsx) and [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx) cover mocked UI behavior.
For an agent-owned plugin environment, verify preparation before connecting,
same-agent probes, account preservation after an environment change, failed
selection-save retry, and switching back while the computer stops. Confirm the
setup hold still blocks ordinary work and API key creation before finishing.
The [setup lifecycle tests](../../server/src/modules/agent-lifecycle/__tests__/setup.test.ts)
exercise durable transitions with synthetic plugin resources; they do not prove
live VM provisioning.
Manual: Hire an agent with a distinct name and role. Complete any required approval, reload the roster, and open its configuration. Confirm manager, adapter, and model persisted; run a small task to prove execution readiness.
For a new Codex hire, choose the Codex harness. Automatic selection uses Paperclip
@@ -169,6 +185,16 @@ the original agent, without showing success on the new page or redirecting back.
Focused coverage: [save receipt](../../ui/src/pages/AgentRunnerUpgrade.test.tsx)
and [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx).
For an existing native agent on a Daytona snapshot or immutable sandbox image,
use **Test** in its saved Harness or Runtime configuration after a managed
computer update. This action qualifies the saved computer under the existing
agent configuration permission before testing the runtime. A current proof must
remain unchanged. A missing proof requires a real successful probe and verified
cleanup. Failed qualification must stop the runtime test. Unsaved configuration
or a different computer must not qualify a draft target. A company owner must not
need instance-admin permission, and the generic environment probe must remain
restricted. Existing runs retain their recorded allocation and snapshot binding.
Storybook: [Runner upgrade](../../ui/storybook/stories/agents/codex-runner/upgrade.stories.tsx)
mounts the production page and shell with mutable HTTP fixtures for both harnesses,
pending, failure/retry, incompatible settings, repair, native/unsupported states,
+40 -1
View File
@@ -72,6 +72,17 @@ database suite checks these states and revoked endpoints using stored provider
receipts; live model adherence remains a separate check.
It also checks saved monitors, disabled repositories, multiple reviewed heads,
read-only finish validation, withdrawal rollback, and separate approval gates.
Repeat the review wait after a tree resume and a same-agent continuation with
no new provider message. Accepted requester lineage and the latest saved review
publication keep the task in review without a self-wake or duplicate publication.
A newer unreviewed head, changed requester/repository, or revoked access cannot
inherit the prior head's passive wait. Omitted/null yielded continuation is filled
from authorized server task context after a current-head review, an accepted tree
resume inheriting it, or a same-head follow-up with this run's processed useful
reply bound to its exact current source. Pending or ambiguous replies and
acknowledgements do not authorize this fallback. A malformed first report can recover by omitting the continuation;
explicit malformed input remains rejected. Revocation between context read,
finish and commit preserves the task without self-waking. Done policy is unchanged.
Manual: For each supported provider being changed, send a unique message, verify the intended agent/company receives it, and inspect the actual external reply in the original thread. Repeat with an unlinked/unauthorized sender, duplicate inbound delivery, and one supported attachment. Record provider-specific results separately.
@@ -129,6 +140,18 @@ contracts with synthetic providers; record a live journey separately.
For a long-lived task, repeat more than 100 continuations and check that tool
access remains available. Fail a later GitHub run after a final answer and
check that the earlier answer remains intact.
After publishing a PR assessment, deliver an ordinary no-new-work author reply.
Hold native presentation after execution succeeds. Verify maintenance makes no
provider write while undecided, including repeated passes and the explicit
fallback path. Commit either a passive wait, genuine missing response, or failure
and verify that the same request settles once with the corresponding behavior.
Verify the actual shared summary stays unchanged during queued/running
acknowledgements and after the committed passive wait, including maintenance,
restart and cleanup. Confirm the per-request acknowledgement is terminal and a
second maintenance pass makes no write. Then request a real same-head and
changed-head assessment and confirm canonical publication can replace it.
Real-PostgreSQL provider fixtures cover this producer and missing/error/unknown
write safety; record hosted destination acceptance separately.
### `endpoint-management`
@@ -163,7 +186,12 @@ write and verify one summary, finding, and App-scoped check. Retry the same tool
call and verify it returns the saved receipt. Include text longer than 500
characters and coverage with more than 50 entries. Change only the text suffix
or final coverage entry and verify rejection without another write. Remove the
durable publication and verify that a retry cannot dispatch a new write.
completed durable publication and verify that a retry cannot dispatch a new write.
Also interrupt metadata reads before publication staging, repeat the exact
`begin_review` and `submit_review` requests, and verify typed results and one
assessment publication. Let the original metadata read finish alongside its
retry and verify that both converge on the same publication. Changed requests
and revoked access must still stop preflight recovery.
Leave a transient failure queued,
restart the instance, and verify publication resumes at its saved deadline
without another inbound message. Revoked access and permanent rejections must
@@ -217,3 +245,14 @@ Sources: Source: [TaskChatBubble.tsx](../../ui/src/components/task-chat/TaskChat
### Documentation scope: Chat and email channel setup
Shared recipes name provider checks; each provider transport/thread/identity/file-size/type combination needs separate live evidence and deeper instructions.
Saved-input Retry regression: fail a disposable GitHub turn, change the
configured instruction skill, and send a new authorized request while an agent
budget gate blocks admission. Clear that gate and use the task thread's ordinary
**Retry** control. Verify the new saved message and its admitted skill snapshot
reach one run, rather than replaying the previous failed request. Preserve both
original receipts. With a committed failed native result, continuation requires
verified controller and environment cleanup; an unknown executor remains held.
After successful admission, reload and verify that the prior skipped receipt does
not strand a later real provider reply or tree resume. Provider fixtures support
this behavior; live fixed-source runtime and destination proof remain separate.
@@ -91,6 +91,12 @@ The [fake-provider integration](../../server/src/__tests__/plugin-runner-task.in
checks acquisition, SDK dispatch, scope denial, stop proof and deletion recovery.
Its WebSocket is mocked; it does not qualify a live provider or a real Runner handshake.
For a same-run retry on a replacement plugin task, verify that the retained
checkpoint loads before provider startup. The prior execution must have a stop
receipt, and the checkpoint must match the original session identity. Include a
turn that ends without a completion result; a successful initial turn alone does
not exercise this recovery path. Reject missing stop proof and changed identities.
Automated: [execution target](../../server/src/__tests__/environment-execution-target.test.ts) and [custom images](../../server/src/__tests__/environment-custom-images-service.test.ts) cover contracts; [SSH live test](../../server/src/__tests__/environment-live-ssh.test.ts) requires its own external setup.
The [environment runtime regression](../../server/src/__tests__/environment-runtime.test.ts)
+46 -2
View File
@@ -19,6 +19,9 @@ Agent access: [companion](../agent-access-map/recovery.md).
progress, and next action without requiring a raw-log interpretation.
- `bounded-continuation`: `recovery/bounded-continuation` — supported interrupted work continues with preserved
conversation context and bounded attempts, without blindly replaying tools.
Restart recovery respects live heartbeat preparation before workspace
synchronization finishes. PostgreSQL regressions cover unchanged ownership,
no duplicate dispatch, and later recovery after preparation leaves the registry.
- `source-action`: `recovery/source-action` — source-scoped recovery actions remain attached to the task;
independent repair work may have its own issue and return owner.
- `exhaustion`: `recovery/exhaustion` — an exhausted infrastructure attempt offers ordinary Retry.
@@ -35,10 +38,15 @@ Agent access: [companion](../agent-access-map/recovery.md).
hosted provider recovery remains separate acceptance.
Native finalization deadline failures also retain the exact prepared source
for the same stop-and-save workflow before Retry admits another executor.
Retry reconstructs missing preservation for historical failures only from an
exact prepared source without a live finalization owner.
- `unknown-outcome`: `recovery/unknown-outcome` — uncertain external side effects require inspection and
an explicit decision, not automatic replay.
- `user-continuation`: `recovery/user-continuation` — saved user messages after a stop are reconsidered once
cleanup proves the old execution is stopped; duplicate wakes are avoided.
A user comment that also reassigns the task retains this intent, including
existing deferred assignment receipts. The comment's identity and author,
current assignment, stop proof and normal execution gates remain required.
- `reconnect`: `recovery/reconnect` — browser stream recovery refreshes persisted state without claiming
the agent itself restarted or that a failed run succeeded.
@@ -77,6 +85,15 @@ stopped-run recovery checks.
### `operator-retry`
The [connected-task regression](../../server/src/__tests__/chat-channels.integration.test.ts)
uses HTTP Retry after an accepted board message fails before provider startup.
It checks the canonical intent, same-user identity and actual queue dispatch,
then repeats Retry after another contained preparation failure with the same
source and a new certified successor;
edited source, contradictory execution evidence and mismatched receipts refuse
or wait. This local boundary probe deliberately stops before a provider call,
so it does not establish hosted recovery of the task.
Use the task's Retry action. It can create an isolated attempt after old execution
is contained even when old-file preservation remains unresolved. Approval,
credentials, budget and deliberate pause use their existing specific controls.
@@ -98,6 +115,15 @@ there must be one successor and no duplicate publication. A second reconnect
after admission, changed App, revoked sender or changed repository must prevent
dispatch. An unadmitted rejection keeps the follow-up available for another
deliberate Retry. Historical deliveries must remain unchanged.
Repeat with legacy input that has no saved App ID and was refused by a budget
before acknowledgement. An earlier processed response from the same endpoint,
conversation and agent can prove its App claim. Missing, late, unlinked or
conflicting proof must reject Retry. Verify actual execution separately.
At dispatch, confirm the admitted successor retains the same source and resolved
continuation receipt. If it fails at Retry authorization before provider startup,
use the next ordinary Retry against that newest failed run. It must retain the
saved follow-up and create one successor; output, an allocated environment or an
active controller must prevent treating that failure as never started.
### `post-stop-message`
@@ -145,7 +171,7 @@ Use these checks alongside the entry-point recipes below and the operation recor
| Capability ID | Action and persisted result | Denial, race and retry checks |
| --- | --- | --- |
| `recovery/diagnosis` | Open the source task and exact run; compare cause, source action, original owner, recovery owner, attempt bounds and next action after reload. | Test an unrelated/private task and a stale run notice. Read-side retirement of a stale action must not create a new attempt, participant, or permission to replay. |
| `recovery/diagnosis` | Open the source task and exact run; compare cause, source action, original owner, recovery owner, attempt bounds and next action after reload. | Test an unrelated/private task and a stale run notice. Read-side retirement of a stale action must not create a new attempt, participant, or permission to replay. After workspace recovery, compare task and run instructions; recovered files must not leave instructions to repair a retained sandbox. The stopped run keeps its replay hold until continuation admission. An obsolete exact-session notice retires only after terminal coordinator proof and a separate exact-run workspace hold; no new execution or file cleanup follows. |
| `recovery/bounded-continuation` | Use a deterministic recoverable interruption and inspect the original run/session, attempt receipts, saved result and eventual useful output. | Repeat restart/receipt delivery, race Stop or a new owner, and retain unknown external outcomes. Accepted completion/finalization recovery must not start a new provider turn or repeat its side effect. |
| `recovery/source-action` | Inspect active and retained actions, follow the repair owner, and resolve one eligible source-bound action with its exact ID. | Retry the settled resolution and reject a stale/foreign action. Recovery ownership alone cannot mutate the source task; inspect source status, audit and wake independently. |
| `recovery/exhaustion` | Exhaust or age a bounded fixture; use the currently offered retry once, then inspect its durable acknowledgement and actual continuation. | Reassign, pause, stop, close, add an unresolved dependency, or impose a budget hold before retry. The old notice must not reopen terminal work or run the wrong owner. |
@@ -192,12 +218,26 @@ deadline. The cases also retain failed-welcome ticket fencing, identity checks,
and reconnect replay without repeated provider effects. These transport cases
do not establish hosted provider acceptance.
The [native provider regression](../../packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs)
sends malformed activity from a real ACPX sidecar process. It checks a structured
transport error, one failed terminal, a closed session, and no provider reopening.
It proves the error contract and retained failure boundary, not the cause of a
historical provider outage or successful hosted task recovery.
Active remote process supervision distinguishes a failed health read from a
confirmed exit. The [executor tests](../../server/src/services/native-runtime/native-session-executor.test.ts)
exercise timeout recovery with a real listening process, unchanged ownership,
and rejected identity evidence. The Runner restart tests require positive exit
evidence before replacement. This coverage does not prove recovery of a
evidence before replacement. The executor regressions also retire a real child
during its metadata read, keep unknown adopted-process ownership held, and reject
launch before detachment when Node is unavailable. The diagnostic tests cover
permission failures and generation-bound zombie receipts. This coverage does not prove recovery of a
historical retained sandbox or behavior during a live provider outage.
The [transport regression](../../packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts)
also retains a real authenticated Runner and its journal when its close probe
rejects, without signalling it, checkpointing it, or starting a replacement.
The failed close still retires its local connections, event timers and
notification stream. Repeated close cannot report successful retirement.
For a release change during a remote provider session, verify that reattachment
uses the controller's admitted pack manifest and runner digest. Check useful
@@ -269,6 +309,10 @@ completed obligations followed by quiet paused input.
The physical export regression holds one export while another completes, then
verifies a third Retry can use the free slot and shutdown joins the held work.
These local checks do not prove recovery of a deployed allocation.
The historical deadline case starts without preservation bookkeeping, holds the
provider stop reply, and verifies that HTTP Retry cannot admit a successor until
the real temporary files are restored. Duplicate requests then admit one queued
turn. GitHub and Telegram admission also retain the exact pending recovery.
Automated: [disposition notices](../../ui/src/components/DispositionRecoveryNotice.test.tsx)
tests pending/error/gated states and waiting for the real retry acknowledgement.
+16
View File
@@ -56,6 +56,22 @@ interfaces with [the paused composer browser suite](../../tests/e2e/paused-compo
Release rechecks tasks reopened after the pause; another active pause still prevents
their execution, and uncertain prior executions must be reconciled before waking.
### Plugin task panels
An installed plugin can offer an agent detail tab in the task side panel through
its optional `taskSidePanel` declaration. The host supplies the task's running
agent. The plugin's authorized availability route decides whether the panel is
shown, and the plugin owns its label and viewer. No contribution appears for a
missing plugin, inactive run, unavailable view or access failure. A closed panel
can be reopened from the launcher while available.
Implementation: [panel discovery](../../ui/src/hooks/useTaskPluginPanels.ts) and
[task panel](../../ui/src/components/task-side-panel/TaskSidePanel.tsx).
Automated: [discovery tests](../../ui/src/hooks/useTaskPluginPanels.test.tsx) and
[task panel tests](../../ui/src/components/task-side-panel/TaskSidePanel.test.tsx)
cover availability, task/agent changes, failures, inactivity and dismissal.
These mocks do not establish a particular plugin's live transport behavior.
## Gotchas
- Review completion and task completion are different events under some policies.
+9
View File
@@ -57,6 +57,15 @@ Automated: [workspace card](../../ui/src/components/IssueWorkspaceCard.test.tsx)
Manual: Run a task that writes a small file, follow the bound workspace, and inspect the file and revision. Reload and verify links still refer to the same workspace, not another checkout or a stale run.
For a repository-free isolated task, complete an explicitly fresh retry, save a
marker, then send ordinary new input. It must retain the bound attempt directory
and marker. A later explicitly fresh retry must use a separate clean sibling.
The [production preparation regression](../../server/src/services/heartbeat/workspace-preparation.test.ts)
uses PostgreSQL and real private directories; it also rejects changed bindings.
The [directory boundary suite](../../server/src/services/isolated-task-directory.test.ts)
checks namespace, missing-directory and symlink refusal. Neither suite proves a
hosted provider turn.
For slow source preparation, configure a short PostgreSQL idle-transaction
timeout in a disposable instance. Hold preparation beyond that interval and
verify it retains its source lock, rejects competing preparation, and leaves
+2 -1
View File
@@ -102,7 +102,8 @@
"cross-env": "^10.1.0",
"esbuild": "^0.28.2",
"typescript": "^7.0.2",
"vitest": "^5.0.3"
"vitest": "^5.0.3",
"yaml": "^2.8.1"
},
"engines": {
"node": ">=24.11.0"
@@ -162,4 +162,45 @@ describe("ephemeral ACPX session environment", () => {
const input = freeze(record()); await expect(wrapper.save(input)).rejects.toBe(failure);
expect(input.acpx?.session_options?.env).toEqual(currentEnvironment);
});
it("never overlaps two saves of one record, even across wrappers, and keeps their order", async () => {
let active = 0, maxActive = 0;
const order: string[] = [];
const failure = new Error("fixture rename failure");
const backing = stubStore(undefined);
backing.save.mockImplementation(async (saved) => {
active += 1; maxActive = Math.max(maxActive, active);
await new Promise(resolve => setTimeout(resolve, 5));
order.push(saved.lastUsedAt);
active -= 1;
if (saved.lastUsedAt === "checkpoint") throw failure;
});
const turnStore = createEphemeralSessionEnvironmentStore(backing, currentEnvironment);
const closeStore = createEphemeralSessionEnvironmentStore(backing, currentEnvironment);
const results = await Promise.allSettled([
turnStore.save({ ...record(), lastUsedAt: "checkpoint" }),
turnStore.save({ ...record(), lastUsedAt: "turn-end" }),
closeStore.save({ ...record(), lastUsedAt: "close" }),
]);
expect(maxActive).toBe(1);
expect(order).toEqual(["checkpoint", "turn-end", "close"]);
expect(results.map(result => result.status)).toEqual(["rejected", "fulfilled", "fulfilled"]);
expect((results[0] as PromiseRejectedResult).reason).toBe(failure);
});
it("does not serialize saves of different records", async () => {
let active = 0, maxActive = 0;
const backing = stubStore(undefined);
backing.save.mockImplementation(async () => {
active += 1; maxActive = Math.max(maxActive, active);
await new Promise(resolve => setTimeout(resolve, 5));
active -= 1;
});
const wrapper = createEphemeralSessionEnvironmentStore(backing, currentEnvironment);
await Promise.all([
wrapper.save({ ...record(), acpxRecordId: "fixture-record-a" }),
wrapper.save({ ...record(), acpxRecordId: "fixture-record-b" }),
]);
expect(maxActive).toBe(2);
});
});
@@ -1,5 +1,22 @@
import type { AcpSessionStore } from "acpx/runtime";
// ACPX saves one record from several writers (live checkpoint, turn end,
// finalize, close) with no lock. Each save renames a temp file onto the record
// file, and on Windows two overlapping renames onto one file fail with EPERM.
// Chain every save of one record so they never overlap.
const pendingSaves = new Map<string, Promise<void>>();
function saveInOrder(recordId: string, save: () => Promise<void>): Promise<void> {
const previous = pendingSaves.get(recordId) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(save);
const settled = current.catch(() => undefined);
pendingSaves.set(recordId, settled);
void settled.then(() => {
if (pendingSaves.get(recordId) === settled) pendingSaves.delete(recordId);
});
return current;
}
/** Keep the current run's environment in memory, outside persisted conversation state. */
export function createEphemeralSessionEnvironmentStore(
persistedStore: AcpSessionStore,
@@ -26,7 +43,7 @@ export function createEphemeralSessionEnvironmentStore(
const { env: _environment, ...sessionOptions } = record.acpx.session_options;
persisted.acpx = { ...record.acpx, session_options: sessionOptions };
}
return persistedStore.save(persisted);
return saveInOrder(record.acpxRecordId, () => persistedStore.save(persisted));
},
};
}
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
CODEX_CHATGPT_MODEL_REJECTION_RE,
codexChatGptRetirementForModel,
codexCliVersionAtLeast,
codexLocalReasoningEffortsForModel,
DEFAULT_CODEX_LOCAL_MODEL,
@@ -25,6 +26,20 @@ describe("codex model CLI floors", () => {
},
);
it("records models retired from Codex with ChatGPT sign-in and keeps them selectable for API keys", () => {
expect(codexChatGptRetirementForModel("gpt-5.5")).toEqual({
retiredOn: "2026-10-14",
replacement: "gpt-6.1-sol (gpt-6-luna on Free and Go plans)",
});
expect(codexChatGptRetirementForModel(" gpt-5.4 ")).toEqual({ retiredOn: "2026-08-31", replacement: "gpt-6-sol" });
expect(codexChatGptRetirementForModel("gpt-5.4-mini")).toEqual({ retiredOn: "2026-08-31", replacement: "gpt-6-luna" });
for (const model of [DEFAULT_CODEX_LOCAL_MODEL, "gpt-6.1-sol", "custom-model", "", null, undefined]) {
expect(codexChatGptRetirementForModel(model)).toBeNull();
}
const modelIds = models.map((model) => model.id);
expect(modelIds).toEqual(expect.arrayContaining(["gpt-5.5", "gpt-5.4", "gpt-5.4-mini"]));
});
it("compares stable versions numerically and rejects prerelease or ambiguous input", () => {
expect(codexCliVersionAtLeast("0.159.0", "0.159.0")).toBe(true);
expect(codexCliVersionAtLeast("0.160.1", "0.159.0")).toBe(true);
@@ -129,6 +129,31 @@ export function minimumCodexCliVersionForModel(model: string | null | undefined)
return CODEX_LOCAL_MODEL_MINIMUM_CLI_VERSIONS[normalizeCodexModel(model)] ?? null;
}
export interface CodexChatGptRetirement {
retiredOn: string;
replacement: string;
}
// Models OpenAI retired from Codex with ChatGPT sign-in (https://learn.chatgpt.com/docs/models).
// The OpenAI API and API-key Codex sessions still serve them, so they stay in the picker; the
// Test names the retirement instead of suggesting a stale CLI or a plan restriction.
const CODEX_LOCAL_CHATGPT_RETIRED_MODELS: Readonly<Record<string, CodexChatGptRetirement>> = {
"gpt-5.5": { retiredOn: "2026-10-14", replacement: "gpt-6.1-sol (gpt-6-luna on Free and Go plans)" },
"gpt-5.4": { retiredOn: "2026-08-31", replacement: "gpt-6-sol" },
"gpt-5.4-mini": { retiredOn: "2026-08-31", replacement: "gpt-6-luna" },
};
export function codexChatGptRetirementForModel(model: string | null | undefined): CodexChatGptRetirement | null {
return CODEX_LOCAL_CHATGPT_RETIRED_MODELS[normalizeCodexModel(model)] ?? null;
}
/** Test hint for a ChatGPT-account rejection of a retired model; shared by the legacy and native Tests. */
export function codexChatGptRetirementHint(model: string | null | undefined): string | null {
const retirement = codexChatGptRetirementForModel(model);
if (!retirement) return null;
return `OpenAI retired ${normalizeCodexModel(model)} from Codex with ChatGPT sign-in on ${retirement.retiredOn}. Choose ${retirement.replacement}, or use an OpenAI API key; API-key sessions are not affected.`;
}
const STABLE_CODEX_CLI_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
function stableCodexCliVersionParts(version: string): number[] | null {
@@ -257,6 +282,7 @@ Notes:
- Paperclip injects desired local skills into the effective CODEX_HOME/skills/ directory at execution time so Codex can discover "$paperclip" and related skills without polluting the project working directory. For new and updated agents, Paperclip assigns an isolated managed home at ~/.paperclip/instances/<id>/companies/<companyId>/agents/<agentId>/codex-home/skills/; when CODEX_HOME is explicitly overridden in adapter config, that override is used instead.
- New and updated codex_local agents persist an empty OPENAI_API_KEY override by default so a host-level OPENAI_API_KEY cannot leak into Codex runs through process inheritance. Explicit CODEX_HOME overrides must not point at the shared company codex-home, $CODEX_HOME, or ~/.codex.
- Some model/tool combinations reject certain effort levels (for example minimal with web search enabled).
- OpenAI retired gpt-5.5 (October 14, 2026), gpt-5.4 and gpt-5.4-mini (August 31, 2026) from Codex with ChatGPT sign-in. They remain selectable for OpenAI API-key sessions; with ChatGPT sign-in the Test names the retirement and its replacement.
- With ChatGPT sign-in, model availability depends on the installed Codex capabilities. Legacy setup reports known model/version mismatches. Native setup tests the actual app-server and selected model; a version number alone does not reject or replace an installed CLI. If the provider rejects the model, select an available model or update Codex in the execution environment.
- Fast mode is supported on GPT-6 (astra/sol/luna), GPT-6.1 Sol, GPT-5.6 (sol/terra/luna), GPT-5.5, GPT-5.4 and manual model IDs. When enabled for those models, Paperclip applies \`service_tier="fast"\` and \`features.fast_mode=true\`.
- When Paperclip realizes a workspace/runtime for a run, it injects PAPERCLIP_WORKSPACE_* and PAPERCLIP_RUNTIME_* env vars for agent-side tooling.
@@ -3,6 +3,7 @@ import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/executio
import { runAdapterExecutionTargetProcess } from "@paperclipai/adapter-utils/execution-target";
import {
CODEX_CHATGPT_MODEL_REJECTION_RE,
codexChatGptRetirementHint,
codexCliVersionAtLeast,
minimumCodexCliVersionForModel,
normalizeCodexModel,
@@ -110,6 +111,7 @@ export function codexHelloProbeModelRejectionCheck(input: {
if (!match) return null;
const model = match[1]!;
const minimum = minimumCodexCliVersionForModel(model);
const retirementHint = codexChatGptRetirementHint(model);
const versionNote = input.detectedVersion
? ` Detected Codex CLI ${input.detectedVersion}.`
: "";
@@ -118,8 +120,8 @@ export function codexHelloProbeModelRejectionCheck(input: {
level: "error",
message: `The Codex backend rejected ${model} for this ChatGPT account.`,
detail: `${match[0]}${versionNote}`,
hint: minimum
hint: retirementHint ?? (minimum
? `${model} needs Codex CLI ${minimum} or newer with ChatGPT sign-in. ${sandboxUpgradeHint(input.targetIsSandbox)} If the CLI is already new enough, the plan does not include this model (Enterprise and Edu administrators must enable it) or the rollout has not reached the account; choose another model or use an OpenAI API key.`
: `The ChatGPT plan does not include ${model}, the rollout has not reached the account, or the installed Codex CLI is older than the model requires. ${sandboxUpgradeHint(input.targetIsSandbox)} Otherwise choose another model or use an OpenAI API key.`,
: `The ChatGPT plan does not include ${model}, the rollout has not reached the account, or the installed Codex CLI is older than the model requires. ${sandboxUpgradeHint(input.targetIsSandbox)} Otherwise choose another model or use an OpenAI API key.`),
};
}
@@ -372,6 +372,35 @@ describe("codex remote environment diagnostics", () => {
expect(result.checks.some((check) => check.code === "codex_hello_probe_auth_required")).toBe(false);
});
it("names the ChatGPT retirement when the backend rejects a retired model", async () => {
runAdapterExecutionTargetProcess.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "ERROR: {\"type\":\"error\",\"status\":400,\"error\":{\"type\":\"invalid_request_error\",\"message\":\"The 'gpt-5.5' model is not supported when using Codex with a ChatGPT account.\"}}",
pid: 223,
startedAt: new Date().toISOString(),
});
const result = await testEnvironment({
companyId: "company-1",
adapterType: "codex_local",
config: { engine: "cli", command: "codex", model: "gpt-5.5" },
executionTarget: sandboxTarget(),
environmentName: "QA Daytona",
});
expect(result.status).toBe("fail");
const rejected = result.checks.find((check) => check.code === "codex_hello_probe_model_rejected");
expect(rejected).toMatchObject({
level: "error",
message: "The Codex backend rejected gpt-5.5 for this ChatGPT account.",
hint: "OpenAI retired gpt-5.5 from Codex with ChatGPT sign-in on 2026-10-14. Choose gpt-6.1-sol (gpt-6-luna on Free and Go plans), or use an OpenAI API key; API-key sessions are not affected.",
});
expect(rejected?.hint).not.toContain("Upgrade Codex");
});
it("emits the canonical adapter_auth_missing check when a sandbox hello probe reports missing auth", async () => {
// The sandbox has no seedable credentials, so the hello probe returns an
// authentication-required error. The Test must emit the neutral canonical
@@ -65,6 +65,8 @@ export const models: Array<{ id: string; label: string }> = [
{ id: "anthropic/claude-fable-5-1", label: "anthropic/claude-fable-5-1" },
{ id: "anthropic/claude-sonnet-5-5", label: "anthropic/claude-sonnet-5-5" },
{ id: "anthropic/claude-sonnet-5", label: "anthropic/claude-sonnet-5" },
{ id: "anthropic/claude-haiku-5-5", label: "anthropic/claude-haiku-5-5" },
{ id: "google/gemini-4-argon", label: "google/gemini-4-argon" },
{ id: "google/gemini-3.8-flash", label: "google/gemini-3.8-flash" },
{ id: "xai/grok-4.7", label: "xai/grok-4.7" },
{ id: "openai/gpt-5.5", label: "openai/gpt-5.5" },
@@ -53,6 +53,7 @@ import {
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE,
runChildProcess,
sanitizeInheritedPaperclipEnv,
} from "@paperclipai/adapter-utils/server-utils";
import { shellQuote } from "@paperclipai/adapter-utils/ssh";
import { isPiUnknownSessionError, parsePiJsonl, createPiJsonlParser } from "./parse.js";
@@ -356,7 +357,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const skillBinDirs = piSkillEntries
.filter((entry) => injectedSkillKeys.has(entry.key) && entry.source.length > 0)
.map((entry) => path.join(entry.source, "bin"));
const mergedEnv = ensurePathInEnv({ ...process.env, ...env });
const mergedEnv = ensurePathInEnv({ ...sanitizeInheritedPaperclipEnv(process.env), ...env });
const pathKey =
typeof mergedEnv.Path === "string" && mergedEnv.Path.length > 0 && !mergedEnv.PATH
? "Path"
@@ -508,7 +509,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
Object.assign(env, paperclipBridge.env);
loggedEnv = buildInvocationEnvForLogs(env, {
runtimeEnv: Object.fromEntries(
Object.entries(ensurePathInEnv({ ...process.env, ...env })).filter(
Object.entries(ensurePathInEnv({ ...sanitizeInheritedPaperclipEnv(process.env), ...env })).filter(
(entry): entry is [string, string] => typeof entry[1] === "string",
),
),
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import type { AdapterModel } from "@paperclipai/adapter-utils";
import { asString, runChildProcess } from "@paperclipai/adapter-utils/server-utils";
import { asString, runChildProcess, sanitizeInheritedPaperclipEnv } from "@paperclipai/adapter-utils/server-utils";
const MODELS_CACHE_TTL_MS = 60_000;
@@ -108,7 +108,7 @@ export async function discoverPiModels(input: {
const command = resolvePiCommand(input.command);
const cwd = asString(input.cwd, process.cwd());
const env = normalizeEnv(input.env);
const runtimeEnv = normalizeEnv({ ...process.env, ...env });
const runtimeEnv = normalizeEnv({ ...sanitizeInheritedPaperclipEnv(process.env), ...env });
const result = await runChildProcess(
`pi-models-${Date.now()}-${Math.random().toString(16).slice(2)}`,
@@ -7,6 +7,7 @@ import {
asString,
parseObject,
ensurePathInEnv,
sanitizeInheritedPaperclipEnv,
} from "@paperclipai/adapter-utils/server-utils";
import {
asStringArray,
@@ -125,7 +126,7 @@ export async function testEnvironment(
for (const [key, value] of Object.entries(envConfig)) {
if (typeof value === "string") env[key] = value;
}
const runtimeEnv = normalizeEnv(ensurePathInEnv({ ...process.env, ...env }));
const runtimeEnv = normalizeEnv(ensurePathInEnv({ ...sanitizeInheritedPaperclipEnv(process.env), ...env }));
const cwdInvalid = checks.some((check) => check.code === "pi_cwd_invalid");
if (cwdInvalid) {
@@ -8,8 +8,9 @@ const postgres = process.env.DRIVER_FORMAT === "cjs"
const mode = process.env.RECOVERY_CASE;
const closed = Promise.withResolvers();
const sql = postgres(process.env.TEST_DATABASE_URL, {
max: 1,
max_pipeline: 1,
max: mode === "no-pipeline" || mode === "no-pipeline-fairness" ? 2 : 1,
max_pipeline: mode?.startsWith("no-pipeline") ? 0 : 1,
connection: { application_name: `driver-recovery-${mode}` },
backoff: 0,
onnotice() {},
onclose: () => closed.resolve(),
@@ -28,7 +29,76 @@ try {
await control.unsafe("drop table if exists connection_recovery_probe");
await control.unsafe("create table connection_recovery_probe (id integer)");
if (mode === "transaction" || mode === "transaction-closed" || mode === "savepoint") {
if (mode === "no-pipeline-fairness") {
const query = "select pg_advisory_xact_lock($1::bigint)";
const lookup = "select $1::int as value";
const one = await sql.reserve();
const two = await sql.reserve();
for (const connection of [one, two]) {
await connection.unsafe(query, [900001]);
await connection.unsafe(lookup, [42]);
}
one.release();
two.release();
let first;
let second;
let fast;
try {
await control.unsafe("select pg_advisory_lock(900001), pg_advisory_lock(900002)");
const waitForBlocked = async (count) => {
const deadline = performance.now() + 5000;
let observed = 0;
while (performance.now() < deadline) {
const [row] = await control.unsafe("select count(*)::int as count from pg_stat_activity where application_name=$1 and wait_event='advisory'", [`driver-recovery-${mode}`]);
observed = row.count;
if (row.count === count) return;
await setImmediate();
}
throw new Error(`Expected ${count} advisory lock waits; observed ${observed}`);
};
let firstFinished = false;
first = sql.unsafe(query, [900001]).then(() => { firstFinished = true; });
await waitForBlocked(1);
second = sql.unsafe(query, [900002]).then(() => {});
await waitForBlocked(2);
fast = sql.unsafe(lookup, [42]).then((rows) => rows);
await control.unsafe("select pg_advisory_unlock(900002)");
assert.equal((await fast)[0].value, 42);
assert.equal(firstFinished, false, "lookup must progress after one pool connection is released while the other stays blocked");
} finally {
await control.unsafe("select pg_advisory_unlock_all()");
await Promise.allSettled([first, second, fast].filter(Boolean));
}
} else if (mode === "no-pipeline" || mode === "no-pipeline-single") {
await sql.begin(async (tx) => {
await tx.unsafe("insert into connection_recovery_probe values (1)");
const results = await Promise.all([
tx.unsafe("select id from connection_recovery_probe"),
tx.unsafe("select count(*)::int as count from connection_recovery_probe"),
]);
assert.deepEqual(results[0].map((row) => row.id), [1]);
assert.equal(results[1][0].count, 1);
assert.equal((await control.unsafe("select count(*)::int as count from connection_recovery_probe"))[0].count, 0);
});
await assert.rejects(sql.begin(async (tx) => {
await tx.unsafe("insert into connection_recovery_probe values (2)");
throw new Error("controlled transaction rollback");
}), /controlled transaction rollback/);
await sql.begin(async (tx) => {
await tx.unsafe("insert into connection_recovery_probe values (3)");
await assert.rejects(tx.savepoint(async (nested) => {
await nested.unsafe("insert into connection_recovery_probe values (4)");
throw new Error("controlled savepoint rollback");
}), /controlled savepoint rollback/);
assert.deepEqual((await tx.unsafe("select id from connection_recovery_probe order by id")).map((row) => row.id), [1, 3]);
});
const reserved = await sql.reserve();
try {
assert.deepEqual((await reserved.unsafe("select id from connection_recovery_probe order by id")).map((row) => row.id), [1, 3]);
} finally {
reserved.release();
}
} else if (mode === "transaction" || mode === "transaction-closed" || mode === "savepoint") {
const started = Promise.withResolvers();
const resume = Promise.withResolvers();
const callbackDone = Promise.withResolvers();
+9 -9
View File
@@ -501,15 +501,15 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
"0332_little_night_nurse.sql",
"0345_luxuriant_carmella_unuscione.sql",
"0369_late_logan.sql",
"0378_mean_scream.sql",
"0379_narrow_the_executioner.sql",
"0382_open_madame_web.sql",
"0383_chemical_madame_web.sql",
"0384_clever_chamber.sql",
"0385_many_reaper.sql",
"0386_normal_blindfold.sql",
"0381_funny_adam_warlock.sql",
"0380_tool_review_company_expiry.sql",
"0380_mean_scream.sql",
"0381_narrow_the_executioner.sql",
"0384_open_madame_web.sql",
"0385_chemical_madame_web.sql",
"0386_clever_chamber.sql",
"0387_many_reaper.sql",
"0388_normal_blindfold.sql",
"0383_funny_adam_warlock.sql",
"0382_tool_review_company_expiry.sql",
]);
async function applyPendingMigrationsManually(
@@ -34,6 +34,14 @@ describeEmbeddedPostgres("connections v3 schema core migration", () => {
`;
expect(chatForeignKey?.definition).toBeTruthy();
await sql`ALTER TABLE "chat_endpoints" DROP CONSTRAINT "chat_endpoints_company_connection_fk"`;
// Project consent is another later grant consumer; rewind only its known FK.
const [projectForeignKey] = await sql<{ definition: string }[]>`
SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint
WHERE conrelid = 'projects'::regclass
AND conname = 'projects_git_authorization_grant_id_connection_grants_id_fk'
`;
expect(projectForeignKey?.definition).toBeTruthy();
await sql`ALTER TABLE "projects" DROP CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk"`;
await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`;
// AI defaults arrive in 0273/0277 and depend on the composite grant key
@@ -83,6 +91,9 @@ describeEmbeddedPostgres("connections v3 schema core migration", () => {
await sql.unsafe(
`ALTER TABLE "chat_endpoints" ADD CONSTRAINT "chat_endpoints_company_connection_fk" ${chatForeignKey!.definition}`,
);
await sql.unsafe(
`ALTER TABLE "projects" ADD CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk" ${projectForeignKey!.definition}`,
);
const [connection] = await sql<{ uid: string; ownership: string; transport: string; auth_kind: string }[]>`
SELECT "uid", "ownership", "transport", "auth_kind" FROM "tool_connections" WHERE "id" = ${connectionId}
@@ -108,6 +119,7 @@ describeEmbeddedPostgres("connections v3 schema core migration", () => {
`).rejects.toMatchObject({ code: "23514" });
await sql`ALTER TABLE "chat_endpoints" DROP CONSTRAINT "chat_endpoints_company_connection_fk"`;
await sql`ALTER TABLE "projects" DROP CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk"`;
await sql`DROP TABLE IF EXISTS "connection_grant_members"`;
await sql`DROP TABLE "connection_grants"`;
await sql`DROP INDEX "tool_connections_company_uid_uq"`;
@@ -15,19 +15,13 @@ import { generateDrizzleJson, generateMigration } from "drizzle-kit/api";
const migrationsDir = fileURLToPath(new URL("./migrations", import.meta.url));
const schemaDir = fileURLToPath(new URL("./schema", import.meta.url));
type JournalEntry = { idx: number; tag: string };
async function readNewestSnapshot(): Promise<{ file: string; snapshot: Record<string, unknown> }> {
const journal = JSON.parse(
await readFile(path.join(migrationsDir, "meta", "_journal.json"), "utf8"),
) as { entries: JournalEntry[] };
const newest = journal.entries.at(-1);
if (!newest) throw new Error("migration journal has no entries");
const file = `${String(newest.idx).padStart(4, "0")}_snapshot.json`;
const snapshot = JSON.parse(await readFile(path.join(migrationsDir, "meta", file), "utf8")) as Record<
string,
unknown
>;
// SQL-only migrations can advance the journal without changing the schema snapshot.
const files = (await readdir(path.join(migrationsDir, "meta")))
.filter(file => /^\d+_snapshot\.json$/.test(file)).sort();
const file = files.at(-1);
if (!file) throw new Error("migration metadata has no schema snapshots");
const snapshot = JSON.parse(await readFile(path.join(migrationsDir, "meta", file), "utf8")) as Record<string, unknown>;
return { file, snapshot };
}
@@ -0,0 +1,111 @@
-- Environment requirements use the same durable runtime journal as explicit skill assignments.
CREATE OR REPLACE FUNCTION paperclip_environment_selects_runtime_skill(p_company uuid, p_environment uuid, p_skill uuid) RETURNS boolean
LANGUAGE sql STABLE SET search_path = public, pg_temp AS $$
SELECT EXISTS (
SELECT 1 FROM environments e
JOIN plugins p ON p.plugin_key = e.config->>'pluginKey'
JOIN plugin_managed_resources r ON r.plugin_id = p.id AND r.company_id = p_company
AND r.resource_kind = 'skill' AND r.resource_id = p_skill
CROSS JOIN LATERAL jsonb_array_elements(coalesce(p.manifest_json->'environmentDrivers', '[]'::jsonb)) AS declared_driver(value)
WHERE e.id = coalesce(p_environment, (SELECT default_environment_id FROM instance_settings LIMIT 1))
AND e.driver = 'plugin' AND declared_driver.value->>'driverKey' = e.config->>'driverKey'
AND coalesce(declared_driver.value->'skillKeys', '[]'::jsonb) ? r.resource_key);
$$;
--> statement-breakpoint
CREATE OR REPLACE FUNCTION paperclip_invalidate_skill_source_runtimes(p_company uuid, sources uuid[]) RETURNS void
LANGUAGE plpgsql SET search_path = public, pg_temp AS $$
DECLARE candidate uuid;
BEGIN
FOR candidate IN SELECT a.id FROM agents a WHERE a.company_id = p_company
AND a.status NOT IN ('pending_approval', 'terminated') AND EXISTS (
SELECT 1 FROM company_skills s WHERE s.company_id = p_company AND s.access_source_id = ANY(sources)
AND (paperclip_agent_selects_runtime_skill(a.adapter_config, a.adapter_type, s.key, s.slug)
OR paperclip_environment_selects_runtime_skill(p_company, a.default_environment_id, s.id)))
ORDER BY a.id FOR NO KEY UPDATE LOOP
PERFORM paperclip_record_agent_runtime(p_company, candidate);
END LOOP;
END;
$$;
--> statement-breakpoint
CREATE OR REPLACE FUNCTION paperclip_skill_runtime_changed() RETURNS trigger
LANGUAGE plpgsql SET search_path = public, pg_temp AS $$
DECLARE previous jsonb; current jsonb; keys text[]; company uuid; candidate uuid;
BEGIN
IF TG_OP <> 'INSERT' THEN previous := to_jsonb(OLD); END IF;
IF TG_OP <> 'DELETE' THEN current := to_jsonb(NEW); END IF;
IF TG_OP = 'UPDATE' AND
jsonb_build_array(OLD.key, OLD.slug, OLD.markdown, OLD.source_type, OLD.source_locator, OLD.source_ref,
OLD.file_inventory, OLD.current_version_id, OLD.access_source_id, OLD.compatibility, OLD.trust_level, OLD.metadata)
IS NOT DISTINCT FROM
jsonb_build_array(NEW.key, NEW.slug, NEW.markdown, NEW.source_type, NEW.source_locator, NEW.source_ref,
NEW.file_inventory, NEW.current_version_id, NEW.access_source_id, NEW.compatibility, NEW.trust_level, NEW.metadata)
THEN RETURN NEW; END IF;
company := coalesce((current->>'company_id')::uuid, (previous->>'company_id')::uuid);
SELECT array_agg(DISTINCT lower(reference)) INTO keys FROM (
SELECT row->>'key' AS reference FROM unnest(ARRAY[previous, current]) row
UNION ALL SELECT regexp_replace(row->>'key', '.*/', '') FROM unnest(ARRAY[previous, current]) row
UNION ALL SELECT CASE WHEN row->>'key' LIKE 'paperclipai/paperclip/%' THEN row->>'slug'
ELSE (row->>'slug') || '--' || left(encode(sha256(convert_to(row->>'key', 'UTF8')), 'hex'), 10) END
FROM unnest(ARRAY[previous, current]) row
) refs WHERE reference IS NOT NULL;
FOR candidate IN SELECT a.id FROM agents a WHERE a.company_id = company
AND a.status NOT IN ('pending_approval', 'terminated') AND (
(a.adapter_type <> 'paperclip_runner' AND keys && ARRAY['paperclipai/paperclip/paperclip', 'paperclipai/paperclip/complain', 'paperclipai/paperclip/suggestion-box']) OR
EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(a.adapter_config#>'{paperclipSkillSync,desiredSkills}') = 'array'
THEN a.adapter_config#>'{paperclipSkillSync,desiredSkills}' ELSE '[]'::jsonb END) choice
WHERE lower(trim(CASE WHEN jsonb_typeof(choice) = 'string' THEN choice#>>'{}' ELSE choice->>'key' END)) = ANY(keys))
OR paperclip_environment_selects_runtime_skill(company, a.default_environment_id, coalesce((current->>'id')::uuid, (previous->>'id')::uuid)))
ORDER BY a.id FOR NO KEY UPDATE LOOP
PERFORM paperclip_record_agent_runtime(company, candidate);
END LOOP;
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END;
$$;
--> statement-breakpoint
CREATE OR REPLACE FUNCTION paperclip_environment_runtimes_changed() RETURNS trigger
LANGUAGE plpgsql SET search_path = public, pg_temp AS $$
DECLARE previous jsonb; current jsonb; candidate record;
BEGIN
IF TG_OP <> 'INSERT' THEN previous := to_jsonb(OLD); END IF;
IF TG_OP <> 'DELETE' THEN current := to_jsonb(NEW); END IF;
IF TG_TABLE_NAME = 'plugin_company_settings' THEN
IF coalesce((previous->>'enabled')::boolean, true) IS NOT DISTINCT FROM coalesce((current->>'enabled')::boolean, true) THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
ELSIF TG_OP = 'UPDATE' AND (CASE TG_TABLE_NAME
WHEN 'environments' THEN previous->'config' IS NOT DISTINCT FROM current->'config' AND previous->'driver' IS NOT DISTINCT FROM current->'driver'
WHEN 'plugins' THEN previous->'manifest_json' IS NOT DISTINCT FROM current->'manifest_json' AND previous->'status' IS NOT DISTINCT FROM current->'status'
ELSE previous->'default_environment_id' IS NOT DISTINCT FROM current->'default_environment_id' END) THEN RETURN NEW; END IF;
FOR candidate IN SELECT a.id, a.company_id FROM agents a
WHERE a.status NOT IN ('pending_approval', 'terminated') AND (CASE TG_TABLE_NAME
WHEN 'environments' THEN coalesce(a.default_environment_id, (SELECT default_environment_id FROM instance_settings LIMIT 1))
= coalesce((current->>'id')::uuid, (previous->>'id')::uuid)
WHEN 'plugins' THEN EXISTS (SELECT 1 FROM environments e
WHERE e.id = coalesce(a.default_environment_id, (SELECT default_environment_id FROM instance_settings LIMIT 1))
AND e.driver = 'plugin' AND e.config->>'pluginKey' = coalesce(current->>'plugin_key', previous->>'plugin_key'))
WHEN 'plugin_company_settings' THEN a.company_id = coalesce((current->>'company_id')::uuid, (previous->>'company_id')::uuid)
AND EXISTS (SELECT 1 FROM environments e JOIN plugins p ON p.plugin_key = e.config->>'pluginKey'
WHERE e.id = coalesce(a.default_environment_id, (SELECT default_environment_id FROM instance_settings LIMIT 1))
AND e.driver = 'plugin' AND p.id = coalesce((current->>'plugin_id')::uuid, (previous->>'plugin_id')::uuid))
ELSE a.default_environment_id IS NULL END)
ORDER BY a.company_id, a.id FOR NO KEY UPDATE OF a LOOP
PERFORM paperclip_record_agent_runtime(candidate.company_id, candidate.id);
END LOOP;
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END;
$$;
--> statement-breakpoint
CREATE TRIGGER paperclip_environment_runtime_changed AFTER INSERT OR UPDATE ON environments
FOR EACH ROW EXECUTE FUNCTION paperclip_environment_runtimes_changed();
--> statement-breakpoint
CREATE TRIGGER paperclip_plugin_environment_runtime_changed AFTER UPDATE ON plugins
FOR EACH ROW EXECUTE FUNCTION paperclip_environment_runtimes_changed();
--> statement-breakpoint
CREATE TRIGGER paperclip_plugin_company_environment_runtime_changed AFTER INSERT OR UPDATE OR DELETE ON plugin_company_settings
FOR EACH ROW EXECUTE FUNCTION paperclip_environment_runtimes_changed();
--> statement-breakpoint
CREATE TRIGGER paperclip_default_environment_runtime_changed AFTER UPDATE ON instance_settings
FOR EACH ROW EXECUTE FUNCTION paperclip_environment_runtimes_changed();
@@ -0,0 +1,3 @@
ALTER TABLE "projects" ADD COLUMN "git_authorization_grant_id" uuid;--> statement-breakpoint
ALTER TABLE "projects" ADD COLUMN "git_authorized_by_user_id" text;--> statement-breakpoint
ALTER TABLE "projects" ADD CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk" FOREIGN KEY ("git_authorization_grant_id") REFERENCES "public"."connection_grants"("id") ON DELETE set null ON UPDATE no action;
+27 -40
View File
@@ -24028,44 +24028,6 @@
"method": "btree",
"with": {}
},
"decisions_open_expiry_idx": {
"name": "decisions_open_expiry_idx",
"columns": [
{
"expression": "expires_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'open'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_pending_continuation_idx": {
"name": "decisions_pending_continuation_idx",
"columns": [
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"continuation_policy\" = 'wake_origin_agent' AND \"decisions\".\"metadata\" ->> 'continuationPending' = 'true' AND (\"decisions\".\"status\" IN ('expired', 'cancelled') OR (\"decisions\".\"status\" = 'decided' AND \"decisions\".\"execution_status\" IN ('succeeded', 'partial', 'failed')))",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_bundle_idx": {
"name": "decisions_bundle_idx",
"columns": [
@@ -51148,6 +51110,18 @@
"primaryKey": false,
"notNull": false
},
"git_authorization_grant_id": {
"name": "git_authorization_grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"git_authorized_by_user_id": {
"name": "git_authorized_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pause_reason": {
"name": "pause_reason",
"type": "text",
@@ -51286,6 +51260,19 @@
],
"onDelete": "no action",
"onUpdate": "no action"
},
"projects_git_authorization_grant_id_connection_grants_id_fk": {
"name": "projects_git_authorization_grant_id_connection_grants_id_fk",
"tableFrom": "projects",
"tableTo": "connection_grants",
"columnsFrom": [
"git_authorization_grant_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -64144,6 +64131,6 @@
"tables": {},
"columns": {}
},
"id": "6b7d6277-49ab-43c8-b6ca-b92f706c68db",
"prevId": "15804294-0eee-46ef-9032-3280ff4d16ef"
"id": "00ed71e7-69a1-4ef5-a678-db965ae7a2e0",
"prevId": "9c7a9027-d6c9-4d7e-a4aa-ceb682cc1b36"
}
+27 -46
View File
@@ -24028,50 +24028,6 @@
"method": "btree",
"with": {}
},
"decisions_running_recovery_idx": {
"name": "decisions_running_recovery_idx",
"columns": [
{
"expression": "updated_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'decided' AND \"decisions\".\"execution_status\" = 'running'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_open_expiry_idx": {
"name": "decisions_open_expiry_idx",
"columns": [
{
"expression": "expires_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'open'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_pending_continuation_idx": {
"name": "decisions_pending_continuation_idx",
"columns": [
@@ -51170,6 +51126,18 @@
"primaryKey": false,
"notNull": false
},
"git_authorization_grant_id": {
"name": "git_authorization_grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"git_authorized_by_user_id": {
"name": "git_authorized_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pause_reason": {
"name": "pause_reason",
"type": "text",
@@ -51308,6 +51276,19 @@
],
"onDelete": "no action",
"onUpdate": "no action"
},
"projects_git_authorization_grant_id_connection_grants_id_fk": {
"name": "projects_git_authorization_grant_id_connection_grants_id_fk",
"tableFrom": "projects",
"tableTo": "connection_grants",
"columnsFrom": [
"git_authorization_grant_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -64166,6 +64147,6 @@
"tables": {},
"columns": {}
},
"id": "9518f54d-db89-43e6-8d87-f9ac789dbe12",
"prevId": "6b7d6277-49ab-43c8-b6ca-b92f706c68db"
"id": "7f808b27-c88b-4f78-ac92-1da4ac6af1a4",
"prevId": "00ed71e7-69a1-4ef5-a678-db965ae7a2e0"
}
+27 -46
View File
@@ -24028,28 +24028,6 @@
"method": "btree",
"with": {}
},
"decisions_running_recovery_idx": {
"name": "decisions_running_recovery_idx",
"columns": [
{
"expression": "updated_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'decided' AND \"decisions\".\"execution_status\" = 'running'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_open_expiry_idx": {
"name": "decisions_open_expiry_idx",
"columns": [
@@ -32077,28 +32055,6 @@
"method": "btree",
"with": {}
},
"grok_dispatch_prepared_idx": {
"name": "grok_dispatch_prepared_idx",
"columns": [
{
"expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"grok_bot_dispatches\".\"status\" = 'prepared'",
"concurrently": false,
"method": "btree",
"with": {}
},
"grok_dispatch_company_status_idx": {
"name": "grok_dispatch_company_status_idx",
"columns": [
@@ -51192,6 +51148,18 @@
"primaryKey": false,
"notNull": false
},
"git_authorization_grant_id": {
"name": "git_authorization_grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"git_authorized_by_user_id": {
"name": "git_authorized_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pause_reason": {
"name": "pause_reason",
"type": "text",
@@ -51330,6 +51298,19 @@
],
"onDelete": "no action",
"onUpdate": "no action"
},
"projects_git_authorization_grant_id_connection_grants_id_fk": {
"name": "projects_git_authorization_grant_id_connection_grants_id_fk",
"tableFrom": "projects",
"tableTo": "connection_grants",
"columnsFrom": [
"git_authorization_grant_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -64188,6 +64169,6 @@
"tables": {},
"columns": {}
},
"id": "d0909d89-89c0-412c-9764-3696eed9ed8d",
"prevId": "9518f54d-db89-43e6-8d87-f9ac789dbe12"
"id": "61e3453f-0fd5-4fb7-92bd-e3df63c657e5",
"prevId": "7f808b27-c88b-4f78-ac92-1da4ac6af1a4"
}
@@ -24028,6 +24028,50 @@
"method": "btree",
"with": {}
},
"decisions_running_recovery_idx": {
"name": "decisions_running_recovery_idx",
"columns": [
{
"expression": "updated_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'decided' AND \"decisions\".\"execution_status\" = 'running'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_open_expiry_idx": {
"name": "decisions_open_expiry_idx",
"columns": [
{
"expression": "expires_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'open'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_pending_continuation_idx": {
"name": "decisions_pending_continuation_idx",
"columns": [
@@ -51126,6 +51170,18 @@
"primaryKey": false,
"notNull": false
},
"git_authorization_grant_id": {
"name": "git_authorization_grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"git_authorized_by_user_id": {
"name": "git_authorized_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pause_reason": {
"name": "pause_reason",
"type": "text",
@@ -51264,6 +51320,19 @@
],
"onDelete": "no action",
"onUpdate": "no action"
},
"projects_git_authorization_grant_id_connection_grants_id_fk": {
"name": "projects_git_authorization_grant_id_connection_grants_id_fk",
"tableFrom": "projects",
"tableTo": "connection_grants",
"columnsFrom": [
"git_authorization_grant_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -64122,6 +64191,6 @@
"tables": {},
"columns": {}
},
"id": "15804294-0eee-46ef-9032-3280ff4d16ef",
"prevId": "ce9f6a62-5259-4041-b313-9de9484154f7"
"id": "a6249181-185e-49c6-bc36-0b2b5841b97f",
"prevId": "61e3453f-0fd5-4fb7-92bd-e3df63c657e5"
}
@@ -24028,6 +24028,66 @@
"method": "btree",
"with": {}
},
"decisions_running_recovery_idx": {
"name": "decisions_running_recovery_idx",
"columns": [
{
"expression": "updated_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'decided' AND \"decisions\".\"execution_status\" = 'running'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_open_expiry_idx": {
"name": "decisions_open_expiry_idx",
"columns": [
{
"expression": "expires_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"status\" = 'open'",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_pending_continuation_idx": {
"name": "decisions_pending_continuation_idx",
"columns": [
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"decisions\".\"continuation_policy\" = 'wake_origin_agent' AND \"decisions\".\"metadata\" ->> 'continuationPending' = 'true' AND (\"decisions\".\"status\" IN ('expired', 'cancelled') OR (\"decisions\".\"status\" = 'decided' AND \"decisions\".\"execution_status\" IN ('succeeded', 'partial', 'failed')))",
"concurrently": false,
"method": "btree",
"with": {}
},
"decisions_bundle_idx": {
"name": "decisions_bundle_idx",
"columns": [
@@ -32017,6 +32077,28 @@
"method": "btree",
"with": {}
},
"grok_dispatch_prepared_idx": {
"name": "grok_dispatch_prepared_idx",
"columns": [
{
"expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"grok_bot_dispatches\".\"status\" = 'prepared'",
"concurrently": false,
"method": "btree",
"with": {}
},
"grok_dispatch_company_status_idx": {
"name": "grok_dispatch_company_status_idx",
"columns": [
@@ -51110,6 +51192,18 @@
"primaryKey": false,
"notNull": false
},
"git_authorization_grant_id": {
"name": "git_authorization_grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"git_authorized_by_user_id": {
"name": "git_authorized_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pause_reason": {
"name": "pause_reason",
"type": "text",
@@ -51248,6 +51342,19 @@
],
"onDelete": "no action",
"onUpdate": "no action"
},
"projects_git_authorization_grant_id_connection_grants_id_fk": {
"name": "projects_git_authorization_grant_id_connection_grants_id_fk",
"tableFrom": "projects",
"tableTo": "connection_grants",
"columnsFrom": [
"git_authorization_grant_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
@@ -64106,6 +64213,6 @@
"tables": {},
"columns": {}
},
"id": "ce9f6a62-5259-4041-b313-9de9484154f7",
"prevId": "f00ffc99-8611-486f-a74a-c6b1e753204d"
"id": "973d2543-9ef7-4bb4-84eb-9a637f640006",
"prevId": "a6249181-185e-49c6-bc36-0b2b5841b97f"
}
+32 -18
View File
@@ -2637,64 +2637,78 @@
{
"idx": 378,
"version": "7",
"when": 1792861534317,
"tag": "0378_mean_scream",
"when": 1793041667443,
"tag": "0378_environment_skill_runtime_hooks",
"breakpoints": true
},
{
"idx": 379,
"version": "7",
"when": 1792861791949,
"tag": "0379_narrow_the_executioner",
"when": 1793049353756,
"tag": "0379_white_giant_girl",
"breakpoints": true
},
{
"idx": 380,
"version": "7",
"when": 1792861791950,
"tag": "0380_tool_review_company_expiry",
"when": 1793049353757,
"tag": "0380_mean_scream",
"breakpoints": true
},
{
"idx": 381,
"version": "7",
"when": 1792863024087,
"tag": "0381_funny_adam_warlock",
"when": 1793049353758,
"tag": "0381_narrow_the_executioner",
"breakpoints": true
},
{
"idx": 382,
"version": "7",
"when": 1792863626931,
"tag": "0382_open_madame_web",
"when": 1793049353759,
"tag": "0382_tool_review_company_expiry",
"breakpoints": true
},
{
"idx": 383,
"version": "7",
"when": 1792871748836,
"tag": "0383_chemical_madame_web",
"when": 1793049353760,
"tag": "0383_funny_adam_warlock",
"breakpoints": true
},
{
"idx": 384,
"version": "7",
"when": 1792872323806,
"tag": "0384_clever_chamber",
"when": 1793049353761,
"tag": "0384_open_madame_web",
"breakpoints": true
},
{
"idx": 385,
"version": "7",
"when": 1792873408795,
"tag": "0385_many_reaper",
"when": 1793049353762,
"tag": "0385_chemical_madame_web",
"breakpoints": true
},
{
"idx": 386,
"version": "7",
"when": 1792875344101,
"tag": "0386_normal_blindfold",
"when": 1793049353763,
"tag": "0386_clever_chamber",
"breakpoints": true
},
{
"idx": 387,
"version": "7",
"when": 1793049353764,
"tag": "0387_many_reaper",
"breakpoints": true
},
{
"idx": 388,
"version": "7",
"when": 1793049353765,
"tag": "0388_normal_blindfold",
"breakpoints": true
}
]
@@ -21,6 +21,22 @@ describe.skipIf(!support.supported)("postgres connection recovery", () => {
afterAll(async () => { await database?.cleanup(); });
for (const format of ["esm", "cjs"]) {
for (const scenario of ["no-pipeline-single", "no-pipeline", "no-pipeline-fairness"]) {
it(`${format}: ${scenario} preserves connection ownership and progress`, async () => {
const { stdout, stderr } = await run(process.execPath, [fixture], {
env: {
...process.env,
TEST_DATABASE_URL: database.connectionString,
DRIVER_FORMAT: format,
RECOVERY_CASE: scenario,
},
timeout: 15_000,
});
expect(stdout.trim()).toBe("recovered");
expect(stderr).toBe("");
}, 20_000);
}
for (const scenario of ["transaction", "transaction-closed", "savepoint", "reserve", "transaction-queue", "reserve-queue"]) {
it(`${format}: rejects disconnected ${scenario} work and recovers the pool`, async () => {
// A driver timer used to crash the whole process. A child also detects
+3
View File
@@ -4,6 +4,7 @@ import type { AgentEnvConfig } from "@paperclipai/shared";
import { companies } from "./companies.js";
import { goals } from "./goals.js";
import { agents } from "./agents.js";
import { connectionGrants } from "./tool_access.js";
export const projects = pgTable(
"projects",
@@ -22,6 +23,8 @@ export const projects = pgTable(
color: text("color"),
icon: text("icon"),
env: jsonb("env").$type<AgentEnvConfig>(),
gitAuthorizationGrantId: uuid("git_authorization_grant_id").references(() => connectionGrants.id, { onDelete: "set null" }),
gitAuthorizedByUserId: text("git_authorized_by_user_id"),
pauseReason: text("pause_reason"),
pausedAt: timestamp("paused_at", { withTimezone: true }),
executionWorkspacePolicy: jsonb("execution_workspace_policy").$type<Record<string, unknown>>(),
+18 -1
View File
@@ -797,6 +797,20 @@ fit the compacted bound produces a diagnostic; the event stream continues.
Tool output and error fields have reserved retention space and size records,
so large input values cannot consume their output tails or make excerpts look
complete. A separator split between reads does not count against the frame limit.
### OpenCode MCP tool results
The Runner-owned MCP bridge sends complete JSON tool results up to 1 MiB of
UTF-8 output. It does not slice JSON text. This includes the native server's
bounded 500 KB app-tool results and saved-result pages. OpenCode can put a long
result in its own output file; that file must still contain the complete JSON.
The existing `read_tool_result` artifact protocol handles larger app results.
Serialization has a bounded traversal budget and checks escaped UTF-8 output.
If delivery exceeds the limit, the bridge reports an error without a partial
success value. The action may already have completed. Reconcile its saved
result or receipt instead of repeating it. Replaying the same MCP call identity
reuses the original handler execution, including when delivery failed.
## Preconfigured home
Set `homeMode: "preconfigured"` in a `paperclip_runner` agent's adapter config
@@ -818,7 +832,10 @@ rules and hooks apply. Native Codex tools can read and modify the execution home
(read-only for planning); credentials in that home are not isolated from tools.
Native Codex separately denies Runner-owned protocol state; ACPX Claude retains
its existing provider trust boundary. Execution is unattended: native Codex uses `never`, and
ACPX rejects requests for approval. The initial ACPX mode requires the Runner
ACPX rejects requests for approval. When Claude starts in its home directory,
its native user settings retain user trust even if the SDK also reports that
same file as project settings. Other project settings keep the native trust filter.
The initial ACPX mode requires the Runner
setting `acpxPermissionMode: "approve-all"` (its default); other Runner modes are
unqualified here and fail before launch. Local permission rules still apply.
Preconfigured ACPX read-only/planning tasks also fail before provider launch
+2 -2
View File
@@ -32,12 +32,12 @@
"requiresProviderPolicy": true
},
"copilot": {
"agentProfileVersion": 61,
"agentProfileVersion": 63,
"agentServerPackage": "@github/copilot",
"agentServerVersion": "1.0.88",
"agentRuntimePackage": null,
"agentRuntimeVersion": null,
"commandDigest": "sha256:956276ebee59f880249fa6955adc224af9ca7b6a9da59bcc5da4a8667550c5b3",
"commandDigest": "sha256:1412842a36a7211d84b6b98a3d1f69e3388bc4814e5825da890a774ae0e3460e",
"requiresProviderPolicy": true
},
"claude": {
@@ -175,16 +175,24 @@ The ACK means that every source event through sequence 9 is committed or
deduplicated. The runner rejects an ACK that moves backward or beyond its
produced source cursor. It removes only events at or below a valid ACK.
The controller stages `item.delta` output snapshots with asynchronous file writes and file
flushes. A slow volume does not block unrelated HTTP requests during those
operations. The controller still publishes the snapshot atomically, flushes its
directory, and waits for persistence before acknowledging an event.
A newer command or authenticated connection can save the
same event while staging is pending; the older snapshot cannot replace that
newer durable state. A failed write fences further authority until reload.
Lifecycle, control, authentication, and semantic tool events retain synchronous
persistence before transport readers can observe their state. Semantic tool
admission and dispatch cannot yield to a replacement connection between those operations.
The controller stages routine priority 1 and 2 event snapshots with asynchronous
file writes and file fsyncs. Those operations let unrelated HTTP requests run
while the volume is slow. Rename and directory fsync remain synchronous. The
candidate snapshot stays private until its atomic replacement
and directory flush finish. Lifecycle readers and replacement connections see
only the committed cursor. The controller acknowledges the event after that commit.
A command that saves during staging includes the pending event in its own
durable write. Further commands do not add event deliveries or cause another
staged write. Other authority changes leave an uncommitted event available for
replay instead of repeatedly rewriting the snapshot. A replaced
connection cannot publish its old candidate. Its unacknowledged event remains
available for replay. A failed write fences further authority until reload.
Priority 0 events, all `run.*` and `turn.*` lifecycle events, commands,
authentication, and semantic tool input retain synchronous persistence. The
lifecycle rule also covers producers that label a terminal event priority 1.
A terminal suffix remains in the same
control-loop turn. Semantic tool admission and dispatch cannot yield to a
replacement connection between those operations.
Controller replacement must still stop ingress and drain admitted processing
before a successor reuses the journal. External control routes stop their
reconnect loop before the controller joins admitted work. An incomplete drain
@@ -1998,9 +1998,11 @@ impl AcpxCommandExecutor {
state.lifecycle = "closed".to_owned();
state.provider_exit_unconfirmed = true;
if let Some(turn_id) = failed_turn {
let message = crate::durable::redact_text(&error.to_string());
state.push(NormalizedProviderEvent { event_type: "turn.failed".to_owned(), priority: EventPriority::P0,
payload: json!({"provider":"acpx","providerTurnId":turn_id,"status":"failed","providerTerminalObserved":false,
"code":"acpx_provider_transport_failed","message":crate::durable::redact_text(&error.to_string())}) })?;
"code":"acpx_provider_transport_failed","message":message,
"error":{"code":"acpx_provider_transport_failed","message":message,"recoverable":false}}) })?;
state.push(NormalizedProviderEvent { event_type: "run.terminal".to_owned(), priority: EventPriority::P0,
payload: json!({"schema":"paperclip.prp.terminal.v1","status":"failed","turnTerminalState":"failed","runTerminalState":"failed","reportedWorkDisposition":"unknown","provider":"acpx"}) })?;
}
@@ -327,6 +327,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
| "turns-unauthorized-tool"
| "turns-permission"
| "turns-provider-death"
| "turns-malformed-activity"
| "permissions-forged-origin"
| "turns-retired"
| "turns-retired-terminal-first"
@@ -377,6 +378,10 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
}
}
write_json(&mut stdout, &response)?;
if command == "turn.start" && mode == "turns-malformed-activity" {
stdout.write_all(b"{invalid sidecar activity\n")?;
stdout.flush()?;
}
let params = request.get("params").unwrap_or(&Value::Null);
let turn_id = params
.get("turnId")
@@ -47,7 +47,7 @@ pub(crate) fn acpx_release_profile(agent: &str) -> Option<AcpxReleaseProfile> {
agent_runtime_package: None,
agent_runtime_version: None,
command_digest:
"sha256:956276ebee59f880249fa6955adc224af9ca7b6a9da59bcc5da4a8667550c5b3",
"sha256:1412842a36a7211d84b6b98a3d1f69e3388bc4814e5825da890a774ae0e3460e",
requires_provider_policy: true,
},
"claude" => AcpxReleaseProfile {
@@ -1103,6 +1103,67 @@ fn routes_reserved_completion_feedback_with_the_full_controller_catalog() {
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn acpx_transport_failure_retains_its_error_without_reopening_the_provider() {
let directory = temporary_directory("acpx-transport-failure");
let mode = "turns-malformed-activity";
let config = acpx_config(&directory, mode);
let mut executor = NativeProviderCommandExecutor::with_runner_config(&directory, &config);
executor
.execute(&command(
1,
"run.prepare",
prepare_payload_with_mode(&directory, "codex", mode),
))
.unwrap();
executor
.execute(&command(2, "session.open", json!({})))
.unwrap();
executor
.execute(&command(
3,
"turn.start",
json!({"text":"Read the saved question", "turnId":"provider-turn-transport"}),
))
.unwrap();
let mut events = Vec::new();
for _ in 0..20 {
let batch = executor.poll_events().unwrap();
executor.acknowledge_events(batch.len()).unwrap();
events.extend(batch);
if events
.iter()
.any(|event| event.event_type == "run.terminal")
{
break;
}
std::thread::sleep(Duration::from_millis(5));
}
let failures: Vec<_> = events
.iter()
.filter(|event| event.event_type == "turn.failed")
.collect();
assert_eq!(failures.len(), 1);
let failure = &failures[0].payload;
assert_eq!(failure["providerTurnId"], "provider-turn-transport");
assert_eq!(failure["providerTerminalObserved"], false);
assert_eq!(failure["error"]["code"], "acpx_provider_transport_failed");
assert!(failure["error"]["message"]
.as_str()
.unwrap()
.contains("ACPX sidecar emitted invalid JSON"));
assert_eq!(failure["error"]["recoverable"], false);
let snapshot = executor
.execute(&command(4, "session.snapshot", json!({})))
.unwrap()
.result;
assert_eq!(snapshot["status"], "closed");
assert_eq!(snapshot["activeProviderTurnId"], Value::Null);
assert!(executor.poll_events().unwrap().is_empty());
executor.shutdown().unwrap();
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn provider_death_expires_input_and_commits_failure_without_querying_the_dead_provider() {
let directory = temporary_directory("acpx-provider-death");
@@ -7,9 +7,9 @@ import { fileURLToPath } from "node:url";
import { resolve, dirname } from "node:path";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const fixture = resolve(root, "test/fixtures/copilot-profile-v61-identity.json");
const fixture = resolve(root, "test/fixtures/copilot-profile-v63-identity.json");
const historical = JSON.parse(readFileSync(resolve(root, "test/fixtures/copilot-profile-v12-identity.json"), "utf8"));
const declaration = { ...historical.declaration, agentProfileVersion: 61 };
const declaration = { ...historical.declaration, agentProfileVersion: 63 };
delete declaration.permissionIdentitySourceSha256;
const sources = {
displayEventSourceSha256: "src/drivers/acpx/copilot-events.ts",
@@ -3,7 +3,7 @@ export const PRP_COMPLETION_TOOL_NAME = "paperclip_finish" as const;
export const PRP_BLOCK_TOOL_NAME = "paperclip_block" as const;
/** Native Runner guidance; legacy adapters use their own skill/API completion paths. */
export const PRP_COMPLETION_TOOL_DESCRIPTION =
"Report completed work (done), work requiring review (needs_review), or an explicit wait (yielded with response_wake for a response, monitor after set_task_monitor confirms a schedule on this task, or omit continuation to use the saved repository-preparation continuation). Use the current completion contract and supporting evidence. If rejected, correct the report and retry. After acceptance, read the returned outcome; do not claim completion while gated. Explain any required approval with its supplied link and action, then write the final response and end the turn without further tool calls.";
"Report completed work (done), work requiring review (needs_review), or an explicit wait (yielded with response_wake for a response, monitor after set_task_monitor confirms a schedule on this task, or omit continuation to use this run's authorized published-review wait or saved repository-preparation continuation). Use the current completion contract and supporting evidence. If rejected, correct the report and retry. After acceptance, read the returned outcome; do not claim completion while gated. Explain any required approval with its supplied link and action, then write the final response and end the turn without further tool calls.";
export const PRP_BLOCK_TOOL_DESCRIPTION =
"Report work that cannot continue because of a concrete blocker. Routine repository preparation is not a blocker: use paperclip_finish with yielded and omit continuation to resume through the saved workspace continuation. Identify the blocker, its owner, and the action needed to unblock it; use the current completion contract and supporting evidence. If rejected, correct the report and retry. After acceptance, read the returned outcome, explain the blocker and any required action in the final response, and end the turn without further tool calls.";
export const PRP_SEMANTIC_TOOL_NAMES = [
@@ -372,7 +372,7 @@ export const PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA = {
...waitContinuationSchema,
type: ["object", "null"],
description:
"For yielded, omit or use null to reuse this task's eligible saved monitor or repository-preparation continuation; the controller reads current task state. Otherwise provide a real response_wake or monitor with summary and idempotencyKey. Use null or omit for done, completed, or needs_review.",
"For yielded, omit or use null to reuse this run's authorized published-review wait, eligible saved monitor, or repository-preparation continuation; the controller reads current task state. Otherwise provide a real response_wake or monitor with summary and idempotencyKey. Use null or omit for done, completed, or needs_review.",
},
},
// Keep the provider-facing root a concrete object. Codex code-mode renders a
@@ -49,32 +49,38 @@ const identity: DurableRecoveryIdentity = {
const expectedRunnerVersion = "0.3.0";
const expectedRunnerDigest = `sha256:${"a".repeat(64)}`;
it.each(["event", "newer_command", "replacement", "write_failure", "drain", "semantic_replacement"] as const)(
it.each(["event", "progress", "lifecycle", "lifecycle_priority_one", "usage", "credentials", "newer_command", "command_burst", "command_failure", "authority_conflict", "replacement", "write_failure", "usage_write_failure", "drain", "usage_drain", "semantic_replacement"] as const)(
"keeps HTTP responsive during a durable event write and preserves %s", async (mode) => {
if (mode === "command_failure" && process.platform === "win32") return;
const root = mkdtempSync(resolve(tmpdir(), "runner-event-io-"));
const dispatch = vi.fn(async () => {
expect(JSON.parse(readFileSync(resolve(root, "control-plane-state.json"), "utf8")).ackedSourceSeq).toBe(1);
return { result: { ok: true } };
});
const effects = new Set<string>();
const commit = vi.fn(async (event: { sourceEventId: string }) => { effects.add(event.sourceEventId); });
const core = new DurablePrpControlPlane({ stateDirectory: root, identity,
expectedRunnerVersion, expectedRunnerDigest, onCommittedEvent: async () => {}, onSemanticToolInput: dispatch });
expectedRunnerVersion, expectedRunnerDigest, onCommittedEvent: commit, onSemanticToolInput: dispatch });
const http = createServer((_req, res) => res.end("responsive"));
let release!: () => void;
const barrier = new Promise<void>(resolveWrite => { release = resolveWrite; });
const originalOpen = fsPromises.open;
let staged = false;
let stagedWrites = 0;
let holdFirst = true;
let client: AuthenticatedClient | null = null;
let replacement: AuthenticatedClient | null = null;
let restoreCommandSync = () => {};
const open = vi.spyOn(fsPromises, "open").mockImplementation(async (...args) => {
const file = await originalOpen(...args);
if (String(args[0]).includes(".control-plane-state.json.")) stagedWrites++;
if (holdFirst && String(args[0]).includes(".control-plane-state.json.")) {
holdFirst = false;
const sync = file.sync.bind(file);
file.sync = async () => {
staged = true;
await barrier;
if (mode === "write_failure") throw new Error("controlled disk failure");
if (mode === "write_failure" || mode === "usage_write_failure") throw new Error("controlled disk failure");
await sync();
};
}
@@ -90,10 +96,30 @@ it.each(["event", "newer_command", "replacement", "write_failure", "drain", "sem
payload.eventType = "item.delta";
payload.priority = 2;
payload.payload = { delta: "output while the volume is slow" };
if (mode === "progress") {
payload.eventType = "tool.execution.progressed";
payload.payload = { schema: "paperclip.tool.execution.v1", executionId: "progress-1",
transport: "process", operation: "execute", status: "running", output: "working",
outputBytes: 7, outputTruncated: false, outputDigest: null };
} else if (mode === "lifecycle" || mode === "lifecycle_priority_one") {
payload.eventType = "turn.completed";
// Direct TypeScript producers can label turn.completed as P1.
payload.priority = mode === "lifecycle_priority_one" ? 1 : 0;
payload.payload = { status: "completed" };
} else if (mode === "usage" || mode === "usage_drain" || mode === "usage_write_failure") {
payload.eventType = "usage.reported";
payload.priority = 1;
payload.payload = { inputTokens: 100, outputTokens: 20 };
} else if (mode === "credentials") {
payload.eventType = "auth.credentials.updated";
payload.priority = 0;
payload.payload = { schema: "paperclip.auth.credentials.updated.v1", provider: "codex",
bindingId: "harness-auth", revision: 1, detection: "credential_store" };
}
}
expect(validatePrpEvent(payload)).toMatchObject({ ok: true });
sendSecure(client, event);
await vi.waitFor(() => expect(staged || dispatch.mock.calls.length > 0).toBe(true));
await vi.waitFor(() => expect(staged || dispatch.mock.calls.length > 0 || core.store.state.ackedSourceSeq > 0).toBe(true));
if (mode === "semantic_replacement") {
replacement = (await authenticate(core, client.leaseToken!))!;
release();
@@ -101,13 +127,51 @@ it.each(["event", "newer_command", "replacement", "write_failure", "drain", "sem
await vi.waitFor(() => expect(core.store.state.commands.some(command => command.type === "semantic_tool.result")).toBe(true));
return;
}
if (mode === "lifecycle" || mode === "lifecycle_priority_one" || mode === "credentials") {
expect(staged).toBe(false);
expect(JSON.parse(readFileSync(core.store.path, "utf8")).ackedSourceSeq).toBe(1);
expect(await receiveSecure(client)).toMatchObject({ kind: "ack", payload: { ackedSourceSeq: 1 } });
return;
}
// The actual socket request completes while the real file's fsync is held.
const address = http.address() as { port: number };
expect(await (await fetch(`http://127.0.0.1:${address.port}`)).text()).toBe("responsive");
expect(JSON.parse(readFileSync(core.store.path, "utf8")).ackedSourceSeq).toBe(0);
if (mode === "newer_command") core.queueCommand("session.snapshot", {}, "command_during_event");
// Lifecycle readers and replacement handshakes must not observe an event
// whose snapshot is still waiting for its first durable write.
expect(core.store.state.ackedSourceSeq).toBe(0);
expect(core.store.state.committedEvents).toEqual([]);
if (mode === "newer_command" || mode === "command_burst") {
core.queueCommand("session.snapshot", {}, "command_during_event");
if (mode === "command_burst") core.queueCommand("session.snapshot", {}, "second_command_during_event");
const saved = JSON.parse(readFileSync(core.store.path, "utf8"));
// The command's existing durable write can also publish the pending
// event. It must not need another full staged write afterward.
expect(saved.ackedSourceSeq).toBe(1);
expect(core.store.state.ackedSourceSeq).toBe(1);
expect(saved.commands.some((command: { commandId: string }) => command.commandId === "command_during_event")).toBe(true);
}
if (mode === "command_failure") {
const originalSync = nodeFs.fsyncSync;
const failDirectorySync = vi.spyOn(nodeFs, "fsyncSync").mockImplementation(fd => {
if (nodeFs.fstatSync(fd).isDirectory()) throw new Error("controlled directory sync failure");
originalSync(fd);
});
syncBuiltinESMExports();
restoreCommandSync = () => { failDirectorySync.mockRestore(); syncBuiltinESMExports(); };
expect(() => core.queueCommand("session.snapshot", {}, "failed_command_during_event")).toThrow("controlled directory sync failure");
expect(JSON.parse(readFileSync(core.store.path, "utf8")).ackedSourceSeq).toBe(1);
expect(core.store.state.ackedSourceSeq).toBe(0);
expect(() => core.queueCommand("session.snapshot")).toThrow("indeterminate");
}
if (mode === "authority_conflict") {
core.store.commit(structuredClone(core.store.state));
core.queueCommand("session.snapshot", {}, "command_after_authority");
expect(JSON.parse(readFileSync(core.store.path, "utf8")).ackedSourceSeq).toBe(0);
expect(core.store.state.ackedSourceSeq).toBe(0);
}
let drained = false;
const retirement = mode === "drain" ? (async () => {
const retirement = mode === "drain" || mode === "usage_drain" ? (async () => {
await core.stop();
await core.drainPendingConnectionProcessing();
drained = true;
@@ -118,6 +182,9 @@ it.each(["event", "newer_command", "replacement", "write_failure", "drain", "sem
}
if (mode === "replacement") {
replacement = (await authenticate(core, client.leaseToken!))!;
expect(replacement.welcome.payload).toMatchObject({ ackedSourceSeq: 0 });
sendSecure(replacement, event);
expect(await receiveSecure(replacement)).toMatchObject({ kind: "ack", payload: { ackedSourceSeq: 1 } });
const second = structuredClone(event);
const next = second.payload as Record<string, unknown>;
next.sourceSeq = 2;
@@ -130,7 +197,10 @@ it.each(["event", "newer_command", "replacement", "write_failure", "drain", "sem
expect(await receiveSecure(client)).toBeNull();
await retirement;
expect(drained).toBe(true);
} else if (mode === "write_failure") {
} else if (mode === "authority_conflict") {
expect(await receiveSecure(client)).toBeNull();
expect(stagedWrites).toBe(1);
} else if (mode === "write_failure" || mode === "usage_write_failure" || mode === "command_failure") {
expect(await receiveSecure(client)).toBeNull();
expect(() => core.queueCommand("session.snapshot")).toThrow("indeterminate");
} else if (mode !== "replacement") {
@@ -139,16 +209,45 @@ it.each(["event", "newer_command", "replacement", "write_failure", "drain", "sem
await core.stop();
await core.drainPendingConnectionProcessing();
const restored = new DurablePrpControlPlane({ stateDirectory: root, identity,
expectedRunnerVersion, expectedRunnerDigest });
const expectedEvents = mode === "replacement" ? 2 : mode === "write_failure" ? 0 : 1;
expectedRunnerVersion, expectedRunnerDigest, onCommittedEvent: commit });
const expectedEvents = mode === "replacement" ? 2 : mode === "write_failure" || mode === "usage_write_failure" || mode === "authority_conflict" ? 0 : 1;
expect(restored.store.state.ackedSourceSeq).toBe(expectedEvents);
expect(restored.store.state.committedEvents).toHaveLength(expectedEvents);
if (mode === "newer_command") {
if (mode === "newer_command" || mode === "command_burst") {
expect(restored.store.state.commands.some(command => command.commandId === "command_during_event")).toBe(true);
expect(commit).toHaveBeenCalledTimes(1);
expect(stagedWrites).toBe(1);
expect(restored.store.state.committedEvents[0].deliveryCount).toBe(1);
if (mode === "command_burst") {
expect(restored.store.state.commands.some(command => command.commandId === "second_command_during_event")).toBe(true);
}
}
if (mode === "replacement") {
expect(commit).toHaveBeenCalledTimes(3);
expect(effects.size).toBe(2);
}
if (mode === "command_failure") {
expect(restored.store.state.commands.some(command => command.commandId === "failed_command_during_event")).toBe(true);
expect(stagedWrites).toBe(1);
}
if (mode === "drain" || mode === "usage_drain" || mode === "authority_conflict") {
await restored.start();
try {
replacement = (await authenticate(restored, client.leaseToken!))!;
sendSecure(replacement, event);
expect(await receiveSecure(replacement)).toMatchObject({ kind: "ack", payload: { ackedSourceSeq: 1 } });
expect(commit).toHaveBeenCalledTimes(2);
expect(effects.size).toBe(1);
} finally {
replacement?.socket.destroy();
await restored.stop();
await restored.drainPendingConnectionProcessing();
}
}
expect(nodeFs.readdirSync(root).filter(name => name.endsWith(".tmp"))).toEqual([]);
} finally {
release();
restoreCommandSync();
open.mockRestore();
client?.socket.destroy();
replacement?.socket.destroy();
@@ -1204,7 +1204,11 @@ class DurableCoreStore {
#state: StoredCoreState;
#writeIndeterminate = false;
#revision = 0;
#savedRevision = 0;
#pendingEvent: {
buildCandidate: (state: StoredCoreState) => StoredCoreState | null;
isCurrentOwner: () => boolean;
committed: boolean;
} | null = null;
constructor(directory: string, identity: DurableRecoveryIdentity) {
try {
@@ -1242,32 +1246,53 @@ class DurableCoreStore {
save(): void {
this.assertWritable();
const revision = ++this.#revision;
++this.#revision;
try {
atomicPrivateWrite(this.path, `${JSON.stringify(this.#state)}\n`);
this.#savedRevision = revision;
const pending = this.#pendingEvent;
// A command already needs a synchronous write. Include the admitted
// event there, rather than invalidating and repeating its full write.
const withEvent = pending && !pending.committed && pending.isCurrentOwner()
? pending.buildCandidate(this.#state) : null;
const candidate = withEvent ?? this.#state;
atomicPrivateWrite(this.path, `${JSON.stringify(candidate)}\n`);
this.#state = candidate;
if (pending && withEvent) pending.committed = true;
} catch (error) {
this.#writeIndeterminate = true;
throw error;
}
}
async saveEvent(): Promise<void> {
this.assertWritable();
const revision = ++this.#revision;
/** Stage event state privately; publish it only after its durable commit. */
async commitEvent(
buildCandidate: (state: StoredCoreState) => StoredCoreState | null,
isCurrentOwner: () => boolean,
): Promise<boolean> {
if (!isCurrentOwner()) return false;
const pending = { buildCandidate, isCurrentOwner, committed: false };
this.#pendingEvent = pending;
try {
await withStagedPrivateWrite(this.path, `${JSON.stringify(this.#state)}\n`, (temporary) => {
this.assertWritable();
const revision = this.#revision;
const candidate = buildCandidate(this.#state);
if (candidate === null) return false;
await withStagedPrivateWrite(this.path, `${JSON.stringify(candidate)}\n`, (temporary) => {
this.assertWritable();
// A command or replacement connection can persist this event and newer
// authority while its file is staged. Never roll that state back.
if (this.#savedRevision >= revision) return;
if (pending.committed || !isCurrentOwner() || this.#revision !== revision) return;
renameSync(temporary, this.path);
syncParentDirectory(this.path);
this.#savedRevision = revision;
this.#state = candidate;
++this.#revision;
pending.committed = true;
});
// Explicit authority commits do not absorb pending events. On conflict,
// leave the event unacknowledged for replay instead of rewriting in a loop.
return pending.committed;
} catch (error) {
this.#writeIndeterminate = true;
throw error;
} finally {
if (this.#pendingEvent === pending) this.#pendingEvent = null;
}
}
@@ -1281,11 +1306,13 @@ class DurableCoreStore {
/** Persist a complete candidate before publishing any new authority in memory. */
commit(candidate: StoredCoreState): void {
this.assertWritable();
const revision = ++this.#revision;
// An explicit authority transaction owns its complete snapshot. Later
// command writes must not absorb an event admitted before that boundary.
this.#pendingEvent = null;
++this.#revision;
try {
atomicPrivateWrite(this.path, `${JSON.stringify(candidate)}\n`);
this.#state = candidate;
this.#savedRevision = revision;
} catch (error) {
// Rename may already have succeeded before directory fsync failed.
// Never overwrite that possibly durable receipt using stale memory.
@@ -3279,42 +3306,51 @@ export class DurablePrpControlPlane {
return;
}
if (existing !== undefined) {
existing.deliveryCount += 1;
this.#store.state.replayDeliveries += 1;
} else {
if (this.#store.state.committedEvents.length >= maxCommittedEventWindow) {
// The awaited business commit may allow another authenticated owner
// or a tool completion to advance the window. Re-evaluate, never use
// an index sampled before that await to delete a different input.
const currentEviction = this.#store.state.committedEvents.findIndex(
(candidate) => !unsettledSemanticInput(candidate, this.#store.state),
);
if (currentEviction < 0) {
connection.close();
return;
}
this.#store.state.committedEvents.splice(currentEviction, 1);
const buildCandidate = (state: StoredCoreState): StoredCoreState | null => {
const committedEvents = [...state.committedEvents];
const replayIndex = committedEvents.findIndex(
(candidate) => candidate.sourceEventId === sourceEventId,
);
if (replayIndex >= 0) {
const replay = committedEvents[replayIndex];
committedEvents[replayIndex] = {
...replay,
deliveryCount: replay.deliveryCount + 1,
};
return { ...state, committedEvents, replayDeliveries: state.replayDeliveries + 1 };
}
this.#store.state.committedEvents.push({
sourceSeq,
sourceEventId,
eventType,
priority,
envelope: structuredClone(envelope),
deliveryCount: 1,
logicalEffectCount: 1,
if (sourceSeq !== state.ackedSourceSeq + 1) return null;
if (committedEvents.length >= maxCommittedEventWindow) {
// A command can settle an input while this snapshot is staged. Use
// the current response ledger to select an event that can be evicted.
const currentEviction = committedEvents.findIndex(
(candidate) => !unsettledSemanticInput(candidate, state),
);
if (currentEviction < 0) return null;
committedEvents.splice(currentEviction, 1);
}
committedEvents.push({
sourceSeq, sourceEventId, eventType, priority,
envelope: structuredClone(envelope), deliveryCount: 1, logicalEffectCount: 1,
});
this.#store.state.ackedSourceSeq = sourceSeq;
}
// Output deltas have no lifecycle or control effects. Other events must
// become durable before transport readers can observe them in memory.
if (eventType === "item.delta") {
await this.#store.saveEvent();
if (this.#eventOwner !== connection || this.#identity !== identity || this.#protocolIntegrityError !== null) return;
} else {
this.#store.save();
return { ...state, committedEvents, ackedSourceSeq: sourceSeq };
};
const isCurrentOwner = () => this.#eventOwner === connection &&
this.#identity === identity && this.#protocolIntegrityError === null;
if (priority === 0 || isSemanticInput || eventType.startsWith("turn.") || eventType.startsWith("run.")) {
// Critical lifecycle suffixes and tool admission must finish in this
// turn before readers react or a replacement owner adopts their cursor.
const candidate = buildCandidate(this.#store.state);
if (candidate === null) {
connection.close();
return;
}
this.#store.commit(candidate);
} else if (!await this.#store.commitEvent(buildCandidate, isCurrentOwner)) {
if (isCurrentOwner()) connection.close();
return;
}
if (!isCurrentOwner()) return;
if (
isSemanticInput &&
@@ -87,9 +87,43 @@ vi.mock("./installation-integrity.js", () => ({ verifyNativeAcpxInstallation: vi
describe("Copilot build-owned installation", () => {
it("admits the current profile with environment launch preparation", () => {
expect(QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion).toBe(61);
expect(QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion).toBe(63);
expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBeUndefined();
expect(QUALIFIED_ACPX_PROFILES.copilot.commandDigest).toBe("sha256:956276ebee59f880249fa6955adc224af9ca7b6a9da59bcc5da4a8667550c5b3");
expect(QUALIFIED_ACPX_PROFILES.copilot.commandDigest).toBe("sha256:1412842a36a7211d84b6b98a3d1f69e3388bc4814e5825da890a774ae0e3460e");
});
it("preserves both published v62 identities while binding their merged source in v63", async () => {
const current = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v63-identity.json", import.meta.url), "utf8"));
for (const [name, checksum, changed] of [
["copilot-profile-v62-identity.json", "faa4d1b35267b54e134a8e0c84586fe1196d8fad5525cb53aa195aae53ca6e83", ["agentProfileVersion", "profileCompatibilitySourceSha256", "semanticCompletionContractSourceSha256", "semanticContinuationSourceSha256"]],
["copilot-profile-v62-candidate-historical-identity.json", "da3f44a3cfda31cbff558d618e1e9cb1cfb80379b613ff1266e8b866ea666df8", ["agentProfileVersion", "profileCompatibilitySourceSha256", "runtimeRequestBridgeSourceSha256"]],
] as const) {
const bytes = readFileSync(new URL(`../../../test/fixtures/${name}`, import.meta.url));
expect(createHash("sha256").update(bytes).digest("hex")).toBe(checksum);
const prior = JSON.parse(bytes.toString("utf8"));
expect(Object.keys(current.declaration).filter(key => current.declaration[key] !== prior.declaration[key]).sort()).toEqual(changed);
expect(Object.keys(current.declaration).sort()).toEqual(Object.keys(prior.declaration).sort());
const sorted = Object.fromEntries(Object.entries(prior.declaration).sort(([a], [b]) => a.localeCompare(b)));
expect(`sha256:${createHash("sha256").update(JSON.stringify(sorted)).digest("hex")}`).toBe(prior.commandDigest);
expect(isSupportedAcpxProfileVersion("copilot", 62)).toBe(true);
await expect(verifyCopilotInstallation({ ...QUALIFIED_ACPX_PROFILES.copilot,
agentProfileVersion: 62, commandDigest: prior.commandDigest })).rejects.toThrow("exact pinned");
}
});
it("preserves v61 while binding uncertain process checks and controller retirement in v62", async () => {
const priorBytes = readFileSync(new URL("../../../test/fixtures/copilot-profile-v61-identity.json", import.meta.url));
expect(createHash("sha256").update(priorBytes).digest("hex")).toBe("ec3c8561bc123a599a01da356978b73e6d48ab030842af9f0d63d1f30413e1a5");
const prior = JSON.parse(priorBytes.toString("utf8"));
const current = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v62-identity.json", import.meta.url), "utf8"));
expect(prior.commandDigest).toBe("sha256:956276ebee59f880249fa6955adc224af9ca7b6a9da59bcc5da4a8667550c5b3");
expect(Object.keys(current.declaration).filter(key => current.declaration[key] !== prior.declaration[key]).sort()).toEqual([
"agentProfileVersion", "profileCompatibilitySourceSha256", "runtimeRequestBridgeSourceSha256",
]);
expect(Object.keys(current.declaration).sort()).toEqual(Object.keys(prior.declaration).sort());
expect(isSupportedAcpxProfileVersion("copilot", 61)).toBe(true);
await expect(verifyCopilotInstallation({ ...QUALIFIED_ACPX_PROFILES.copilot,
agentProfileVersion: 61, commandDigest: prior.commandDigest })).rejects.toThrow("exact pinned");
});
it("preserves v60 while binding controller journal retirement in v61", async () => {
@@ -48,12 +48,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = {
"protocolVersion": 1,
"acpxVersion": "0.13.1",
"agent": "copilot",
"agentProfileVersion": 61,
"agentProfileVersion": 63,
"agentServerPackage": "@github/copilot",
"agentServerVersion": "1.0.88",
"agentRuntimePackage": null,
"agentRuntimeVersion": null,
"commandDigest": "sha256:956276ebee59f880249fa6955adc224af9ca7b6a9da59bcc5da4a8667550c5b3",
"commandDigest": "sha256:1412842a36a7211d84b6b98a3d1f69e3388bc4814e5825da890a774ae0e3460e",
"permissionPolicy": "interactive"
},
"claude": {
@@ -2,13 +2,13 @@ import { QUALIFIED_ACPX_PROFILE_DATA } from "./generated-profiles.js";
/** Decodable historical profile revisions, not permission to launch them.
* Exact current profile/package/digest admission is checked separately. */
type HistoricalAcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60;
type HistoricalAcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62;
type CurrentAcpxProfileVersion = typeof QUALIFIED_ACPX_PROFILE_DATA[keyof typeof QUALIFIED_ACPX_PROFILE_DATA]["agentProfileVersion"];
export type AcpxProfileVersion = HistoricalAcpxProfileVersion | CurrentAcpxProfileVersion;
const historicalVersions: Readonly<Record<string, readonly HistoricalAcpxProfileVersion[]>> = {
pi: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28], claude: [1, 2, 3, 4, 5], codex: [1, 2, 3, 4, 5],
grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60],
grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62],
cursor: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
};
@@ -25,6 +25,13 @@ describe("controller-owned completion continuation", () => {
.toEqual({ ...yielded, continuation: preparation });
});
it.each([undefined, null])("fills a server-owned published response wait (%s)", async absent => {
const responseWait = { kind: "response_wake", summary: "Wait for the author.", idempotencyKey: "published-review:run:receipt" };
expect(await resolveCompletionContinuation({ ...yielded, continuation: absent }, "run", async () => ({
...context, completionContinuation: responseWait,
}))).toEqual({ ...yielded, continuation: responseWait });
});
it("rechecks a sidecar-resolved workspace continuation against current server authority", async () => {
const preparation = { kind: "same_agent", summary: "Continue with the prepared repository.", idempotencyKey: "repository:task:receipt:run" };
const report = { ...yielded, continuation: preparation };
@@ -15,10 +15,10 @@ export async function resolveCompletionContinuation(
const task = object(context.activeTask);
const continuation = object(context.completionContinuation);
if (object(context.run).id !== runId || task.executionRunId !== runId ||
!["monitor", "same_agent"].includes(String(continuation.kind)) ||
!["monitor", "same_agent", "response_wake"].includes(String(continuation.kind)) ||
typeof continuation.summary !== "string" || !continuation.summary.trim() ||
typeof continuation.idempotencyKey !== "string" || !continuation.idempotencyKey.trim()) {
throw new Error("Cannot yield without a continuation: no eligible saved monitor or workspace continuation exists on this task. Save a monitor for a deferred check, provide an explicit response_wake for a real response wait, or continue the unfinished work. Do not repeat completed actions.");
throw new Error("Cannot yield without a continuation: no eligible saved monitor or workspace continuation or authorized response wait exists on this task. Save a monitor for a deferred check, provide an explicit response_wake for a real response wait, or continue the unfinished work. Do not repeat completed actions.");
}
if (report.continuation != null && (continuation.kind !== "same_agent" || supplied.summary !== continuation.summary ||
supplied.idempotencyKey !== continuation.idempotencyKey)) {
@@ -50,6 +50,65 @@ describe("OpenCode MCP bridge", () => {
});
});
it("delivers a complete large assigned-tool result and replays its receipt without repeating the action", async () => {
const files = Array.from({ length: 27 }, (_, index) => ({
filename: `src/public-fixture-${index}.ts`,
patch: `@@ synthetic public fixture ${index} @@\n${"+ documented change\n".repeat(220)}`,
}));
const data = { items: files, page: 1, hasMore: false, receipt: "LAST_FILE_AND_RECEIPT_INTACT" };
const result = { content: [{ type: "text", text: JSON.stringify(data) }], data };
expect(JSON.stringify(result).length).toBeGreaterThan(111_877);
const handler = vi.fn(async () => result);
const bridge = await startOpenCodeMcpBridge({
tools: [{ name: "paperclip_call_assigned_tool", inputSchema: { type: "object" } }], handler,
});
bridges.push(bridge);
const request = { id: "large-result", method: "tools/call", params: { name: "paperclip_call_assigned_tool", arguments: {} } };
for (let attempt = 0; attempt < 2; attempt++) {
const response = await (await rpc(bridge, request)).json() as { result: { content: Array<{ text: string }> } };
expect(JSON.parse(response.result.content[0]!.text)).toEqual(result);
}
expect(handler).toHaveBeenCalledTimes(1);
});
it("preserves producer-sized pages with UTF-8 and heavily escaped nested data", async () => {
const chunk = '\"\\\n\t\u0000😀';
const result = { responseText: { nextOffsetBytes: 300_000, totalBytes: 600_000 }, data: chunk.repeat(25_000) };
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(500_000);
expect(Buffer.byteLength(JSON.stringify(result))).toBeGreaterThan(64 * 1024);
// The driver returns a controller text item, not the raw app page. Its
// encoded JSON must survive a second layer of escaping at this boundary.
const controllerResult = { text: JSON.stringify(result), type: "inputText" };
expect(Buffer.byteLength(JSON.stringify(controllerResult))).toBeGreaterThan(500_000);
const bridge = await startOpenCodeMcpBridge({
tools: [{ name: "read_tool_result", inputSchema: { type: "object" } }], handler: async () => controllerResult,
});
bridges.push(bridge);
const response = await (await rpc(bridge, { id: "page", method: "tools/call", params: { name: "read_tool_result", arguments: {} } })).json() as { result: { content: Array<{ text: string }> } };
const delivered = JSON.parse(response.result.content[0]!.text) as typeof controllerResult;
expect(delivered).toEqual(controllerResult);
expect(JSON.parse(delivered.text)).toEqual(result);
});
it.each([
["UTF-8 scalar", () => ({ data: "😀".repeat(300_000) })],
["escaped scalar", () => ({ data: "\u0000".repeat(200_000) })],
["many fields", () => Array.from({ length: 600_000 }, () => 0)],
])("rejects an oversized %s without a partial success or repeating the completed call", async (_name, makeResult) => {
const handler = vi.fn(async () => makeResult());
const bridge = await startOpenCodeMcpBridge({
tools: [{ name: "assigned.write", inputSchema: { type: "object" } }], handler,
});
bridges.push(bridge);
const request = { id: "write-receipt", method: "tools/call", params: { name: "assigned.write", arguments: {} } };
for (let attempt = 0; attempt < 2; attempt++) {
expect(await (await rpc(bridge, request)).json()).toMatchObject({
result: { isError: true, content: [{ text: expect.stringContaining("may already have completed; do not repeat it") }] },
});
}
expect(handler).toHaveBeenCalledTimes(1);
});
it("admits runner-private extension operations without advertising them to the model", async () => {
const handler = vi.fn(async ({ tool }) => ({ decision: tool === "__paperclip_permission" ? "accept" : "decline" }));
const bridge = await startOpenCodeMcpBridge({
@@ -44,6 +44,9 @@ export interface OpenCodeMcpBridge {
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_BODY_BYTES = 1_048_576;
// Native app results/pages are capped at 500 KB before reaching this bridge.
// Leave room for their delivery envelope, but never cut a completed JSON value.
const MAX_RESULT_BYTES = 1_048_576;
export function canonicalOpenCodeMcpToolName(name: string): string {
const trimmed = name.trim();
@@ -348,8 +351,39 @@ function safeError(error: unknown): string {
}
function safeJson(value: unknown): string {
const serialized = JSON.stringify(value);
return (serialized ?? "null").slice(0, 64 * 1024);
const tooLarge = () => new Error(
"Tool result delivery exceeded the 1 MiB MCP limit. The action may already have completed; do not repeat it. Reconcile its saved result or receipt instead.",
);
// Separator accounting is conservative (it includes the first entry too).
// Twice the output limit admits every result within the exact byte cap.
let budget = 2 * MAX_RESULT_BYTES;
let root = true;
const charge = (text: string) => {
// Check length before measuring UTF-8 so even a huge scalar is rejected
// without copying it. JSON escaping can expand the final value further.
if (text.length > budget) throw tooLarge();
budget -= Buffer.byteLength(text);
if (budget < 0) throw tooLarge();
};
const serialized = JSON.stringify(value, function (key, entry: unknown) {
const first = root;
root = false;
const scalar = entry === null || typeof entry !== "object";
const omitted = entry === undefined || typeof entry === "function" || typeof entry === "symbol";
if (omitted && !Array.isArray(this)) return entry;
if (!first) {
charge(",");
if (!Array.isArray(this)) { charge(key); charge('"":'); }
}
if (typeof entry === "string" || entry instanceof String) { charge(String(entry)); charge('""'); }
else if (!scalar) charge("{}");
else charge(omitted ? "null" : JSON.stringify(entry) ?? "null");
return entry;
}) ?? "null";
// The traversal budget bounds allocation even for many small fields. This
// exact check also accounts for quotes, control characters and UTF-8 bytes.
if (Buffer.byteLength(serialized) > MAX_RESULT_BYTES) throw tooLarge();
return serialized;
}
function canonicalJson(value: unknown): string {
@@ -2184,12 +2184,13 @@ describe("OpenCodeServerDriver", () => {
await session.close({ reason: "test" });
});
it.each([true, false])("resolves an omitted continuation through the real OpenCode MCP boundary only with a saved monitor: %s", async eligible => {
it.each(["monitor", "response_wake"] as const)("resolves an omitted %s through the real OpenCode MCP boundary only from current server state", async kind => {
for (const eligible of [true, false]) {
await chmod(fixture, 0o755);
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-monitor-"));
const workspace = await mkdtemp(join(tmpdir(), "paperclip-opencode-monitor-workspace-"));
roots.push(root, workspace);
const continuation = { kind: "monitor", summary: "Wait for the saved task monitor.", idempotencyKey: "task-monitor:saved" };
const continuation = { kind, summary: "Wait for the saved task path.", idempotencyKey: "task-wait:saved" };
const reads: string[] = [];
const accepted: unknown[] = [];
const driver = new OpenCodeServerDriver({
@@ -2216,7 +2217,8 @@ describe("OpenCodeServerDriver", () => {
expect(events.filter(event => event.eventType === "run.result.proposed")).toEqual([]);
expect((await session.snapshot()).semanticResult).toBeNull();
}
} finally { await session.close({ reason: "monitor default test complete" }); }
} finally { await session.close({ reason: "saved wait default test complete" }); }
}
});
it("keeps assigned discovery operation IDs at the authenticated MCP and controller boundary", async () => {
@@ -8322,6 +8322,7 @@ async function verifyLiveRunnerAdoption(
goalMidTurn = false,
detachBeforeCleanup = false,
startWithoutCheckpoint = false,
uncertainAtClose = false,
) {
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-live-adopt-"));
const server = createServer();
@@ -8344,7 +8345,7 @@ async function verifyLiveRunnerAdoption(
authority = next;
return {
connectUrl: `ws://127.0.0.1:${address.port}/runner`,
...(mismatchedArtifact ? { checkpoint } : {}),
...(mismatchedArtifact || uncertainAtClose ? { checkpoint } : {}),
release: async () => {
if (authority === next) authority = null;
},
@@ -8371,6 +8372,7 @@ async function verifyLiveRunnerAdoption(
let runnerPid: number | null = null;
let adopted: ReturnType<typeof createCapabilityRunnerdCodexTransport> | null =
null;
let restoreIntervalSpies: () => void = () => undefined;
try {
let opened: Record<string, unknown>;
try {
@@ -8438,8 +8440,14 @@ async function verifyLiveRunnerAdoption(
});
const openedThread = opened.thread as Record<string, unknown>;
const signal = vi.fn(() => true);
const probeError = new Error("fixture remote process identity is unavailable");
let rejectLiveness = false;
const intervals = uncertainAtClose ? vi.spyOn(globalThis, "setInterval") : null;
const clearedIntervals = uncertainAtClose ? vi.spyOn(globalThis, "clearInterval") : null;
restoreIntervalSpies = () => { intervals?.mockRestore(); clearedIntervals?.mockRestore(); };
adopted = createCapabilityRunnerdCodexTransport({
...sharedOptions,
...(uncertainAtClose ? { closeGraceMs: 2_000 } : {}),
// Hash different stable bytes without replacing the real runner artifact
// used by concurrent tests. Adoption must never execute this path.
...(mismatchedArtifact
@@ -8462,6 +8470,7 @@ async function verifyLiveRunnerAdoption(
startedAt: new Date().toISOString(),
signal,
isAlive: () => {
if (rejectLiveness) return Promise.reject(probeError);
try {
process.kill(runnerPid!, 0);
return true;
@@ -8540,6 +8549,30 @@ async function verifyLiveRunnerAdoption(
expect(observed.params).toMatchObject({ threadId: "codex-thread-1", turnId: "provider-goal-turn-1" });
}
expect(duplicateLauncher).not.toHaveBeenCalled();
if (uncertainAtClose) {
const before = JSON.parse(await readFile(controlPlaneStatePath, "utf8"));
const retainedAuthority = authority as DurablePrpControlPlane | null;
rejectLiveness = true;
await expect(adopted.transport.close()).rejects.toBe(probeError);
expect(retainedAuthority?.activeRunnerConnectionCount()).toBe(0);
expect(intervals!.mock.results.length).toBeGreaterThan(0);
for (const interval of intervals!.mock.results) if (interval.type === "return") expect(clearedIntervals).toHaveBeenCalledWith(interval.value);
const notificationsClosed = (async () => { for await (const _event of adopted!.transport.notifications()) {} return true; })();
let queueDeadline: ReturnType<typeof setTimeout> | undefined;
try {
expect(await Promise.race([notificationsClosed, new Promise<boolean>(resolve => { queueDeadline = setTimeout(() => resolve(false), 250); })])).toBe(true);
} finally { clearTimeout(queueDeadline); }
await expect(adopted.transport.close()).rejects.toBe(probeError);
expect(adopted.transport.processInfo()).toMatchObject({ exited: false });
expect(() => process.kill(runnerPid!, 0)).not.toThrow();
expect(signal).not.toHaveBeenCalled();
expect(checkpoint).not.toHaveBeenCalled();
expect(duplicateLauncher).not.toHaveBeenCalled();
const retained = JSON.parse(await readFile(controlPlaneStatePath, "utf8"));
expect(retained.identity).toEqual(before.identity);
expect(retained.commands).toEqual(before.commands);
return;
}
expect(adopted.evidence().diagnostics).toContain(
`adopted runner ${runnerPid} authenticated to its durable PRP authority`,
);
@@ -8563,6 +8596,15 @@ async function verifyLiveRunnerAdoption(
}
} finally {
await adopted?.transport.close().catch(() => undefined);
if (uncertainAtClose) {
const providerPid = adopted?.evidence().codexPid;
if (providerPid) {
try { process.kill(providerPid, "SIGKILL"); }
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
}
await (authority as DurablePrpControlPlane | null)?.stop();
}
restoreIntervalSpies();
if (runnerPid) {
try {
process.kill(-runnerPid, "SIGKILL");
@@ -8586,6 +8628,8 @@ it(
30_000,
);
it("retains authenticated adopted-runner ownership when a close probe rejects", () => verifyLiveRunnerAdoption(false, false, false, false, false, true), 30_000);
it(
"blocks adopted runner artifact drift without duplicate launch, checkpoint replacement, or process signals",
() => verifyLiveRunnerAdoption(false, true),
@@ -4513,6 +4513,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
this.#closed = true;
this.#resolveClosedSignal();
this.#turnStartAdmission?.resolve(false);
await this.#retireControllerForRecovery(deadline);
this.#handle = null;
this.#diagnostic(
"controller authority detached for restart; durable runner left alive",
);
}
async #retireControllerForRecovery(deadline: number): Promise<void> {
if (this.#pump !== null) clearInterval(this.#pump);
this.#pump = null;
if (this.#adoptedRunnerMonitor !== null)
@@ -4523,21 +4531,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
this.#controlPlaneRelease = null;
await Promise.resolve(release?.("detach")).catch((error: unknown) => {
this.#diagnostic(
`controller route release failed during restart detach: ${String(error)}`,
`controller route release failed during retirement: ${String(error)}`,
);
});
// A successor must not share this journal with an admitted async write.
// A timeout rejects detachment, including repeated calls, instead of
// reporting that the old writer has retired.
try {
await this.#stopAndDrainAuthority(deadline);
} finally {
this.#queue.close();
}
this.#handle = null;
this.#diagnostic(
"controller authority detached for restart; durable runner left alive",
);
}
#trackStartup<T>(start: () => Promise<T>): Promise<T> {
@@ -4557,6 +4558,20 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
}
async #closeOnce(): Promise<void> {
const deadline = Date.now() + runnerCloseGraceMs(this.options);
try {
await this.#closeAndSettle();
} catch (error) {
this.#queue.close();
try { await this.#retireControllerForRecovery(deadline); }
catch (retirementError) {
this.#diagnostic(`controller retirement after failed close is unconfirmed: ${String(retirementError)}`);
}
throw error;
}
}
async #closeAndSettle(): Promise<void> {
this.#closed = true;
this.#resolveClosedSignal();
const { preparationDeadline, closeDeadline } = runnerCloseDeadlines(Date.now(), runnerCloseGraceMs(this.options));
@@ -6898,11 +6913,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
if (this.#handle) return this.#handle.isExitConfirmed?.() ?? this.#handle.child.exitCode !== null;
const adoptedRunner = this.options.adoptExistingRunner;
if (!adoptedRunner) return true;
try {
return !(await adoptedRunner.isAlive());
} catch {
return true;
}
return !(await adoptedRunner.isAlive());
}
#watchAdoptedRunner(
@@ -1,8 +1,11 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, resolve } from "node:path";
import { dirname, join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { pathToFileURL } from "node:url";
import test from "node:test";
const runnerPackage = JSON.parse(
@@ -217,3 +220,39 @@ test("the Claude patch removes ambient project and local configuration", () => {
);
}
});
test("Claude preserves user permission modes when its working directory is home", async (t) => {
const packagePath = createRequire(import.meta.url).resolve("@agentclientprotocol/claude-agent-acp/package.json");
const settingsModule = pathToFileURL(resolve(dirname(packagePath), "dist/settings.js")).href;
const root = await mkdtemp(join(tmpdir(), "claude-settings-origin-"));
t.after(() => rm(root, { recursive: true, force: true }));
const home = join(root, "home");
const project = join(root, "project");
await mkdir(join(home, ".claude"), { recursive: true });
await mkdir(join(project, ".claude"), { recursive: true });
const userFile = join(home, ".claude/settings.json");
const env = { ...process.env, HOME: home };
delete env.CLAUDE_CONFIG_DIR;
delete env.PAPERCLIP_ACPX_ISOLATED_CONTEXT;
const inspect = (cwd) => JSON.parse(execFileSync(process.execPath, ["--input-type=module", "-e", `
import { SettingsManager } from ${JSON.stringify(settingsModule)};
const manager = new SettingsManager(${JSON.stringify(cwd)});
try {
await manager.initialize();
console.log(JSON.stringify(manager.getSettings()));
} finally { manager.dispose(); }
`], { env, encoding: "utf8", timeout: 10_000 }));
for (const defaultMode of ["bypassPermissions", "acceptEdits", "auto", "plan", "default"]) {
const content = JSON.stringify({ permissions: { defaultMode, deny: ["Read(./private)"] } });
await writeFile(userFile, content);
assert.deepEqual(inspect(home).permissions, { defaultMode, deny: ["Read(./private)"] });
assert.equal(await readFile(userFile, "utf8"), content, "discovery does not rewrite the profile");
}
await writeFile(userFile, JSON.stringify({ permissions: { defaultMode: "bypassPermissions" } }));
for (const defaultMode of ["bypassPermissions", "acceptEdits", "auto"]) {
await writeFile(join(project, ".claude/settings.json"), JSON.stringify({ permissions: { defaultMode } }));
assert.equal(inspect(project).permissions?.defaultMode, undefined, "real project escalation stays filtered");
}
await writeFile(join(home, ".claude/settings.local.json"), JSON.stringify({ permissions: { defaultMode: "plan" } }));
assert.equal(inspect(home).permissions.defaultMode, "plan", "local restrictions still win");
});
@@ -0,0 +1,85 @@
{
"commandDigest": "sha256:1251b53cb4716273c74e5839eb112ef8ca639e0967eb90a9f1a5f5ddafdb642c",
"declaration": {
"schema": "paperclip.acpx_profile_declaration.v1",
"agent": "copilot",
"agentProfileVersion": 62,
"acpxVersion": "0.13.1",
"agentServerVersion": "1.0.88",
"protocolPolicyRevision": "copilot-agent-manual-v1",
"acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1",
"policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3",
"distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107",
"agentFilesBinding": "registered-runtime-context-v1",
"systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1",
"sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",
"innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a",
"upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0",
"patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679",
"messageIdentityContract": "copilot-native-message-id-v1",
"ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1",
"permissionContextContract": "copilot-edit-permission-context-v1",
"permissionContextSourceSha256": "de2d38d702b3c574161af0c0c04790fb6f6347916eb3916ce7a131a8c229121b",
"permissionAdapterSourceSha256": "ee5929ed2ee647ad0369465dee9d51a00b2dd28e1ff735b43e969ddc9c164668",
"permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9",
"permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f",
"permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4",
"semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2",
"semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791",
"semanticBridgeSourceSha256": "8764b8c9032fdc7d1415b01e75a9fc57c550e7a5e11da4bed7d9100082872ae5",
"toolEvidenceSourceSha256": "6eef5039afc75bb851eaf9cd82a6f099e4bd398ca2deb59dd66f5b2a81a7a706",
"semanticNormalizedInputContract": "validated-forwarded-input-commit-v1",
"semanticSidecarSourceSha256": "17361d1782c0dcebb2b7972635f45c890f2a4081f8bc0ef2d2276550e0b91629",
"semanticDirectDriverSourceSha256": "ff572638f2cb5d9f8249ff8e2f412311c1e3af209ef0bf7e5ea9f10a21d91103",
"semanticValidationSourceSha256": "02fbb92681c78c5de5d2f1aae25aabc25a0e5df6b0ff4baccac652192a8da975",
"semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e",
"semanticCompletionContractSourceSha256": "f49398b682a5623812f5d3c33d6bb9a749008e47cc0ed969072041615f66df59",
"semanticValidatorsSourceSha256": "f22d9caf2035b600abc1a6625ae23ca97f1409d7e29ed5b7264bb8f9784c7dc9",
"semanticSchemaBundleSourceSha256": "016391a087cc217aafed4ba1f4efafc6e4881a7525952dce824b7f4d24530603",
"semanticSidecarProtocolSourceSha256": "03c0c95b900f9dc18f29f6be27b8c79bc0bcab29780190d46a74e95328081236",
"semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1",
"displayEventSourceSha256": "d72f9a6035c247bc6a42c067c05753076c54322c4b58984e93922f3325dc6877",
"displayProjectionSourceSha256": "75952606b26dd93bbc582c1f0a4424487377272ea745fb3a27ceae031fd5dc7e",
"configuredEnvironmentSourceSha256": "5c9008d121979a3a8987e6b8a5752172eafdc4a2b5d725a73f3bbb8fb83be8ff",
"configuredEnvironmentRustSourceSha256": "85c87fae62b8a9377e4f0a4c00302c7519fae4397b1c48253f8f2b7ba7faf994",
"profileActivitySourceSha256": "4fdb6b0f9125fd8372ba6f27945fa5c8a3d3b2ec891df544092e3dc7a75d5282",
"profileExtensionsSourceSha256": "a80ddc95eb4505095bfdbbf85c758199949ab20be9c84b34c77f762eb7180571",
"profileInstallationSourceSha256": "3e61c4cdd4b78e38fcb16eaadae4f1fd65ce3c7127184ea7a80948c8e5d77f88",
"attachmentPolicySourceSha256": "4f7638b7cc64e18f6a4ba33fd46de2b3d49225e32aeab41f5c695b268fa4f8e2",
"singleReadEvidenceSourceSha256": "4069393405089bde613cecec04f5123c426594811da4c668bd96f0e7e283550f",
"nativeSessionRuntimeSourceSha256": "1fe6fa9e6b96d84d70432b85a57c473f833606d4a521563d5022b4d3c41576ce",
"nativeRuntimeContextSourceSha256": "71607f80dbb8dc5cc6c123d0b8f3995d6c5407277695a8c82cbedc90fb8f4842",
"nativeRuntimePromptsSourceSha256": "103b83066da72434602e9e461e6278dfb40bb993d2f3b49b2e93df81bbb08b72",
"nativeSessionContractSourceSha256": "22a8c96ce41ba4f03e976fc37f0cc7c5d05cee99fa789941da31ee1dab440b90",
"harnessSessionContractSourceSha256": "03f4cd7f76f34f6d82e009b66aa51f18f6e23dc235b660778060e35b6ea07412",
"harnessBackendSourceSha256": "dc827e281ae6731545b166ee4d709a4f67f594a556dcbe63c70fe8f1aca26249",
"harnessSessionSourceSha256": "81361733e86b56dd5a66415aefc6f72e69be24acc8d3417370154ebb7fef6e94",
"transportContractSourceSha256": "03fca93d36a89b0cc0917335e293ad097fdf04356d21b307827bb0ea4c13f523",
"nativeBackendSourceSha256": "e7b12d4418c7a71f5f2474b046697d3009eae3613b284bec381df5e9965a1c37",
"nativeBackendFactorySourceSha256": "7e431c926b76d53c4c08e3a4105353dcd34bd940f6588a1a68f79631f6feeb44",
"nativeInstructionsSourceSha256": "9173ebccf09cb56a781d2bf5c7eb27fdafb13d3450d99342c6aff86b42d6b43a",
"providerLaunchSourceSha256": "fa8db1c42c378898287c141d8cea9069166981e369c9b9c51422cb6177de5a2c",
"launchPreparationStoreSourceSha256": "ff6025568bbc0aa6ce545772d73dfca2d3da226740bd3a7b386b069e76cff296",
"runtimeRequestBridgeSourceSha256": "e6c98128d98a4177c42d68a04c1f749554fd5ec844da1bbbdb3f682670189445",
"runtimeRequestFacadeSourceSha256": "d0ed28e0c5ddad34db8f437e704c8a755eb0b47f27e08e44185f66d1d2205295",
"runtimeRequestNotificationSourceSha256": "6196c6175f11c69295dc00fc773201f4fdeca26c500653870253c43b81e65211",
"guardedInstallationSourceSha256": "56a177d3e702914818dca4ca50e061f0d25f988bfc4c0582c36ce23c1696d82f",
"nativeExecutionSourceSha256": "3a30d52bffad68c7f02349193be84761050eb99039fc0556c2b449891a36e918",
"profileCompatibilitySourceSha256": "be60656e66d7f61a290f8d1c9a3c9ec511fb13b6541825a087b470e971ccc020",
"installationSourceSha256": "a1c7c6f103b898216973e77ffbac0ef7572e250aa574d1a4065270e9dfa0dc2d",
"assetOwnershipSourceSha256": "1785e3f31e5dad5a13b53e25d8cf9482a9bd89a27b6c127830aed6b81acc605c",
"assetInstallerSourceSha256": "d3bd9514e5920d0cc3567aa50487fb534c57a6f66b8da0d3f22c5f6e499c841f",
"credentialBindingSourceSha256": "7586d44b47c83395498dc8806287cd3538ef58177ba7c5949f5766ed105a0161",
"sidecarErrorSourceSha256": "b09af4577f8bf42eee7036b2ad9842202cfc763e72b53c3287f82c6090cdad80",
"profileSourceSha256": "f5538b3dbefa7634a332b87d5ededcefb56aa7e5790cede1c7a0d948a548a456",
"metadataProbeSourceSha256": "be4c8416edd27061109bc1f33d0c26071b4facbb3f651beaae6b3c0275cce727",
"permissionToolIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1",
"semanticContinuationSourceSha256": "c9cc0fd516b3df92a6655f56ee9bef37615a889c371e2e137d8ac5c1176de811",
"runtimeHostSourceSha256": "94a73749267f5a80b5df19413a65b4b9263c00a9bf7e98fda00f00b8f9fd32ec",
"runtimeAdapterSourceSha256": "e4c764c2c3c7dd655a965b39472bd1ad8d577d1e7258b25594b171c9429752b8",
"runtimeSandboxSourceSha256": "92dfa53f5a3ed0062913ae417eeccec243b430d444495efde2a8e9c4c02e78ea",
"cancellationSourceSha256": "a07d1a9e982dec0ae130c1ad1efa5bc75c6a39e013b730ba3ee45256f09ceeca",
"agentFilesSourceSha256": "fb32f6badc13dfa22f231479509b631b2f0eba0c99b1ab9f3cd5c0c601aa03ba",
"nativeDistributionSourceSha256": "aed327c389e957483a503cb1bb8b247ee7cd7ff4b528fb4567c39bcb4577690b"
}
}
@@ -0,0 +1,85 @@
{
"commandDigest": "sha256:aeeb80bc186569c78911aeaa445c1fdf5e81420cfeadb563d5620497c58dd0f4",
"declaration": {
"schema": "paperclip.acpx_profile_declaration.v1",
"agent": "copilot",
"agentProfileVersion": 62,
"acpxVersion": "0.13.1",
"agentServerVersion": "1.0.88",
"protocolPolicyRevision": "copilot-agent-manual-v1",
"acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1",
"policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3",
"distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107",
"agentFilesBinding": "registered-runtime-context-v1",
"systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1",
"sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",
"innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a",
"upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0",
"patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679",
"messageIdentityContract": "copilot-native-message-id-v1",
"ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1",
"permissionContextContract": "copilot-edit-permission-context-v1",
"permissionContextSourceSha256": "de2d38d702b3c574161af0c0c04790fb6f6347916eb3916ce7a131a8c229121b",
"permissionAdapterSourceSha256": "ee5929ed2ee647ad0369465dee9d51a00b2dd28e1ff735b43e969ddc9c164668",
"permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9",
"permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f",
"permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4",
"semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2",
"semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791",
"semanticBridgeSourceSha256": "8764b8c9032fdc7d1415b01e75a9fc57c550e7a5e11da4bed7d9100082872ae5",
"toolEvidenceSourceSha256": "6eef5039afc75bb851eaf9cd82a6f099e4bd398ca2deb59dd66f5b2a81a7a706",
"semanticNormalizedInputContract": "validated-forwarded-input-commit-v1",
"semanticSidecarSourceSha256": "17361d1782c0dcebb2b7972635f45c890f2a4081f8bc0ef2d2276550e0b91629",
"semanticDirectDriverSourceSha256": "ff572638f2cb5d9f8249ff8e2f412311c1e3af209ef0bf7e5ea9f10a21d91103",
"semanticValidationSourceSha256": "02fbb92681c78c5de5d2f1aae25aabc25a0e5df6b0ff4baccac652192a8da975",
"semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e",
"semanticCompletionContractSourceSha256": "3343df6362252d44d12b079ff78c8f6539d1544f3ce5ec36ff36db70ab0fac31",
"semanticValidatorsSourceSha256": "f22d9caf2035b600abc1a6625ae23ca97f1409d7e29ed5b7264bb8f9784c7dc9",
"semanticSchemaBundleSourceSha256": "016391a087cc217aafed4ba1f4efafc6e4881a7525952dce824b7f4d24530603",
"semanticSidecarProtocolSourceSha256": "03c0c95b900f9dc18f29f6be27b8c79bc0bcab29780190d46a74e95328081236",
"semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1",
"displayEventSourceSha256": "d72f9a6035c247bc6a42c067c05753076c54322c4b58984e93922f3325dc6877",
"displayProjectionSourceSha256": "75952606b26dd93bbc582c1f0a4424487377272ea745fb3a27ceae031fd5dc7e",
"configuredEnvironmentSourceSha256": "5c9008d121979a3a8987e6b8a5752172eafdc4a2b5d725a73f3bbb8fb83be8ff",
"configuredEnvironmentRustSourceSha256": "85c87fae62b8a9377e4f0a4c00302c7519fae4397b1c48253f8f2b7ba7faf994",
"profileActivitySourceSha256": "4fdb6b0f9125fd8372ba6f27945fa5c8a3d3b2ec891df544092e3dc7a75d5282",
"profileExtensionsSourceSha256": "a80ddc95eb4505095bfdbbf85c758199949ab20be9c84b34c77f762eb7180571",
"profileInstallationSourceSha256": "3e61c4cdd4b78e38fcb16eaadae4f1fd65ce3c7127184ea7a80948c8e5d77f88",
"attachmentPolicySourceSha256": "4f7638b7cc64e18f6a4ba33fd46de2b3d49225e32aeab41f5c695b268fa4f8e2",
"singleReadEvidenceSourceSha256": "4069393405089bde613cecec04f5123c426594811da4c668bd96f0e7e283550f",
"nativeSessionRuntimeSourceSha256": "1fe6fa9e6b96d84d70432b85a57c473f833606d4a521563d5022b4d3c41576ce",
"nativeRuntimeContextSourceSha256": "71607f80dbb8dc5cc6c123d0b8f3995d6c5407277695a8c82cbedc90fb8f4842",
"nativeRuntimePromptsSourceSha256": "103b83066da72434602e9e461e6278dfb40bb993d2f3b49b2e93df81bbb08b72",
"nativeSessionContractSourceSha256": "22a8c96ce41ba4f03e976fc37f0cc7c5d05cee99fa789941da31ee1dab440b90",
"harnessSessionContractSourceSha256": "03f4cd7f76f34f6d82e009b66aa51f18f6e23dc235b660778060e35b6ea07412",
"harnessBackendSourceSha256": "dc827e281ae6731545b166ee4d709a4f67f594a556dcbe63c70fe8f1aca26249",
"harnessSessionSourceSha256": "81361733e86b56dd5a66415aefc6f72e69be24acc8d3417370154ebb7fef6e94",
"transportContractSourceSha256": "03fca93d36a89b0cc0917335e293ad097fdf04356d21b307827bb0ea4c13f523",
"nativeBackendSourceSha256": "e7b12d4418c7a71f5f2474b046697d3009eae3613b284bec381df5e9965a1c37",
"nativeBackendFactorySourceSha256": "7e431c926b76d53c4c08e3a4105353dcd34bd940f6588a1a68f79631f6feeb44",
"nativeInstructionsSourceSha256": "9173ebccf09cb56a781d2bf5c7eb27fdafb13d3450d99342c6aff86b42d6b43a",
"providerLaunchSourceSha256": "fa8db1c42c378898287c141d8cea9069166981e369c9b9c51422cb6177de5a2c",
"launchPreparationStoreSourceSha256": "ff6025568bbc0aa6ce545772d73dfca2d3da226740bd3a7b386b069e76cff296",
"runtimeRequestBridgeSourceSha256": "9be35e006ffffcca48205f9e53548dd453ec6a8cbcf0aa4dd735194e9619dfc7",
"runtimeRequestFacadeSourceSha256": "d0ed28e0c5ddad34db8f437e704c8a755eb0b47f27e08e44185f66d1d2205295",
"runtimeRequestNotificationSourceSha256": "6196c6175f11c69295dc00fc773201f4fdeca26c500653870253c43b81e65211",
"guardedInstallationSourceSha256": "56a177d3e702914818dca4ca50e061f0d25f988bfc4c0582c36ce23c1696d82f",
"nativeExecutionSourceSha256": "3a30d52bffad68c7f02349193be84761050eb99039fc0556c2b449891a36e918",
"profileCompatibilitySourceSha256": "be60656e66d7f61a290f8d1c9a3c9ec511fb13b6541825a087b470e971ccc020",
"installationSourceSha256": "a1c7c6f103b898216973e77ffbac0ef7572e250aa574d1a4065270e9dfa0dc2d",
"assetOwnershipSourceSha256": "1785e3f31e5dad5a13b53e25d8cf9482a9bd89a27b6c127830aed6b81acc605c",
"assetInstallerSourceSha256": "d3bd9514e5920d0cc3567aa50487fb534c57a6f66b8da0d3f22c5f6e499c841f",
"credentialBindingSourceSha256": "7586d44b47c83395498dc8806287cd3538ef58177ba7c5949f5766ed105a0161",
"sidecarErrorSourceSha256": "b09af4577f8bf42eee7036b2ad9842202cfc763e72b53c3287f82c6090cdad80",
"profileSourceSha256": "f5538b3dbefa7634a332b87d5ededcefb56aa7e5790cede1c7a0d948a548a456",
"metadataProbeSourceSha256": "be4c8416edd27061109bc1f33d0c26071b4facbb3f651beaae6b3c0275cce727",
"permissionToolIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1",
"semanticContinuationSourceSha256": "d248e47a0fe7f2536d1e64cea0b0b410f34104800cd643d995b4473104ecc8e0",
"runtimeHostSourceSha256": "94a73749267f5a80b5df19413a65b4b9263c00a9bf7e98fda00f00b8f9fd32ec",
"runtimeAdapterSourceSha256": "e4c764c2c3c7dd655a965b39472bd1ad8d577d1e7258b25594b171c9429752b8",
"runtimeSandboxSourceSha256": "92dfa53f5a3ed0062913ae417eeccec243b430d444495efde2a8e9c4c02e78ea",
"cancellationSourceSha256": "a07d1a9e982dec0ae130c1ad1efa5bc75c6a39e013b730ba3ee45256f09ceeca",
"agentFilesSourceSha256": "fb32f6badc13dfa22f231479509b631b2f0eba0c99b1ab9f3cd5c0c601aa03ba",
"nativeDistributionSourceSha256": "aed327c389e957483a503cb1bb8b247ee7cd7ff4b528fb4567c39bcb4577690b"
}
}
@@ -0,0 +1,85 @@
{
"commandDigest": "sha256:1412842a36a7211d84b6b98a3d1f69e3388bc4814e5825da890a774ae0e3460e",
"declaration": {
"schema": "paperclip.acpx_profile_declaration.v1",
"agent": "copilot",
"agentProfileVersion": 63,
"acpxVersion": "0.13.1",
"agentServerVersion": "1.0.88",
"protocolPolicyRevision": "copilot-agent-manual-v1",
"acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1",
"policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3",
"distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107",
"agentFilesBinding": "registered-runtime-context-v1",
"systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1",
"sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",
"innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a",
"upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0",
"patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679",
"messageIdentityContract": "copilot-native-message-id-v1",
"ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1",
"permissionContextContract": "copilot-edit-permission-context-v1",
"permissionContextSourceSha256": "de2d38d702b3c574161af0c0c04790fb6f6347916eb3916ce7a131a8c229121b",
"permissionAdapterSourceSha256": "ee5929ed2ee647ad0369465dee9d51a00b2dd28e1ff735b43e969ddc9c164668",
"permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9",
"permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f",
"permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4",
"semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2",
"semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791",
"semanticBridgeSourceSha256": "8764b8c9032fdc7d1415b01e75a9fc57c550e7a5e11da4bed7d9100082872ae5",
"toolEvidenceSourceSha256": "6eef5039afc75bb851eaf9cd82a6f099e4bd398ca2deb59dd66f5b2a81a7a706",
"semanticNormalizedInputContract": "validated-forwarded-input-commit-v1",
"semanticSidecarSourceSha256": "17361d1782c0dcebb2b7972635f45c890f2a4081f8bc0ef2d2276550e0b91629",
"semanticDirectDriverSourceSha256": "ff572638f2cb5d9f8249ff8e2f412311c1e3af209ef0bf7e5ea9f10a21d91103",
"semanticValidationSourceSha256": "02fbb92681c78c5de5d2f1aae25aabc25a0e5df6b0ff4baccac652192a8da975",
"semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e",
"semanticCompletionContractSourceSha256": "f49398b682a5623812f5d3c33d6bb9a749008e47cc0ed969072041615f66df59",
"semanticValidatorsSourceSha256": "f22d9caf2035b600abc1a6625ae23ca97f1409d7e29ed5b7264bb8f9784c7dc9",
"semanticSchemaBundleSourceSha256": "016391a087cc217aafed4ba1f4efafc6e4881a7525952dce824b7f4d24530603",
"semanticSidecarProtocolSourceSha256": "03c0c95b900f9dc18f29f6be27b8c79bc0bcab29780190d46a74e95328081236",
"semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1",
"displayEventSourceSha256": "d72f9a6035c247bc6a42c067c05753076c54322c4b58984e93922f3325dc6877",
"displayProjectionSourceSha256": "75952606b26dd93bbc582c1f0a4424487377272ea745fb3a27ceae031fd5dc7e",
"configuredEnvironmentSourceSha256": "5c9008d121979a3a8987e6b8a5752172eafdc4a2b5d725a73f3bbb8fb83be8ff",
"configuredEnvironmentRustSourceSha256": "85c87fae62b8a9377e4f0a4c00302c7519fae4397b1c48253f8f2b7ba7faf994",
"profileActivitySourceSha256": "4fdb6b0f9125fd8372ba6f27945fa5c8a3d3b2ec891df544092e3dc7a75d5282",
"profileExtensionsSourceSha256": "a80ddc95eb4505095bfdbbf85c758199949ab20be9c84b34c77f762eb7180571",
"profileInstallationSourceSha256": "3e61c4cdd4b78e38fcb16eaadae4f1fd65ce3c7127184ea7a80948c8e5d77f88",
"attachmentPolicySourceSha256": "4f7638b7cc64e18f6a4ba33fd46de2b3d49225e32aeab41f5c695b268fa4f8e2",
"singleReadEvidenceSourceSha256": "4069393405089bde613cecec04f5123c426594811da4c668bd96f0e7e283550f",
"nativeSessionRuntimeSourceSha256": "1fe6fa9e6b96d84d70432b85a57c473f833606d4a521563d5022b4d3c41576ce",
"nativeRuntimeContextSourceSha256": "71607f80dbb8dc5cc6c123d0b8f3995d6c5407277695a8c82cbedc90fb8f4842",
"nativeRuntimePromptsSourceSha256": "103b83066da72434602e9e461e6278dfb40bb993d2f3b49b2e93df81bbb08b72",
"nativeSessionContractSourceSha256": "22a8c96ce41ba4f03e976fc37f0cc7c5d05cee99fa789941da31ee1dab440b90",
"harnessSessionContractSourceSha256": "03f4cd7f76f34f6d82e009b66aa51f18f6e23dc235b660778060e35b6ea07412",
"harnessBackendSourceSha256": "dc827e281ae6731545b166ee4d709a4f67f594a556dcbe63c70fe8f1aca26249",
"harnessSessionSourceSha256": "81361733e86b56dd5a66415aefc6f72e69be24acc8d3417370154ebb7fef6e94",
"transportContractSourceSha256": "03fca93d36a89b0cc0917335e293ad097fdf04356d21b307827bb0ea4c13f523",
"nativeBackendSourceSha256": "e7b12d4418c7a71f5f2474b046697d3009eae3613b284bec381df5e9965a1c37",
"nativeBackendFactorySourceSha256": "7e431c926b76d53c4c08e3a4105353dcd34bd940f6588a1a68f79631f6feeb44",
"nativeInstructionsSourceSha256": "9173ebccf09cb56a781d2bf5c7eb27fdafb13d3450d99342c6aff86b42d6b43a",
"providerLaunchSourceSha256": "fa8db1c42c378898287c141d8cea9069166981e369c9b9c51422cb6177de5a2c",
"launchPreparationStoreSourceSha256": "ff6025568bbc0aa6ce545772d73dfca2d3da226740bd3a7b386b069e76cff296",
"runtimeRequestBridgeSourceSha256": "9be35e006ffffcca48205f9e53548dd453ec6a8cbcf0aa4dd735194e9619dfc7",
"runtimeRequestFacadeSourceSha256": "d0ed28e0c5ddad34db8f437e704c8a755eb0b47f27e08e44185f66d1d2205295",
"runtimeRequestNotificationSourceSha256": "6196c6175f11c69295dc00fc773201f4fdeca26c500653870253c43b81e65211",
"guardedInstallationSourceSha256": "56a177d3e702914818dca4ca50e061f0d25f988bfc4c0582c36ce23c1696d82f",
"nativeExecutionSourceSha256": "3a30d52bffad68c7f02349193be84761050eb99039fc0556c2b449891a36e918",
"profileCompatibilitySourceSha256": "5b00c3f78ad12321d48e66a90338af2d53d59dd17bb4b72b10ccdb4240b5a150",
"installationSourceSha256": "a1c7c6f103b898216973e77ffbac0ef7572e250aa574d1a4065270e9dfa0dc2d",
"assetOwnershipSourceSha256": "1785e3f31e5dad5a13b53e25d8cf9482a9bd89a27b6c127830aed6b81acc605c",
"assetInstallerSourceSha256": "d3bd9514e5920d0cc3567aa50487fb534c57a6f66b8da0d3f22c5f6e499c841f",
"credentialBindingSourceSha256": "7586d44b47c83395498dc8806287cd3538ef58177ba7c5949f5766ed105a0161",
"sidecarErrorSourceSha256": "b09af4577f8bf42eee7036b2ad9842202cfc763e72b53c3287f82c6090cdad80",
"profileSourceSha256": "f5538b3dbefa7634a332b87d5ededcefb56aa7e5790cede1c7a0d948a548a456",
"metadataProbeSourceSha256": "be4c8416edd27061109bc1f33d0c26071b4facbb3f651beaae6b3c0275cce727",
"permissionToolIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1",
"semanticContinuationSourceSha256": "c9cc0fd516b3df92a6655f56ee9bef37615a889c371e2e137d8ac5c1176de811",
"runtimeHostSourceSha256": "94a73749267f5a80b5df19413a65b4b9263c00a9bf7e98fda00f00b8f9fd32ec",
"runtimeAdapterSourceSha256": "e4c764c2c3c7dd655a965b39472bd1ad8d577d1e7258b25594b171c9429752b8",
"runtimeSandboxSourceSha256": "92dfa53f5a3ed0062913ae417eeccec243b430d444495efde2a8e9c4c02e78ea",
"cancellationSourceSha256": "a07d1a9e982dec0ae130c1ad1efa5bc75c6a39e013b730ba3ee45256f09ceeca",
"agentFilesSourceSha256": "fb32f6badc13dfa22f231479509b631b2f0eba0c99b1ab9f3cd5c0c601aa03ba",
"nativeDistributionSourceSha256": "aed327c389e957483a503cb1bb8b247ee7cd7ff4b528fb4567c39bcb4577690b"
}
}
+41
View File
@@ -259,6 +259,18 @@ A card or section rendered on the main dashboard. Use this for at-a-glance metri
An additional tab on a project, issue, agent, goal, or run detail page. Rendered when the user navigates to that entity's detail view. Receives `PluginDetailTabProps` with `context.companyId` set to the active company and `context.entityId` / `context.entityType` guaranteed to be non-null, so you can immediately scope data fetches to the relevant entity. Specify which entity types the tab applies to via the `entityTypes` array in the manifest slot declaration. Requires the `ui.detailTab.register` capability.
Agent detail tabs can also appear in task side panels. Add
`taskSidePanel: { availabilityPath: "/agents/:entityId/view/availability" }` to the
slot and declare that exact path as a board-only GET API route with
`companyResolution: { from: "agent", param: "entityId" }`. The route returns
`{ available: true }` only while its view is in use. The host replaces `:entityId`
with the task's running agent ID, polls availability and mounts the same component
with agent context. The plugin owns availability, labels, content and controls.
No private plugin identifier or provider protocol belongs in Core. Unavailable
views, access failures, inactive runs and missing plugins contribute no task tab.
Closing a tab preserves dismissal during polling; available panels remain in the
launcher. Only tab identity is persisted, never availability responses or secrets.
#### `taskDetailView`
A specialized slot rendered in the context of a task or issue detail view. Similar to `detailTab` but designed for inline content within the task detail layout rather than a separate tab. Receives `context.companyId`, `context.entityId`, and `context.entityType` like `detailTab`. Requires the `ui.detailTab.register` capability.
@@ -1432,3 +1444,32 @@ lifecycle inbox listings or the company secret catalog. Do not expose values
through plugin entities, state, data handlers, UI, or logs. Agent instance
secrets retain their existing lifecycle contract. Back up the tenant's existing
local secrets master key together with its database.
### Project Git credentials
Trusted workspace providers can declare `projects.git-credentials` and call
`ctx.projects.resolveGitCredential(projectId, workspaceId, companyId)` from the
matching host-issued project lifecycle or workspace operation. Other invocations
cannot obtain credentials through this method. The workspace must be a current
repository in that project and company; plugins cannot supply arbitrary URLs.
Background work uses a project writer's explicit consent to their own personal,
company-installed GitHub Connector grant. It does not retain task context. Core
checks the exact grant and its owner's active company membership on every use.
Foreground preparation uses the active run's identity and trust policy instead.
Public repositories return null and require no connection. Private repositories
without authorization wait before provisioning. Repository visibility comes from
the Connector catalog and retained project selections; legacy URL-only sources
use anonymous discovery when visibility is unknown. A revoked or invalid private
repository authorization fails closed. There is no fallback to another grant.
Project consent follows the connection's current repository access, including
sources added later, rather than a separate project repository approval list.
The consenting user must retain project read access, and background credential
export requires the project's existing trust policy to allow standard execution.
Archived projects keep credential access only for host-issued workspace inspection
and removal with existing consent; provisioning remains blocked.
The return value is transient raw credential material with the Connector's
existing permissions. This capability is for trusted execution infrastructure,
not agent-facing tools or UI. Never expose or persist it. See
[GitHub identity](../../../doc/execution-github-identity.md#project-authorization-for-background-repository-work).
@@ -202,6 +202,7 @@ export interface HostServices {
projects: {
list(params: WorkerToHostMethods["projects.list"][0]): Promise<WorkerToHostMethods["projects.list"][1]>;
get(params: WorkerToHostMethods["projects.get"][0]): Promise<WorkerToHostMethods["projects.get"][1]>;
resolveGitCredential(params: WorkerToHostMethods["projects.resolveGitCredential"][0], context: WorkerHostCallContext): Promise<string | null>;
getInstanceSecrets(params: WorkerToHostMethods["projects.getInstanceSecrets"][0]): Promise<WorkerToHostMethods["projects.getInstanceSecrets"][1]>;
listWorkspaces(params: WorkerToHostMethods["projects.listWorkspaces"][0]): Promise<WorkerToHostMethods["projects.listWorkspaces"][1]>;
getPrimaryWorkspace(params: WorkerToHostMethods["projects.getPrimaryWorkspace"][0]): Promise<WorkerToHostMethods["projects.getPrimaryWorkspace"][1]>;
@@ -443,6 +444,7 @@ const METHOD_CAPABILITY_MAP: Record<WorkerToHostMethodName, PluginCapability | n
"projects.list": "projects.read",
"projects.get": "projects.read",
"projects.getInstanceSecrets": "projects.instance-secrets",
"projects.resolveGitCredential": "projects.git-credentials",
"projects.listWorkspaces": "project.workspaces.read",
"projects.getPrimaryWorkspace": "project.workspaces.read",
"projects.getWorkspaceForIssue": "project.workspaces.read",
@@ -834,6 +836,14 @@ export function createHostClientHandlers(
"projects.list": gated("projects.list", async (params) => {
return services.projects.list(params);
}),
"projects.resolveGitCredential": gated("projects.resolveGitCredential", async (params, context) => {
const companyId = resolveRequiredCompanyId("projects.resolveGitCredential", params, context);
const scope = context?.invocationScope?.projectGit;
if (!scope || scope.projectId !== params.projectId || (scope.workspaceId && scope.workspaceId !== params.workspaceId)) {
throw new Error("Git credentials require a matching host project operation");
}
return services.projects.resolveGitCredential({ ...params, companyId }, context!);
}),
"projects.getInstanceSecrets": gated("projects.getInstanceSecrets", async (params, context) => {
const companyId = resolveRequiredCompanyId("projects.getInstanceSecrets", params, context);
return services.projects.getInstanceSecrets({ ...params, companyId });
+6 -1
View File
@@ -289,6 +289,7 @@ export type PluginRpcErrorCode =
*/
export interface PluginInvocationScope {
companyId: string;
projectGit?: { projectId: string; workspaceId?: string; runId?: string; agentId?: string; operation?: "prepare" | "inspect" | "remove" };
}
/**
@@ -1796,6 +1797,10 @@ export interface WorkerToHostMethods {
params: { companyId: string; limit?: number; offset?: number },
result: Project[],
];
"projects.resolveGitCredential": [
params: { projectId: string; workspaceId: string; companyId: string },
result: string | null,
];
"projects.getInstanceSecrets": [
params: { projectId: string; companyId: string },
result: Record<string, string>,
@@ -2153,7 +2158,7 @@ export interface WorkerToHostMethods {
result: PluginAgentRuntimeIdentity | null,
];
"agents.getRuntime": [
params: { agentId: string; companyId: string },
params: { agentId: string; companyId: string; environmentId?: string; installEnvironmentSkills?: boolean },
result: PluginAgentRuntimeState | null,
];
"agents.get": [
+4
View File
@@ -1032,6 +1032,10 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
},
},
projects: {
async resolveGitCredential() {
requireCapability(manifest, capabilitySet, "projects.git-credentials");
throw new Error("Git credentials require a matching host project operation");
},
async getInstanceSecrets(projectId, companyId) {
requireCapability(manifest, capabilitySet, "projects.instance-secrets");
requireCapability(manifest, capabilitySet, "events.subscribe");
+7 -1
View File
@@ -875,6 +875,9 @@ export interface PluginEntitiesClient {
* @see PLUGIN_SPEC.md §7 — Project Workspaces
*/
export interface PluginProjectsClient {
/** Transient GitHub credential for a stored repository in the current host-issued
* lifecycle/workspace invocation. Requires projects.git-credentials. Never persist or log. */
resolveGitCredential(projectId: string, workspaceId: string, companyId: string): Promise<string | null>;
/** Trusted worker access to this plugin’s native project credentials.
* Requires projects.instance-secrets; never expose via UI/data handlers. */
getInstanceSecrets(projectId: string, companyId: string): Promise<Record<string, string>>;
@@ -1716,6 +1719,8 @@ export interface PluginAgentConnectionAssignments {
export interface PluginAgentRuntimeState {
connectionAssignments: PluginAgentConnectionAssignments;
skills: PluginAgentRuntimeSkill[];
/** Selected company skills omitted because the environment requires the same skill name. */
shadowedSkills?: Array<{ key: string; shadowedBy: string }>;
revision: string;
agent: Agent;
instructionsRootPath: string | null;
@@ -1731,7 +1736,8 @@ export type PluginAgentRuntimeIdentity = Pick<PluginAgentRuntimeState, "revision
export interface PluginAgentsClient {
getRuntimeIdentity(agentId: string, companyId: string): Promise<PluginAgentRuntimeIdentity | null>;
getRuntime(agentId: string, companyId: string): Promise<PluginAgentRuntimeState | null>;
/** Lifecycle reconciliation can install missing environment skills; task and recovery reads leave this false. */
getRuntime(agentId: string, companyId: string, environmentId?: string, installEnvironmentSkills?: boolean): Promise<PluginAgentRuntimeState | null>;
list(input: { companyId: string; status?: Agent["status"]; limit?: number; offset?: number }): Promise<Agent[]>;
get(agentId: string, companyId: string): Promise<Agent | null>;
/** Pause an agent. Throws if agent is terminated or not found. Requires `agents.pause`. */
+5 -2
View File
@@ -720,6 +720,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
},
projects: {
async resolveGitCredential(projectId, workspaceId, companyId) {
return callHost("projects.resolveGitCredential", { projectId, workspaceId, companyId });
},
async list(input) {
return callHost("projects.list", {
companyId: input.companyId,
@@ -1166,8 +1169,8 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
async getRuntimeIdentity(agentId, companyId) {
return callHost("agents.getRuntimeIdentity", { agentId, companyId });
},
async getRuntime(agentId, companyId) {
return callHost("agents.getRuntime", { agentId, companyId });
async getRuntime(agentId, companyId, environmentId, installEnvironmentSkills) {
return callHost("agents.getRuntime", { agentId, companyId, ...(environmentId ? { environmentId } : {}), ...(installEnvironmentSkills ? { installEnvironmentSkills: true } : {}) });
},
async list(input) {
return callHost("agents.list", {
@@ -452,3 +452,25 @@ describe("project instance secrets", () => {
expect(getInstanceSecrets).toHaveBeenCalledWith(params);
});
});
describe("project Git credentials", () => {
it("requires capability, company, project and repository scope before calling credential services", async () => {
const resolveGitCredential = vi.fn(async () => "transient-token");
const services = { projects: { resolveGitCredential } } as unknown as HostServices;
const params = { companyId: "company-a", projectId: "project-a", workspaceId: "workspace-a" };
const context = { invocationScope: { companyId: "company-a", projectGit: { projectId: "project-a", workspaceId: "workspace-a", runId: "run-a", agentId: "agent-a" } } };
const denied = createHostClientHandlers({ pluginId: "fixture", capabilities: [], services });
await expect(denied["projects.resolveGitCredential"](params, context)).rejects.toBeInstanceOf(CapabilityDeniedError);
const allowed = createHostClientHandlers({ pluginId: "fixture", capabilities: ["projects.git-credentials"], services });
for (const invalid of [undefined, { invocationScope: { companyId: "other" } },
{ invocationScope: { companyId: "company-a" } },
{ invocationScope: { companyId: "company-a", projectGit: { projectId: "other" } } },
{ invocationScope: { companyId: "company-a", projectGit: { projectId: "project-a", workspaceId: "other" } } },
{ ...context, invalidInvocationScope: true }]) {
await expect(allowed["projects.resolveGitCredential"](params, invalid)).rejects.toThrow();
}
expect(resolveGitCredential).not.toHaveBeenCalled();
await expect(allowed["projects.resolveGitCredential"](params, context)).resolves.toBe("transient-token");
expect(resolveGitCredential).toHaveBeenCalledWith(params, context);
});
});
Loaded 100 of 356 files, more files were not shown because too many files have changed in this diff. Show more