mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 11:40:00 +01:00
Own agent hiring and termination in a lifecycle module (#15631)
## Thinking Path > - Paperclip manages AI agents and their work. > - Agent creation, approval, pause, and termination change whether an agent can work. > - These changes currently use separate service and database paths. > - Some agents need setup after their record exists and before their harness can run. > - This PR adds one module that owns those state changes and their transactions. > - The module records progress and retries incomplete work after a server restart. ## Linked Issues or Issue Description **Problem or motivation** A hire can become active before its execution environment is ready. Direct agent state writes also bypass one common lifecycle boundary. Termination does not have a durable step for resource cleanup. **Proposed solution** Use agent lifecycle commands for hiring, approval, pause, resume, and termination. Keep proposed hires pending until approval. Prepare each approved hire, test its saved harness configuration, and then permit work. Wait for required plugin work before completing a step. **Alternatives considered** A general database commit hook would expose transaction details to callers. A timer alone would delay each new hire. This module owns each command transaction and starts its worker after commit. A periodic scan recovers work after a process stops. **Roadmap alignment** This change adds the lifecycle boundary for the existing agent and plugin systems. It does not add a user interface or a provider implementation. It replaces the lifecycle delivery approach in #15391. Related proposals include #11475 and #13099; this change does not add their external executor protocols. ## What Changed - Add durable approval, preparation, verification, pause, resume, stop, and cleanup states. - Keep agent creation, lifecycle state, configuration writes, and agent record deletion behind `modules/agent-lifecycle`. Keep validation, credential rules, reads, onboarding, invitations, general approvals, and company data deletion in their services. - Commit a hire before the remaining onboarding or invitation work. Serialize requests with the existing dedicated database connection helper. Reuse the hire after a failed attempt. - Keep accepted work in the run queue during setup. Require execution and cleanup evidence before completing pause or termination. - Retain the original credential owner when approving migrated hires. - Start lifecycle work after each command commits. Use database leases and revision checks for retries and late results. - Add a generic required plugin method and capability. Store the required plugin IDs for each agent. Track host and plugin completion separately. - Keep harness verification and credential rules in services. Supply their results to lifecycle through explicit ports. Reject failed logins and incomplete probes. - Remove reverse imports from lifecycle adapters into services. Share record queries and validation below both layers. - Use one hire decision path for agent IDs and approval IDs. Resolve the approval and agent change in one transaction. Expose policy reconciliation on the command object. - Save configuration and verification invalidation through one module operation. Ordinary commands own their transaction. Restrict the shared transaction integration to its listed callers. Reject identity, company, accounting, timestamp, and unknown fields. - Require completed termination before deleting agent records. The company deletion service calls the module through a separate deletion interface. - Save an approved secret before applying its agent binding. A failed binding leaves the secret approved. A retry reuses it. - Remove old permission and metadata export files. Move hire configuration rules out of lifecycle persistence. - Report failed worker steps and scans with operation context and known error codes. Omit provider messages, stacks, and configuration values. Document ordinary application use and extension rules. - Recover expired native owners only after execution stops. Retry cleanup of failed retained leases. Wait for setup in the live smoke script. - Keep manual, budget, and company pause reasons separate. Guard execution status writes with the ready state. - Add a migration, boundary checks, regression tests, and a lifecycle guide. Keep the current UI. - Limit periodic policy checks to 100 eligible agents per minute. Continue from the last agent ID. Exclude pending hires and agents in termination or a final state. Keep explicit company and budget updates immediate. ## Verification - Latest head `ccc3c86b0` aligns the shared status update schema with the PATCH route. All 15 shared tests, 104 server route/OpenAPI tests, 2 CLI tests, and shared/server/CLI TypeScript checks pass. The Greptile comment is fixed. CI is running; no new Apex review was requested for this small fix. - Rebase `75708ac94` rebases onto master at `2eb5187e4`. The backup test uses the shared 90-second timeout from master; the older timeout commit was removed. The affected backup test passes. - Agent budget edits now pass the target agent ID through enforcement. All 50 affected tests, server TypeScript, and 11 boundary tests pass. Both configuration update paths have regression coverage. CI is running on the latest head. No new Apex review was requested for these small fixes. - Rebase `9b568666a` preserves the run-control extraction and delivery-work startup changes from master. All 559 affected tests, server TypeScript, and 11 boundary tests pass. CI and Apex review are running on the final head. - The policy scan fix passes 56 lifecycle and diagnostic tests, 24 policy and caller tests, and 11 boundary tests. A regression test checks the page limit, interval, excluded states, and cursor wraparound. - Rebase `fd4698750` passes all 611 tests in eight affected lifecycle, route, and heartbeat suites. Server TypeScript and all 11 module boundary tests pass. The company deletion rollback and concurrent hire tests are included. - Follow-up `00aac7646` fixes the failed decision deletion test and the public update schema. All 126 affected server tests, 8 shared tests, 2 CLI tests, and 11 boundary tests pass. Shared, server, CLI, and UI TypeScript checks pass. - Server TypeScript passes: `pnpm --filter @paperclipai/server exec tsc --noEmit`. - All 11 boundary tests pass: `node --test scripts/check-module-boundaries.test.mjs`. The repository boundary scan also passes. - All 68 lifecycle, failure diagnostic, and harness verification tests pass. Tests reject forbidden fields through the root command, combined transition command, and restricted transaction integration. They also check invalid fields returned by configuration preparation. - Failure tests cover host work, plugin work, claims, renewals, deferrals, and scans. Log tests check known error codes and exclusion of private error contents. - All 355 tests in 10 existing caller suites pass. These tests cover secret approval, pairing, pending hires, credentials, company import, built-in agents, managed agents, instructions, and skills. - The branch is rebased onto `origin/master` at `2eb5187e4`. The queue guards and cancellation lock fix use the extracted heartbeat queue. Agent cancellation uses the extracted run-control file. The source diff scan found no secrets or private URLs. - Earlier checks cover approval retries, rollback, late verification results, policy holds, deletion rollback, concurrent company deletion, and queue admission during setup. - Before the rebase, CI passed on `00aac7646` and Greptile Apex rated it 5/5 with no open comments. CI and a new Apex review are pending for the rebased commit. The branch has no merge conflicts. - The full local build and native Dot suite were not run. The host has no Cargo. No live provider test was run. ## Risks - Background policy recovery takes more than one minute when more than 100 agents are eligible. Explicit company and budget updates still reconcile immediately. - The restricted configuration integration keeps an agent reference and its dependent records in one transaction. It cannot change a budget or invoke a lifecycle transition. A periodic scan starts pending setup after that transaction commits. - Secret approval and binding use separate transactions. A failed binding can leave an approved secret with no agent binding. - New approved hires remain unavailable until setup and verification complete. Existing clients see `paused` during these steps. This PR does not change the UI. - Migration `0320_daily_onslaught.sql` maps existing statuses and pause reasons. It does not create external resources or claim that an existing harness passed verification. - Use a coordinated server update for this migration. Older server versions can write legacy status without the new lifecycle checks. - A failed onboarding or invitation request can leave a committed hire. A retry reuses that hire and completes the remaining records. - Deletion requires completed termination. Company deletion can require another request while cleanup is pending. - Required plugins must make repeated calls safe and reject older revisions. A disabled or removed required plugin blocks completion until it is restored. - A new hire can run a second harness test after the existing UI test. Some adapters can charge for this test. - No live provider test was run. Provider implementation and resource backfill remain separate work. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code tools, and local test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in this PR with the feature request field labels - [x] I have not referenced internal or instance-local issues or links - [x] My branch name describes the change - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] Targeted local tests pass - [x] All Paperclip CI gates are green on the new commit - [x] Greptile Apex is 5/5 with no open comments on the new commit - [x] I will address review comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
ab8dcab809
commit
2dd9811e8b
152 files changed
+6790
-2758
No files matched your search
@@ -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.
|
||||
Reference in new issue
Block a user