merge: integrate agent lifecycle ownership from master

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-09 11:24:59 -05:00
commit ad5d8826ad
159 files changed
+7173 -2805

No files matched your search

+2 -1
View File
@@ -1308,10 +1308,11 @@ export async function quarantineSeededWorktreeExecutionState(
.update(agents)
.set({
runtimeConfig: normalized.runtimeConfig,
status: nextStatus,
updatedAt: new Date(),
})
.where(eq(agents.id, agent.id));
if (nextStatus !== agent.status) await tx.update(agents).set({ status: "idle", updatedAt: new Date() })
.where(and(eq(agents.id, agent.id), eq(agents.lifecycleState, "ready")));
}
}
+264
View File
@@ -0,0 +1,264 @@
# Agent lifecycle
The agent lifecycle module controls hiring, pause, resume, and termination.
Its public entry point is `server/src/modules/agent-lifecycle/index.ts`.
Use its commands to create an agent or change its lifecycle state.
Do not pass a database transaction to a command.
Each hire or transition command owns its transaction.
## Application use
Application code imports the configured factory from `services/agent-lifecycle.ts`.
This service supplies the module dependencies. Use the root database connection.
Apply the existing caller authorization checks before you call a command.
```ts
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
const lifecycle = createAgentLifecycle(db);
await lifecycle.updateConfiguration(agentId, { title: "Engineer" });
await lifecycle.pauseAgent(agentId);
const state = await lifecycle.get(agentId);
```
The pause command records the request. The worker completes the external steps.
Read `lifecycleState` to check progress.
Configuration updates accept only the fields in `AGENT_CONFIGURATION_FIELDS`.
They reject identity, company, accounting totals, timestamp, and lifecycle fields.
The public update schema also rejects spend totals. Budget limit changes remain
permitted through `budgetMonthlyCents`.
Do not import module adapters or construct module dependencies in a caller.
The company deletion service uses the separate deletion entry point.
The listed configuration workflows use the restricted transaction service.
These are the only transaction integrations. They are described below.
## States
| State | Meaning | Next state |
| --- | --- | --- |
| `pending_approval` | The hire needs board approval. | `preparing` or `rejected` |
| `preparing` | Required plugins prepare the agent. | `verifying` |
| `verifying` | The host tests the saved harness configuration. | `ready` |
| `ready` | The lifecycle permits work. | `pausing` or `terminating` |
| `pausing` | The host stops work. Required plugins stop their resources. | `paused` |
| `paused` | A pause hold prevents work. | `resuming` or `terminating` |
| `resuming` | Required plugins start their resources. | The state saved before pause |
| `terminating` | The host revokes keys and stops work. | `cleaning_up` |
| `cleaning_up` | Required plugins remove their resources. | `terminated` |
| `terminated` | Termination is complete. | None |
| `rejected` | The board rejected the hire. | None |
Termination can start before preparation or verification completes.
An old result cannot complete a newer operation.
Deletion requires completed termination or a rejected hire.
The existing restrictions for built-in agents and accounting still apply.
## Commands and transactions
`requestHire` writes the agent record before preparation starts.
An approved hire starts preparation after the transaction commits.
A proposed hire waits for `approveHire`.
`approveHire` and `rejectHire` accept an agent ID or `{ approvalId }`.
Both forms use the same hire decision path. An agent ID also resolves its open
hire approval. The approval and the agent change commit together.
The existing company approval rules still apply.
`pauseAgent`, `resumeAgent`, and `terminateAgent` record the requested change.
They do not wait for external resource operations.
`retry` makes a failed step available for another attempt.
`reconcilePolicyHolds` updates budget and company holds for the specified company.
The background policy check processes at most 100 eligible agents each minute.
It continues from the last agent ID and returns to the start after the last page.
Pending hires and agents in termination or a final state are excluded.
An explicit company or budget change still updates all affected agents immediately.
`updateAndTransition` applies a configuration change and a lifecycle command
in one transaction. A failed command does not save the configuration change.
The onboarding and invitation services own their feature workflows.
They commit the hire through `requestHire` before they save the other records.
A separate database transaction holds only the workflow lock.
It prevents concurrent requests for the same workflow.
The hire command commits through its own connection and transaction.
A failure in the lock transaction cannot undo a committed hire.
If a later step fails, a retry uses the existing agent.
The onboarding revision is saved only after its content and audit record commit.
The approval service owns comments, revisions, and general approval records.
The lifecycle module resolves a hire approval and changes the agent in one
transaction. It retains the original credential owner when it approves a hire.
The company deletion service owns the company data cascade.
It requests agent termination before it starts that cascade.
It locks the company in the deletion transaction and removes dependent records.
It then calls `agentLifecycleCompanyDeletion.deleteCompanyData(tx, companyId)`
through the module's separate `company-deletion.ts` entry point.
This operation implements the shared `CompanyDeletionParticipant` interface.
It locks the agent rows, checks their states, and deletes them.
All agents must be terminated or rejected. Otherwise, it throws an error.
The error rolls back all database changes in the deletion transaction.
A concurrent hire makes deletion fail or waits until deletion ends.
The module's delete statement also restricts removal to terminated or rejected agents.
`purgeAgent` deletes a single agent. It owns the transaction and checks the agent
state before it calls the service to remove dependent records.
The service checks accounting holds. The module then deletes the agent record.
An error rolls back both operations. Neither path permits incomplete termination.
The ordinary agent service owns reads, permissions, and keys.
The configuration service owns validation and configuration revisions.
The lifecycle module owns the agent configuration write.
Credential checks remain in the agent credential service.
Secret proposal approval saves the secret before it applies the agent binding.
If the binding fails, the secret remains approved and the binding remains pending.
A retry uses the approved secret. It does not create another secret.
The binding transaction checks authorization, expiry, and the current reporting
structure again before it changes the agent.
The hire service owns names, appearance, permissions, credential binding,
connection installs, identity setup, and primary-agent selection.
The module calls the hire service before and after the agent record write.
These operations use the lifecycle transaction. A failed operation rolls back
the hire and its dependent records.
The module owns the initial state, approval transition, and lifecycle events.
The service in `services/agent-lifecycle.ts` supplies these integrations to the
module. The module does not import services or routes. Shared record queries
and validation functions are in `lib/`. They do not call lifecycle commands.
The application supplies the worker driver at startup.
`updateConfiguration` owns the transaction for an ordinary configuration update.
The module locks the agent. The configuration service validates and prepares the
patch. The module saves it and invalidates an old verification result when
execution configuration changes during setup. The service then updates dependent
records and saves the configuration revision in the same transaction.
There is no separate invalidation operation for callers.
Configuration writes reject caller-supplied lifecycle fields.
For `updateAndTransition`, lifecycle owns the transaction and calls the
same configuration operation. Both changes commit together.
Some workflows must save an agent reference and their own records together.
The module exposes `configuration.ts` for these transactions. Only
`services/agent-configuration-transaction.ts` can import it.
This service supplies the module integrations. It cannot save a configuration
without the module's invalidation check.
Its permitted callers are secret binding approval, Connection adoption, runner
pairing, avatar updates, instruction revisions, and skill reassignment.
The boundary check lists these callers. Ordinary callers use the root command.
Budget changes always use a root command so enforcement follows the commit.
The transaction integration cannot approve, pause, resume, or terminate an agent.
It does not start a worker before the caller commits. The periodic scan recovers
pending setup work after the commit.
Manual, budget, and company pause holds are independent.
A manual resume does not remove a budget or company hold.
Restoring a company does not remove a manual hold.
Budget and company policy still prevent admission while the pause work runs.
The legacy `status` field remains available to existing clients.
It shows `paused` during preparation, verification, pause, and resume.
It shows `terminated` as soon as termination starts.
Execution code can change this field only when the lifecycle is `ready`.
Use `lifecycleState` to distinguish the steps.
This change does not change the user interface.
## Required plugin work
A plugin can declare `agentLifecycle: true` in its manifest.
It must also request `agents.lifecycle.manage`.
The plugin implements `onAgentLifecycle` in the SDK.
This method is separate from event delivery and event acknowledgment.
The host selects the required plugins before the first lifecycle step.
`setRequiredPlugins` stores their IDs on the agent.
The host is not a plugin ID. Each operation records host completion and
completed plugin IDs separately. The host step must finish before plugin calls.
A disabled or removed plugin cannot silently release an existing requirement.
Restore that plugin to complete the operation.
A later plugin installation does not change an existing selection.
Each request contains these fields:
- `companyId` and `agentId` identify the agent.
- `phase` identifies the lifecycle step.
- `operationId` identifies the operation.
- `version` identifies the state revision.
Return the same `operationId` and `version` with `status: "complete"` or
`status: "pending"`.
Return `complete` only after the requested effect is complete.
Return `pending` while external work continues.
Throw an error when the step fails.
The host stores a fixed error message. It does not store the provider error text.
Server logs identify the failed step, phase, operation, and plugin when available.
They include only known error codes. Unknown codes become `unclassified`.
They do not include provider messages, stacks, or configuration values.
A failure before the agent is read can have only a step and agent ID.
A scan failure has no agent ID.
Calls can repeat after a timeout or a server restart.
A plugin must make repeated calls safe.
It must retain the highest version for each company and agent.
It must reject an older request after it accepts a newer version.
It must also prevent an older operation from creating resources after cleanup.
Serialize external effects or remove resources from a late completion.
Do not treat a host timeout as cancellation of the external effect.
## Verification and recovery
The harness verification service uses the existing environment-test code.
It owns test configuration, credential selection, and test result checks.
It tests the saved agent configuration and the selected environment.
A failed login or an incomplete probe cannot complete verification.
The lifecycle module receives completion, pending work, or failure through its
driver. It owns the state transition and has no harness test rules.
The current UI can also run a test before the hire.
Some adapters can charge for these tests.
It uses the saved responsible user for managed credentials.
The host does not grant new credential access for this test.
A connection pool selects an account for a separate lifecycle test operation.
An external controller must complete its existing readiness test.
Task requests can enter the durable run queue during preparation, verification,
and resume. Execution waits for readiness. Queue recovery does not require
periodic agent heartbeats to be enabled.
A cancelled run record does not prove that execution stopped.
The host also checks process ownership, controller leases, and environment cleanup.
Required plugin cleanup cannot start while these checks are incomplete.
The worker starts after a committed command.
A periodic scan recovers work after a process stops.
A database lease permits one active attempt for each agent.
The worker renews that lease during external calls.
Each result must match the current revision and lease owner.
Shutdown waits for active work.
The agent API returns `lifecycleState`, `lifecycleVersion`, and `lifecycleError`.
A board user can retry through `POST /api/agents/:id/lifecycle/retry`.
The route applies the existing company access checks.
## Existing installations
Migration `0320_daily_onslaught.sql` maps the current status of each agent.
Active execution states become `ready`.
Paused, pending, and terminated agents retain their current meaning.
The migration retains each existing pause reason as a hold.
It does not provision external resources or record a successful harness test.
Resource backfill is a separate task.
Run the normal database migration process before starting the new server.
Stop older server processes during the change.
An older process can write the legacy status without the new lifecycle checks.
`pnpm check:module-boundaries` checks the module imports and agent writes.
Tests and migration fixtures can write records directly.
Production creation and lifecycle state writes must use the lifecycle module.
Production record deletion must also use the lifecycle module.
Execution configuration writes must use the module. The offline worktree seed
command can disable timers in a copied database before the server starts.
## Extension rules
Add a lifecycle command to the module entry point. Put state transition rules in
`domain/policy.ts`. Put database operations in the module adapters.
Keep harness and provider rules in services. Supply external work through the
worker driver. Report completion only after that work is complete.
Add a test for a failed or repeated operation. Run `pnpm check:module-boundaries`
to check the import and write boundaries.
@@ -6,7 +6,17 @@ It binds master's shared protocol-validation sources without changing the
executable or supplying new paid qualification. Historical checkpoints below
retain their original identities and outcomes.
Historical source candidate (2026-10-01): **Copilot profile v12 is unqualified**.
Historical source candidate (2026-10-02): **Copilot profile v13 is unqualified**.
Pi's explicit reasoning-mode support changed four shared transport and schema
source files included in Copilot's execution identity. Version 13 records those
source hashes with digest
`sha256:3ff08fbe76fe4549c9eb01e8794428d8909c65c151d775220f2ec111d9e6f7c1`.
The Copilot executable closure, model and provider behavior are unchanged. The
historical v12 declaration is preserved; v12 warm sessions are rejected by the
current candidate. This identity update supplies no new paid qualification.
Fresh runtime packages and local/Daytona qualification remain required.
Historical source candidate (2026-10-01): **Copilot profile v12 was unqualified**.
Receipt v2 preserves the original `inputSha256` and separately captures
`normalizedInputSha256` from the same invocation's validated outgoing body.
For the native sidecar, only a successful, correlated `tool.resolve` commits
+192 -3
View File
@@ -22,7 +22,92 @@ for the exact source/image evidence and merge status.
All dated checkpoints below describe historical qualification attempts. Their
failures and profile numbers are retained; they are not current release gates.
## Historical Pi 1.0 candidate (2026-10-02, profile v12)
## Historical Pi 1.0 candidate (2026-10-02, profile v13)
Pi remains pinned to **`@earendil-works/pi-coding-agent@1.0.0`**, with
`pi-acp@0.0.33`, ACPX `0.13.1`, and Node `24.21.0`. Profile 13 adds explicit
reasoning-mode selection and rejects previous profile identities. It is a new
qualification candidate; profile-12 results below remain historical evidence.
Pi's new field also changes four shared files covered by Copilot's source
identity. Copilot therefore advances to a still-unqualified profile v13 without
changing its executable or model. Pi's profile-13 identity and native closure
remain unchanged. Final artifacts must bind the corrected source; the initial
ARM startup and 61 contract passes alone do not establish production readiness.
The normal Pi configuration records `piThinkingLevel` as `off`, `low`, `high`,
or `max`. New configurations and qualification cases explicitly select `low`.
The runner binds that setting to the session identity and requires native
confirmation of the effective level before sending the prompt, including after
session restoration. An unsupported level, absent acknowledgement, or effective
level different from the requested value must fail admission. Changing the
level requires a new compatible session; a warm session cannot silently retain
its previous setting.
The wrapper obtains available levels from Pi's native
`get_available_thinking_levels` RPC, exposes them through ACP session modes and
the `thought_level` configuration option, and confirms changes with native
`get_state`. This avoids advertising the static `minimal`, `medium`, or `xhigh`
aliases when the selected model does not support them. For the pinned DeepSeek
model, Pi 1.0 supports `off`, `low`, `high`, and `max`. Pi's implicit `medium`
default resolves to `high`; Pi 0.84.2 also resolved that default to `high`, so
this is a configuration gap rather than evidence of a new Pi 1.0 default.
The [provider-free wire proof](../../packages/paperclip-runner/test-fixtures/pi-acp/thinking-modes.v13.darwin-arm64.json)
records actual Pi 1.0 request bodies changing from `high` to `low` through ACP,
truthful `max` restoration, blocked non-loopback connections, and owned-process
retirement. Synthetic responses establish propagation, not paid qualification.
The paid profile-12 hello passed in the actual installed application. Its first
question continuation failed at the unchanged 120-second native deadline after
1,019 reasoning deltas and no emitted tool call or question. The required tool
was present with its exact schema. This establishes model activity without the
required interaction; it does not prove the reasoning setting caused the timeout.
The test remains failed. Profile-13 deterministic, local paid, Runner, native
control, and Daytona results must be established independently.
| Capability | Native / ACP surface | Paperclip surface | Remaining boundary |
| --- | --- | --- | --- |
| Supported thinking levels | `get_available_thinking_levels`; ACP available session modes and `thought_level` choices | Pi reasoning-level configuration | Model selection is explicit and unrestricted; historical qualification used the recorded model and level. |
| Set and verify thinking level | Native `set_thinking_level`, then `get_state`; ACP `session/set_mode` / config option | Saved agent setting, typed runner input, effective-mode admission | Live setting changes during an active turn are not exposed; a new compatible session is required. |
| Recover selected level | Native restored state plus explicit effective-level verification | Mode-bound durable session identity | Old profiles and missing or mismatched mode identity cannot reuse a warm session. |
| Provider notice severity and pricing provenance | `paperclip/pi_notice` and canonical `provider.notice.recorded` | Retained run event, usage metadata, and safe summary with severity in the activity row | Summary/severity rendering has deterministic coverage; paid visual verification of the rebuilt UI remains pending. Pricing estimates remain distinct from provider billing receipts. |
## Historical profile-13 qualification checkpoint (2026-10-02)
The installed candidate from source `eac50643213d0902a93a5384bae2f1d6c065c9f2`
uses Pi 1.0.0, the explicit OpenRouter DeepSeek model above, and verified `low`
reasoning. Paid local Product E2E passes cover hello, semantic question/answer
continuation, all four native question forms, and human permission denial with
no file side effect. The paid extended Runner `get-task-context` case also
passes through the packaged runner against its authenticated, seeded test
control plane. Runner protocol evidence does not qualify the Product UI.
Three local attempts remain failed: file-edit validation, pending-input
controller restart, and three-turn warm continuation. The first two exposed
assertion gaps: streamed command output supplies the exit receipt, and a
pre-start submission may precede assignment of the native turn ID. Narrow
fixture repairs have positive and negative coverage; neither failed attempt
has been regraded and both require fresh live runs.
The warm attempt completed its first turn and edited files on its second, but
its final semantic tool stayed pending until the existing deadline. OpenRouter
metadata joins the exact native session and records the final response as
cancelled with no finish reason. This supports an unfinished upstream response
at cancellation; it does not establish why the response stopped progressing.
A real pinned SDK/wrapper replay proves both restored-session completion with
the new agent home and completion contract, and safe cancellation when complete
tool JSON arrives without the provider's stream finish marker. The latter
executes no semantic mutation. No timeout or runtime policy was changed to make
that replay pass.
Fresh builds must incorporate the subsequent launch, UI, and fixture fixes.
macOS Intel startup, the remaining local and Runner cases, Linux/Daytona, and
final source-wide checks remain qualification gates. The provider remains
unqualified until that evidence is complete. API-key usage observations cover
the capped qualification campaign; native pricing estimates are not bills.
## Historical Pi 1.0 profile-v12 checkpoint (2026-10-02)
The candidate now pins **`@earendil-works/pi-coding-agent@1.0.0`** with
`pi-acp@0.0.33`, ACPX `0.13.1`, and portable Node `24.21.0`. Pi v11 and older
@@ -97,6 +182,76 @@ Pi's published CLI mode union is `text | json | rpc`; no native ACP mode is
present in this release. The reviewed `pi-acp` wrapper remains necessary.
## Explicit Linux companion setup for a Mac controller
A Mac controller needs independently verified Linux runner bytes for Daytona.
Its host Pi installation is not a Linux provider pack. The operator imports a
release companion once, before launching agents:
```sh
paperclipai runtime import-remote /path/to/release/linux-x64 --sha256 MANIFEST_SHA256
```
Obtain `MANIFEST_SHA256` from the trusted release channel, separately from the
copied directory. The directory contains `companion.json`,
`bin/paperclip-runnerd`, and the complete `provider-pack/`. Import verifies the
installed server's exact build commit, qualified Pi profile, Linux x64 ELF,
manifest digest, and every file, mode, directory and contained symbolic link.
External hardlinks, escaping links, extra or modified files, and unsafe modes
are rejected. This command performs no network requests or model calls and does
not run the Linux executable on the Mac.
The destination is the private `remote-companions/linux-x64` directory beneath
the actual installed `@paperclipai/server` package. It must be writable by the
operator, outside the task workspace, and protected with the same host access
controls as the server installation. It is not an agent workspace or a remote
image's self-reported authority. An existing different or damaged installation
is never replaced automatically. Stop all runs before an operator removes or
upgrades that cache. Verification and copying use asynchronous 1 MiB chunks,
yield between chunks, and enforce the same full inventory and ten-minute bound.
Directory entries must retain owner read/write/search permissions so failed imports
can drain their owned cleanup. SIGINT/SIGTERM are deferred through owned filesystem
phases and drain cleanup;
an uncatchable kill or host failure leaves the import unadmitted until the
operator resolves its retained lock or incomplete directory. Do not move the
cache into a task workspace to work around permissions.
Normal remote Pi resolves this authority without binary or pack environment
overrides. The controller re-verifies its complete inventory and uses the exact
Linux daemon identity. Existing remote verification compares image bytes against
that local authority; a mismatch takes the existing verified upload path.
Controller restart and warm-session recovery retain the original Runner artifact
identity checks. Cursor, Copilot and explicit operator overrides keep their
existing admission rules.
For release maintainers, assemble the Linux daemon and default provider pack
for the **same final commit** as the public server/CLI packages. A reused daemon
requires complete native source/config/protocol input equality and retains its
original compiler/build provenance; the manifest does not claim recompilation. In a fresh
release directory place those outputs at `bin/paperclip-runnerd` and
`provider-pack/`, preserving the pack's relative links and modes. Then run the
source-owned manifest generator after building the matching server:
```sh
node scripts/create-runner-remote-companion.mjs /path/to/release/linux-x64 FINAL_SOURCE_SHA
```
Publish the complete companion directory (or distribute it through the normal
trusted release channel) together with the printed manifest SHA256 and the
source/profile/platform provenance. The import command accepts an already
extracted directory, not an archive or URL. The release companion must remain
available with that release; a short-lived qualification artifact is not a
release distribution. No release publication is implied by the tests here.
Build/publish the Daytona image from those same daemon/pack outputs and configure
its immutable OCI digest through the ordinary Daytona environment `image` field.
The image digest and companion manifest are output metadata, not new source
constants, so publication does not require another source commit. The final live
proof must use the installed public CLI, this import command, and ordinary image
configuration without E2E remote binary/provider-pack overrides. That installed
and paid proof remains pending.
Historical v10 qualification checkpoint (2026-09-30): **Pi profile v10 remains unqualified.** The capped-key/login prerequisite remains blocked. Native USD is unknown. The optional private budget helper is not integrated; Cursor's account-cycle cap does not establish Pi's provider spending bound. V10 keeps the native wrapper and closures unchanged, binds the shared ACPX patch under a new digest, and rejects v9 sessions. Fresh exact-runtime admission and final controller verification remain pending.
Historical v9 checkpoint (2026-09-30): **Pi profile v9 remains unqualified**. Current runtime source is `5b8e4454ef0bf12d0bb068c2e41d8c9df9356a1c`; controller/Product harness source is `40064d28522de25fea85c1297f35b41bb8a8897a`. Runtime builds for macOS ARM64/x64 and Linux x64 are complete. No paid profile-v9 pass is claimed. A credential with a verifiable spend limit is still needed for the remaining paid qualification. The optional transport-budget candidate is frozen on a separate branch and is not integrated or a live spending guarantee. See the [comparative capability report](runner-rich-acp-capabilities.md) for current qualification gates and the field audit. The dated observations below retain their original profile identities.
@@ -209,8 +364,8 @@ addressed by v4. Version 2 hello completion and every failure remain retained.
The wider local and Linux x64 Daytona matrix remains pending; this document does
not promote the candidate to a qualified production runtime.
The runner pins `pi-acp@0.0.33` and
`@earendil-works/pi-coding-agent@0.84.2`. The candidate model is
At this historical pre-1.0 checkpoint, the runner pinned `pi-acp@0.0.33` and
`@earendil-works/pi-coding-agent@0.84.2`. The candidate model was
`openrouter/deepseek/deepseek-v4-flash-0731`; only an explicitly bound OpenRouter
credential may reach this profile. `patches/pi-acp@0.0.33.patch` repairs the ACP
wrapper. `pi-runtime-extension.ts` supplies the runner-owned semantic bridge and
@@ -985,3 +1140,37 @@ that ID unchanged into the shared MCP dedupe boundary. This is a further
integration defect. The shared dedupe guard and canonical grader remain intact.
Both runs lack terminal usage; measured billing is $0.002440082 and cleanup
passes. Restart and refreshed hello are held until this defect is repaired.
## Explicit host installation
For a published local Paperclip installation, run `paperclipai runtime setup pi`
with the same installed CLI and account that owns the server package. This is an
explicit download and verification step; npm installation and agent launch never
perform it automatically. It installs only this host's supported platform
(macOS ARM64, macOS x64, or Linux x64), using the source-pinned Node archive, npm
lock, wrapper patch and complete Pi closure. Node 24, npm, git, tar and the normal
platform dependency inspector (`otool` or `ldd`) must be available. The server
package must be writable by the installing account. Explicit setup preserves
`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`, their lowercase equivalents,
`SSL_CERT_FILE`, `SSL_CERT_DIR` and
`NODE_EXTRA_CA_CERTS` for public downloads, and enables Node's environment proxy
handling. The provisioner keeps the same closed allowlist. Instance settings,
provider credentials, user npm configuration, `HOME`, `NODE_OPTIONS` and
`NODE_PATH` are excluded; TLS certificate validation stays enabled.
The public server carries a self-contained setup tool and small pinned inputs in
`dist/vendor/paperclip-runner/cli`; the installed host closure lives in that
server package's `provider-assets/pi/<platform>`. Setup validates an existing
closure again before accepting it. A corrupt existing installation is left
untouched and rejected; reinstall the same Paperclip release into a clean package
location and repeat setup. Concurrent setup is rejected. Cancellation drains the
current bounded download/build command before removing its private staging tree;
allow that cleanup to complete before trying again.
Then select Pi with an explicit provider/model ID and bind its provider credential
through the normal agent environment configuration. Setup itself makes no model request.
A missing host closure produces explicit setup guidance. Daytona uses the
separately built and verified Linux provider pack in its runner image; running
local setup does not install or qualify a remote image. Published-tar local and
Daytona startup evidence must bind the final installation candidate, with no
candidate qualification flags, before a production-readiness claim.
+105 -11
View File
@@ -22,6 +22,100 @@ for the exact source/image evidence and merge status.
All dated checkpoints below describe historical qualification attempts. Their
failures and profile numbers are retained; they are not current release gates.
## Historical Pi 1.0 qualification checkpoint — October 2, 2026
Pi uses `@earendil-works/pi-coding-agent@1.0.0`, `pi-acp@0.0.33`, and ACPX
`0.13.1`. Profile **13** adds explicit, native-acknowledged reasoning selection
for the exact model `openrouter/deepseek/deepseek-v4-flash-0731`. New Pi
configuration and qualification cases select `low`. This candidate is not yet
production qualified. Cursor v10 and Copilot v13 remain gated.
The installed profile-13 candidate at `eac50643213d0902a93a5384bae2f1d6c065c9f2`
has paid local passes for hello, semantic question continuation, all four native
question forms, and human permission denial without a file side effect. Its
paid extended Runner `get-task-context` case passes against the authenticated
seeded test control plane. That protocol case does not qualify the Product UI.
File validation, pending-input controller restart, and three-turn warm
continuation remain failed and unregraded. Assertion repairs and an actual
SDK/wrapper replay now cover the identified boundaries; fresh live proof is
still required. See the [historical Pi checkpoint](runner-pi-capabilities.md#historical-profile-13-qualification-checkpoint-2026-10-02)
for the request-stream diagnosis and remaining platform gates.
Copilot's declaration hashes the shared sidecar, sidecar protocol, direct driver,
and generated schema bundle. Pi's reasoning field changed those four files, so
Copilot's pending declaration advances to v13 with digest
`sha256:3ff08fbe76fe4549c9eb01e8794428d8909c65c151d775220f2ec111d9e6f7c1`.
Its executable, distribution closure, model, permissions, and qualification
status are unchanged. The v12 declaration remains historical, and v12 warm
sessions are rejected. This source-identity repair supplies no Copilot paid proof.
The first profile-13 source (`f5c5fde38`) built a fresh ARM daemon and Pi pack,
then passed original startup and all 61 native/ACP contract tests without model
calls. Its full Runner suite found three missing-mode test fixtures and the
stale Copilot declaration. Those failures are retained. The corrected final
source still requires fresh platform builds, complete checks, and paid tests.
Profile 12 passed one paid local hello through the actual installed public
CLI/server and normal runtime setup. The next question-continuation case failed
at the unchanged 120-second native deadline: Pi emitted 1,019 reasoning deltas,
but no tool call or question. The tool and schema were present. One native turn
was submitted; the two visible start rows were canonical and mirrored activity,
not evidence of two provider requests. Both attempts completed owned-process,
IPC, temporary-root, installed-inventory, and post-run accounting checks.
The dedicated key recorded $0.000510742 for the hello and $0.004995065 for the
failed question. Including the earlier profile-11 failure ($0.000142518), its
observed total was $0.005648325 at that reconciliation. These are observed key
usage changes, not native per-request bills. No failed result has been regraded.
Diagnosis found that the runner did not select the ACP reasoning mode. The
pinned model's implicit Pi `medium` setting resolves to `high`; this behavior
also existed in Pi 0.84.2. Pi 1.0 exposes a genuine `low` level. Profile 13 carries
an explicit setting through configuration, transport, and durable identity,
and requires the native effective level to match before a prompt is sent.
It does not increase the timeout. The timed-out HTTP body was not captured,
so source-derived default mapping does not establish the cause of that failure.
Fresh qualification must use the new profile and exact final build.
Historical source `4c58da84fd86a0cd7bc1d952987b031786fc6b2b` passed full Runner
verification and normal Intel startup at 28.295 seconds under the original
30-second limit, plus all 48 native/ACP contract tests. The Intel result has
only 1.705 seconds of margin and does not establish broad cold-start reliability.
Its fresh Linux daemon, Pi pack, and image were built and inventoried; live
Daytona qualification remained pending. The public Mac installation reproduced
the complete Pi dependency closure using npm 11.19.0 from the verified Node
archive. None of these artifacts qualifies profile 13.
The same source's full repository check failed six stale test assertions and
an `ETXTBSY` binary-staging error; the downstream Grok check then lacked built
server output. Typecheck, token gates, and Product E2E typecheck/unit checks
passed. The stale assertions have targeted repairs. A Linux process owner was
not captured for `ETXTBSY`; two exact native fixtures later passed on ARM with
all owned daemon handles closed, which does not resolve the Linux failure.
The next complete source run retains bounded executable-holder evidence around
check boundaries. A later run on obsolete harness source was canceled by the
lead and is retained as incomplete, not successful verification.
Normal Daytona setup has an explicit operator command to import a verified
Linux companion into the installed server. It binds the trusted manifest to the
installed source, Pi profile, daemon, and complete provider-pack inventory, then
uses ordinary remote execution without test-only binary or pack overrides.
The final installed import, image publication, and paid proof remain required.
The dedicated Pi test key has a $5 lifetime OpenRouter-credit limit. Its BYOK
charges are outside that provider-enforced limit, so qualification additionally
uses the reviewed no-BYOK operational policy, fresh account/key evidence, one
paid case at a time, and usage monitoring. The $5 reservation is counted once
within the combined $100 campaign budget. Native price estimates are never
substituted for provider bills.
The [Pi capability inventory](runner-pi-capabilities.md#historical-pi-10-candidate-2026-10-02-profile-v13)
records native interfaces, ACP mappings, user surfaces, and explicit gaps.
The comparison below remains the supported-surface map; old observations retain
their exact historical profile identities. Final source checks and profile-13
local Product, Runner protocol, native-control, and Daytona qualification remain
pending.
Historical source checkpoint (2026-10-01): **Cursor v10, Copilot v12 and Pi v10
remain unqualified**. Copilot receipt v2 distinguishes original provider
arguments from the validated outgoing completion input. The sidecar commits
@@ -73,7 +167,7 @@ as `25303cf84953985b961b95f89aff0bdb864b2d65`, from head
unchanged; this adds no paid proof. Those definitions remain the historical
Cursor v8 checkpoint and require a separate reviewed Cursor v9 update.
Current checkpoint (2026-09-30): **Cursor v9, Copilot v8 and Pi v10 remain unqualified.** The frozen runtime is `5c69b69ef2aeab8d8a367b25a8d894cc5308befa`; controller candidate is `a8df2064d68f40fbf4dec670c4b8478c4b1b1b3f`. All profiles bind shared ACPX patch SHA-256 `bd5393058a218040d217fa85449d59a6f30507de54cd645bf0ef21422823f85e`. No profile is promoted and no prior grade is changed.
Historical checkpoint (2026-09-30): **Cursor v9, Copilot v8 and Pi v10 remain unqualified.** The frozen runtime is `5c69b69ef2aeab8d8a367b25a8d894cc5308befa`; controller candidate is `a8df2064d68f40fbf4dec670c4b8478c4b1b1b3f`. All profiles bind shared ACPX patch SHA-256 `bd5393058a218040d217fa85449d59a6f30507de54cd645bf0ef21422823f85e`. No profile is promoted and no prior grade is changed.
Current-profile protocol eval definitions merged in [paperclip-evals #36](https://github.com/paperclipai/paperclip-evals/pull/36) as `d987357461933baca0d4c10cc081f40e7eae5c1b`: 136 deterministic tests and 21 validated cells. These definitions do not supply paid qualification evidence.
@@ -683,22 +777,22 @@ deterministic evidence are mapped separately after the comparison.
| Capability | Codex app-server benchmark | Cursor ACP candidate | Copilot ACP candidate | Pi ACP candidate |
| --- | --- | --- | --- | --- |
| Exact model | Selected and reported model | Explicit ID required; exact echo, paid semantic protocol and five local semantic product cases passed | Explicit ID required; exact `gpt-5.6-luna` echo, paid semantic protocol and local completion/file/plan/restart passed | Exact `openrouter/deepseek/deepseek-v4-flash-0731`; model echo and v2/v3 paid Product completion/file/question cases passed; v5 native controls passed |
| Exact model | Selected and reported model | Explicit ID required; exact echo, paid semantic protocol and five local semantic product cases passed | Explicit ID required; exact `gpt-5.6-luna` echo, paid semantic protocol and local completion/file/plan/restart passed | Exact `openrouter/deepseek/deepseek-v4-flash-0731`, native-verified `low`; profile-13 paid hello, semantic continuation, native questions and human denial pass; file/restart/warm failures remain open |
| Text and tools | Typed thread/turn/item events | Standard ACP updates; child activity kept separate | Standard ACP plus opt-in native session events | Wrapper text/tool updates and owned tool gates |
| Active steering | Dedicated `turn/steer` | Concurrent prompt replaces/cancels, so it is not steering | Concurrent prompt replaces/cancels, so it is not steering | Owned `pi/steer` requires handshake, exact active turn and acknowledgment; real active-turn probe passed |
| Queued follow-up | Product continuation controls | Controller can schedule a later prompt; native queue not established | Native pending-message activity exists; no qualified ACP queue responder | Owned `pi/follow_up`, separately named and ordered; real queued marker followed the steered current response |
| Active steering | Dedicated `turn/steer` | Concurrent prompt replaces/cancels, so it is not steering | Concurrent prompt replaces/cancels, so it is not steering | Owned `pi/steer` requires handshake, exact active turn and acknowledgment; historical probe passed, profile-13 paid proof pending |
| Queued follow-up | Product continuation controls | Controller can schedule a later prompt; native queue not established | Native pending-message activity exists; no qualified ACP queue responder | Owned `pi/follow_up`, separately named and ordered; historical marker-order proof, profile-13 paid proof pending |
| Cancellation | Typed interrupt and process lifecycle | ACP cancel; paid command cleanup pending | ACP cancel; attached async native settlement passes offline. Explicit detached work is rejected before side effects; it is not supported background settlement | Native abort; wrapper waits for `agent_settled` and treats provider errors as failure |
| Session continuity | Read/load/history/fork and durable identity | Session load/list observed; paid semantic warm continuation passed; native history replay unverified and fork absent in tested methods | Session load plus native history events; semantic pending-question controller recovery passed | Private Pi JSONL mapping/load; native RPC `fork`, `clone`, `get_fork_messages` are not mapped through this ACP wrapper; unresolved UI promises cannot survive provider death |
| Questions | Typed input requests and response correlation | `cursor/ask_question`, option identity and multiple selection preserved | Native ask-user capability exists, but pinned ACP does not wire its responder; do not display a false answerable form | `select`, `confirm`, `input`, `editor` through typed form elicitation |
| Permissions | Durable typed approvals | Standard ACP permission options; denied shell write had no observed side effects; separately labeled exact-correlation assessment | Standard ACP; real native reject_once prevented marker creation; session decision scope inspected | Native pre-tool gate; allow once, exact-operation session grant, deny; paths rechecked after wait |
| Plans | Typed plan and collaboration mode | `cursor/create_plan` includes full plan and revision-bound accept/reject/cancel; todo activity separate | Native plan events displayed; native plan-decision callback not exposed in ACP | No native structured plan event; authenticated Paperclip planning tools available |
| Authenticated tools | Runner bridge and governed operations | ACP HTTP MCP binding; paid context/history reads passed | ACP HTTP MCP binding; paid context read passed | Owned extension registers exact bound MCP tools; four authenticated semantic reads succeeded in a paid partial run; no ambient servers |
| Authenticated tools | Runner bridge and governed operations | ACP HTTP MCP binding; paid context/history reads passed | ACP HTTP MCP binding; paid context read passed | Owned extension registers exact bound MCP tools; profile-13 paid Product completion/questions and seeded Runner context pass; no ambient servers |
| Delegation | Typed agent roles and lifecycle | Opt-in subagent lifecycle, nested ownership and bounded child activity; never parent transcript flattening | Native session details retain agent/model fields with unknown originating turn; typed turn-owned delegation is not inferred | No built-in ACP delegation protocol; arbitrary extensions are excluded |
| Files/diffs | Typed file changes and artifact references | Standard tool changes plus validated image references | Correlated ACP tool events remain available; native session file/workspace details are session notices, not attributed task file changes | Wrapper-retained read/write/edit diffs; common typed/UI projection remains partial; semantic artifact tools |
| Images/artifacts | Typed references and registered work products | Existing contained files only, provenance, `registered:false` | Native session artifact details are bounded notices with no inferred turn ownership or automatic registration | Image/resource tool blocks preserved by wrapper; dedicated artifact channel absent |
| Image/attachment input | Typed input conversion | ACP advertises images, but the runner turn converter currently forwards text only | ACP advertises images/embedded context, but the runner turn converter currently forwards text only | Native Pi/ACP image input exists, but the runner turn converter currently forwards text only |
| Usage | Per-request receipt and model context | Pinned ACP omitted receipts on denied and successful turns; account UI confirms included usage separately | ACP/native tokens retained; account UI confirms included credits separately, without a per-run USD receipt | Assistant-message and compaction token receipts; dollar cost is a catalog pricing estimate, never authoritative billing |
| Config/model changes | Typed configurable controls | Agent/Plan/Ask setup is bound to native configuration acknowledgements and recovery; unsolicited mode drift fails admission. Rich parameterized model picker remains unused | Model/reasoning/mode options exist; runtime policy remains authoritative | Exact pinned candidate model; arbitrary slash commands/config/extensions disabled |
| Config/model changes | Typed configurable controls | Agent/Plan/Ask setup is bound to native configuration acknowledgements and recovery; unsolicited mode drift fails admission. Rich parameterized model picker remains unused | Model/reasoning/mode options exist; runtime policy remains authoritative | Exact model; native available levels and set/get-state confirmation map through ACP mode/config to typed `piThinkingLevel`, recovery identity and UI setup. Active-turn mode changes and arbitrary slash commands/extensions remain disabled |
| Reconnect/restart | Durable controller replay and qualified provider restoration | Semantic pending question survived a real controller restart; exact native callback restoration remains unverified | Semantic pending question survived controller restart with the same interaction and provider session; native callback restoration remains unverified | Wrapper explicitly advertises live-process-only pending-input recovery |
| Shared capability | User-visible surface | Inspectable implementation / deterministic evidence |
@@ -763,7 +857,7 @@ configuration defaults to full auto; it never overrides read-only task policy.
## Distribution and isolation
Cursor pins `2026.09.26-dd393fe`; Copilot pins `1.0.88`; Pi pins wrapper `0.0.33`,
runtime `1.0.0` (Pi profile v12), portable Node and its full npm lock. Native distribution hashes
runtime `1.0.0` (Pi profile v13), portable Node and its full npm lock. Native distribution hashes
cover macOS ARM64, macOS x64 and Linux x64. Source-owned closure pins remain
separate from profile declaration digests. Native admission reads held files,
verifies every admitted byte, creates a private immutable snapshot and retains
@@ -792,8 +886,8 @@ qualification gates, not claims that a JavaScript path check confines a shell.
| Priority | Exposed but unused, partial, or unverified | Reason and next proof |
| --- | --- | --- |
| P0 | Remaining paid product cases on local and Daytona | Current Cursor7/Copilot7/Pi9 require authenticated local and Daytona evidence on the exact current runtime. Historical Cursor4 passed hello/question/plan/restart but its latest file marker failed despite correct bytes. Copilot4 passed all five basic local journeys and Daytona hello. Pi7 passed native questions but continuation exposed the final-message bug repaired in8. The semaphore blocker is resolved and Cursor's approved on-demand cap is $25. Native interaction, denial, settlement, platform and complete cost/cleanup gates remain open; no old profile pass qualifies new bytes. |
| P0 | Pi fresh-profile Product verification | Historical v4 plan startup failed with unavailable Postgres semaphores. Historical v6 attempts exposed profile admission and verified-runtime startup faults, repaired without raising deadlines. Preserve every failed attempt and run unchanged canonical cases against the final build; do not remove unrelated IPC objects. |
| P0 | Remaining paid product cases on local and Daytona | Current Cursor10/Copilot13/Pi13 require authenticated local and Daytona evidence on the exact current runtime. The current Pi checkpoint above supersedes older profile coverage. Historical Cursor4 passed hello/question/plan/restart but its latest file marker failed despite correct bytes. Copilot4 passed all five basic local journeys and Daytona hello. Pi7 passed native questions but continuation exposed the final-message bug repaired in8. The semaphore blocker is resolved and Cursor's approved on-demand cap is $25. Native interaction, denial, settlement, platform and complete cost/cleanup gates remain open; no old profile pass qualifies new bytes. |
| P0 | Pi profile-13 Product and platform verification | Four paid local cases and one seeded Runner case pass. File validation, pending-input restart and warm continuation remain failed; assertion repairs do not regrade them. Finish the remaining local, Runner/native-control, Intel startup and Linux/Daytona cases on fresh final builds. Earlier semaphore and v6 startup faults remain historical evidence; never remove unrelated IPC objects. |
| P0 | Copilot native ask-user and plan-decision callbacks | Pinned ACP does not install native responders. Prove no blocking request is exposed, or add a qualified responder/wrapper; never swallow the request. |
| P0 | Broader Copilot denial and background settlement qualification | Pinned 1.0.88 and isolated 1.0.89 settle attached async commands, but deliberately detached work can finish after end_turn. The earlier paid detached success depended on that model waiting and is not general settlement evidence. Profiles v3/v4 reject explicit detached admission before effects; governed long-lived background work remains unsupported. Denial and process-death recovery pass offline; paid local/Daytona proof remains required. |
| P0 | Cursor native question availability | Explicit Luna and Composer native-only Plan-mode probes admitted the selected model and trusted instructions but emitted no question callback. The vendor-patch reversal and actual MCP-context constructor proof identify no local native-tool removal. Effective native tool selection is beyond the remote AgentService boundary; seek upstream catalog/availability evidence. No further blind model grid or semantic-question substitution qualifies this feature. |
@@ -808,7 +902,7 @@ qualification gates, not claims that a JavaScript path check confines a shell.
| P1 | User attachments and image prompting | `AcpxRuntimeTurnInput` and the common runtime adapter currently forward text only, despite underlying image-input support. Implement validated attachment-to-ACP content conversion and model-specific capability admission, then qualify real local/Daytona image prompts. This is an implementation gap as well as a live-verification gap. |
| P1 | Copilot native session event attribution | `_session_event` omits an originating turn. Preserve bounded event fields as session-scoped notices with `turnAttribution: unknown`; typed delegation, artifacts and compaction need an explicit native correlation contract before turn-owned projection. Standard correlated ACP events remain separate. |
| P1 | Copilot session-store files and export/artifact URIs | Provider paths are not task-workspace paths. Add a separately authorized export flow with validated bytes and provenance; do not resolve arbitrary URLs or auto-register. |
| P1 | Pi native fork/history/export interfaces | Pinned Pi 0.84.2 native RPC exposes `fork(entryId)`, `clone`, `get_fork_messages` and `export_html`. The wrapper does not map them to runner controls. Add durable branch lineage for fork/clone and an authorized, contained artifact flow for HTML export before exposing them; do not label these native capabilities absent. |
| P1 | Pi native fork/history/export interfaces | Pi native RPC exposes `fork(entryId)`, `clone`, `get_fork_messages` and `export_html`; these remain available in the pinned 1.0.0 release. The wrapper does not map them to runner controls. Add durable branch lineage for fork/clone and an authorized, contained artifact flow for HTML export before exposing them; do not label these native capabilities absent. |
| P1 | Complete usage/billing provenance | Missing cache fields remain unknown. Pi price estimates are displayed separately. Budget qualification requires actual spend coverage, not an estimate presented as a bill. |
| P1 | Fork/history and richer configuration controls | Cursor session mode now has explicit admission-bound setup. Arbitrary session discovery/forking, mid-turn configuration changes and the parameterized model picker still need company-scoped controls and durable lineage. |
| P1 | Exact pending-request restoration after process death | Session transcript restoration does not restore callbacks. Expire unresolved requests unless a provider proves exact restoration. |
@@ -816,7 +910,7 @@ qualification gates, not claims that a JavaScript path check confines a shell.
| P2 | Remaining Copilot native diagnostic/config/account events | The provider inventory records every event and field, its projection or reason for omission. Preserve bounded useful context; avoid credentials, raw environment or unbounded blobs. |
| P2 | Pi empty or whitespace-only submitted input/editor text | Canonical required text rejects blank responses; optional blank responses are omitted. Defaults can be empty and nonblank text preserves boundary whitespace. Add explicit empty-text semantics across TypeScript, Rust and UI before claiming complete native empty-answer parity. |
| P2 | Pi native extension surfaces and unsupported slash commands | Arbitrary extensions/templates/themes may execute ambient code. Only reviewed runner-owned capabilities are admitted; structured native plan/goals are not fabricated. Native fork/clone/export are separate unmapped capabilities above. |
| P2 | Pi status/widget/title/editor and session/configuration notifications | `setStatus`, `setWidget`, `setTitle` and `set_editor_text` have no UI projection and are unused by the owned extension. Native session-name and thinking-level events also lack a dedicated projection. Add reviewed bounded notice schemas and governed configuration controls before exposing these fields; `notify` and interactive input already have separate bridges. |
| P2 | Pi status/widget/title/editor and session/configuration notifications | `setStatus`, `setWidget`, `setTitle` and `set_editor_text` have no UI projection and are unused by the owned extension. Native session-name and thinking-level notifications also lack a dedicated projection, although selected thinking level is now handled through ACP mode/config and native confirmation. Provider notice summary/severity has deterministic UI coverage, with rebuilt paid visual proof pending. Add bounded schemas for the remaining fields; `notify` and interactive input already have separate bridges. |
| P2 | Pi invocation and history provenance metadata | The v4 wrapper retains `nativeToolCallId`, `modelIteration`, `historyMessageIndex` and `identityScope` in private ACP-wire metadata. Closed common tool and permission projections omit them from the UI. Normalized IDs still correlate live tool, MCP and permission events. Add bounded, redacted display-only provenance fields and parity tests before surfacing the native metadata. |
| P2 | Conditional native-plan follow-up fields | Cursor's optional rejection-reason field also appears for accept/cancel. The current question renderer has no conditional fields; add conditional presentation without changing the revision-bound decision receipt. |
| P2 | Cursor command exit code projection | The paid file case preserved native `exitCode: 0` inside output text, while the canonical command field remained null. Normalize a typed, correlated exit code without parsing arbitrary prose; current independent file assertions do not prove this field. |
+45 -11
View File
@@ -36,15 +36,15 @@ Docker materialization, Git installer, or extra login isolation wholesale.
## Current slice: Codex defaults
Authorized 2026-10-09. Canonical branch: `codex/codex-runner-default`.
Master base: `835a022936ddc7a152b9feab0c0420d02249a6d1`.
Integration base: master `2dd9811e8be1dab59cccd86cdb25e8953b02fe07`.
Canonical PR: [draft #15683](https://github.com/paperclipai/paperclip/pull/15683).
Latest reviewed candidate: `1be8502f27b042566df5fc2d88e46dbcfc8484f3`.
Latest pushed candidate before integration: `4275309f9d619055f48a9b21cb0ad0a1ff7c2c63`.
The follow-up fixes configure-on-first-use for an existing built-in that still
needs setup. The PR remains under 100 files, with no workflow or lockfile
changes. Fresh final-head CI and review are required after that fix.
Preview: [isolated Codex QA](http://127.0.0.1:3125), normal dev supervisor,
separate database. Hosted Linux live onboarding passed at `38199ea8`; execution
code is unchanged at `1be8502f`. UI changes have separate revision-bound proof.
separate database. Hosted Linux live onboarding passed at `38199ea8`; it remains
historical proof after the lifecycle integration. UI has separate revision-bound proof.
Attended local subscription and managed staging journeys remain unverified.
New Codex agents select Paperclip Runner on qualified Linux x64 targets. Users
@@ -78,13 +78,13 @@ Claude's explicit native fixture is unchanged until its later default PR.
| Area | Owner | Current state |
| --- | --- | --- |
| Shared contract, server resolution, setup readiness | Core worker | 394 focused cases and 147 guard/inheritance controls pass; server noemit passes; counts overlap |
| Shared contract, server resolution, setup readiness | Core worker | Integrated lifecycle: 210 core cases, 109 connection cases and five affected refresh controls pass; server noemit passes; counts overlap |
| Production create/edit/onboarding UI and stories | UI worker | 171 fresh focused cases, 30 desktop/10 mobile captures and six keyboard checks; built-in follow-up passes 15 cases, UI typecheck and token gates |
| Built-ins, plugins, approvals, imports/exports, CLI | Creation-path worker | 105 portability, eight approval, three CLI and three asset checks pass; 77 corrected skill-route cases pass; full Linux checks pending on final head |
| Built-ins, plugins, approvals, imports/exports, CLI | Creation-path worker | Integrated lifecycle: 105 portability, eight approval and three asset cases pass; 73 DB cases skipped on macOS; final Linux checks required |
| Execution/dev gate, E2E gaps, packaging, live journeys | Lead | Selected Linux onboarding case passes all 13 assertions, actual task/artifact/follow-up and cleanup; 149 public-projection/support cases pass |
| Full CI and final review | Lead | Native compilation passes at `1be8502f`; main CI is running; its fresh 4/5 review finding is fixed locally, with final-head replay required |
| Full CI and final review | Lead | All seven known findings fixed/resolved; master lifecycle merge conflicts resolved locally; new combined head needs full CI and fresh review |
| Local subscription task + follow-up | Lead | Embedded-browser onboarding prepared; attended sign-in unfinished; macOS automatic legacy selection is expected |
| Managed staging API/subscription onboarding | Lead | Dedicated tenant access, serving revision, snapshot and cleanup ownership unresolved; Fleet Admin needs attended sign-in |
| Managed staging API/subscription onboarding | Lead | Fleet Admin sign-in completed; dedicated tenant exists, active/awake and pinned to old release; scoped one-hour QA owner access approved; final serving revision/snapshot/runtime/cleanup qualification pending |
| Shipped npm/Docker/cloud artifacts | Lead | Clean Linux npm consumer passes at the prior candidate: 18 packages, no Codex payloads, host dependency from official npm; final-head replay pending; actual cloud composition is post-merge |
Keep CPU-heavy Rust/Docker builds in hosted CI. Use Node 24, bounded workers,
@@ -220,9 +220,11 @@ proof is in progress. Existing UI verification passed 28 desktop/eight mobile
renders, six keyboard/footer cases and two touch/wheel journeys. Final CI/review
must run after this combined follow-up is frozen.
The isolated preview remains [3125](http://127.0.0.1:3125/COD/dashboard).
Its supervisor now uses the correct port and the backend restarted at
The isolated preview uses [3125](http://127.0.0.1:3125/COD/dashboard).
Its supervisor uses the correct port and the prior backend restarted at
`2026-10-09T15:28:08.305Z`. No user preview or the separate OAuth proxy was stopped.
The owned supervisor/backend were gracefully paused during lifecycle integration;
restart and serving-source verification are required before another live journey.
The first-agent name draft survived reload. The cached local daemon is not proof
of the new native Rust seams; Linux hosted build/live execution supply that proof.
Attended subscription login and current access to the dedicated managed staging
@@ -252,6 +254,38 @@ running, with no test failure observed yet.
Next action: freeze the built-in setup follow-up, require green
exact-head CI and fresh 5/5 review, and publish sanitized retained evidence when
operator access is available. Complete the attended and managed staging journeys
when access is available. The PR stays
when their remaining resources are ready. The PR stays
a draft and is neither merge-ready nor production-ready yet. Merge and production
deployment remain outside authorization.
### 2026-10-09 Current-master lifecycle integration
Master merged [#15631](https://github.com/paperclipai/paperclip/pull/15631) during
qualification. GitHub blocked the new candidate on nine real merge conflicts.
The integration preserves master's agent lifecycle ownership. Common runner
resolution now runs in `prepareAgentHire`; approval activation retains the frozen
reviewed runner, responsible-user identity and credential restrictions. Existing
agent updates keep their saved execution. Obsolete source edits were removed,
and redundant generic API prose was dropped while the agent-creation skill and
its reference retain the complete runner contract. The diff remains 99 files.
Focused integration checks pass: 210 core, 109 connection, five affected refresh,
105 portability, eight approval and three built-in asset cases. Counts overlap.
Server noemit and the existing lifecycle-boundary scanner pass. Shared, DB and
plugin SDK JavaScript outputs were refreshed without migrations, Rust or Docker.
The 73 DB-heavy cases were skipped on macOS and require hosted Linux proof.
The full local route-fixture attempt was interrupted and is incomplete evidence;
loopback restrictions were identified before its bounded affected-case rerun.
That unrestricted rerun passes all 61 selected cases; 108 unrelated cases were
excluded and remain part of required full hosted CI.
The human completed Fleet Admin sign-in. The dedicated QA stack exists and is
active, awake, healthy and user-managed, so ordinary fleet rollouts skip it.
It still serves historical Core `2dbe43a4`, not this candidate. The human approved
one hour of scoped owner access for this QA tenant through the audited admin flow.
No release change, provider task, new image or fleet-wide action has run here.
Next action: freeze/push the integrated candidate,
require exact-head CI and fresh 5/5 review, restart the matched local preview and
qualify the dedicated managed target against that candidate. The previous Linux
run is retained evidence; it must not be relabeled as the new live measurement.
+1 -1
View File
@@ -9,7 +9,7 @@ The first built-ins are `briefs` and `learning`. Operators can provision them fr
The subsystem has four layers:
- Registry: `server/src/services/built-in-agents.ts` defines the static `BuiltInAgentDefinition` list.
- Marker: `server/src/services/built-in-agent-metadata.ts` reads and writes `metadata.paperclipBuiltInAgent`.
- Marker: `server/src/lib/built-in-agent-metadata.ts` reads and writes `metadata.paperclipBuiltInAgent`.
- Provisioning service: `builtInAgentService(db)` finds, creates, updates, resets, and requires built-ins per company.
- Routes: `server/src/routes/built-in-agents.ts` exposes list, provision, and reset APIs.
@@ -197,7 +197,7 @@ describe("probeClaudeAcpSandboxLogin", () => {
// The parsed result is a success, so no login gate and no probe-unavailable
// check appears.
expect(checks).toEqual([]);
expect(checks).toEqual([expect.objectContaining({ code: "claude_hello_probe_passed", level: "info" })]);
});
it("keeps a non-auth failed probe with a token phrase on the probe-unavailable path", async () => {
@@ -256,7 +256,7 @@ describe("probeClaudeAcpSandboxLogin", () => {
expect(authRequired?.hint).toBe("Run `claude login` in this environment, then retry the probe.");
});
it("emits no checks when the sandbox probe reports a healthy login", async () => {
it("records a successful probe when the sandbox reports a healthy login", async () => {
probeResult.value = { exitCode: 0, stdout: helloStdout, stderr: "", timedOut: false };
const checks = await probeClaudeAcpSandboxLogin({
@@ -264,7 +264,13 @@ describe("probeClaudeAcpSandboxLogin", () => {
target: sandboxTarget,
});
expect(checks).toEqual([]);
expect(checks).toEqual([expect.objectContaining({ code: "claude_hello_probe_passed", level: "info" })]);
});
it("does not record success for an empty probe result", async () => {
probeResult.value = { exitCode: 0, stdout: "", stderr: "", timedOut: false };
const checks = await probeClaudeAcpSandboxLogin({ config: { engine: "acp" }, target: sandboxTarget });
expect(checks).toEqual([expect.objectContaining({ code: "claude_acp_login_probe_unavailable", level: "warn" })]);
});
it("emits a distinct warn check, not a silent pass, when the probe cannot run", async () => {
@@ -552,6 +558,8 @@ describe("Claude ACP hello probe on local and SSH targets", () => {
expect(result.checks).toContainEqual(expect.objectContaining({
code: "claude_acp_anthropic_api_key_detected", level: "warn",
}));
expect(result.status).toBe("warn");
expect(result.checks).toContainEqual(expect.objectContaining({ code: "claude_hello_probe_passed", level: "info" }));
// The host key value never enters a check.
expect(JSON.stringify(result.checks)).not.toContain("sk-ant-host-key");
});
@@ -721,7 +721,10 @@ export async function probeClaudeAcpSandboxLogin(input: {
});
return [buildAcpLoginProbeUnavailableCheck("The Claude login probe did not complete.", targetIsSandbox)];
}
return [];
if (!/\bhello\b/i.test(parsedStream.summary)) {
return [buildAcpLoginProbeUnavailableCheck("The Claude login probe did not return hello.", targetIsSandbox)];
}
return [{ code: "claude_hello_probe_passed", level: "info", message: "Claude login probe succeeded." }];
}
export async function testClaudeAcpEnvironment(
+1 -1
View File
@@ -45,7 +45,7 @@
"generate": "pnpm run check:migrations && pnpm run clean && tsc -p tsconfig.json && drizzle-kit generate && pnpm run prune:snapshots",
"prune:snapshots": "ls src/migrations/meta/*_snapshot.json | sort -r | tail -n +6 | xargs rm -f",
"migrate": "pnpm run check:migrations && tsx src/migrate.ts",
"seed": "tsx src/seed.ts"
"seed": "pnpm --filter @paperclipai/server exec tsx scripts/seed.ts"
},
"dependencies": {
"@paperclipai/shared": "workspace:*",
+2 -1
View File
@@ -7,6 +7,7 @@ import postgres from "postgres";
import { createBufferedTextFileWriter, runDatabaseBackup, runDatabaseRestore } from "./backup-lib.js";
import { ensurePostgresDatabase } from "./client.js";
import {
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./test-embedded-postgres.js";
@@ -105,7 +106,7 @@ describeEmbeddedPostgres("runDatabaseBackup", () => {
if (previous === undefined) delete process.env.PAPERCLIP_PG_DUMP_PATH;
else process.env.PAPERCLIP_PG_DUMP_PATH = previous;
}
});
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
it("preserves identity generation, sequence options and progress in JavaScript backups", async () => {
const source = await createTempDatabase();
@@ -0,0 +1,16 @@
ALTER TABLE "agents" ADD COLUMN "lifecycle_state" text DEFAULT 'ready' NOT NULL;--> statement-breakpoint
ALTER TABLE "agents" ADD COLUMN "lifecycle_required_plugin_ids" jsonb;--> statement-breakpoint
ALTER TABLE "agents" ADD COLUMN "lifecycle_holds" jsonb DEFAULT '[]'::jsonb NOT NULL;--> statement-breakpoint
ALTER TABLE "agents" ADD COLUMN "lifecycle_version" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
ALTER TABLE "agents" ADD COLUMN "lifecycle_error" text;--> statement-breakpoint
ALTER TABLE "agents" ADD COLUMN "lifecycle_operation" jsonb;--> statement-breakpoint
CREATE INDEX "agents_lifecycle_work_idx" ON "agents" USING btree ("lifecycle_state","updated_at","id");
--> statement-breakpoint
UPDATE "agents" SET
"lifecycle_state" = CASE "status"
WHEN 'pending_approval' THEN 'pending_approval'
WHEN 'paused' THEN 'paused'
WHEN 'terminated' THEN 'terminated'
ELSE 'ready' END,
"lifecycle_holds" = CASE WHEN "status" = 'paused'
THEN jsonb_build_array(coalesce("pause_reason", 'manual')) ELSE '[]'::jsonb END;
+7
View File
@@ -2227,6 +2227,13 @@
"when": 1791490887468,
"tag": "0319_heavy_captain_midlands",
"breakpoints": true
},
{
"idx": 320,
"version": "7",
"when": 1791497222457,
"tag": "0320_daily_onslaught",
"breakpoints": true
}
]
}
+8 -1
View File
@@ -1,4 +1,4 @@
import type { AgentAppearance } from "@paperclipai/shared";
import type { AgentAppearance, AgentLifecycleState, AgentLifecycleOperation } from "@paperclipai/shared";
import {
type AnyPgColumn,
pgTable,
@@ -25,6 +25,12 @@ export const agents = pgTable(
icon: text("icon"),
appearance: jsonb("appearance").$type<AgentAppearance>(),
status: text("status").notNull().default("idle"),
lifecycleState: text("lifecycle_state").$type<AgentLifecycleState>().notNull().default("ready"),
lifecycleRequiredPluginIds: jsonb("lifecycle_required_plugin_ids").$type<string[]>(),
lifecycleHolds: jsonb("lifecycle_holds").$type<string[]>().notNull().default([]),
lifecycleVersion: integer("lifecycle_version").notNull().default(0),
lifecycleError: text("lifecycle_error"),
lifecycleOperation: jsonb("lifecycle_operation").$type<AgentLifecycleOperation>(),
reportsTo: uuid("reports_to").references((): AnyPgColumn => agents.id),
capabilities: text("capabilities"),
adapterType: text("adapter_type").notNull().default("process"),
@@ -45,6 +51,7 @@ export const agents = pgTable(
},
(table) => ({
companyIdUq: unique("agents_company_id_uq").on(table.companyId, table.id),
lifecycleWorkIdx: index("agents_lifecycle_work_idx").on(table.lifecycleState, table.updatedAt, table.id),
companyStatusIdx: index("agents_company_status_idx").on(table.companyId, table.status),
companyReportsToIdx: index("agents_company_reports_to_idx").on(table.companyId, table.reportsTo),
companyDefaultEnvironmentIdx: index("agents_company_default_environment_idx").on(table.companyId, table.defaultEnvironmentId),
@@ -6550,11 +6550,11 @@ it("rotates PRP authority in place for a warm cross-run attachment", async () =>
it("reopens Pi after a completed turn within its cold admission budget during warm attachment", async () => {
const root = await mkdtemp(join(tmpdir(), "runnerd-pi-warm-admission-"));
const cliRoot = join(root, "dist/cli");
await mkdir(cliRoot, { recursive: true });
await mkdir(cliRoot, { recursive: true, mode: 0o700 });
const sidecarPath = join(cliRoot, "acpx-runtime-sidecar.cjs");
const journal = join(root, "commands.ndjson");
const fixture = await readFile(fileURLToPath(new URL("./fixtures/fake-pi-warm-sidecar.cjs", import.meta.url)), "utf8");
await writeFile(sidecarPath, fixture.replace("/* fixture-config */ null", JSON.stringify({ journal, resumeDelayMs: 32_000, commandDigest: QUALIFIED_ACPX_PROFILES.pi.commandDigest })));
await writeFile(sidecarPath, fixture.replace("/* fixture-config */ null", JSON.stringify({ journal, resumeDelayMs: 32_000, commandDigest: QUALIFIED_ACPX_PROFILES.pi.commandDigest })), { mode: 0o600 });
const digest = (path: string) => `sha256:${createHash("sha256").update(readFileSync(path)).digest("hex")}`;
const bundle = createCapabilityRunnerdCodexTransport({
provider: "acpx", acpxAgent: "pi", piThinkingLevel: "low", acpxPermissionMode: "deny-all",
@@ -1,3 +1,4 @@
import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
/**
* `definePlugin` — the top-level helper for authoring a Paperclip plugin.
@@ -358,6 +359,8 @@ export interface PluginDefinition {
* Requires `external.objects.read`.
*/
/** Propose a member from host-authorized candidates. Requires ai.connections.route. */
onAgentLifecycle?(params: AgentLifecycleRequest): Promise<AgentLifecycleResult>;
onRouteAiConnection?(params: AiConnectionRouterRequest): Promise<AiConnectionRouterResult>;
onResolveExternalObject?(
+2
View File
@@ -456,3 +456,5 @@ export { preserveEnvironmentSyncErrorDiagnostic, environmentSyncErrorData, readE
export type { PluginEnvironmentSyncErrorDiagnostic } from "./environment-sync-error.js";
export type { AiConnectionPool, AiConnectionPoolConfig, AiConnectionPoolMember, AiConnectionRouterRequest, AiConnectionRouterResult, AiConnectionRouterSelection } from "@paperclipai/shared";
export type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
+3
View File
@@ -1,3 +1,4 @@
import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
/**
* JSON-RPC 2.0 message types and protocol helpers for the host ↔ worker IPC
@@ -1345,6 +1346,7 @@ export interface HostToWorkerMethods {
/** Scoped plugin API route dispatch. */
handleApiRequest: [params: PluginApiRequestInput, result: PluginApiResponse];
/** @see PLUGIN_SPEC.md §13.8 */
agentLifecycle: [params: AgentLifecycleRequest, result: AgentLifecycleResult];
getData: [params: GetDataParams, result: unknown];
/** @see PLUGIN_SPEC.md §13.9 */
performAction: [params: PerformActionParams, result: unknown];
@@ -1481,6 +1483,7 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[]
"runJob",
"handleWebhook",
"handleApiRequest",
"agentLifecycle",
"getData",
"performAction",
"executeTool",
@@ -1,3 +1,4 @@
import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared";
import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
import { environmentCreationCleanupErrorData } from "./environment-creation-cleanup.js";
import { environmentSyncErrorData, withEnvironmentSyncErrorCapture } from "./environment-sync-error.js";
@@ -1659,6 +1660,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
return handleExecuteTool(params as ExecuteToolParams);
case "detectExternalObjects":
return handleDetectExternalObjects(params as DetectExternalObjectsParams);
case "agentLifecycle":
if (!plugin.definition.onAgentLifecycle) throw methodNotImplemented("agentLifecycle");
return plugin.definition.onAgentLifecycle(params as AgentLifecycleRequest);
case "routeAiConnection":
if (!plugin.definition.onRouteAiConnection) throw methodNotImplemented("routeAiConnection");
return plugin.definition.onRouteAiConnection(params as AiConnectionRouterRequest);
@@ -1779,6 +1783,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
if (plugin.definition.onIdleDrain) supportedMethods.push("prepareIdleSleep", "releaseIdleSleep");
if (plugin.definition.onApiRequest) supportedMethods.push("handleApiRequest");
if (plugin.definition.onDetectExternalObjects) supportedMethods.push("detectExternalObjects");
if (plugin.definition.onAgentLifecycle) supportedMethods.push("agentLifecycle");
if (plugin.definition.onRouteAiConnection) supportedMethods.push("routeAiConnection");
if (plugin.definition.onResolveExternalObject) supportedMethods.push("resolveExternalObject");
if (plugin.definition.onRefreshExternalObjects) supportedMethods.push("refreshExternalObjects");
+1
View File
@@ -1340,6 +1340,7 @@ export const PLUGIN_CAPABILITIES = [
"approvals.read",
"issue.documents.read",
"agents.read",
"agents.lifecycle.manage",
"goals.read",
"goals.create",
"goals.update",
+4
View File
@@ -2859,3 +2859,7 @@ export * from "./agent-avatar-upload.js";
export type { DotBinding, DotInvitation, DotConnection, DotPairing } from "./dot-invitations.js";
export { agentHarnessType, agentRunner, paperclipRunnerProfileForHarness, paperclipRunnerSupportsPlatform, type AgentRunnerChoice, type AgentRunner, type AgentRunnerAvailability } from "./agent-runner.js";
export { AGENT_LIFECYCLE_STATES, type AgentLifecycleState, type AgentLifecycleOperation } from "./types/agent-lifecycle.js";
export type { AgentLifecycleRequest, AgentLifecycleResult } from "./types/agent-lifecycle.js";
@@ -0,0 +1,31 @@
/** The lifecycle controls admission. Execution status describes current work. */
export const AGENT_LIFECYCLE_STATES = [
"pending_approval", "preparing", "verifying", "ready", "pausing", "paused",
"resuming", "terminating", "cleaning_up", "terminated", "rejected",
] as const;
export type AgentLifecycleState = typeof AGENT_LIFECYCLE_STATES[number];
export interface AgentLifecycleOperation {
id: string;
resumeState?: "preparing" | "verifying" | "ready";
hostComplete: boolean;
completedPluginIds: string[];
leaseOwner?: string;
leaseUntil?: string;
retryAt?: string;
attempts: number;
responsibleUserId?: string | null;
}
export interface AgentLifecycleRequest {
companyId: string;
agentId: string;
operationId: string;
version: number;
phase: AgentLifecycleState;
}
export interface AgentLifecycleResult {
operationId: string;
version: number;
status: "complete" | "pending";
}
+4
View File
@@ -1,3 +1,4 @@
import type { AgentLifecycleState } from "./agent-lifecycle.js";
import type { AgentAppearance } from "../agent-appearance.js";
import type { AiConnectionLoginIntent } from "../ai-connections.js";
import type {
@@ -90,6 +91,9 @@ export interface Agent {
appearance?: AgentAppearance | null;
avatarUrl?: string;
status: AgentStatus;
lifecycleState?: AgentLifecycleState;
lifecycleVersion?: number;
lifecycleError?: string | null;
reportsTo: string | null;
capabilities: string | null;
adapterType: AgentAdapterType;
+2
View File
@@ -1098,3 +1098,5 @@ export type { AgentInstructionErrorCode, AgentInstructionErrorDetails, AgentInst
export type { AgentInstructionCandidate } from "./agent.js";
export * from "./skill-source.js";
export * from "./agent-lifecycle.js";
+2
View File
@@ -688,6 +688,8 @@ export interface PaperclipPluginManifestV1 {
/** Capabilities this plugin requires from the host. Enforced at runtime. */
capabilities: PluginCapability[];
/** Opt into the native pooled-connection catalog, setup, and management UI. */
/** Required participant in agent preparation, stop, resume, and cleanup. */
agentLifecycle?: true;
aiConnectionRouter?: { name: string; description: string };
/** Entrypoint paths relative to the package root. */
entrypoints: {
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { updateAgentSchema } from "./agent.js";
describe("agent update schema", () => {
it.each(["paused", "idle", "terminated"])("accepts lifecycle status request %s", status => {
expect(updateAgentSchema.parse({ status })).toEqual({ status });
});
it.each(["active", "running", "error", "pending_approval"])("rejects direct status write %s", status => {
const result = updateAgentSchema.safeParse({ name: "Renamed", status });
expect(result.success).toBe(false);
if (!result.success) expect(result.error.issues).toEqual(expect.arrayContaining([
expect.objectContaining({ path: ["status"] }),
]));
});
it.each([{ spentMonthlyCents: 0 }, { name: "Renamed", spentMonthlyCents: 10 }])("rejects spend totals: %j", payload => {
const result = updateAgentSchema.safeParse(payload);
expect(result.success).toBe(false);
if (!result.success) expect(result.error.issues).toEqual(expect.arrayContaining([
expect.objectContaining({ path: ["spentMonthlyCents"] }),
]));
});
it("accepts profile and budget limit changes", () => {
expect(updateAgentSchema.parse({ name: "Renamed", budgetMonthlyCents: 100 })).toEqual({ name: "Renamed", budgetMonthlyCents: 100 });
});
});
+2 -3
View File
@@ -4,7 +4,6 @@ import { z } from "zod";
import {
AGENT_ICON_NAMES,
AGENT_ROLES,
AGENT_STATUSES,
INBOX_MINE_ISSUE_STATUS_FILTER,
} from "../constants.js";
import { agentAdapterTypeSchema } from "../adapter-type.js";
@@ -157,8 +156,8 @@ export const updateAgentSchema = objectWithoutDefaults(
.extend({
permissions: z.never().optional(),
replaceAdapterConfig: z.boolean().optional(),
status: z.enum(AGENT_STATUSES).optional(),
spentMonthlyCents: z.number().int().nonnegative().optional(),
status: z.enum(["paused", "idle", "terminated"]).optional(),
spentMonthlyCents: z.never().optional(),
});
export type UpdateAgent = z.infer<typeof updateAgentSchema>;
@@ -33,6 +33,12 @@ describe("plugin capability constants", () => {
});
describe("plugin manifest validators", () => {
it("requires authority for required agent lifecycle participants", () => {
const manifest = { id: "example.lifecycle", apiVersion: 1, version: "0.1.0", displayName: "Lifecycle", description: "Lifecycle tests", author: "Tests", categories: ["automation"], entrypoints: { worker: "worker.js" }, agentLifecycle: true };
expect(pluginManifestV1Schema.safeParse({ ...manifest, capabilities: ["agents.read"] }).success).toBe(false);
expect(pluginManifestV1Schema.parse({ ...manifest, capabilities: ["agents.lifecycle.manage"] }).agentLifecycle).toBe(true);
});
it("requires routing authority for native pooled connector declarations without a custom UI bundle", () => {
const manifest = { id: "example.pool", apiVersion: 1, version: "0.1.0", displayName: "Pool", description: "Pool", author: "Tests", categories: ["connector"], entrypoints: { worker: "worker.js" }, aiConnectionRouter: { name: "AI connection pool", description: "Use saved connections" } };
expect(pluginManifestV1Schema.safeParse({ ...manifest, capabilities: ["ui.page.register"] }).success).toBe(false);
+5
View File
@@ -782,6 +782,7 @@ export const pluginManifestV1Schema = z.object({
"minimumPaperclipVersion must follow semver (e.g. 1.0.0)",
).optional(),
capabilities: z.array(z.enum(PLUGIN_CAPABILITIES)).min(1),
agentLifecycle: z.literal(true).optional(),
aiConnectionRouter: z.object({ name: z.string().trim().min(1).max(100), description: z.string().trim().min(1).max(500) }).strict().optional(),
entrypoints: z.object({
worker: z.string().min(1),
@@ -806,6 +807,10 @@ export const pluginManifestV1Schema = z.object({
launchers: z.array(pluginLauncherDeclarationSchema).optional(),
}).optional(),
}).superRefine((manifest, ctx) => {
if (manifest.agentLifecycle && !manifest.capabilities.includes("agents.lifecycle.manage")) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Agent lifecycle participation requires agents.lifecycle.manage", path: ["capabilities"] });
}
// ── Entrypoint ↔ UI slot consistency ──────────────────────────────────
// Plugins that declare UI slots must also declare a UI entrypoint so the
// host knows where to load the bundle from (PLUGIN_SPEC.md §10.1).
@@ -0,0 +1,50 @@
import { readdirSync, readFileSync } from "node:fs";
import { resolve, relative } from "node:path";
import { fileURLToPath } from "node:url";
const protectedFields = new Set(["pauseReason", "pausedAt", "lifecycleState", "lifecycleVersion", "lifecycleError", "lifecycleOperation", "lifecycleRequiredPluginIds", "lifecycleHolds", "adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"]);
export function agentLifecycleWriteViolations(source, file = "") {
const aliases = [...source.matchAll(/\bagents(?:\s+as\s+(\w+))?\s*[,}]/g)].map(match => match[1] ?? "agents");
const violations = [];
const text = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, "");
for (const alias of new Set(aliases)) {
for (const match of text.matchAll(new RegExp(`\\.(insert|delete|update)\\(\\s*${alias}\\s*\\)([^;]*)`, "g"))) {
const [, operation, chain] = match;
if (operation !== "update") { violations.push(operation === "delete"
? "Use the agent lifecycle module to delete an agent"
: "Use the agent lifecycle module to insert an agent"); continue; }
for (const field of protectedFields) {
// The offline seed copy disables timers before any server can verify or run an agent.
if (field === "runtimeConfig" && file === "cli/src/commands/worktree.ts") continue;
if (new RegExp(`(?<![\\w.])${field}\\s*(?=:|[,}])`).test(chain)) violations.push(`Use the agent lifecycle module to change ${field}`);
}
if (/\bstatus\s*:/.test(chain) && !chain.includes(`eq(${alias}.lifecycleState, "ready")`)) {
violations.push("An execution status write must require lifecycleState ready");
}
}
}
return violations;
}
export function scanAgentLifecycleBoundaries(root = resolve(fileURLToPath(new URL("..", import.meta.url)))) {
const violations = [];
function walk(directory) {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (["node_modules", "dist", "__tests__"].includes(entry.name)) continue;
const path = resolve(directory, entry.name);
const label = relative(root, path);
if (label.includes("modules/agent-lifecycle/")) continue;
if (entry.isDirectory()) walk(path);
else if (/\.tsx?$/.test(entry.name) && !/\.(test|spec)\./.test(entry.name)) {
for (const reason of agentLifecycleWriteViolations(readFileSync(path, "utf8"), label)) violations.push(`${label}: ${reason}`);
}
}
}
for (const directory of ["server/src", "server/scripts", "cli/src", "packages/db/src"]) walk(resolve(root, directory));
return violations;
}
if (resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) {
const violations = scanAgentLifecycleBoundaries();
if (violations.length) { console.error(violations.join("\n")); process.exitCode = 1; }
else console.log("Agent lifecycle write boundary check passed.");
}
@@ -0,0 +1,31 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { agentLifecycleWriteViolations } from "./check-agent-lifecycle-boundaries.mjs";
const source = body => `import { agents as records } from "@paperclipai/db"; ${body}`;
test("finds inserts, deletes, and lifecycle writes through an import alias", () => {
for (const body of ["db.insert(records).values(input)", "db.delete(records)", "db.update(records).set({ lifecycleState: 'ready' })", "db.update(records).set({ pauseReason })"]) {
assert.equal(agentLifecycleWriteViolations(source(body)).length, 1);
}
});
test("permits configuration writes and guards execution status writes", () => {
assert.deepEqual(agentLifecycleWriteViolations(source("db.update(records).set({ name })")), []);
assert.equal(agentLifecycleWriteViolations(source("db.update(records).set({ status: 'idle' })")).length, 1);
assert.deepEqual(agentLifecycleWriteViolations(source('db.update(records).set({ status: "idle" }).where(eq(records.lifecycleState, "ready"))')), []);
});
test("execution configuration writes must use lifecycle invalidation", () => {
for (const field of ["adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"]) {
assert.equal(agentLifecycleWriteViolations(source(`db.update(records).set({ ${field}: value })`)).length, 1);
}
});
test("offline seed quarantine can disable timers but cannot change lifecycle state", () => {
const file = "cli/src/commands/worktree.ts";
assert.deepEqual(agentLifecycleWriteViolations(source("db.update(records).set({ runtimeConfig })"), file), []);
assert.equal(agentLifecycleWriteViolations(source("db.update(records).set({ lifecycleState: 'ready' })"), file).length, 1);
});
test("rejects agent deletion outside the module even with a terminal state guard", () => {
assert.equal(agentLifecycleWriteViolations(source('db.delete(records).where(and(eq(records.id, id), inArray(records.lifecycleState, ["terminated", "rejected"])))')).length, 1);
assert.equal(agentLifecycleWriteViolations(source('db.delete(records).where(inArray(records.lifecycleState, ["ready", "terminated"]))')).length, 1);
});
+25 -2
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env node
import { scanAgentLifecycleBoundaries } from "./check-agent-lifecycle-boundaries.mjs";
import { readdirSync, readFileSync } from "node:fs";
import { dirname, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
@@ -9,6 +10,10 @@ const defaultServerSrc = resolve(repoRoot, "server/src");
const defaultModulesRoot = resolve(defaultServerSrc, "modules");
const layerNames = new Set(["domain", "application", "adapters"]);
const databasePackages = ["@paperclipai/db", "drizzle-orm", "embedded-postgres", "postgres"];
const configurationTransactionCallers = new Set([
"services/secret-proposals.ts", "services/connection-intents.ts", "services/dot-runner-broker.ts",
"services/public-mcp/oauth.ts", "services/agent-profile-avatar.ts", "services/agent-instruction-revisions.ts", "services/company-skills.ts",
]);
function normalizedRelative(from, to) {
return relative(from, to).split(sep).join("/");
@@ -99,6 +104,18 @@ export function scanModuleBoundaries({
const targetSegments = targetServerSegments(serverSrc, target);
const targetLocation = target ? moduleLocation(modulesRoot, target) : null;
if (/^services\/agent-configuration-transaction\.(?:js|ts)$/.test(targetSegments.join("/")) &&
!configurationTransactionCallers.has(normalizedRelative(serverSrc, sourceFile))) {
addViolation(violations, sourceLabel, sourceLocation?.layer ?? null, specifier,
"configuration transaction integration is limited to its explicit workflow callers");
}
if (sourceLocation?.moduleName === "agent-lifecycle" &&
(targetSegments.includes("services") || targetSegments.includes("routes"))) {
addViolation(violations, sourceLabel, sourceLocation.layer, specifier,
"agent lifecycle must receive service integrations through its ports");
}
if (sourceLocation?.layer === "domain") {
if (isDatabasePackage(specifier)) {
addViolation(violations, sourceLabel, "domain", specifier, "domain cannot import database packages");
@@ -135,7 +152,11 @@ export function scanModuleBoundaries({
if (targetLocation && sourceLocation?.moduleName !== targetLocation.moduleName) {
const targetRelative = normalizedRelative(resolve(modulesRoot, targetLocation.moduleName), target);
if (targetRelative !== "index.js" && targetRelative !== "index.ts") {
const configurationIntegration = /^configuration\.(?:js|ts)$/.test(targetRelative) &&
normalizedRelative(serverSrc, sourceFile) === "services/agent-configuration-transaction.ts";
const companyDeletionIntegration = /^company-deletion\.(?:js|ts)$/.test(targetRelative) &&
normalizedRelative(serverSrc, sourceFile) === "services/company-deletion.ts";
if (targetRelative !== "index.js" && targetRelative !== "index.ts" && !companyDeletionIntegration && !configurationIntegration) {
addViolation(
violations,
sourceLabel,
@@ -158,13 +179,15 @@ export function formatViolation(violation) {
function main() {
const violations = scanModuleBoundaries();
const lifecycleViolations = scanAgentLifecycleBoundaries();
if (lifecycleViolations.length) { console.error(lifecycleViolations.join("\n")); process.exitCode = 1; }
if (violations.length > 0) {
console.error("Feature module boundary check failed:");
for (const violation of violations) console.error(`- ${formatViolation(violation)}`);
process.exitCode = 1;
return;
}
console.log("Feature module boundary check passed.");
if (!lifecycleViolations.length) console.log("Feature module boundary check passed.");
}
if (resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) main();
+55
View File
@@ -1,3 +1,4 @@
import "./check-agent-lifecycle-boundaries.test.mjs";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -88,3 +89,57 @@ test("scanModuleBoundaries rejects outward dependencies and module-internal impo
test("the repository's feature modules satisfy their import boundaries", () => {
assert.deepEqual(scanModuleBoundaries(), []);
});
test("only the company deletion coordinator can import module deletion entry points", () => {
const serverSrc = mkdtempSync(join(tmpdir(), "paperclip-company-deletion-boundaries-"));
const modulesRoot = join(serverSrc, "modules");
try {
mkdirSync(join(serverSrc, "services"));
mkdirSync(join(serverSrc, "routes"));
const integration = 'import { deletion } from "../modules/example/company-deletion.js";';
writeFileSync(join(serverSrc, "services", "company-deletion.ts"), integration);
writeFileSync(join(serverSrc, "services", "other.ts"), integration);
writeFileSync(join(serverSrc, "routes", "companies.ts"), integration);
const violations = scanModuleBoundaries({ serverSrc, modulesRoot });
assert.equal(violations.length, 2);
assert(violations.some(({ file }) => file.endsWith("services/other.ts")));
assert(violations.some(({ file }) => file.endsWith("routes/companies.ts")));
} finally {
rmSync(serverSrc, { recursive: true, force: true });
}
});
test("configuration integration is limited to its composition and workflow callers", () => {
const serverSrc = mkdtempSync(join(tmpdir(), "paperclip-configuration-boundaries-"));
const modulesRoot = join(serverSrc, "modules");
try {
mkdirSync(join(serverSrc, "services"));
mkdirSync(join(serverSrc, "routes"));
const integration = 'import { update } from "../modules/agent-lifecycle/configuration.js";';
const workflow = 'import { update } from "./agent-configuration-transaction.js";';
writeFileSync(join(serverSrc, "services", "agent-configuration-transaction.ts"), integration);
writeFileSync(join(serverSrc, "services", "secret-proposals.ts"), workflow);
writeFileSync(join(serverSrc, "services", "other.ts"), workflow);
writeFileSync(join(serverSrc, "routes", "agents.ts"), integration);
const violations = scanModuleBoundaries({ serverSrc, modulesRoot });
assert.equal(violations.length, 2);
assert(violations.some(({ file }) => file.endsWith("services/other.ts")));
assert(violations.some(({ file }) => file.endsWith("routes/agents.ts")));
} finally {
rmSync(serverSrc, { recursive: true, force: true });
}
});
test("agent lifecycle adapters and entry point cannot depend on services", () => {
const serverSrc = mkdtempSync(join(tmpdir(), "paperclip-lifecycle-boundaries-"));
const modulesRoot = join(serverSrc, "modules");
try {
mkdirSync(join(modulesRoot, "agent-lifecycle", "adapters"), { recursive: true });
writeFileSync(join(modulesRoot, "agent-lifecycle", "index.ts"), 'import "../../services/example.js";');
writeFileSync(join(modulesRoot, "agent-lifecycle", "adapters", "records.ts"), 'import "../../../services/example.js";');
assert.equal(scanModuleBoundaries({ serverSrc, modulesRoot }).filter(item =>
item.reason === "agent lifecycle must receive service integrations through its ports").length, 2);
} finally {
rmSync(serverSrc, { recursive: true, force: true });
}
});
@@ -1,5 +1,11 @@
import { createDb } from "./client.js";
import { companies, agents, goals, projects, issues } from "./schema/index.js";
import { createDb } from "@paperclipai/db";
import { createAgentLifecycle } from "../src/services/agent-lifecycle.js";
import {
companies,
goals,
projects,
issues,
} from "@paperclipai/db";
const url = process.env.DATABASE_URL;
if (!url) throw new Error("DATABASE_URL is required");
@@ -18,10 +24,7 @@ const [company] = await db
})
.returning();
const [ceo] = await db
.insert(agents)
.values({
companyId: company!.id,
const ceo = await createAgentLifecycle(db).requestHire(company!.id, {
name: "CEO Agent",
role: "ceo",
title: "Chief Executive Officer",
@@ -29,13 +32,9 @@ const [ceo] = await db
adapterType: "process",
adapterConfig: { command: "echo", args: ["hello from ceo"] },
budgetMonthlyCents: 15000,
})
.returning();
});
const [engineer] = await db
.insert(agents)
.values({
companyId: company!.id,
const engineer = await createAgentLifecycle(db).requestHire(company!.id, {
name: "Engineer Agent",
role: "engineer",
title: "Software Engineer",
@@ -44,8 +43,7 @@ const [engineer] = await db
adapterType: "process",
adapterConfig: { command: "echo", args: ["hello from engineer"] },
budgetMonthlyCents: 10000,
})
.returning();
});
const [goal] = await db
.insert(goals)
+16 -2
View File
@@ -1,4 +1,4 @@
/** Opt-in live qualification: creates an isolated database/workspace and spends two Codex turns.
/** Opt-in live qualification: creates an isolated database/workspace and runs a harness test and two Codex turns.
* PATH=<pnpm-bin>:<codex-bin>:$PATH node --import tsx server/scripts/smoke-native-task-monitor.ts --run
*/
import assert from "node:assert/strict";
@@ -17,6 +17,9 @@ process.env.PAPERCLIP_INSTANCE_ID = "monitor-smoke";
process.env.PAPERCLIP_TELEMETRY_ENABLED = "false";
const { createDb, companies, agents, authUsers, companyMemberships, issues, heartbeatRuns, agentWakeupRequests, nativeRunResults, statusDecisions } = await import("@paperclipai/db");
const { startEmbeddedPostgresTestDatabase } = await import("../src/__tests__/helpers/embedded-postgres.js");
const { createAgentLifecycle, startAgentLifecycle } = await import("../src/services/agent-lifecycle.js");
const { createLifecycleDriver } = await import("../src/services/agent-lifecycle-driver.js");
const { createPluginWorkerManager } = await import("../src/services/plugin-worker-manager.js");
const { heartbeatService } = await import("../src/services/heartbeat.js");
const { setupRunnerPrpWebSocketServer, runnerPrpWebSocketInternals } = await import("../src/realtime/runner-prp-ws.js");
const { closeIdleWarmNativeSessionsForRestart } = await import("../src/services/native-runtime/native-session-executor.js");
@@ -30,6 +33,7 @@ process.env.PAPERCLIP_API_URL = `http://127.0.0.1:${address.port}`;
setupRunnerPrpWebSocketServer(server, { apiUrl: process.env.PAPERCLIP_API_URL });
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
const heartbeat = heartbeatService(db);
const lifecycle = startAgentLifecycle(db, createLifecycleDriver(db, createPluginWorkerManager()), () => true);
const readRuns = () => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)).orderBy(heartbeatRuns.createdAt);
console.log(JSON.stringify({ root, companyId, agentId, issueId }));
try {
@@ -38,9 +42,18 @@ try {
await db.insert(companies).values({ id: companyId, name: "Isolated monitor smoke", issuePrefix: "MON", defaultResponsibleUserId: "monitor-smoke", requireBoardApprovalForNewAgents: false });
await db.insert(authUsers).values({ id: "monitor-smoke", name: "Monitor smoke", email: "monitor-smoke@example.test", createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "monitor-smoke", status: "active", membershipRole: "owner" });
await db.insert(agents).values({ id: agentId, companyId, name: "Monitor verifier", status: "active", adapterType: "paperclip_runner",
await createAgentLifecycle(db).requestHire(companyId, { id: agentId, name: "Monitor verifier", status: "active", adapterType: "paperclip_runner",
adapterConfig: { provider: "codex", cwd, lifecycleMode: "warm", idleTimeoutMs: 300_000, timeoutSeconds: 180 },
runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } } });
const setupDeadline = Date.now() + 3 * 60_000;
while (true) {
const agent = await createAgentLifecycle(db).get(agentId);
assert.ok(agent, "the hired agent must exist");
assert.equal(agent.lifecycleError, null, "agent setup failed");
if (agent.lifecycleState === "ready") break;
assert.ok(Date.now() < setupDeadline, "agent setup timed out");
await delay(250);
}
await db.insert(issues).values({ id: issueId, companyId, title: "Verify a one-shot native task monitor", identifier: "MON-1", status: "in_progress", assigneeAgentId: agentId,
description: "This is an isolated two-run integration test. First run: use set_task_monitor on this task with a fresh nextCheckAt about 45 seconds in the future (compute the current UTC time if needed), notes saying to verify issue_monitor_due, and idempotencyKey monitor-live-first. Confirm the receipt. Then call paperclip_finish with yielded and continuation.kind monitor, accurately retaining the second run as blocking remaining work. End immediately after acceptance. Do not sleep or poll. Second run: if the wake reason is issue_monitor_due, the requested check succeeded. Report that reason and finish done using the current completion contract. Do not schedule another monitor or request human review. No files or other deliverables are required." });
await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", reason: "monitor_smoke",
@@ -90,6 +103,7 @@ try {
await writeFile(join(root, "evidence.json"), JSON.stringify(evidence, null, 2));
console.log(JSON.stringify({ passed: true, evidence: join(root, "evidence.json"), warmReuse: evidence.warmReuse }));
} finally {
await lifecycle.stop();
await writeFile(join(root, "run-records.json"), JSON.stringify(await readRuns(), null, 2));
await closeIdleWarmNativeSessionsForRestart();
runnerPrpWebSocketInternals.resetForTests();
@@ -2,6 +2,7 @@
* Uses real Codex, disposable database/workspaces, and a private copy of login credentials.
* Writes only content-free evidence to stdout; never runs as part of the unit suite.
*/
import { createAgentLifecycle } from "../src/services/agent-lifecycle.js";
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { chmod, copyFile, lstat, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
@@ -63,7 +64,7 @@ try {
let result;
if (mode === "legacy") {
await server.db.update(heartbeatRuns).set({ runtimeMode: "legacy", nativeIssueId: null }).where(eq(heartbeatRuns.id, f.runId));
await server.db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, f.agentId));
await createAgentLifecycle(server.db).updateConfiguration(f.agentId, { adapterType: "codex_local" });
result = await executeLegacy({
runId: f.runId,
agent: { id: f.agentId, companyId: f.companyId, name: "Feedback smoke", adapterType: "codex_local", adapterConfig: {} },
@@ -413,3 +413,9 @@ describe("adapter auth-signal route", () => {
expect(mockResolveEnvironmentExecutionTarget).not.toHaveBeenCalled();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
}) };
});
@@ -1225,3 +1225,10 @@ describe("agent routes adapter validation", () => {
expect(mockAgentService.update).toHaveBeenCalledOnce();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
}) };
});
@@ -212,7 +212,10 @@ describe("internal agent commentary through both transports", () => {
await server.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId, status: "running", invocationSource: "on_demand" });
await submitAgentCommentary(server.db, { companyId: f.companyId, agentId, runId }, { ...input, kind: "complaint" });
expect((await rows({ ...f, runId }))[0].issueId).toBeNull();
if (owner === "agent") await agentService(server.db).remove(agentId);
if (owner === "agent") {
await server.db.update(agents).set({ lifecycleState: "terminated", status: "terminated" }).where(eq(agents.id, agentId));
await agentService(server.db).remove(agentId);
}
else await companyService(server.db).remove(f.companyId);
expect(await rows({ ...f, runId })).toHaveLength(0);
});
@@ -755,3 +755,13 @@ describe("agent cross-tenant route authorization", () => {
expect(mockLogActivity).not.toHaveBeenCalled();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
pauseAgent: (...args: unknown[]) => mockAgentService.pause(...args),
resumeAgent: (...args: unknown[]) => mockAgentService.resume(...args),
terminateAgent: (...args: unknown[]) => mockAgentService.terminate(...args),
}) };
});
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
@@ -50,7 +51,7 @@ describeDatabase("new agent configuration defaults", () => {
issuePrefix: `PD${companyId.slice(0, 6).toUpperCase()}`,
});
const create = (name: string, permissions: Record<string, unknown> = {}, metadata?: Record<string, unknown>) =>
agentService(db).create(companyId, {
createAgentLifecycle(db).requestHire(companyId, {
name,
role: "engineer",
adapterType: "process",
@@ -130,6 +131,7 @@ describeDatabase("new agent configuration defaults", () => {
expect(await db.select().from(principalPermissionGrants)
.where(eq(principalPermissionGrants.principalId, standard.id))).toEqual([]);
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }).where(eq(agents.id, peer.id));
await agentService(db).remove(peer.id);
expect(await db.select().from(principalPermissionGrants)
.where(eq(principalPermissionGrants.principalId, peer.id))).toEqual([]);
@@ -190,7 +192,7 @@ describeDatabase("new agent configuration defaults", () => {
name: "Pending permission default",
issuePrefix: `PP${companyId.slice(0, 6).toUpperCase()}`,
});
const pending = await agentService(db).create(companyId, {
const pending = await createAgentLifecycle(db).requestHire(companyId, {
name: "Pending hire",
status: "pending_approval",
role: "engineer",
@@ -201,7 +203,7 @@ describeDatabase("new agent configuration defaults", () => {
expect(await db.select().from(principalPermissionGrants)
.where(eq(principalPermissionGrants.companyId, companyId))).toEqual([]);
const result = await agentService(db).activatePendingApproval(pending.id);
const result = await createAgentLifecycle(db).approveHire(pending.id);
expect(result?.activated).toBe(true);
expect((await db.select().from(principalPermissionGrants)
.where(eq(principalPermissionGrants.companyId, companyId)))
@@ -220,7 +222,7 @@ describeDatabase("new agent configuration defaults", () => {
name: "Invited permission default",
issuePrefix: `PI${companyId.slice(0, 6).toUpperCase()}`,
});
const invited = await agentService(db).create(companyId, {
const invited = await createAgentLifecycle(db).requestHire(companyId, {
name: "Invited agent",
role: "engineer",
adapterType: "process",
@@ -1709,3 +1709,10 @@ describe("adapter device-login routes", () => {
expect(loggedText).not.toContain("provider-lease-");
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
}) };
});
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import type { AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
import { ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared";
import { assertHarnessTestPassed } from "../services/agent-harness-verification.js";
describe("saved harness verification", () => {
const result = (status: AdapterEnvironmentTestResult["status"], codes: string[]): AdapterEnvironmentTestResult => ({
adapterType: "test", status, testedAt: new Date().toISOString(),
checks: codes.map(code => ({ code, level: "info", message: code })),
});
it.each([
["fail", []], ["warn", ["claude_hello_probe_auth_required"]],
["warn", ["gemini_hello_probe_timed_out"]], ["pass", ["claude_hello_probe_skipped_custom_command"]],
["warn", ["claude_acp_anthropic_api_key_detected", "claude_acp_login_probe_unavailable"]],
["warn", ["cli_version_probe_mismatch"]], ["pass", [ADAPTER_AUTH_MISSING_CHECK_CODE]],
["warn", ["claude_hello_probe_passed", "claude_hello_probe_auth_required"]],
] as const)("rejects %s with %j", (status, codes) => {
expect(() => assertHarnessTestPassed(result(status, [...codes]))).toThrow("The harness test failed");
});
it.each([
["pass", ["process_command_available"]], ["warn", ["claude_hello_probe_passed", "optional_environment_warning"]],
["warn", ["claude_acp_anthropic_api_key_detected", "claude_hello_probe_passed"]],
["pass", ["codex_hello_probe_succeeded"]], ["warn", ["ai_connection_api_key_reverified"]],
] as const)("accepts %s with %j", (status, codes) => {
expect(() => assertHarnessTestPassed(result(status, [...codes]))).not.toThrow();
});
});
@@ -22,6 +22,7 @@ import { aiConnectionRouterService } from "../services/ai-connection-router.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { toolAccessService } from "../services/tool-access.js";
import { waitForPendingRunFailureReports } from "../services/run-failure-report.js";
import { configureAgentLifecycle } from "../services/agent-lifecycle.js";
const captureRunFailure = vi.hoisted(() => vi.fn());
vi.mock("../sentry.js", async (importOriginal) => ({
@@ -374,7 +375,7 @@ describe("agent-created hires use managed AI connections", () => {
const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Other provider", role: "engineer", adapterType }));
expect(agent.runtimeConfig.aiConnection).toMatchObject({ provider: otherProvider, mode: "responsible_user" });
await expect(prepareManagedAiRuntime(db, { companyId: f.companyId, agentId: agent.id, responsibleUserId: f.userId, adapterType, binding: agent.runtimeConfig.aiConnection, config: agent.adapterConfig })).rejects.toMatchObject({ details: { code: "ai_connection_default_missing" } });
expect(agent.status).toBe("idle");
expect(agent).toMatchObject({ status: "paused", lifecycleState: "preparing" });
});
for (const endpoint of ["agent-hires", "agents"]) {
@@ -486,11 +487,17 @@ describe("agent-created hires use managed AI connections", () => {
});
describe("hired agents sharing a subscription", () => {
async function finishSetup(agentId: string) {
// These tests cover task credentials after setup; lifecycle tests cover verification.
const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" });
try { await worker.process(agentId); } finally { await worker.stop(); }
}
it("keeps a credential-lock timeout on automatic retry without blocking the task or starting a provider", async () => {
const f = await fixture("openai", "subscription");
const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Waiting teammate", role: "engineer", adapterType: f.adapterType, runner: "legacy", reportsTo: f.agentId, adapterConfig: { engine: "cli" }, runtimeConfig: { heartbeat: { enabled: false } } }));
// Only an operator may set host execution paths after the agent is hired.
await db.update(agents).set({ adapterConfig: { ...agent.adapterConfig, cwd: home } }).where(eq(agents.id, agent.id));
await finishSetup(agent.id);
const [issue] = await db.insert(issues).values({ companyId: f.companyId, title: "Wait for credential rotation", status: "todo", assigneeAgentId: agent.id, responsibleUserId: f.userId, createdByUserId: f.userId }).returning();
const execute = vi.fn(async () => ({ exitCode: 0, signal: null, timedOut: false, resultJson: {} }));
registerServerAdapter({ ...getServerAdapter(f.adapterType), execute });
@@ -534,6 +541,7 @@ describe("hired agents sharing a subscription", () => {
const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Concurrent teammate", role: "engineer", adapterType: f.adapterType, runner: "legacy", reportsTo: f.agentId, adapterConfig: { engine: "cli" }, runtimeConfig: { heartbeat: { enabled: false } } }));
// Host working directories are configured by an operator, not an agent key.
await db.update(agents).set({ adapterConfig: { ...agent.adapterConfig, cwd: home } }).where(eq(agents.id, agent.id));
await finishSetup(agent.id);
const [issue] = await db.insert(issues).values({ companyId: f.companyId, title: "Subscription child task", status: "todo", assigneeAgentId: agent.id, responsibleUserId: f.userId, createdByUserId: f.userId }).returning();
const parentRuntime = await prepareManagedAiRuntime(db, { companyId: f.companyId, agentId: f.agentId, responsibleUserId: f.userId, adapterType: f.adapterType, binding: f.binding, config: { cwd: home } });
const execute = vi.fn(async () => {
+3 -2
View File
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomBytes, randomUUID, verify, generateKeyPairSync } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -74,7 +75,7 @@ describe("agent cryptographic identity", () => {
});
it("creates identities in the agent creation transaction and rolls both writes back on failure", async () => {
const created = await agentService(db).create(companyId, { name: "New identity", role: "engineer", status: "pending_approval" });
const created = await createAgentLifecycle(db).requestHire(companyId, { name: "New identity", role: "engineer", status: "pending_approval" });
expect(await agentIdentityService(db).getPublicIdentity(companyId, created.id)).toMatchObject({ algorithm: "Ed25519" });
const id = randomUUID();
await expect(db.transaction(async tx => {
@@ -85,7 +86,7 @@ describe("agent cryptographic identity", () => {
expect(await db.select().from(agents).where(eq(agents.id, id))).toHaveLength(0);
expect(await agentIdentityService(db).getPublicIdentity(companyId, id)).toBeNull();
const fail = vi.spyOn(localEncryptedProvider, "createSecret").mockRejectedValueOnce(new Error("encryption unavailable"));
await expect(agentService(db).create(companyId, { name: "Must roll back", role: "engineer", status: "pending_approval" })).rejects.toThrow("encryption unavailable");
await expect(createAgentLifecycle(db).requestHire(companyId, { name: "Must roll back", role: "engineer", status: "pending_approval" })).rejects.toThrow("encryption unavailable");
fail.mockRestore();
expect(await db.select().from(agents).where(eq(agents.name, "Must roll back"))).toHaveLength(0);
});
@@ -844,3 +844,10 @@ describe("agent instructions bundle routes", () => {
expect(res.body.adapterConfig.instructionsFilePath).toBeUndefined();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
}) };
});
@@ -1940,3 +1940,9 @@ describe("agent live run routes", () => {
expect(mockWorkspaceDiffReprojection.persist).not.toHaveBeenCalled();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
}) };
});
@@ -73,8 +73,8 @@ const mockApprovalService = vi.hoisted(() => ({
create: vi.fn(),
getById: vi.fn(),
findOpenHireApprovalForAgent: vi.fn(),
approve: vi.fn(),
reject: vi.fn(),
approveHire: vi.fn(),
rejectHire: vi.fn(),
}));
const mockBudgetService = vi.hoisted(() => ({
@@ -326,8 +326,8 @@ describe("agent permission routes", () => {
mockApprovalService.create.mockReset();
mockApprovalService.getById.mockReset();
mockApprovalService.findOpenHireApprovalForAgent.mockReset();
mockApprovalService.approve.mockReset();
mockApprovalService.reject.mockReset();
mockApprovalService.approveHire.mockReset();
mockApprovalService.rejectHire.mockReset();
mockBudgetService.upsertPolicy.mockReset();
mockHeartbeatService.listTaskSessions.mockReset();
mockHeartbeatService.resetRuntimeSession.mockReset();
@@ -692,6 +692,16 @@ describe("agent permission routes", () => {
]);
});
it.each([{ spentMonthlyCents: 0 }, { name: "Renamed", spentMonthlyCents: 0 }])(
"rejects accounting fields before applying an agent update: %j", async payload => {
const app = await createApp({ type: "board", userId: "board-user", source: "session", isInstanceAdmin: true, companyIds: [companyId] });
const res = await requestApp(app, baseUrl => request(baseUrl).patch(`/api/agents/${agentId}`).send(payload));
expect(res.status).toBe(400);
expect(res.body.details).toEqual(expect.arrayContaining([expect.objectContaining({ path: ["spentMonthlyCents"] })]));
expect(mockAgentService.update).not.toHaveBeenCalled();
},
);
it("blocks agent updates for authenticated company members without agent admin permission", async () => {
mockAccessService.canUser.mockResolvedValue(false);
@@ -1297,7 +1307,7 @@ describe("agent permission routes", () => {
expect.objectContaining({
status: "idle",
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "agent-admin-user", claudeLogin: { storedSessionId: null, ownerUserId: "agent-admin-user", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "agent-admin-user", responsibleUserId: "agent-admin-user", claudeLogin: { storedSessionId: null, ownerUserId: "agent-admin-user", applyExistingWithoutClaim: false } },
);
expect(mockAccessService.setPrincipalPermission).toHaveBeenCalledWith(
companyId,
@@ -1427,7 +1437,7 @@ describe("agent permission routes", () => {
},
},
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1463,7 +1473,7 @@ describe("agent permission routes", () => {
model: DEFAULT_OPENCODE_LOCAL_MODEL,
}),
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1501,7 +1511,7 @@ describe("agent permission routes", () => {
model: "anthropic/claude-sonnet-4-5",
}),
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1543,7 +1553,7 @@ describe("agent permission routes", () => {
{
runnerResolved: true,
aiConnectionInstall: undefined,
createdByUserId: "board-user",
createdByUserId: "board-user", responsibleUserId: "board-user",
claudeLogin: {
storedSessionId: null,
ownerUserId: "board-user",
@@ -1564,9 +1574,10 @@ describe("agent permission routes", () => {
status: "idle",
};
mockAgentService.getById.mockResolvedValue(pendingAgent);
mockAgentService.activatePendingApproval.mockResolvedValue({
mockApprovalService.approveHire.mockResolvedValue({
agent: approvedAgent,
activated: true,
applied: true,
approval: null,
});
const app = await createApp({
@@ -1582,8 +1593,7 @@ describe("agent permission routes", () => {
.send({}));
expect(res.status).toBe(200);
expect(mockAgentService.activatePendingApproval).toHaveBeenCalledWith(agentId);
expect(mockApprovalService.approve).not.toHaveBeenCalled();
expect(mockApprovalService.approveHire).toHaveBeenCalledWith(agentId, "board-user");
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
companyId,
actorType: "user",
@@ -1604,19 +1614,9 @@ describe("agent permission routes", () => {
...baseAgent,
status: "idle",
};
// First getById (getAccessibleAgent) sees the pending agent; the second
// (after the approval resolves) sees the activated agent.
mockAgentService.getById
.mockResolvedValueOnce(pendingAgent)
.mockResolvedValue(approvedAgent);
mockApprovalService.findOpenHireApprovalForAgent.mockResolvedValue({
id: "approval-1",
companyId,
type: "hire_agent",
status: "pending",
payload: { agentId },
});
mockApprovalService.approve.mockResolvedValue({
mockAgentService.getById.mockResolvedValue(pendingAgent);
mockApprovalService.approveHire.mockResolvedValue({
agent: approvedAgent,
approval: { id: "approval-1", status: "approved" },
applied: true,
});
@@ -1635,7 +1635,7 @@ describe("agent permission routes", () => {
expect(res.status).toBe(200);
// The shared approval flow handles activation; we must not double-activate.
expect(mockApprovalService.approve).toHaveBeenCalledWith("approval-1", "board-user");
expect(mockApprovalService.approveHire).toHaveBeenCalledWith(agentId, "board-user");
expect(mockAgentService.activatePendingApproval).not.toHaveBeenCalled();
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "agent.approved",
@@ -1652,19 +1652,9 @@ describe("agent permission routes", () => {
...baseAgent,
status: "terminated",
};
// getAccessibleAgent sees the pending agent; after the rejection resolves
// (which terminates internally) the route re-reads the terminated agent.
mockAgentService.getById
.mockResolvedValueOnce(pendingAgent)
.mockResolvedValue(terminatedAgent);
mockApprovalService.findOpenHireApprovalForAgent.mockResolvedValue({
id: "approval-1",
companyId,
type: "hire_agent",
status: "pending",
payload: { agentId },
});
mockApprovalService.reject.mockResolvedValue({
mockAgentService.getById.mockResolvedValue(pendingAgent);
mockApprovalService.rejectHire.mockResolvedValue({
agent: terminatedAgent,
approval: { id: "approval-1", status: "rejected" },
applied: true,
});
@@ -1687,8 +1677,8 @@ describe("agent permission routes", () => {
.send({}));
expect(res.status).toBe(200);
expect(mockApprovalService.reject).toHaveBeenCalledWith("approval-1", "board-user");
// reject() terminates the agent internally; the route must not terminate again.
expect(mockApprovalService.rejectHire).toHaveBeenCalledWith(agentId, "board-user");
// The hire decision rejects the pending agent; the route must not terminate again.
expect(mockAgentService.terminate).not.toHaveBeenCalled();
});
@@ -1718,7 +1708,7 @@ describe("agent permission routes", () => {
expect(res.status).toBe(200);
expect(mockAgentService.terminate).toHaveBeenCalledWith(agentId);
expect(mockApprovalService.findOpenHireApprovalForAgent).not.toHaveBeenCalled();
expect(mockApprovalService.reject).not.toHaveBeenCalled();
expect(mockApprovalService.rejectHire).not.toHaveBeenCalled();
});
it("rejects direct approval for agents that are not pending approval", async () => {
@@ -1735,7 +1725,7 @@ describe("agent permission routes", () => {
.send({}));
expect(res.status).toBe(409);
expect(mockAgentService.activatePendingApproval).not.toHaveBeenCalled();
expect(mockApprovalService.approveHire).not.toHaveBeenCalled();
expect(mockLogActivity).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "agent.approved",
}));
@@ -1774,7 +1764,7 @@ describe("agent permission routes", () => {
expect.objectContaining({
defaultEnvironmentId: environmentId,
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1861,7 +1851,7 @@ describe("agent permission routes", () => {
adapterType: expectedAdapterType,
defaultEnvironmentId: environmentId,
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "board-user", responsibleUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
if (adapterCase.adapterType === "codex_local") {
expect(mockAgentService.create.mock.calls[0][1].adapterConfig).toMatchObject({ provider: "codex" });
@@ -2346,3 +2336,12 @@ describe("agent permission routes", () => {
expect(mockHeartbeatService.cancelRun).not.toHaveBeenCalled();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
approveHire: (...args: unknown[]) => mockAgentService.activatePendingApproval(...args),
terminateAgent: (...args: unknown[]) => mockAgentService.terminate(...args),
}) };
});
@@ -8,7 +8,7 @@ import {
defaultAgentPermissions,
normalizeAgentPermissions,
permissionsImplyLowTrust,
} from "../services/agent-permissions.js";
} from "../lib/agent-permissions.js";
describe("agent permissions service", () => {
it("grants agent-creation authority to new agents by default", () => {
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
@@ -20,15 +21,17 @@ describe("persisted agent personas", () => {
afterAll(async () => { await database?.cleanup(); });
it("randomizes once, accepts a saved draft and preserves identity across edits and revision rollback", async () => {
const service = agentService(db);
const random = await service.create(companyId, { name: "Random", role: "engineer", adapterType: "process" });
const serviceLifecycle = createAgentLifecycle(db);
const random = await serviceLifecycle.requestHire(companyId, { name: "Random", role: "engineer", adapterType: "process" });
expect(agentAppearanceSchema.safeParse(random.appearance).success).toBe(true);
const appearance = appearanceForPalette("arctic-blue");
const original = await service.create(companyId, { name: "Draft", role: "engineer", adapterType: "process", appearance });
const original = await serviceLifecycle.requestHire(companyId, { name: "Draft", role: "engineer", adapterType: "process", appearance });
expect(original.appearance).toEqual(appearance);
const updated = await service.update(original.id, { name: "Renamed" }, { recordRevision: { source: "test" } });
expect(updated?.appearance).toEqual(appearance);
const [revision] = await service.listConfigRevisions(original.id);
await service.update(original.id, { name: "Changed again", status: "paused" });
await service.update(original.id, { name: "Changed again" });
await serviceLifecycle.pauseAgent(original.id);
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored?.appearance).toEqual(appearance);
expect((await agentService(db).getById(original.id))?.avatarUrl).toContain("/arctic-blue/rest.png?size=512");
@@ -1020,7 +1020,7 @@ describe("agent skill routes", () => {
}),
}),
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "local-board", responsibleUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
);
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
expect.anything(),
@@ -1070,7 +1070,7 @@ describe("agent skill routes", () => {
expect.objectContaining({
role: "security",
}),
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
{ runnerResolved: true, aiConnectionInstall: undefined, createdByUserId: "local-board", responsibleUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
);
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
expect.anything(),
@@ -1532,7 +1532,7 @@ describe("agent skill routes", () => {
{
runnerResolved: true,
aiConnectionInstall: undefined,
createdByUserId: "local-board",
createdByUserId: "local-board", responsibleUserId: "local-board",
claudeLogin: {
storedSessionId: null,
ownerUserId: "local-board",
@@ -1616,3 +1616,10 @@ describe("agent skill routes", () => {
expect(mockAgentInstructionsService.materializeManagedBundle).not.toHaveBeenCalled();
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => mockAgentService.create(...args),
}) };
});
@@ -116,10 +116,7 @@ vi.mock("../services/ai-connection-runtime.js", async (importOriginal) => ({
},
}));
const mockValidateAiApiKey = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("../routes/ai-connections.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../routes/ai-connections.js")>()),
validateAiApiKey: mockValidateAiApiKey,
}));
vi.mock("../services/ai-api-key-test.js", () => ({ validateAiApiKey: mockValidateAiApiKey }));
const mockMarkAuthenticationFailed = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("../services/ai-connections.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../services/ai-connections.js")>()),
@@ -1030,3 +1027,9 @@ describe("agent test-environment route", () => {
});
});
});
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
}) };
});
@@ -416,3 +416,9 @@ describeEmbeddedPostgres("agents adapter-config user-secret resolution routes",
function beforeEachActor(actor: TestActor) {
currentActor = actor;
}
vi.mock("../services/agent-lifecycle.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/agent-lifecycle.js")>();
return { ...actual, createAgentLifecycle: () => ({
}) };
});
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import os from "node:os";
@@ -362,7 +363,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
});
@@ -376,7 +377,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// A replay of the same claim inserts no second agent.
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -386,7 +387,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("rejects a missing claim and inserts no binding", async () => {
const scope = await seedScope();
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: undefined, ownerUserId: scope.ownerUserId },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -397,7 +398,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: "intruder" },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -409,7 +410,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() - 1_000);
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -420,7 +421,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000, "awaiting_code");
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -432,8 +433,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// Missing claim.
const missingScope = await seedScope();
messages.push(
await agentService(db)
.create(missingScope.companyId, createInput(missingScope), {
await createAgentLifecycle(db).requestHire(missingScope.companyId, createInput(missingScope), {
claudeLogin: { storedSessionId: undefined, ownerUserId: missingScope.ownerUserId },
})
.then(() => "no-error")
@@ -443,8 +443,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const foreignScope = await seedScope();
const foreignSession = await seedStoredClaim(foreignScope, Date.now() + 60_000);
messages.push(
await agentService(db)
.create(foreignScope.companyId, createInput(foreignScope), {
await createAgentLifecycle(db).requestHire(foreignScope.companyId, createInput(foreignScope), {
claudeLogin: { storedSessionId: foreignSession, ownerUserId: "intruder" },
})
.then(() => "no-error")
@@ -454,8 +453,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const expiredScope = await seedScope();
const expiredSession = await seedStoredClaim(expiredScope, Date.now() - 1_000);
messages.push(
await agentService(db)
.create(expiredScope.companyId, createInput(expiredScope), {
await createAgentLifecycle(db).requestHire(expiredScope.companyId, createInput(expiredScope), {
claudeLogin: { storedSessionId: expiredSession, ownerUserId: expiredScope.ownerUserId },
})
.then(() => "no-error")
@@ -465,8 +463,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const nonStoredScope = await seedScope();
const nonStoredSession = await seedStoredClaim(nonStoredScope, Date.now() + 60_000, "submitting");
messages.push(
await agentService(db)
.create(nonStoredScope.companyId, createInput(nonStoredScope), {
await createAgentLifecycle(db).requestHire(nonStoredScope.companyId, createInput(nonStoredScope), {
claudeLogin: { storedSessionId: nonStoredSession, ownerUserId: nonStoredScope.ownerUserId },
})
.then(() => "no-error")
@@ -475,12 +472,11 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// Already consumed.
const consumedScope = await seedScope();
const consumedSession = await seedStoredClaim(consumedScope, Date.now() + 60_000);
await agentService(db).create(consumedScope.companyId, createInput(consumedScope), {
await createAgentLifecycle(db).requestHire(consumedScope.companyId, createInput(consumedScope), {
claudeLogin: { storedSessionId: consumedSession, ownerUserId: consumedScope.ownerUserId },
});
messages.push(
await agentService(db)
.create(consumedScope.companyId, createInput(consumedScope), {
await createAgentLifecycle(db).requestHire(consumedScope.companyId, createInput(consumedScope), {
claudeLogin: { storedSessionId: consumedSession, ownerUserId: consumedScope.ownerUserId },
})
.then(() => "no-error")
@@ -495,10 +491,10 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
const results = await Promise.allSettled([
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
}),
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
}),
]);
@@ -536,8 +532,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
});
await locked;
const createPromise = agentService(db)
.create(scope.companyId, createInput(scope), {
const createPromise = createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
})
.then(() => "created")
@@ -555,7 +550,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("removes the fixed binding on a normal update", async () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
});
@@ -568,7 +563,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("re-points the binding to a plain value on a normal update", async () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
});
@@ -583,7 +578,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("removes the binding by a move to another adapter type on a normal update", async () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
});
@@ -603,7 +598,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("keeps an existing binding when the update changes another field", async () => {
const scope = await seedScope();
const sessionId = await seedStoredClaim(scope, Date.now() + 60_000);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { storedSessionId: sessionId, ownerUserId: scope.ownerUserId },
});
@@ -616,7 +611,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("rejects a newly introduced binding on update, because it carries no claim", async () => {
const scope = await seedScope();
const created = await agentService(db).create(scope.companyId, {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, {
name: "Api Key Agent",
role: "engineer",
status: "idle",
@@ -645,7 +640,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
await seedStoredOwnerValue(scope);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { ownerUserId: scope.ownerUserId, applyExistingWithoutClaim: true },
});
@@ -666,9 +661,9 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
await seedStoredOwnerValue(scope);
const created = await agentService(
const created = await createAgentLifecycle(
db,
).create(scope.companyId, { ...createInput(scope), status: "pending_approval" }, {
).requestHire(scope.companyId, { ...createInput(scope), status: "pending_approval" }, {
claudeLogin: { ownerUserId: scope.ownerUserId, applyExistingWithoutClaim: true },
});
@@ -680,7 +675,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("binds the fixed reference on an update from a stored owner value with no claim", async () => {
const scope = await seedScope();
await seedStoredOwnerValue(scope);
const created = await agentService(db).create(scope.companyId, {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, {
name: "Claude Agent",
role: "engineer",
status: "idle",
@@ -706,7 +701,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { ownerUserId: scope.ownerUserId, applyExistingWithoutClaim: true },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -723,7 +718,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// The route sets no owner for an agent actor. The gate rejects the no-claim
// bind, so an agent actor never binds the fixed reference.
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { ownerUserId: null, applyExistingWithoutClaim: true },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -739,7 +734,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
foreignScope.ownerUserId = ownerScope.ownerUserId;
await expect(
agentService(db).create(foreignScope.companyId, createInput(foreignScope), {
createAgentLifecycle(db).requestHire(foreignScope.companyId, createInput(foreignScope), {
claudeLogin: { ownerUserId: foreignScope.ownerUserId, applyExistingWithoutClaim: true },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -753,7 +748,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// The apply-existing flag is set, but the config carries no fixed binding. The
// gate mints the fixed reference only when the client presents the exact fixed
// binding, so the flag alone binds nothing and creates no fixed definition.
const created = await agentService(db).create(
const created = await createAgentLifecycle(db).requestHire(
scope.companyId,
{
name: "Plain Agent",
@@ -781,7 +776,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// A client adds a secret id and a foreign owner to the binding. The persist
// normalization keeps only the fixed reference fields, so the extra selectors
// never reach the stored binding. The runtime derives the owner from context.
const created = await agentService(db).create(
const created = await createAgentLifecycle(db).requestHire(
scope.companyId,
createInput(scope, {
CLAUDE_CODE_OAUTH_TOKEN: {
@@ -804,7 +799,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
it("resolves the bound reference to the stored value without leaking it in a log", async () => {
const scope = await seedScope();
await seedStoredOwnerValue(scope, "sk-secret-resolve");
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { ownerUserId: scope.ownerUserId, applyExistingWithoutClaim: true },
});
@@ -858,7 +853,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
const parent = await seedParentAgent(scope);
const created = await agentService(db).create(scope.companyId, createInput(scope), {
const created = await createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { inheritedFromAgentId: parent.id },
});
@@ -871,7 +866,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
const parent = await seedParentAgent(scope, { version: 5 });
const created = await agentService(db).create(
const created = await createAgentLifecycle(db).requestHire(
scope.companyId,
createInput(scope, { CLAUDE_CODE_OAUTH_TOKEN: { ...FIXED_BINDING, version: 5 } }),
{ claudeLogin: { inheritedFromAgentId: parent.id } },
@@ -890,7 +885,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const parent = await seedParentAgent(scope, { version: 5 });
await expect(
agentService(db).create(
createAgentLifecycle(db).requestHire(
scope.companyId,
createInput(scope, { CLAUDE_CODE_OAUTH_TOKEN: { ...FIXED_BINDING, version: 2 } }),
{ claudeLogin: { inheritedFromAgentId: parent.id } },
@@ -906,7 +901,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const parent = await seedParentAgent(scope, { holdsFixedBinding: false });
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { inheritedFromAgentId: parent.id },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -921,7 +916,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const parent = await seedParentAgent(foreignScope);
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { inheritedFromAgentId: parent.id },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -934,7 +929,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const scope = await seedScope();
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { inheritedFromAgentId: randomUUID() },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -950,7 +945,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
const parent = await seedParentAgent(scope, { adapterType: "codex_local" });
await expect(
agentService(db).create(scope.companyId, createInput(scope), {
createAgentLifecycle(db).requestHire(scope.companyId, createInput(scope), {
claudeLogin: { inheritedFromAgentId: parent.id },
}),
).rejects.toMatchObject({ message: CLAUDE_OAUTH_CLAIM_REJECTED });
@@ -988,8 +983,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => {
// The child's copied reference still names version 5, the version the
// route read before the rotation started. The create call must wait for
// the parent row lock, so it can only proceed once the rotation commits.
const createPromise = agentService(db)
.create(
const createPromise = createAgentLifecycle(db).requestHire(
scope.companyId,
createInput(scope, { CLAUDE_CODE_OAUTH_TOKEN: { ...FIXED_BINDING, version: 5 } }),
{ claudeLogin: { inheritedFromAgentId: parent.id } },
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
@@ -66,9 +67,10 @@ describeEmbeddedPostgres("pending approval agent config integrity", () => {
it("resolves internal Codex creation once and preserves legacy agents through ordinary edits", async () => {
const companyId = await seedCompany();
const service = agentService(db);
const native = await service.create(companyId, { name: "New Codex", adapterType: "codex_local", adapterConfig: { modelReasoningEffort: "high" }, status: "pending_approval" });
const legacy = await service.create(companyId, { name: "Legacy Codex", adapterType: "codex_local", runner: "legacy", adapterConfig: { extraArgs: ["--search"] }, status: "pending_approval" });
const reviewedLegacy = await service.create(companyId, { name: "Historical approved hire", adapterType: "codex_local", adapterConfig: {}, status: "pending_approval" }, { runnerResolved: true });
const lifecycle = createAgentLifecycle(db);
const native = await lifecycle.requestHire(companyId, { name: "New Codex", adapterType: "codex_local", adapterConfig: { modelReasoningEffort: "high" }, status: "pending_approval" });
const legacy = await lifecycle.requestHire(companyId, { name: "Legacy Codex", adapterType: "codex_local", runner: "legacy", adapterConfig: { extraArgs: ["--search"] }, status: "pending_approval" });
const reviewedLegacy = await lifecycle.requestHire(companyId, { name: "Historical approved hire", adapterType: "codex_local", adapterConfig: {}, status: "pending_approval" }, { runnerResolved: true });
// Only public Linux x64 artifacts qualify an automatic native default;
// source-built macOS/Windows agents keep legacy until their packaging is qualified.
if (process.platform === "linux" && process.arch === "x64") {
@@ -79,8 +81,9 @@ describeEmbeddedPostgres("pending approval agent config integrity", () => {
expect(legacy.adapterType).toBe("codex_local");
expect(reviewedLegacy.adapterType).toBe("codex_local");
for (const agent of [native, legacy, reviewedLegacy]) {
expect(agent).not.toHaveProperty("runner");
// Ordinary title changes on an activated agent must not revisit creation defaults.
await service.activatePendingApproval(agent.id);
await lifecycle.approveHire(agent.id);
await service.update(agent.id, { title: "Updated title" });
const saved = await service.getById(agent.id);
expect(saved?.adapterType).toBe(agent.adapterType);
@@ -91,8 +94,9 @@ describeEmbeddedPostgres("pending approval agent config integrity", () => {
it("freezes generic pending hire config and reapplies the approval snapshot on activation", async () => {
const companyId = await seedCompany();
const agentSvc = agentService(db);
const agentSvcLifecycle = createAgentLifecycle(db);
const approvalSvc = approvalService(db);
const pending = await agentSvc.create(companyId, {
const pending = await agentSvcLifecycle.requestHire(companyId, {
name: "Pending Coder",
role: "engineer",
title: "Software Engineer",
@@ -170,7 +174,8 @@ describeEmbeddedPostgres("pending approval agent config integrity", () => {
await approvalSvc.approve(approval.id, "board-user", "Approved generic hire");
await expect(agentSvc.getById(pending.id)).resolves.toMatchObject({
status: "idle",
status: "paused",
lifecycleState: "preparing",
appearance: pending.appearance,
name: "Pending Coder",
role: "engineer",
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import os from "node:os";
@@ -86,7 +87,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
value: "sk-ant-123",
});
const created = await agentService(db).create(companyId, {
const created = await createAgentLifecycle(db).requestHire(companyId, {
name: "Claude Novita",
role: "engineer",
status: "pending_approval",
@@ -137,7 +138,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
value: "slack-test-token",
});
const created = await agentService(db).create(companyId, {
const created = await createAgentLifecycle(db).requestHire(companyId, {
name: "Slack Briefing",
role: "briefing",
adapterType: "codex_local",
@@ -185,7 +186,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
});
await expect(
agentService(db).create(companyId, {
createAgentLifecycle(db).requestHire(companyId, {
name: "Unlisted Static Lease",
role: "engineer",
adapterType: "codex_local",
@@ -220,7 +221,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
const companyId = await seedCompany();
const literalApiKey = `hermes-key-${randomUUID()}`;
const created = await agentService(db).create(companyId, {
const created = await createAgentLifecycle(db).requestHire(companyId, {
name: "Hermes Gateway",
role: "engineer",
status: "idle",
@@ -289,7 +290,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
value: "next-value",
});
const created = await agentService(db).create(companyId, {
const created = await createAgentLifecycle(db).requestHire(companyId, {
name: "Binding Swapper",
role: "engineer",
adapterType: "codex_local",
@@ -359,13 +360,14 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
.where(eq(companySecretBindings.targetId, agentId));
expect(beforeBindings).toHaveLength(0);
const approved = await agentService(db).activatePendingApproval(agentId);
const approved = await createAgentLifecycle(db).approveHire(agentId);
expect(approved).toMatchObject({
activated: true,
agent: {
id: agentId,
status: "idle",
status: "paused",
lifecycleState: "preparing",
},
});
@@ -390,7 +392,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
const missingSecretId = randomUUID();
await expect(
agentService(db).create(companyId, {
createAgentLifecycle(db).requestHire(companyId, {
name: "Broken Create",
role: "engineer",
adapterType: "claude_local",
@@ -420,7 +422,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
provider: "local_encrypted",
value: "valid-value",
});
const created = await agentService(db).create(companyId, {
const created = await createAgentLifecycle(db).requestHire(companyId, {
name: "Transactional Update",
role: "engineer",
adapterType: "codex_local",
@@ -483,7 +485,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => {
permissions: {},
});
await expect(agentService(db).activatePendingApproval(agentId)).rejects.toBeTruthy();
await expect(createAgentLifecycle(db).approveHire(agentId)).rejects.toBeTruthy();
const reloaded = await agentService(db).getById(agentId);
expect(reloaded?.status).toBe("pending_approval");
@@ -2,21 +2,23 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { approvalService } from "../services/approvals.ts";
import { companies } from "@paperclipai/db";
vi.mock("../services/budgets.js", () => ({
vi.mock("../services/budgets.js", async importOriginal => ({
...await importOriginal<typeof import("../services/budgets.js")>(),
budgetService: () => ({ deliverPendingEnforcement: vi.fn(async () => {}) }),
budgetServiceInTransaction: () => ({ upsertPolicy: vi.fn(async () => {}) }),
}));
const mockAgentService = vi.hoisted(() => ({
activatePendingApproval: vi.fn(),
getById: vi.fn(async () => ({ id: "agent-1" })),
create: vi.fn(),
terminate: vi.fn(),
}));
const mockNotifyHireApproved = vi.hoisted(() => vi.fn());
vi.mock("../services/agents.js", () => ({
agentService: vi.fn(() => mockAgentService),
vi.mock("../modules/agent-lifecycle/adapters/records.js", () => ({
agentRecords: vi.fn(() => ({ ...mockAgentService, rejectPendingHire: mockAgentService.terminate })),
}));
vi.mock("../services/hire-hook.js", () => ({
@@ -114,7 +116,7 @@ describe("approvalService resolution idempotency", () => {
const result = await svc.approve("approval-1", "board", "ship it");
expect(result.applied).toBe(true);
expect(mockAgentService.activatePendingApproval).toHaveBeenCalledWith("agent-1", approved.payload);
expect(mockAgentService.activatePendingApproval).toHaveBeenCalledWith("agent-1", approved.payload, approved.requestedByUserId);
expect(mockNotifyHireApproved).toHaveBeenCalledTimes(1);
});
@@ -163,7 +165,7 @@ describe("approvalService resolution idempotency", () => {
adapterType: "codex_local",
adapterConfig: approved.payload.adapterConfig,
}),
{ runnerResolved: true, createdByUserId: expectedCreator },
{ runnerResolved: true, createdByUserId: expectedCreator, responsibleUserId: requestedByUserId },
);
});
});
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
@@ -795,8 +796,8 @@ describeEmbeddedPostgres("attention service", () => {
},
]);
await agentService(db).pause(pausedReviewerId);
await agentService(db).terminate(terminatedReviewerId);
await createAgentLifecycle(db).pauseAgent(pausedReviewerId);
await createAgentLifecycle(db).terminateAgent(terminatedReviewerId);
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
const interactionTitles = feed.items
@@ -886,7 +887,7 @@ describeEmbeddedPostgres("attention service", () => {
effectiveResolverPolicy: "human_only",
payload: { version: 1, questions: [] },
});
await agentService(db).pause(reviewerId);
await createAgentLifecycle(db).pauseAgent(reviewerId);
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
const otherUserFeed = await attentionService(db).list(companyId, { userId: "other-user" });
+67 -16
View File
@@ -1,3 +1,4 @@
import { createAgentLifecycle, configureAgentLifecycle } from "../services/agent-lifecycle.js";
import fs from "node:fs/promises";
import { fileHash } from "../services/agent-file-store.js";
import { stockHash } from "../services/managed-resource-drift.js";
@@ -9,6 +10,9 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
import { and, eq, sql } from "drizzle-orm";
import {
activityLog,
heartbeatRuns,
agentWakeupRequests,
routineRuns,
agentConfigRevisions,
agents,
approvals,
@@ -35,14 +39,14 @@ import { agentInstructionsService } from "../services/agent-instructions.ts";
import { agentService } from "../services/agents.ts";
import { approvalService } from "../services/approvals.ts";
import {
builtInAgentService,
builtInAgentService as createBuiltInAgentService,
deriveBuiltInAgentStatus,
listBuiltInAgentDefinitions,
readBuiltInTextWithFallback,
reconcileBuiltInAgentsOnStartup,
validateBuiltInAgentDefinitions,
} from "../services/built-in-agents.ts";
import { readBuiltInAgentMarker, withBuiltInAgentMarker } from "../services/built-in-agent-metadata.ts";
import { readBuiltInAgentMarker, withBuiltInAgentMarker } from "../lib/built-in-agent-metadata.ts";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
@@ -119,6 +123,22 @@ describe("built-in agent asset loading", () => {
describeEmbeddedPostgres("built-in agents", () => {
let db!: ReturnType<typeof createDb>;
let lifecycleWorker: ReturnType<typeof configureAgentLifecycle>;
function builtInAgentService(database: typeof db) {
const service = createBuiltInAgentService(database);
return { ...service,
async ensure(...args: Parameters<typeof service.ensure>) {
const result = await service.ensure(...args);
if (result.agentId) await lifecycleWorker.process(result.agentId);
return service.get(args[0], args[1]);
},
async get(...args: Parameters<typeof service.get>) {
const result = await service.get(...args);
if (result.agentId) await lifecycleWorker.process(result.agentId);
return service.get(...args);
},
};
}
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let runnerSelectionSpy: { mockRestore(): void } | undefined;
const runnerTarget = { driver: "local", platform: "linux", architecture: "x64" };
@@ -136,6 +156,7 @@ describeEmbeddedPostgres("built-in agents", () => {
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-built-in-agents-");
db = createDb(tempDb.connectionString);
lifecycleWorker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" });
}, 20_000);
beforeEach(async () => {
@@ -149,6 +170,7 @@ describeEmbeddedPostgres("built-in agents", () => {
afterEach(async () => {
runnerSelectionSpy?.mockRestore();
await lifecycleWorker.sweep();
await db.delete(routineTriggers);
await db.delete(routines);
await db.delete(issueThreadInteractions);
@@ -170,6 +192,7 @@ describeEmbeddedPostgres("built-in agents", () => {
});
afterAll(async () => {
await lifecycleWorker.stop();
await tempDb?.cleanup();
});
@@ -551,7 +574,7 @@ describeEmbeddedPostgres("built-in agents", () => {
});
expect(ready.status).toBe("ready");
await agentService(db).pause(ready.agentId!, "manual");
await createAgentLifecycle(db).pauseAgent(ready.agentId!, "manual");
await expect(builtIns.get(companyId, "learning")).resolves.toMatchObject({
status: "paused",
agentId: ready.agentId,
@@ -593,7 +616,7 @@ describeEmbeddedPostgres("built-in agents", () => {
warning: null,
});
await agentService(db).pause(ready.agentId!, "maintenance");
await createAgentLifecycle(db).pauseAgent(ready.agentId!, "maintenance");
await expect(builtIns.requireBuiltInAgent(companyId, "briefs")).resolves.toMatchObject({
agent: { id: ready.agentId },
warning: {
@@ -638,7 +661,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("reconciles an enabled Reflection Coach bundle with skill sync and a disabled routine", async () => {
const companyId = await seedCompany({ requireApproval: false });
const root = await agentService(db).create(companyId, {
const root = await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -730,7 +753,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("recreates missing managed resource bindings idempotently during concurrent reconcile", async () => {
const companyId = await seedCompany({ requireApproval: false });
await agentService(db).create(companyId, {
await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -768,7 +791,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("preserves new-agent approval gates during on-demand Reflection Coach provisioning", async () => {
const companyId = await seedCompany({ requireApproval: true });
const root = await agentService(db).create(companyId, {
const root = await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -1012,7 +1035,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("prevents direct marker add, remove, or mutation", async () => {
const companyId = await seedCompany();
const builtIn = await builtInAgentService(db).ensure(companyId, "briefs");
const normal = await agentService(db).create(companyId, {
const normal = await createAgentLifecycle(db).requestHire(companyId, {
name: "Normal",
role: "engineer",
status: "idle",
@@ -1022,7 +1045,7 @@ describeEmbeddedPostgres("built-in agents", () => {
permissions: {},
});
await expect(agentService(db).create(companyId, {
await expect(createAgentLifecycle(db).requestHire(companyId, {
name: "Spoof",
role: "engineer",
status: "idle",
@@ -1275,7 +1298,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("automatically materializes the Reflection Coach bundle without enabling background work", async () => {
const companyId = await seedCompany();
const root = await agentService(db).create(companyId, {
const root = await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -1350,7 +1373,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("materializes the Summarizer bundle paused on Claude Haiku with a disabled routine", async () => {
const companyId = await seedCompany();
const root = await agentService(db).create(companyId, {
const root = await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -1462,9 +1485,35 @@ describeEmbeddedPostgres("built-in agents", () => {
expect(resetFile.content).not.toContain("Operator edit.");
});
it("keeps a built-in routine task while the agent prepares", async () => {
const companyId = await seedCompany({ requireApproval: false });
const builtIns = createBuiltInAgentService(db);
const created = await builtIns.ensure(companyId, "reflection-coach");
await lifecycleWorker.stop();
lifecycleWorker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "pending" });
try {
const result = await builtIns.runRoutine(companyId, "reflection-coach", "recent-agent-reflection", { userId: "responsible-user" });
expect(result.status).toBe("issue_created");
const tasks = await db.select().from(issues).where(eq(issues.companyId, companyId));
expect(tasks).toHaveLength(1);
expect(tasks[0]!.assigneeAgentId).toBe(created.agentId);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)))
.toEqual([expect.objectContaining({ status: "queued", agentId: created.agentId })]);
// A second request during setup must not try to resume an already preparing agent.
await expect(builtIns.runRoutine(companyId, "reflection-coach", "recent-agent-reflection", { userId: "responsible-user" }))
.resolves.toHaveProperty("id");
} finally {
await lifecycleWorker.stop();
await db.delete(routineRuns).where(eq(routineRuns.companyId, companyId));
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
lifecycleWorker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" });
}
});
it("controls the Reflection Coach routine schedule without enabling it by default", async () => {
const companyId = await seedCompany();
await agentService(db).create(companyId, {
await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -1487,7 +1536,8 @@ describeEmbeddedPostgres("built-in agents", () => {
"recent-agent-reflection",
{ userId: "board-user" },
);
expect(enabled.status).toBe("needs_setup");
await lifecycleWorker.process(enabled.agentId!);
expect((await builtIns.get(companyId, "reflection-coach")).status).toBe("needs_setup");
expect(enabled.resources.find((resource) => resource.resourceKind === "routine")).toMatchObject({
stockStatus: "stock_current",
scheduleEnabled: true,
@@ -1515,7 +1565,7 @@ describeEmbeddedPostgres("built-in agents", () => {
it("surfaces pending Reflection Coach proposal interactions on the routine resource", async () => {
const companyId = await seedCompany();
await agentService(db).create(companyId, {
await createAgentLifecycle(db).requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -1568,7 +1618,8 @@ describeEmbeddedPostgres("built-in agents", () => {
it("gates Reflection Coach proposal mutations until an accepted follow-up apply step", async () => {
const companyId = await seedCompany();
const agentsSvc = agentService(db);
await agentsSvc.create(companyId, {
const agentsSvcLifecycle = createAgentLifecycle(db);
await agentsSvcLifecycle.requestHire(companyId, {
name: "CEO",
role: "ceo",
status: "idle",
@@ -1577,7 +1628,7 @@ describeEmbeddedPostgres("built-in agents", () => {
runtimeConfig: {},
permissions: {},
});
const target = await agentsSvc.create(companyId, {
const target = await agentsSvcLifecycle.requestHire(companyId, {
name: "Target Coder",
role: "engineer",
status: "idle",
@@ -1,3 +1,4 @@
import { createAgentLifecycle, configureAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
@@ -41,6 +42,7 @@ describeEmbeddedPostgres("cleanup removal services", () => {
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-cleanup-removal-");
db = createDb(tempDb.connectionString);
configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" });
}, 20_000);
afterEach(async () => {
@@ -146,6 +148,7 @@ describeEmbeddedPostgres("cleanup removal services", () => {
createdByRunId: runId,
});
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }).where(eq(agents.id, agentId));
const removed = await agentService(db).remove(agentId);
expect(removed?.id).toBe(agentId);
+24 -10
View File
@@ -33,9 +33,10 @@ vi.mock("../services/cloud-lifecycle-sync.js", () => ({
notifyCloudOfPrimaryCompanyLifecycleChange: notifyCloudSpy,
}));
import { configureAgentLifecycle } from "../services/agent-lifecycle.js";
import { companyService } from "../services/companies.js";
import { deriveIssuePrefixBase } from "../services/issue-prefix.js";
import { readBuiltInAgentMarker } from "../services/built-in-agent-metadata.js";
import { readBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js";
import { builtInAgentService, reconcileBuiltInAgentsOnStartup } from "../services/built-in-agents.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
@@ -49,6 +50,16 @@ if (!embeddedPostgresSupport.supported) {
describeEmbeddedPostgres("companyService", () => {
let db!: ReturnType<typeof createDb>;
let lifecycleWorker: ReturnType<typeof configureAgentLifecycle>;
beforeEach(() => { lifecycleWorker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" }); });
async function insertAgents(input: typeof agents.$inferInsert | Array<typeof agents.$inferInsert>) {
const rows = Array.isArray(input) ? input : [input];
await db.insert(agents).values(rows.map(row => ({ ...row,
lifecycleState: ["paused", "pending_approval", "terminated"].includes(row.status ?? "") ? row.status! : "ready",
lifecycleHolds: row.status === "paused" ? [row.pauseReason ?? "manual"] : [],
})));
}
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
@@ -57,6 +68,7 @@ describeEmbeddedPostgres("companyService", () => {
}, 20_000);
afterEach(async () => {
await lifecycleWorker.stop();
await db.delete(routineTriggers);
await db.delete(routines);
await db.delete(builtInManagedResources);
@@ -165,7 +177,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values([
await insertAgents([
{
id: runningAgentId,
companyId,
@@ -335,7 +347,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values([
await insertAgents([
{
id: archivedPausedAgentId,
companyId,
@@ -382,6 +394,7 @@ describeEmbeddedPostgres("companyService", () => {
);
expect(reactivated?.status).toBe("active");
await lifecycleWorker.process(archivedPausedAgentId);
const reactivateActivity = await db
.select({
@@ -441,7 +454,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values([
await insertAgents([
{
id: runningAgentId,
companyId,
@@ -551,7 +564,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values([
await insertAgents([
{
id: archivedPausedAgentId,
companyId,
@@ -587,6 +600,7 @@ describeEmbeddedPostgres("companyService", () => {
);
expect(reactivated?.status).toBe("active");
await lifecycleWorker.process(archivedPausedAgentId);
const rows = await db
.select({ id: agents.id, status: agents.status, pauseReason: agents.pauseReason })
@@ -618,7 +632,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
await insertAgents({
id: terminatedAgentId,
companyId,
name: "Terminated Agent",
@@ -661,7 +675,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
await insertAgents({
id: manualPausedAgentId,
companyId,
name: "Manual Paused Agent",
@@ -713,7 +727,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
await insertAgents({
id: agentId,
companyId,
name: "Idle Agent",
@@ -788,7 +802,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
await insertAgents({
id: agentId,
companyId,
name: "Idle Agent",
@@ -863,7 +877,7 @@ describeEmbeddedPostgres("companyService", () => {
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
await insertAgents({
id: idleAgentId,
companyId,
name: "Idle Agent",
@@ -134,6 +134,13 @@ vi.mock("../services/agents.js", () => ({
agentService: () => agentSvc,
}));
vi.mock("../services/agent-lifecycle.js", () => ({
createAgentLifecycle: () => ({
requestHire: (...args: unknown[]) => agentSvc.create(...args),
pauseAgent: vi.fn(),
}),
}));
vi.mock("../services/access.js", () => ({
accessService: () => accessSvc,
}));
+5 -1
View File
@@ -189,12 +189,16 @@ describe("company decision service", () => {
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest,
actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt" } };
const remove = () => agentService(db).remove(f.agentId);
let inFlightDeletionError: unknown;
f.provider.mockImplementationOnce(async () => {
await expect(remove()).rejects.toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
// Exercise the accounting guard after lifecycle termination.
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }).where(eq(agents.id, f.agentId));
inFlightDeletionError = await remove().catch(error => error);
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" });
return { errorCode: "timeout", receipt: decisionReceipt("openai", null) };
});
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("failed");
expect(inFlightDeletionError).toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
await expect(remove()).rejects.toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0]).toMatchObject({ state: "held", amountCents: "1.0000000" });
});
+28 -2
View File
@@ -1,3 +1,8 @@
import { logActivity } from "../services/activity-log.js";
vi.mock("../services/activity-log.js", async importOriginal => {
const actual = await importOriginal<typeof import("../services/activity-log.js")>();
return { ...actual, logActivity: vi.fn(actual.logActivity) };
});
import { randomBytes, randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -38,7 +43,8 @@ it("atomically resumes one pending invite across retries and never persists a pa
const service = dotInvitationService(db);
const [a, b] = await Promise.all([service.create(f.companyId, f.userId), service.create(f.companyId, f.userId)]);
expect(a.agent.id).toBe(b.agent.id);
expect(a.agent.status).toBe("idle");
expect(a.agent.status).toBe("paused");
expect((await db.select().from(agents).where(eq(agents.id, a.agent.id)))[0]!.lifecycleState).toBe("preparing");
expect(await service.resume(f.companyId, f.userId)).toMatchObject({ agent: { id: a.agent.id } });
expect(await service.resume(f.companyId, randomUUID())).toBeNull();
expect(await db.select().from(agents).where(eq(agents.companyId, f.companyId))).toHaveLength(1);
@@ -47,6 +53,26 @@ it("atomically resumes one pending invite across retries and never persists a pa
expect(JSON.stringify(logs)).not.toContain(code.pairingCode);
expect(JSON.stringify(await service.resume(f.companyId, f.userId))).not.toContain(code.pairingCode);
});
it("reuses a committed hire when invitation completion must retry", async () => {
const f = await fixture(true);
const actual = await vi.importActual<typeof import("../services/activity-log.js")>("../services/activity-log.js");
vi.mocked(logActivity).mockImplementation(async (...args) => {
if (args[1].action === "agent.hire_created") {
vi.mocked(logActivity).mockImplementation(actual.logActivity);
throw new Error("Invitation audit unavailable");
}
return actual.logActivity(...args);
});
const service = dotInvitationService(db);
await expect(service.create(f.companyId, f.userId)).rejects.toThrow("Invitation audit unavailable");
const before = await db.select().from(agents).where(eq(agents.companyId, f.companyId));
expect(before).toHaveLength(1);
expect(await service.resume(f.companyId, f.userId)).toBeNull();
const retried = await service.create(f.companyId, f.userId);
expect(retried.agent.id).toBe(before[0]!.id);
expect(await db.select().from(approvals).where(eq(approvals.companyId, f.companyId))).toHaveLength(1);
expect(await db.select().from(agents).where(eq(agents.companyId, f.companyId))).toHaveLength(1);
});
it("honors hiring approval before issuing a pairing capability", async () => {
const f = await fixture(true);
const invite = await dotInvitationService(db).create(f.companyId, f.userId);
@@ -91,7 +117,7 @@ it("keeps invite routes company-scoped and denies viewers and agent actors", asy
expect(result.status, JSON.stringify(result.body)).toBe(200);
expect(result.body.agent.id).toBeTruthy();
expect((await request(app).get(path)).body.agent.id).toBe(result.body.agent.id);
expect(await db.select().from(agents).where(and(eq(agents.companyId, f.companyId), eq(agents.status, "idle")))).toHaveLength(1);
expect(await db.select().from(agents).where(and(eq(agents.companyId, f.companyId), eq(agents.lifecycleState, "preparing")))).toHaveLength(1);
});
it("does not trust editable agent metadata as an invitation ownership receipt", async () => {
@@ -4,7 +4,7 @@ import express from "express";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { createDb, authUsers, companies, companyMemberships, agents, dotAgentBindings, mcpOauthGrants, mcpOauthRequests, mcpOauthTokens } from "@paperclipai/db";
import { createDb, authUsers, companies, companyMemberships, agents, dotAgentBindings, dotMailboxItems, mcpEventSubscriptions, mcpOauthGrants, mcpOauthRequests, mcpOauthTokens } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { createPublicMcpOAuth, publicMcpConfig, hashMcpSecret, DEVICE_GRANT } from "../services/public-mcp/oauth.js";
import { instanceSettingsService } from "../services/instance-settings.js";
@@ -22,12 +22,12 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
}, 120000);
beforeEach(async () => { await instanceSettingsService(db).updateExperimental({ enablePublicMcp: true, enableOpenAiDot: true, enableNativeRunner: false }); });
afterAll(async () => { await temp?.cleanup(); });
async function fixture(authorizationOrigin?: string) {
async function fixture(authorizationOrigin?: string, lifecycleState = "ready") {
const userId = randomUUID();
await db.insert(authUsers).values({ id: userId, name: "Operator", email: userId + "@example.test", createdAt: new Date(), updatedAt: new Date() });
const [company] = await db.insert(companies).values({ name: "Dot onboarding", issuePrefix: "DO" + randomBytes(3).toString("hex") }).returning();
await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" });
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Dot", adapterType: "paperclip_runner", adapterConfig: { provider: "openai_dot" }, status: "active" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Dot", adapterType: "paperclip_runner", adapterConfig: { provider: "openai_dot" }, lifecycleState, status: lifecycleState === "ready" ? "active" : "paused" }).returning();
const oauth = createPublicMcpOAuth(db, { ...config, ...(authorizationOrigin ? { authorizationOrigin } : {}) });
const client = await oauth.register({ client_name: "Dot", redirect_uris: [callback], grant_types: ["authorization_code", "refresh_token", DEVICE_GRANT] }, randomUUID());
const verifier = randomBytes(32).toString("base64url");
@@ -43,6 +43,49 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
return f.oauth.token({ grant_type: "authorization_code", client_id: f.client.client_id,
redirect_uri: callback, resource: config.resource, code: new URL(consent.redirectUrl).searchParams.get("code"), code_verifier: f.verifier });
}
it("invalidates setup when a broker pairing is applied or revoked", async () => {
const f = await fixture(undefined, "preparing");
const consent = await f.oauth.consent(f.id, { type: "board", source: "session", userId: f.userId },
{ decision: "approve", companyId: f.company.id, allowWrites: false });
const tokens = await f.oauth.token({ grant_type: "authorization_code", client_id: f.client.client_id,
redirect_uri: callback, resource: config.resource, code: new URL(consent.redirectUrl).searchParams.get("code"), code_verifier: f.verifier });
const principal = await f.oauth.authenticate(tokens.access_token);
const broker = dotRunnerBroker(db);
await broker.pair(principal, f.pairing.pairingCode);
const [paired] = await db.select().from(agents).where(eq(agents.id, f.agent.id));
expect(paired.adapterConfig.dotBindingId).toBe(f.pairing.bindingId);
expect(paired.lifecycleVersion).toBe(f.agent.lifecycleVersion + 1);
await expect(broker.pair(principal, f.pairing.pairingCode)).rejects.toThrow("Pairing code expired or was consumed");
await broker.revoke(f.company.id, f.agent.id, f.userId);
const [revoked] = await db.select().from(agents).where(eq(agents.id, f.agent.id));
expect(revoked.adapterConfig).not.toHaveProperty("dotBindingId");
expect(revoked.lifecycleVersion).toBe(paired.lifecycleVersion + 1);
await expect(f.oauth.authenticate(tokens.access_token)).rejects.toThrow();
});
it.each(["preparing", "verifying"])("allows Dot setup during %s without allowing task access", async (state) => {
const f = await fixture(undefined, state);
const tokens = await connect(f);
const principal = await f.oauth.authenticate(tokens.access_token);
const broker = dotRunnerBroker(db);
await db.insert(mcpEventSubscriptions).values({ id: randomUUID(), companyId: f.company.id,
grantId: principal.grant.id, name: "paperclip.dot.mailbox_updated", bindingId: f.pairing.bindingId,
arguments: {}, deliveryMaterial: {}, verifiedAt: new Date(), expiresAt: new Date(Date.now() + 60_000) });
await db.insert(dotMailboxItems).values({ companyId: f.company.id, bindingId: f.pairing.bindingId,
bindingGeneration: 1, kind: "assignment", sourceEventId: randomUUID(), references: { task: "hidden" } });
await broker.challenge(f.company.id, f.agent.id);
const inbox = await broker.mailbox(principal);
expect(inbox.items.map(item => item.kind)).toEqual(["readiness_challenge"]);
expect(inbox.nextCursor).toBe(0);
await expect(broker.confirmChallenge(principal, String(inbox.items[0]!.references.challenge))).resolves.toEqual({ status: "ready" });
expect(await broker.capabilities(principal)).toMatchObject({ ready: false });
await expect(broker.tasks(principal)).rejects.toThrow("authority");
await expect(broker.snapshot(f.company.id, f.agent.id, f.pairing.bindingId)).rejects.toThrow("authority");
await db.update(agents).set({ lifecycleState: "paused" }).where(eq(agents.id, f.agent.id));
expect((await broker.mailbox(principal)).items).toEqual([]);
await expect(broker.confirmChallenge(principal, "already-used")).rejects.toThrow("authority");
});
it("refreshes a Dot connection after years of inactivity, still rotates and revokes on replay", async () => {
const f = await fixture();
const tokens = await connect(f);
@@ -12,6 +12,7 @@ import {
stopSshEnvLabFixture,
} from "@paperclipai/adapter-utils/ssh";
import {
activityLog,
costEvents,
agents,
builtInManagedResources,
@@ -219,6 +220,7 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
await stopSshEnvLabFixture(path.join(root, "state.json")).catch(() => undefined);
await rm(root, { recursive: true, force: true }).catch(() => undefined);
}
await db.delete(activityLog);
await db.delete(environmentLeases);
await db.delete(issues);
await db.delete(costEvents);
@@ -5780,6 +5782,21 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
});
});
it("destroys a failed retained lease when the agent stops", async () => {
const { lease, workerManager, runtimeWithPlugin, runId } = await seedStaleLifecycleReusableLease("retain_on_failure");
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
await runtimeWithPlugin.releaseRunLeases(runId, "failed");
await expect(environmentService(db).getLeaseById(lease.id)).resolves.toMatchObject({ status: "retained", cleanupStatus: "failed" });
vi.mocked(workerManager.getWorker).mockReturnValue({ supportedMethods: ["environmentDestroyLease"] } as never);
vi.mocked(workerManager.call).mockResolvedValue({ providerLeaseId: lease.providerLeaseId, state: "destroyed" });
const { heartbeatService } = await import("../services/heartbeat.js");
const stopped = await heartbeatService(db, { pluginWorkerManager: workerManager })
.stopInvocationsForAgents([lease.metadata!.agentId as string], "Agent lifecycle stop requested");
expect(stopped).toBe(true);
expect(workerManager.call).toHaveBeenCalledWith(expect.any(String), "environmentDestroyLease", expect.objectContaining({ providerLeaseId: lease.providerLeaseId }), expect.any(Number));
await expect(environmentService(db).getLeaseById(lease.id)).resolves.toMatchObject({ status: "expired", cleanupStatus: "success" });
});
it("fails closed on expiry destruction when the worker no longer advertises the destroy lifecycle method", async () => {
const { pluginId, lease, workerManager, runtimeWithPlugin } = await seedStaleLifecycleReusableLease();
@@ -9046,7 +9046,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
expect(mockTerminateLocalService).toHaveBeenCalledWith(
expect.objectContaining({ pid: 81_501, processGroupId: 81_502 }),
{ forceAfterMs: 3000 },
{ forceAfterMs: 3000, signal: "SIGINT" },
);
expect(runningProcesses.has(runId)).toBe(false);
});
@@ -216,6 +216,26 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {
return { companyId, agentId };
}
it.each(["preparing", "verifying", "resuming"] as const)("keeps assigned work queued through %s, including recovery with timers disabled", async lifecycleState => {
const { companyId, agentId } = await seedCompanyAndAgent({ heartbeatConfig: { enabled: false } });
await db.update(agents).set({ status: "paused", lifecycleState }).where(eq(agents.id, agentId));
const [issue] = await db.insert(issues).values({ companyId, title: "Work accepted during setup", status: "todo", assigneeAgentId: agentId }).returning();
const run = await heartbeat.wakeup(agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned",
requestedByActorType: "system", payload: { issueId: issue.id } });
expect(run?.status).toBe("queued");
await heartbeat.resumeQueuedRuns();
expect((await heartbeat.getRun(run!.id))?.status).toBe("queued");
expect(countExecuteCallsForRun(run!.id)).toBe(0);
expect((await heartbeat.reconcileStrandedAssignedIssues()).escalated).toBe(0);
expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0]).toMatchObject({ status: "todo", assigneeAgentId: agentId });
await db.update(agents).set({ status: "idle", lifecycleState: "ready" }).where(eq(agents.id, agentId));
const recovered = heartbeatService(db, { runtimeEnv: { ...process.env, PAPERCLIP_IN_WORKTREE: "false" } });
await recovered.resumeQueuedRuns();
expect(await waitForCondition(async () => countExecuteCallsForRun(run!.id) === 1)).toBe(true);
await recovered.waitForRunExecutionDrain(run!.id);
expect(countExecuteCallsForRun(run!.id)).toBe(1);
});
async function seedQueuedRun(input: {
companyId: string;
agentId: string;
@@ -7,6 +7,10 @@ const canUserMock = vi.fn();
const insertMock = vi.fn();
function registerModuleMocks() {
vi.doMock("../services/agent-lifecycle.js", () => ({
createAgentLifecycle: () => ({}),
AgentLifecycleConflict: class extends Error {},
}));
vi.doMock("../services/index.js", () => ({
accessService: () => ({
isInstanceAdmin: vi.fn(),
@@ -8,7 +8,7 @@ import {
normalizeHumanRole,
resolveHumanInviteRole,
} from "../services/company-member-roles.js";
import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "../services/agent-permissions.js";
import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "../lib/agent-permissions.js";
const invitedAgentId = "agent-1";
const defaultAgentGrants = NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({
@@ -1031,6 +1031,7 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
{ agentId: creatorAgentId },
);
await db.update(agents).set({ lifecycleState: "terminated", status: "terminated" }).where(eq(agents.id, addresseeAgentId));
await agentService(db).remove(addresseeAgentId);
const cancelled = await interactionsSvc.getById(created.id);
@@ -236,7 +236,9 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
expect(companyGoals[0]?.title).toBe("Make robotics boring");
expect(companyGoals[0]?.description).toBe("Boring enough that hospitals buy it.");
// No agent and no task were sent, so none were invented.
expect(await ctx.db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
const committedAgents = await ctx.db.select().from(agents).where(eq(agents.companyId, companyId));
expect(committedAgents).toHaveLength(0);
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
expect(await ctx.db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(0);
expect(response.body.agentId).toBeNull();
expect(response.body.issueId).toBeNull();
@@ -273,12 +275,7 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
expect(entries).toHaveLength(1);
});
it("rolls the whole seed back when the audit entry cannot be written", async () => {
// The audit entry shares the seed's transaction, so a failure to write it
// must leave nothing behind. The alternative — commit the seed and lose the
// entry — is unrecoverable: Cloud stops retrying on a 2xx, and a later
// replay reports `changed: false` and never logs, so the entry would be
// permanently absent.
it("reuses the committed hire after the content transaction fails", async () => {
const { companyId, app } = await seedCompany();
// Injected at the module boundary, not on `ctx.db`: the audit write goes
@@ -289,18 +286,20 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
const failed = await post(app, companyId, SEED);
expect(failed.status).toBeGreaterThanOrEqual(500);
// Nothing committed: no seed record, so Cloud has no acknowledged revision
// and keeps retrying, and no orphaned agent from the rolled-back attempt.
// The failed content transaction must not acknowledge the revision.
expect(
await ctx.db
.select()
.from(companyOnboardingSeeds)
.where(eq(companyOnboardingSeeds.companyId, companyId)),
).toHaveLength(0);
expect(await ctx.db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
const committedAgents = await ctx.db.select().from(agents).where(eq(agents.companyId, companyId));
expect(committedAgents).toHaveLength(1);
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
// And the retry recovers completely — seed applied, entry present.
await post(app, companyId, SEED).expect(200);
expect((await ctx.db.select().from(agents).where(eq(agents.companyId, companyId))).map(agent => agent.id))
.toEqual(committedAgents.map(agent => agent.id));
expect(
await ctx.db
.select()
@@ -327,7 +326,9 @@ describeEmbeddedPostgres("POST /api/companies/:companyId/onboarding-seed", () =>
const response = await post(strangerApp, companyId, SEED);
expect(response.status).toBe(403);
expect(await ctx.db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
const committedAgents = await ctx.db.select().from(agents).where(eq(agents.companyId, companyId));
expect(committedAgents).toHaveLength(0);
expect(await ctx.db.select().from(projects).where(eq(projects.companyId, companyId))).toHaveLength(0);
expect(await ctx.db.select().from(companyOnboardingSeeds)).toHaveLength(0);
});
@@ -279,6 +279,15 @@ function loadSpecRoutes() {
}
describe("openapi routes", () => {
it("documents only writable agent update fields and lifecycle status requests", () => {
const document = buildOpenApiSpec() as any;
const properties = document.paths["/api/agents/{id}"].patch.requestBody.content["application/json"].schema.properties;
expect(properties).not.toHaveProperty("spentMonthlyCents");
expect(properties.status.enum).toEqual(["paused", "idle", "terminated"]);
expect(properties).toHaveProperty("name");
expect(properties).toHaveProperty("budgetMonthlyCents");
});
it("documents manager-only task privacy hints without protected scope identity", () => {
const spec = buildOpenApiSpec() as any;
const operation = spec.paths["/api/issues/{id}/privacy-constraints"].get;
@@ -21,6 +21,18 @@ function fixture(definition: PluginDefinition, rpcTimeoutMs = 30_000) {
}
describe("plugin idle RPC", () => {
it("advertises and dispatches the agent lifecycle method", async () => {
const request = { companyId: "company", agentId: "agent", operationId: "operation", version: 7, phase: "preparing" };
const f = fixture({ async setup() {}, async onAgentLifecycle(input) {
expect(input).toEqual(request);
return { operationId: input.operationId, version: input.version, status: "pending" };
} });
try {
expect((await f.initialize()).result.supportedMethods).toContain("agentLifecycle");
expect((await f.call("agentLifecycle", request)).result).toEqual({ operationId: "operation", version: 7, status: "pending" });
} finally { f.close(); }
});
const hold = () => ({ ownerId: "idle-owner", expiresAt: Date.now() + 30_000 });
it("seals an idle worker, fences stale releases, and restores normal calls", async () => {
@@ -1,3 +1,4 @@
import { createAgentLifecycle, configureAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
@@ -268,11 +269,15 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
it("keeps an explicit resume durable across managed-agent reconcile", async () => {
const { companyId, services } = await seedCompanyAndPlugin({ manifest: pausedManifest() });
const created = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
await agentService(db).resume(created.agentId!);
await createAgentLifecycle(db).resumeAgent(created.agentId!);
const reconciled = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
expect(reconciled.agent).toMatchObject({
expect(reconciled.agent).toMatchObject({ lifecycleState: "resuming", pauseReason: null });
const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" });
await worker.process(created.agentId!);
await worker.stop();
expect((await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" })).agent).toMatchObject({
status: "idle",
pauseReason: null,
pausedAt: null,
+10 -8
View File
@@ -1,3 +1,4 @@
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import express from "express";
@@ -42,7 +43,7 @@ if (!support.supported) console.warn(`Primary agent database tests unavailable:
await db.insert(companyMemberships).values(["user-a", "user-b", "explicit"].map(principalId => ({ companyId: id, principalType: "user", principalId, status: "active", membershipRole: "admin" })));
return id;
}
const create = (companyId: string, name: string, userId?: string) => agentService(db).create(companyId, {
const create = (companyId: string, name: string, userId?: string) => createAgentLifecycle(db).requestHire(companyId, {
name, adapterType: "process", status: "idle",
}, { createdByUserId: userId });
const get = (companyId: string, userId = "user-a") => primaryAgentService(db).get(companyId, userId);
@@ -123,9 +124,9 @@ if (!support.supported) console.warn(`Primary agent database tests unavailable:
it("retains paused/error primaries, clears on leave, rejoins when chosen, and preserves stars", async () => {
const c = await company(); const a = await create(c, "Maia", "user-a");
await agentService(db).pause(a.id);
await createAgentLifecycle(db).pauseAgent(a.id);
expect((await get(c)).primaryAgentId).toBe(a.id);
await agentService(db).update(a.id, { status: "error" });
await db.update(agents).set({ status: "error", lifecycleState: "ready", lifecycleHolds: [] }).where(eq(agents.id, a.id));
expect((await get(c)).primaryAgentId).toBe(a.id);
const memberships = resourceMembershipService(db);
await memberships.updateAgent({ companyId: c, userId: "user-a", agentId: a.id, state: "left", actor: actor(c) });
@@ -153,23 +154,24 @@ if (!support.supported) console.warn(`Primary agent database tests unavailable:
it("clears terminated/deleted primaries and rejects terminated targets and explicit removal", async () => {
const c = await company(); const a = await create(c, "Maia", "user-a");
await agentService(db).terminate(a.id);
await createAgentLifecycle(db).terminateAgent(a.id);
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: true });
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: a.id }).expect(422);
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: null }).expect(400);
const b = await create(c, "Alex", "user-a");
expect((await get(c)).primaryAgentId).toBeNull();
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: b.id }).expect(200);
await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }).where(eq(agents.id, b.id));
await agentService(db).remove(b.id);
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: true });
});
it("rolls creation and initialization back together", async () => {
it("rejects creation inside a caller transaction", async () => {
const c = await company();
await expect(db.transaction(async tx => {
await agentService(tx as unknown as typeof db).create(c, { name: "Rolled back", adapterType: "process" }, { createdByUserId: "user-a" });
await createAgentLifecycle(tx as unknown as typeof db).requestHire(c, { name: "Rolled back", adapterType: "process" }, { createdByUserId: "user-a" });
throw new Error("rollback");
})).rejects.toThrow("rollback");
})).rejects.toThrow("root database");
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: false });
expect(await db.select().from(agents).where(eq(agents.companyId, c))).toHaveLength(0);
});
@@ -177,7 +179,7 @@ if (!support.supported) console.warn(`Primary agent database tests unavailable:
it("backfills the earliest human event, leaves gone/terminated originals empty, and preserves explicit preferences", async () => {
const c = await company(); const first = await create(c, "First"), later = await create(c, "Later");
const terminated = await create(c, "Terminated");
await agentService(db).terminate(terminated.id);
await createAgentLifecycle(db).terminateAgent(terminated.id);
const events = [
["human", first.id, "user", 1], ["human", later.id, "user", 2],
["gone", randomUUID(), "user", 1], ["gone", later.id, "user", 2],
@@ -1,3 +1,4 @@
import { createAgentLifecycle, configureAgentLifecycle } from "../services/agent-lifecycle.js";
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { eq, sql } from "drizzle-orm";
@@ -22,23 +23,29 @@ describePostgres("Resource lifecycle events", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let companyId: string;
let worker: ReturnType<typeof configureAgentLifecycle>;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-resource-events-");
db = createDb(database.connectionString);
}, 90_000);
afterAll(async () => { await database?.cleanup(); });
afterAll(async () => { await worker?.stop(); await database?.cleanup(); });
beforeEach(async () => {
vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", undefined);
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", undefined);
await worker?.stop();
worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost: async () => "complete" });
companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Lifecycle fixture", issuePrefix: `L${companyId.replaceAll("-", "").slice(0, 6)}` });
});
afterEach(() => { vi.unstubAllEnvs(); });
const events = () => db.select().from(resourceLifecycleEvents).where(eq(resourceLifecycleEvents.companyId, companyId));
const createAgent = (status: "idle" | "pending_approval" | "terminated" = "idle", database: Db = db) =>
agentService(database).create(companyId, { name: "Lifecycle agent", adapterType: "process", adapterConfig: {}, status });
const createAgent = async (status: "idle" | "pending_approval" | "terminated" = "idle", database: Db = db) => {
const agent = await createAgentLifecycle(database).requestHire(companyId, { name: "Lifecycle agent", adapterType: "process", adapterConfig: {}, status });
await worker.process(agent.id);
return (await agentService(db).getById(agent.id))!;
};
const createPlugin = async () => {
const [plugin] = await db.insert(plugins).values({ pluginKey: randomUUID(), packageName: "lifecycle-fixture", version: "1.0.0", status: "ready", manifestJson: {} as never }).returning();
return plugin;
@@ -56,7 +63,7 @@ describePostgres("Resource lifecycle events", () => {
const approval = await approvalService(db).create(companyId, { type: "hire_agent", status: "pending", payload: { agentId: agent.id } });
await approvalService(db).approve(approval.id, "fixture-board");
await approvalService(db).approve(approval.id, "fixture-board");
await agentService(db).activatePendingApproval(agent.id);
await createAgentLifecycle(db).approveHire(agent.id);
expect(await events()).toEqual([expect.objectContaining({ resourceType: "agent", resourceId: agent.id })]);
});
@@ -64,6 +71,7 @@ describePostgres("Resource lifecycle events", () => {
const approval = await approvalService(db).create(companyId, { type: "hire_agent", status: "pending", payload: { name: "Legacy hire", adapterType: "process" } });
await approvalService(db).approve(approval.id, "fixture-board");
const [intent] = await events();
if (intent) await worker.process(intent.resourceId);
expect(intent?.resourceType).toBe("agent");
expect(await agentService(db).getById(intent!.resourceId)).toMatchObject({ status: "idle", companyId });
});
@@ -111,25 +119,32 @@ describePostgres("Resource lifecycle events", () => {
it("records every pause/resume cycle and termination in resource order, without duplicate hooks", async () => {
const agent = await createAgent();
const service = agentService(db);
const serviceLifecycle = createAgentLifecycle(db);
await db.insert(agentApiKeys).values({ agentId: agent.id, companyId, name: "Lifecycle key", keyHash: "fixture-hash" });
await Promise.all(Array.from({ length: 4 }, () => service.pause(agent.id)));
await Promise.all(Array.from({ length: 4 }, () => service.resume(agent.id)));
await service.update(agent.id, { status: "paused" });
await service.update(agent.id, { status: "idle" });
await Promise.all(Array.from({ length: 4 }, () => service.terminate(agent.id)));
await Promise.all(Array.from({ length: 4 }, () => serviceLifecycle.pauseAgent(agent.id)));
await worker.process(agent.id);
await Promise.all(Array.from({ length: 4 }, () => serviceLifecycle.resumeAgent(agent.id)));
await worker.process(agent.id);
await serviceLifecycle.pauseAgent(agent.id);
await worker.process(agent.id);
await worker.process(agent.id);
await serviceLifecycle.resumeAgent(agent.id);
await worker.process(agent.id);
await worker.process(agent.id);
await Promise.all(Array.from({ length: 4 }, () => serviceLifecycle.terminateAgent(agent.id)));
const rows = (await events()).sort((a, b) => a.id - b.id);
expect(rows.map(row => row.action)).toEqual(["create", "pause", "resume", "pause", "resume", "terminate"]);
expect(rows.every(row => row.resourceId === agent.id)).toBe(true);
const [key] = await db.select().from(agentApiKeys).where(eq(agentApiKeys.agentId, agent.id));
expect(key.revokedAt).not.toBeNull();
await expect(service.pause(agent.id)).rejects.toMatchObject({ status: 409 });
await expect(service.resume(agent.id)).rejects.toMatchObject({ status: 409 });
await expect(serviceLifecycle.pauseAgent(agent.id)).rejects.toMatchObject({ name: "AgentLifecycleConflict" });
await expect(serviceLifecycle.resumeAgent(agent.id)).rejects.toMatchObject({ name: "AgentLifecycleConflict" });
});
it("does not bypass pending hire approval with pause or resume", async () => {
const agent = await createAgent("pending_approval");
await expect(agentService(db).pause(agent.id)).rejects.toMatchObject({ status: 409 });
await expect(agentService(db).resume(agent.id)).rejects.toMatchObject({ status: 409 });
await expect(createAgentLifecycle(db).pauseAgent(agent.id)).rejects.toMatchObject({ name: "AgentLifecycleConflict" });
await expect(createAgentLifecycle(db).resumeAgent(agent.id)).rejects.toMatchObject({ name: "AgentLifecycleConflict" });
expect(await events()).toEqual([]);
});
@@ -142,6 +157,7 @@ describePostgres("Resource lifecycle events", () => {
await service.evaluateCostEvent(event);
expect(await agentService(db).getById(agent.id)).toMatchObject({ status: "paused", pauseReason: "budget" });
await service.upsertPolicy(companyId, { scopeType: "agent", scopeId: agent.id, amount: 200 }, "fixture-board");
await worker.process(agent.id);
expect(await agentService(db).getById(agent.id)).toMatchObject({ status: "idle", pauseReason: null });
expect((await events()).sort((a, b) => a.id - b.id).map(row => row.action)).toEqual(["create", "pause", "resume"]);
});
@@ -149,14 +165,15 @@ describePostgres("Resource lifecycle events", () => {
it("rolls back pause, resume, termination, and key revocation if a hook write fails", async () => {
const agent = await createAgent();
const paused = await createAgent();
await agentService(db).pause(paused.id);
await createAgentLifecycle(db).pauseAgent(paused.id);
await worker.process(paused.id);
await db.insert(agentApiKeys).values({ agentId: agent.id, companyId, name: "Retained key", keyHash: "fixture-retained-hash" });
const before = await events();
await db.execute(sql`ALTER TABLE resource_lifecycle_events ADD CONSTRAINT fixture_reject_hook CHECK (false) NOT VALID`);
try {
await expect(agentService(db).pause(agent.id)).rejects.toThrow();
await expect(agentService(db).resume(paused.id)).rejects.toThrow();
await expect(agentService(db).terminate(agent.id)).rejects.toThrow();
await expect(createAgentLifecycle(db).pauseAgent(agent.id)).rejects.toThrow();
await expect(createAgentLifecycle(db).resumeAgent(paused.id)).rejects.toThrow();
await expect(createAgentLifecycle(db).terminateAgent(agent.id)).rejects.toThrow();
expect(await agentService(db).getById(agent.id)).toMatchObject({ status: "idle" });
expect(await agentService(db).getById(paused.id)).toMatchObject({ status: "paused" });
const [key] = await db.select().from(agentApiKeys).where(eq(agentApiKeys.agentId, agent.id));
@@ -172,7 +189,8 @@ describePostgres("Resource lifecycle events", () => {
const projectId = randomUUID();
await expect(db.transaction(async tx => {
const txDb = tx as unknown as Db;
await agentService(txDb).create(companyId, { id: agentId, name: "Rolled back agent" });
await tx.insert(agents).values({ id: agentId, companyId, name: "Rolled back agent" });
await recordResourceCreationEvent(txDb, companyId, "agent", agentId);
await projectService(txDb).createWithRepositories(companyId, { id: projectId, name: "Rolled back project" }, []);
throw new Error("rollback fixture");
})).rejects.toThrow("rollback fixture");
@@ -387,8 +405,10 @@ describePostgres("Resource lifecycle events", () => {
const first = await createPlugin();
const second = await createPlugin();
const agent = await createAgent();
await agentService(db).pause(agent.id);
await agentService(db).resume(agent.id);
await createAgentLifecycle(db).pauseAgent(agent.id);
await worker.process(agent.id);
await createAgentLifecycle(db).resumeAgent(agent.id);
await worker.process(agent.id);
const journal = (await events()).sort((a, b) => a.id - b.id);
const inbox = pluginLifecycleInbox(db, first.id);
const [event] = await inbox.list(companyId);
@@ -426,7 +446,8 @@ describePostgres("Resource lifecycle events", () => {
const plugin = await createPlugin();
const inbox = pluginLifecycleInbox(db, plugin.id);
await db.transaction(async tx => {
const low = await agentService(tx as unknown as Db).create(companyId, { name: "Delayed commit" });
const [low] = await tx.insert(agents).values({ companyId, name: "Delayed commit" }).returning();
await recordResourceCreationEvent(tx as unknown as Db, companyId, "agent", low.id);
const high = await createAgent();
const [visible] = await inbox.list(companyId);
expect(visible.resourceId).toBe(high.id);
@@ -335,7 +335,7 @@ describeEmbeddedPostgres("secret proposal routes", () => {
]);
});
it("requires agent JWT and atomically cascade-approves a secret plus binding with dual audits", async () => {
it("requires agent JWT and approves a secret before its binding with dual audits", async () => {
const fixture = await seedRun();
const denied = await request(createAgentApp(fixture, "agent_key"))
.post("/api/agents/me/secret-proposals")
@@ -475,6 +475,46 @@ describeEmbeddedPostgres("secret proposal routes", () => {
]);
});
it("keeps an approved secret after binding fails and reuses it on retry", async () => {
const fixture = await seedRun();
const agentApp = createAgentApp(fixture);
const boardApp = createBoardApp(fixture);
const secret = await request(agentApp).post("/api/agents/me/secret-proposals").send({
kind: "secret", name: "dev/retry/token", value: "retry-fixture", justification: "Needed by task",
});
const binding = await request(agentApp).post("/api/agents/me/secret-proposals").send({
kind: "binding", secretProposalId: secret.body.id, configPath: "env.RETRY_TOKEN", justification: "Use saved secret",
});
expect(secret.status).toBe(201);
expect(binding.status).toBe(201);
await db.update(agents).set({ adapterConfig: { env: { RETRY_TOKEN: "existing-value" } } })
.where(eq(agents.id, fixture.agentId));
const approve = () => request(boardApp)
.post(`/api/companies/${fixture.companyId}/secret-proposals/${binding.body.id}/approve`).send({ cascade: true });
expect((await approve()).status).toBe(409);
const [saved] = await db.select().from(companySecrets);
expect(saved).toMatchObject({ name: "dev/retry/token", status: "active" });
expect(await db.select().from(companySecretProposals)).toEqual(expect.arrayContaining([
expect.objectContaining({ id: secret.body.id, status: "approved", createdSecretId: saved.id, valueCiphertext: null }),
expect.objectContaining({ id: binding.body.id, status: "pending" }),
]));
expect(await db.select().from(companySecretBindings)).toHaveLength(0);
expect((await db.select().from(agents))[0].adapterConfig).toEqual({ env: { RETRY_TOKEN: "existing-value" } });
expect((await db.select().from(issueThreadInteractions))[0].status).toBe("pending");
await db.update(agents).set({ adapterConfig: {} }).where(eq(agents.id, fixture.agentId));
expect((await approve()).status).toBe(200);
expect(await db.select().from(companySecrets)).toHaveLength(1);
expect(await db.select().from(companySecretVersions)).toHaveLength(1);
expect(await db.select().from(companySecretBindings)).toEqual([
expect.objectContaining({ secretId: saved.id, targetId: fixture.agentId, configPath: "env.RETRY_TOKEN" }),
]);
const history = await db.select().from(activityLog);
expect(history.filter(row => row.action === "secret.created")).toHaveLength(1);
expect(history.filter(row => row.action === "secret.proposal.approved")).toHaveLength(2);
});
it("approves a binding without cascade after its secret proposal was approved separately", async () => {
const fixture = await seedRun();
const agentApp = createAgentApp(fixture);
@@ -1446,7 +1486,7 @@ describeEmbeddedPostgres("secret proposal routes", () => {
]));
});
it("holds the org graph stable until binding approval commits", async () => {
it("rechecks the org graph after secret approval commits", async () => {
const fixture = await seedRun();
const targetAgentId = randomUUID();
await db.insert(agents).values({
@@ -1532,8 +1572,9 @@ describeEmbeddedPostgres("secret proposal routes", () => {
expect(reorgFinished).toBe(false);
const approval = await approvalPromise;
expect(approval.status).toBe(200);
await reorgPromise;
expect(approval.status).toBe(409);
expect(approval.body.error).toContain("chain-of-command policy");
} finally {
await db.execute(sql.raw(`
DROP TRIGGER IF EXISTS paperclip_test_pause_secret_approval ON company_secrets;
@@ -1541,9 +1582,12 @@ describeEmbeddedPostgres("secret proposal routes", () => {
`));
}
expect(await db.select().from(companySecretBindings)).toEqual([
expect.objectContaining({ targetId: targetAgentId, configPath: "access.CONCURRENT_REORG_TOKEN" }),
]);
expect(await db.select().from(companySecretBindings)).toHaveLength(0);
expect(await db.select().from(companySecrets)).toHaveLength(1);
expect(await db.select().from(companySecretProposals)).toEqual(expect.arrayContaining([
expect.objectContaining({ id: secretProposal.body.id, status: "approved", valueCiphertext: null }),
expect.objectContaining({ id: bindingProposal.body.id, status: "pending" }),
]));
expect(await db.select({ reportsTo: agents.reportsTo }).from(agents).where(eq(agents.id, targetAgentId)))
.toEqual([{ reportsTo: null }]);
});
+1 -1
View File
@@ -27,7 +27,7 @@ import {
} from "@paperclipai/shared";
import { errorHandler } from "../middleware/index.js";
import { statusCardRoutes } from "../routes/status-cards.js";
import { withBuiltInAgentMarker } from "../services/built-in-agent-metadata.js";
import { withBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import type { IssueAssignmentWakeupDeps } from "../services/issue-assignment-wakeup.js";
import { issueService } from "../services/issues.js";
+1 -1
View File
@@ -20,7 +20,7 @@ import {
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { summarySlotService } from "../services/summary-slots.ts";
import { withBuiltInAgentMarker } from "../services/built-in-agent-metadata.ts";
import { withBuiltInAgentMarker } from "../lib/built-in-agent-metadata.ts";
import { issueService } from "../services/issues.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+6
View File
@@ -1,5 +1,7 @@
import { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js";
import { createLifecycleDriver } from "./services/agent-lifecycle-driver.js";
import { startAgentLifecycle } from "./services/agent-lifecycle.js";
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "./middleware/idle-admission.js";
import { isIdleTaskDrainActive, trackIdleWork } from "./services/task-admission.js";
import { customerSuccessRoutes } from "./routes/customer-success.js";
@@ -623,6 +625,8 @@ export async function createApp(
const hostServicesDisposers = new Map<string, () => void>();
const workerManager = opts.pluginWorkerManager ?? createPluginWorkerManager();
let lifecyclePluginsReady = false;
const agentLifecycle = startAgentLifecycle(db, createLifecycleDriver(db, workerManager), () => lifecyclePluginsReady && !isWarmStandby() && !isIdleTaskDrainActive());
const connectionIntentHeartbeat = heartbeatService(db, {
pluginWorkerManager: workerManager,
});
@@ -1360,6 +1364,7 @@ export async function createApp(
logger.error({ err }, "Failed to load ready plugins on startup");
});
app.locals.bundledPluginsStartup = trackIdleWork(bundledPluginsStartup);
void bundledPluginsStartup.then(() => { lifecyclePluginsReady = true; return agentLifecycle.sweep(); }).catch(() => logger.warn("Agent lifecycle recovery failed; retrying."));
// The shutdown hook runs at most once. It caches the in-flight promise, so a
// second caller (for example the `exit` handler) awaits the same completion
// instead of starting a second teardown.
@@ -1370,6 +1375,7 @@ export async function createApp(
// The scheduler tick queries the database. Stop it here, inside the
// awaited teardown, so no tick runs after the caller ends the pool.
scheduler.stop();
await agentLifecycle.stop();
await publicMcpEvents?.stop();
await dotMcpEvents?.stop();
jobCoordinator.stop();
File renamed without changes.
+475
View File
@@ -0,0 +1,475 @@
import { createHash, randomBytes } from "node:crypto";
import { and, eq, gte, inArray, lt, sql } from "drizzle-orm";
import { agents, costEvents, type Db } from "@paperclipai/db";
import {
agentAppearanceSchema, resolveAgentAppearance, agentAvatarUrl,
AGENT_DEFAULT_MAX_CONCURRENT_RUNS, agentRuntimeConfigSchema, getAgentWorkEligibility,
normalizeAgentUrlKey, type AgentEligibilityAgent, type AgentRunnerChoice,
} from "@paperclipai/shared";
import { conflict, notFound, unprocessable } from "../errors.js";
import { REDACTED_EVENT_VALUE, sanitizeRecord } from "../redaction.js";
import { normalizeAgentPermissions } from "./agent-permissions.js";
import { builtInAgentMarkersEqual, readBuiltInAgentMarker } from "./built-in-agent-metadata.js";
export function hashToken(token: string) {
return createHash("sha256").update(token).digest("hex");
}
export function createToken() {
return `pcp_${randomBytes(24).toString("hex")}`;
}
const CONFIG_REVISION_FIELDS = [
"name",
"role",
"title",
"icon",
"appearance",
"reportsTo",
"capabilities",
"adapterType",
"adapterConfig",
"runtimeConfig",
"defaultEnvironmentId",
"budgetMonthlyCents",
"metadata",
] as const;
type ConfigRevisionField = (typeof CONFIG_REVISION_FIELDS)[number];
type AgentConfigSnapshot = Pick<typeof agents.$inferSelect, ConfigRevisionField>;
export interface RevisionMetadata {
createdByAgentId?: string | null;
createdByUserId?: string | null;
source?: string;
rolledBackFromRevisionId?: string | null;
}
/**
* The Claude login context for an agent write. The route derives the owner user
* from the authenticated actor, not from the request body, and forwards the
* non-secret `storedSessionId` claim from a completed Claude login session. A
* controlled internal override permits a migration or an administrator repair to
* bind or unbind the fixed OAuth token without a claim.
*
* The `applyExistingWithoutClaim` field is the user-actor apply-existing path.
* The route sets it only for an authenticated user actor and derives the owner
* from that actor. The path binds the fixed reference to the owner stored value
* with no login round trip. It is distinct from `allowInternalBindingOverride`,
* which does no ownership check.
*
* The `inheritedFromAgentId` field is the hire-inheritance path. The route
* sets it only for an authenticated agent actor whose hire request inherited
* the fixed reference from that named parent. The service re-reads the parent
* agent inside the write transaction and binds the fixed reference only when
* the parent exists, is in the same company, is a `claude_local` agent, and
* already holds the exact fixed binding.
*/
export interface ClaudeLoginContext {
storedSessionId?: string | null;
ownerUserId?: string | null;
allowInternalBindingOverride?: boolean;
applyExistingWithoutClaim?: boolean;
inheritedFromAgentId?: string | null;
}
export interface UpdateAgentOptions {
recordRevision?: RevisionMetadata;
allowBuiltInAgentMetadata?: boolean;
allowPendingApprovalConfigUpdate?: boolean;
claudeLogin?: ClaudeLoginContext;
}
export type CreateAgentData = Omit<typeof agents.$inferInsert, "companyId" | "lifecycleState" | "lifecycleRequiredPluginIds" | "lifecycleHolds" | "lifecycleVersion" | "lifecycleError" | "lifecycleOperation"> & { runner?: AgentRunnerChoice };
export type AgentConfigurationRecord = typeof agents.$inferSelect;
export const AGENT_CONFIGURATION_FIELDS = [...CONFIG_REVISION_FIELDS, "permissions"] as const;
export type AgentConfigurationPatch = Partial<Pick<typeof agents.$inferInsert, typeof AGENT_CONFIGURATION_FIELDS[number]>>;
export type AgentHireRecord = Pick<typeof agents.$inferSelect, "id" | "companyId" | "adapterType" | "adapterConfig" | "permissions" | "metadata" | "status">;
export interface CreateAgentOptions {
/** Reviewed/historical execution already resolved by a governed internal caller. */
runnerResolved?: boolean;
responsibleUserId?: string | null;
createdByUserId?: string | null;
aiConnectionInstall?: { connectionId: string; memberConnectionIds?: string[]; createdByUserId: string | null };
allowBuiltInAgentMetadata?: boolean;
claudeLogin?: ClaudeLoginContext;
}
interface AgentShortnameRow {
id: string;
name: string;
status: string;
}
interface AgentShortnameCollisionOptions {
excludeAgentId?: string | null;
}
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function jsonEqual(left: unknown, right: unknown): boolean {
return JSON.stringify(left) === JSON.stringify(right);
}
export function buildConfigSnapshot(
row: Pick<typeof agents.$inferSelect, ConfigRevisionField>,
): AgentConfigSnapshot {
const adapterConfig =
typeof row.adapterConfig === "object" && row.adapterConfig !== null && !Array.isArray(row.adapterConfig)
? sanitizeRecord(row.adapterConfig as Record<string, unknown>)
: {};
const runtimeConfig =
typeof row.runtimeConfig === "object" && row.runtimeConfig !== null && !Array.isArray(row.runtimeConfig)
? sanitizeRecord(row.runtimeConfig as Record<string, unknown>)
: {};
const metadata =
typeof row.metadata === "object" && row.metadata !== null && !Array.isArray(row.metadata)
? sanitizeRecord(row.metadata as Record<string, unknown>)
: row.metadata ?? null;
return {
name: row.name,
role: row.role,
title: row.title,
icon: row.icon,
appearance: row.appearance,
reportsTo: row.reportsTo,
capabilities: row.capabilities,
adapterType: row.adapterType,
adapterConfig,
runtimeConfig,
defaultEnvironmentId: row.defaultEnvironmentId,
budgetMonthlyCents: row.budgetMonthlyCents,
metadata,
};
}
export function containsRedactedMarker(value: unknown): boolean {
if (value === REDACTED_EVENT_VALUE) return true;
if (Array.isArray(value)) return value.some((item) => containsRedactedMarker(item));
if (typeof value !== "object" || value === null) return false;
return Object.values(value as Record<string, unknown>).some((entry) => containsRedactedMarker(entry));
}
export function hasConfigPatchFields(data: Partial<typeof agents.$inferInsert>) {
return CONFIG_REVISION_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(data, field));
}
export function changedPendingApprovalConfigFields(
existing: Omit<typeof agents.$inferSelect, "lifecycleOperation" | "lifecycleRequiredPluginIds">,
data: Partial<typeof agents.$inferInsert>,
) {
return CONFIG_REVISION_FIELDS.filter((field) =>
Object.prototype.hasOwnProperty.call(data, field) && !jsonEqual(data[field], existing[field]),
);
}
export function configPatchFromApprovalPayload(payload: Record<string, unknown>) {
const patch: Partial<typeof agents.$inferInsert> = {};
if (typeof payload.name === "string") patch.name = payload.name;
if (typeof payload.role === "string") patch.role = payload.role;
if (payload.appearance != null) patch.appearance = agentAppearanceSchema.parse(payload.appearance);
if (Object.prototype.hasOwnProperty.call(payload, "title")) {
patch.title = typeof payload.title === "string" ? payload.title : null;
}
if (Object.prototype.hasOwnProperty.call(payload, "icon")) {
patch.icon = typeof payload.icon === "string" ? payload.icon : null;
}
if (Object.prototype.hasOwnProperty.call(payload, "reportsTo")) {
patch.reportsTo = typeof payload.reportsTo === "string" ? payload.reportsTo : null;
}
if (Object.prototype.hasOwnProperty.call(payload, "capabilities")) {
patch.capabilities = typeof payload.capabilities === "string" ? payload.capabilities : null;
}
if (typeof payload.adapterType === "string") patch.adapterType = payload.adapterType;
if (isPlainRecord(payload.adapterConfig)) patch.adapterConfig = payload.adapterConfig;
if (isPlainRecord(payload.runtimeConfig)) patch.runtimeConfig = payload.runtimeConfig;
if (Object.prototype.hasOwnProperty.call(payload, "defaultEnvironmentId")) {
patch.defaultEnvironmentId =
typeof payload.defaultEnvironmentId === "string" ? payload.defaultEnvironmentId : null;
}
if (typeof payload.budgetMonthlyCents === "number") {
patch.budgetMonthlyCents = payload.budgetMonthlyCents;
}
if (Object.prototype.hasOwnProperty.call(payload, "metadata")) {
patch.metadata = isPlainRecord(payload.metadata) ? payload.metadata : null;
}
if (isPlainRecord(payload.permissions)) {
patch.permissions = payload.permissions;
}
return patch;
}
function parseFiniteNumberLike(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value !== "string") return null;
const parsed = Number(value.trim());
return Number.isFinite(parsed) ? parsed : null;
}
export function normalizeRuntimeConfigForNewAgent(runtimeConfig: unknown): Record<string, unknown> {
const normalizedRuntimeConfig = isPlainRecord(runtimeConfig) ? { ...runtimeConfig } : {};
const heartbeat = isPlainRecord(normalizedRuntimeConfig.heartbeat)
? { ...normalizedRuntimeConfig.heartbeat }
: {};
if (parseFiniteNumberLike(heartbeat.maxConcurrentRuns) == null) {
heartbeat.maxConcurrentRuns = AGENT_DEFAULT_MAX_CONCURRENT_RUNS;
}
normalizedRuntimeConfig.heartbeat = heartbeat;
return normalizedRuntimeConfig;
}
export function diffConfigSnapshot(
before: AgentConfigSnapshot,
after: AgentConfigSnapshot,
): string[] {
return CONFIG_REVISION_FIELDS.filter((field) => !jsonEqual(before[field], after[field]));
}
export function configPatchFromSnapshot(snapshot: unknown): Partial<typeof agents.$inferInsert> {
if (!isPlainRecord(snapshot)) throw unprocessable("Invalid revision snapshot");
if (typeof snapshot.name !== "string" || snapshot.name.length === 0) {
throw unprocessable("Invalid revision snapshot: name");
}
if (typeof snapshot.role !== "string" || snapshot.role.length === 0) {
throw unprocessable("Invalid revision snapshot: role");
}
if (typeof snapshot.adapterType !== "string" || snapshot.adapterType.length === 0) {
throw unprocessable("Invalid revision snapshot: adapterType");
}
if (typeof snapshot.budgetMonthlyCents !== "number" || !Number.isFinite(snapshot.budgetMonthlyCents)) {
throw unprocessable("Invalid revision snapshot: budgetMonthlyCents");
}
const runtimeConfig = agentRuntimeConfigSchema.safeParse(
isPlainRecord(snapshot.runtimeConfig) ? snapshot.runtimeConfig : {},
);
if (!runtimeConfig.success) {
throw unprocessable("Invalid revision snapshot: runtimeConfig");
}
return {
name: snapshot.name,
role: snapshot.role,
title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null,
reportsTo:
typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null,
capabilities:
typeof snapshot.capabilities === "string" || snapshot.capabilities === null
? snapshot.capabilities
: null,
adapterType: snapshot.adapterType,
adapterConfig: isPlainRecord(snapshot.adapterConfig) ? snapshot.adapterConfig : {},
runtimeConfig: runtimeConfig.data,
defaultEnvironmentId:
typeof snapshot.defaultEnvironmentId === "string" || snapshot.defaultEnvironmentId === null
? snapshot.defaultEnvironmentId
: null,
budgetMonthlyCents: Math.max(0, Math.floor(snapshot.budgetMonthlyCents)),
metadata: isPlainRecord(snapshot.metadata) || snapshot.metadata === null ? snapshot.metadata : null,
};
}
export function hasAgentShortnameCollision(
candidateName: string,
existingAgents: AgentShortnameRow[],
options?: AgentShortnameCollisionOptions,
): boolean {
const candidateShortname = normalizeAgentUrlKey(candidateName);
if (!candidateShortname) return false;
return existingAgents.some((agent) => {
if (agent.status === "terminated") return false;
if (options?.excludeAgentId && agent.id === options.excludeAgentId) return false;
return normalizeAgentUrlKey(agent.name) === candidateShortname;
});
}
export function deduplicateAgentName(
candidateName: string,
existingAgents: AgentShortnameRow[],
): string {
if (!hasAgentShortnameCollision(candidateName, existingAgents)) {
return candidateName;
}
for (let i = 2; i <= 100; i++) {
const suffixed = `${candidateName} ${i}`;
if (!hasAgentShortnameCollision(suffixed, existingAgents)) {
return suffixed;
}
}
return `${candidateName} ${Date.now()}`;
}
export function agentRecordQueries(db: Db) {
function currentUtcMonthWindow(now = new Date()) {
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
return {
start: new Date(Date.UTC(year, month, 1, 0, 0, 0, 0)),
end: new Date(Date.UTC(year, month + 1, 1, 0, 0, 0, 0)),
};
}
function withUrlKey<T extends { id: string; name: string }>(row: T) {
return {
...row,
urlKey: normalizeAgentUrlKey(row.name) ?? row.id,
};
}
function normalizeAgentBaseRow(row: typeof agents.$inferSelect) {
const { lifecycleOperation, lifecycleRequiredPluginIds, ...publicRow } = row;
return withUrlKey({
...publicRow,
permissions: normalizeAgentPermissions(row.permissions),
});
}
function toEligibilityAgent(row: Pick<typeof agents.$inferSelect, "id" | "companyId" | "name" | "status" | "reportsTo">): AgentEligibilityAgent {
return {
id: row.id,
companyId: row.companyId,
name: row.name,
status: row.status,
reportsTo: row.reportsTo,
};
}
function normalizeAgentRows(rows: (typeof agents.$inferSelect)[], allCompanyRows = rows) {
const eligibilityAgents = allCompanyRows.map(toEligibilityAgent);
return rows.map((row) => {
const base = normalizeAgentBaseRow(row);
const appearance = resolveAgentAppearance(row.appearance, row.id);
return {
...base,
appearance,
avatarUrl: agentAvatarUrl(appearance),
orgChainHealth: getAgentWorkEligibility({
agent: toEligibilityAgent(row),
agents: eligibilityAgents,
}).orgChainHealth,
};
});
}
function normalizeAgentRow(row: typeof agents.$inferSelect, allCompanyRows?: (typeof agents.$inferSelect)[]) {
return normalizeAgentRows([row], allCompanyRows)[0]!;
}
async function listCompanyAgentRows(companyId: string) {
return db.select().from(agents).where(eq(agents.companyId, companyId));
}
async function getMonthlySpendByAgentIds(companyId: string, agentIds: string[]) {
if (agentIds.length === 0) return new Map<string, number>();
const { start, end } = currentUtcMonthWindow();
const rows = await db
.select({
agentId: costEvents.agentId,
spentMonthlyCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::double precision`,
})
.from(costEvents)
.where(
and(
eq(costEvents.companyId, companyId),
inArray(costEvents.agentId, agentIds),
gte(costEvents.occurredAt, start),
lt(costEvents.occurredAt, end),
),
)
.groupBy(costEvents.agentId);
return new Map(rows.map((row) => [row.agentId, Number(row.spentMonthlyCents ?? 0)]));
}
async function hydrateAgentSpend<T extends { id: string; companyId: string; spentMonthlyCents: number }>(rows: T[]) {
const agentIds = rows.map((row) => row.id);
const companyId = rows[0]?.companyId;
if (!companyId || agentIds.length === 0) return rows;
const spendByAgentId = await getMonthlySpendByAgentIds(companyId, agentIds);
return rows.map((row) => ({
...row,
spentMonthlyCents: spendByAgentId.get(row.id) ?? 0,
}));
}
async function getById(id: string) {
const row = await db
.select()
.from(agents)
.where(eq(agents.id, id))
.then((rows) => rows[0] ?? null);
if (!row) return null;
const [companyRows, hydrated] = await Promise.all([
listCompanyAgentRows(row.companyId),
hydrateAgentSpend([row]).then((rows) => rows[0]!),
]);
return normalizeAgentRow(hydrated, companyRows);
}
async function ensureManager(companyId: string, managerId: string) {
const manager = await getById(managerId);
if (!manager) throw notFound("Manager not found");
if (manager.companyId !== companyId) {
throw unprocessable("Manager must belong to same company");
}
return manager;
}
async function assertNoCycle(agentId: string, reportsTo: string | null | undefined) {
if (!reportsTo) return;
if (reportsTo === agentId) throw unprocessable("Agent cannot report to itself");
let cursor: string | null = reportsTo;
while (cursor) {
if (cursor === agentId) throw unprocessable("Reporting relationship would create cycle");
const next = await getById(cursor);
cursor = next?.reportsTo ?? null;
}
}
async function assertCompanyShortnameAvailable(
companyId: string,
candidateName: string,
options?: AgentShortnameCollisionOptions,
) {
const candidateShortname = normalizeAgentUrlKey(candidateName);
if (!candidateShortname) return;
const existingAgents = await db
.select({
id: agents.id,
name: agents.name,
status: agents.status,
})
.from(agents)
.where(eq(agents.companyId, companyId));
const hasCollision = hasAgentShortnameCollision(candidateName, existingAgents, options);
if (hasCollision) {
throw conflict(
`Agent shortname '${candidateShortname}' is already in use in this company`,
);
}
}
function assertBuiltInAgentMetadataMutationAllowed(
beforeMetadata: unknown,
afterMetadata: unknown,
options?: { allowBuiltInAgentMetadata?: boolean },
) {
if (options?.allowBuiltInAgentMetadata) return;
const beforeMarker = readBuiltInAgentMarker(beforeMetadata);
const afterMarker = readBuiltInAgentMarker(afterMetadata);
if (builtInAgentMarkersEqual(beforeMarker, afterMarker)) return;
throw conflict("Built-in agent marker is managed by Paperclip and cannot be edited directly", {
code: "built_in_agent_marker_readonly",
key: beforeMarker?.key ?? afterMarker?.key ?? null,
});
}
return { normalizeAgentRows, normalizeAgentRow, listCompanyAgentRows, hydrateAgentSpend,
getById, ensureManager, assertNoCycle, assertCompanyShortnameAvailable, assertBuiltInAgentMetadataMutationAllowed };
}
+68
View File
@@ -0,0 +1,68 @@
import { and, eq, inArray } from "drizzle-orm";
import { approvals, type Db } from "@paperclipai/db";
import { notFound, unprocessable } from "../errors.js";
export const resolvableApprovalStatuses = ["pending", "revision_requested"];
export function approvalResolutionRecords(db: Db) {
const canResolveStatuses = new Set(resolvableApprovalStatuses);
const resolvableStatuses = resolvableApprovalStatuses;
type ApprovalRecord = typeof approvals.$inferSelect;
type ResolutionResult = { approval: ApprovalRecord; applied: boolean };
async function getExistingApproval(id: string, database: Db = db) {
const existing = await database
.select()
.from(approvals)
.where(eq(approvals.id, id))
.then((rows) => rows[0] ?? null);
if (!existing) throw notFound("Approval not found");
return existing;
}
async function resolveApproval(
id: string,
targetStatus: "approved" | "rejected",
decidedByUserId: string,
decisionNote: string | null | undefined,
database: Db = db,
): Promise<ResolutionResult> {
const existing = await getExistingApproval(id, database);
if (!canResolveStatuses.has(existing.status)) {
if (existing.status === targetStatus) {
return { approval: existing, applied: false };
}
throw unprocessable(
`Only pending or revision requested approvals can be ${targetStatus === "approved" ? "approved" : "rejected"}`,
);
}
const now = new Date();
const updated = await database
.update(approvals)
.set({
status: targetStatus,
decidedByUserId,
decisionNote: decisionNote ?? null,
decidedAt: now,
updatedAt: now,
})
.where(and(eq(approvals.id, id), inArray(approvals.status, resolvableStatuses)))
.returning()
.then((rows) => rows[0] ?? null);
if (updated) {
return { approval: updated, applied: true };
}
const latest = await getExistingApproval(id, database);
if (latest.status === targetStatus) {
return { approval: latest, applied: false };
}
throw unprocessable(
`Only pending or revision requested approvals can be ${targetStatus === "approved" ? "approved" : "rejected"}`,
);
}
return { getExistingApproval, resolveApproval };
}
+9
View File
@@ -0,0 +1,9 @@
import type { Db } from "@paperclipai/db";
type CompanyDeletionTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
export interface CompanyDeletionParticipant {
// The caller holds the company lock and removes dependent records first.
// Use this transaction only. Throw on failure. Do not call external systems.
deleteCompanyData(tx: CompanyDeletionTransaction, companyId: string): Promise<void>;
}
+2
View File
@@ -1,3 +1,4 @@
import { AgentLifecycleConflict } from "../modules/agent-lifecycle/index.js";
import type { Request, Response, NextFunction } from "express";
import type { Db } from "@paperclipai/db";
import { ZodError } from "zod";
@@ -129,6 +130,7 @@ export function errorHandler(
res: Response,
_next: NextFunction,
) {
if (err instanceof AgentLifecycleConflict) { res.status(409).json({ error: err.message }); return; }
if (err instanceof HttpError) {
const details =
err.details &&
+30 -3
View File
@@ -22,10 +22,37 @@ adapters → application → domain
Postgres queries, transactions, and process control. An adapter file may
import `drizzle-orm`, `@paperclipai/db`, and Node.js I/O modules.
A module exposes one entry point, `index.ts`, which composes the adapters
A module exposes its commands through `index.ts`, which composes the adapters
and the use cases behind a factory function. Code outside the module imports
only that entry point, never a file inside `domain/`, `application/`, or
that entry point, never a file inside `domain/`, `application/`, or
`adapters/` directly.
`pnpm check:module-boundaries` enforces these rules for production source
files. It also rejects imports that bypass another module's `index.ts`.
files. It also checks access to the company deletion entry point below.
## Company deletion
The existing company deletion service owns the database transaction and deletion
order. A module can expose a separate `company-deletion.ts` entry point.
Only `services/company-deletion.ts` can import this entry point.
The entry point exports an implementation of `CompanyDeletionParticipant` from
`lib/company-deletion.ts`. Do not export it through the normal module index.
The service must complete external cleanup before it starts the transaction.
It must lock the company before it deletes dependent records or calls a module.
Creation commands must use the same company lock.
The service removes dependent records before it calls the module.
The module checks its deletion conditions and deletes the records it owns.
Use the supplied transaction. Do not start another transaction or call external
systems. Throw an error if deletion cannot proceed.
An error must roll back all database changes in the deletion transaction.
Call each module explicitly in dependency order. No module registry is required.
The agent lifecycle module also has a restricted `configuration.ts` entry point.
It saves configuration and invalidates verification in the caller's transaction.
The [lifecycle guide](../../../doc/AGENT-LIFECYCLE.md) lists its permitted callers.
Ordinary configuration updates use the root lifecycle command.
The [agent lifecycle module](../../../doc/AGENT-LIFECYCLE.md) owns agent creation,
pause, resume, and termination. Use its commands for these changes.
@@ -456,6 +456,7 @@ export function createPostgresWatchdogAdapter(db: Db): WatchdogRunReader & Watch
eq(agents.id, input.run.agentId),
eq(agents.companyId, companyId),
notInArray(agents.status, ["paused", "terminated"]),
eq(agents.lifecycleState, "ready"),
));
return updatedRun;
@@ -0,0 +1,68 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { createLifecycleWorker } from "../application/worker.js";
import type { LifecycleAgent, LifecycleStore, LifecycleDriver } from "../application/ports.js";
import { startAgentLifecycle } from "../index.js";
import { createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
import { logger } from "../../../middleware/logger.js";
const agent: LifecycleAgent = { id: "agent", companyId: "company", lifecycleState: "verifying", lifecycleVersion: 3,
lifecycleRequiredPluginIds: null, lifecycleError: null,
lifecycleOperation: { id: "operation", hostComplete: false, completedPluginIds: [], attempts: 1 } };
function fixture() {
const store = { get: vi.fn(), claim: vi.fn().mockResolvedValue(agent), renew: vi.fn().mockResolvedValue(true),
setRequiredPlugins: vi.fn().mockResolvedValue(true), completeHost: vi.fn().mockResolvedValue(true),
completePlugin: vi.fn().mockResolvedValue(true), defer: vi.fn().mockResolvedValue(true),
change: vi.fn().mockResolvedValue({ ...agent, lifecycleState: "ready" }), pending: vi.fn().mockResolvedValue([agent.id]) } satisfies LifecycleStore;
const driver = { requiredPluginIds: vi.fn().mockResolvedValue(["plugin"]), runHost: vi.fn().mockResolvedValue("complete"),
runPlugin: vi.fn().mockResolvedValue("complete") } satisfies LifecycleDriver;
const report = vi.fn();
return { store, driver, report, worker: createLifecycleWorker(store, driver, report) };
}
afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });
describe("lifecycle failure diagnostics", () => {
it.each(["host", "plugin", "claim", "renew", "scan", "defer"] as const)("reports %s failures with the available context", async stage => {
const { store, driver, report, worker } = fixture();
const error = new Error("private provider detail");
if (stage === "host") driver.runHost.mockRejectedValue(error);
else if (stage === "plugin") driver.runPlugin.mockRejectedValue(error);
else if (stage === "scan") store.pending.mockRejectedValue(error);
else if (stage === "defer") { driver.runHost.mockResolvedValue("pending"); store.defer.mockRejectedValue(error); }
else store[stage].mockRejectedValue(error);
const work = stage === "scan" ? worker.sweep() : worker.process(agent.id);
if (["claim", "scan", "defer"].includes(stage)) await expect(work).rejects.toThrow(error);
else await work;
expect(report).toHaveBeenCalledWith(expect.objectContaining({ stage }), error);
if (!["claim", "scan"].includes(stage)) expect(report).toHaveBeenCalledWith(expect.objectContaining({
agentId: agent.id, companyId: agent.companyId, phase: "verifying", operationId: "operation", version: 3,
...(stage === "plugin" ? { pluginId: "plugin" } : {}),
}), error);
await worker.stop();
});
it("reports periodic policy scan failures", async () => {
vi.useFakeTimers();
const error = new Error("private database detail");
const db = { select: () => { throw error; } } as unknown as Db;
const effects = { ...createAgentLifecycleEffects(), reportFailure: vi.fn() };
const work = startAgentLifecycle(db, effects, fixture().driver, () => true);
try {
await vi.advanceTimersByTimeAsync(5_000);
expect(effects.reportFailure).toHaveBeenCalledWith({ stage: "policy_scan" }, error);
} finally { await work.stop(); }
});
it.each([
[{ code: "required_plugin_unavailable" }, "required_plugin_unavailable"],
[{ code: "harness_test_failed" }, "harness_test_failed"],
[{ cause: { code: "40P01", message: "private query" } }, "40P01"],
[{ code: "private credential value" }, "unclassified"],
])("logs known codes without provider error contents", (details, failureCode) => {
const log = vi.spyOn(logger, "warn").mockImplementation(() => {});
const context = { stage: "host" as const, agentId: "agent", phase: "verifying" as const, operationId: "operation", version: 3 };
createAgentLifecycleEffects().reportFailure(context, Object.assign(new Error("private provider detail"), details));
expect(log).toHaveBeenCalledExactlyOnceWith({ ...context, failureCode }, "Agent lifecycle operation failed");
expect(JSON.stringify(log.mock.calls)).not.toContain("private");
});
});
@@ -0,0 +1,673 @@
import { createAgentLifecycle as createLifecycleCommands } from "../index.js";
import { createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
import { deleteCompany } from "../../../services/company-deletion.js";
import { agentLifecycleCompanyDeletion } from "../company-deletion.js";
import { requireServerAdapter } from "../../../adapters/index.js";
import { agentExecutionsHaveStopped } from "../../../services/agent-execution-stop.js";
import { remoteTerminationReceipt } from "../../../services/remote-execution-termination.js";
import { approvalService } from "../../../services/approvals.js";
import { updateAgentConfigurationInTransaction } from "../../../services/agent-configuration-transaction.js";
import { agentService as agentConfiguration } from "../../../services/agents.js";
import { readFileSync } from "node:fs";
import express from "express";
import request from "supertest";
import { agentRoutes } from "../../../routes/agents.js";
import { errorHandler } from "../../../middleware/error-handler.js";
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { agents, approvals, projects, issues, heartbeatRuns, nativeRunFinalizations, budgetPolicies, environmentLeases, agentApiKeys, activityLog, agentConfigRevisions, userCompanyPreferences, companies, companyMemberships, principalPermissionGrants, plugins, pluginCompanySettings, createDb, type Db } from "@paperclipai/db";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { createAgentLifecycle, configureAgentLifecycle } from "../../../services/agent-lifecycle.js";
import { createLifecycleStore as createStore } from "../adapters/postgres.js";
import { transition } from "../domain/policy.js";
import type { LifecycleAgent } from "../application/ports.js";
import { budgetService } from "../../../services/budgets.js";
const createLifecycleStore = (db: Db) => createStore(db, createAgentLifecycleEffects());
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("agent lifecycle commands", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let companyId: string;
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-agent-lifecycle-"); db = createDb(database.connectionString); }, 90_000);
afterAll(async () => { for (const worker of workers) await worker.stop(); await database?.cleanup(); });
beforeEach(async () => {
for (const work of workers) await work.stop();
companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Lifecycle test", issuePrefix: `L${companyId.slice(0, 7)}` });
});
function worker(runHost: (agent: LifecycleAgent) => Promise<"complete" | "pending"> = async () => "complete") {
const value = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost });
workers.push(value); return value;
}
async function hire(status = "idle") { return createAgentLifecycle(db).requestHire(companyId, { name: "Agent", status, adapterType: "process" }); }
async function current(id: string) { return (await db.select().from(agents).where(eq(agents.id, id)))[0]!; }
it("maps existing states without starting setup or clearing pause reasons", async () => {
const rows = await db.insert(agents).values(["idle", "running", "error", "paused", "pending_approval", "terminated"].map(status => ({
companyId, name: status, status, pauseReason: status === "paused" ? "budget" : null,
}))).returning();
const migration = readFileSync(new URL("../../../../../packages/db/src/migrations/0320_daily_onslaught.sql", import.meta.url), "utf8");
await db.execute(sql.raw(migration.slice(migration.indexOf('UPDATE "agents"'))));
for (const row of rows) {
const mapped = await current(row.id);
expect(mapped.lifecycleState).toBe(["paused", "pending_approval", "terminated"].includes(row.status) ? row.status : "ready");
expect(mapped.lifecycleOperation).toBeNull();
expect(mapped.lifecycleRequiredPluginIds).toBeNull();
expect(mapped.lifecycleHolds).toEqual(row.status === "paused" ? ["budget"] : []);
}
});
it("commits the record before preparation and verifies before admission", async () => {
const observed: string[] = [];
const work = worker(async agent => {
expect((await current(agent.id)).lifecycleState).toBe(agent.lifecycleState);
observed.push(agent.lifecycleState); return "complete";
});
const agent = await hire();
expect(agent).toMatchObject({ lifecycleState: "preparing", status: "paused" });
await work.process(agent.id);
expect(observed).toEqual(["preparing", "verifying"]);
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle" });
expect(agent).not.toHaveProperty("lifecycleOperation");
});
it("rolls back a hire and its grants when hire initialization fails", async () => {
const effects = createAgentLifecycleEffects();
const lifecycle = createLifecycleCommands(db, { ...effects,
initializeHire: async (tx, agent, options) => {
await effects.initializeHire(tx, agent, options);
throw new Error("Hire initialization failed");
},
});
await expect(lifecycle.requestHire(companyId, { name: "Rollback hire", adapterType: "process" }))
.rejects.toThrow("Hire initialization failed");
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId))).toHaveLength(0);
});
it("runs the saved harness test and keeps a failed configuration out of ready", async () => {
const driver = createLifecycleDriver(db, {} as never);
const work = worker(driver.runHost);
const agent = await hire();
await work.process(agent.id);
expect(await current(agent.id)).toMatchObject({ lifecycleState: "verifying", status: "paused" });
await agentConfiguration(db).update(agent.id, { adapterConfig: { command: process.execPath } });
await work.process(agent.id);
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle", lifecycleError: null });
});
it.each(["claude_local", "gemini_local"])("keeps %s authentication warnings out of ready", async adapterType => {
const adapter = requireServerAdapter(adapterType);
const probe = vi.spyOn(adapter, "testEnvironment").mockResolvedValue({ adapterType, status: "warn",
testedAt: new Date().toISOString(), checks: [{ code: `${adapterType.split("_")[0]}_hello_probe_auth_required`, level: "warn", message: "Login required" }] });
try {
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Login test", adapterType });
const work = worker(createLifecycleDriver(db, {} as never).runHost);
await work.process(agent.id);
expect(probe).toHaveBeenCalled();
expect(await current(agent.id)).toMatchObject({ lifecycleState: "verifying", lifecycleError: "The lifecycle step failed. Retry the operation." });
} finally { probe.mockRestore(); }
});
it("recovers an expired native owner only after the cancelled run and controller stop", async () => {
const agent = await hire();
const [issue] = await db.insert(issues).values({ companyId, title: "Cancelled native run" }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, nativeIssueId: issue.id,
status: "cancelled", invocationSource: "on_demand", runtimeMode: "native",
startedAt: new Date(), finishedAt: new Date(), processPid: process.pid }).returning();
await db.insert(nativeRunFinalizations).values({ companyId, issueId: issue.id, runId: run.id,
phase: "executing", leaseOwner: "stopped-server", leaseExpiresAt: new Date(0), controllerPid: process.pid });
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(false);
await db.update(nativeRunFinalizations).set({ controllerPid: null }).where(eq(nativeRunFinalizations.runId, run.id));
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(false);
await db.update(heartbeatRuns).set({ processPid: 2_000_000_000 }).where(eq(heartbeatRuns.id, run.id));
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, run.id));
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(false);
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(0) }).where(eq(nativeRunFinalizations.runId, run.id));
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(true);
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id)))[0]).toMatchObject({ leaseOwner: null, leaseExpiresAt: null });
});
it("does not advance termination while a cancelled process still runs", async () => {
const agent = await hire();
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id,
status: "cancelled", invocationSource: "on_demand", runtimeMode: "legacy",
startedAt: new Date(), finishedAt: new Date(), processPid: process.pid }).returning();
const driver = createLifecycleDriver(db, {} as never);
const work = worker(driver.runHost);
await createAgentLifecycle(db).terminateAgent(agent.id);
await work.process(agent.id);
expect((await current(agent.id)).lifecycleState).toBe("terminating");
await db.update(heartbeatRuns).set({ processPid: null,
resultJson: { executionCancellation: { state: "acknowledged" } } }).where(eq(heartbeatRuns.id, run.id));
await createAgentLifecycle(db).retry(agent.id);
await work.process(agent.id);
expect((await current(agent.id)).lifecycleState).toBe("terminated");
});
it("does not cancel a reporting agent when its manager pauses", async () => {
const parent = await hire();
const [child] = await db.insert(agents).values({ companyId, name: "Report", reportsTo: parent.id,
status: "idle", lifecycleState: "ready" }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: child.id,
status: "queued", invocationSource: "on_demand" }).returning();
const work = worker(createLifecycleDriver(db, {} as never).runHost);
await createAgentLifecycle(db).pauseAgent(parent.id);
await work.process(parent.id);
expect((await current(parent.id)).lifecycleState).toBe("paused");
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]!.status).toBe("queued");
});
it("retains company data until every agent finishes termination", async () => {
const agent = await hire();
const [project] = await db.insert(projects).values({ companyId, name: "Keep until cleanup", leadAgentId: agent.id }).returning();
await db.insert(issues).values({ companyId, projectId: project.id, title: "Keep this task", assigneeAgentId: agent.id });
const pending = worker(async () => "pending");
await expect(deleteCompany(db, companyId)).rejects.toThrow("Complete termination");
expect(await db.select().from(projects).where(eq(projects.id, project.id))).toHaveLength(1);
expect(await db.select().from(issues).where(eq(issues.companyId, companyId))).toHaveLength(1);
await pending.stop();
const complete = worker();
await createAgentLifecycle(db).retry(agent.id);
await complete.process(agent.id);
await deleteCompany(db, companyId);
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
expect(await db.select().from(companies).where(eq(companies.id, companyId))).toHaveLength(0);
});
it("requires a transaction for the company deletion integration", async () => {
await expect(agentLifecycleCompanyDeletion.deleteCompanyData(db as never, companyId))
.rejects.toThrow("Company deletion requires a database transaction");
});
it("rejects individual deletion before cleanup and rolls back failed cleanup", async () => {
const agent = await hire();
const effects = createAgentLifecycleEffects();
const cleanup = vi.fn(effects.deleteDependencies);
const lifecycle = createLifecycleCommands(db, { ...effects, deleteDependencies: cleanup });
await expect(lifecycle.purgeAgent(agent.id)).rejects.toThrow("Complete termination");
expect(cleanup).not.toHaveBeenCalled();
await db.update(agents).set({ lifecycleState: "terminated", status: "terminated" }).where(eq(agents.id, agent.id));
const [key] = await db.insert(agentApiKeys).values({ companyId, agentId: agent.id, name: "Keep on rollback", keyHash: randomUUID() }).returning();
cleanup.mockImplementation(async (tx, companyId, id) => {
await effects.deleteDependencies(tx, companyId, id);
throw new Error("Dependency cleanup failed");
});
await expect(lifecycle.purgeAgent(agent.id)).rejects.toThrow("Dependency cleanup failed");
expect(await current(agent.id)).toMatchObject({ lifecycleState: "terminated" });
expect(await db.select().from(agentApiKeys).where(eq(agentApiKeys.id, key.id))).toHaveLength(1);
});
it("deletes terminated and rejected agents only in the requested company", async () => {
await db.insert(agents).values((["terminated", "rejected"] as const).map(lifecycleState => ({
companyId, name: lifecycleState, status: "terminated", lifecycleState,
})));
const [otherCompany] = await db.insert(companies).values({ name: "Keep this company", issuePrefix: `K${companyId.slice(0, 7)}` }).returning();
const [otherAgent] = await db.insert(agents).values({ companyId: otherCompany.id, name: "Keep this agent",
status: "terminated", lifecycleState: "terminated" }).returning();
await deleteCompany(db, companyId);
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
expect(await current(otherAgent.id)).toMatchObject({ companyId: otherCompany.id });
expect(await db.select().from(companies).where(eq(companies.id, otherCompany.id))).toHaveLength(1);
});
it("rolls back agent and company data deletion when a later operation fails", async () => {
const agent = await hire("terminated");
const [project] = await db.insert(projects).values({ companyId, name: "Keep on rollback" }).returning();
const removeAgents = agentLifecycleCompanyDeletion.deleteCompanyData;
const failure = vi.spyOn(agentLifecycleCompanyDeletion, "deleteCompanyData").mockImplementation(async (tx, id) => {
await removeAgents(tx, id);
expect(await tx.select().from(agents).where(eq(agents.companyId, id))).toHaveLength(0);
throw new Error("Later deletion failed");
});
try {
await expect(deleteCompany(db, companyId)).rejects.toThrow("Later deletion failed");
expect(await current(agent.id)).toMatchObject({ lifecycleState: "terminated" });
expect(await db.select().from(projects).where(eq(projects.id, project.id))).toHaveLength(1);
expect(await db.select().from(companies).where(eq(companies.id, companyId))).toHaveLength(1);
} finally { failure.mockRestore(); }
});
it("blocks a concurrent hire until company deletion commits", async () => {
let reportLock!: (pid: number) => void;
let rejectLock!: (error: unknown) => void;
const locked = new Promise<number>((resolve, reject) => { reportLock = resolve; rejectLock = reject; });
let release!: () => void;
const released = new Promise<void>(resolve => { release = resolve; });
const removeAgents = agentLifecycleCompanyDeletion.deleteCompanyData;
const pause = vi.spyOn(agentLifecycleCompanyDeletion, "deleteCompanyData").mockImplementation(async (tx, id) => {
const [backend] = await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`);
reportLock(backend!.pid);
await released;
await removeAgents(tx, id);
});
const deletion = deleteCompany(db, companyId);
void deletion.catch(rejectLock);
let hiring: Promise<unknown> | undefined;
try {
const pid = await locked;
hiring = hire().then(() => "created", error => error.message);
await vi.waitFor(async () => {
const blocked = await db.execute(sql`select 1 from pg_stat_activity
where datname = current_database() and ${pid} = any(pg_blocking_pids(pid))`);
expect(blocked).toHaveLength(1);
});
release();
await deletion;
expect(await hiring).toBe("Company not found");
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(0);
} finally {
release();
await Promise.allSettled([deletion, hiring]);
pause.mockRestore();
}
});
it("requires cleanup proof after a remote run is already cancelled", async () => {
const agent = await hire();
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id,
status: "cancelled", invocationSource: "on_demand", runtimeMode: "native",
startedAt: new Date(), finishedAt: new Date() }).returning();
const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: run.id,
provider: "test", providerLeaseId: "test-lease", status: "pending_cleanup",
cleanupStatus: "failed", releasedAt: new Date() }).returning();
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(false);
await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success" })
.where(eq(environmentLeases.id, lease.id));
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(false);
await db.update(environmentLeases).set({ metadata: {
remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "destroyed" }),
} }).where(eq(environmentLeases.id, lease.id));
expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(true);
});
it("does not prepare a proposed hire until approval", async () => {
const observed: string[] = [];
const work = worker(async agent => { observed.push(agent.lifecycleState); return "complete"; });
const agent = await hire("pending_approval");
await work.process(agent.id);
expect(observed).toEqual([]);
const approval = await approvalService(db).create(companyId, { type: "hire_agent", payload: { agentId: agent.id }, status: "pending" });
await approvalService(db).approve(approval.id, "board");
await vi.waitFor(async () => expect((await current(agent.id)).lifecycleState).toBe("ready"));
expect(observed).toEqual(["preparing", "verifying"]);
});
it.each(["approved", "rejected"] as const)("uses the same %s hire decision for an agent and its approval", async decision => {
const agent = await hire("pending_approval");
const approval = await approvalService(db).create(companyId, { type: "hire_agent",
requestedByUserId: "requester", payload: { agentId: agent.id }, status: "pending" });
const lifecycle = createAgentLifecycle(db);
const decide = decision === "approved" ? lifecycle.approveHire : lifecycle.rejectHire;
const first = await decide(agent.id, "board");
expect(first).toMatchObject({ applied: true, approval: { id: approval.id, status: decision },
agent: { lifecycleState: decision === "approved" ? "preparing" : "rejected" } });
const version = (await current(agent.id)).lifecycleVersion;
expect(await decide({ approvalId: approval.id }, "board")).toMatchObject({ applied: false, hireApprovedAgentId: null });
expect((await current(agent.id)).lifecycleVersion).toBe(version);
});
it("rolls back the approval and agent together when activation fails", async () => {
const agent = await hire("pending_approval");
const approval = await approvalService(db).create(companyId, { type: "hire_agent",
payload: { agentId: agent.id }, status: "pending" });
const lifecycle = createLifecycleCommands(db, { ...createAgentLifecycleEffects(),
recordCreation: async () => { throw new Error("Creation event failed"); } });
await expect(lifecycle.approveHire(agent.id, "board")).rejects.toThrow("Creation event failed");
expect((await current(agent.id)).lifecycleState).toBe("pending_approval");
expect((await db.select().from(approvals).where(eq(approvals.id, approval.id)))[0].status).toBe("pending");
});
it("keeps the hire credential owner and recovers it for migrated approvals", async () => {
for (const savedOwner of [null, "original-owner"]) {
const [agent] = await db.insert(agents).values({ companyId, name: "Migrated hire", status: "pending_approval",
lifecycleState: "pending_approval", lifecycleOperation: savedOwner ? {
id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, responsibleUserId: savedOwner,
} : null }).returning();
const approval = await approvalService(db).create(companyId, { type: "hire_agent",
requestedByUserId: "requesting-member", payload: { agentId: agent.id }, status: "pending" });
await approvalService(db).approve(approval.id, "approving-member");
expect((await current(agent.id)).lifecycleOperation?.responsibleUserId).toBe(savedOwner ?? "requesting-member");
}
});
it("rejects transaction injection and generic state writes", async () => {
const agent = await hire("pending_approval");
await expect(db.transaction(async tx => createAgentLifecycle(tx as unknown as Db))).rejects.toThrow("root database");
await expect(agentConfiguration(db).update(agent.id, { status: "idle" } as never)).rejects.toThrow("lifecycle command");
await expect(createAgentLifecycle(db).requestHire(companyId, { name: "Bypass", lifecycleRequiredPluginIds: [] } as never)).rejects.toThrow("Lifecycle fields");
});
it("clears a rejected hire from the user's primary selection", async () => {
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Proposed", status: "pending_approval" }, { createdByUserId: "board" });
const preference = () => db.select().from(userCompanyPreferences).where(eq(userCompanyPreferences.companyId, companyId));
expect((await preference())[0]!.primaryAgentId).toBe(agent.id);
const approval = await approvalService(db).create(companyId, { type: "hire_agent", payload: { agentId: agent.id }, status: "pending" });
await approvalService(db).reject(approval.id, "board");
expect((await preference())[0]!.primaryAgentId).toBeNull();
expect((await current(agent.id)).lifecycleState).toBe("rejected");
});
it("rolls back configuration and its revision when the requested transition fails", async () => {
const lifecycle = createAgentLifecycle(db);
const agent = await hire("terminated");
await expect(lifecycle.updateAndTransition(agent.id, "resume", { name: "Must not persist" },
{ recordRevision: { createdByUserId: "board", source: "patch" } })).rejects.toThrow("Cannot resume");
expect((await current(agent.id)).name).toBe("Agent");
expect(await db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, agent.id))).toEqual([]);
const active = await hire();
expect(await lifecycle.updateAndTransition(active.id, "pause", { name: "Paused agent" })).toMatchObject({ name: "Paused agent", lifecycleState: "pausing" });
});
it("preserves a disabled positive budget at approval and applies explicit configuration changes", async () => {
const agent = await hire("pending_approval");
const budgets = budgetService(db);
await budgets.upsertPolicy(companyId, { scopeType: "agent", scopeId: agent.id, amount: 1000, isActive: false }, null);
const approval = await approvalService(db).create(companyId, { type: "hire_agent",
payload: { agentId: agent.id, budgetMonthlyCents: 1000 }, status: "pending" });
const policy = async () => (await db.select().from(budgetPolicies).where(eq(budgetPolicies.scopeId, agent.id)))[0]!;
await approvalService(db).approve(approval.id, "board");
expect(await policy()).toMatchObject({ amount: 1000, isActive: false });
await agentConfiguration(db).update(agent.id, { budgetMonthlyCents: 2000 });
expect(await policy()).toMatchObject({ amount: 2000, isActive: true });
await agentConfiguration(db).update(agent.id, { budgetMonthlyCents: 0 });
expect(await policy()).toMatchObject({ amount: 0, isActive: false });
});
it.each(["updateConfiguration", "updateAndTransition"] as const)("limits %s budget reconciliation to the edited agent", async command => {
const lifecycle = createAgentLifecycle(db);
const one = await hire();
const two = await lifecycle.requestHire(companyId, { name: "Other budget target" });
await db.update(companies).set({ status: "paused" }).where(eq(companies.id, companyId));
if (command === "updateConfiguration") await lifecycle.updateConfiguration(one.id, { budgetMonthlyCents: 1000 });
else await lifecycle.updateAndTransition(one.id, "pause", { budgetMonthlyCents: 1000 });
expect((await current(one.id)).lifecycleHolds).toContain("company_paused");
expect((await current(two.id)).lifecycleHolds).toEqual([]);
});
it("limits invocation policy checks to the requested agent", async () => {
const one = await hire();
const two = await createAgentLifecycle(db).requestHire(companyId, { name: "Another agent" });
await db.update(companies).set({ status: "paused" }).where(eq(companies.id, companyId));
await budgetService(db).getInvocationBlock(companyId, one.id);
expect((await current(one.id)).lifecycleHolds).toContain("company_paused");
expect((await current(two.id)).lifecycleHolds).toEqual([]);
});
it("keeps a manual hold when company policy changes", async () => {
const work = worker(); const lifecycle = createAgentLifecycle(db); const agent = await hire(); await work.process(agent.id);
await lifecycle.pauseAgent(agent.id); await work.process(agent.id);
await db.update(companies).set({ status: "archived" }).where(eq(companies.id, companyId));
await createAgentLifecycle(db).reconcilePolicyHolds(companyId); await work.process(agent.id);
await db.update(companies).set({ status: "active" }).where(eq(companies.id, companyId));
await createAgentLifecycle(db).reconcilePolicyHolds(companyId); await work.process(agent.id);
expect(await current(agent.id)).toMatchObject({ lifecycleState: "paused", lifecycleHolds: ["manual"] });
await lifecycle.resumeAgent(agent.id); await work.process(agent.id);
expect((await current(agent.id)).lifecycleState).toBe("ready");
});
it("defers automatic policy changes while a task holds the agent lock", async () => {
const agent = await hire("paused");
await db.transaction(async tx => {
await tx.select().from(agents).where(eq(agents.id, agent.id)).for("update");
expect(await createLifecycleStore(db).change(agent.id, "reconcile")).toBeNull();
});
expect(await createLifecycleStore(db).change(agent.id, "reconcile")).not.toBeNull();
});
it("retains the failed phase and the same operation for retry", async () => {
let fail = true;
const work = worker(async agent => { if (agent.lifecycleState === "verifying" && fail) throw new Error("private detail"); return "complete"; });
const agent = await hire(); await work.process(agent.id);
const failed = await current(agent.id);
expect(failed.lifecycleState).toBe("verifying");
expect(failed.lifecycleError).not.toContain("private detail");
fail = false;
await createAgentLifecycle(db).retry(agent.id); await work.process(agent.id);
expect((await current(agent.id)).lifecycleState).toBe("ready");
});
it("fences a late completion when termination replaces preparation", async () => {
const agent = await hire("paused");
const store = createLifecycleStore(db);
await createAgentLifecycle(db).resumeAgent(agent.id);
const claimed = await store.claim(agent.id, "old", new Date());
expect(claimed).not.toBeNull();
await store.setRequiredPlugins(claimed!, "old", []);
await createAgentLifecycle(db).terminateAgent(agent.id);
expect(await store.completeHost(claimed!, "old")).toBe(false);
expect(await store.change(agent.id, "complete", { owner: "old", version: claimed!.lifecycleVersion })).toBeNull();
expect((await current(agent.id)).lifecycleState).toBe("terminating");
});
it("revokes keys at termination and waits for cleanup before deletion", async () => {
let pending = true;
const phases: string[] = [];
const work = worker(async agent => { phases.push(agent.lifecycleState); return agent.lifecycleState === "cleaning_up" && pending ? "pending" : "complete"; });
const lifecycle = createAgentLifecycle(db); const agent = await hire(); await work.process(agent.id);
await db.insert(agentApiKeys).values({ agentId: agent.id, companyId, name: "Test", keyHash: randomUUID() });
await lifecycle.terminateAgent(agent.id); await work.process(agent.id);
expect((await current(agent.id)).lifecycleState).toBe("cleaning_up");
expect((await db.select().from(agentApiKeys).where(eq(agentApiKeys.agentId, agent.id)))[0].revokedAt).not.toBeNull();
await expect(agentConfiguration(db).remove(agent.id)).rejects.toThrow("Complete termination");
pending = false; await lifecycle.retry(agent.id); await work.process(agent.id);
expect(phases).toContain("terminating");
expect((await current(agent.id)).lifecycleState).toBe("terminated");
await agentConfiguration(db).remove(agent.id);
expect(await current(agent.id)).toBeUndefined();
});
it("retains required plugin IDs and checks the operation and company on each reply", async () => {
const agent = await hire("paused");
const pluginId = randomUUID();
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "lifecycle-test", version: "1.0.0", status: "ready",
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage"] } as never });
const call = vi.fn(async (_id, _method, input) => ({ operationId: input.operationId, version: input.version, status: "complete" }));
const driver = createLifecycleDriver(db, { call } as never);
const snapshot = (await createLifecycleStore(db).get(agent.id))!;
expect(await driver.requiredPluginIds(snapshot)).toContain(pluginId);
await db.insert(pluginCompanySettings).values({ companyId, pluginId, enabled: false });
expect(await driver.requiredPluginIds(snapshot)).not.toContain(pluginId);
expect(await driver.requiredPluginIds({ ...snapshot, lifecycleRequiredPluginIds: [pluginId] })).toContain(pluginId);
await expect(driver.runPlugin(snapshot, pluginId)).rejects.toThrow("unavailable");
await db.update(pluginCompanySettings).set({ enabled: true }).where(eq(pluginCompanySettings.pluginId, pluginId));
expect(await driver.runPlugin(snapshot, pluginId)).toBe("complete");
expect(call).toHaveBeenCalledWith(pluginId, "agentLifecycle", { companyId, agentId: agent.id,
operationId: snapshot.lifecycleOperation!.id, version: snapshot.lifecycleVersion, phase: "paused" }, 30_000);
call.mockResolvedValueOnce({ operationId: "stale", version: snapshot.lifecycleVersion, status: "complete" });
await expect(driver.runPlugin(snapshot, pluginId)).rejects.toThrow("Invalid lifecycle result");
});
it("keeps host completion and required plugin results across a worker restart", async () => {
const pluginIds = [randomUUID(), randomUUID()];
const runHost = vi.fn(async () => "complete" as const);
const firstPlugin = vi.fn(async (_agent: LifecycleAgent, pluginId: string) =>
pluginId === pluginIds[0] ? "complete" as const : "pending" as const);
const first = configureAgentLifecycle(db, { requiredPluginIds: async () => pluginIds, runHost, runPlugin: firstPlugin });
workers.push(first);
const agent = await hire();
await first.process(agent.id);
expect(await current(agent.id)).toMatchObject({ lifecycleState: "preparing", lifecycleRequiredPluginIds: pluginIds,
lifecycleOperation: { hostComplete: true, completedPluginIds: [pluginIds[0]] } });
await first.stop();
const discover = vi.fn(async () => []);
const resumedPlugin = vi.fn(async (_agent: LifecycleAgent, _pluginId: string) => "complete" as const);
const resumed = configureAgentLifecycle(db, { requiredPluginIds: discover, runHost, runPlugin: resumedPlugin });
workers.push(resumed);
await createAgentLifecycle(db).retry(agent.id);
await resumed.process(agent.id);
expect((await current(agent.id)).lifecycleState).toBe("ready");
expect(discover).not.toHaveBeenCalled();
expect(runHost).toHaveBeenCalledTimes(2);
expect(resumedPlugin.mock.calls.map(call => call[1])).toEqual([pluginIds[1], ...pluginIds]);
});
it("requires host and plugin completion and freezes the selected plugin IDs", async () => {
const agent = await hire();
const store = createLifecycleStore(db);
const claimed = (await store.claim(agent.id, "test", new Date()))!;
const pluginId = randomUUID();
expect(await store.setRequiredPlugins(claimed, "test", [pluginId])).toBe(true);
expect(await store.setRequiredPlugins(claimed, "test", [])).toBe(false);
expect(await store.completePlugin(claimed, "test", randomUUID())).toBe(false);
const complete = () => store.change(agent.id, "complete", { owner: "test", version: claimed.lifecycleVersion });
expect(await complete()).toBeNull();
expect(await store.completePlugin(claimed, "test", pluginId)).toBe(true);
expect(await complete()).toBeNull();
expect(await store.completeHost(claimed, "test")).toBe(true);
expect(await complete()).toMatchObject({ lifecycleState: "verifying" });
expect(await store.completePlugin(claimed, "test", pluginId)).toBe(false);
});
it("fences verification when the saved configuration changes", async () => {
const lifecycle = createAgentLifecycle(db); const store = createLifecycleStore(db);
const agent = await hire();
const claimed = (await store.claim(agent.id, "configuration-test", new Date()))!;
await store.setRequiredPlugins(claimed, "configuration-test", []);
await agentConfiguration(db).update(agent.id, { adapterConfig: { command: "echo" } });
expect(await store.completeHost(claimed, "configuration-test")).toBe(false);
expect((await lifecycle.get(agent.id))!.lifecycleVersion).toBeGreaterThan(claimed.lifecycleVersion);
});
it("invalidates only changed execution configuration during setup", async () => {
const lifecycle = createAgentLifecycle(db);
const agent = await hire();
const before = await current(agent.id);
await lifecycle.updateConfiguration(agent.id, { name: "Profile only" });
await lifecycle.updateConfiguration(agent.id, { adapterConfig: before.adapterConfig });
expect((await current(agent.id)).lifecycleVersion).toBe(before.lifecycleVersion);
await lifecycle.updateConfiguration(agent.id, { runtimeConfig: { heartbeat: { enabled: false } } });
expect((await current(agent.id)).lifecycleVersion).toBe(before.lifecycleVersion + 1);
const work = worker();
await work.process(agent.id);
const ready = await current(agent.id);
expect(ready.lifecycleState).toBe("ready");
await lifecycle.updateConfiguration(agent.id, { adapterConfig: { command: "echo" } });
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", lifecycleVersion: ready.lifecycleVersion });
});
it("rejects identity, accounting, and unknown fields through every configuration entry point", async () => {
const agent = await hire();
const lifecycle = createAgentLifecycle(db);
const before = await current(agent.id);
for (const patch of [{ id: randomUUID() }, { companyId: randomUUID() }, { spentMonthlyCents: 0 },
{ spendMonthUtc: "2099-01" }, { lastHeartbeatAt: new Date() }, { errorReason: null },
{ createdAt: new Date() }, { updatedAt: new Date() }, { lifecycleState: "ready" }, { futureColumn: true }]) {
await expect(lifecycle.updateConfiguration(agent.id, patch as never)).rejects.toThrow("Unsupported configuration field");
await expect(lifecycle.updateAndTransition(agent.id, "pause", patch as never)).rejects.toThrow("Unsupported configuration field");
await expect(db.transaction(tx => updateAgentConfigurationInTransaction(tx as unknown as Db, agent.id, patch as never)))
.rejects.toThrow("Unsupported configuration field");
}
expect(await current(agent.id)).toEqual(before);
const effects = createAgentLifecycleEffects();
const malformed = createLifecycleCommands(db, { ...effects, prepareConfiguration: async () => ({ id: randomUUID() }) as never });
await expect(malformed.updateConfiguration(agent.id, { name: "Changed" })).rejects.toThrow("Unsupported configuration field");
expect(await current(agent.id)).toEqual(before);
});
it("records only the changed configuration fields for a legacy appearance", async () => {
const [agent] = await db.insert(agents).values({ companyId, name: "Legacy", appearance: null }).returning();
await createAgentLifecycle(db).updateConfiguration(agent.id, { name: "Renamed" },
{ recordRevision: { source: "test", createdByUserId: "board" } });
const revisions = await db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, agent.id));
expect(revisions).toHaveLength(1);
expect(revisions[0].changedKeys).toEqual(["name"]);
expect(revisions[0].beforeConfig.appearance).toEqual(revisions[0].afterConfig.appearance);
});
it("accepts the unchanged resolved appearance of a pending hire", async () => {
const [agent] = await db.insert(agents).values({ companyId, name: "Pending legacy", status: "pending_approval", appearance: null }).returning();
const resolved = await agentConfiguration(db).getById(agent.id);
await expect(createAgentLifecycle(db).updateConfiguration(agent.id, { appearance: resolved!.appearance }))
.resolves.toMatchObject({ id: agent.id });
await expect(createAgentLifecycle(db).updateConfiguration(agent.id, { name: "Changed" }))
.rejects.toThrow("Pending approval agent configuration cannot be changed");
});
it("rolls back a root configuration command when dependent records fail", async () => {
const agent = await hire();
const before = await current(agent.id);
const effects = createAgentLifecycleEffects();
const lifecycle = createLifecycleCommands(db, { ...effects, completeConfiguration: async (...args) => {
await effects.completeConfiguration(...args);
throw new Error("Configuration completion failed");
} });
await expect(lifecycle.updateConfiguration(agent.id, { adapterConfig: { command: "echo" } },
{ recordRevision: { source: "test", createdByUserId: "board" } })).rejects.toThrow("Configuration completion failed");
expect(await current(agent.id)).toMatchObject({ adapterConfig: before.adapterConfig,
lifecycleVersion: before.lifecycleVersion, lifecycleOperation: before.lifecycleOperation });
expect(await db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, agent.id))).toHaveLength(0);
});
it("rolls back configuration and verification invalidation in the binding transaction", async () => {
const agent = await hire();
const before = await current(agent.id);
await expect(updateAgentConfigurationInTransaction(db, agent.id, { name: "Uncommitted" }))
.rejects.toThrow("requires a database transaction");
expect(() => updateAgentConfigurationInTransaction(db, agent.id, { budgetMonthlyCents: 100 } as never))
.toThrow("Budget changes require a root lifecycle command");
await expect(db.transaction(async tx => agentConfiguration(tx as unknown as Db).update(agent.id, { name: "Uncommitted" })))
.rejects.toThrow("root database");
await expect(db.transaction(async tx => {
await updateAgentConfigurationInTransaction(tx as unknown as Db, agent.id, { adapterConfig: { command: "echo" } });
expect((await tx.select().from(agents).where(eq(agents.id, agent.id)))[0].lifecycleVersion).toBe(before.lifecycleVersion + 1);
throw new Error("Binding change failed");
})).rejects.toThrow("Binding change failed");
expect(await current(agent.id)).toMatchObject({ adapterConfig: before.adapterConfig,
lifecycleVersion: before.lifecycleVersion, lifecycleOperation: before.lifecycleOperation });
});
it("permits a board retry and rejects an agent or a different company", async () => {
const agent = await hire();
function app(actor: Express.Request["actor"]) {
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = actor; next(); });
app.use("/api", agentRoutes(db)); app.use(errorHandler); return app;
}
const board: Express.Request["actor"] = { type: "board", source: "session", userId: "board", companyIds: [companyId],
memberships: [{ companyId, membershipRole: "admin", status: "active" }] };
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board", membershipRole: "admin" });
await db.insert(principalPermissionGrants).values(["agents:create", "agents:configure"].map(permissionKey => ({ companyId, principalType: "user", principalId: "board", permissionKey })));
const url = `/api/agents/${agent.id}/lifecycle/retry`;
const response = await request(app(board)).post(url).send({});
expect(response.status, JSON.stringify(response.body)).toBe(200);
expect(response.body.lifecycleState).toBe("preparing");
expect(response.body).not.toHaveProperty("lifecycleOperation");
expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, agent.id), eq(activityLog.action, "agent.lifecycle_retried"))))
.toEqual([expect.objectContaining({ actorType: "user", actorId: "board" })]);
await request(app({ type: "agent", source: "agent_key", companyId, agentId: agent.id })).post(url).send({}).expect(403);
const denied = await request(app({ ...board, companyIds: [], memberships: [] })).post(url).send({});
expect([403, 404]).toContain(denied.status);
});
it("recovers an expired lease and never accepts an expired completion", async () => {
const agent = await hire("paused"); const store = createLifecycleStore(db);
await createAgentLifecycle(db).resumeAgent(agent.id);
const claim = await store.claim(agent.id, "first", new Date(Date.now() - 180_000));
expect(claim).not.toBeNull();
await store.setRequiredPlugins(claim!, "first", []);
await store.completeHost(claim!, "first");
expect(await store.change(agent.id, "complete", { owner: "first", version: claim!.lifecycleVersion })).toBeNull();
expect(await store.claim(agent.id, "second", new Date())).not.toBeNull();
});
});
describe("lifecycle transition rules", () => {
it("does not bypass authorization, verification, or cleanup", () => {
expect(() => transition("pending_approval", "resume")).toThrow();
expect(transition("preparing", "complete")).toBe("verifying");
expect(transition("terminating", "complete")).toBe("cleaning_up");
expect(transition("cleaning_up", "complete")).toBe("terminated");
expect(() => transition("terminated", "resume")).toThrow();
expect(transition("terminating", "terminate")).toBe("terminating");
});
});
@@ -0,0 +1,63 @@
import { agents, companies, createDb, type Db } from "@paperclipai/db";
import { asc, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { startAgentLifecycle } from "../index.js";
import { createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("lifecycle policy sweep", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-lifecycle-policy-");
db = createDb(database.connectionString);
}, 90_000);
afterAll(async () => { await database?.cleanup(); });
it("caps each policy page, skips ineligible agents, and returns to the first page", async () => {
const [company] = await db.insert(companies).values({ name: "Policy pages", issuePrefix: "POL" }).returning();
const eligible = await db.insert(agents).values(Array.from({ length: 101 }, (_, index) => ({
id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,
companyId: company.id, name: `Agent ${index}`, status: "idle", lifecycleState: "ready" as const,
lifecycleHolds: ["company_paused"], pauseReason: "company_paused",
}))).returning();
const excluded = await db.insert(agents).values((["pending_approval", "terminating", "cleaning_up", "terminated", "rejected"] as const).map(lifecycleState => ({
companyId: company.id, name: lifecycleState, status: "terminated", lifecycleState,
lifecycleHolds: ["company_paused"], pauseReason: "company_paused",
}))).returning();
const effects = createAgentLifecycleEffects();
const transaction = vi.spyOn(effects, "transaction");
const now = Date.now();
const clock = vi.spyOn(Date, "now").mockReturnValue(now);
const timer = vi.spyOn(globalThis, "setInterval").mockImplementation(() => ({ unref() {} }) as ReturnType<typeof setInterval>);
const clearTimer = vi.spyOn(globalThis, "clearInterval").mockImplementation(() => {});
const work = startAgentLifecycle(db, effects, {
requiredPluginIds: async () => [], runHost: async () => "pending", runPlugin: async () => "pending",
}, () => true);
const rows = () => db.select().from(agents).where(eq(agents.companyId, company.id)).orderBy(asc(agents.id));
try {
await work.sweep();
expect(transaction).toHaveBeenCalledTimes(100);
expect((await rows()).filter(row => row.lifecycleHolds.length === 0)).toHaveLength(100);
await work.sweep();
expect(transaction).toHaveBeenCalledTimes(100);
clock.mockReturnValue(now + 60_001);
await work.sweep();
expect(transaction).toHaveBeenCalledTimes(101);
expect((await rows()).filter(row => row.lifecycleHolds.length > 0).map(row => row.id).sort())
.toEqual(excluded.map(row => row.id).sort());
await db.update(agents).set({ lifecycleHolds: ["company_paused"] }).where(eq(agents.id, eligible[0].id));
clock.mockReturnValue(now + 120_002);
await work.sweep();
expect(transaction).toHaveBeenCalledTimes(201);
expect((await rows())[0].lifecycleHolds).toEqual([]);
} finally {
await work.stop();
transaction.mockRestore();
clock.mockRestore();
timer.mockRestore();
clearTimer.mockRestore();
}
});
});
@@ -0,0 +1,96 @@
import { agentAppearanceSchema } from "@paperclipai/shared";
import { approvals, type Db } from "@paperclipai/db";
import { and, desc, eq, inArray, sql } from "drizzle-orm";
import { unprocessable } from "../../../errors.js";
import { approvalResolutionRecords, resolvableApprovalStatuses } from "../../../lib/approval-records.js";
import { agentRecords } from "./records.js";
import { createLifecycleStore } from "./postgres.js";
import type { LifecycleEffects } from "./effects.js";
export type HireDecisionTarget = string | { approvalId: string };
type HireDecisionResult = {
approval: typeof approvals.$inferSelect | null;
agent: Awaited<ReturnType<ReturnType<typeof agentRecords>["getById"]>>;
applied: boolean;
activated: boolean;
hireApprovedAgentId: string | null;
};
export function hireApprovalService(db: Db, effects: LifecycleEffects) {
const { getExistingApproval, resolveApproval } = approvalResolutionRecords(db);
async function decide(target: HireDecisionTarget, status: "approved" | "rejected", userId: string, note?: string | null): Promise<HireDecisionResult | null> {
const initial = typeof target === "string"
? await agentRecords(db, effects).getById(target)
: await getExistingApproval(target.approvalId);
if (!initial) return null;
if (typeof target !== "string" && (!("type" in initial) || initial.type !== "hire_agent")) throw unprocessable("Expected a hire approval");
const companyId = initial.companyId;
// Hire decisions acquire the company lock before changing an approval or agent.
return effects.transaction(db, companyId, async (tx, publications) => {
const records = agentRecords(tx, effects);
let approvalId = typeof target === "string" ? null : target.approvalId;
if (typeof target === "string") {
const [open] = await tx.select({ id: approvals.id }).from(approvals).where(and(
eq(approvals.companyId, companyId), eq(approvals.type, "hire_agent"),
inArray(approvals.status, resolvableApprovalStatuses),
sql`${approvals.payload}->>'agentId' = ${target}`,
)).orderBy(desc(approvals.createdAt)).limit(1);
approvalId = open?.id ?? null;
}
let approval: typeof approvals.$inferSelect | null = null;
let applied = true;
if (approvalId) {
const result = await resolveApproval(approvalId, status, userId, note, tx);
approval = result.approval;
applied = result.applied;
}
const payload = approval?.payload ?? {};
let agentId = typeof target === "string" ? target : typeof payload.agentId === "string" ? payload.agentId : null;
if (applied && status === "approved") {
if (agentId) {
const activated = await records.activatePendingApproval(agentId, approval ? payload : null, approval ? approval.requestedByUserId : userId);
if (!approval) applied = activated?.activated ?? false;
} else {
const created = await records.create(companyId, {
name: String(payload.name ?? "New Agent"),
appearance: payload.appearance == null ? undefined : agentAppearanceSchema.parse(payload.appearance),
role: String(payload.role ?? "general"),
title: typeof payload.title === "string" ? payload.title : null,
reportsTo: typeof payload.reportsTo === "string" ? payload.reportsTo : null,
capabilities: typeof payload.capabilities === "string" ? payload.capabilities : null,
adapterType: String(payload.adapterType ?? "process"),
adapterConfig:
typeof payload.adapterConfig === "object" && payload.adapterConfig !== null
? (payload.adapterConfig as Record<string, unknown>)
: {},
budgetMonthlyCents:
typeof payload.budgetMonthlyCents === "number" ? payload.budgetMonthlyCents : 0,
metadata:
typeof payload.metadata === "object" && payload.metadata !== null
? (payload.metadata as Record<string, unknown>)
: null,
status: "idle",
spentMonthlyCents: 0,
permissions: undefined,
lastHeartbeatAt: null,
}, { runnerResolved: true, createdByUserId: approval!.requestedByAgentId ? null : approval!.requestedByUserId, responsibleUserId: approval!.requestedByUserId });
agentId = created.id;
}
if (approval && agentId && typeof payload.budgetMonthlyCents === "number" && payload.budgetMonthlyCents > 0) {
await effects.setAgentBudget(tx, publications, companyId, agentId, payload.budgetMonthlyCents, userId);
}
} else if (applied && agentId) {
if (approval) await records.rejectPendingHire(agentId);
else {
const before = await records.getById(agentId);
await createLifecycleStore(tx, effects).change(agentId, "reject");
applied = before?.lifecycleState !== "rejected";
}
}
return { approval, agent: agentId ? await records.getById(agentId) : null, applied,
activated: status === "approved" && applied,
hireApprovedAgentId: status === "approved" && applied ? agentId : null };
});
}
return { decide };
}
@@ -0,0 +1,19 @@
import { agents } from "@paperclipai/db";
import { and, eq, inArray } from "drizzle-orm";
import type { CompanyDeletionParticipant } from "../../../lib/company-deletion.js";
import { AgentLifecycleConflict, assertAgentPurgeAllowed } from "../domain/policy.js";
export const agentLifecycleCompanyDeletion: CompanyDeletionParticipant = {
async deleteCompanyData(tx, companyId) {
if (!("nestedIndex" in tx)) {
throw new AgentLifecycleConflict("Company deletion requires a database transaction");
}
const rows = await tx.select({ lifecycleState: agents.lifecycleState }).from(agents)
.where(eq(agents.companyId, companyId)).for("update");
for (const agent of rows) assertAgentPurgeAllowed(agent);
await tx.delete(agents).where(and(
eq(agents.companyId, companyId),
inArray(agents.lifecycleState, ["terminated", "rejected"]),
));
},
};
@@ -0,0 +1,32 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { agents, type Db } from "@paperclipai/db";
import { agentRecordQueries, AGENT_CONFIGURATION_FIELDS, jsonEqual, type AgentConfigurationPatch, type UpdateAgentOptions } from "../../../lib/agent-records.js";
import type { ActivityPublication } from "../../../types/activity-publication.js";
import { AgentLifecycleConflict } from "../domain/policy.js";
import type { LifecycleEffects } from "./effects.js";
export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects, id: string, data: AgentConfigurationPatch, options?: UpdateAgentOptions, publications: ActivityPublication[] = []) {
if (!("nestedIndex" in tx)) throw new AgentLifecycleConflict("Configuration integration requires a database transaction");
assertConfigurationFields(data);
const [current] = await tx.select().from(agents).where(eq(agents.id, id)).for("update");
if (!current) return null;
const patch = await effects.prepareConfiguration(tx, current, data, options);
assertConfigurationFields(patch);
const changed = ["adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"].some(key =>
Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key as keyof typeof patch], current[key as keyof typeof current]));
const invalidate = changed && ["preparing", "verifying", "resuming"].includes(current.lifecycleState);
const [updated] = await tx.update(agents).set({ ...patch, updatedAt: new Date(), ...(invalidate ? {
lifecycleVersion: current.lifecycleVersion + 1, lifecycleError: null,
lifecycleOperation: { ...current.lifecycleOperation!, id: randomUUID(), hostComplete: false,
completedPluginIds: [], leaseOwner: undefined, leaseUntil: undefined, retryAt: undefined },
} : {}) }).where(eq(agents.id, id)).returning();
await effects.completeConfiguration(tx, current, updated, patch, options, publications);
return agentRecordQueries(tx).getById(id);
}
function assertConfigurationFields(data: AgentConfigurationPatch) {
if (Object.keys(data).some(field => !AGENT_CONFIGURATION_FIELDS.some(allowed => allowed === field))) {
throw new AgentLifecycleConflict("Unsupported configuration field; use the command that owns this field, such as a lifecycle command");
}
}
@@ -0,0 +1,27 @@
import { agents, type Db } from "@paperclipai/db";
import { and, eq, inArray } from "drizzle-orm";
import { conflict } from "../../../errors.js";
import { agentRecordQueries } from "../../../lib/agent-records.js";
import { readBuiltInAgentMarker } from "../../../lib/built-in-agent-metadata.js";
import { assertAgentPurgeAllowed } from "../domain/policy.js";
import type { LifecycleEffects } from "./effects.js";
export async function purgeAgent(db: Db, effects: LifecycleEffects, id: string) {
const { getById, normalizeAgentRow } = agentRecordQueries(db);
const existing = await getById(id);
if (!existing) return null;
return effects.transaction(db, existing.companyId, async tx => {
const [agent] = await tx.select().from(agents).where(eq(agents.id, id)).for("update");
if (!agent) return null;
const marker = readBuiltInAgentMarker(agent.metadata);
if (marker) throw conflict("Built-in agents cannot be deleted; pause them instead", {
code: "built_in_agent_undeletable", key: marker.key, featureKeys: marker.featureKeys,
});
assertAgentPurgeAllowed(agent);
await effects.deleteDependencies(tx, agent.companyId, id);
const [deleted] = await tx.delete(agents).where(and(
eq(agents.id, id), inArray(agents.lifecycleState, ["terminated", "rejected"]),
)).returning();
return deleted ? normalizeAgentRow(deleted) : null;
});
}
@@ -0,0 +1,24 @@
import type { LifecycleFailure } from "../application/ports.js";
import type { Db } from "@paperclipai/db";
import type { budgetPolicies } from "@paperclipai/db";
import type { CreateAgentData, CreateAgentOptions, AgentConfigurationPatch, AgentConfigurationRecord, AgentHireRecord, UpdateAgentOptions } from "../../../lib/agent-records.js";
import type { ActivityPublication } from "../../../types/activity-publication.js";
/** Services supply integrations; lifecycle owns the transaction and state writes. */
export interface LifecycleEffects {
reportFailure(context: LifecycleFailure, error: unknown): void;
deleteDependencies(db: Db, companyId: string, agentId: string): Promise<void>;
prepareConfiguration(db: Db, current: AgentConfigurationRecord, data: AgentConfigurationPatch, options?: UpdateAgentOptions): Promise<AgentConfigurationPatch>;
completeConfiguration(db: Db, before: AgentConfigurationRecord, after: AgentConfigurationRecord, patch: AgentConfigurationPatch, options: UpdateAgentOptions | undefined, publications: ActivityPublication[]): Promise<void>;
transaction<T>(db: Db, companyId: string, work: (tx: Db, publications: ActivityPublication[]) => Promise<T>): Promise<T>;
policyBlocks(db: Db, policy: typeof budgetPolicies.$inferSelect): Promise<boolean>;
setAgentBudget(db: Db, publications: ActivityPublication[], companyId: string, agentId: string, amount: number, userId: string | null, isActive?: boolean): Promise<unknown>;
enforceBudget(db: Db, companyId: string, agentId: string): Promise<void>;
recordCreation(db: Db, companyId: string, agentId: string): Promise<void>;
recordStatus(db: Db, companyId: string, agentId: string, before: string, after: string): Promise<void>;
clearPrimary(db: Db, companyId: string, agentId: string): Promise<unknown>;
prepareHire(db: Db, companyId: string, data: CreateAgentData, options?: CreateAgentOptions): Promise<CreateAgentData>;
initializeHire(db: Db, agent: AgentHireRecord, options?: CreateAgentOptions): Promise<void>;
prepareHireApproval(db: Db, agent: AgentHireRecord, payload?: Record<string, unknown> | null): Promise<AgentConfigurationPatch>;
completeHireApproval(db: Db, agent: AgentHireRecord, previous: AgentHireRecord): Promise<void>;
}
@@ -0,0 +1,151 @@
import { randomUUID } from "node:crypto";
import { and, asc, eq, inArray, sql } from "drizzle-orm";
import { agents, agentApiKeys, companies, budgetPolicies, type Db } from "@paperclipai/db";
import type { AgentLifecycleOperation } from "@paperclipai/shared";
import { AgentLifecycleConflict, compatibilityStatus, transition } from "../domain/policy.js";
import type { LifecycleEffects } from "./effects.js";
import type { LifecycleStore } from "../application/ports.js";
export function assertRootDatabase(db: Db) {
if ("nestedIndex" in db) throw new AgentLifecycleConflict("Lifecycle commands require the root database connection");
}
export function createLifecycleStore(db: Db, effects: LifecycleEffects): LifecycleStore {
const get = (id: string) => db.select().from(agents).where(eq(agents.id, id)).then(rows => rows[0] ?? null);
return {
get,
async change(id, command, options = {}) {
const existing = await get(id);
if (!existing) return null;
return effects.transaction(db, existing.companyId, async tx => {
const [agent] = await tx.select().from(agents).where(eq(agents.id, id)).for("update", command === "reconcile" ? { skipLocked: true } : undefined);
if (!agent) return null;
if (options.version !== undefined && options.version !== agent.lifecycleVersion) return null;
if (command === "complete" && (!options.owner || !agent.lifecycleOperation?.leaseUntil || agent.lifecycleOperation?.leaseOwner !== options.owner ||
Date.parse(agent.lifecycleOperation?.leaseUntil ?? "") <= Date.now() ||
!agent.lifecycleOperation.hostComplete || agent.lifecycleRequiredPluginIds === null ||
agent.lifecycleRequiredPluginIds.some(id => !agent.lifecycleOperation!.completedPluginIds.includes(id)))) return null;
if (command === "retry") {
transition(agent.lifecycleState, command);
if (agent.lifecycleOperation?.leaseUntil && Date.parse(agent.lifecycleOperation.leaseUntil) > Date.now()) return agent;
const [updated] = await tx.update(agents).set({ lifecycleError: null,
lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt' - 'leaseOwner' - 'leaseUntil'`, updatedAt: new Date() }).where(eq(agents.id, id)).returning();
return updated;
}
if (command === "resume" && !["ready", "paused", "pausing", "resuming"].includes(agent.lifecycleState)) transition(agent.lifecycleState, command);
let holds = agent.lifecycleHolds;
const reason = options.reason ?? "manual";
if (command === "reconcile") {
if (["pending_approval", "terminating", "cleaning_up", "terminated", "rejected"].includes(agent.lifecycleState)) return agent;
const [company] = await tx.select().from(companies).where(eq(companies.id, agent.companyId));
const policies = await tx.select().from(budgetPolicies).where(and(eq(budgetPolicies.companyId, agent.companyId),
eq(budgetPolicies.scopeType, "agent"), eq(budgetPolicies.scopeId, id)));
let budgetBlocked = false;
for (const policy of policies) if (await effects.policyBlocks(tx, policy)) budgetBlocked = true;
holds = holds.filter(hold => hold !== "budget" && hold !== "company_archived" && hold !== "company_paused");
if (budgetBlocked) holds.push("budget");
if (company.status === "archived") holds.push("company_archived");
if (company.status === "paused") holds.push("company_paused");
}
if (command === "pause") holds = [...new Set([...holds, reason])];
if (command === "resume") holds = holds.filter(hold => reason === "user" ? ["budget", "company_archived", "company_paused"].includes(hold) : hold !== reason);
let next = command === "reconcile"
? holds.length && !["pausing", "paused"].includes(agent.lifecycleState) ? "pausing" as const
: !holds.length && agent.lifecycleState === "paused" ? "resuming" as const : agent.lifecycleState
: command === "resume" && (holds.length || agent.lifecycleState === "pausing") ? agent.lifecycleState
: transition(agent.lifecycleState, command, agent.lifecycleOperation?.resumeState);
if (command === "complete" && next === "ready" && holds.length) next = "pausing";
if (command === "complete" && next === "paused" && !holds.length) next = "resuming";
if (next === agent.lifecycleState) {
if (JSON.stringify(holds) !== JSON.stringify(agent.lifecycleHolds) || agent.pauseReason !== (holds[0] ?? null)) {
await tx.update(agents).set({ lifecycleHolds: holds, pauseReason: holds[0] ?? null }).where(eq(agents.id, id));
}
return agent;
}
const operation: AgentLifecycleOperation = {
responsibleUserId: agent.lifecycleOperation?.responsibleUserId,
id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0,
resumeState: next === "pausing"
? agent.lifecycleState === "preparing" || agent.lifecycleState === "verifying" ? agent.lifecycleState : agent.lifecycleOperation?.resumeState ?? "ready"
: agent.lifecycleOperation?.resumeState,
};
if (next === "ready") operation.resumeState = "ready";
const status = compatibilityStatus(next, agent.status);
const [updated] = await tx.update(agents).set({
lifecycleHolds: holds, lifecycleState: next, lifecycleVersion: agent.lifecycleVersion + 1, lifecycleError: null,
lifecycleOperation: operation, status,
pauseReason: holds[0] ?? null,
pausedAt: next === "pausing" ? new Date() : next === "ready" ? null : agent.pausedAt,
updatedAt: new Date(),
}).where(eq(agents.id, id)).returning();
if (next === "terminating" || next === "rejected") {
await tx.update(agentApiKeys).set({ revokedAt: new Date() }).where(eq(agentApiKeys.agentId, id));
await effects.clearPrimary(tx, agent.companyId, id);
}
if (command === "approve") await effects.recordCreation(tx, agent.companyId, id);
if (next === "pausing" || next === "resuming" || next === "terminating" || next === "rejected") {
await effects.recordStatus(tx, agent.companyId, id,
next === "resuming" ? "paused" : "idle",
next === "resuming" ? "idle" : next === "pausing" ? "paused" : "terminated");
}
return updated;
});
},
async claim(id, owner, now) {
const [agent] = await db.update(agents).set({
lifecycleOperation: sql`coalesce(${agents.lifecycleOperation}, '{"id":"", "hostComplete":false, "completedPluginIds":[], "attempts":0}'::jsonb)
|| jsonb_build_object('leaseOwner', ${owner}::text, 'leaseUntil', ${(new Date(now.getTime() + 120_000)).toISOString()}::text,
'attempts', coalesce((${agents.lifecycleOperation}->>'attempts')::integer, 0) + 1)`,
}).where(and(eq(agents.id, id), inArray(agents.lifecycleState, ["preparing", "verifying", "pausing", "resuming", "terminating", "cleaning_up"]),
sql`coalesce((${agents.lifecycleOperation}->>'leaseUntil')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
sql`coalesce((${agents.lifecycleOperation}->>'retryAt')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
)).returning();
return agent ?? null;
},
async renew(agent, owner, now) {
const rows = await db.update(agents).set({ lifecycleOperation: sql`jsonb_set(${agents.lifecycleOperation}, '{leaseUntil}', ${JSON.stringify(new Date(now.getTime() + 120_000).toISOString())}::jsonb)` })
.where(and(eq(agents.id, agent.id), eq(agents.lifecycleVersion, agent.lifecycleVersion), sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id });
return rows.length > 0;
},
async setRequiredPlugins(agent, owner, pluginIds) {
const rows = await db.update(agents).set({ lifecycleRequiredPluginIds: pluginIds })
.where(and(eq(agents.id, agent.id), eq(agents.lifecycleVersion, agent.lifecycleVersion),
sql`${agents.lifecycleRequiredPluginIds} is null`,
sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id });
return rows.length > 0;
},
async completeHost(agent, owner) {
const rows = await db.update(agents).set({
lifecycleOperation: sql`jsonb_set(${agents.lifecycleOperation}, '{hostComplete}', 'true'::jsonb)`,
}).where(and(eq(agents.id, agent.id), eq(agents.lifecycleVersion, agent.lifecycleVersion),
sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id });
return rows.length > 0;
},
async completePlugin(agent, owner, pluginId) {
const rows = await db.update(agents).set({
lifecycleOperation: sql`jsonb_set(${agents.lifecycleOperation}, '{completedPluginIds}',
coalesce(${agents.lifecycleOperation}->'completedPluginIds', '[]'::jsonb) || ${JSON.stringify([pluginId])}::jsonb)`,
}).where(and(eq(agents.id, agent.id), eq(agents.lifecycleVersion, agent.lifecycleVersion),
sql`${agents.lifecycleRequiredPluginIds} @> ${JSON.stringify([pluginId])}::jsonb`,
sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id });
return rows.length > 0;
},
async defer(agent, owner, error, now) {
const rows = await db.update(agents).set({
lifecycleError: error,
lifecycleOperation: sql`(${agents.lifecycleOperation} - 'leaseOwner' - 'leaseUntil')
|| jsonb_build_object('retryAt', ${new Date(now.getTime() + (error ? 60_000 : 2_000)).toISOString()}::text)`,
updatedAt: now,
}).where(and(eq(agents.id, agent.id), eq(agents.lifecycleVersion, agent.lifecycleVersion),
sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id });
return rows.length > 0;
},
async pending(limit, now) {
return db.select({ id: agents.id }).from(agents).where(and(
inArray(agents.lifecycleState, ["preparing", "verifying", "pausing", "resuming", "terminating", "cleaning_up"]),
sql`coalesce((${agents.lifecycleOperation}->>'leaseUntil')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
sql`coalesce((${agents.lifecycleOperation}->>'retryAt')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
)).orderBy(asc(agents.updatedAt), asc(agents.id)).limit(limit).then(rows => rows.map(row => row.id));
},
};
}
@@ -0,0 +1,118 @@
import type { LifecycleEffects } from "./effects.js";
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { agents, agentApiKeys, type Db } from "@paperclipai/db";
import { conflict, notFound } from "../../../errors.js";
import { agentRecordQueries, type CreateAgentOptions, type CreateAgentData } from "../../../lib/agent-records.js";
export function agentRecords(db: Db, effects: LifecycleEffects) {
const { getById } = agentRecordQueries(db);
return {
getById,
create: async (companyId: string, data: CreateAgentData, options?: CreateAgentOptions) => {
if (Object.keys(data).some(key => key.startsWith("lifecycle"))) throw conflict("Lifecycle fields belong to the lifecycle module");
return effects.transaction(db, companyId, async (txDb) => {
const tx = txDb;
const prepared = await effects.prepareHire(txDb, companyId, data, options);
const created = await tx
.insert(agents)
.values({
...prepared,
lifecycleState: data.status === "pending_approval" ? "pending_approval" : data.status === "terminated" ? "terminated" : data.status === "paused" ? "paused" : "preparing",
lifecycleVersion: 1,
lifecycleHolds: data.status === "paused" ? [data.pauseReason ?? "manual"] : [],
pauseReason: data.status === "paused" ? data.pauseReason ?? "manual" : null,
pausedAt: data.status === "paused" ? new Date() : null,
lifecycleOperation: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, resumeState: "preparing", responsibleUserId: options?.responsibleUserId ?? options?.createdByUserId },
status: data.status === "pending_approval" ? "pending_approval" : data.status === "terminated" ? "terminated" : "paused",
companyId,
})
.returning()
.then((rows) => rows[0]);
await effects.initializeHire(txDb, created, options);
if (created.status !== "pending_approval" && created.status !== "terminated") {
await effects.recordCreation(txDb, companyId, created.id);
}
const normalizedCreated = await agentRecordQueries(txDb).getById(created.id);
if (!normalizedCreated) {
throw notFound("Agent not found");
}
return normalizedCreated;
});
},
clearError: async (id: string) => {
const existing = await getById(id);
if (!existing) return null;
if (existing.status === "terminated") throw conflict("Cannot clear error on terminated agent");
if (existing.status === "pending_approval") {
throw conflict("Pending approval agents cannot have errors cleared");
}
if (existing.status !== "error") {
throw conflict("Only agents in error status can have their error cleared");
}
const updated = await db
.update(agents)
.set({
status: "idle",
pauseReason: null,
pausedAt: null,
errorReason: null,
updatedAt: new Date(),
})
.where(and(eq(agents.id, id), eq(agents.status, "error"), eq(agents.lifecycleState, "ready")))
.returning()
.then((rows) => rows[0] ?? null);
if (!updated) {
throw conflict("Only agents in error status can have their error cleared");
}
return getById(updated.id);
},
rejectPendingHire: async (id: string) => {
const rows = await db.update(agents).set({ status: "terminated", lifecycleState: "rejected",
lifecycleVersion: sql`${agents.lifecycleVersion} + 1`, lifecycleOperation: null,
updatedAt: new Date() }).where(and(eq(agents.id, id), eq(agents.lifecycleState, "pending_approval"))).returning();
for (const row of rows) {
await effects.clearPrimary(db, row.companyId, id);
await db.update(agentApiKeys).set({ revokedAt: new Date() }).where(eq(agentApiKeys.agentId, id));
await effects.recordStatus(db, row.companyId, id, "pending_approval", "terminated");
}
return rows;
},
activatePendingApproval: async (id: string, approvedPayload?: Record<string, unknown> | null, requestedByUserId?: string | null) => {
const activatedAgent = await db.transaction(async (tx) => {
const txDb = tx as unknown as Db;
const existing = await agentRecordQueries(txDb).getById(id);
if (!existing || existing.status !== "pending_approval") return null;
const patch = await effects.prepareHireApproval(txDb, existing, approvedPayload);
const updated = await tx
.update(agents)
.set({ ...patch, status: "paused", lifecycleState: "preparing", lifecycleVersion: existing.lifecycleVersion + 1, lifecycleError: null, lifecycleOperation: sql`jsonb_build_object('id', ${randomUUID()}::text, 'hostComplete', false, 'completedPluginIds', '[]'::jsonb, 'attempts', 0, 'responsibleUserId', coalesce(nullif(${agents.lifecycleOperation}->'responsibleUserId', 'null'::jsonb), to_jsonb(${requestedByUserId ?? null}::text)))`, updatedAt: new Date() })
.where(and(eq(agents.id, id), eq(agents.status, "pending_approval")))
.returning()
.then((rows) => rows[0] ?? null);
if (!updated) return null;
await effects.completeHireApproval(txDb, updated, existing);
await effects.recordCreation(txDb, existing.companyId, updated.id);
const agent = await agentRecordQueries(txDb).getById(updated.id);
if (!agent) {
throw notFound("Agent not found");
}
return agent;
});
if (activatedAgent) {
return { agent: activatedAgent, activated: true };
}
const existing = await getById(id);
return existing ? { agent: existing, activated: false } : null;
},
};
}
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more